diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..620039c9e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +venv +docker +data +__pycahce__ +log diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index db8c40a50..d596801ed 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1 +1,3 @@ -custom: https://zeronet.io/docs/help_zeronet/donate/ +liberapay: caryoscelus +ko_fi: caryoscelus +custom: https://caryoscelus.github.io/donate/ diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index fe7c81781..667936496 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -2,19 +2,9 @@ name: Feature request about: Suggest an idea for ZeroNet title: '' -labels: '' +labels: 'enhancement' assignees: '' --- -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. +*we have to rigid structure for feature requests right now, but please try to include important details on the matter* diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 000000000..f467e83d6 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,66 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + workflow_dispatch: + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'javascript', 'python' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Learn more about CodeQL language support at https://git.io/codeql-language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + # - name: Autobuild + # uses: github/codeql-action/autobuild@v2 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl + + # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language + + - run: | + python3 -m venv venv + source venv/bin/activate + pip install -r requirements.txt + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9c6f6f3b2..67e067feb 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,6 +1,7 @@ name: tests -on: [push, pull_request] +on: + workflow_dispatch: jobs: test: @@ -9,7 +10,7 @@ jobs: strategy: max-parallel: 16 matrix: - python-version: [3.5, 3.6, 3.7, 3.8, 3.9] + python-version: [3.6, 3.7, 3.8, 3.9, 3.10] steps: - uses: actions/checkout@v2 diff --git a/.gitignore b/.gitignore index 38dd3a34a..0d03e87fc 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ __pycache__/ # Hidden files .* +!.dockerignore !/.github !/.gitignore !/.travis.yml @@ -14,13 +15,16 @@ __pycache__/ # Temporary files *.bak +*~ # Data dir data/* +docker/data/ *.db # Virtualenv env/* +venv/* # Tor data tools/tor/data @@ -33,3 +37,11 @@ zeronet.conf # ZeroNet log files log/* + +# Enabled plugins that disabled by default +plugins/Bootstrapper +plugins/DonationMessage +plugins/Multiuser +plugins/NoNewSites +plugins/StemPort +plugins/UiPassword diff --git a/.travis.yml b/.travis.yml index bdaafa22d..75ffb9efc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,7 @@ language: python python: - - 3.4 - - 3.5 - - 3.6 - - 3.7 - - 3.8 + - 3.9 + - 3.10 services: - docker cache: pip @@ -40,8 +37,3 @@ after_failure: after_success: - codecov - coveralls --rcfile=src/Test/coverage.ini -notifications: - email: - recipients: - hello@zeronet.io - on_success: change diff --git a/CHANGELOG.md b/CHANGELOG.md index b49b9ef6d..172f5f7b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,204 @@ -### ZeroNet 0.7.2 (2020-09-?) Rev4206? - - +### zeronet-conservancy 0.7.10+ +- disable site-plugins installed for security reasons (@caryoscelus) +- fix downloading geoip db (@caryoscelus) +- python <3.6 is officially unsupported +- SafeRe improvements by @geekless +- remove and don't update muted files (@caryoscelus) +- option to disable port checking (@caryoscelus) +- new install startup improvements (@caryoscelus) +- fix blank site with UiPassword under certain conditions (reported & sponsored by @bitcoren) (@caryoscelus) +- fix chromium compatibility (@caryoscelus) +- better fix of local sites leak (@caryoscelus) +- ipython-based repl via --repl for debug/interactive development (@caryoscelus) +- various improvements + +### zeronet-conservancy 0.7.10 (2023-07-26) (18d35d3bed4f0683e99) +prepared by @caryoscelus +- update merkletools dependency to avoid legacy pysha3 (@caryoscelus) +- fix ReDoS in file editor (UiFileManager plugin) due to outdated codemirror (@caryoscelus) +- more anonymous UPnP (thanks to 0netdwf for reporting) +- remove old zeroname plugins (.bit deprecation) +- sitePublish --recursive option +- windows build instruction improvement +- importBundle command line action +- use Syncronite tracker site by default +- fix leak of local 0net sites to clearnet sites (originally reported by @egosown/beardog) +- various improvements + +### zeronet-conservancy 0.7.9 (2023-07-02) (f966a4203fe33bd9f35) +maintainers: @caryoscelus -> none +- update README (build/dev instructions; thanks to @fgaz) +- better debugging of update non-propagation +- sec update of msgpck dependency (@chncaption) +- deprecate python-3.6 as it apparently is no longer used (by active users) +- improvement in imports and naming (@caryoscelus) +- siteSign accepts absolute paths as well as paths relative to working directory (@caryoscelus) +- updated trackers from Syncronite by @Styromaniac +- no longer officially maintained + +### zeronet-conservancy 0.7.8.1 (2022-11-28) (0054eca9df0c9c8c2f4a78) +maintainers: @caryoscelus +- fix favourite/unfavourite in sidebar +- fix tracker connection regression introduced in dc804b9d5f3a2a9f1fffa1b97d82e0e04c44508b (thanks to @bitcoren) +- GiveUpGitHub notice +- update README +- new, more compact boot logo in console (more suitable for small screens) + +### zeronet-conservancy 0.7.8 (2022-11-23) (110307a4198cb13cc907ae) +maintainers: @caryoscelus +- use archived version of .bit domain registry to avoid malicious rewrites +- readdress .bit domains as part of their deprecation +- remove potential vulnerability via setuptools (@ajesse11x) +- improve copying peers from sidebar +- reduce fingerprinting information available to unprivileged sites +- improve starting script +- fix default ssl version to be secure +- disable geoip-related ip address leak when in tor-only mode +- windows os build/running instruction (WIP) +- better command line parsing +- ArchLinux AUR package +- update android instruction (thanks oseido for reporting) +- better browser launch handling +- ability to add/remove from favourites from sidebar +- NoNewSites plugin +- show help message even when startup fails +- fix plugin options handling regression +- multiple code improvements + +### zeronet-conservancy 0.7.7 (2022-07-27) (f40dbfeb2163b9902495ba) +maintainers: @caryoscelus, @FraYoshi, @prtngn, @d47081 (ex @d4708) +- return UPnP using secure xml library (@caryoscelus) +- xmr donations in sidebar fixed (@caryoscelus) +- add libffi-dev dependency (@d47081) +- add more deb dependencies (@BlueRook) +- add pyaes as external dependency (@caryoscelus) +- remove built-in pyaes (thanks to @emdee-net) +- fix error messages in sidebar (@caryoscelus) +- reduce fingerprinting of site owner (@caryoscelus) +- minor code improvements and reduce fingerprinting from zeronet-enhanced (by @geekless, adopted by @caryoscelus) +- improve and speed up content.json loading (@caryoscelus) +- show `--help` even if data directory is inaccessible (@caryoscelus) +- ask for optional user mute reason (@caryoscelus) +- multiple code improvements + +### zeronet-conservancy 0.7.6 (2022-06-10) (864b7feb797d12077) +maintainers: @caryoscelus, @d4708, @FraYoshi, @prtngn +- more trackers from Syncronite by default +- introduce multiple donations methods (@caryoscelus) +- easier termux startup script (@unmanbearpig) +- Brazilian Portuguese readme translation (@iFallenHunt) +- reduce fingerprinting information (@caryoscelus) +- only enable site donations when activated (@caryoscelus) +- new docker files (@prtngn) +- updated Russian readme (@Programmator9000) +- multiple improvements in sidebar button UX and icons (@d4708) +- fuller debug messages (@caryoscelus) +- new contributions are GPLv3+ + +### zeronet-conservancy 0.7.5 (2022-05-17) (fca3c8544debd533) +maintainers: @caryoscelus , @d4708 +- disable UPnP until it's proven robust +- new icon & minor rebranding +- don't check port in tor-only mode +- documentation updates & fixes (by @caryoscelus and @d4708) +- update Android/Termux dependency list (thx to nnmnmknmki reports) +- fix compatibility with modern hashlib (affects Android/Termux & others) +- cleanup +- more active trackers +- replace old start script with a better one +- colourful greetings + +### zeronet-conservancy 0.7.4 (2022-04-25) (733b1b05b1) +maintainers: @caryoscelus +- fix UiRequest.parsePath & minor code improvements +- Sidebar "Open site directory" feature (by @defder-su) +- fix multiuser/merger plugin interaction +- use new admin page +- update dependency instructions + +### zeronet-conservancy 0.7.3.2 (2022-01-26) (1a73dd7) +maintainers: @caryoscelus +(quick fix: technical release with proper versioning info) + +### zeronet-conservancy 0.7.3.1 (2022-01-26) (a57ebf8) +maintainers: @caryoscelus +- don't grant ADMIN permission to home or update pages +- allow granting ADMIN permission via `--admin_pages` command line option +- fix infinite readdress bug (thx @mahdi-ln for reporting) + +### zeronet-conservancy 0.7.3 (2022-01-21) Rev5000 +maintainers: @caryoscelus +- forked from the latest py3 branch of ZeroNet +- fixed potential vulnerability discovered by @purplesyringa +- onion v3 support (thanks to @anonymoose, @zeroseed and @geekless) +- partial readme rewrite (thanks to @mitya57) +- disable updating through zite (unsafe) +- polish translation update (by Krzysztof Otręba) +- improved install instructions + +### ZeroNet 0.7.2+ (latest official py3 branch) +maintainers: shortcutme a.k.a nofish a.k.a HelloZeroNet a.k.a Tamas Kocsis +- Update requirements.txt (#2617) (Jabba) +- Fix Cors permission request for connecting site +- Allow sites to request several CORS permissions at once (#2631) (Ivanq) +- Display library versions at /Env url endpoint +- Fix OpenSSL dll/so location find patcher +- Fix site listing show on big site visit +- Fix 404 error handler in UiFilePlugin (Ivanq) +- other fixes, improvements and translation updates (see more in git log) + +### ZeroNet 0.7.2 2020-09-21 (Rev4528) +maintainers: shortcutme a.k.a nofish a.k.a HelloZeroNet a.k.a Tamas Kocsis +- Save content.json of site even if limit size is reached (#2114) (Lola Dam) +- fix #2107; Still save the content.json received even if site size limit is reached but dont download files (Lola Dam) +- Add multiuser admin status to server info +- Restrict blocked site addition when using mergerSiteAdd +- Open console with #ZeroNet:Console hash in url +- Fix compacting large json files +- Fix utf8 post data parsing +- Remove UiRequestPlugin from Zeroname plugin +- Fix shutdown errors on macOS +- Fix OpenSSL cert generation using LibreSSL +- Allow NOSANDBOX in local mode (#2238) (Filip Š) +- Remove limitations for img, font, media, style src in raw mode +- Use master seed to create new site from cli +- No restart after update (#2242) (Lola Dam) +- Upgrade to Python 3.8 (Christian Clauss) +- Allow all valid filenames to be added to content.json (#2141) (Josh) +- Fix loading screen scrolling on smaller screens +- Fix file rendering if content.json download failed +- Replace usage of deprecated API 'cgi.parse_qsl' (Natalia Fenclová) +- Handle announcer thread killing properly +- Move file writes and reads to separate thread +- Allow images from data uris +- Prefer connecting to non-onion peers +- Make sure we use local peers if possible +- Faster, async local ip discovery +- improve db access locks +- Fix memory leak when using sleep in threads +- more thread safety +- Validate json files in src and plugins dir +- Don't add escaping iframe message for link without target=_top +- Fix updateing deleted site in contentdb +- Don't allow parallel sites.json loading +- Fix incomplete loading of dbschema.json +- Added Custom Openssl Path for Native Clients and start_dir config (canewsin) +- Fixed "LookupError: 'hex' is not a text encoding" on /StatsBootstrapper page (#2442) (krzotr) +- Switch from gevent-websocket to gevent-ws (#2439) (Ivanq) +- Make ThreadPool a context manager to prevent memory leaks (Ivanq) +- Fix sslcrypto thread safety (#2454) +- Search for any OpenSSL version in LD_LIBRARY_PATH (Ivanq) +- Change to GPLv3 license +- Allow opening the sidebar while content.json is not loaded (Vadim Ushakov) +- UiPassword fixes +- Fix loading invalid site block list +- Fix wrapper_nonce adding to url +- Try to recover site privatekey from master seed when site owned switch enabled +- Fix not downloaded site delete on startup +- bad file download fixes +- UiFileManager plugin +- translation updates +- many other fixes and improvements (see git log for details) ### ZeroNet 0.7.1 (2019-07-01) Rev4206 ### Added @@ -20,7 +218,7 @@ - Link to site's sidebar with "#ZeroNet:OpenSidebar" hash ### Changed - - Allow .. in file names [Thanks to imachug] + - Allow .. in file names [Thanks to purplesyringa] - Change unstable trackers - More clean errors on sites.json/users.json load error - Various tweaks for tracker rating on unstable connections @@ -31,12 +229,12 @@ ### Fixed - Fix parsing config lines that have no value - - Fix start.py [Thanks to imachug] + - Fix start.py [Thanks to purplesyringa] - Allow multiple values of the same key in the config file [Thanks ssdifnskdjfnsdjk for reporting] - Fix parsing config file lines that has % in the value [Thanks slrslr for reporting] - Fix bootstrapper plugin hash reloads [Thanks geekless for reporting] - Fix CryptMessage plugin OpenSSL dll loading on Windows (ZeroMail errors) [Thanks cxgreat2014 for reporting] - - Fix startup error when using OpenSSL 1.1 [Thanks to imachug] + - Fix startup error when using OpenSSL 1.1 [Thanks to purplesyringa] - Fix a bug that did not loaded merged site data for 5 sec after the merged site got added - Fix typo that allowed to add new plugins in public proxy mode. [Thanks styromaniac for reporting] - Fix loading non-big files with "|all" postfix [Thanks to krzotr] @@ -59,10 +257,10 @@ Note: The fix is also back ported to ZeroNet Py 2.x version (Rev3870) - Generated SSL certificate randomization to avoid protocol filters (Thanks to ValdikSS) - Offline mode - P2P source code update using ZeroNet protocol - - ecdsaSign/Verify commands to CryptMessage plugin (Thanks to imachug) + - ecdsaSign/Verify commands to CryptMessage plugin (Thanks to purplesyringa) - Efficient file rename: change file names instead of re-downloading the file. - Make redirect optional on site cloning (Thanks to Lola) - - EccPrivToPub / EccPubToPriv functions (Thanks to imachug) + - EccPrivToPub / EccPubToPriv functions (Thanks to purplesyringa) - Detect and change dark/light theme based on OS setting (Thanks to filips123) ### Changed @@ -81,7 +279,7 @@ Note: The fix is also back ported to ZeroNet Py 2.x version (Rev3870) - Fix site download as zip file - Fix displaying sites with utf8 title - Error message if dbRebuild fails (Thanks to Lola) - - Fix browser reopen if executing start.py again. (Thanks to imachug) + - Fix browser reopen if executing start.py again. (Thanks to purplesyringa) ### ZeroNet 0.6.5 (2019-02-16) Rev3851 (Last release targeting Python 2.7.x) @@ -170,7 +368,7 @@ Affected versions: All versions before ZeroNet Rev3616 - Detect network level tracker blocking and easy setting meek proxy for tracker connections. - Support downloading 2GB+ sites as .zip (Thx to Radtoo) - Support ZeroNet as a transparent proxy (Thx to JeremyRand) - - Allow fileQuery as CORS command (Thx to imachug) + - Allow fileQuery as CORS command (Thx to purplesyringa) - Windows distribution includes Tor and meek client by default - Download sites as zip link to sidebar - File server port randomization @@ -233,7 +431,7 @@ Affected versions: All versions before ZeroNet Rev3616 ### Added - New plugin: Chart - Collect and display charts about your contribution to ZeroNet network - - Allow list as argument replacement in sql queries. (Thanks to imachug) + - Allow list as argument replacement in sql queries. (Thanks to purplesyringa) - Newsfeed query time statistics (Click on "From XX sites in X.Xs on ZeroHello) - New UiWebsocket API command: As to run commands as other site - Ranged ajax queries for big files @@ -254,7 +452,7 @@ Affected versions: All versions before ZeroNet Rev3616 - Only zoom sidebar globe if mouse button is pressed down ### Fixed - - Open port checking error reporting (Thanks to imachug) + - Open port checking error reporting (Thanks to purplesyringa) - Out-of-range big file requests - Don't output errors happened on gevent greenlets twice - Newsfeed skip sites with no database @@ -334,7 +532,7 @@ Affected versions: All versions before ZeroNet Rev3616 - Opened port checking (Thanks l5h5t7 & saber28 for reporting) - Standalone update.py argument parsing (Thanks Zalex for reporting) - uPnP crash on startup (Thanks Vertux for reporting) - - CoffeeScript 1.12.6 compatibility (Thanks kavamaken & imachug) + - CoffeeScript 1.12.6 compatibility (Thanks kavamaken & purplesyringa) - Multi value argument parsing - Database error when running from directory that contains special characters (Thanks Pupiloho for reporting) - Site lock violation logging diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 7839cfa0c..000000000 --- a/Dockerfile +++ /dev/null @@ -1,33 +0,0 @@ -FROM alpine:3.11 - -#Base settings -ENV HOME /root - -COPY requirements.txt /root/requirements.txt - -#Install ZeroNet -RUN apk --update --no-cache --no-progress add python3 python3-dev gcc libffi-dev musl-dev make tor openssl \ - && pip3 install -r /root/requirements.txt \ - && apk del python3-dev gcc libffi-dev musl-dev make \ - && echo "ControlPort 9051" >> /etc/tor/torrc \ - && echo "CookieAuthentication 1" >> /etc/tor/torrc - -RUN python3 -V \ - && python3 -m pip list \ - && tor --version \ - && openssl version - -#Add Zeronet source -COPY . /root -VOLUME /root/data - -#Control if Tor proxy is started -ENV ENABLE_TOR false - -WORKDIR /root - -#Set upstart command -CMD (! ${ENABLE_TOR} || tor&) && python3 zeronet.py --ui_ip 0.0.0.0 --fileserver_port 26552 - -#Expose ports -EXPOSE 43110 26552 diff --git a/Dockerfile.arm64v8 b/Dockerfile.arm64v8 deleted file mode 100644 index d27b76206..000000000 --- a/Dockerfile.arm64v8 +++ /dev/null @@ -1,34 +0,0 @@ -FROM alpine:3.12 - -#Base settings -ENV HOME /root - -COPY requirements.txt /root/requirements.txt - -#Install ZeroNet -RUN apk --update --no-cache --no-progress add python3 python3-dev gcc libffi-dev musl-dev make tor openssl \ - && pip3 install -r /root/requirements.txt \ - && apk del python3-dev gcc libffi-dev musl-dev make \ - && echo "ControlPort 9051" >> /etc/tor/torrc \ - && echo "CookieAuthentication 1" >> /etc/tor/torrc - -RUN python3 -V \ - && python3 -m pip list \ - && tor --version \ - && openssl version - -#Add Zeronet source -COPY . /root -VOLUME /root/data - -#Control if Tor proxy is started -ENV ENABLE_TOR false - -WORKDIR /root - -#Set upstart command -CMD (! ${ENABLE_TOR} || tor&) && python3 zeronet.py --ui_ip 0.0.0.0 --fileserver_port 26552 - -#Expose ports -EXPOSE 43110 26552 - diff --git a/LICENSE b/LICENSE index 0d17b72da..9b5df6d92 100644 --- a/LICENSE +++ b/LICENSE @@ -11,7 +11,16 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . -Additional Conditions : +All contributions after commit 2a4927b77b55dea9c40d14ce2cfa8a0bf0a90b80 +(and/or made after 2022-05-22 UTC 00:00:00) can additionally be used +under GNU General Public License as published by the Free Software +Foundation, version 3 or (at your option) any later version. + + +Additional Conditions (please note that these are likely to not be legally bounding, +but before this is cleared we're leaving this note) applying to contributions from +commit 1de748585846e935d9d88bc7f22c69c84f7b8252 till commit +2a4927b77b55dea9c40d14ce2cfa8a0bf0a90b80: Contributing to this repo This repo is governed by GPLv3, same is located at the root of the ZeroNet git repo, diff --git a/README-ptbr.md b/README-ptbr.md new file mode 100644 index 000000000..a53bc9c28 --- /dev/null +++ b/README-ptbr.md @@ -0,0 +1,164 @@ +# zeronet-conservancy + +[in English](README.md) | [по-русски](README-ru.md) | [简体中文](README-zh-cn.md) + +[![Packaging status](https://repology.org/badge/vertical-allrepos/zeronet-conservancy.svg)](https://repology.org/project/zeronet-conservancy/versions) + +zeronet-conservancy é um garfo/continuação do projeto [ZeroNet](https://github.com/HelloZeroNet/ZeroNet) +(que foi abandonada por seu criador) que se dedica a sustentar a rede p2p existente e a desenvolver +seus valores de descentralização e liberdade, enquanto muda gradualmente para uma rede mais bem projetada + +## Por que garfo? + +Durante a crise da onion-v3, precisávamos de um garfo que funcionasse com onion-v3 e não dependesse da confiança de um ou +duas pessoas. Este garfo começou a partir do cumprimento dessa missão, implementando mudanças mínimas para +[ZeroNet/py3](https://github.com/HelloZeroNet/ZeroNet/tree/py3) ramo que é fácil de ser auditado por qualquer pessoa. Enquanto +você ainda pode usar as primeiras liberações do garfo para fazer funcionar a onion-v3, o objetivo deste garfo mudou desde então +e nos dedicamos a resolver mais problemas e melhorar a experiência do usuário e a segurança por toda parte, até +a nova rede, completamente transparente e auditada está pronta e este projeto pode ser colocado para descansar + +## Por que 0net? + +* Acreditamos em redes e comunicação abertas, livres e não censuradas. +* Nenhum ponto único de falha: O site permanece online desde que pelo menos 1 par seja + servindo-o. +* Sem custos de hospedagem: Os sites são servidos por visitantes. +* Impossível de ser desligado: Não está em lugar nenhum porque está em toda parte. +* Rápido e funciona offline: Você pode acessar o site, mesmo que a Internet seja + indisponível. + + +## Características + + * Sites atualizados em tempo real + * Clonar websites em um clique + * Autorização sem senha usando chaves públicas/privadas + * Servidor SQL integrado com sincronização de dados P2P: permite um desenvolvimento dinâmico mais fácil do site + * Anonimato: Suporte de rede Tor com serviços ocultos .onion (incluindo suporte a onion-v3) + * conexões criptografadas TLS (através de clearnet) + * Abertura automática da porta uPnP (se optado por entrar) + * Plugin para suporte multiusuário (openproxy) + * Funciona com qualquer navegador/OS moderno + + +## Como funciona? + +* Após iniciar o `zeronet.py` você poderá visitar os sites da zeronet utilizando + `http://127.0.0.1:43110/{zeronet_address}` (ex. + `http://127.0.0.1:43110/126NXcevn1AUehWFZLTBw7FrX1crEizQdr`). +* Quando você visita um novo site zeronet, ele tenta encontrar pares usando o BitTorrent + para poder baixar os arquivos do site (html, css, js...) a partir deles. +* Cada site visitado também é servido por você. +* Cada site contém um arquivo `content.json` que contém todos os outros arquivos em um hash sha512 + e uma assinatura gerada usando a chave privada do site. +* Se o proprietário do site (que tem a chave privada para o endereço do site) modificar o + então ele assina o novo `content.json` e o publica para os colegas. + Em seguida, os pares verificam a integridade do `content.json` (utilizando o + assinatura), eles baixam os arquivos modificados e publicam o novo conteúdo para + outros colegas. + +Os links a seguir referem-se à ZeroNet original: + +- [Slideshow sobre criptografia ZeroNet, atualizações de sites, sites multiusuário "](https://docs.google.com/presentation/d/1_2qK1IuOKJ51pgBvllZ9Yu7Au2l551t3XBgyTSvilew/pub?start=false&loop=false&delayms=3000) +- [Perguntas mais freqüentes "](https://zeronet.io/docs/faq/) +- [Documentação do Desenvolvedor da ZeroNet "](https://zeronet.io/docs/site_development/getting_started/) + +## Como aderir + +### Instalar a partir da fonte (recomendado) + +#### Dependências do sistema + +##### Genéricos unix-like (incluindo mac os x) + +Instalar o autoconf e outras ferramentas básicas de desenvolvimento, python3 e pip. + +##### Apt-based (debian, ubuntu, etc) + - `sudo apt update` + - `sudo apt install pkg-config python3-pip python3-venv` + +##### Android/Termux + - install [Termux](https://termux.com/) (no Termux você pode instalar pacotes via `pkg install `) + - Atualização do "pkg". + - `pkg install python automake git binutils libtool` (TODO: verificar nova instalação se há mais dependências para instalar) + - (opcional) `pkg install tor` + - (opcional) rodar tor via comando `tor --ControlPort 9051 --CookieAuthentication 1` (você pode então abrir uma nova sessão deslizando para a direita) + +#### Construindo dependências python & running + - clonar este repo (NOTA: no Android/Termux você deve cloná-lo na pasta "home" do Termux, porque o ambiente virtual não pode viver no `storage/`) + - "python3 -m venv venv" (fazer python ambiente virtual, o último `venv` é apenas um nome, se você usar diferente você deve substituí-lo em comandos posteriores) + - "fonte venv/bin/activate" (activar ambiente) + - `python3 -m pip install -r requirements.txt` (instalar dependências) + - zeronet.py` (**run zeronet-conservancy!**) + - abra a página de desembarque em seu navegador navegando para: http://127.0.0.1:43110/ + - para reiniciá-lo a partir de um terminal novo, você precisa navegar para redirecionar o diretório e: + - "fonte venv/bin/activate + - "python3 zeronet.py + +#### Construir imagem do Docker +- construir imagem 0net: `docker build -t 0net:conservancy . -f Dockerfile` +- ou construir imagem 0net com tor integrado: `docker build -t 0net:conservancy . -f Dockerfile.integrated_tor` +- e dirigi-lo: `docker run --rm -it -v :/app/data -p 43110:43110 -p 26552:26552 0net:conservancy''. +- /caminho/até/0n/dados/diretório - diretório, onde todos os dados serão salvos, incluindo seus certificados secretos. Se você executá-lo com o modo de produção, não remova esta pasta! +- ou você pode executá-lo com o docker-compose: `docker compose up -d 0net` sobe dois containers - 0net e tor separadamente. +- ou: "docker compose up -d 0net-tor" para rodar 0net e tor em um recipiente. + +#### roteiro alternativo + - após instalar as dependências gerais e clonagem repo (como acima), execute `start-venv.sh` que criará um ambiente virtual para você e instalará os requisitos python + - mais roteiros de conveniência a serem adicionados em breve + +## Limitações atuais + +* As transações de arquivos não são comprimidas +* Sem sites privados +* Sem suporte de DHT +* Elementos centralizados como o zeroid (estamos trabalhando nisso!) +* Nenhuma proteção confiável contra spam (e nisto também) +* Não funciona diretamente do navegador (uma das principais prioridades para o futuro médio) +* Sem transparência de dados + + +## Como posso criar um site ZeroNet? + + Clique em **⋮*** > **"Criar site novo, vazio "** item do menu [página admin](http://127.0.0.1:43110/126NXcevn1AUehWFZLTBw7FrX1crEizQdr). + * Você será **re-direcionado *** para um site completamente novo que só pode ser modificado por você! + * Você pode encontrar e modificar o conteúdo de seu site no diretório **data/[endereço de seu site]**. + * Após as modificações abrir seu site, arraste o botão superior direito "0" para a esquerda, depois pressione **sign** e **publish** botões na parte inferior + +Próximos passos: [Documentação do Desenvolvedor da ZeroNet](https://zeronet.io/docs/site_development/getting_started/) + +## Ajude este projeto a permanecer vivo + +### Torne-se um mantenedor + +Precisamos de mais mantenedores! Torne-se um hoje! Você não precisa saber como codificar, +há muito mais trabalho a ser feito. + +### Corrigir bugs e adicionar recursos + +Decidimos ir em frente e fazer uma web p2p perfeita, então precisamos de mais ajuda +implementando-o. + +#### Faça seu site/bring seu conteúdo + +Sabemos que a documentação está faltando, mas tentamos o melhor para apoiar qualquer um +que quer migrar. Não hesite em perguntar. + +#### Use-o e espalhe a palavra + +Certifique-se de dizer às pessoas por que você usa 0net e este garfo em particular! Pessoas +precisam conhecer suas alternativas. + +### Mantenedores de suporte financeiro + +Atualmente, o principal desenvolvedor/mantenedor deste garfo é @caryoscelus. Você pode +veja maneiras de doar para eles em https://caryoscelus.github.io/donate/ (ou verifique +sidebar se você estiver lendo isto no github para mais maneiras). À medida que nossa equipe cresce, nós +também criará contas de equipe em plataformas amigáveis de financiamento de multidões. + +Se você quiser ter certeza de que sua doação é reconhecida como doação para isto +projeto, também há um endereço dedicado ao bitcoin para isso: +1Kjuw3reZvxRVNs27Gen7jPJYCn6LY7Fg6 + +Se você quiser doar de uma maneira diferente, sinta-se à vontade para contatar o mantenedor ou +criar uma publicação! diff --git a/README-ru.md b/README-ru.md index 75abbfab9..1c9df4264 100644 --- a/README-ru.md +++ b/README-ru.md @@ -1,40 +1,48 @@ -# ZeroNet [![Build Status](https://travis-ci.org/HelloZeroNet/ZeroNet.svg?branch=master)](https://travis-ci.org/HelloZeroNet/ZeroNet) [![Documentation](https://img.shields.io/badge/docs-faq-brightgreen.svg)](https://zeronet.io/docs/faq/) [![Help](https://img.shields.io/badge/keep_this_project_alive-donate-yellow.svg)](https://zeronet.io/docs/help_zeronet/donate/) +# zeronet-conservancy -[简体中文](./README-zh-cn.md) -[English](./README.md) +[in English](README.md) | [em português](README-ptbr.md) | [简体中文](README-zh-cn.md) -Децентрализованные вебсайты использующие Bitcoin криптографию и BitTorrent сеть - https://zeronet.io +[![Packaging status](https://repology.org/badge/vertical-allrepos/zeronet-conservancy.svg)](https://repology.org/project/zeronet-conservancy/versions) +zeronet-conservancy — это форк/продолжение проекта [ZeroNet](https://github.com/HelloZeroNet/ZeroNet) +(покинутого его создателем), предназначенный для поддержки существующей сети p2p и развития +идей ценности децентрализации и свободы, постепенно развивающийся в более совершенную сеть -## Зачем? +## Зачем нужен этот форк? -* Мы верим в открытую, свободную, и не отцензуренную сеть и коммуникацию. +Во время кризиса onion-v3 появилась необходимость в форке, который работал бы с onion-v3 и не зависел от доверия к конкретным личностям. +Для выполнения этой задачи форк начался с внесения минимальных изменений в +[ZeroNet/py3](https://github.com/HelloZeroNet/ZeroNet/tree/py3), которые легко проверяются. В то время как остается возможность использования ранних версий форка для работы с onion-v3, цель данного форка изменилась и мы стали стремиться решать больше проблем и повышать удобность и безопасность для пользователей до тех пор, пока новая, полностью прозрачная и проверенная сеть не будет готова, и необходимость в этом проекте не отпадет. + + +## Зачем нужен 0net? + +* Мы верим в открытую, свободную, и не поддающуюся цензуре сеть и коммуникацию. * Нет единой точки отказа: Сайт онлайн пока по крайней мере 1 пир обслуживает его. * Никаких затрат на хостинг: Сайты обслуживаются посетителями. * Невозможно отключить: Он нигде, потому что он везде. * Быстр и работает оффлайн: Вы можете получить доступ к сайту, даже если Интернет недоступен. + + ## Особенности * Обновляемые в реальном времени сайты - * Поддержка Namecoin .bit доменов - * Лёгок в установке: распаковал & запустил * Клонирование вебсайтов в один клик - * Password-less [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) - based authorization: Ваша учетная запись защищена той же криптографией, что и ваш Bitcoin-кошелек - * Встроенный SQL-сервер с синхронизацией данных P2P: Позволяет упростить разработку сайта и ускорить загрузку страницы - * Анонимность: Полная поддержка сети Tor с помощью скрытых служб .onion вместо адресов IPv4 - * TLS зашифрованные связи - * Автоматическое открытие uPnP порта + * Авторизация без паролей, с использованием пары публичный/приватный ключ + * Встроенный SQL-сервер с синхронизацией данных P2P: позволяет упростить разработку сайта + * Анонимность: поддержка сети Tor с помощью скрытых служб .onion (включая onion-v3) + * TLS зашифрованные связи (в клирнете) + * Автоматическое открытие uPnP порта (опционально) * Плагин для поддержки многопользовательской (openproxy) * Работает с любыми браузерами и операционными системами ## Как это работает? -* После запуска `zeronet.py` вы сможете посетить зайты (zeronet сайты) используя адрес +* После запуска `zeronet.py` вы сможете посетить zeronet сайты используя адрес `http://127.0.0.1:43110/{zeronet_address}` -(например. `http://127.0.0.1:43110/1HeLLo4uzjaLetFx6NH3PMwFP3qbRbTf3D`). +(например. `http://127.0.0.1:43110/1MCoA8rQHhwu4LY2t2aabqcGSRqrL8uf2X`). * Когда вы посещаете новый сайт zeronet, он пытается найти пиров с помощью BitTorrent чтобы загрузить файлы сайтов (html, css, js ...) из них. * Каждый посещенный зайт также обслуживается вами. (Т.е хранится у вас на компьютере) @@ -44,168 +52,117 @@ подписывает новый `content.json` и публикует его для пиров. После этого пиры проверяют целостность `content.json` (используя подпись), они загружают измененные файлы и публикуют новый контент для других пиров. + +Ссылки c информацией о ZeroNet: + #### [Слайд-шоу о криптографии ZeroNet, обновлениях сайтов, многопользовательских сайтах »](https://docs.google.com/presentation/d/1_2qK1IuOKJ51pgBvllZ9Yu7Au2l551t3XBgyTSvilew/pub?start=false&loop=false&delayms=3000) #### [Часто задаваемые вопросы »](https://zeronet.io/docs/faq/) - #### [Документация разработчика ZeroNet »](https://zeronet.io/docs/site_development/getting_started/) +#### [Скриншоты в ZeroNet документации »](https://zeronet.io/docs/using_zeronet/sample_sites/) +## Как присоединиться -## Скриншоты - -![Screenshot](https://i.imgur.com/H60OAHY.png) -![ZeroTalk](https://zeronet.io/docs/img/zerotalk.png) - -#### [Больше скриншотов в ZeroNet документации »](https://zeronet.io/docs/using_zeronet/sample_sites/) - - -## Как вступить - -* Скачайте ZeroBundle пакет: - * [Microsoft Windows](https://github.com/HelloZeroNet/ZeroNet-win/archive/dist/ZeroNet-win.zip) - * [Apple macOS](https://github.com/HelloZeroNet/ZeroNet-mac/archive/dist/ZeroNet-mac.zip) - * [Linux 64-bit](https://github.com/HelloZeroNet/ZeroBundle/raw/master/dist/ZeroBundle-linux64.tar.gz) - * [Linux 32-bit](https://github.com/HelloZeroNet/ZeroBundle/raw/master/dist/ZeroBundle-linux32.tar.gz) -* Распакуйте где угодно -* Запустите `ZeroNet.exe` (win), `ZeroNet(.app)` (osx), `ZeroNet.sh` (linux) +### Установить из репозитория вашего дистрибутива -### Linux терминал +- NixOS: https://search.nixos.org/packages?channel=22.05&show=zeronet-conservancy&type=packages&query=zeronet-conservancy +- ArchLinux: [последний релиз](https://aur.archlinux.org/packages/zeronet-conservancy), [git-версия](https://aur.archlinux.org/packages/zeronet-conservancy-git) -* `wget https://github.com/HelloZeroNet/ZeroBundle/raw/master/dist/ZeroBundle-linux64.tar.gz` -* `tar xvpfz ZeroBundle-linux64.tar.gz` -* `cd ZeroBundle` -* Запустите с помощью `./ZeroNet.sh` +### Установить из исходного кода (рекомендовано) -Он загружает последнюю версию ZeroNet, затем запускает её автоматически. +#### System dependencies -#### Ручная установка для Debian Linux +##### Generic unix-like (including mac os x) -* `sudo apt-get update` -* `sudo apt-get install msgpack-python python-gevent` -* `wget https://github.com/HelloZeroNet/ZeroNet/archive/master.tar.gz` -* `tar xvpfz master.tar.gz` -* `cd ZeroNet-master` -* Запустите с помощью `python2 zeronet.py` -* Откройте http://127.0.0.1:43110/ в вашем браузере. +Установите autoconf и другие базовые инструменты разработки, python3 и pip. -### [Arch Linux](https://www.archlinux.org) +##### Apt-based (debian, ubuntu, etc) + - `sudo apt update` + - `sudo apt install pkg-config python3-pip python3-venv` -* `git clone https://aur.archlinux.org/zeronet.git` -* `cd zeronet` -* `makepkg -srci` -* `systemctl start zeronet` -* Откройте http://127.0.0.1:43110/ в вашем браузере. +##### Android/Termux + - Установите [Termux](https://termux.com/) (в Termux вы можете устанавливать пакеты через команду `pkg install `) + - `pkg update` + - `pkg install python automake git binutils libtool` + - (optional) `pkg install tor` + - (optional) запустить тор через команду `tor --ControlPort 9051 --CookieAuthentication 1` (вы можете открыть новый сеанс свайпом вправо) -Смотрите [ArchWiki](https://wiki.archlinux.org)'s [ZeroNet -article](https://wiki.archlinux.org/index.php/ZeroNet) для дальнейшей помощи. +#### Скрипт, который всё сделает за вас + - после установки общих зависимостей и клонирования репозитория (как указано выше) запустите `start-venv.sh` который создаст для вас виртуальную среду (если её ещё нет) и установит необходимые пакеты Python + - больше удобных скриптов будует добавлено в ближайшее время -### [Gentoo Linux](https://www.gentoo.org) +#### Установка Python-зависимостей и запуск + - клонируйте репозиторий (NOTE: на Android/Termux вы должны клонировать его в «домашнюю» папку Termux, потому что виртуальная среда не может находиться в `storage/`) + - `python3 -m venv venv` (создайте виртуальную среду python, последнее `venv` это просто имя/название, если вы используете другое, вы должны заменить его в более поздних командах.) + - `source venv/bin/activate` (активируйте среду) + - `python3 -m pip install -r requirements.txt` (установите зависимости) + - `python3 zeronet.py` (**запустите zeronet-conservancy!**) + - откройте основную страницу в браузере, перейдя по: http://127.0.0.1:43110/ + - для повторного запуска с нового терминала вам нужно перейти в деректорию репозитория и ввести : + - `source venv/bin/activate` + - `python3 zeronet.py` -* [`layman -a raiagent`](https://github.com/leycec/raiagent) -* `echo '>=net-vpn/zeronet-0.5.4' >> /etc/portage/package.accept_keywords` -* *(Опционально)* Включить поддержку Tor: `echo 'net-vpn/zeronet tor' >> - /etc/portage/package.use` -* `emerge zeronet` -* `rc-service zeronet start` -* Откройте http://127.0.0.1:43110/ в вашем браузере. +#### (альтернативно) Создание образа Docker +- создание образа: `docker build -t 0net-conservancy:latest . -f Dockerfile` +- или создрание образа с встроенным tor: `docker build -t 0net-conservancy:latest . -f Dockerfile.integrated_tor` +- и его запуск: `docker run --rm -it -v :/app/data -p 43110:43110 -p 26552:26552 0net-conservancy:latest` +- /path/to/0n/data/directory - директория, куда будут сохраняться все данные в том числе секретные ключи. Если вы запускаете в боевом режиме, не потеряйте эту папку! +- или вы можете воспользоваться docker-compose: `docker compose up -d 0net-conservancy` запускает два контейнера раздельно, для 0net и tor сервисов. +- или: `docker compose up -d 0net-tor` запускает один контейнер с tor и 0net. -Смотрите `/usr/share/doc/zeronet-*/README.gentoo.bz2` для дальнейшей помощи. +## Текущие ограничения -### [FreeBSD](https://www.freebsd.org/) - -* `pkg install zeronet` or `cd /usr/ports/security/zeronet/ && make install clean` -* `sysrc zeronet_enable="YES"` -* `service zeronet start` -* Откройте http://127.0.0.1:43110/ в вашем браузере. - -### [Vagrant](https://www.vagrantup.com/) - -* `vagrant up` -* Подключитесь к VM с помощью `vagrant ssh` -* `cd /vagrant` -* Запустите `python2 zeronet.py --ui_ip 0.0.0.0` -* Откройте http://127.0.0.1:43110/ в вашем браузере. - -### [Docker](https://www.docker.com/) -* `docker run -d -v :/root/data -p 15441:15441 -p 127.0.0.1:43110:43110 nofish/zeronet` -* Это изображение Docker включает в себя прокси-сервер Tor, который по умолчанию отключён. - Остерегайтесь что некоторые хостинг-провайдеры могут не позволить вам запускать Tor на своих серверах. - Если вы хотите включить его,установите переменную среды `ENABLE_TOR` в` true` (по умолчанию: `false`) Например: - - `docker run -d -e "ENABLE_TOR=true" -v :/root/data -p 15441:15441 -p 127.0.0.1:43110:43110 nofish/zeronet` -* Откройте http://127.0.0.1:43110/ в вашем браузере. - -### [Virtualenv](https://virtualenv.readthedocs.org/en/latest/) - -* `virtualenv env` -* `source env/bin/activate` -* `pip install msgpack gevent` -* `python2 zeronet.py` -* Откройте http://127.0.0.1:43110/ в вашем браузере. - -## Текущие ограничения - -* ~~Нет torrent-похожего файла разделения для поддержки больших файлов~~ (поддержка больших файлов добавлена) -* ~~Не анонимнее чем Bittorrent~~ (добавлена встроенная поддержка Tor) -* Файловые транзакции не сжаты ~~ или незашифрованы еще ~~ (добавлено шифрование TLS) +* Файловые транзакции не сжаты * Нет приватных сайтов +* Отсутствует поддержка DHT +* Централизованные элементы, такие как Zeroid (мы работаем над этим!) +* Нет надежной защиты от спама (в процессе разработки) +* Не работает напрямую из браузера (один из главных приоритетов в ближайшем будущем) +* Нет прозрачности данных -## Как я могу создать сайт в Zeronet? - -Завершите работу zeronet, если он запущен +## Как создать сайт ZeroNet? -```bash -$ zeronet.py siteCreate -... -- Site private key (Приватный ключ сайта): 23DKQpzxhbVBrAtvLEc2uvk7DZweh4qL3fn3jpM3LgHDczMK2TtYUq -- Site address (Адрес сайта): 13DNDkMUExRf9Xa9ogwPKqp7zyHFEqbhC2 -... -- Site created! (Сайт создан) -$ zeronet.py -... -``` - -Поздравляем, вы закончили! Теперь каждый может получить доступ к вашему зайту используя -`http://localhost:43110/13DNDkMUExRf9Xa9ogwPKqp7zyHFEqbhC2` + * Нажмите на **⋮** > **"Create new, empty site"** пункт меню на [admin page](http://127.0.0.1:43110/126NXcevn1AUehWFZLTBw7FrX1crEizQdr). + * Вы будете перенаправлены **redirected** на совершенно новый сайт, который можете изменить только вы! + * Вы можете найти и изменить содержимое своего сайта в каталоге **data/[yoursiteaddress]** + * После внесения изменений откройте свой сайт, перетащите верхнюю правую кнопку «0» влево, затем нажмите кнопки **sign** и **publish** , находящиеся внизу. Следующие шаги: [ZeroNet Developer Documentation](https://zeronet.io/docs/site_development/getting_started/) +## Поддержите проект -## Как я могу модифицировать Zeronet сайт? +### Вы можете стать одним из сопровождающих -* Измените файлы расположенные в data/13DNDkMUExRf9Xa9ogwPKqp7zyHFEqbhC2 директории. - Когда закончите с изменением: +Нам нужно больше сопровождающих! Станьте им сегодня! Вам не нужно знать, как кодировать, +есть много другой работы. -```bash -$ zeronet.py siteSign 13DNDkMUExRf9Xa9ogwPKqp7zyHFEqbhC2 -- Signing site (Подпись сайта): 13DNDkMUExRf9Xa9ogwPKqp7zyHFEqbhC2... -Private key (Приватный ключ) (input hidden): -``` +### Исправленные баги & новые функции -* Введите секретный ключ, который вы получили при создании сайта, потом: +Мы решили пойти дальше и создать идеальную сеть p2p, поэтому нам нужна дополнительная помощь в воплощении этой идеи. -```bash -$ zeronet.py sitePublish 13DNDkMUExRf9Xa9ogwPKqp7zyHFEqbhC2 -... -Site:13DNDk..bhC2 Publishing to 3/10 peers... -Site:13DNDk..bhC2 Successfuly published to 3 peers -- Serving files.... -``` +### Создайте свой сайт / переносите свой контент -* Вот и всё! Вы успешно подписали и опубликовали свои изменения. +Мы знаем, что документации не хватает, но мы делаем все возможное, чтобы поддержать любого +кто хочет переехать. Не стесняйтесь спрашивать. +### Используйте его и делитесь информацией о его существовании -## Поддержите проект +Обязательно расскажите людям, почему вы используете 0net и этот форк в частности! Люди +должны знать об альтернативах. -- Bitcoin: 1QDhxQ6PraUZa21ET5fYUCPgdrwBomnFgX -- Paypal: https://zeronet.io/docs/help_zeronet/donate/ -### Спонсоры +### Финансовая поддержка сопровождающих -* Улучшенная совместимость с MacOS / Safari стала возможной благодаря [BrowserStack.com](https://www.browserstack.com) +В настоящее время ведущим разработчиком/сопровождающим этого форка является @caryoscelus. Вы можете +посмотреть способы пожертвования на https://caryoscelus.github.io/donate/ (или проверьте +боковую панель, если вы читаете это на github, чтобы узнать больше). По мере роста нашей команды мы +также создаст командные аккаунты на дружественных краудфандинговых платформах. -#### Спасибо! +Если вы хотите, чтобы ваше пожертвование было признано пожертвованием для этого +проекта, для этого также есть специальный биткоин-адрес: +1Kjuw3reZvxRVNs27Gen7jPJYCn6LY7Fg6. Либо если хотите сделать более анонимный донат, вы +можете пожертвовать Monero: +4AiYUcqVRH4C2CVr9zbBdkhRnJnHiJoypHEsq4N7mQziGUoosPCpPeg8SPr87nvwypaRzDgMHEbWWDekKtq8hm9LBmgcMzC -* Больше информации, помощь, журнал изменений, zeronet сайты: https://www.reddit.com/r/zeronet/ -* Приходите, пообщайтесь с нами: [#zeronet @ FreeNode](https://kiwiirc.com/client/irc.freenode.net/zeronet) или на [gitter](https://gitter.im/HelloZeroNet/ZeroNet) -* Email: hello@zeronet.io (PGP: CB9613AE) +Если вы хотите сделать пожертвование другим способом, не стесняйтесь обращаться к сопровождающему или +создать запрос diff --git a/README-zh-cn.md b/README-zh-cn.md index fabdb0e59..2a4bb346b 100644 --- a/README-zh-cn.md +++ b/README-zh-cn.md @@ -1,9 +1,10 @@ -# ZeroNet [![Build Status](https://travis-ci.org/HelloZeroNet/ZeroNet.svg?branch=py3)](https://travis-ci.org/HelloZeroNet/ZeroNet) [![Documentation](https://img.shields.io/badge/docs-faq-brightgreen.svg)](https://zeronet.io/docs/faq/) [![Help](https://img.shields.io/badge/keep_this_project_alive-donate-yellow.svg)](https://zeronet.io/docs/help_zeronet/donate/) +# zeronet-conservancy -[English](./README.md) +**警告**:这个翻译已经过时了。请阅读英文版。对此翻译的任何贡献都将受到高度赞赏 -使用 Bitcoin 加密和 BitTorrent 网络的去中心化网络 - https://zeronet.io +[![Packaging status](https://repology.org/badge/vertical-allrepos/zeronet-conservancy.svg)](https://repology.org/project/zeronet-conservancy/versions) +[in English](README.md) | [em português](README-ptbr.md) | [по-русски](README-ru.md) ## 为什么? @@ -16,7 +17,6 @@ ## 功能 * 实时站点更新 - * 支持 Namecoin 的 .bit 域名 * 安装方便:只需解压并运行 * 一键克隆存在的站点 * 无需密码、基于 [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) @@ -48,46 +48,12 @@ ## 屏幕截图 -![Screenshot](https://i.imgur.com/H60OAHY.png) -![ZeroTalk](https://zeronet.io/docs/img/zerotalk.png) - #### [ZeroNet 文档中的更多屏幕截图 »](https://zeronet.io/docs/using_zeronet/sample_sites/) ## 如何加入 -### Windows - - - 下载 [ZeroNet-py3-win64.zip](https://github.com/HelloZeroNet/ZeroNet-win/archive/dist-win64/ZeroNet-py3-win64.zip) (18MB) - - 在任意位置解压缩 - - 运行 `ZeroNet.exe` - -### macOS - - - 下载 [ZeroNet-dist-mac.zip](https://github.com/HelloZeroNet/ZeroNet-dist/archive/mac/ZeroNet-dist-mac.zip) (13.2MB) - - 在任意位置解压缩 - - 运行 `ZeroNet.app` - -### Linux (x86-64bit) - - - `wget https://github.com/HelloZeroNet/ZeroNet-linux/archive/dist-linux64/ZeroNet-py3-linux64.tar.gz` - - `tar xvpfz ZeroNet-py3-linux64.tar.gz` - - `cd ZeroNet-linux-dist-linux64/` - - 使用以下命令启动 `./ZeroNet.sh` - - 在浏览器打开 http://127.0.0.1:43110/ 即可访问 ZeroHello 页面 - - __提示:__ 若要允许在 Web 界面上的远程连接,使用以下命令启动 `./ZeroNet.sh --ui_ip '*' --ui_restrict your.ip.address` - -### 从源代码安装 - - - `wget https://github.com/HelloZeroNet/ZeroNet/archive/py3/ZeroNet-py3.tar.gz` - - `tar xvpfz ZeroNet-py3.tar.gz` - - `cd ZeroNet-py3` - - `sudo apt-get update` - - `sudo apt-get install python3-pip` - - `sudo python3 -m pip install -r requirements.txt` - - 使用以下命令启动 `python3 zeronet.py` - - 在浏览器打开 http://127.0.0.1:43110/ 即可访问 ZeroHello 页面 + ## 现有限制 @@ -99,7 +65,7 @@ ## 如何创建一个 ZeroNet 站点? - * 点击 [ZeroHello](http://127.0.0.1:43110/1HeLLo4uzjaLetFx6NH3PMwFP3qbRbTf3D) 站点的 **⋮** > **「新建空站点」** 菜单项 + * 点击 [ZeroHello](http://127.0.0.1:43110/126NXcevn1AUehWFZLTBw7FrX1crEizQdr) 站点的 **⋮** > **「新建空站点」** 菜单项 * 您将被**重定向**到一个全新的站点,该站点只能由您修改 * 您可以在 **data/[您的站点地址]** 目录中找到并修改网站的内容 * 修改后打开您的网站,将右上角的「0」按钮拖到左侧,然后点击底部的**签名**并**发布**按钮 @@ -108,16 +74,8 @@ ## 帮助这个项目 -- Bitcoin: 1QDhxQ6PraUZa21ET5fYUCPgdrwBomnFgX -- Paypal: https://zeronet.io/docs/help_zeronet/donate/ - -### 赞助商 - -* [BrowserStack.com](https://www.browserstack.com) 使更好的 macOS/Safari 兼容性成为可能 +- Bitcoin: 1Kjuw3reZvxRVNs27Gen7jPJYCn6LY7Fg6 #### 感谢您! * 更多信息,帮助,变更记录和 zeronet 站点:https://www.reddit.com/r/zeronet/ -* 前往 [#zeronet @ FreeNode](https://kiwiirc.com/client/irc.freenode.net/zeronet) 或 [gitter](https://gitter.im/HelloZeroNet/ZeroNet) 和我们聊天 -* [这里](https://gitter.im/ZeroNet-zh/Lobby)是一个 gitter 上的中文聊天室 -* Email: hello@zeronet.io (PGP: [960F FF2D 6C14 5AA6 13E8 491B 5B63 BAE6 CB96 13AE](https://zeronet.io/files/tamas@zeronet.io_pub.asc)) diff --git a/README.md b/README.md index d8e36a717..9f1cdb435 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,32 @@ -# ZeroNet [![Build Status](https://travis-ci.org/HelloZeroNet/ZeroNet.svg?branch=py3)](https://travis-ci.org/HelloZeroNet/ZeroNet) [![Documentation](https://img.shields.io/badge/docs-faq-brightgreen.svg)](https://zeronet.io/docs/faq/) [![Help](https://img.shields.io/badge/keep_this_project_alive-donate-yellow.svg)](https://zeronet.io/docs/help_zeronet/donate/) ![tests](https://github.com/HelloZeroNet/ZeroNet/workflows/tests/badge.svg) [![Docker Pulls](https://img.shields.io/docker/pulls/nofish/zeronet)](https://hub.docker.com/r/nofish/zeronet) +# zeronet-conservancy -Decentralized websites using Bitcoin crypto and the BitTorrent network - https://zeronet.io / [onion](http://zeronet34m3r5ngdu54uj57dcafpgdjhxsgq5kla5con4qvcmfzpvhad.onion) +[![Packaging status](https://repology.org/badge/vertical-allrepos/zeronet-conservancy.svg)](https://repology.org/project/zeronet-conservancy/versions) +(NOTE THAT TRANSLATIONS ARE USUALLY BEHIND THIS FILE) -## Why? +[по-русски](README-ru.md) | [em português](README-ptbr.md) | [简体中文](README-zh-cn.md) -* We believe in open, free, and uncensored network and communication. +`zeronet-conservancy` is a fork/continuation of [ZeroNet](https://github.com/HelloZeroNet/ZeroNet) project +(that has been abandoned by its creator) that is dedicated to sustaining existing p2p network and developing +its values of decentralization and freedom, while gradually switching to a better designed network + +## No active maintainer warning + +This fork was created and maintained by @caryoscelus, but due to vanishing interest and in order to avoid having +another one-person project, the development is limitted. + +## Why fork? + +During onion-v3 switch crisis, we needed a fork that worked with onion-v3 and didn't depend on trust to one or +two people. This fork started from fulfilling that mission, implementing minimal changes to +[ZeroNet/py3](https://github.com/HelloZeroNet/ZeroNet/tree/py3) branch which are easy to audit by anyone. While +you can still use the early releases of the fork to get onion-v3 working, the goal of this fork has since shifted +and we're dedicated to solving more problems and improving user experience and security all over, until the +brand new, completely transparent and audited network is ready and this project can be put to rest + +## Why 0net? + +* We believe in open, free, and uncensored networks and communication. * No single point of failure: Site remains online so long as at least 1 peer is serving it. * No hosting costs: Sites are served by visitors. @@ -16,24 +37,22 @@ Decentralized websites using Bitcoin crypto and the BitTorrent network - https:/ ## Features * Real-time updated sites - * Namecoin .bit domains support - * Easy to setup: unpack & run * Clone websites in one click - * Password-less [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) - based authorization: Your account is protected by the same cryptography as your Bitcoin wallet - * Built-in SQL server with P2P data synchronization: Allows easier site development and faster page load times - * Anonymity: Full Tor network support with .onion hidden services instead of IPv4 addresses - * TLS encrypted connections - * Automatic uPnP port opening + * Password-less authorization using private/public keys + * Built-in SQL server with P2P data synchronization: allows easier dynamic site development + * Anonymity: Tor network support with .onion hidden services (including onion-v3 support) + * TLS encrypted connections (through clearnet) + * Automatic uPnP port opening (if opted in) * Plugin for multiuser (openproxy) support - * Works with any browser/OS + * Works with any modern browser/OS + * Works offline and can be synced via alternative transports (or when connection is back) ## How does it work? * After starting `zeronet.py` you will be able to visit zeronet sites using `http://127.0.0.1:43110/{zeronet_address}` (eg. - `http://127.0.0.1:43110/1HeLLo4uzjaLetFx6NH3PMwFP3qbRbTf3D`). + `http://127.0.0.1:43110/1MCoA8rQHhwu4LY2t2aabqcGSRqrL8uf2X/`). * When you visit a new zeronet site, it tries to find peers using the BitTorrent network so it can download the site files (html, css, js...) from them. * Each visited site is also served by you. @@ -45,93 +64,225 @@ Decentralized websites using Bitcoin crypto and the BitTorrent network - https:/ signature), they download the modified files and publish the new content to other peers. -#### [Slideshow about ZeroNet cryptography, site updates, multi-user sites »](https://docs.google.com/presentation/d/1_2qK1IuOKJ51pgBvllZ9Yu7Au2l551t3XBgyTSvilew/pub?start=false&loop=false&delayms=3000) -#### [Frequently asked questions »](https://zeronet.io/docs/faq/) +Following links relate to original ZeroNet: -#### [ZeroNet Developer Documentation »](https://zeronet.io/docs/site_development/getting_started/) +- [Slideshow about ZeroNet cryptography, site updates, multi-user sites »](https://docs.google.com/presentation/d/1_2qK1IuOKJ51pgBvllZ9Yu7Au2l551t3XBgyTSvilew/pub?start=false&loop=false&delayms=3000) +- [Frequently asked questions »](https://zeronet.io/docs/faq/) +- [ZeroNet Developer Documentation »](https://zeronet.io/docs/site_development/getting_started/) (getting outdated) +## How to join -## Screenshots +### Install from your distribution repository -![Screenshot](https://i.imgur.com/H60OAHY.png) -![ZeroTalk](https://zeronet.io/docs/img/zerotalk.png) +- NixOS: [zeronet-conservancy packages search](https://search.nixos.org/packages?from=0&size=50&sort=relevance&type=packages&query=zeronet-conservancy) (and see below) +- ArchLinux: [latest release](https://aur.archlinux.org/packages/zeronet-conservancy), [fresh git version](https://aur.archlinux.org/packages/zeronet-conservancy-git) -#### [More screenshots in ZeroNet docs »](https://zeronet.io/docs/using_zeronet/sample_sites/) +### Install from Nix package manager (Linux or MacOS) + - install & configure nix package manager (if needed) + - `nix-env -iA nixpkgs.zeronet-conservancy` -## How to join +or add `zeronet-conservancy` to your system configuration if you're on NixOS -### Windows - - - Download [ZeroNet-py3-win64.zip](https://github.com/HelloZeroNet/ZeroNet-win/archive/dist-win64/ZeroNet-py3-win64.zip) (18MB) - - Unpack anywhere - - Run `ZeroNet.exe` - -### macOS - - - Download [ZeroNet-dist-mac.zip](https://github.com/HelloZeroNet/ZeroNet-dist/archive/mac/ZeroNet-dist-mac.zip) (13.2MB) - - Unpack anywhere - - Run `ZeroNet.app` - -### Linux (x86-64bit) - - `wget https://github.com/HelloZeroNet/ZeroNet-linux/archive/dist-linux64/ZeroNet-py3-linux64.tar.gz` - - `tar xvpfz ZeroNet-py3-linux64.tar.gz` - - `cd ZeroNet-linux-dist-linux64/` - - Start with: `./ZeroNet.sh` - - Open the ZeroHello landing page in your browser by navigating to: http://127.0.0.1:43110/ - - __Tip:__ Start with `./ZeroNet.sh --ui_ip '*' --ui_restrict your.ip.address` to allow remote connections on the web interface. - - ### Android (arm, arm64, x86) - - minimum Android version supported 16 (JellyBean) - - [Download from Google Play](https://play.google.com/store/apps/details?id=in.canews.zeronetmobile) - - APK download: https://github.com/canewsin/zeronet_mobile/releases - - XDA Labs: https://labs.xda-developers.com/store/app/in.canews.zeronet - -#### Docker -There is an official image, built from source at: https://hub.docker.com/r/nofish/zeronet/ +(thanks @fgaz for making & maintaining the package) ### Install from source - - `wget https://github.com/HelloZeroNet/ZeroNet/archive/py3/ZeroNet-py3.tar.gz` - - `tar xvpfz ZeroNet-py3.tar.gz` - - `cd ZeroNet-py3` - - `sudo apt-get update` - - `sudo apt-get install python3-pip` - - `sudo python3 -m pip install -r requirements.txt` - - Start with: `python3 zeronet.py` - - Open the ZeroHello landing page in your browser by navigating to: http://127.0.0.1:43110/ +#### System dependencies + +##### Generic unix-like (including mac os x) + +Install autoconf and other basic development tools, python3 and pip, then proceed to "building python dependencies" +(if running fails due to missing dependency, please report it/make pull request to fix dependency list) + +##### Apt-based (debian, ubuntu, etc) + - `sudo apt update` + - `sudo apt install git pkg-config libffi-dev python3-pip python3-venv python3-dev build-essential libtool` + +##### Red Hat and Fedora based + - `yum install epel-release -y 2>/dev/null` + - `yum install git python3 python3-wheel` + +##### Fedora based dandified + - `sudo dnf install git python3-pip python3-wheel -y` + +##### openSUSE + - `sudo zypper install python3-pip python3-setuptools python3-wheel` + +##### Arch and Manjaro based + - `sudo pacman -S git python-pip -v --no-confirm` + +##### Android/Termux + - install [Termux](https://termux.com/) (in Termux you can install packages via `pkg install `) + - `pkg update` + - `pkg install python automake git binutils libtool` + - (on an older android versions you may also need to install) `pkg install openssl-tool libcrypt clang` + - (if you've installed the above packages and still run into launch issues, please report) + - (optional) `pkg install tor` + - (optional) run tor via `tor --ControlPort 9051 --CookieAuthentication 1` command (you can then open new session by swiping to the right) + +#### Building python dependencies, venv & running + - clone this repo (NOTE: on Android/Termux you should clone it into "home" folder of Termux, because virtual environment cannot live in `storage/`) + - `python3 -m venv venv` (make python virtual environment, the last `venv` is just a name, if you use different you should replace it in later commands) + - `source venv/bin/activate` (activate environment) + - `python3 -m pip install -r requirements.txt` (install dependencies) + - `python3 zeronet.py` (**run zeronet-conservancy!**) + - open the landing page in your browser by navigating to: http://127.0.0.1:43110/ + - to start it again from fresh terminal, you need to navigate to repo directory and: + - `source venv/bin/activate` + - `python3 zeronet.py` + +#### (alternatively) On NixOS +- clone this repo +- `nix-shell '' -A zeronet-conservancy` to enter shell with installed dependencies +- `./zeronet.py` + +#### (alternatively) Build Docker image +- build 0net image: `docker build -t 0net-conservancy:latest . -f Dockerfile` +- or build 0net image with integrated tor: `docker build -t 0net-conservancy:latest . -f Dockerfile.integrated_tor` +- and run it: `docker run --rm -it -v :/app/data -p 43110:43110 -p 26552:26552 0net-conservancy:latest` +- /path/to/0n/data/directory - directory, where all data will be saved, including your secret certificates. If you run it with production mode, do not remove this folder! +- or you can run it with docker-compose: `docker compose up -d 0net-conservancy` up two containers - 0net and tor separately. +- or: `docker compose up -d 0net-tor` for run 0net and tor in one container. +(please check if these instructions are still accurate) + +#### Alternative one-liner (by @ssdifnskdjfnsdjk) (installing python dependencies globally) + +Clone Github repository and install required Python modules. First +edit zndir path at the begining of the command, to be the path where +you want to store `zeronet-conservancy`: + +`zndir="/home/user/myapps/zeronet" ; if [[ ! -d "$zndir" ]]; then git clone --recursive "https://github.com/zeronet-conservancy/zeronet-conservancy.git" "$zndir" && cd "$zndir"||exit; else cd "$zndir";git pull origin master; fi; cd "$zndir" && pip install -r requirements.txt|grep -v "already satisfied"; echo "Try to run: python3 $(pwd)/zeronet.py"` + +(This command can also be used to keep `zeronet-conservancy` up to date) + +#### Alternative script + - after installing general dependencies and cloning repo (as above), + run `start-venv.sh` which will create a virtual env for you and + install python requirements + - more convenience scripts to be added soon + +### (unofficial) Windows OS build + +Download and extract .zip archive +[zeronet-conservancy-0.7.10-unofficial-win64.zip](https://github.com/zeronet-conservancy/zeronet-conservancy/releases/download/v0.7.10/zeronet-conservancy-0.7.10-unofficial-win64.zip) + +### Building under Windows OS + +(These instructions are work-in-progress, please help us test it and improve it!) + +- install python from https://www.python.org/downloads/ +- install some windows compiler suitable for python , this proved to be the most difficult part for me as non-windows user (see here https://wiki.python.org/moin/WindowsCompilers and i'll link more references later) +- [optionally to get latest dev version] install git from https://git-scm.com/downloads +- [optionally to use tor for better connectivity and anonymization] install tor browser from https://www.torproject.org/download/ +- open git bash console +- type/copypaste `git clone https://github.com/zeronet-conservancy/zeronet-conservancy.git` into command line +- wait till git downloads latest dev version and continue in console +- `cd zeronet-conservancy` +- `python -m venv venv` (create virtual python environment) +- `venv\Scripts\activate` (this activates the environment) +- `pip install -r requirements.txt` (install python dependencies) (some users reported that this command doesn't successfully install requirements and only manual installation of dependencies one by one works) +- (NOTE: if previous step fails, it most likely means you haven't installed c/c++ compiler successfully) +- [optional for tor for better connectivity and anonymity] launch Tor Browser +- (NOTE: windows might show a window saying it blocked access to internet for "security reasons" — you should allow the access) +- `python zeronet.py --tor_proxy 127.0.0.1:9150 --tor_controller 127.0.0.1:9151` (launch zeronet-conservancy!) +- [for full tor anonymity launch this instead] `python zeronet.py --tor_proxy 127.0.0.1:9150 --tor_controller 127.0.0.1:9151 --tor always` +- navigate to http://127.0.0.1:43110 in your favourite browser! + +To build .exe + +- follow the same steps as above, but additionally +- `pip install pyinstaller` +- `pyinstaller -p src -p plugins --hidden-import merkletools --hidden-import lib.bencode_open --hidden-import Crypt.Crypt --hidden-import Db.DbQuery --hidden-import lib.subtl --hidden-import lib.subtl.subtl --hidden-import sockshandler --add-data "src;src" --add-data "plugins;plugins" --clean zeronet.py` +- dist/zeronet should contain working zeronet.exe! ## Current limitations -* ~~No torrent-like file splitting for big file support~~ (big file support added) -* ~~No more anonymous than Bittorrent~~ (built-in full Tor support added) -* File transactions are not compressed ~~or encrypted yet~~ (TLS encryption added) +* File transactions are not compressed * No private sites +* No DHT support +* No I2P support +* Centralized elements like zeroid (we're working on this!) +* No reliable spam protection (and on this too) +* Doesn't work directly from browser (one of the top priorities for mid-future) +* No data transparency +* No reproducible builds +* No on-disk encryption +* No reproducible builds (hence no builds beyond certain GNU/Linux distributions) ## How can I create a ZeroNet site? - * Click on **⋮** > **"Create new, empty site"** menu item on the site [ZeroHello](http://127.0.0.1:43110/1HeLLo4uzjaLetFx6NH3PMwFP3qbRbTf3D). + * Click on **⋮** > **"Create new, empty site"** menu item on the [dashboard](http://127.0.0.1:43110/191CazMVNaAcT9Y1zhkxd9ixMBPs59g2um/). * You will be **redirected** to a completely new site that is only modifiable by you! * You can find and modify your site's content in **data/[yoursiteaddress]** directory - * After the modifications open your site, drag the topright "0" button to left, then press **sign** and **publish** buttons on the bottom + * After the modifications open your site, drag the topright "0" button to the left, then press **sign and publish** button on the bottom Next steps: [ZeroNet Developer Documentation](https://zeronet.io/docs/site_development/getting_started/) -## Help keep this project alive +## Help this project stay alive + +### Become a maintainer + +We need more maintainers! Become one today! You don't need to know how to code, +there's a lot of other work to do. + +### Make builds for your platforms + +We need reproducible stand-alone builds for major platforms, as well as presense in various FLOSS +repositories. If you're using one of Linux distributions which don't have packages yet, why not make +a package for it or (if you don't know how) ask a maintainer now? + +### Fix bugs & add features + +We've decided to go ahead and make a perfect p2p web, so we need more help +implementing it. + +### Make your site/bring your content + +We know the documentation is lacking, but we try our best to support anyone +who wants to migrate. Don't hesitate to ask. + +### Use it and spread the word + +Make sure to tell people why do you use 0net and this fork in particular! People +need to know their alternatives. + +### Financially support maintainers + +This fork was created and maintained by @caryoscelus. You can +see ways to donate to them on https://caryoscelus.github.io/donate/ (or check +sidebar if you're reading this on github for more ways). As our team grows, we +will create team accounts on friendly crowdfunding platforms as well. + +If you want to make sure your donation is recognized as donation for this +project, there is a dedicated bitcoin address for that, too: +1Kjuw3reZvxRVNs27Gen7jPJYCn6LY7Fg6. And if you want to stay more anonymous and +private, a Monero wallet: +4AiYUcqVRH4C2CVr9zbBdkhRnJnHiJoypHEsq4N7mQziGUoosPCpPeg8SPr87nvwypaRzDgMHEbWWDekKtq8hm9LBmgcMzC + +If you want to donate in a different way, feel free to contact maintainer or +create an issue -- Bitcoin: 1QDhxQ6PraUZa21ET5fYUCPgdrwBomnFgX -- Paypal: https://zeronet.io/docs/help_zeronet/donate/ +# We're using GitHub under protest -### Sponsors +This project is currently hosted on GitHub. This is not ideal; GitHub is a +proprietary, trade-secret system that is not Free/Libre and Open Souce Software +(FLOSS). We are deeply concerned about using a proprietary system like GitHub +to develop our FLOSS project. We have an +[open issue](https://github.com/zeronet-conservancy/zeronet-conservancy/issues/89) +to track moving away from GitHub in the long term. We urge you to read about the +[Give up GitHub](https://GiveUpGitHub.org) campaign from +[the Software Freedom Conservancy](https://sfconservancy.org) to understand +some of the reasons why GitHub is not a good place to host FOSS projects. -* Better macOS/Safari compatibility made possible by [BrowserStack.com](https://www.browserstack.com) +If you are a contributor who personally has already quit using GitHub, feel +free to [check out from our mirror on notabug](https://notabug.org/caryoscelus/zeronet-conservancy) +and develop there or send git patches directly to project maintainer via +preffered [contact channel](https://caryoscelus.github.io/contacts/). -#### Thank you! +Any use of this project's code by GitHub Copilot, past or present, is done +without our permission. We do not consent to GitHub's use of this project's +code in Copilot. -* More info, help, changelog, zeronet sites: https://www.reddit.com/r/zeronet/ -* Come, chat with us: [#zeronet @ FreeNode](https://kiwiirc.com/client/irc.freenode.net/zeronet) or on [gitter](https://gitter.im/HelloZeroNet/ZeroNet) -* Email: hello@zeronet.io (PGP: [960F FF2D 6C14 5AA6 13E8 491B 5B63 BAE6 CB96 13AE](https://zeronet.io/files/tamas@zeronet.io_pub.asc)) +![Logo of the GiveUpGitHub campaign](https://sfconservancy.org/img/GiveUpGitHub.png) diff --git a/Vagrantfile b/Vagrantfile deleted file mode 100644 index 24fe0c45f..000000000 --- a/Vagrantfile +++ /dev/null @@ -1,45 +0,0 @@ -# -*- mode: ruby -*- -# vi: set ft=ruby : - -VAGRANTFILE_API_VERSION = "2" - -Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| - - #Set box - config.vm.box = "ubuntu/trusty64" - - #Do not check fo updates - config.vm.box_check_update = false - - #Add private network - config.vm.network "private_network", type: "dhcp" - - #Redirect ports - config.vm.network "forwarded_port", guest: 43110, host: 43110 - config.vm.network "forwarded_port", guest: 15441, host: 15441 - - #Sync folder using NFS if not windows - config.vm.synced_folder ".", "/vagrant", - :nfs => !Vagrant::Util::Platform.windows? - - #Virtal Box settings - config.vm.provider "virtualbox" do |vb| - # Don't boot with headless mode - #vb.gui = true - - # Set VM settings - vb.customize ["modifyvm", :id, "--memory", "512"] - vb.customize ["modifyvm", :id, "--cpus", 1] - end - - #Update system - config.vm.provision "shell", - inline: "sudo apt-get update -y && sudo apt-get upgrade -y" - - #Install deps - config.vm.provision "shell", - inline: "sudo apt-get install msgpack-python python-gevent python-pip python-dev -y" - config.vm.provision "shell", - inline: "sudo pip install msgpack --upgrade" - -end diff --git a/bootstrap.url b/bootstrap.url new file mode 100644 index 000000000..ec7a3944b --- /dev/null +++ b/bootstrap.url @@ -0,0 +1 @@ +https://github.com/zeronet-conservancy/zeronet-conservancy/releases/download/v0.7.10/data-default-2023-09-03.zip \ No newline at end of file diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 000000000..716138005 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,25 @@ +FROM python:3.12-alpine + +RUN apk --update --no-cache --no-progress add git gcc libffi-dev musl-dev make openssl g++ autoconf automake libtool + +RUN adduser -u 1600 -D service-0net + +USER service-0net:service-0net + +WORKDIR /home/service-0net + +COPY requirements.txt . + +RUN python3 -m pip install -r requirements.txt + +# the part below is updated with source updates + +COPY . . + +ENTRYPOINT python3 zeronet.py --ui_ip "*" --fileserver_port 26552 \ + --tor $TOR_ENABLED --tor_controller tor:$TOR_CONTROL_PORT \ + --tor_proxy tor:$TOR_SOCKS_PORT --tor_password $TOR_CONTROL_PASSWD + +CMD main + +EXPOSE 43110 26552 diff --git a/docker/debian.Dockerfile b/docker/debian.Dockerfile new file mode 100644 index 000000000..8507914b9 --- /dev/null +++ b/docker/debian.Dockerfile @@ -0,0 +1,26 @@ +FROM python:3.12-slim-bookworm + +RUN apt-get update +RUN apt-get -y install git openssl pkg-config libffi-dev python3-pip python3-dev build-essential libtool + +RUN useradd -u 1600 -m service-0net + +USER service-0net:service-0net + +WORKDIR /home/service-0net + +COPY requirements.txt . + +RUN python3 -m pip install -r requirements.txt + +# the part below is updated with source updates + +COPY . . + +ENTRYPOINT python3 zeronet.py --ui_ip "*" --fileserver_port 26552 \ + --tor $TOR_ENABLED --tor_controller tor:$TOR_CONTROL_PORT \ + --tor_proxy tor:$TOR_SOCKS_PORT --tor_password $TOR_CONTROL_PASSWD + +CMD main + +EXPOSE 43110 26552 diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml new file mode 100644 index 000000000..78a6908e2 --- /dev/null +++ b/docker/docker-compose.yml @@ -0,0 +1,55 @@ +version: '3' + +services: + tor: + tty: true + stdin_open: true + build: + context: .. + dockerfile: docker/tor.Dockerfile + networks: + - 0net-network + environment: &tor-environments + # since we are using tor internally, password doesn't really matter + TOR_CONTROL_PASSWD: some_password + TOR_SOCKS_PORT: 9050 + TOR_CONTROL_PORT: 9051 + + 0net-conservancy: + tty: true + stdin_open: true + build: + context: .. + dockerfile: docker/Dockerfile + networks: + - 0net-network + volumes: + # NOTE: this refers to docker/data.. + - ./data:/home/service-0net/data + ports: + - "26552:26552" + - "127.0.0.1:43110:43110" + depends_on: + - tor + environment: + TOR_ENABLED: enable + <<: *tor-environments + + # integrated container with tor + 0net-tor: + tty: true + stdin_open: true + build: + context: .. + dockerfile: docker/znctor.Dockerfile + networks: + - 0net-network + volumes: + # NOTE: this refers to docker/data.. + - ./data:/home/service-0net/data + ports: + - "26552:26552" + - "127.0.0.1:43110:43110" + +networks: + 0net-network: diff --git a/docker/tor.Dockerfile b/docker/tor.Dockerfile new file mode 100644 index 000000000..77fa00e5f --- /dev/null +++ b/docker/tor.Dockerfile @@ -0,0 +1,9 @@ +FROM alpine:3.18 + +RUN apk --update --no-cache --no-progress add tor + +USER tor + +CMD tor --SocksPort 0.0.0.0:${TOR_SOCKS_PORT} --ControlPort 0.0.0.0:${TOR_CONTROL_PORT} --HashedControlPassword $(tor --quiet --hash-password $TOR_CONTROL_PASSWD) + +EXPOSE $TOR_SOCKS_PORT $TOR_CONTROL_PORT diff --git a/docker/znctor.Dockerfile b/docker/znctor.Dockerfile new file mode 100644 index 000000000..152bca707 --- /dev/null +++ b/docker/znctor.Dockerfile @@ -0,0 +1,31 @@ +FROM python:3.12-alpine + +RUN apk --update --no-cache --no-progress add git gcc libffi-dev musl-dev make openssl g++ autoconf automake libtool +RUN apk add tor + +RUN echo "ControlPort 9051" >> /etc/tor/torrc +RUN echo "CookieAuthentication 1" >> /etc/tor/torrc + +RUN adduser -u 1600 -D service-0net + +USER service-0net:service-0net + +WORKDIR /home/service-0net + +COPY requirements.txt . + +RUN python3 -m pip install -r requirements.txt + +RUN echo "tor &" > start.sh +RUN echo "python3 zeronet.py --ui_ip '*' --fileserver_port 26552" >> start.sh +RUN chmod +x start.sh + +# the part below is updated with source updates + +COPY . . + +ENTRYPOINT ./start.sh + +CMD main + +EXPOSE 43110 26552 diff --git a/greet.py b/greet.py new file mode 100644 index 000000000..5f72dca20 --- /dev/null +++ b/greet.py @@ -0,0 +1,35 @@ +def grad(n): + s = 0x08 + r = 0xff + g = 0x00 + b = 0x00 + for i in range(n): + if r >= s and b < s: + r -= s + g += s + elif g >= s and r < s: + g -= s + b += s + elif b >= s and g < s: + b -= s + r += s + return f'#{r:02x}{g:02x}{b:02x}' + +def fancy_greet(version): + from rich.console import Console + from rich.text import Text + zc_msg = fr''' +||| . . _ _._|_ _. . . _ .__ _.. _. . __.. _ __. . +||| //\|/ |/_| | == / / \|/ |( /_||/ | | __||/ |/ \_| +||| \_/| |\_ |. \__\_/| |_) \_ | \/ |__|| |\__ _/ +||| +||| v{version} +''' + lns = zc_msg.split('\n') + console = Console() + for l in lns: + txt = Text(l) + txt.stylize('bold') + for i in range(len(l)): + txt.stylize(grad(i), i, i+1) + console.print(txt) diff --git a/plugins/AnnounceLocal/AnnounceLocalPlugin.py b/plugins/AnnounceLocal/AnnounceLocalPlugin.py index b92259665..8b6b490df 100644 --- a/plugins/AnnounceLocal/AnnounceLocalPlugin.py +++ b/plugins/AnnounceLocal/AnnounceLocalPlugin.py @@ -31,7 +31,7 @@ def __init__(self, server, listen_port): self.sender_info["peer_id"] = self.server.peer_id self.sender_info["port"] = self.server.port self.sender_info["broadcast_port"] = listen_port - self.sender_info["rev"] = config.rev + self.sender_info["rev"] = config.user_agent_rev self.known_peers = {} self.last_discover = 0 @@ -142,6 +142,6 @@ def stop(self): class ConfigPlugin(object): def createArguments(self): group = self.parser.add_argument_group("AnnounceLocal plugin") - group.add_argument('--broadcast_port', help='UDP broadcasting port for local peer discovery', default=1544, type=int, metavar='port') + group.add_argument('--broadcast-port', help='UDP broadcasting port for local peer discovery', default=1544, type=int, metavar='port') return super(ConfigPlugin, self).createArguments() diff --git a/plugins/AnnounceShare/AnnounceSharePlugin.py b/plugins/AnnounceShare/AnnounceSharePlugin.py index 057ce55a1..b350cf422 100644 --- a/plugins/AnnounceShare/AnnounceSharePlugin.py +++ b/plugins/AnnounceShare/AnnounceSharePlugin.py @@ -185,6 +185,6 @@ def portCheck(self, *args, **kwargs): class ConfigPlugin(object): def createArguments(self): group = self.parser.add_argument_group("AnnounceShare plugin") - group.add_argument('--working_shared_trackers_limit', help='Stop discovering new shared trackers after this number of shared trackers reached', default=5, type=int, metavar='limit') + group.add_argument('--working-shared-trackers-limit', help='Stop discovering new shared trackers after this number of shared trackers reached', default=5, type=int, metavar='limit') return super(ConfigPlugin, self).createArguments() diff --git a/plugins/AnnounceZero/AnnounceZeroPlugin.py b/plugins/AnnounceZero/AnnounceZeroPlugin.py index 623cd4b5e..d57190b2b 100644 --- a/plugins/AnnounceZero/AnnounceZeroPlugin.py +++ b/plugins/AnnounceZero/AnnounceZeroPlugin.py @@ -124,7 +124,7 @@ def announceTrackerZero(self, tracker_address, mode="start", num_want=10): sign = CryptRsa.sign(res["onion_sign_this"].encode("utf8"), self.site.connection_server.tor_manager.getPrivatekey(onion)) request["onion_signs"][publickey] = sign res = tracker_peer.request("announce", request) - if not res or "onion_sign_this" in res: + if not res: if full_announce: time_full_announced[tracker_address] = 0 raise AnnounceError("Announce onion address to failed: %s" % res) diff --git a/plugins/Benchmark/BenchmarkPlugin.py b/plugins/Benchmark/BenchmarkPlugin.py index fd6cacf35..193b46c2f 100644 --- a/plugins/Benchmark/BenchmarkPlugin.py +++ b/plugins/Benchmark/BenchmarkPlugin.py @@ -413,7 +413,7 @@ def createArguments(self): back = super(ConfigPlugin, self).createArguments() if self.getCmdlineValue("test") == "benchmark": self.test_parser.add_argument( - '--num_multipler', help='Benchmark run time multipler', + '--num-multipler', help='Benchmark run time multipler', default=1.0, type=float, metavar='num' ) self.test_parser.add_argument( @@ -422,7 +422,7 @@ def createArguments(self): ) elif self.getCmdlineValue("test") == "portChecker": self.test_parser.add_argument( - '--func_name', help='Name of open port checker function', + '--func-name', help='Name of open port checker function', default=None, metavar='func_name' ) return back diff --git a/plugins/Bigfile/BigfilePlugin.py b/plugins/Bigfile/BigfilePlugin.py index 78a27b05d..6fc8f43b7 100644 --- a/plugins/Bigfile/BigfilePlugin.py +++ b/plugins/Bigfile/BigfilePlugin.py @@ -837,7 +837,7 @@ def pooledNeedBigfile(inner_path, *args, **kwargs): class ConfigPlugin(object): def createArguments(self): group = self.parser.add_argument_group("Bigfile plugin") - group.add_argument('--autodownload_bigfile_size_limit', help='Also download bigfiles smaller than this limit if help distribute option is checked', default=10, metavar="MB", type=int) - group.add_argument('--bigfile_size_limit', help='Maximum size of downloaded big files', default=False, metavar="MB", type=int) + group.add_argument('--autodownload-bigfile-size-limit', help='Also download bigfiles smaller than this limit if help distribute option is checked', default=10, metavar="MB", type=int) + group.add_argument('--bigfile-size-limit', help='Maximum size of downloaded big files', default=False, metavar="MB", type=int) return super(ConfigPlugin, self).createArguments() diff --git a/plugins/ContentFilter/ContentFilterPlugin.py b/plugins/ContentFilter/ContentFilterPlugin.py index f2f84b497..c4d8bf3d1 100644 --- a/plugins/ContentFilter/ContentFilterPlugin.py +++ b/plugins/ContentFilter/ContentFilterPlugin.py @@ -38,7 +38,7 @@ def add(self, address, *args, **kwargs): block_details = None if block_details: - raise Exception("Site blocked: %s" % html.escape(block_details.get("reason", "unknown reason"))) + raise Exception(f'Site blocked: {html.escape(block_details.get("reason", "unknown reason"))}') else: return super(SiteManagerPlugin, self).add(address, *args, **kwargs) @@ -56,14 +56,11 @@ def cbMuteAdd(self, to, auth_address, cert_user_id, reason): @flag.no_multiuser def actionMuteAdd(self, to, auth_address, cert_user_id, reason): - if "ADMIN" in self.getPermissions(to): - self.cbMuteAdd(to, auth_address, cert_user_id, reason) - else: - self.cmd( - "confirm", - [_["Hide all content from %s?"] % html.escape(cert_user_id), _["Mute"]], - lambda res: self.cbMuteAdd(to, auth_address, cert_user_id, reason) - ) + self.cmd( + "prompt", + [_["Remove all content from %s?"] % html.escape(cert_user_id), reason, _["Mute"]], + lambda res: self.cbMuteAdd(to, auth_address, cert_user_id, res if res else reason) + ) @flag.no_multiuser def cbMuteRemove(self, to, auth_address): @@ -207,18 +204,40 @@ def updateDbFile(self, inner_path, file=None, cur=None): # Check if any of the adresses are in the mute list for auth_address in matches: if filter_storage.isMuted(auth_address): - self.log.debug("Mute match: %s, ignoring %s" % (auth_address, inner_path)) + self.log.debug(f'Mute match: {auth_address}, ignoring {inner_path}') return False return super(SiteStoragePlugin, self).updateDbFile(inner_path, file=file, cur=cur) def onUpdated(self, inner_path, file=None): - file_path = "%s/%s" % (self.site.address, inner_path) - if file_path in filter_storage.file_content["includes"]: - self.log.debug("Filter file updated: %s" % inner_path) + file_path = f'{self.site.address}/{inner_path}' + if file_path in filter_storage.file_content['includes']: + self.log.debug('Filter file updated: {inner_path}') filter_storage.includeUpdateAll() return super(SiteStoragePlugin, self).onUpdated(inner_path, file=file) +@PluginManager.registerTo("Site") +class SitePlugin(object): + def needFile(self, inner_path, update=False, blocking=True, peer=None, priority=0): + self.log.debug(f'needFile {inner_path}') + matches = re.findall('/(1[A-Za-z0-9]{26,35})/', inner_path) + for auth_address in matches: + if filter_storage.isMuted(auth_address): + self.log.info(f'Mute match in Site.needFile: {auth_address}, ignoring {inner_path}') + return False + return super(SitePlugin, self).needFile(inner_path, update, blocking, peer, priority) + +@PluginManager.registerTo("FileRequest") +class FileRequestPlugin: + def actionUpdate(self, params): + inner_path = params.get('inner_path', '') + matches = re.findall('/(1[A-Za-z0-9]{26,35})/', inner_path) + for auth_address in matches: + if filter_storage.isMuted(auth_address): + self.log.info(f'Mute match in FileRequest.actionUpdate: {auth_address}, ignoring {inner_path}') + self.response({'ok': f'Thanks, file {inner_path} updated!'}) + return False + return super(FileRequestPlugin, self).actionUpdate(params) @PluginManager.registerTo("UiRequest") class UiRequestPlugin(object): diff --git a/plugins/ContentFilter/ContentFilterStorage.py b/plugins/ContentFilter/ContentFilterStorage.py index 289ec2a98..2ad378d6b 100644 --- a/plugins/ContentFilter/ContentFilterStorage.py +++ b/plugins/ContentFilter/ContentFilterStorage.py @@ -158,7 +158,7 @@ def changeDbs(self, auth_address, action): dir_inner_path = helper.getDirname(row["inner_path"]) for file_name in site.storage.walk(dir_inner_path): if action == "remove": - site.storage.onUpdated(dir_inner_path + file_name, False) + site.storage.delete(dir_inner_path + file_name) else: site.storage.onUpdated(dir_inner_path + file_name) site.onFileDone(dir_inner_path + file_name) diff --git a/plugins/FilePack/FilePackPlugin.py b/plugins/FilePack/FilePackPlugin.py index a095c6d45..1c931316a 100644 --- a/plugins/FilePack/FilePackPlugin.py +++ b/plugins/FilePack/FilePackPlugin.py @@ -45,7 +45,7 @@ def actionSiteMedia(self, path, **kwargs): file_obj = None path_parts = self.parsePath(path) file_path = "%s/%s/%s" % (config.data_dir, path_parts["address"], path_parts["inner_path"]) - match = re.match("^(.*\.(?:tar.gz|zip))/(.*)", file_path) + match = re.match(r"^(.*\.(?:tar.gz|zip))/(.*)", file_path) archive_path, path_within = match.groups() if archive_path not in archive_cache: site = self.server.site_manager.get(path_parts["address"]) @@ -99,7 +99,7 @@ def streamFile(self, file): class SiteStoragePlugin(object): def isFile(self, inner_path): if ".zip/" in inner_path or ".tar.gz/" in inner_path: - match = re.match("^(.*\.(?:tar.gz|zip))/(.*)", inner_path) + match = re.match(r"^(.*\.(?:tar.gz|zip))/(.*)", inner_path) archive_inner_path, path_within = match.groups() return super(SiteStoragePlugin, self).isFile(archive_inner_path) else: @@ -127,7 +127,7 @@ def openArchive(self, inner_path): def walk(self, inner_path, *args, **kwags): if ".zip" in inner_path or ".tar.gz" in inner_path: - match = re.match("^(.*\.(?:tar.gz|zip))(.*)", inner_path) + match = re.match(r"^(.*\.(?:tar.gz|zip))(.*)", inner_path) archive_inner_path, path_within = match.groups() archive = self.openArchive(archive_inner_path) path_within = path_within.lstrip("/") @@ -151,7 +151,7 @@ def walk(self, inner_path, *args, **kwags): def list(self, inner_path, *args, **kwags): if ".zip" in inner_path or ".tar.gz" in inner_path: - match = re.match("^(.*\.(?:tar.gz|zip))(.*)", inner_path) + match = re.match(r"^(.*\.(?:tar.gz|zip))(.*)", inner_path) archive_inner_path, path_within = match.groups() archive = self.openArchive(archive_inner_path) path_within = path_within.lstrip("/") @@ -178,7 +178,7 @@ def list(self, inner_path, *args, **kwags): def read(self, inner_path, mode="rb", **kwargs): if ".zip/" in inner_path or ".tar.gz/" in inner_path: - match = re.match("^(.*\.(?:tar.gz|zip))(.*)", inner_path) + match = re.match(r"^(.*\.(?:tar.gz|zip))(.*)", inner_path) archive_inner_path, path_within = match.groups() archive = self.openArchive(archive_inner_path) path_within = path_within.lstrip("/") diff --git a/plugins/OptionalManager/OptionalManagerPlugin.py b/plugins/OptionalManager/OptionalManagerPlugin.py index f01fab652..420f9e050 100644 --- a/plugins/OptionalManager/OptionalManagerPlugin.py +++ b/plugins/OptionalManager/OptionalManagerPlugin.py @@ -247,7 +247,7 @@ def fileDone(self, inner_path): class ConfigPlugin(object): def createArguments(self): group = self.parser.add_argument_group("OptionalManager plugin") - group.add_argument('--optional_limit', help='Limit total size of optional files', default="10%", metavar="GB or free space %") - group.add_argument('--optional_limit_exclude_minsize', help='Exclude files larger than this limit from optional size limit calculation', default=20, metavar="MB", type=int) + group.add_argument('--optional-limit', help='Limit total size of optional files', default="10%", metavar="GB or free space %") + group.add_argument('--optional-limit-exclude-minsize', help='Exclude files larger than this limit from optional size limit calculation', default=20, metavar="MB", type=int) return super(ConfigPlugin, self).createArguments() diff --git a/plugins/Sidebar/ConsolePlugin.py b/plugins/Sidebar/ConsolePlugin.py index 15f6a1bac..46cd9acaa 100644 --- a/plugins/Sidebar/ConsolePlugin.py +++ b/plugins/Sidebar/ConsolePlugin.py @@ -14,8 +14,7 @@ def __init__(self, stream_id, ui_websocket, filter): self.ui_websocket = ui_websocket if filter: - if not SafeRe.isSafePattern(filter): - raise Exception("Not a safe prex pattern") + SafeRe.guard(filter) self.filter_re = re.compile(".*" + filter) else: self.filter_re = None @@ -55,7 +54,7 @@ def actionConsoleLogRead(self, to, filter=None, read_size=32 * 1024, limit=500): pos_start = log_file.tell() lines = [] if filter: - assert SafeRe.isSafePattern(filter) + SafeRe.guard(filter) filter_re = re.compile(".*" + filter) last_match = False diff --git a/plugins/Sidebar/SidebarPlugin.py b/plugins/Sidebar/SidebarPlugin.py index 4ecca75a1..b8c5f0f3a 100644 --- a/plugins/Sidebar/SidebarPlugin.py +++ b/plugins/Sidebar/SidebarPlugin.py @@ -12,6 +12,7 @@ import gevent import util +import main from Config import config from Plugin import PluginManager from Debug import Debug @@ -115,11 +116,11 @@ def sidebarRenderPeerStats(self, body, site): local_html = "" peer_ips = [peer.key for peer in site.getConnectablePeers(20, allow_private=False)] + self_onion = main.file_server.tor_manager.site_onions.get(site.address, None) + if self_onion is not None: + peer_ips.append(self_onion+'.onion') peer_ips.sort(key=lambda peer_ip: ".onion:" in peer_ip) - copy_link = "http://127.0.0.1:43110/%s/?zeronet_peers=%s" % ( - site.content_manager.contents.get("content.json", {}).get("domain", site.address), - ",".join(peer_ips) - ) + copy_link = f'http://127.0.0.1:43110/{site.address}/?zeronet_peers={",".join(peer_ips)}' body.append(_("""
  • @@ -175,6 +176,7 @@ def sidebarRenderFileStats(self, body, site): {_[Files]} {_[Browse files]} + {_[Open site directory]} {_[Save as .zip]} @@ -414,43 +416,87 @@ def sidebarRenderControls(self, body, site): class_pause = "hidden" class_resume = "" + dashboard = config.homepage + dsite = self.user.sites.get(dashboard, None) + if not dsite: + print('No dashboard found, cannot favourite') + class_favourite = "hidden" + class_unfavourite = "hidden" + elif not dsite.get('settings', {}).get('favorite_sites', {}).get(self.site.address, False): + class_favourite = "" + class_unfavourite = "hidden" + else: + class_favourite = "hidden" + class_unfavourite = "" + body.append(_("""
  • {_[Update]} {_[Pause]} + {_[Favourite]} + {_[Unfavourite]} {_[Resume]} {_[Delete]}
  • """)) - donate_key = site.content_manager.contents.get("content.json", {}).get("donate", True) site_address = self.site.address body.append(_("""

  • {site_address} - """)) - if donate_key == False or donate_key == "": - pass - elif (type(donate_key) == str or type(donate_key) == str) and len(donate_key) > 0: - body.append(_("""
  • + """)) + donate_generic = site.content_manager.contents.get("content.json", {}).get("donate", None) or site.content_manager.contents.get("content.json", {}).get("donate-generic", None) + donate_btc = site.content_manager.contents.get("content.json", {}).get("donate-btc", None) + donate_xmr = site.content_manager.contents.get("content.json", {}).get("donate-xmr", None) + donate_ada = site.content_manager.contents.get("content.json", {}).get("donate-ada", None) + donate_enabled = bool(donate_generic or donate_btc or donate_xmr or donate_ada) + if donate_enabled: + body.append(_("""
  • -
    -
    - {donate_key} +
    """)) - else: + if donate_generic: body.append(_(""" - {_[Donate]} +
    + {donate_generic} +
    """)) - body.append(_(""" -
    + if donate_btc: + body.append(_(""" +
    + {donate_btc}
    +
    + + """)) + if donate_xmr: + body.append(_(""" +
    + {donate_xmr}
    +
    + + """)) + if donate_ada: + body.append(_(""" +
    + {donate_ada}
    +
    + + """)) + if donate_enabled: + body.append(_("""
  • - """)) + """)) def sidebarRenderOwnedCheckbox(self, body, site): if self.site.settings["own"]: @@ -556,9 +602,9 @@ def actionSidebarGetHtmlTag(self, to): def downloadGeoLiteDb(self, db_path): import gzip import shutil - from util import helper + import requests - if config.offline: + if config.offline or config.tor == 'always': return False self.log.info("Downloading GeoLite2 City database...") @@ -571,19 +617,18 @@ def downloadGeoLiteDb(self, db_path): downloadl_err = None try: # Download - response = helper.httpRequest(db_url) - data_size = response.getheader('content-length') + response = requests.get(db_url, stream=True) + data_size = response.headers.get('content-length') + if data_size is None: + data.write(response.content) + data_size = int(data_size) data_recv = 0 data = io.BytesIO() - while True: - buff = response.read(1024 * 512) - if not buff: - break + for buff in response.iter_content(chunk_size=1024 * 512): data.write(buff) data_recv += 1024 * 512 - if data_size: - progress = int(float(data_recv) / int(data_size) * 100) - self.cmd("progress", ["geolite-info", _["Downloading GeoLite2 City database (one time only, ~20MB)..."], progress]) + progress = int(float(data_recv) / data_size * 100) + self.cmd("progress", ["geolite-info", _["Downloading GeoLite2 City database (one time only, ~20MB)..."], progress]) self.log.info("GeoLite2 City database downloaded (%s bytes), unpacking..." % data.tell()) data.seek(0) @@ -738,9 +783,6 @@ def actionSidebarGetPeers(self, to): @flag.admin @flag.no_multiuser def actionSiteSetOwned(self, to, owned): - if self.site.address == config.updatesite: - return {"error": "You can't change the ownership of the updater site"} - self.site.settings["own"] = bool(owned) self.site.updateWebsocket(owned=owned) return "ok" diff --git a/plugins/Sidebar/languages/pl.json b/plugins/Sidebar/languages/pl.json index 932685078..740aaafd2 100644 --- a/plugins/Sidebar/languages/pl.json +++ b/plugins/Sidebar/languages/pl.json @@ -1,9 +1,13 @@ { + "Total peers": "Łącznie użytkowników równorzędnych", + "Connected peers": "Łącznie połączonych użytkowników równorzędnych", "Peers": "Użytkownicy równorzędni", "Connected": "Połączony", - "Connectable": "Możliwy do podłączenia", + "Connectable": "Do połączenia", "Connectable peers": "Połączeni użytkownicy równorzędni", + "Copy to clipboard": "Kopiuj do schowka", + "Data transfer": "Transfer danych", "Received": "Odebrane", "Received bytes": "Odebrany bajty", @@ -11,7 +15,7 @@ "Sent bytes": "Wysłane bajty", "Files": "Pliki", - "Total": "Sumarycznie", + "Total": "Łącznie", "Image": "Obraz", "Other": "Inne", "User data": "Dane użytkownika", @@ -36,6 +40,10 @@ "Identity address": "Adres identyfikacyjny", "Change": "Zmień", + "Needs to be updated": "Muszą zostać zaktualizowane", + "Download previous files": "Pobierz wszystkie pliki", + "Help distribute added optional files": "Pomóż rozpowszechniać wszystkie pliki", + "Auto download big file size limit": "Limit dla automatycznego pobierania dużych plików", "Site control": "Kontrola strony", "Update": "Zaktualizuj", @@ -56,11 +64,15 @@ "Site title": "Tytuł strony", "Site description": "Opis strony", "Save site settings": "Zapisz ustawienia strony", + "Save as .zip": "Zapisz jako .zip", + "Browse files": "Przeglądaj pliki", + "Add saved private key": "Dodaj klucz prywatny", "Content publishing": "Publikowanie treści", "Choose": "Wybierz", "Sign": "Podpisz", "Publish": "Opublikuj", + "Sign and publish": "Zapisz i opublikuj", "This function is disabled on this proxy": "Ta funkcja jest zablokowana w tym proxy", "GeoLite2 City database download error: {}!
    Please download manually and unpack to data dir:
    {}": "Błąd ściągania bazy danych GeoLite2 City: {}!
    Proszę ściągnąć ją recznie i wypakować do katalogu danych:
    {}", diff --git a/plugins/Sidebar/media/Class.coffee b/plugins/Sidebar/media/Class.coffee deleted file mode 100644 index d62ab25cb..000000000 --- a/plugins/Sidebar/media/Class.coffee +++ /dev/null @@ -1,23 +0,0 @@ -class Class - trace: true - - log: (args...) -> - return unless @trace - return if typeof console is 'undefined' - args.unshift("[#{@.constructor.name}]") - console.log(args...) - @ - - logStart: (name, args...) -> - return unless @trace - @logtimers or= {} - @logtimers[name] = +(new Date) - @log "#{name}", args..., "(started)" if args.length > 0 - @ - - logEnd: (name, args...) -> - ms = +(new Date)-@logtimers[name] - @log "#{name}", args..., "(Done in #{ms}ms)" - @ - -window.Class = Class \ No newline at end of file diff --git a/plugins/Sidebar/media/Console.coffee b/plugins/Sidebar/media/Console.coffee deleted file mode 100644 index d5a833461..000000000 --- a/plugins/Sidebar/media/Console.coffee +++ /dev/null @@ -1,201 +0,0 @@ -class Console extends Class - constructor: (@sidebar) -> - @tag = null - @opened = false - @filter = null - @tab_types = [ - {title: "All", filter: ""}, - {title: "Info", filter: "INFO"}, - {title: "Warning", filter: "WARNING"}, - {title: "Error", filter: "ERROR"} - ] - @read_size = 32 * 1024 - @tab_active = "" - #@filter = @sidebar.wrapper.site_info.address_short - handleMessageWebsocket_original = @sidebar.wrapper.handleMessageWebsocket - @sidebar.wrapper.handleMessageWebsocket = (message) => - if message.cmd == "logLineAdd" and message.params.stream_id == @stream_id - @addLines(message.params.lines) - else - handleMessageWebsocket_original(message) - - $(window).on "hashchange", => - if window.top.location.hash.startsWith("#ZeroNet:Console") - @open() - - if window.top.location.hash.startsWith("#ZeroNet:Console") - setTimeout (=> @open()), 10 - - createHtmltag: -> - if not @container - @container = $(""" -
    -
    -
    -
    -
    Loading...
    -
    -
    -
    - -
    -
    -
    - - """) - @text = @container.find(".console-text") - @text_elem = @text[0] - @tabs = @container.find(".console-tabs") - - @text.on "mousewheel", (e) => # Stop animation on manual scrolling - if e.originalEvent.deltaY < 0 - @text.stop() - RateLimit 300, @checkTextIsBottom - - @text.is_bottom = true - - @container.appendTo(document.body) - @tag = @container.find(".console") - for tab_type in @tab_types - tab = $("", {href: "#", "data-filter": tab_type.filter, "data-title": tab_type.title}).text(tab_type.title) - if tab_type.filter == @tab_active - tab.addClass("active") - tab.on("click", @handleTabClick) - if window.top.location.hash.endsWith(tab_type.title) - @log "Triggering click on", tab - tab.trigger("click") - @tabs.append(tab) - - @container.on "mousedown touchend touchcancel", (e) => - if e.target != e.currentTarget - return true - @log "closing" - if $(document.body).hasClass("body-console") - @close() - return true - - @loadConsoleText() - - checkTextIsBottom: => - @text.is_bottom = Math.round(@text_elem.scrollTop + @text_elem.clientHeight) >= @text_elem.scrollHeight - 15 - - toColor: (text, saturation=60, lightness=70) -> - hash = 0 - for i in [0..text.length-1] - hash += text.charCodeAt(i)*i - hash = hash % 1777 - return "hsl(" + (hash % 360) + ",#{saturation}%,#{lightness}%)"; - - formatLine: (line) => - match = line.match(/(\[.*?\])[ ]+(.*?)[ ]+(.*?)[ ]+(.*)/) - if not match - return line.replace(/\/g, ">") - - [line, added, level, module, text] = line.match(/(\[.*?\])[ ]+(.*?)[ ]+(.*?)[ ]+(.*)/) - added = "#{added}" - level = "#{level}" - module = "#{module}" - - text = text.replace(/(Site:[A-Za-z0-9\.]+)/g, "$1") - text = text.replace(/\/g, ">") - #text = text.replace(/( [0-9\.]+(|s|ms))/g, "$1") - return "#{added} #{level} #{module} #{text}" - - - addLines: (lines, animate=true) => - html_lines = [] - @logStart "formatting" - for line in lines - html_lines.push @formatLine(line) - @logEnd "formatting" - @logStart "adding" - @text.append(html_lines.join("
    ") + "
    ") - @logEnd "adding" - if @text.is_bottom and animate - @text.stop().animate({scrollTop: @text_elem.scrollHeight - @text_elem.clientHeight + 1}, 600, 'easeInOutCubic') - - - loadConsoleText: => - @sidebar.wrapper.ws.cmd "consoleLogRead", {filter: @filter, read_size: @read_size}, (res) => - @text.html("") - pos_diff = res["pos_end"] - res["pos_start"] - size_read = Math.round(pos_diff/1024) - size_total = Math.round(res['pos_end']/1024) - @text.append("

    ") - @text.append("Displaying #{res.lines.length} of #{res.num_found} lines found in the last #{size_read}kB of the log file. (#{size_total}kB total)
    ") - @addLines res.lines, false - @text_elem.scrollTop = @text_elem.scrollHeight - if @stream_id - @sidebar.wrapper.ws.cmd "consoleLogStreamRemove", {stream_id: @stream_id} - @sidebar.wrapper.ws.cmd "consoleLogStream", {filter: @filter}, (res) => - @stream_id = res.stream_id - - close: => - window.top.location.hash = "" - @sidebar.move_lock = "y" - @sidebar.startDrag() - @sidebar.stopDrag() - - open: => - @sidebar.startDrag() - @sidebar.moved("y") - @sidebar.fixbutton_targety = @sidebar.page_height - @sidebar.fixbutton_inity - 50 - @sidebar.stopDrag() - - onOpened: => - @sidebar.onClosed() - @log "onOpened" - - onClosed: => - $(document.body).removeClass("body-console") - if @stream_id - @sidebar.wrapper.ws.cmd "consoleLogStreamRemove", {stream_id: @stream_id} - - cleanup: => - if @container - @container.remove() - @container = null - - stopDragY: => - # Animate sidebar and iframe - if @sidebar.fixbutton_targety == @sidebar.fixbutton_inity - # Closed - targety = 0 - @opened = false - else - # Opened - targety = @sidebar.fixbutton_targety - @sidebar.fixbutton_inity - @onOpened() - @opened = true - - # Revent sidebar transitions - if @tag - @tag.css("transition", "0.5s ease-out") - @tag.css("transform", "translateY(#{targety}px)").one transitionEnd, => - @tag.css("transition", "") - if not @opened - @cleanup() - # Revert body transformations - @log "stopDragY", "opened:", @opened, targety - if not @opened - @onClosed() - - changeFilter: (filter) => - @filter = filter - if @filter == "" - @read_size = 32 * 1024 - else - @read_size = 5 * 1024 * 1024 - @loadConsoleText() - - handleTabClick: (e) => - elem = $(e.currentTarget) - @tab_active = elem.data("filter") - $("a", @tabs).removeClass("active") - elem.addClass("active") - @changeFilter(@tab_active) - window.top.location.hash = "#ZeroNet:Console:" + elem.data("title") - return false - -window.Console = Console diff --git a/plugins/Sidebar/media/Menu.coffee b/plugins/Sidebar/media/Menu.coffee deleted file mode 100644 index 3e19fd9f0..000000000 --- a/plugins/Sidebar/media/Menu.coffee +++ /dev/null @@ -1,49 +0,0 @@ -class Menu - constructor: (@button) -> - @elem = $(".menu.template").clone().removeClass("template") - @elem.appendTo("body") - @items = [] - - show: -> - if window.visible_menu and window.visible_menu.button[0] == @button[0] # Same menu visible then hide it - window.visible_menu.hide() - @hide() - else - button_pos = @button.offset() - left = button_pos.left - @elem.css({"top": button_pos.top+@button.outerHeight(), "left": left}) - @button.addClass("menu-active") - @elem.addClass("visible") - if @elem.position().left + @elem.width() + 20 > window.innerWidth - @elem.css("left", window.innerWidth - @elem.width() - 20) - if window.visible_menu then window.visible_menu.hide() - window.visible_menu = @ - - - hide: -> - @elem.removeClass("visible") - @button.removeClass("menu-active") - window.visible_menu = null - - - addItem: (title, cb) -> - item = $(".menu-item.template", @elem).clone().removeClass("template") - item.html(title) - item.on "click", => - if not cb(item) - @hide() - return false - item.appendTo(@elem) - @items.push item - return item - - - log: (args...) -> - console.log "[Menu]", args... - -window.Menu = Menu - -# Hide menu on outside click -$("body").on "click", (e) -> - if window.visible_menu and e.target != window.visible_menu.button[0] and $(e.target).parent()[0] != window.visible_menu.elem[0] - window.visible_menu.hide() diff --git a/plugins/Sidebar/media/Prototypes.coffee b/plugins/Sidebar/media/Prototypes.coffee deleted file mode 100644 index a9edd255e..000000000 --- a/plugins/Sidebar/media/Prototypes.coffee +++ /dev/null @@ -1,9 +0,0 @@ -String::startsWith = (s) -> @[...s.length] is s -String::endsWith = (s) -> s is '' or @[-s.length..] is s -String::capitalize = -> if @.length then @[0].toUpperCase() + @.slice(1) else "" -String::repeat = (count) -> new Array( count + 1 ).join(@) - -window.isEmpty = (obj) -> - for key of obj - return false - return true diff --git a/plugins/Sidebar/media/RateLimit.coffee b/plugins/Sidebar/media/RateLimit.coffee deleted file mode 100644 index 17c67433f..000000000 --- a/plugins/Sidebar/media/RateLimit.coffee +++ /dev/null @@ -1,14 +0,0 @@ -limits = {} -call_after_interval = {} -window.RateLimit = (interval, fn) -> - if not limits[fn] - call_after_interval[fn] = false - fn() # First call is not delayed - limits[fn] = setTimeout (-> - if call_after_interval[fn] - fn() - delete limits[fn] - delete call_after_interval[fn] - ), interval - else # Called within iterval, delay the call - call_after_interval[fn] = true diff --git a/plugins/Sidebar/media/Sidebar.coffee b/plugins/Sidebar/media/Sidebar.coffee deleted file mode 100644 index 57d36eac3..000000000 --- a/plugins/Sidebar/media/Sidebar.coffee +++ /dev/null @@ -1,644 +0,0 @@ -class Sidebar extends Class - constructor: (@wrapper) -> - @tag = null - @container = null - @opened = false - @width = 410 - @console = new Console(@) - @fixbutton = $(".fixbutton") - @fixbutton_addx = 0 - @fixbutton_addy = 0 - @fixbutton_initx = 0 - @fixbutton_inity = 15 - @fixbutton_targetx = 0 - @move_lock = null - @page_width = $(window).width() - @page_height = $(window).height() - @frame = $("#inner-iframe") - @initFixbutton() - @dragStarted = 0 - @globe = null - @preload_html = null - - @original_set_site_info = @wrapper.setSiteInfo # We going to override this, save the original - - # Start in opened state for debugging - if window.top.location.hash == "#ZeroNet:OpenSidebar" - @startDrag() - @moved("x") - @fixbutton_targetx = @fixbutton_initx - @width - @stopDrag() - - - initFixbutton: -> - - # Detect dragging - @fixbutton.on "mousedown touchstart", (e) => - if e.button > 0 # Right or middle click - return - e.preventDefault() - - # Disable previous listeners - @fixbutton.off "click touchend touchcancel" - - # Make sure its not a click - @dragStarted = (+ new Date) - - # Fullscreen drag bg to capture mouse events over iframe - $(".drag-bg").remove() - $("
    ").appendTo(document.body) - - $("body").one "mousemove touchmove", (e) => - mousex = e.pageX - mousey = e.pageY - if not mousex - mousex = e.originalEvent.touches[0].pageX - mousey = e.originalEvent.touches[0].pageY - - @fixbutton_addx = @fixbutton.offset().left - mousex - @fixbutton_addy = @fixbutton.offset().top - mousey - @startDrag() - @fixbutton.parent().on "click touchend touchcancel", (e) => - if (+ new Date) - @dragStarted < 100 - window.top.location = @fixbutton.find(".fixbutton-bg").attr("href") - @stopDrag() - @resized() - $(window).on "resize", @resized - - resized: => - @page_width = $(window).width() - @page_height = $(window).height() - @fixbutton_initx = @page_width - 75 # Initial x position - if @opened - @fixbutton.css - left: @fixbutton_initx - @width - else - @fixbutton.css - left: @fixbutton_initx - - # Start dragging the fixbutton - startDrag: -> - #@move_lock = "x" # Temporary until internals not finished - @log "startDrag", @fixbutton_initx, @fixbutton_inity - @fixbutton_targetx = @fixbutton_initx # Fallback x position - @fixbutton_targety = @fixbutton_inity # Fallback y position - - @fixbutton.addClass("dragging") - - # IE position wrap fix - if navigator.userAgent.indexOf('MSIE') != -1 or navigator.appVersion.indexOf('Trident/') > 0 - @fixbutton.css("pointer-events", "none") - - # Don't go to homepage - @fixbutton.one "click", (e) => - @stopDrag() - @fixbutton.removeClass("dragging") - moved_x = Math.abs(@fixbutton.offset().left - @fixbutton_initx) - moved_y = Math.abs(@fixbutton.offset().top - @fixbutton_inity) - if moved_x > 5 or moved_y > 10 - # If moved more than some pixel the button then don't go to homepage - e.preventDefault() - - # Animate drag - @fixbutton.parents().on "mousemove touchmove", @animDrag - @fixbutton.parents().on "mousemove touchmove" ,@waitMove - - # Stop dragging listener - @fixbutton.parents().one "mouseup touchend touchcancel", (e) => - e.preventDefault() - @stopDrag() - - - # Wait for moving the fixbutton - waitMove: (e) => - document.body.style.perspective = "1000px" - document.body.style.height = "100%" - document.body.style.willChange = "perspective" - document.documentElement.style.height = "100%" - #$(document.body).css("backface-visibility", "hidden").css("perspective", "1000px").css("height", "900px") - # $("iframe").css("backface-visibility", "hidden") - - moved_x = Math.abs(parseInt(@fixbutton[0].style.left) - @fixbutton_targetx) - moved_y = Math.abs(parseInt(@fixbutton[0].style.top) - @fixbutton_targety) - if moved_x > 5 and (+ new Date) - @dragStarted + moved_x > 50 - @moved("x") - @fixbutton.stop().animate {"top": @fixbutton_inity}, 1000 - @fixbutton.parents().off "mousemove touchmove" ,@waitMove - - else if moved_y > 5 and (+ new Date) - @dragStarted + moved_y > 50 - @moved("y") - @fixbutton.parents().off "mousemove touchmove" ,@waitMove - - moved: (direction) -> - @log "Moved", direction - @move_lock = direction - if direction == "y" - $(document.body).addClass("body-console") - return @console.createHtmltag() - @createHtmltag() - $(document.body).addClass("body-sidebar") - @container.on "mousedown touchend touchcancel", (e) => - if e.target != e.currentTarget - return true - @log "closing" - if $(document.body).hasClass("body-sidebar") - @close() - return true - - $(window).off "resize" - $(window).on "resize", => - $(document.body).css "height", $(window).height() - @scrollable() - @resized() - - # Override setsiteinfo to catch changes - @wrapper.setSiteInfo = (site_info) => - @setSiteInfo(site_info) - @original_set_site_info.apply(@wrapper, arguments) - - # Preload world.jpg - img = new Image(); - img.src = "/uimedia/globe/world.jpg"; - - setSiteInfo: (site_info) -> - RateLimit 1500, => - @updateHtmlTag() - RateLimit 30000, => - @displayGlobe() - - # Create the sidebar html tag - createHtmltag: -> - @when_loaded = $.Deferred() - if not @container - @container = $(""" - - """) - @container.appendTo(document.body) - @tag = @container.find(".sidebar") - @updateHtmlTag() - @scrollable = window.initScrollable() - - - updateHtmlTag: -> - if @preload_html - @setHtmlTag(@preload_html) - @preload_html = null - else - @wrapper.ws.cmd "sidebarGetHtmlTag", {}, @setHtmlTag - - setHtmlTag: (res) => - if @tag.find(".content").children().length == 0 # First update - @log "Creating content" - @container.addClass("loaded") - morphdom(@tag.find(".content")[0], '
    '+res+'
    ') - # @scrollable() - @when_loaded.resolve() - - else # Not first update, patch the html to keep unchanged dom elements - morphdom @tag.find(".content")[0], '
    '+res+'
    ', { - onBeforeMorphEl: (from_el, to_el) -> # Ignore globe loaded state - if from_el.className == "globe" or from_el.className.indexOf("noupdate") >= 0 - return false - else - return true - } - - # Save and forget privatekey for site signing - @tag.find("#privatekey-add").off("click, touchend").on "click touchend", (e) => - @wrapper.displayPrompt "Enter your private key:", "password", "Save", "", (privatekey) => - @wrapper.ws.cmd "userSetSitePrivatekey", [privatekey], (res) => - @wrapper.notifications.add "privatekey", "done", "Private key saved for site signing", 5000 - return false - - @tag.find("#privatekey-forget").off("click, touchend").on "click touchend", (e) => - @wrapper.displayConfirm "Remove saved private key for this site?", "Forget", (res) => - if not res - return false - @wrapper.ws.cmd "userSetSitePrivatekey", [""], (res) => - @wrapper.notifications.add "privatekey", "done", "Saved private key removed", 5000 - return false - - # Use requested address for browse files urls - @tag.find("#browse-files").attr("href", document.location.pathname.replace(/(\/.*?(\/|$)).*$/, "/list$1")) - - - - animDrag: (e) => - mousex = e.pageX - mousey = e.pageY - if not mousex and e.originalEvent.touches - mousex = e.originalEvent.touches[0].pageX - mousey = e.originalEvent.touches[0].pageY - - overdrag = @fixbutton_initx - @width - mousex - if overdrag > 0 # Overdragged - overdrag_percent = 1 + overdrag/300 - mousex = (mousex + (@fixbutton_initx-@width)*overdrag_percent)/(1+overdrag_percent) - targetx = @fixbutton_initx - mousex - @fixbutton_addx - targety = @fixbutton_inity - mousey - @fixbutton_addy - - if @move_lock == "x" - targety = @fixbutton_inity - else if @move_lock == "y" - targetx = @fixbutton_initx - - if not @move_lock or @move_lock == "x" - @fixbutton[0].style.left = (mousex + @fixbutton_addx) + "px" - if @tag - @tag[0].style.transform = "translateX(#{0 - targetx}px)" - - if not @move_lock or @move_lock == "y" - @fixbutton[0].style.top = (mousey + @fixbutton_addy) + "px" - if @console.tag - @console.tag[0].style.transform = "translateY(#{0 - targety}px)" - - #if @move_lock == "x" - # @fixbutton[0].style.left = "#{@fixbutton_targetx} px" - #@fixbutton[0].style.top = "#{@fixbutton_inity}px" - #if @move_lock == "y" - # @fixbutton[0].style.top = "#{@fixbutton_targety} px" - - # Check if opened - if (not @opened and targetx > @width/3) or (@opened and targetx > @width*0.9) - @fixbutton_targetx = @fixbutton_initx - @width # Make it opened - else - @fixbutton_targetx = @fixbutton_initx - - if (not @console.opened and 0 - targety > @page_height/10) or (@console.opened and 0 - targety > @page_height*0.8) - @fixbutton_targety = @page_height - @fixbutton_inity - 50 - else - @fixbutton_targety = @fixbutton_inity - - - # Stop dragging the fixbutton - stopDrag: -> - @fixbutton.parents().off "mousemove touchmove" - @fixbutton.off "mousemove touchmove" - @fixbutton.css("pointer-events", "") - $(".drag-bg").remove() - if not @fixbutton.hasClass("dragging") - return - @fixbutton.removeClass("dragging") - - # Move back to initial position - if @fixbutton_targetx != @fixbutton.offset().left or @fixbutton_targety != @fixbutton.offset().top - # Animate fixbutton - if @move_lock == "y" - top = @fixbutton_targety - left = @fixbutton_initx - if @move_lock == "x" - top = @fixbutton_inity - left = @fixbutton_targetx - @fixbutton.stop().animate {"left": left, "top": top}, 500, "easeOutBack", => - # Switch back to auto align - if @fixbutton_targetx == @fixbutton_initx # Closed - @fixbutton.css("left", "auto") - else # Opened - @fixbutton.css("left", left) - - $(".fixbutton-bg").trigger "mouseout" # Switch fixbutton back to normal status - - @stopDragX() - @console.stopDragY() - @move_lock = null - - stopDragX: -> - # Animate sidebar and iframe - if @fixbutton_targetx == @fixbutton_initx or @move_lock == "y" - # Closed - targetx = 0 - @opened = false - else - # Opened - targetx = @width - if @opened - @onOpened() - else - @when_loaded.done => - @onOpened() - @opened = true - - # Revent sidebar transitions - if @tag - @tag.css("transition", "0.4s ease-out") - @tag.css("transform", "translateX(-#{targetx}px)").one transitionEnd, => - @tag.css("transition", "") - if not @opened - @container.remove() - @container = null - if @tag - @tag.remove() - @tag = null - - # Revert body transformations - @log "stopdrag", "opened:", @opened - if not @opened - @onClosed() - - sign: (inner_path, privatekey) -> - @wrapper.displayProgress("sign", "Signing: #{inner_path}...", 0) - @wrapper.ws.cmd "siteSign", {privatekey: privatekey, inner_path: inner_path, update_changed_files: true}, (res) => - if res == "ok" - @wrapper.displayProgress("sign", "#{inner_path} signed!", 100) - else - @wrapper.displayProgress("sign", "Error signing #{inner_path}", -1) - - publish: (inner_path, privatekey) -> - @wrapper.ws.cmd "sitePublish", {privatekey: privatekey, inner_path: inner_path, sign: true, update_changed_files: true}, (res) => - if res == "ok" - @wrapper.notifications.add "sign", "done", "#{inner_path} Signed and published!", 5000 - - handleSiteDeleteClick: -> - if @wrapper.site_info.privatekey - question = "Are you sure?
    This site has a saved private key" - options = ["Forget private key and delete site"] - else - question = "Are you sure?" - options = ["Delete this site", "Blacklist"] - @wrapper.displayConfirm question, options, (confirmed) => - if confirmed == 1 - @tag.find("#button-delete").addClass("loading") - @wrapper.ws.cmd "siteDelete", @wrapper.site_info.address, -> - document.location = $(".fixbutton-bg").attr("href") - else if confirmed == 2 - @wrapper.displayPrompt "Blacklist this site", "text", "Delete and Blacklist", "Reason", (reason) => - @tag.find("#button-delete").addClass("loading") - @wrapper.ws.cmd "siteblockAdd", [@wrapper.site_info.address, reason] - @wrapper.ws.cmd "siteDelete", @wrapper.site_info.address, -> - document.location = $(".fixbutton-bg").attr("href") - - onOpened: -> - @log "Opened" - @scrollable() - - # Re-calculate height when site admin opened or closed - @tag.find("#checkbox-owned, #checkbox-autodownloadoptional").off("click touchend").on "click touchend", => - setTimeout (=> - @scrollable() - ), 300 - - # Site limit button - @tag.find("#button-sitelimit").off("click touchend").on "click touchend", => - @wrapper.ws.cmd "siteSetLimit", $("#input-sitelimit").val(), (res) => - if res == "ok" - @wrapper.notifications.add "done-sitelimit", "done", "Site storage limit modified!", 5000 - @updateHtmlTag() - return false - - # Site autodownload limit button - @tag.find("#button-autodownload_bigfile_size_limit").off("click touchend").on "click touchend", => - @wrapper.ws.cmd "siteSetAutodownloadBigfileLimit", $("#input-autodownload_bigfile_size_limit").val(), (res) => - if res == "ok" - @wrapper.notifications.add "done-bigfilelimit", "done", "Site bigfile auto download limit modified!", 5000 - @updateHtmlTag() - return false - - # Site start download optional files - @tag.find("#button-autodownload_previous").off("click touchend").on "click touchend", => - @wrapper.ws.cmd "siteUpdate", {"address": @wrapper.site_info.address, "check_files": true}, => - @wrapper.notifications.add "done-download_optional", "done", "Optional files downloaded", 5000 - - @wrapper.notifications.add "start-download_optional", "info", "Optional files download started", 5000 - return false - - # Database reload - @tag.find("#button-dbreload").off("click touchend").on "click touchend", => - @wrapper.ws.cmd "dbReload", [], => - @wrapper.notifications.add "done-dbreload", "done", "Database schema reloaded!", 5000 - @updateHtmlTag() - return false - - # Database rebuild - @tag.find("#button-dbrebuild").off("click touchend").on "click touchend", => - @wrapper.notifications.add "done-dbrebuild", "info", "Database rebuilding...." - @wrapper.ws.cmd "dbRebuild", [], => - @wrapper.notifications.add "done-dbrebuild", "done", "Database rebuilt!", 5000 - @updateHtmlTag() - return false - - # Update site - @tag.find("#button-update").off("click touchend").on "click touchend", => - @tag.find("#button-update").addClass("loading") - @wrapper.ws.cmd "siteUpdate", @wrapper.site_info.address, => - @wrapper.notifications.add "done-updated", "done", "Site updated!", 5000 - @tag.find("#button-update").removeClass("loading") - return false - - # Pause site - @tag.find("#button-pause").off("click touchend").on "click touchend", => - @tag.find("#button-pause").addClass("hidden") - @wrapper.ws.cmd "sitePause", @wrapper.site_info.address - return false - - # Resume site - @tag.find("#button-resume").off("click touchend").on "click touchend", => - @tag.find("#button-resume").addClass("hidden") - @wrapper.ws.cmd "siteResume", @wrapper.site_info.address - return false - - # Delete site - @tag.find("#button-delete").off("click touchend").on "click touchend", => - @handleSiteDeleteClick() - return false - - # Owned checkbox - @tag.find("#checkbox-owned").off("click touchend").on "click touchend", => - owned = @tag.find("#checkbox-owned").is(":checked") - @wrapper.ws.cmd "siteSetOwned", [owned], (res_set_owned) => - @log "Owned", owned - if owned - @wrapper.ws.cmd "siteRecoverPrivatekey", [], (res_recover) => - if res_recover == "ok" - @wrapper.notifications.add("recover", "done", "Private key recovered from master seed", 5000) - else - @log "Unable to recover private key: #{res_recover.error}" - - - # Owned auto download checkbox - @tag.find("#checkbox-autodownloadoptional").off("click touchend").on "click touchend", => - @wrapper.ws.cmd "siteSetAutodownloadoptional", [@tag.find("#checkbox-autodownloadoptional").is(":checked")] - - # Change identity button - @tag.find("#button-identity").off("click touchend").on "click touchend", => - @wrapper.ws.cmd "certSelect" - return false - - # Save settings - @tag.find("#button-settings").off("click touchend").on "click touchend", => - @wrapper.ws.cmd "fileGet", "content.json", (res) => - data = JSON.parse(res) - data["title"] = $("#settings-title").val() - data["description"] = $("#settings-description").val() - json_raw = unescape(encodeURIComponent(JSON.stringify(data, undefined, '\t'))) - @wrapper.ws.cmd "fileWrite", ["content.json", btoa(json_raw), true], (res) => - if res != "ok" # fileWrite failed - @wrapper.notifications.add "file-write", "error", "File write error: #{res}" - else - @wrapper.notifications.add "file-write", "done", "Site settings saved!", 5000 - if @wrapper.site_info.privatekey - @wrapper.ws.cmd "siteSign", {privatekey: "stored", inner_path: "content.json", update_changed_files: true} - @updateHtmlTag() - return false - - - # Open site directory - @tag.find("#link-directory").off("click touchend").on "click touchend", => - @wrapper.ws.cmd "serverShowdirectory", ["site", @wrapper.site_info.address] - return false - - # Copy site with peers - @tag.find("#link-copypeers").off("click touchend").on "click touchend", (e) => - copy_text = e.currentTarget.href - handler = (e) => - e.clipboardData.setData('text/plain', copy_text) - e.preventDefault() - @wrapper.notifications.add "copy", "done", "Site address with peers copied to your clipboard", 5000 - document.removeEventListener('copy', handler, true) - - document.addEventListener('copy', handler, true) - document.execCommand('copy') - return false - - # Sign and publish content.json - $(document).on "click touchend", => - @tag?.find("#button-sign-publish-menu").removeClass("visible") - @tag?.find(".contents + .flex").removeClass("sign-publish-flex") - - @tag.find(".contents-content").off("click touchend").on "click touchend", (e) => - $("#input-contents").val(e.currentTarget.innerText); - return false; - - menu = new Menu(@tag.find("#menu-sign-publish")) - menu.elem.css("margin-top", "-130px") # Open upwards - menu.addItem "Sign", => - inner_path = @tag.find("#input-contents").val() - - @wrapper.ws.cmd "fileRules", {inner_path: inner_path}, (rules) => - if @wrapper.site_info.auth_address in rules.signers - # ZeroID or other ID provider - @sign(inner_path) - else if @wrapper.site_info.privatekey - # Privatekey stored in users.json - @sign(inner_path, "stored") - else - # Ask the user for privatekey - @wrapper.displayPrompt "Enter your private key:", "password", "Sign", "", (privatekey) => # Prompt the private key - @sign(inner_path, privatekey) - - @tag.find(".contents + .flex").removeClass "active" - menu.hide() - - menu.addItem "Publish", => - inner_path = @tag.find("#input-contents").val() - @wrapper.ws.cmd "sitePublish", {"inner_path": inner_path, "sign": false} - - @tag.find(".contents + .flex").removeClass "active" - menu.hide() - - @tag.find("#menu-sign-publish").off("click touchend").on "click touchend", => - if window.visible_menu == menu - @tag.find(".contents + .flex").removeClass "active" - menu.hide() - else - @tag.find(".contents + .flex").addClass "active" - @tag.find(".content-wrapper").prop "scrollTop", 10000 - menu.show() - return false - - $("body").on "click", => - if @tag - @tag.find(".contents + .flex").removeClass "active" - - @tag.find("#button-sign-publish").off("click touchend").on "click touchend", => - inner_path = @tag.find("#input-contents").val() - - @wrapper.ws.cmd "fileRules", {inner_path: inner_path}, (rules) => - if @wrapper.site_info.auth_address in rules.signers - # ZeroID or other ID provider - @publish(inner_path, null) - else if @wrapper.site_info.privatekey - # Privatekey stored in users.json - @publish(inner_path, "stored") - else - # Ask the user for privatekey - @wrapper.displayPrompt "Enter your private key:", "password", "Sign", "", (privatekey) => # Prompt the private key - @publish(inner_path, privatekey) - return false - - # Close - @tag.find(".close").off("click touchend").on "click touchend", (e) => - @close() - return false - - @loadGlobe() - - close: -> - @move_lock = "x" - @startDrag() - @stopDrag() - - - onClosed: -> - $(window).off "resize" - $(window).on "resize", @resized - $(document.body).css("transition", "0.6s ease-in-out").removeClass("body-sidebar").on transitionEnd, (e) => - if e.target == document.body and not $(document.body).hasClass("body-sidebar") and not $(document.body).hasClass("body-console") - $(document.body).css("height", "auto").css("perspective", "").css("will-change", "").css("transition", "").off transitionEnd - @unloadGlobe() - - # We dont need site info anymore - @wrapper.setSiteInfo = @original_set_site_info - - - loadGlobe: => - if @tag.find(".globe").hasClass("loading") - setTimeout (=> - if typeof(DAT) == "undefined" # Globe script not loaded, do it first - script_tag = $(" - \ No newline at end of file diff --git a/update.py b/update.py index cf9898f99..621064691 100644 --- a/update.py +++ b/update.py @@ -6,6 +6,13 @@ def update(): + print('please update zeronet-conservancy via git. usually it can be done via single commnad') + print(' git pull') + print('although it depends on your branches setup') + print('updating through 1update site is not considered safe at the moment') + print('if you really want to use it, edit this file') + return False + from Config import config config.parse(silent=True) diff --git a/zeronet.py b/zeronet.py index dacd20961..bb53404fb 100755 --- a/zeronet.py +++ b/zeronet.py @@ -1,17 +1,21 @@ #!/usr/bin/env python3 import os import sys +from src.Config import config +# fix further imports from src dir +sys.modules['Config'] = sys.modules['src.Config'] -def main(): +def launch(): + '''renamed from main to avoid clashes with main module''' if sys.version_info.major < 3: print("Error: Python 3.x is required") sys.exit(0) - if "--silent" not in sys.argv: - print("- Starting ZeroNet...") + if '--silent' not in sys.argv: + from greet import fancy_greet + fancy_greet(config.version) - main = None try: import main main.start() @@ -23,11 +27,10 @@ def main(): except Exception as log_err: print("Failed to log error:", log_err) traceback.print_exc() - from Config import config error_log_path = config.log_dir + "/error.log" traceback.print_exc(file=open(error_log_path, "w")) print("---") - print("Please report it: https://github.com/HelloZeroNet/ZeroNet/issues/new?assignees=&labels=&template=bug-report.md") + print("Please report it: https://github.com/zeronet-conservancy/zeronet-conservancy/issues/new?template=bug-report.md") if sys.platform.startswith("win") and "python.exe" not in sys.executable: displayErrorMessage(err, error_log_path) @@ -66,8 +69,8 @@ def displayErrorMessage(err, error_log_path): res = ctypes.windll.user32.MessageBoxW(0, err_title, "ZeroNet error", MB_YESNOCANCEL | MB_ICONEXCLAIMATION) if res == ID_YES: import webbrowser - report_url = "https://github.com/HelloZeroNet/ZeroNet/issues/new?assignees=&labels=&template=bug-report.md&title=%s" - webbrowser.open(report_url % urllib.parse.quote("Unhandled exception: %s" % err_message)) + report_url = "https://github.com/zeronet-conservancy/zeronet-conservancy/issues/new" + webbrowser.open(report_url) if res in [ID_YES, ID_NO]: subprocess.Popen(['notepad.exe', error_log_path]) @@ -120,6 +123,7 @@ def restart(): def start(): + config.working_dir = os.getcwd() app_dir = os.path.dirname(os.path.abspath(__file__)) os.chdir(app_dir) # Change working dir to zeronet.py dir sys.path.insert(0, os.path.join(app_dir, "src/lib")) # External liblary directory @@ -131,7 +135,7 @@ def start(): import update update.update() else: - main() + launch() if __name__ == '__main__':