Skip to content

Commit

Permalink
rename and comment
Browse files Browse the repository at this point in the history
  • Loading branch information
dashroshan committed Oct 2, 2022
1 parent 4466d92 commit 9bd61bd
Show file tree
Hide file tree
Showing 10 changed files with 97 additions and 97 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.env
config.json

# Logs
logs
Expand Down
15 changes: 15 additions & 0 deletions database/mongo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const visitsBadgeSchema = require('./schema.js');

module.exports.visitsBadge = async function (uniqueID) {
const badge = await visitsBadgeSchema.findOneAndUpdate(
{ uniqueID: uniqueID },
{
$setOnInsert: {
uniqueID: uniqueID,
},
$inc: { visitsCount: 1 },
},
{ new: true, upsert: true }
).select({ visitsCount: 1 });
return badge.visitsCount;
}
9 changes: 9 additions & 0 deletions database/schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const mongoose = require("mongoose");

module.exports = mongoose.model("visitsBadge", new mongoose.Schema({
uniqueID: String,
visitsCount: {
type: Number,
default: 0,
},
}));
16 changes: 16 additions & 0 deletions frontend/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ function App() {
const [linkCopied, setLinkCopied] = useState(false);
const [codeCopied, setCodeCopied] = useState(false);

// Update the live preview of the SVG badge when any of the customization options change
useEffect(() => {
setSvgData(svgBadge(formData.text, formData.shadow, formData.visitsBG, formData.countBG, formData.visitsText, formData.countText, 12345));
}, [formData]);

// Copy given content to the clipboard
const copyToClipboard = (content) => {
const el = document.createElement('textarea');
el.value = content;
Expand All @@ -37,28 +39,38 @@ function App() {
document.body.removeChild(el);
};

// Create the badge link with current customizations
const createLink = () => {
// Create a random 20 character long string for the uniqueID
let charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
let randomStr = "";
for (let i = 0; i < 20; i++)
randomStr += charset[Math.floor(Math.random() * charset.length)];

// HTML encode space to %20 and stuffs like that
var textContent = encodeURI(formData.text)

// Create and send the link
const link = `https://visits.roshan.cyou/${randomStr}?textContent=${textContent}&textShadow=${(formData.shadow) ? 1 : 0}&visitsBG=${formData.visitsBG.substring(1)}&countBG=${formData.countBG.substring(1)}&visitsText=${formData.visitsText.substring(1)}&countText=${formData.countText.substring(1)}`;
return link;
}

// Create the HTML embed code for the badge
const createCode = () => {
let imgLink = createLink();
return `<a href="https://visits.roshan.cyou"><img src="${imgLink}" alt="Visits Counter Badge" height=30px/></a>`
}

return (
<div className={classes.app}>
{/* SVG badge preview */}
<SVG
className={classes.badge}
src={svgData}
title="React"
/>

{/* Buttons to copy image link and html embed code */}
<div className={classes.copyButtons}>
<Tooltip title="Direct link to the svg badge image" arrow>
<Button variant="contained" disableElevation startIcon={(linkCopied) ? <DoneIcon /> : <ContentCopyIcon />} onClick={() => {
Expand All @@ -83,6 +95,8 @@ function App() {
</Button>
</Tooltip>
</div>

{/* Customizations card */}
<div className={classes.card}>
<div className={classes.customize}>Customizations</div>
<TextField
Expand All @@ -98,6 +112,8 @@ function App() {
<MuiColorInput isAlphaHidden={true} format='hex' value={formData.countText} onChange={(c) => setFormData({ ...formData, "countText": c })} helperText="Colour of the visitor count on right" />
<FormControlLabel control={<Switch checked={formData.shadow} onChange={(e) => setFormData({ ...formData, "shadow": !formData.shadow })} />} label="Text shadow" />
</div>

{/* Footer with link to the GitHub repo and author site*/}
<div className={classes.bottomLinks}>
<Button target="_blank" href="https://github.com/roshan1337d/visits-counter" variant="contained" disableElevation startIcon={<GitHubIcon />}>
SOURCE CODE
Expand Down
8 changes: 1 addition & 7 deletions frontend/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,10 @@ import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
);
13 changes: 0 additions & 13 deletions frontend/src/reportWebVitals.js

This file was deleted.

5 changes: 0 additions & 5 deletions frontend/src/setupTests.js

This file was deleted.

49 changes: 27 additions & 22 deletions frontend/src/svgBadge.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Get an approximate width of the given string
const approxWidth = (str) => {
let size = 0;
for (var i = 0; i < str.length; i++) {
Expand All @@ -14,6 +15,9 @@ const approxWidth = (str) => {
return size * 6 / 1000.0;
};

// Generate the shadow color when black is mixed in with the bgColor. This is
// used instead of opacity as multiple texts with the shadowColor are added a
// little below one another to create a solid long shadow
const shadowColor = (bgColor) => {
var a = 0.3;
var r = Math.floor(0x00 * a + Number(`0x${bgColor.substring(0, 2)}`) * (1 - a));
Expand All @@ -23,46 +27,47 @@ const shadowColor = (bgColor) => {
return finalColor;
};

// Strip the # in the color code if present
const processColor = (color) => {
if (color[0] === "#") return color.substring(1);
else return color;
}

function svgBadge(textContentI, textShadowI, visitsBGI, countBGI, visitsTextI, countTextI, visitsI) {
// Getting values
const visitsBG = processColor(visitsBGI);
const countBG = processColor(countBGI);
const visitsText = processColor(visitsTextI);
const countText = processColor(countTextI);
const textShadow = (typeof textShadowI === "boolean") ? ((textShadowI) ? "1" : "0") : textShadowI;
const visitsValue = textContentI;
const visits = visitsI;
// Generate and return the SVG code for the badge
function svgBadge(label, shadow, labelBGColor, countBGColor, labelTextColor, countTextColor, visits) {
// Format the given parameter values
labelBGColor = processColor(labelBGColor);
countBGColor = processColor(countBGColor);
labelTextColor = processColor(labelTextColor);
countTextColor = processColor(countTextColor);
shadow = (typeof shadow === "boolean") ? ((shadow) ? "1" : "0") : shadow;

// Calculating text widths
let visitsWidth = 10 + (approxWidth(visitsValue)) * 10;
// Calculate the text widths
let visitsWidth = 10 + (approxWidth(label)) * 10;
let countWidth = 10 + (approxWidth(visits.toString())) * 10;

// Text shadow template
let shadow = (textShadow === "1") ? `
<text transform="matrix(1 0 0 1 ${visitsWidth + 10.4} 14.8206)" fill="${shadowColor(countBG)}" font-family="Arial" font-size="10px">${visits}</text>
<text transform="matrix(1 0 0 1 ${visitsWidth + 10.4} 14.1597)" fill="${shadowColor(countBG)}" font-family="Arial" font-size="10px">${visits}</text>
<text transform="matrix(1 0 0 1 7.0189 14.8425)" fill="${shadowColor(visitsBG)}" font-family="Arial" font-size="10px">${visitsValue}</text>
<text transform="matrix(1 0 0 1 7.038 14.1817)" fill="${shadowColor(visitsBG)}" font-family="Arial" font-size="10px">${visitsValue}</text>
let shadowTemplate = (shadow === "1") ? `
<text transform="matrix(1 0 0 1 ${visitsWidth + 10.4} 14.8206)" fill="${shadowColor(countBGColor)}" font-family="Arial" font-size="10px">${visits}</text>
<text transform="matrix(1 0 0 1 ${visitsWidth + 10.4} 14.1597)" fill="${shadowColor(countBGColor)}" font-family="Arial" font-size="10px">${visits}</text>
<text transform="matrix(1 0 0 1 7.0189 14.8425)" fill="${shadowColor(labelBGColor)}" font-family="Arial" font-size="10px">${label}</text>
<text transform="matrix(1 0 0 1 7.038 14.1817)" fill="${shadowColor(labelBGColor)}" font-family="Arial" font-size="10px">${label}</text>
`: '';

// Main svg template
// Main SVG template
let svg = `
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 ${visitsWidth + countWidth + 7.5} 20" xml:space="preserve">
<g id="badge">
<path fill="#${visitsBG}" d="M46.11,20H4c-2.21,0-4-1.79-4-4V4c0-2.21,1.79-4,4-4h${visitsWidth}V20z"/>
<path fill="#${countBG}" d="M46.11,20H${visitsWidth + countWidth + 3.5}c2.21,0,4-1.79,4-4V4c0-2.21-1.79-4-4-4H${visitsWidth + 4}V20z"/>
${shadow}
<text transform="matrix(1 0 0 1 ${visitsWidth + 10.4} ${(textShadow === "1") ? '13.4559' : '13.8'})" fill="#${countText}" font-family="Arial" font-size="10px">${visits}</text>
<text transform="matrix(1 0 0 1 7.038 ${(textShadow === "1") ? '13.4559' : '13.8'})" fill="#${visitsText}" font-family="Arial" font-size="10px">${visitsValue}</text>
<path fill="#${labelBGColor}" d="M46.11,20H4c-2.21,0-4-1.79-4-4V4c0-2.21,1.79-4,4-4h${visitsWidth}V20z"/>
<path fill="#${countBGColor}" d="M46.11,20H${visitsWidth + countWidth + 3.5}c2.21,0,4-1.79,4-4V4c0-2.21-1.79-4-4-4H${visitsWidth + 4}V20z"/>
${shadowTemplate}
<text transform="matrix(1 0 0 1 ${visitsWidth + 10.4} ${(shadow === "1") ? '13.4559' : '13.8'})" fill="#${countTextColor}" font-family="Arial" font-size="10px">${visits}</text>
<text transform="matrix(1 0 0 1 7.038 ${(shadow === "1") ? '13.4559' : '13.8'})" fill="#${labelTextColor}" font-family="Arial" font-size="10px">${label}</text>
</g>
</svg>
`;

// Return the SVG template
return svg;
}

Expand Down
63 changes: 28 additions & 35 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,56 +1,49 @@
const express = require("express");
const cors = require("cors");
const Visits = require("./mongodb");
const svgBadge = require("./frontend/src/svgBadge");
const { port, mongourl } = require('./config.json');

const port = process.env.PORT || 3000;

// Create an express instance and setup middlewares
const app = express();
app.use(express.json());
app.use(cors());
app.use(express.static(__dirname + '/frontend/build'));

// Initilize mongoDB connection
const mongoose = require('mongoose');
const database = require('./database/mongo.js');
mongoose.connect(mongourl, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB.'))
.catch((err) => console.log('Unable to connect to MongoDB.\nError: ' + err));

// Disable caching
app.use(function (req, res, next) {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Cache-Control', 'private, no-cache, no-store, must-revaluniqueIDate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
next()
});

async function processSVG(req, res) {
// Getting values from query
const visitsBG = req.query.visitsBG || "484848";
const countBG = req.query.countBG || "2574EA";
const visitsText = req.query.visitsText || "FFFFFF";
const countText = req.query.countText || "FFFFFF";
const textShadow = req.query.textShadow || "1";
const visitsValue = req.query.textContent || "VISITS";
const userName = req.params.userName;

// Database Operations
const visit = await Visits.findOneAndUpdate(
{ userName: userName },
{ $inc: { visits: 1 } },
{ new: true }
).select({ visits: 1 });
let visits = 1;
if (visit != null) visits = visit.visits;
else {
const visit = new Visits({
userName: userName,
visits: 1,
});
await visit.save();
}

// Creating the SVG Badge
const svg = svgBadge(visitsValue, textShadow, visitsBG, countBG, visitsText, countText, visits);

// Sending the SVG Badge
// Get values from query and parameter
const labelBGColor = req.query.labelBGColor || "484848";
const countBGColor = req.query.countBGColor || "2574EA";
const labelTextColor = req.query.labelTextColor || "FFFFFF";
const countTextColor = req.query.countTextColor || "FFFFFF";
const shadow = req.query.shadow || "1";
const label = req.query.label || "VISITS";
const uniqueID = req.params.uniqueID;

// Get the current visits count
const visits = await database.visitsBadge(uniqueID);

// Create the SVG Badge
const svg = svgBadge(label, shadow, labelBGColor, countBGColor, labelTextColor, countTextColor, visits);

// Send the SVG Badge
res.setHeader("Content-Type", "image/svg+xml");
res.send(svg);
}

app.get("/:userName", (req, res) => processSVG(req, res));
app.listen(port, () => console.log(`Running on port ${port}...`));
app.get("/:uniqueID", (req, res) => processSVG(req, res));
app.listen(port, () => console.log(`Ready on port ${port}.`));
15 changes: 0 additions & 15 deletions mongodb.js

This file was deleted.

0 comments on commit 9bd61bd

Please sign in to comment.