Queer European MD passionate about IT
Browse Source

Merge dynamic site into this project

Davte 5 years ago
parent
commit
958d888460
8 changed files with 245 additions and 0 deletions
  1. 10 0
      .gitignore
  2. 0 0
      dynamic/__init__.py
  3. 111 0
      dynamic/app.py
  4. 0 0
      dynamic/data/__init__.py
  5. 19 0
      dynamic/pull_image_editor.sh
  6. 9 0
      dynamic/requirements.txt
  7. 11 0
      dynamic/website.service
  8. 85 0
      run_me.sh

+ 10 - 0
.gitignore

@@ -4,3 +4,13 @@
 .Spotlight-V100
 .TemporaryItems
 .Trashes
+
+# Dynamic site data folder, except init file
+dynamic/data/*
+!dynamic/data/__init__.py
+
+# Python virtual environment
+env/
+
+# Bash configuration files
+*config.sh

+ 0 - 0
dynamic/__init__.py


+ 111 - 0
dynamic/app.py

@@ -0,0 +1,111 @@
+"""Run an aiohttp web app."""
+
+# Standard library modules
+import asyncio
+import datetime
+import logging
+import os
+
+# Third party modules
+from aiohttp import web
+# from davtelepot import Bot
+
+# Project modules
+from data.config import (
+    log_file_name, errors_file_name, app_host, app_port
+)
+# from data.passwords import bot_token
+
+path = os.path.dirname(__file__)
+log_file = "{}/data/{}".format(path, log_file_name)
+errors_file = "{}/data/{}".format(path, errors_file_name)
+
+# Outputs the log in console, log_file and errors_file
+#   Log formatter: datetime, module name (filled with spaces up to 15
+#       characters), logging level name (filled to 8), message
+log_formatter = logging.Formatter(
+    "%(asctime)s [%(module)-15s %(levelname)-8s]     %(message)s",
+    style='%'
+)
+root_logger = logging.getLogger()
+root_logger.setLevel(logging.DEBUG)
+
+file_handler = logging.FileHandler(log_file, mode="a", encoding="utf-8")
+file_handler.setFormatter(log_formatter)
+file_handler.setLevel(logging.DEBUG)
+root_logger.addHandler(file_handler)
+
+file_handler = logging.FileHandler(errors_file, mode="a", encoding="utf-8")
+file_handler.setFormatter(log_formatter)
+file_handler.setLevel(logging.ERROR)
+root_logger.addHandler(file_handler)
+
+consoleHandler = logging.StreamHandler()
+consoleHandler.setFormatter(log_formatter)
+consoleHandler.setLevel(logging.DEBUG)
+root_logger.addHandler(consoleHandler)
+
+app = web.Application()
+# davtebot = Bot.get(bot_token)
+
+
+def page(path='/', headers={'Content-Type': 'text/html'}, prefix='/michele'):
+    """Decorator: serve the result of such decorated function at given path."""
+    path = "{pr}{pa}".format(
+        pr=prefix,
+        pa=path
+    )
+
+    def decorator(func):
+        async def decorated(request):
+            response = await func(request)
+            if type(response) is str:
+                if response.endswith('.html'):
+                    with open('vita/homepage.html', 'r') as _file:
+                        response = _file.read()
+                response = web.Response(
+                    text=response,
+                    headers=headers
+                )
+            assert isinstance(
+                response, web.Response
+            ), "Invalid response returned!"
+            return response
+        app.router.add_get(path, decorated)
+        return
+    return decorator
+
+
+@page('/test')
+async def test(request):
+    """Test page: return datetime."""
+    return str(datetime.datetime.now())
+
+
+@page('/pull/image-editor/nZ7Vgm9SSg4vNBy3ytG')
+async def pull_image_editor_project(request):
+    """Git pull at request."""
+    try:
+        _subprocess = await asyncio.create_subprocess_shell(
+            'bash {path}/pull_image_editor.sh'.format(
+                path=path
+            )
+        )
+        stdout, stderr = await _subprocess.communicate()
+    except Exception as e:
+        logging.error(
+            "Exception {e}:\n{o}\n{er}".format(
+                e=e,
+                o=stdout.decode().strip(),
+                er=stderr.decode().strip()
+            )
+        )
+    return web.Response(
+        status=302,
+        headers={
+            'location': 'https://www.davte.it/michele/image-editor/src/',
+        },
+    )
+
+
+web.run_app(app, host=app_host, port=app_port)

+ 0 - 0
dynamic/data/__init__.py


+ 19 - 0
dynamic/pull_image_editor.sh

@@ -0,0 +1,19 @@
+#!/bin/bash
+
+key="/home/michele/aruba_repo";
+
+# Get current directory
+this_script_directory=$(cd `dirname $0` && pwd);
+parent_directory=$(
+  dirname $(
+    dirname "$this_script_directory"
+  )
+)
+log_file="$parent_directory/michele/pull/log.txt";
+
+cd /home/michele/michele/image-editor;
+eval `ssh-agent -s`;
+ssh-add "$key";
+echo "Pulled at $(date '+%d/%m/%Y %H:%M:%S') with result:" >> "$log_file";
+git pull &>> "$log_file";
+eval `ssh-agent -k`;

+ 9 - 0
dynamic/requirements.txt

@@ -0,0 +1,9 @@
+aiohttp==3.5.4
+async-timeout==3.0.1
+attrs==19.1.0
+chardet==3.0.4
+davtelepot==1.4.25
+davteutil==1.1.17
+idna==2.8
+multidict==4.5.2
+yarl==1.3.0

+ 11 - 0
dynamic/website.service

@@ -0,0 +1,11 @@
+[Unit]
+Description=website
+
+[Service]
+WorkingDirectory=/home/michele/dynamic_site/
+Restart=always
+RestartSec=30
+ExecStart=/home/michele/dynamic_site/run_me.sh
+
+[Install]
+WantedBy=default.target

+ 85 - 0
run_me.sh

@@ -0,0 +1,85 @@
+#!/bin/bash
+
+# This file must be executable, otherwise the service cannot run it.
+
+# Run `./santanibot/bot.py` while exit code of script is 65.
+# At each iteration, pull news from repository and update dependencies.
+
+# Get current directory
+this_script_directory=$(cd `dirname $0` && pwd)
+
+# Import variables from my_config.sh
+#  `$botenv`: python virtual environment directory
+#    containing `python` and `pip`
+# `$python_script`: complete path to python script to be run
+#  `$pull_from_repository`: boolean
+#     if set to true, at each iteration pull from origin
+#  `$key`: complete path to private key used to pull
+source $this_script_directory/my_config.sh;
+
+# Ensure the success of importing procedure:
+## variables of interest should be non-zero (`-z`)
+if [ -z "${python_virtual_environment}" ];
+then
+  printf "Please set in \"my_config.sh\" the path to bot python \
+virtual environment\n\
+\n\
+Example:\n\
+python_virtual_environment=\"path/to/virtual/env\"\n\
+";
+  exit;
+fi
+if [ -z "${python_script}" ];
+then
+  printf "Please set in \"my_config.sh\" the path to python script to be run \
+\n\
+Example:\n\
+python_script=\"path/to/python/script.py\"\n\
+";
+  exit;
+elif [ ! -e "${python_script}" ];
+then
+  printf "File $python_script does not exist\n\
+Please point to a valid file.\n\
+Example:\n\
+python_script=\"path/to/python/script.py\"\n\
+";
+fi
+if [ -z "${key}" ];
+then
+  printf "Please set in \"my_config.sh\" the path to key\n\
+\n\
+Example:\n\
+key=\"path/to/key.pvt\"\n\
+";
+  exit;
+fi
+if [ -z ${pull_from_repository} ];
+then
+  printf "Please set in \"my_config.sh\" a variable named \
+`pull_from_repository`, set to either `true` or `false`.\n\n\
+Example:\n\
+pull_from_repository=true\n\
+";
+  exit;
+fi
+
+echo "Python script will be run while it exits with value===65.";
+i=65;
+while [ $i -eq 65 ]
+do
+if [ $pull_from_repository = true ];
+then
+  echo "Pulling from remote origin.";
+  eval `ssh-agent -s`;
+  ssh-add $key;
+  git pull;
+  eval `ssh-agent -k`;
+fi
+echo "Updating dependencies";
+"$python_virtual_environment/pip" install --upgrade --no-cache-dir \
+--no-deps davteutil davtelepot;
+echo "Running python script";
+"$python_virtual_environment/python" "$python_script";
+i=$?;
+done