Skip to content

Commit

Permalink
nour files
Browse files Browse the repository at this point in the history
  • Loading branch information
maxzod committed Apr 3, 2021
2 parents f1c1e58 + ea5b70a commit 05eb959
Show file tree
Hide file tree
Showing 14 changed files with 186 additions and 14 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,7 @@ build/

# Directory created by dartdoc
doc/api/
# TODO :: ignore the `.yaml` file
# TODO :: ignore the `.yaml` file
.yaml
*.mp3
*.mp4
18 changes: 18 additions & 0 deletions example/bin/002_static_file_serving.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import 'dart:io';
import 'package:http_server/http_server.dart';

Future main() async {
var staticFiles = VirtualDirectory('public');
staticFiles.allowDirectoryListing = true;

if (true) {
//! Change to false if you show listing page
staticFiles.directoryHandler = (dir, request) {
var indexUri = Uri.file(dir.path).resolve('index.html');
staticFiles.serveFile(File(indexUri.toFilePath()), request);
};
}

var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 3000);
await server.forEach(staticFiles.serveRequest);
}
12 changes: 9 additions & 3 deletions lib/src/gates.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import 'dart:async';
import 'dart:io' as io;

import 'package:palace/palace.dart';
import 'package:palace/utils/logger.dart';

Future<void> openGates(
PalaceRouter palaceRouter, {
int port = 3000,
}) async {
/// open the server
final server = await io.HttpServer.bind(io.InternetAddress.loopbackIPv4, port);
final server =
await io.HttpServer.bind(io.InternetAddress.loopbackIPv4, port);

/// print the server url
print('Listening on http://localhost:${server.port}');
Expand All @@ -18,7 +20,10 @@ Future<void> openGates(
try {
/// * look for desired endpoint
final endpoint = palaceRouter.match(ioReq.method, ioReq.uri.path) ??
EndPoint(path: ioReq.uri.path, method: ioReq.method, handler: palaceRouter.notFoundHandler);
EndPoint(
path: ioReq.uri.path,
method: ioReq.method,
handler: palaceRouter.notFoundHandler);

/// * create Place req form dart io req and the desired endpoint;
final req = await Request.init(ioReq, endpoint);
Expand All @@ -40,9 +45,10 @@ Future<void> openGates(
await handler(req, res);
if (res.isClosed) break;
}
throw 'Something Critical Happened !';
} catch (e) {
if (allowLogs) {
// TODO :: log this exception
await PalaceLogger.e(e);
}
await Response(ioReq).internalServerError(exception: e);
} finally {
Expand Down
20 changes: 14 additions & 6 deletions lib/src/http/response/file.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,19 @@ import 'package:palace/palace.dart';
import 'package:mime_type/mime_type.dart';

extension ResponseWithFile on Response {
Future<void> file(String name, String path) async {
final _name = Uri.parse(name).toString();
request.response.headers.add('Content-Disposition', 'attachment;filename=$_name');
;
Future<void> file(String path, {String? name}) async {
final file = File(Directory.current.path + '/private' + path);

final file = File(Directory.current.path + '/files' + path);
late String _name;
if (name != null) {
_name = Uri.parse(name).toString();
} else {
var fileName = (file.path.split('/').last);
_name = file.path.replaceAll('/$fileName', '');
}

request.response.headers
.add('Content-Disposition', 'attachment;filename=$_name');
final exists = await file.exists();
if (!exists) {
await notFound();
Expand All @@ -22,7 +29,8 @@ extension ResponseWithFile on Response {

extension SS on HttpResponse {
void setContentTypeFromFile(File file) {
if (headers.contentType == null || headers.contentType!.mimeType == 'text/plain') {
if (headers.contentType == null ||
headers.contentType!.mimeType == 'text/plain') {
headers.contentType = file.contentType;
} else {
headers.contentType == ContentType.binary;
Expand Down
50 changes: 50 additions & 0 deletions lib/utils/logger.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import 'dart:io';

import 'package:path/path.dart';

class PalaceLogger {
static DateTime get dt => DateTime.now();
static Directory get logFolder =>
Directory(Directory.current.path + '\\logs\\');
static String get _fileName =>
join(logFolder.path + '${dt.year}-${dt.month}-${dt.day}.log');

static Future<void> e(Object e) async {
if (await logFolder.exists()) {
await File(_fileName).writeAsString(
'\n ERROR: [${dt.toIso8601String()}] $e',
mode: FileMode.append);
} else {
await Directory(logFolder.path).create();
await File(_fileName).writeAsString(
'\n ERROR: [${dt.toIso8601String()}] $e',
mode: FileMode.append);
}
}

static Future<void> l(Object e) async {
if (await logFolder.exists()) {
await File(_fileName).writeAsString(
'\n LOG: [${dt.toIso8601String()}] $e',
mode: FileMode.append);
} else {
await Directory(logFolder.path).create();
await File(_fileName).writeAsString(
'\n LOG: [${dt.toIso8601String()}] $e',
mode: FileMode.append);
}
}

static Future<void> i(Object e) async {
if (await logFolder.exists()) {
await File(_fileName).writeAsString(
'\n INFO: [${dt.toIso8601String()}] $e',
mode: FileMode.append);
} else {
await Directory(logFolder.path).create();
await File(_fileName).writeAsString(
'\n INFO: [${dt.toIso8601String()}] $e',
mode: FileMode.append);
}
}
}
3 changes: 3 additions & 0 deletions logs/2021-4-3.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

ERROR: [2021-04-03T07:24:19.910156] Something Critical Happened !
ERROR: [2021-04-03T07:24:29.434278] Something Critical Happened !
File renamed without changes.
Binary file added public/archive.zip
Binary file not shown.
Binary file added public/document.pdf
Binary file not shown.
Binary file added public/image.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>hey</p>
</body>
</html>
74 changes: 74 additions & 0 deletions public/markdown.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# **`Part of Queen Palace 🏰👑`**

🚧 Palace Is Under Construction 🚧 👷

🔑 Gates Will Open ASAP

✔️ Stay Safe

👑 Stay inside the kingdom

# take look at bin/main

- to run use dart `bin/main.dart`
- use `lighthouse` for `run` && `watch` for changes
`lh bin/main.dart`
- there is a lot to do you are welcome to help building your `palace`

# example

if you want to test your self clone and run `bin/main.dart`

```dart
Future<void> main(List<String> args) async {
final palace = PalaceRouter();
palace.use(LoggerGuard());
palace.get('/greet_the_queen', (req, res) async {
return res.json({'data': 'Long Live The Queen'});
});
/// start the `server`
await openGates(palace);
}
```

## Core Parts

## `Request`

wrapper class around dart `HttpRequest`
mostly will be getters to ease extracting values form the `HttpRequest`

## `Response`

wrapper class around dart `HttpResponse`
will have functions ease the process of responding to the incoming requests

## `PalaceGuard`

abstract class with one function to execute before giving the http request for the handler witch meas if you responds to the request form any guards the requests will not reach the next guards or even the endpoint handler it self
**if you response to the request you will be ending the request life cycle**

- in case of ending

## `PalaceRouter`

to help you set routes and the handler for each route

## `palace`

the palace file contains only one function `openGates(PalaceRouter,{port})` which takes palace router and will start server
wait for incoming requests
transforming them to Request object
find the right endpoint if not found will respond with 404
if exist will loop throw the guards and the endpoint handler then close the IO request

## TODO

- [x] configuration reader
example
`final port = config('port');`
- []
2 changes: 1 addition & 1 deletion pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ packages:
source: hosted
version: "0.0.2"
path:
dependency: transitive
dependency: "direct main"
description:
name: path
url: "https://pub.dartlang.org"
Expand Down
4 changes: 1 addition & 3 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,14 @@ environment:
sdk: ">=2.12.0 <3.0.0"

dependencies:
# annotations
http_server: ^1.0.0
meta: ^1.3.0
# to validate route matching
path_to_regexp: ^0.4.0
yaml: ^3.1.0
# classes to ease access to http-server utils
http_server: ^1.0.0
mime_type: ^1.0.0
palace_validators: ^0.0.2

dev_dependencies:
# linting
pedantic: 1.11.0

0 comments on commit 05eb959

Please sign in to comment.