From 6e31ebaa3b4f15d31073604724ccebed1601c919 Mon Sep 17 00:00:00 2001 From: Addin Munawwar <91366027+moonawar@users.noreply.github.com> Date: Fri, 17 Nov 2023 02:08:35 +0700 Subject: [PATCH] feat: fix docker and integrate env file --- .env.example | 6 ++ .gitignore | 7 +- Dockerfile | 4 +- app/main/Db.php | 12 +-- app/main/Main.php | 4 - db-init/seeding/all.sh | 18 ----- db-init/seeding/author.py | 43 ----------- db-init/seeding/book.py | 95 ------------------------ db-init/seeding/genre.py | 40 ---------- db-init/seeding/tmp/.gitkeep | 0 db-init/seeding/user.py | 71 ------------------ db-init/base.sql => db/V1__init.sql | 110 ++++++++++++++-------------- docker-compose.yml | 39 +++------- 13 files changed, 87 insertions(+), 362 deletions(-) create mode 100644 .env.example delete mode 100755 db-init/seeding/all.sh delete mode 100644 db-init/seeding/author.py delete mode 100644 db-init/seeding/book.py delete mode 100644 db-init/seeding/genre.py delete mode 100644 db-init/seeding/tmp/.gitkeep delete mode 100644 db-init/seeding/user.py rename db-init/base.sql => db/V1__init.sql (97%) diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..87339ac --- /dev/null +++ b/.env.example @@ -0,0 +1,6 @@ +MYSQL_DATABASE: 'wbd-db' +MYSQL_USER: 'user' +MYSQL_PASSWORD: 'secret' +MYSQL_ROOT_PASSWORD: 'root' + +DB_HOST: 'wbd-db' \ No newline at end of file diff --git a/.gitignore b/.gitignore index fd438a1..e6489aa 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,10 @@ -/mysql -/db-init/seeding/init.flag +/db/mysql** /app/storage/image/book_cover/* !/app/storage/image/book_cover/.gitkeep /app/storage/image/profile_pic/* !/app/storage/image/profile_pic/.gitkeep /app/storage/audio/* -!/app/storage/audio/.gitkeep \ No newline at end of file +!/app/storage/audio/.gitkeep + +.env \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 42439ca..afb87c0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,4 +4,6 @@ WORKDIR /var/www/html # PHP extension and Apache configuration RUN docker-php-ext-install mysqli RUN a2enmod rewrite -RUN apt-get -y update && apt-get -y upgrade && apt-get install -y ffmpeg \ No newline at end of file +RUN apt-get -y update ; \ + apt-get -y upgrade ; \ + apt-get -y install ffmpeg ; \ \ No newline at end of file diff --git a/app/main/Db.php b/app/main/Db.php index a2dbb22..95ff3e9 100644 --- a/app/main/Db.php +++ b/app/main/Db.php @@ -2,10 +2,9 @@ // Database connection for query class Db { private $conn; - private $host = 'wbd-db'; - private $user = 'user'; - private $pass = 'secret'; - private $db = 'wbd-db'; + private $host; + private $pass; + private $db; private static $instance = null; @@ -18,8 +17,11 @@ class Db { private function __construct() { + $this->host = $_ENV['DB_HOST']; + $this->db = $_ENV['MYSQL_DATABASE']; + $this->pass = $_ENV['MYSQL_ROOT_PASSWORD']; - $this->conn = new mysqli($this->host, $this->user, $this->pass); + $this->conn = new mysqli($this->host, 'root', $this->pass); if ($this->conn->connect_error) { die("db connection failed " . $this->conn->connect_error); } diff --git a/app/main/Main.php b/app/main/Main.php index bb2002f..4f2c4d8 100644 --- a/app/main/Main.php +++ b/app/main/Main.php @@ -6,10 +6,6 @@ class Main { private $db; public function __construct() { - // require_once __DIR__ . '/../pages/Example.php'; - // require_once __DIR__ . '/../controllers/NotFoundController.php'; - - // $this->controller = new NotFoundController(); $this->method = 'index'; $url = $this->parseUrl(); diff --git a/db-init/seeding/all.sh b/db-init/seeding/all.sh deleted file mode 100755 index 0694db8..0000000 --- a/db-init/seeding/all.sh +++ /dev/null @@ -1,18 +0,0 @@ -apt-get update -apt-get install -y python3 python3-pip - -pip3 install requests Faker - -# check if seeding has already been done -if [ ! -f init.flag ]; then - echo "Seeding database... ###########################################" - python3 user.py - python3 genre.py - python3 author.py - python3 book.py - touch init.flag -else - echo "Action already initiated. Skipping..." - -echo "Seeding complete." -fi \ No newline at end of file diff --git a/db-init/seeding/author.py b/db-init/seeding/author.py deleted file mode 100644 index 19ff43c..0000000 --- a/db-init/seeding/author.py +++ /dev/null @@ -1,43 +0,0 @@ -import requests -import random - -api_url = 'http://web/author/add' - -print (""" -Seeding Authors -==================================== - -... -""") - -# Authors Generator -AUTHORS = [ - "Andrea Hirata", - "Dee Lestari", - "Pramoedya Ananta Toer", - "Tere Liye", - "Ika Natassa", - "Ahmad Fuadi", - "Tere Liye", - "Dewi Lestari", - "Habiburrahman El Shirazy", - "Ayah Edy", - "Fira Basuki", - "Seno Gumira Ajidarma", - "Djenar Maesa Ayu", - "Mira W", - "Leila S. Chudori" -] - -for author in AUTHORS: - author_data = { - 'author-name': author, - 'author-age': random.randint(20, 50) - } - - response = requests.post(api_url, data=author_data) - - if response.status_code == 200: - print(f"Author '{author_data['author-name']}' inserted successfully.") - else: - print(f"Failed to insert author '{author_data['author-name']}'.") \ No newline at end of file diff --git a/db-init/seeding/book.py b/db-init/seeding/book.py deleted file mode 100644 index 2ae534e..0000000 --- a/db-init/seeding/book.py +++ /dev/null @@ -1,95 +0,0 @@ -import requests -import random -import os - -print (""" -Seeding Books -==================================== - -... -""") - - -NUM_OF_AUTHORS = 15 -NUM_OF_GENRES = 15 - -post_api = 'http://web/book/add' - - -books = [] -cat = ['hardcover-fiction', 'hardcover-nonfiction', 'young-adult'] - -# use nytimes api to get top 50 books -api_key = 'NjAsG7nGHyOJCVXiQRf3OIDPcnA8F0qu' -book_data_api = f'https://api.nytimes.com/svc/books/v3/lists/current/' - - -for c in cat: - params = { - "api-key": api_key - } - - # Get books data - response = requests.get(book_data_api + c, params=params) - - if response.status_code != 200: - print("Failed to get books data.", response.status_code, response.text) - exit(1) - - data = response.json() - books.extend(data['results']['books']) - - -for b in books: - title = (b['title']).title() - - print(f"Trying to add book - {title} to database.") - - num_of_authors = random.randint(1, 4) - authors = [] - for _ in range(num_of_authors): - authors.append(random.randint(1, NUM_OF_AUTHORS)) - - num_of_genres = random.randint(1, 3) - genres = [] - for _ in range(num_of_genres): - genres.append(random.randint(1, NUM_OF_GENRES)) - - year = random.randint(2000, 2020) - price = random.randint(1,100) * 10000 - - book_cover_url = b['book_image'] - book_cover_temp_path = f'tmp/{title}.jpg' - - with open(book_cover_temp_path, 'wb') as image_file: - image_content = requests.get(book_cover_url).content - image_file.write(image_content) - - audio_rnd = random.randint(0, 2) - audio_path = f'tmp/tmp{audio_rnd}.mp3' - - files = { - 'cover': open(book_cover_temp_path, 'rb'), - 'audio': open(audio_path, 'rb') - } - - data = { - 'title': title, - 'year': year, - 'summary': b['description'], - 'authors[]': authors, - 'genres[]': genres, - 'price': price, - 'lang': 'English', - } - - response = requests.post(post_api, data=data, files=files) - - if response.status_code == 200: - print(f"Book '{data['title']}' inserted successfully.") - else: - print(f"Failed to insert book '{data['title']}'.") - - print("----------------------------------------------") - - os.remove(book_cover_temp_path) \ No newline at end of file diff --git a/db-init/seeding/genre.py b/db-init/seeding/genre.py deleted file mode 100644 index b477fbd..0000000 --- a/db-init/seeding/genre.py +++ /dev/null @@ -1,40 +0,0 @@ -import requests - -print (""" -Seeding Genres -==================================== - -... -""") - -BOOK_GENRES = [ - "Mystery", - "Science Fiction", - "Fantasy", - "Romance", - "Thriller", - "Non-Fiction", - "Historical Fiction", - "Biography", - "Horror", - "Adventure", - "Young Adult", - "Dystopian", - "Self-Help", - "Crime", - "Classics" -] - -api_url = 'http://web/genre/add' - -for genre in BOOK_GENRES: - data = { - 'genre': genre - } - - response = requests.post(api_url, data=data) - - if response.status_code == 200: - print(f"Genre '{data['genre']}' inserted successfully.") - else: - print(f"Failed to insert genre '{data['genre']}'.") \ No newline at end of file diff --git a/db-init/seeding/tmp/.gitkeep b/db-init/seeding/tmp/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/db-init/seeding/user.py b/db-init/seeding/user.py deleted file mode 100644 index 3b916f3..0000000 --- a/db-init/seeding/user.py +++ /dev/null @@ -1,71 +0,0 @@ -import requests -from faker import Faker -import random -import os - -fake = Faker() - -api_url = 'http://web/user/register' - -print (""" -Seeding Users -==================================== - -... -""") - -users = [] -for _ in range(20): - username = fake.user_name() - password = username - email = fake.email() - - # Generate a random image URL from picsum.photos - image_url = f'https://picsum.photos/500' - - # Create a temporary image file - image_path = f'tmp/{username}.jpg' - - with open(image_path, 'wb') as image_file: - image_content = requests.get(image_url).content - image_file.write(image_content) - - role = random.randint(0,1) - - user_data = { - 'username': username, - 'role': ['customer', 'admin'][role], - 'email': email, - 'password': password - } - - users.append((user_data, image_path)) - - -users.append(({ - 'username': 'admin', - 'role': 'admin', - 'email': 'admin@gmail.com', - 'password': 'admin' -}, 'tmp/tmp.jpg')) - -users.append(({ - 'username': 'cust', - 'role': 'cust', - 'email': 'cust@gmail.com', - 'password': 'cust' -}, 'tmp/tmp.jpg')) - -# Send POST requests to create users with file uploads -for user_data, image_path in users: - files = {'profile-pic': open(image_path, 'rb')} - response = requests.post(api_url, data=user_data, files=files) - - if response.status_code == 200: - print(f"User '{user_data['username']}' inserted successfully.") - else: - print(f"Failed to insert user '{user_data['username']}'.") - - # Clean up: remove temporary image file - if (image_path != 'tmp/tmp.jpg'): - os.remove(image_path) \ No newline at end of file diff --git a/db-init/base.sql b/db/V1__init.sql similarity index 97% rename from db-init/base.sql rename to db/V1__init.sql index 0a347e1..85645cb 100644 --- a/db-init/base.sql +++ b/db/V1__init.sql @@ -1,56 +1,56 @@ -CREATE TABLE IF NOT EXISTS `user` ( - `username` varchar(32) PRIMARY KEY, - `role` ENUM('customer', 'admin') NOT NULL, - `email` varchar(320), - `password` varchar(128) NOT NULL, - `image_path` TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS `have` ( - `username` varchar(25), - `book_id` integer, - `purchase_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`username`, `book_id`) -); - -CREATE TABLE IF NOT EXISTS `book` ( - `book_id` integer PRIMARY KEY AUTO_INCREMENT, - `title` varchar(255) NOT NULL, - `year` year(4) NOT NULL, - `summary` text, - `price` integer NOT NULL, - `duration` integer NOT NULL COMMENT 'in seconds', - `lang` varchar(64) DEFAULT 'English', - `audio_path` text NOT NULL, - `cover_path` text NOT NULL -); - -CREATE TABLE IF NOT EXISTS `genre` ( - `genre_id` integer PRIMARY KEY AUTO_INCREMENT, - `name` varchar(32) -); - -CREATE TABLE IF NOT EXISTS `book_genre` ( - `book_id` integer, - `genre_id` integer, - PRIMARY KEY (`book_id`, `genre_id`) -); - -CREATE TABLE IF NOT EXISTS `author` ( - `author_id` integer PRIMARY KEY AUTO_INCREMENT, - `full_name` varchar(32) NOT NULL, - `age` int -); - -CREATE TABLE IF NOT EXISTS `authored_by` ( - `book_id` integer, - `author_id` integer, - PRIMARY KEY (`book_id`, `author_id`) -); - -ALTER TABLE `have` ADD FOREIGN KEY (`username`) REFERENCES `user`(`username`) ON DELETE CASCADE ON UPDATE CASCADE; -ALTER TABLE `have` ADD FOREIGN KEY (`book_id`) REFERENCES `book`(`book_id`) ON DELETE CASCADE ON UPDATE CASCADE; -ALTER TABLE `book_genre` ADD FOREIGN KEY (`book_id`) REFERENCES `book`(`book_id`) ON DELETE CASCADE ON UPDATE CASCADE; -ALTER TABLE `book_genre` ADD FOREIGN KEY (`genre_id`) REFERENCES `genre`(`genre_id`) ON DELETE CASCADE ON UPDATE CASCADE; -ALTER TABLE `authored_by` ADD FOREIGN KEY (`book_id`) REFERENCES `book`(`book_id`) ON DELETE CASCADE ON UPDATE CASCADE; +CREATE TABLE IF NOT EXISTS `user` ( + `username` varchar(32) PRIMARY KEY, + `role` ENUM('customer', 'admin') NOT NULL, + `email` varchar(320), + `password` varchar(128) NOT NULL, + `image_path` TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS `have` ( + `username` varchar(25), + `book_id` integer, + `purchase_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`username`, `book_id`) +); + +CREATE TABLE IF NOT EXISTS `book` ( + `book_id` integer PRIMARY KEY AUTO_INCREMENT, + `title` varchar(255) NOT NULL, + `year` year(4) NOT NULL, + `summary` text, + `price` integer NOT NULL, + `duration` integer NOT NULL COMMENT 'in seconds', + `lang` varchar(64) DEFAULT 'English', + `audio_path` text NOT NULL, + `cover_path` text NOT NULL +); + +CREATE TABLE IF NOT EXISTS `genre` ( + `genre_id` integer PRIMARY KEY AUTO_INCREMENT, + `name` varchar(32) +); + +CREATE TABLE IF NOT EXISTS `book_genre` ( + `book_id` integer, + `genre_id` integer, + PRIMARY KEY (`book_id`, `genre_id`) +); + +CREATE TABLE IF NOT EXISTS `author` ( + `author_id` integer PRIMARY KEY AUTO_INCREMENT, + `full_name` varchar(32) NOT NULL, + `age` int +); + +CREATE TABLE IF NOT EXISTS `authored_by` ( + `book_id` integer, + `author_id` integer, + PRIMARY KEY (`book_id`, `author_id`) +); + +ALTER TABLE `have` ADD FOREIGN KEY (`username`) REFERENCES `user`(`username`) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE `have` ADD FOREIGN KEY (`book_id`) REFERENCES `book`(`book_id`) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE `book_genre` ADD FOREIGN KEY (`book_id`) REFERENCES `book`(`book_id`) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE `book_genre` ADD FOREIGN KEY (`genre_id`) REFERENCES `genre`(`genre_id`) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE `authored_by` ADD FOREIGN KEY (`book_id`) REFERENCES `book`(`book_id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `authored_by` ADD FOREIGN KEY (`author_id`) REFERENCES `author`(`author_id`) ON DELETE CASCADE ON UPDATE CASCADE; \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 2303b1c..bf1b015 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -3,47 +3,32 @@ services: web: container_name: tubes-1 user: "1000:1000" - image: tubes-1:latest + build: + context: . + dockerfile: Dockerfile + env_file: + - .env ports: - 8000:80 depends_on: - db volumes: - ./app:/var/www/html/ - networks: - - wbd-network expose: - '80' + links: + - db db: container_name: wbd-db user: "1000:1000" image: mysql restart: always - environment: - MYSQL_DATABASE: 'wbd-db' - MYSQL_USER: 'user' - MYSQL_PASSWORD: 'secret' - MYSQL_ROOT_PASSWORD: 'secret' + env_file: + - .env volumes: - - ./mysql:/var/lib/mysql - - ./db-init:/docker-entrypoint-initdb.d + - ./db/mysql2:/var/lib/mysql + - ./db:/docker-entrypoint-initdb.d ports: - '9096:3306' expose: - - '3306' - networks: - - wbd-network - data-seeding: - container_name: python-seeding - image: python:3.7 - volumes: - - ./db-init/seeding/:/app - working_dir: /app - command: ["sh", "all.sh"] - depends_on: - - web - - db - networks: - - wbd-network -networks: - wbd-network: \ No newline at end of file + - '3306' \ No newline at end of file -- GitLab