This repository has been archived on 2024-06-16. You can view files and clone it, but cannot push or open issues or pull requests.
mebe/lib/mebe_engine/worker.ex

82 lines
2.2 KiB
Elixir

defmodule MebeEngine.Worker do
@moduledoc """
This worker initializes the post database and keeps it alive while the server is running.
"""
use GenServer
require Logger
alias MebeEngine.Crawler
alias MebeEngine.DB
alias MebeEngine.MenuParser
alias MebeWeb.Utils
def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, :ok, opts)
end
def init(:ok) do
load_db()
{:ok, nil}
end
def handle_call(:refresh, _from, nil) do
refresh_db()
{:reply, :ok, nil}
end
def refresh_db() do
Logger.info "Destroying database…"
DB.destroy()
Logger.info "Reloading database…"
load_db()
Logger.info "Update done!"
end
@doc """
Initialize the database by crawling the configured path and parsing data to the DB.
"""
def load_db() do
data_path = Utils.get_conf(:data_path)
Logger.info("Loading menu from '#{data_path}/menu'…")
menu = MenuParser.parse(data_path)
Logger.info("Loading post database from '#{data_path}'…")
%{
pages: pages,
posts: posts,
tags: tags,
authors: authors,
author_names: author_names,
years: years,
months: months,
} = Crawler.crawl(data_path)
Logger.info("Loaded #{Enum.count pages} pages and #{Enum.count posts} posts.")
DB.init()
DB.insert_menu(menu)
DB.insert_posts(posts)
DB.insert_count(:all, Enum.count(posts))
Enum.each Map.keys(pages), fn page -> DB.insert_page pages[page] end
DB.insert_tag_posts(tags)
Enum.each(Map.keys(tags), fn tag -> DB.insert_count(:tag, tag, Enum.count(tags[tag])) end)
if Utils.get_conf(:multi_author_mode) do
DB.insert_author_posts(authors)
DB.insert_author_names(author_names)
Enum.each(Map.keys(authors), fn author -> DB.insert_count(:author, author, Enum.count(authors[author])) end)
end
# For years and months, only insert the counts (the data can be fetched from main posts table)
Enum.each(Map.keys(years), fn year -> DB.insert_count(:year, year, Enum.count(years[year])) end)
Enum.each(Map.keys(months), fn month -> DB.insert_count(:month, month, Enum.count(months[month])) end)
Logger.info("Posts loaded.")
end
end