am-i-alive-nodejs

Make it easy for people to check if you are alive or not.
git clone http://git.hanabi.in/repos/am-i-alive-nodejs.git
Log | Files | Refs | LICENSE

index.js (5639B)


      1 //     Import.
      2 //      _                            _
      3 //     (_)_ __ ___  _ __   ___  _ __| |_
      4 //     | | '_ ` _ \| '_ \ / _ \| '__| __|
      5 //     | | | | | | | |_) | (_) | |  | |_
      6 //     |_|_| |_| |_| .__/ \___/|_|   \__|
      7 //                 |_|
      8 
      9 const { name, port, auth } = require("./config.js");
     10 //     Global variables.
     11 const offset = 16 * 10 ** 8;
     12 const ms = 10 ** 3;
     13 const sec2hr = 3600;
     14 const [_4hr, _18hr, _60hr, _5d] = [4, 18, 60, 120].map((_) => _ * sec2hr);
     15 
     16 //     Server setup
     17 //     ____                                      _
     18 //    / ___|  ___ _ ____   _____ _ __   ___  ___| |_ _   _ _ __
     19 //    \___ \ / _ \ '__\ \ / / _ \ '__| / __|/ _ \ __| | | | '_ \
     20 //     ___) |  __/ |   \ V /  __/ |    \__ \  __/ |_| |_| | |_) |
     21 //    |____/ \___|_|    \_/ \___|_|    |___/\___|\__|\__,_| .__/
     22 //                                                        |_|
     23 
     24 const express = require("express");
     25 const app = express();
     26 app.use(express.json());
     27 app.use((req, res, next) => {
     28   res.header("Access-Control-Allow-Origin", "*");
     29   res.header("Access-Control-Allow-Headers", "Content-Type");
     30   next();
     31 });
     32 app.listen(port, () => console.log(`Server is running on port:${port}.`));
     33 
     34 //     Route setup
     35 //      ____             _                  _
     36 //     |  _ \ ___  _   _| |_ ___   ___  ___| |_ _   _ _ __
     37 //     | |_) / _ \| | | | __/ _ \ / __|/ _ \ __| | | | '_ \
     38 //     |  _ < (_) | |_| | ||  __/ \__ \  __/ |_| |_| | |_) |
     39 //     |_| \_\___/ \__,_|\__\___| |___/\___|\__|\__,_| .__/
     40 //                                                   |_|
     41 
     42 // Get status.
     43 app.get("/", async (req, res) => {
     44   let db;
     45   try {
     46     db = await opendb();
     47     const updatedAt = await getUpdatedAt(db);
     48     res.statusCode = 200;
     49 
     50     // If user has never used amialive yet.
     51     if (updatedAt == 0) {
     52       res.json({
     53         message: `${name} has not started using this tool.`,
     54       });
     55     }
     56     // If the user has been using amialive.
     57     else {
     58       const diff = getTimeDiff(updatedAt);
     59       const { lastseen, unix } = getLastSeen(updatedAt);
     60 
     61       // Less than 4 hours means most certainly alive.  Don't show timestamp.
     62       if (diff > 0 && diff <= _4hr) {
     63         res.json({
     64           message: `${name} is most certainly alive.`,
     65           lastseen,
     66           unix,
     67         });
     68       }
     69       // 4-18 hours.  Likely AFK.  Don't show timestamp.
     70       else if (diff > _4hr && diff <= _18hr) {
     71         res.json({
     72           message: `${name} is most likely AFK.`,
     73           lastseen,
     74           unix,
     75         });
     76       }
     77       // 18-60 hours.  Might want to check on me, I am not away for that long.  Show timestamp.
     78       else if (diff > _18hr && diff <= _60hr) {
     79         res.json({
     80           message: `${name} has been away for quite some time now.  You might want to check on him.`,
     81           lastseen,
     82           unix,
     83         });
     84       }
     85       // Away for 2.5-5d. That is rather too long.  Please check on me!
     86       else if (diff > _60hr && diff <= _5d) {
     87         res.json({
     88           message: `${name} has been away for rather too long.  If ${name} didn't tell you he will be gone for so long, *please* check on him!`,
     89           lastseen,
     90           unix,
     91         });
     92       }
     93       // Most likely dead if I have been away for five days.
     94       else if (diff > _5d) {
     95         res.json({
     96           message: `${name} is most certainly dead.`,
     97           lastseen,
     98           unix,
     99         });
    100       }
    101     }
    102   } catch (err) {
    103     res.statusCode = 500;
    104     res.json({ err: err.toString() });
    105   } finally {
    106     async () => await db.close();
    107   }
    108 });
    109 
    110 // Post timestamp.
    111 app.post("/update", async (req, res) => {
    112   let db;
    113   try {
    114     db = await opendb();
    115     const authorised = req.body.auth == auth;
    116     res.statusCode = authorised ? 200 : 401;
    117     if (!authorised) {
    118       res.json({ message: "Incorrect credentials.", updated: authorised });
    119     } else {
    120       await updatedb(db);
    121       res.json({ updated: authorised });
    122     }
    123   } catch (err) {
    124     res.statusCode = 500;
    125     res.json({ err: err.toString() });
    126   } finally {
    127     async () => await db.close();
    128   }
    129 });
    130 
    131 //      DB setup
    132 //      ____  ____             _
    133 //     |  _ \| __ )   ___  ___| |_ _   _ _ __
    134 //     | | | |  _ \  / __|/ _ \ __| | | | '_ \
    135 //     | |_| | |_) | \__ \  __/ |_| |_| | |_) |
    136 //     |____/|____/  |___/\___|\__|\__,_| .__/
    137 //                                      |_|
    138 
    139 const { Database } = require("sqlite3");
    140 const sqlite = require("sqlite");
    141 
    142 //      _   _      _                    __
    143 //     | | | | ___| |_ __   ___ _ __   / _|_ __  ___
    144 //     | |_| |/ _ \ | '_ \ / _ \ '__| | |_| '_ \/ __|
    145 //     |  _  |  __/ | |_) |  __/ |    |  _| | | \__ \
    146 //     |_| |_|\___|_| .__/ \___|_|    |_| |_| |_|___/
    147 //                  |_|
    148 
    149 // Open the database.
    150 async function opendb() {
    151   const db = await sqlite.open({
    152     filename: "./am-i-alive.db",
    153     driver: Database,
    154   });
    155   return db;
    156 }
    157 
    158 // Get updated at.
    159 async function getUpdatedAt(db) {
    160   const { updatedat } = await db.get("SELECT updatedat FROM alive WHERE id=0");
    161   return updatedat;
    162 }
    163 
    164 // Update timestamp in database.
    165 async function updatedb(db) {
    166   const now = Math.floor(Date.now() / ms) - offset;
    167   const result = await db.run(
    168     "UPDATE alive SET updatedat = ? WHERE id = 0",
    169     now
    170   );
    171   return result;
    172 }
    173 
    174 // Get time difference in seconds.
    175 function getTimeDiff(updatedAt) {
    176   const now = Math.floor(Date.now() / ms) - offset;
    177   return now - updatedAt;
    178 }
    179 
    180 // Get last seen as a string and UNIX timestamp.
    181 function getLastSeen(updatedAt) {
    182   const unix = (updatedAt + offset) * ms;
    183   const datetime = new Date(unix);
    184   const lastseen = `${name} was last active around ${datetime}.`;
    185   return { lastseen, unix };
    186 }