Skip to content
This repository has been archived by the owner on Mar 27, 2024. It is now read-only.

Commit

Permalink
Implement Level 2 Web Share + extras
Browse files Browse the repository at this point in the history
Includes updated service worker with proper scope, notification and working file upload.
Disables Level 1 (until spec for using both works correctly)
Adds Audio play from gallery (and 3 premade filetype filters)
Bump version due to stats.json change.
  • Loading branch information
Wojbie committed May 3, 2019
1 parent 9185d51 commit c3e9fab
Show file tree
Hide file tree
Showing 9 changed files with 112 additions and 26 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ sessions
!/public/jquery.mobile.custom.min.js
!/public/service-worker.js
!/public/poop192.png
!/public/poop512.png
!/public/poop512.png
!/public/poop96.png
63 changes: 42 additions & 21 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const package = require("./package.json");
const version = package.version;
const config = require(process.argv[2] || "./config.json");
config.url = config.url.replace(/\/?$/, "/")
config.imagePath = config.imagePath.replace(/\/?$/, "/")

const _ = require("lodash");

Expand Down Expand Up @@ -57,7 +59,10 @@ if (fs.existsSync("custom-name.js")) {
}

if (fs.existsSync("stats.json")) {
statCache = JSON.parse(fs.readFileSync("stats.json"));
try {
statCache = JSON.parse(fs.readFileSync("stats.json"));
} catch(error) { console.error('stats.json file was corrupted and has been regenerated. Please merge your backup with current one.'); statCache = {version}; }

if (statCache.version !== version) statCache = { version }; /* note: remember to change version every time stats.json format changes */
else {
_.forOwn(statCache, (value, key) => {
Expand All @@ -68,7 +73,10 @@ if (fs.existsSync("stats.json")) {
}

if (fs.existsSync("nonces.json")) {
nonces = JSON.parse(fs.readFileSync("nonces.json"));
try {
nonces = JSON.parse(fs.readFileSync("nonces.json"));
} catch(error) { console.error('nonces.json file was corrupted and has been regenerated. Please merge your backup with current one.'); nonces = {}; }

_.forOwn(nonces, (value, key) => {
noncesLookup[nonces[key]] = key;
});
Expand Down Expand Up @@ -111,11 +119,19 @@ fs.writeFileSync("public/manifest.json", JSON.stringify({
"short_name": "Shitty",
"name": config.name,
"share_target": {
"action": "upload",
"action": "webshareupload",
"method": "POST",
"enctype": "multipart/form-data",
"params": {
"title": "title",
"text": "text",
"url": "url"
"title": "sharetitle",
"text": "sharetext",
"url": "shareurl",
"files": [
{
"name": "file",
"accept": ["*/*"]
}
]
}
},
"description": config.title,
Expand All @@ -131,8 +147,8 @@ fs.writeFileSync("public/manifest.json", JSON.stringify({
"type": "image/png"
}
],
"start_url": "upload",
"scope": "upload",
"start_url": "webshareupload",
"scope": "webshareupload",
"background_color": "#ffffff",
"display": "standalone",
"theme_color": config.name_color
Expand All @@ -154,7 +170,7 @@ app.engine(".hbs", handlebars({
app.set("view engine", ".hbs");
app.use(session({
secret: config.sessionSecret,
cookie: {maxAge: 2628000000},
cookie: {maxAge: 2*31*24*60*60*1000},
store: new FileStore({}),
resave: false,
saveUninitialized: false
Expand Down Expand Up @@ -288,15 +304,15 @@ router.post("/login", (req, res) => {
res.redirect(pathname+"gallery");
});

router.get("/upload", auth, (req, res) => {
router.get(["/upload","/webshareupload"], auth, (req, res) => {
res.render("upload", {
config: _.omit(config, ["password", "sessionSecret"]),
pageTemplate: "upload",
pathname
});
});

router.post("/upload", (req, res) => {
router.post(["/upload","/webshareupload"], (req, res) => {
if ( typeof req.body.link === "undefined" && typeof req.body.file === "undefined" && (!req.files || !req.files.file)) return error(req, res, "No file/URL specified.");

if (!req.session || !req.session.authed) {
Expand Down Expand Up @@ -355,13 +371,13 @@ router.post("/upload", (req, res) => {
flushNonces();
name = "l/" + name;

if (req.body.online === "yes") {
if (req.path === "/webshareupload") {
success(req, res, `URL shortened to <a href="${config.url}${name}">"${config.url}${name}"</a>` );
} else {
res.json({
ok: true,
url: `${config.url.replace(/\/?$/, "/")}${name}`,
deleteUrl: config.uploadDeleteLink ? `${config.url.replace(/\/?$/, "/")}delete/${nonce}` : undefined
url: `${config.url}${name}`,
deleteUrl: config.uploadDeleteLink ? `${config.url}delete/${nonce}` : undefined
});
}
});
Expand All @@ -374,13 +390,15 @@ router.post("/upload", (req, res) => {
let nonce = generateNonce(`${config.imagePath}/${name}${ext}`);
flushNonces();

if (req.body.online === "yes") {
if (req.path === "/webshareupload") {
success(req, res, `${config.url}${name}${ext}` );
} else if (req.body.online === "yes") {
res.redirect(`${config.url}${name}${ext}`);
} else {
res.json({
ok: true,
url: `${config.url.replace(/\/?$/, "/")}${name}${ext}`,
deleteUrl: config.uploadDeleteLink ? `${config.url.replace(/\/?$/, "/")}delete/${nonce}` : undefined
url: `${config.url}${name}${ext}`,
deleteUrl: config.uploadDeleteLink ? `${config.url}delete/${nonce}` : undefined
});
}
});
Expand All @@ -397,13 +415,15 @@ router.post("/upload", (req, res) => {
name = "paste/" + name;
}

if (req.body.online === "yes") {
if (req.path === "/webshareupload") {
success(req, res, `${config.url}${name}${ext}` );
} else if (req.body.online === "yes") {
res.redirect(`${config.url}${name}${ext}`);
} else {
res.json({
ok: true,
url: `${config.url.replace(/\/?$/, "/")}${name}${ext}`,
deleteUrl: config.uploadDeleteLink ? `${config.url.replace(/\/?$/, "/")}delete/${nonce}` : undefined
url: `${config.url}${name}${ext}`,
deleteUrl: config.uploadDeleteLink ? `${config.url}delete/${nonce}` : undefined
});
}
});
Expand Down Expand Up @@ -592,6 +612,7 @@ function fileListing(mask, pageTemplate, route, req, res) {
const o = {
name: path.relative(config.imagePath, f),
video: ( ext == ".mp4" || ext == ".webm" ? 1 : undefined), /* undefined is not saved into JSON */
audio: ( ext == ".mp3" || ext == ".wav" || ext == ".flac" ? 1 : undefined), /* undefined is not saved into JSON */
size: stat.size,
mtime: stat.mtime,
mtimeSave: stat.mtime.toString(),
Expand Down Expand Up @@ -619,7 +640,7 @@ function fileListing(mask, pageTemplate, route, req, res) {
});
}

router.get("/gallery/:page?", auth, (req, res) => fileListing("*.<(jpeg|jpg|png|gif|mp4|webm)$>", "gallery", pathname+"gallery", req, res));
router.get("/gallery/:page?", auth, (req, res) => fileListing("*.<(jpeg|jpg|png|gif|mp4|webm|mp3|wav|flac)$>", "gallery", pathname+"gallery", req, res));
router.get("/list/:page?", auth, (req, res) => fileListing("*", "list", pathname+"list", req, res));
router.get("/links/:page?", auth, (req, res) => fileListing("<^[^.]+$>", "links", pathname+"links", req, res));

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "shittydl",
"version": "1.0.0",
"version": "1.0.1",
"description": "",
"main": "index.js",
"scripts": {
Expand Down
Binary file added public/poop96.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
41 changes: 40 additions & 1 deletion public/service-worker.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,42 @@
let version = "0.0.19"

function poke(topic,body) {
self.registration.showNotification(topic, {
body: body,
tag: 'webshareupload',
badge: new URL("poop96.png",self.registration.scope).toString(),
icon: new URL("poop192.png",self.registration.scope).toString(),
silent: true,
});
};

function uploadDone(req) {
return req.then(function(response) {
if (response.ok) {
poke('Upload Completed');
} else {
poke('Upload Failed');
}
return true
})
}

self.addEventListener('notificationclick', function(event) {
event.notification.close();
});

self.addEventListener('message', function(event){
if (event.data == "debug") { poke("Test Notification",version); }
if (event.data == "debug2") { self.registration.showNotification("Test2 Notification", {body: "Hope you are happy now",tag: 'egg',badge: new URL("poop96.png",self.registration.scope).toString(),icon: new URL("poop192.png",self.registration.scope).toString(),vibrate: [500,110,500,110,450,110,200,110,170,40,450,110,200,110,170,40,500]}); }
});

self.addEventListener('fetch', function(event) {
event.respondWith(fetch(event.request));
const url = new URL(event.request.url);
if (event.request.method == 'POST' && url.pathname.endsWith('webshareupload')) {
let req = fetch(event.request);
event.respondWith(req);
poke('Uploading File', 'Please wait while file is uplading');
event.waitUntil(uploadDone(req));
}
return event.respondWith(fetch(event.request));
});
6 changes: 6 additions & 0 deletions views/gallery.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@
<img class="lazy" data-original="{{@root.pathname}}{{@root.config.logo}}">
</a>
</video>
{{else if audio}}
<audio controls preload='metadata' src="{{@root.pathname}}{{name}}">
<a href="{{@root.pathname}}{{name}}" class="image">
<img class="lazy" data-original="{{@root.pathname}}{{@root.config.logo}}">
</a>
</audio>
{{else}}
<a href="{{@root.pathname}}{{name}}" class="image">
<img class="lazy" data-original="{{@root.pathname}}{{name}}">
Expand Down
2 changes: 1 addition & 1 deletion views/layouts/main.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
};
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('{{pathname}}service-worker.js');
navigator.serviceWorker.register('{{pathname}}service-worker.js', {scope: './'});
};
$("img.lazy").lazyload({
Expand Down
17 changes: 16 additions & 1 deletion views/misc.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
</div>
<div class="ui content center aligned">
<div id="install" class="ui positive button disabled" onclick="runInstall()">Instal Shitty as Share Target</div>
<div class="ui primary button" onclick="Notification.requestPermission()">Add Share Target Notifications</div>
</div>
<div id="debug" class="ui content center aligned" style="display: none;">
<div class="ui button" onclick="navigator.serviceWorker.controller.postMessage('debug');">Test</div>
<div class="ui button" onclick="navigator.serviceWorker.controller.postMessage('debug2');">Test2</div>
</div>
<div class="ui content center aligned">
<div class="ui action input">
Expand Down Expand Up @@ -91,7 +96,17 @@
};
$(function() {
let k = '38384040373937396665'
let i = ''
$(document).keyup((e) => {
i+=(""+e.which);
if (i===k) {$("#debug").show();}
if (!k.indexOf(i)) return;
i = ("" + e.which);
})
$("#pas").change((e) => {
if (e.target.value === "debug") {$("#debug").show();}
})
});
</script>
{{/section}}
4 changes: 4 additions & 0 deletions views/partials/filters.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
<div class="ui field input">
<input type="text" placeholder="search" id="filter-search">
</div>
<br/>
<div onclick="$('#filter-search').val('.jpeg,.jpg,.png,.gif')" class="ui mini icon button"><i class="file image outline icon"></i>Image</div>
<div onclick="$('#filter-search').val('.mp3,.wav,.flac')" class="ui mini icon button"><i class="file audio outline icon"></i>Audio</div>
<div onclick="$('#filter-search').val('.mp4,.webm')" class="ui mini icon button"><i class="file video outline icon"></i>Video</div>
<br/><br/>
<button class="ui button" id="filter-clear">Clear</button>
<button class="ui primary button" id="filter-submit">Filter</button>
Expand Down

0 comments on commit c3e9fab

Please sign in to comment.