4 Commits

9 changed files with 153 additions and 55 deletions

View File

@@ -1,44 +1,86 @@
# Web File Storage # Cista Web Storage
The Python package installs a `cista` executable. Use `hatch shell` to initiate and install in a virtual environment, or `pip install` it on your system. Alternatively `hatch run cista` may be used to skip the shell step but stay virtual. `pip install hatch` first if needed. <img src="https://git.zi.fi/Vasanko/cista-storage/raw/branch/main/docs/cista.jpg" align=right width=250>
Create your user account: Cista takes its name from the ancient cistae, metal containers used by Greeks and Egyptians to safeguard valuable items. This modern application provides a browser interface for secure and accessible file storage, echoing the trust and reliability of its historical namesake.
```sh This is a cutting-edge **file and document server** designed for speed, efficiency, and unparalleled ease of use. Experience **lightning-fast browsing**, thanks to the file list maintained directly in your browser and updated from server filesystem events, coupled with our highly optimized code. Fully **keyboard-navigable** and with a responsive layout, Cista flawlessly adapts to your devices, providing a seamless experience wherever you are. Our powerful **instant search** means you're always just a few keystrokes away from finding exactly what you need. Press **1/2/3** to switch ordering, navigate with all four arrow keys (+Shift to select). Or click your way around on **breadcrumbs that remember where you were**.
cista --user admin --privileged
The Cista project started as an inevitable remake of [Droppy](https://github.com/droppyjs/droppy) which we used and loved despite its numerous bugs. Cista Storage stands out in handling even the most exotic filenames, ensuring a smooth experience where others falter.
All of this is wrapped in an intuitive interface with automatic light and dark themes, making Cista Storage the ideal choice for anyone seeking a reliable, versatile, and quick file storage solution. Quickly setup your own Cista where your files are just a click away, safe, and always accessible.
Experience Cista by visiting [Cista Demo](https://drop.zi.fi) for a test run and perhaps upload something...
## Getting Started
### Installation
To install the cista application, use:
```fish
pip install cista
``` ```
## Running the server Note: Some Linux distributions might need `--break-system-packages` to install Python packages, which are safely installed in the user's home folder. As an alternative to avoid installation, run it with command `pipx run cista`
Serve your files on localhost:8000: ### Running the Server
```sh Create an account: (or run a public server without authentication)
```fish
cista --user yourname --privileged
```
Serve your files at http://localhost:8000:
```fish
cista -l :8000 /path/to/files cista -l :8000 /path/to/files
``` ```
The Git repository does not contain a frontend build, so you should first do that... The server remembers its settings in the config folder (default `~/.local/share/cista/`), including the listen port and directory, for future runs without arguments.
## Build frontend ### Internet Access
Frontend needs to be built before using and after any frontend changes: To use your own TLS certificates, place them in the config folder and run:
```sh ```fish
cd frontend cista -l cista.example.com
npm install
npm run build
``` ```
This will place the front in `cista/wwwroot` from where the backend server delivers it, and that also gets included in the Python package built via `hatch build`. Most admins instead find the [Caddy](https://caddyserver.com/) web server convenient for its auto TLS certificates and all. A proxy also allows running multiple web services or Cista instances on the same IP address. Caddy configuration **/etc/caddy/Caddyfile** is dead simple:
```Caddyfile
cista.example.com {
reverse_proxy :8000
}
```
## Development setup ## Development setup
For rapid turnaround during development, you should run `npm run dev` Vite development server on the Vue frontend. While that is running, start the backend on another terminal `hatch run cista --dev -l :8000` and connect to the frontend. For rapid development, we use the Vite development server for the Vue frontend, while running the backend on port 8000 that Vite proxies backend requests to. Each server live reloads whenever its code or configuration are modified.
The backend and the frontend will each reload automatically at any code or config changes. ```fish
cd frontend
npm install
npm run dev
```
## System deployment Concurrently, start the backend on another terminal:
Clone the repository to `/srv/cista/cista-storage` or other suitable location accessible to the storage user account you plan to use. `sudo -u storage -s` and build the frontend if you hadn't already. ```fish
hatch shell
pip install -e '.[dev]'
cista --dev -l :8000 /path/to/files
```
We use `hatch shell` for installing on a virtual environment, to not disturb the rest of the system with our hacking.
Vue is used to build files in `cista/wwwroot`, included prebuilt in the Python package. Running `hatch build` builds the frontend and creates a NodeJS-independent Python package.
## System Deployment
This setup allows easy addition of storages, each with its own domain, configuration, and files.
Assuming a restricted user account **storage** for serving files and that cista is installed system-wide or on this account (check with `sudo -u storage -s`). Alternatively, use `pipx run cista` or `hatch run cista` as the ExecStart command.
Create **/etc/systemd/system/cista@.service**: Create **/etc/systemd/system/cista@.service**:
@@ -48,24 +90,22 @@ Description=Cista storage %i
[Service] [Service]
User=storage User=storage
WorkingDirectory=/srv/cista/cista-storage ExecStart=cista -c /srv/cista/%i -l /srv/cista/%i/socket /media/storage/@%i/
ExecStart=hatch run cista -c /srv/cista/%i -l /srv/cista/%i/socket /media/storage/@%i/
TimeoutStopSec=2
Restart=always Restart=always
[Install] [Install]
WantedBy=multi-user.target WantedBy=multi-user.target
``` ```
This assumes you may want to run multiple separate storages, each having their files under `/media/storage/<domain>` and configuration under `/srv/cista/<domain>/`. Instead of numeric ports, we use UNIX sockets for convenience. This setup supports multiple storages, each under `/media/storage/<domain>` for files and `/srv/cista/<domain>/` for configuration. UNIX sockets are used instead of numeric ports for convenience.
```sh ```fish
systemctl daemon-reload systemctl daemon-reload
systemctl enable --now cista@foo.example.com systemctl enable --now cista@foo.example.com
systemctl enable --now cista@bar.example.com systemctl enable --now cista@bar.example.com
``` ```
Exposing this publicly online is the most convenient using the [Caddy](https://caddyserver.com/) web server but you can of course use Nginx or others as well. Or even run the server with `-l domain.example.com` given TLS certificates in the config folder. Public exposure is easiest using the Caddy web server, but Nginx or others also work. Run the server with -l domain.example.com if you have TLS certificates in the config folder.
**/etc/caddy/Caddyfile**: **/etc/caddy/Caddyfile**:
@@ -74,5 +114,3 @@ foo.example.com, bar.example.com {
reverse_proxy unix//srv/cista/{host}/socket reverse_proxy unix//srv/cista/{host}/socket
} }
``` ```
Using the `{host}` placeholder we can just put all the domains on the same block. That's the full server configuration you need. `systemctl enable --now caddy` or `systemctl restart caddy` for the config to take effect.

View File

@@ -62,12 +62,15 @@ def _main():
_confdir(args) _confdir(args)
exists = config.conffile.exists() exists = config.conffile.exists()
import_droppy = args["--import-droppy"] import_droppy = args["--import-droppy"]
necessary_opts = exists or import_droppy or path and listen necessary_opts = exists or import_droppy or path
if not necessary_opts: if not necessary_opts:
# Maybe run without arguments # Maybe run without arguments
print(doc) print(doc)
print( print(
"No config file found! Get started with:\n cista -l :8000 /path/to/files, or\n cista -l example.com --import-droppy # Uses Droppy files\n", "No config file found! Get started with one of:\n"
" cista --user yourname --privileged\n"
" cista --import-droppy\n"
" cista -l :8000 /path/to/files\n"
) )
return 1 return 1
settings = {} settings = {}
@@ -79,8 +82,15 @@ def _main():
settings = droppy.readconf() settings = droppy.readconf()
if path: if path:
settings["path"] = path settings["path"] = path
elif not exists:
settings["path"] = Path.home() / "Downloads"
if listen: if listen:
settings["listen"] = listen settings["listen"] = listen
elif not exists:
settings["listen"] = ":8000"
if not exists and not import_droppy:
# We have no users, so make it public
settings["public"] = True
operation = config.update_config(settings) operation = config.update_config(settings)
print(f"Config {operation}: {config.conffile}") print(f"Config {operation}: {config.conffile}")
# Prepare to serve # Prepare to serve
@@ -112,11 +122,23 @@ def _confdir(args):
def _user(args): def _user(args):
_confdir(args) _confdir(args)
config.load_config() if config.conffile.exists():
config.load_config()
operation = False
else:
# Defaults for new config when user is created
operation = config.update_config(
{
"listen": ":8000",
"path": Path.home() / "Downloads",
"public": False,
}
)
print(f"Config {operation}: {config.conffile}\n")
name = args["--user"] name = args["--user"]
if not name or not name.isidentifier(): if not name or not name.isidentifier():
raise ValueError("Invalid username") raise ValueError("Invalid username")
config.load_config()
u = config.config.users.get(name) u = config.config.users.get(name)
info = f"User {name}" if u else f"New user {name}" info = f"User {name}" if u else f"New user {name}"
changes = {} changes = {}
@@ -128,12 +150,17 @@ def _user(args):
info += " (admin)" if oldadmin else "" info += " (admin)" if oldadmin else ""
if args["--password"] or not u: if args["--password"] or not u:
changes["password"] = pw = pwgen.generate() changes["password"] = pw = pwgen.generate()
info += f"\n Password: {pw}" info += f"\n Password: {pw}\n"
res = config.update_user(args["--user"], changes) res = config.update_user(name, changes)
print(info) print(info)
if res == "read": if res == "read":
print(" No changes") print(" No changes")
if operation == "created":
print(
"Now you can run the server:\n cista # defaults set: -l :8000 ~/Downloads\n"
)
if __name__ == "__main__": if __name__ == "__main__":
sys.exit(main()) sys.exit(main())

View File

@@ -11,7 +11,7 @@ import brotli
import sanic.helpers import sanic.helpers
from blake3 import blake3 from blake3 import blake3
from sanic import Blueprint, Sanic, empty, raw from sanic import Blueprint, Sanic, empty, raw
from sanic.exceptions import Forbidden, NotFound, ServerError from sanic.exceptions import Forbidden, NotFound
from sanic.log import logging from sanic.log import logging
from stream_zip import ZIP_AUTO, stream_zip from stream_zip import ZIP_AUTO, stream_zip
@@ -120,10 +120,19 @@ def _load_wwwroot(www):
br = False br = False
wwwnew[name] = data, br, headers wwwnew[name] = data, br, headers
if not wwwnew: if not wwwnew:
raise ServerError( msg = f"Web frontend missing from {base}\n Did you forget: hatch build\n"
"Web frontend missing. Did you forget npm run build?", if not www:
extra={"wwwroot": str(base)}, logging.warning(msg)
quiet=True, if not app.debug:
msg = "Web frontend missing. Cista installation is broken.\n"
wwwnew[""] = (
msg.encode(),
False,
{
"etag": "error",
"content-type": "text/plain",
"cache-control": "no-store",
},
) )
return wwwnew return wwwnew

View File

@@ -138,7 +138,7 @@ def update_user(conf: Config, name: str, changes: dict) -> Config:
# Encode into dict, update values with new, convert to Config # Encode into dict, update values with new, convert to Config
try: try:
u = conf.users[name].__copy__() u = conf.users[name].__copy__()
except KeyError: except (KeyError, AttributeError):
u = User() u = User()
if "password" in changes: if "password" in changes:
from . import auth from . import auth
@@ -147,7 +147,7 @@ def update_user(conf: Config, name: str, changes: dict) -> Config:
del changes["password"] del changes["password"]
udict = msgspec.to_builtins(u, enc_hook=enc_hook) udict = msgspec.to_builtins(u, enc_hook=enc_hook)
udict.update(changes) udict.update(changes)
settings = msgspec.to_builtins(conf, enc_hook=enc_hook) settings = msgspec.to_builtins(conf, enc_hook=enc_hook) if conf else {"users": {}}
settings["users"][name] = msgspec.convert(udict, User, dec_hook=dec_hook) settings["users"][name] = msgspec.convert(udict, User, dec_hook=dec_hook)
return msgspec.convert(settings, Config, dec_hook=dec_hook) return msgspec.convert(settings, Config, dec_hook=dec_hook)

BIN
docs/cista.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

View File

@@ -4,7 +4,7 @@
<HeaderMain ref="headerMain" :path="path.pathList" :query="path.query"> <HeaderMain ref="headerMain" :path="path.pathList" :query="path.query">
<HeaderSelected :path="path.pathList" /> <HeaderSelected :path="path.pathList" />
</HeaderMain> </HeaderMain>
<BreadCrumb :path="path.pathList" tabindex="-1"/> <BreadCrumb :path="path.pathList" primary />
</header> </header>
<main> <main>
<RouterView :path="path.pathList" :query="path.query" /> <RouterView :path="path.pathList" :query="path.query" />
@@ -51,6 +51,7 @@ const globalShortcutHandler = (event: KeyboardEvent) => {
const fileExplorer = store.fileExplorer as any const fileExplorer = store.fileExplorer as any
if (!fileExplorer) return if (!fileExplorer) return
const c = fileExplorer.isCursor() const c = fileExplorer.isCursor()
const input = (event.target as HTMLElement).tagName === 'INPUT'
const keyup = event.type === 'keyup' const keyup = event.type === 'keyup'
if (event.repeat) { if (event.repeat) {
if ( if (
@@ -70,13 +71,21 @@ const globalShortcutHandler = (event: KeyboardEvent) => {
else if (!keyup && event.key === 'f' && (event.ctrlKey || event.metaKey)) { else if (!keyup && event.key === 'f' && (event.ctrlKey || event.metaKey)) {
headerMain.value!.toggleSearchInput() headerMain.value!.toggleSearchInput()
} }
// Search also on / (UNIX style)
else if (keyup && !input && event.key === '/') {
headerMain.value!.toggleSearchInput()
}
// Globally close search on Escape
else if (keyup && event.key === 'Escape') {
headerMain.value!.closeSearch(event)
}
// Select all (toggle); keydown to prevent builtin // Select all (toggle); keydown to prevent builtin
else if (!keyup && event.key === 'a' && (event.ctrlKey || event.metaKey)) { else if (!keyup && event.key === 'a' && (event.ctrlKey || event.metaKey)) {
fileExplorer.toggleSelectAll() fileExplorer.toggleSelectAll()
} }
// Keys 1-3 to sort columns // Keys 1-3 to sort columns
else if ( else if (
c && !input &&
keyup && keyup &&
(event.key === '1' || event.key === '2' || event.key === '3') (event.key === '1' || event.key === '2' || event.key === '3')
) { ) {

View File

@@ -5,6 +5,8 @@
@keyup.left.stop="move(-1)" @keyup.left.stop="move(-1)"
@keyup.right.stop="move(1)" @keyup.right.stop="move(1)"
@keyup.enter="move(0)" @keyup.enter="move(0)"
@focus=focusCurrent
tabindex=0
> >
<a href="#/" <a href="#/"
:ref="el => setLinkRef(0, el)" :ref="el => setLinkRef(0, el)"
@@ -26,7 +28,7 @@
<script setup lang="ts"> <script setup lang="ts">
import home from '@/assets/svg/home.svg' import home from '@/assets/svg/home.svg'
import { onBeforeUpdate, ref, watchEffect } from 'vue' import { nextTick, onBeforeUpdate, ref, watchEffect } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
const router = useRouter() const router = useRouter()
@@ -37,22 +39,33 @@ onBeforeUpdate(() => { links.length = 1 }) // 1 to keep home
const props = defineProps<{ const props = defineProps<{
path: Array<string> path: Array<string>
primary?: boolean
}>() }>()
const longest = ref<Array<string>>([]) const longest = ref<Array<string>>([])
const isCurrent = (index: number) => index == props.path.length ? 'location' : undefined const isCurrent = (index: number) => index == props.path.length ? 'location' : undefined
const focusCurrent = () => {
nextTick(() => {
const index = props.path.length
if (index < links.length) links[index].focus()
})
}
const navigate = (index: number) => { const navigate = (index: number) => {
const link = links[index] const link = links[index]
if (!link) throw Error(`No link at index ${index} (path: ${props.path})`) if (!link) throw Error(`No link at index ${index} (path: ${props.path})`)
const url = `/${longest.value.slice(0, index).join('/')}/` const url = index ? `/${longest.value.slice(0, index).join('/')}/` : '/'
const here = `/${longest.value.join('/')}/` const long = longest.value.length ? `/${longest.value.join('/')}/` : '/'
const current = decodeURIComponent(location.hash.slice(1).split('//')[0]) const browser = decodeURIComponent(location.hash.slice(1).split('//')[0])
const u = url.replaceAll('?', '%3F').replaceAll('#', '%23') const u = url.replaceAll('?', '%3F').replaceAll('#', '%23')
if (here.startsWith(current)) router.replace(u) // Clicking on current link clears the rest of the path and adds new history
if (isCurrent(index)) { longest.value.splice(index); router.push(u) }
// Moving along breadcrumbs doesn't create new history
else if (long.startsWith(browser)) router.replace(u)
// Nornal navigation from elsewhere (e.g. search result breadcrumbs)
else router.push(u) else router.push(u)
link.focus()
} }
const move = (dir: number) => { const move = (dir: number) => {
@@ -64,13 +77,16 @@ const move = (dir: number) => {
watchEffect(() => { watchEffect(() => {
const longcut = longest.value.slice(0, props.path.length) const longcut = longest.value.slice(0, props.path.length)
const same = longcut.every((value, index) => value === props.path[index]) const same = longcut.every((value, index) => value === props.path[index])
// Navigated out of previous path, reset longest to current
if (!same) longest.value = props.path if (!same) longest.value = props.path
else if (props.path.length > longcut.length) { else if (props.path.length > longcut.length) {
longest.value = longcut.concat(props.path.slice(longcut.length)) longest.value = longcut.concat(props.path.slice(longcut.length))
} }
}) // If needed, focus primary navigation to new location
watchEffect(() => { if (props.primary) nextTick(() => {
if (links.length) navigate(props.path.length) const act = document.activeElement as HTMLElement
if (!act || [...links, document.body].includes(act)) focusCurrent()
})
}) })
</script> </script>

View File

@@ -58,13 +58,13 @@
@keyup.right.stop="ev => { if (doc.dir) (ev.target as HTMLElement).click() }" @keyup.right.stop="ev => { if (doc.dir) (ev.target as HTMLElement).click() }"
>{{ doc.name }}</a >{{ doc.name }}</a
> >
<button v-if="cursor == doc" class="rename-button" @click="() => (editing = doc)">🖊</button> <button tabindex=-1 v-if="cursor == doc" class="rename-button" @click="() => (editing = doc)">🖊</button>
</template> </template>
</td> </td>
<FileModified :doc=doc :key=nowkey /> <FileModified :doc=doc :key=nowkey />
<FileSize :doc=doc /> <FileSize :doc=doc />
<td class="menu"> <td class="menu">
<button tabindex="-1" @click.stop="contextMenu($event, doc)"></button> <button tabindex=-1 @click.stop="contextMenu($event, doc)"></button>
</td> </td>
</tr> </tr>
</template> </template>

View File

@@ -21,7 +21,6 @@
@input="updateSearch" @input="updateSearch"
placeholder="Search words" placeholder="Search words"
class="margin-input" class="margin-input"
@keyup.escape="closeSearch"
/> />
</template> </template>
<SvgButton ref="searchButton" name="find" @click.prevent="toggleSearchInput" /> <SvgButton ref="searchButton" name="find" @click.prevent="toggleSearchInput" />