Skip to content
Snippets Groups Projects
Commit 729a39ee authored by lordjbs's avatar lordjbs
Browse files

yes

parent 559a9588
No related branches found
No related tags found
No related merge requests found
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/shortnex.iml" filepath="$PROJECT_DIR$/.idea/shortnex.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="Python" name="Python">
<configuration sdkName="Python 3.6 (venv)" />
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Python 3.6 (venv) interpreter library" level="application" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
{
"port": 5000,
"database": "database.db"
}
\ No newline at end of file
File added
# shortnex v2.0
# made by jbs (https://github.com/lordjbs/)
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
import sqlite3
import traceback
class Database:
def __init__(self, file):
print("shortnex | Loading database")
try:
self.conn = sqlite3.connect(file, check_same_thread=False)
self.db = self.conn.cursor()
print("shortnex | Connected to database!")
print("shortnex | Testing database...")
self.checkStart()
print("shortnex | Success testing database!")
except Exception:
print("shortnex | Database connection failed. Exiting...")
exit(0)
def __close__(self):
self.conn.commit()
self.conn.close()
def checkStart(self):
output = self.db.execute("CREATE TABLE IF NOT EXISTS urls (id text, url text, date integer)")
self.conn.commit()
def add(self, id, url, date):
print("cbt")
try:
self.db.execute("INSERT INTO urls VALUES (:i, :u, :d)", {'i': id, 'u': url, 'd': date})
except Exception as e:
traceback.print_exc()
self.conn.commit()
def getURL(self, id):
try:
a = self.db.execute("""SELECT url FROM urls WHERE id = :bruh;""", {'bruh': id})
value = a.fetchone()[0]
if value is None:
return None
else:
return value
except TypeError:
return None
main.py 0 → 100644
# shortnex v2.0
# made by jbs (https://github.com/lordjbs/)
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from flask import Flask, request, redirect, send_from_directory, render_template, url_for
import utils
from database import Database
import json
import time
with open('config.json') as _config:
data = json.load(_config)
config = {"port": data["port"], "database": data["database"]}
db = Database(config.get("database"))
app = Flask(__name__, static_url_path='/static/')
@app.route('/')
def index():
return render_template("index.html")
# curl --header "Content-Type: application/json, charset=utf-8" --request POST --data '{"url":"https://lordjbs.xyz"}' http://localhost:5000/shorten
@app.route("/shorten", methods=['POST'])
def shorten():
if request.method != "POST":
return {"success": "false", "error": "This route is POST only."}
content = request.get_json()
print(content)
if not "url" in content:
return {"success": False, "error": "The parameter 'url' does not exist.", "code": 1}
if utils.checkIfProperURL(content.get("url")) is None:
return {"success": False, "error": "That is not a proper url.", "code": 1}
url = utils.returnProperURL(content.get("url"))
try:
id = utils.createID()
db.add(id, content.get("url"), int(time.time()))
return {"success": True, "id": id, "url": request.base_url}
except Exception:
return {"success": False, "message": "Error has occurred while shortening. Please contact an administrator."}
@app.route("/<id>")
def goto(id):
if not db.getURL(id):
return {"success": False, "error": "Invalid ID"}
else:
return redirect(db.getURL(id))
@app.route("/check/tokensystem")
def tokensystem():
return {"active": False}
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
This diff is collapsed.
/*! js-cookie v2.2.0 | MIT */
!function(e){var n=!1;if("function"==typeof define&&define.amd&&(define(e),n=!0),"object"==typeof exports&&(module.exports=e(),n=!0),!n){var o=window.Cookies,t=window.Cookies=e();t.noConflict=function(){return window.Cookies=o,t}}}(function(){function e(){for(var e=0,n={};e<arguments.length;e++){var o=arguments[e];for(var t in o)n[t]=o[t]}return n}function n(o){function t(n,r,i){var c;if("undefined"!=typeof document){if(arguments.length>1){if("number"==typeof(i=e({path:"/"},t.defaults,i)).expires){var a=new Date;a.setMilliseconds(a.getMilliseconds()+864e5*i.expires),i.expires=a}i.expires=i.expires?i.expires.toUTCString():"";try{c=JSON.stringify(r),/^[\{\[]/.test(c)&&(r=c)}catch(e){}r=o.write?o.write(r,n):encodeURIComponent(r+"").replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),n=(n=(n=encodeURIComponent(n+"")).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent)).replace(/[\(\)]/g,escape);var s="";for(var f in i)i[f]&&(s+="; "+f,!0!==i[f]&&(s+="="+i[f]));return document.cookie=n+"="+r+s}n||(c={});for(var p=document.cookie?document.cookie.split("; "):[],d=/(%[0-9A-Z]{2})+/g,u=0;u<p.length;u++){var l=p[u].split("="),C=l.slice(1).join("=");this.json||'"'!==C.charAt(0)||(C=C.slice(1,-1));try{var m=l[0].replace(d,decodeURIComponent);if(C=o.read?o.read(C,m):o(C,m)||C.replace(d,decodeURIComponent),this.json)try{C=JSON.parse(C)}catch(e){}if(n===m){c=C;break}n||(c[m]=C)}catch(e){}}return c}}return t.set=t,t.get=function(e){return t.call(t,e)},t.getJSON=function(){return t.apply({json:!0},[].slice.call(arguments))},t.defaults={},t.remove=function(n,o){t(n,"",e(o,{expires:-1}))},t.withConverter=n,t}return n(function(){})});
\ No newline at end of file
var istokenactive = false;
function pressed() {
addTokenToURL(function(token) {
$.ajax({
//url: "/shorten?url=" + document.getElementById("url").value + token,
url: "/shorten",
type: "POST",
data: JSON.stringify({"url": document.getElementById("url").value}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
console.log(data)
if (data.success !== true) {
console.log(data)
switch (data.code) {
case 0:
setText("Database Error. (Error Code: 0)");
break;
case 1:
setText("The URL is invalid. (Error Code: 1)");
break;
case 2:
setText("The URL is \"undefined\"! (Error Code: 2)");
break;
case 3:
setText("The Usersystem encountered an Error. Check Logs. (Error Code: 3)");
break;
case 4:
setText("You don't have Permissions to do that. (Error Code: 4)");
break;
case 5:
setText("This URL is not in the Database. (Error Code: 5)");
break;
case 6:
setText("Unexpected User Database Error (Error Code: 6)");
break;
default:
setText("Unable to shorten URL (Unknown Error -> Switch Default)");
break;
}
} else {
setText("Shortened URL: http://" + data.url + "/" + data.id);
}
}
});
});
}
function checkTokensystem(func) {
$.ajax({
url: "/check/tokensystem",
type: "GET",
success: function(data) {
if (data.active) addTokenbar(true);
else addTokenbar(false);
return func(data.active);
}
});
}
function setText(Text) {
document.getElementById("u").innerHTML = Text;
}
function addTokenbar(boolean) {
if (boolean) {
istokenactive = true;
document.getElementById("tokenholder").style.visibility = 'visible';
} else {
istokenactive = false;
document.getElementById("tokenholder").style.visibility = 'hidden';
}
}
function registerColor() {
var e = Cookies.get("color");
if (e == "#282c34") {
setColor(false);
} else {
setColor(true);
}
}
function addTokenToURL(func) {
var string = "&token=" + document.getElementById("token").value;
if (addTokenToURL) {
func(string);
} else {
func("");
}
}
function setColor(bool) {
if (bool) {
Cookies.set("color", "#282c34");
} else if (!bool) {
Cookies.set("color", "#ffffff");
} else {
Cookies.set("color", "#ffffff");
}
updateColor(Cookies.get("color"));
}
function updateColor(hex) {
const obj = document.getElementById("main");
if (hex == "#282c34") {
document.body.style.background = "#282c34";
document.body.style.color = "#ffffff";
obj.style = "background-color: #282c34; color: white;";
} else if (hex == "#ffffff") {
document.body.style.background = "#ffffff";
document.body.style.color = "#ffffff";
obj.style = "background-color: #ffffff; color: black;";
}
}
$("#re").click(function() {
var e = Cookies.get("color");
console.log("click clock");
if (e !== "#282c34") {
setColor(true);
} else {
setColor(false);
}
});
window.onload = function() {
var e = Cookies.get("color");
if (e == "#282c34") {
setColor(true);
} else {
setColor(false);
}
checkTokensystem(function(active) {
console.log(active);
});
}
\ No newline at end of file
body {
display: flex;
min-height: 100vh;
flex-direction: column;
}
main {
flex: 1 0 auto;
}
.middleContent {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
margin-top: 4%;
margin-bottom: 4%;
}
.bt1 {
position: absolute;
left:0%;
}
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="UTF-8">
<meta name="title" content="shortnex">
<meta name="og:title" content="shortnex">
<meta name="twitter:title" content="shortnex">
<meta name="og:site_name" content="shortnex">
<meta name="description" content="shortnex | a small shortener">
<meta name="og:description" content="shortnex | a small shortener">
<meta name="twitter:description" content="shortnex | a small shortener">
<link rel="icon" href="static/logo.ico">
<script src="/static/jquery.min.js"></script>
<script src="/static/js.cookie-2.2.0.min.js"></script>
<script src="/static/requesthandler.js"></script>
</head>
<body>
<div class=".page-flexbox-wrapper">
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.0/cookieconsent.min.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.0/cookieconsent.min.js"></script>
<script>
window.addEventListener("load", function(){
window.cookieconsent.initialise({
"palette": {
"popup": {
"background": "#efefef",
"text": "#404040"
},
"button": {
"background": "#66bb6a",
"text": "#ffffff"
}
},
"theme": "edgeless",
"position": "bottom-right"
})});
</script>
<header>
<nav>
<div class="nav-wrapper green">
<a href="#!" class="brand-logo center">shortnex</a>
<a href="#" data-target="sidenav" class="sidenav-trigger"><i class="material-icons">menu</i></a>
<ul class="right hide-on-med-and-down">
<li><a href="https://owo.codes/jbs/Shortnex">Git</a></li>
<li><a onclick="registerColor()"><i class="material-icons left">opacity</i></a></li>
</ul>
</div>
</nav>
<ul class="sidenav" id="sidenav">
<li><a href="https://owo.codes/jbs/Shortnex">Git</a></li>
<li><a onclick="registerColor()"><i class="material-icons left">opacity</i></a></li>
</ul>
</header>
<main id="main">
<div class="section no-pad-bot middleContent" id="index-banner">
<div class="container">
<br><br>
<h1 class="header center green-text">Shorten a link.</h1>
<div class="row center">
<h5 class="header col s12 light" id="u">Shortened URL: </h5>
</div>
<div class="row center">
<form class="col s12">
<div class="row">
<div class="input-field col s6" style="left: 25% !important;">
<input placeholder="https://example.org" id="url" type="text" class="validate">
<label for="url">URL</label>
</div>
</div>
</form>
<button id="shortenz" class="btn-large waves-effect waves-light green" onclick="pressed()">Shorten!</button>
<form class="col s12" id="tokenholder">
<div class="row">
<div class="input-field col s6" style="left: 25% !important;">
<input placeholder="Token" id="token" type="password" class="validate">
<label for="token">TOKEN</label>
</div>
</div>
</form>
</div>
<br><br>
<!-- <button onclick="registerColor()" id="re" class="bt1 waves-effect waves-light green btn"><i class="material-icons left">opacity</i> Change Color</button> -->
</div>
</div>
</main>
<footer class="page-footer green footer ft" style="position:fixed;bottom:0;left:0;width:100%;">
<div class="container">
</div>
<div class="footer-copyright">
<div class="container">
shortnex | Made with &#9829; by jbs.
</div>
</div>
</footer>
<script>
$(document).ready(function(){
$('.sidenav').sidenav();
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</div>
</body>
</html>
\ No newline at end of file
utils.py 0 → 100644
# shortnex v2.0
# made by jbs (https://github.com/lordjbs/)
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
import string, random, re
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
def checkIfProperURL(url):
return re.match(regex, returnProperURL(url))
def returnProperURL(url):
out = url
if not re.match(r'^https://', url) or re.match(r'^http://', url):
out = "https://" + url
return out
def createID():
ran = ''.join([random.choice(string.ascii_letters
+ string.digits) for n in range(6)])
return ran
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment