feat: add desktop repo (#1071)
|
|
@ -1,4 +1,3 @@
|
|||
# git
|
||||
.git/
|
||||
.gitignore
|
||||
.eslintcache
|
||||
|
|
@ -7,3 +6,4 @@ dist
|
|||
packages/web-server/public/assets
|
||||
packages/web-server/tmp
|
||||
packages/web-server/vendor/bundles
|
||||
packages/desktop
|
||||
2
.eslintignore
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
node_modules
|
||||
packages/*/coverage
|
||||
4
.github/codeql/codeql-config.yml
vendored
|
|
@ -6,7 +6,11 @@ queries:
|
|||
|
||||
paths:
|
||||
- packages/web/src/javascripts
|
||||
- packages/desktop/app
|
||||
|
||||
paths-ignore:
|
||||
- bin
|
||||
- node_modules
|
||||
- build
|
||||
- dist
|
||||
- packages/desktop/app/dist
|
||||
27
.github/workflows/desktop.dev.yml
vendored
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
name: Dev
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- develop
|
||||
paths:
|
||||
- packages/desktop/**
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ./packages/desktop
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: '14.x'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
- run: yarn setup
|
||||
- run: node scripts/build.mjs appimage-x64
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: 'AppImage'
|
||||
path: dist/*.AppImage
|
||||
2
.github/workflows/git-sync.yml
vendored
|
|
@ -6,7 +6,7 @@ jobs:
|
|||
- name: git-sync
|
||||
uses: wei/git-sync@v3
|
||||
with:
|
||||
source_repo: "standardnotes/web"
|
||||
source_repo: "standardnotes/app"
|
||||
source_branch: "refs/remotes/source/*"
|
||||
destination_repo: "standardnotes/private-web"
|
||||
destination_branch: "refs/heads/*"
|
||||
|
|
|
|||
|
|
@ -3,6 +3,9 @@ name: Beta
|
|||
on:
|
||||
push:
|
||||
branches: [ beta/* ]
|
||||
paths:
|
||||
- packages/web-server/**
|
||||
- packages/web/**
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
|
|
@ -8,8 +8,8 @@ on:
|
|||
push:
|
||||
branches: [ develop ]
|
||||
paths:
|
||||
- packages/web-server
|
||||
- packages/web
|
||||
- packages/web-server/**
|
||||
- packages/web/**
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
|
|
@ -8,8 +8,8 @@ on:
|
|||
push:
|
||||
branches: [ main ]
|
||||
paths:
|
||||
- packages/web-server
|
||||
- packages/web
|
||||
- packages/web-server/**
|
||||
- packages/web/**
|
||||
|
||||
jobs:
|
||||
test:
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
||||
level of experience, education, socio-economic status, nationality, personal
|
||||
appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at help@standardnotes.org. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see
|
||||
https://www.contributor-covenant.org/faq
|
||||
|
|
@ -8,7 +8,7 @@ Standard Notes is a simple and private notes app available on most platforms, in
|
|||
<div align="center">
|
||||
|
||||
[](https://github.com/standardnotes/desktop/releases)
|
||||
[](https://github.com/standardnotes/web/blob/main/LICENSE)
|
||||
[](https://github.com/standardnotes/app/blob/main/LICENSE)
|
||||
[](https://standardnotes.com/slack)
|
||||
[](https://twitter.com/standardnotes)
|
||||
|
||||
|
|
@ -58,8 +58,6 @@ Developers can create and publish their own extensions. Visit the [documentation
|
|||
|
||||
Questions? Find answers on our [Help page](https://standardnotes.com/help).
|
||||
|
||||
🙏
|
||||
|
||||
---
|
||||
|
||||
### Docker setup
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ case "$COMMAND" in
|
|||
echo "Prestart Step 1/1 - Removing server lock"
|
||||
rm -f /app/packages/web-server/tmp/pids/server.pid
|
||||
echo "Starting Server..."
|
||||
yarn start:web
|
||||
yarn start:server:web
|
||||
;;
|
||||
|
||||
'start-local' )
|
||||
|
|
@ -21,7 +21,7 @@ case "$COMMAND" in
|
|||
echo "Prestart Step 4/4 - Building"
|
||||
yarn build
|
||||
echo "Starting Server..."
|
||||
yarn start:web
|
||||
yarn start:server:web
|
||||
;;
|
||||
|
||||
* )
|
||||
|
|
|
|||
4
linter.tsconfig.json
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"exclude": ["node_modules"],
|
||||
"extends": "./node_modules/@standardnotes/config/src/linter.tsconfig.json"
|
||||
}
|
||||
|
|
@ -15,8 +15,9 @@
|
|||
"test": "lerna run test --parallel",
|
||||
"clean": "lerna run clean",
|
||||
"build": "lerna run build",
|
||||
"start:web": "lerna run start --scope=@standardnotes/web-server",
|
||||
"start:web:localhost": "lerna run start:no-binding --scope=@standardnotes/web-server",
|
||||
"build:web": "lerna run build --scope=@standardnotes/web",
|
||||
"start:server:web": "lerna run start --scope=@standardnotes/web-server",
|
||||
"start:server:web:localhost": "lerna run start:no-binding --scope=@standardnotes/web-server",
|
||||
"prepare": "husky install"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
|
|||
1
packages/desktop/.env.sample
Normal file
|
|
@ -0,0 +1 @@
|
|||
DEFAULT_SYNC_SERVER=https://api.standardnotes.com
|
||||
42
packages/desktop/.eslintrc
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
{
|
||||
"env": {
|
||||
"node": true,
|
||||
"commonjs": true
|
||||
},
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/eslint-recommended",
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"prettier",
|
||||
"../../node_modules/@standardnotes/config/src/.eslintrc"
|
||||
],
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"ignorePatterns": ["test", "scripts", ".eslintrc", "tsconfig.json", "node_modules"],
|
||||
"rules": {
|
||||
/** Style */
|
||||
"quotes": ["error", "single", { "avoidEscape": true }],
|
||||
|
||||
/** Preferences */
|
||||
"no-console": "off",
|
||||
"accessor-pairs": 0,
|
||||
"no-nonoctal-decimal-escape": 0,
|
||||
"no-unsafe-optional-chaining": 0,
|
||||
"@typescript-eslint/explicit-function-return-type": 0,
|
||||
"@typescript-eslint/no-use-before-define": ["error", "nofunc"],
|
||||
"@typescript-eslint/no-non-null-assertion": 0,
|
||||
"@typescript-eslint/no-explicit-any": 0,
|
||||
"@typescript-eslint/no-var-requires": 0,
|
||||
/**
|
||||
* The following rules are disabled because they are already implemented
|
||||
* in the TypeScript configuration, or vice-versa
|
||||
*/
|
||||
"no-unused-vars": 0,
|
||||
"no-useless-constructor": 0,
|
||||
"no-unused-expressions": 0,
|
||||
"@typescript-eslint/camelcase": 0
|
||||
},
|
||||
"plugins": ["@typescript-eslint"],
|
||||
"globals": {
|
||||
"zip": true
|
||||
}
|
||||
}
|
||||
15
packages/desktop/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
node_modules/
|
||||
.DS_Store
|
||||
dist/
|
||||
npm-debug.log
|
||||
test/data/tmp/
|
||||
|
||||
/app/dist
|
||||
.vscode
|
||||
.idea
|
||||
.env
|
||||
.env.production
|
||||
.env.development
|
||||
|
||||
codeqldb
|
||||
yarn-error.log
|
||||
2
packages/desktop/.husky/pre-commit
Executable file
|
|
@ -0,0 +1,2 @@
|
|||
#!/bin/sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
5
packages/desktop/.mocharc.json
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
{
|
||||
"extension": ["ts"],
|
||||
"spec": "test/*.spec.ts",
|
||||
"require": "ts-node/register/transpile-only"
|
||||
}
|
||||
6
packages/desktop/.npmrc
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
runtime = electron
|
||||
target = 5.0.10
|
||||
target_arch = x64
|
||||
disturl = https://atom.io/download/atom-shell
|
||||
export npm_config_runtime=electron
|
||||
export npm_config_build_from_source=true
|
||||
1
packages/desktop/.nvmrc
Normal file
|
|
@ -0,0 +1 @@
|
|||
14.17.3
|
||||
8
packages/desktop/.prettierignore
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
node_modules/
|
||||
dist/
|
||||
app/dist/
|
||||
test/data/tmp/
|
||||
web/
|
||||
.github
|
||||
codeqldb
|
||||
*.js
|
||||
6
packages/desktop/.prettierrc
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"printWidth": 120,
|
||||
"semi": false
|
||||
}
|
||||
661
packages/desktop/LICENSE
Normal file
|
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
81
packages/desktop/README.md
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
# Standard Notes
|
||||
|
||||
<div align="center">
|
||||
|
||||
[](https://github.com/standardnotes/desktop/releases)
|
||||
[](https://github.com/standardnotes/desktop/blob/master/LICENSE)
|
||||
[](https://standardnotes.com/slack)
|
||||
[](https://twitter.com/standardnotes)
|
||||
|
||||
</div>
|
||||
|
||||
This application makes use of the core JS/CSS/HTML code found in the [web repo](https://github.com/standardnotes/app). For issues related to the actual app experience, please post issues in the web repo.
|
||||
|
||||
## Running Locally
|
||||
|
||||
Make sure [Yarn](https://classic.yarnpkg.com/en/) is installed on your system.
|
||||
|
||||
```bash
|
||||
yarn setup
|
||||
yarn build:web # Or `yarn dev:web`
|
||||
yarn dev
|
||||
|
||||
# In another terminal
|
||||
yarn start
|
||||
```
|
||||
|
||||
We use [commitlint](https://github.com/conventional-changelog/commitlint) to validate commit messages.
|
||||
Before making a pull request, make sure to check the output of the following commands:
|
||||
|
||||
```bash
|
||||
yarn lint
|
||||
yarn test # Make sure to start `yarn dev` before running the tests, and quit any running Standard Notes applications so they don't conflict.
|
||||
```
|
||||
|
||||
Pull requests should target the `develop` branch.
|
||||
|
||||
### Installing dependencies
|
||||
|
||||
To determine where to install a dependency:
|
||||
|
||||
- If it is only required for building, install it in `package.json`'s `devDependencies`
|
||||
- If it is required at runtime but can be packaged by webpack, install it in `package.json`'s `dependencies`.
|
||||
- If it must be distributed as a node module (not packaged by webpack), install it in `app/package.json`'s `dependencies`
|
||||
- Also make sure to declare it as an external commonjs dependency in `webpack.common.js`.
|
||||
|
||||
## Building
|
||||
|
||||
Build for all platforms:
|
||||
|
||||
- `yarn release`
|
||||
|
||||
## Building natively on arm64
|
||||
|
||||
Building arm64 releases on amd64 systems is only possible with AppImage, Debian and universal "dir" targets.
|
||||
|
||||
Building arm64 releases natively on arm64 systems requires some additional preparation:
|
||||
|
||||
- `export npm_config_target_arch=arm64`
|
||||
- `export npm_config_arch=arm64`
|
||||
|
||||
A native `fpm` installation is needed for Debian builds. `fpm` needs to be available in `$PATH`, which can be achieved by running
|
||||
|
||||
- `gem install fpm --no-document`
|
||||
|
||||
and making sure `$GEM_HOME/bin` is added to `$PATH`.
|
||||
|
||||
Snap releases also require a working snapcraft / `snapd` installation.
|
||||
|
||||
Building can then be done by running:
|
||||
|
||||
- `yarn setup`
|
||||
|
||||
Followed by
|
||||
|
||||
- `node scripts/build.mjs deb-arm64`
|
||||
|
||||
## Installation
|
||||
|
||||
On Linux, download the latest AppImage from the [Releases](https://github.com/standardnotes/desktop/releases/latest) page, and give it executable permission:
|
||||
|
||||
`chmod u+x standard-notes*.AppImage`
|
||||
37
packages/desktop/SECURITY.md
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
Thank you for your work in helping keep Standard Notes safe and secure. If you believe you've found a security issue in our product, we encourage you to notify us. We welcome working with you to resolve the issue promptly.
|
||||
|
||||
# Disclosure Policy
|
||||
|
||||
- Let us know as soon as possible upon discovery of a potential security issue, and we'll make every
|
||||
effort to quickly resolve the issue. Please email [security@standardnotes.com](mailto:security@standardnotes.com) for a direct response.
|
||||
- Provide us a reasonable amount of time to resolve the issue before any disclosure to the public or a
|
||||
third-party. We may publicly disclose the issue before resolving it, if appropriate.
|
||||
- Make a good faith effort to avoid privacy violations, destruction of data, and interruption or
|
||||
degradation of our service. Only interact with accounts you own or with explicit permission of the
|
||||
account holder.
|
||||
|
||||
# In-scope
|
||||
|
||||
- Security issues in any current release of Standard Notes. Our product downloads are available on our homepage at https://standardnotes.com, and our source code is available at https://github.com/standardnotes.
|
||||
|
||||
# Exclusions
|
||||
|
||||
The following bug classes are out-of scope:
|
||||
|
||||
- Bugs that are already reported on any of Standard Notes' issue trackers (https://github.com/standardnotes), or that we already know of.
|
||||
- Issues in an upstream software dependency (ex: Electron, React Native) which are already reported to the upstream maintainer.
|
||||
- Attacks requiring physical access to a user's device.
|
||||
- Self-XSS
|
||||
- Issues related to software or protocols not under SN's control
|
||||
- Vulnerabilities in outdated versions of Standard Notes
|
||||
- Missing security best practices that do not directly lead to a vulnerability
|
||||
- Issues that do not have any impact on the general public
|
||||
|
||||
While researching, we'd like to ask you to refrain from:
|
||||
|
||||
- Denial of service
|
||||
- Spamming
|
||||
- Social engineering (including phishing) of Standard Notes' staff or contractors
|
||||
- Any physical attempts against Standard Notes' property or data centers
|
||||
|
||||
Thank you for helping keep Standard Notes secure!
|
||||
4
packages/desktop/app/@types/modules.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
declare module '*.html' {
|
||||
const content: string
|
||||
export default content
|
||||
}
|
||||
179
packages/desktop/app/application.ts
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
import { App, Shell } from 'electron'
|
||||
import { createExtensionsServer } from './javascripts/Main/ExtensionsServer'
|
||||
import { isLinux, isMac, isWindows } from './javascripts/Main/Types/Platforms'
|
||||
import { Store, StoreKeys } from './javascripts/Main/Store'
|
||||
import { AppName, initializeStrings } from './javascripts/Main/Strings'
|
||||
import { createWindowState, WindowState } from './javascripts/Main/Window'
|
||||
import { Keychain } from './javascripts/Main/Keychain/Keychain'
|
||||
import { isDev, isTesting } from './javascripts/Main/Utils/Utils'
|
||||
import { Urls, Paths } from './javascripts/Main/Types/Paths'
|
||||
import { action, makeObservable, observable } from 'mobx'
|
||||
import { UpdateState } from './javascripts/Main/UpdateManager'
|
||||
import { handleTestMessage } from './javascripts/Main/Utils/Testing'
|
||||
import { MessageType } from '../test/TestIpcMessage'
|
||||
|
||||
const deepLinkScheme = 'standardnotes'
|
||||
|
||||
export class AppState {
|
||||
readonly version: string
|
||||
readonly store: Store
|
||||
readonly startUrl = Urls.indexHtml
|
||||
readonly isPrimaryInstance: boolean
|
||||
public willQuitApp = false
|
||||
public lastBackupDate: number | null = null
|
||||
public windowState?: WindowState
|
||||
public deepLinkUrl?: string
|
||||
public readonly updates: UpdateState
|
||||
|
||||
constructor(app: Electron.App) {
|
||||
this.version = app.getVersion()
|
||||
this.store = new Store(Paths.userDataDir)
|
||||
this.isPrimaryInstance = app.requestSingleInstanceLock()
|
||||
makeObservable(this, {
|
||||
lastBackupDate: observable,
|
||||
setBackupCreationDate: action,
|
||||
})
|
||||
this.updates = new UpdateState(this)
|
||||
|
||||
if (isTesting()) {
|
||||
handleTestMessage(MessageType.AppStateCall, (method, ...args) => {
|
||||
;(this as any)[method](...args)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
setBackupCreationDate(date: number | null): void {
|
||||
this.lastBackupDate = date
|
||||
}
|
||||
}
|
||||
|
||||
export function initializeApplication(args: { app: Electron.App; ipcMain: Electron.IpcMain; shell: Shell }): void {
|
||||
const { app } = args
|
||||
|
||||
app.name = AppName
|
||||
|
||||
const state = new AppState(app)
|
||||
|
||||
void setupDeepLinking(app)
|
||||
|
||||
registerSingleInstanceHandler(app, state)
|
||||
|
||||
registerAppEventListeners({
|
||||
...args,
|
||||
state,
|
||||
})
|
||||
|
||||
if (isDev()) {
|
||||
/** Expose the app's state as a global variable. Useful for debugging */
|
||||
;(global as any).appState = state
|
||||
}
|
||||
}
|
||||
|
||||
function focusWindow(appState: AppState) {
|
||||
const window = appState.windowState?.window
|
||||
|
||||
if (window) {
|
||||
if (!window.isVisible()) {
|
||||
window.show()
|
||||
}
|
||||
if (window.isMinimized()) {
|
||||
window.restore()
|
||||
}
|
||||
window.focus()
|
||||
}
|
||||
}
|
||||
|
||||
function registerSingleInstanceHandler(app: Electron.App, appState: AppState) {
|
||||
app.on('second-instance', (_event: Event, argv: string[]) => {
|
||||
if (isWindows()) {
|
||||
appState.deepLinkUrl = argv.find((arg) => arg.startsWith(deepLinkScheme))
|
||||
}
|
||||
|
||||
/* Someone tried to run a second instance, we should focus our window. */
|
||||
focusWindow(appState)
|
||||
})
|
||||
}
|
||||
|
||||
function registerAppEventListeners(args: {
|
||||
app: Electron.App
|
||||
ipcMain: Electron.IpcMain
|
||||
shell: Shell
|
||||
state: AppState
|
||||
}) {
|
||||
const { app, state } = args
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (!isMac()) {
|
||||
app.quit()
|
||||
}
|
||||
})
|
||||
|
||||
app.on('before-quit', () => {
|
||||
state.willQuitApp = true
|
||||
})
|
||||
|
||||
app.on('activate', () => {
|
||||
const windowState = state.windowState
|
||||
if (!windowState) {
|
||||
return
|
||||
}
|
||||
windowState.window.show()
|
||||
})
|
||||
|
||||
app.on('open-url', (_event, url) => {
|
||||
state.deepLinkUrl = url
|
||||
focusWindow(state)
|
||||
})
|
||||
|
||||
app.on('ready', () => {
|
||||
if (!state.isPrimaryInstance) {
|
||||
console.warn('Quiting app and focusing existing instance.')
|
||||
app.quit()
|
||||
return
|
||||
}
|
||||
|
||||
void finishApplicationInitialization(args)
|
||||
})
|
||||
}
|
||||
|
||||
async function setupDeepLinking(app: Electron.App) {
|
||||
if (!app.isDefaultProtocolClient(deepLinkScheme)) {
|
||||
app.setAsDefaultProtocolClient(deepLinkScheme)
|
||||
}
|
||||
}
|
||||
|
||||
async function finishApplicationInitialization({ app, shell, state }: { app: App; shell: Shell; state: AppState }) {
|
||||
const keychainWindow = await Keychain.ensureKeychainAccess(state.store)
|
||||
|
||||
initializeStrings(app.getLocale())
|
||||
initializeExtensionsServer(state.store)
|
||||
|
||||
const windowState = await createWindowState({
|
||||
shell,
|
||||
appState: state,
|
||||
appLocale: app.getLocale(),
|
||||
teardown() {
|
||||
state.windowState = undefined
|
||||
},
|
||||
})
|
||||
|
||||
/**
|
||||
* Close the keychain window after the main window is created, otherwise the
|
||||
* app will quit automatically
|
||||
*/
|
||||
keychainWindow?.close()
|
||||
|
||||
state.windowState = windowState
|
||||
|
||||
if ((isWindows() || isLinux()) && state.windowState.trayManager.shouldMinimizeToTray()) {
|
||||
state.windowState.trayManager.createTrayIcon()
|
||||
}
|
||||
|
||||
void windowState.window.loadURL(state.startUrl)
|
||||
}
|
||||
|
||||
function initializeExtensionsServer(store: Store) {
|
||||
const host = createExtensionsServer()
|
||||
|
||||
store.set(StoreKeys.ExtServerHost, host)
|
||||
}
|
||||
16
packages/desktop/app/enableExperimentalWebFeatures.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { app } from 'electron'
|
||||
|
||||
/**
|
||||
* @FIXME
|
||||
* Due to a bug in Electron (https://github.com/electron/electron/issues/28422),
|
||||
* downloading a file using the File System Access API does not work, causing an exception:
|
||||
* "Uncaught DOMException: The request is not allowed by the user agent or the platform in the current context."
|
||||
*
|
||||
* The following workaround fixes the issue by enabling experimental web platform features
|
||||
* which makes the file system access permission always be true.
|
||||
*
|
||||
* Since this workaround involves enabling experimental features, it could lead
|
||||
* to other issues. This should be removed as soon as the upstream bug is fixed.
|
||||
*/
|
||||
export const enableExperimentalFeaturesForFileAccessFix = () =>
|
||||
app.commandLine.appendSwitch('enable-experimental-web-platform-features')
|
||||
95
packages/desktop/app/grantLinuxPasswordsAccess.html
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Standard Notes</title>
|
||||
<link rel="stylesheet" media="all" href="web/app.css" />
|
||||
<link rel="stylesheet" media="all" href="stylesheets/renderer.css" />
|
||||
</head>
|
||||
|
||||
<body class="main-ui">
|
||||
<div class="sk-modal">
|
||||
<div class="challenge-modal sk-modal-content" style="margin: 2rem">
|
||||
<div class="sn-component">
|
||||
<div class="sk-panel">
|
||||
<div class="sk-panel-header">
|
||||
<div class="sk-panel-header-title capitalize">Password service access</div>
|
||||
</div>
|
||||
<div class="sk-panel-content" style="padding-bottom: 2rem">
|
||||
<h1 class="sk-h1">Choose how you want Standard Notes to store your account keys</h1>
|
||||
<p class="sk-p">
|
||||
Standard Notes can either use your operating system's password manager or its own local storage
|
||||
facility.
|
||||
</p>
|
||||
<p class="sk-p">
|
||||
<strong>Standard Notes currently does not have access to your system password service.</strong>
|
||||
If you grant it access, you must quit the app for the change to come into effect.
|
||||
</p>
|
||||
<div class="sk-panel-row">
|
||||
<div class="sk-button-group">
|
||||
<button class="sk-button info" id="quit-button">
|
||||
<div class="sk-label capitalize">Use password service (quit)</div>
|
||||
</button>
|
||||
<button class="sk-button neutral capitalize" id="use-storage-button">
|
||||
<div class="sk-label">Use local storage (continue)</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sk-panel-row"></div>
|
||||
<a class="sk-a capitalize" id="learn-more">Learn more</a>
|
||||
<div style="display: none" id="more-info">
|
||||
<div class="sk-panel-section">
|
||||
<h1 class="sk-h1">What's the difference?</h1>
|
||||
<p class="sk-p">
|
||||
Using local storage, your account keys may be more easily accessible by third-party programs, unlike
|
||||
in your password manager which has additional protections built-in.
|
||||
</p>
|
||||
<p class="sk-p">
|
||||
In either cases, the strongest way to protect your account keys is to use a strong passcode, which
|
||||
will be used to encrypt your keys and prevent any software or operating system from reading them.
|
||||
<strong> If you plan on setting a passcode, you can safely use local storage. </strong>
|
||||
</p>
|
||||
<div class="sk-panel-row"></div>
|
||||
<h2 class="sk-h2">Granting Standard Notes access to your system password service</h2>
|
||||
<p class="sk-p">
|
||||
Note that
|
||||
<strong>
|
||||
granting access to your system password service will allow Standard Notes to read, write, and
|
||||
delete <em>any</em> of your saved passwords.
|
||||
</strong>
|
||||
Standard Notes will never use this privilege to do anything more than reading and writing to its own
|
||||
entry.
|
||||
</p>
|
||||
<ol>
|
||||
<li class="sk-li">Quit Standard Notes</li>
|
||||
<li class="sk-li">Open your software store (Ubuntu Software Center/Snap Store)</li>
|
||||
<li class="sk-li">In your installed apps list, click on Standard Notes</li>
|
||||
<li class="sk-li">Look for a <em>Permissions</em> button</li>
|
||||
<li class="sk-li">
|
||||
Make sure the permission associated with reading and writing passwords is checked
|
||||
</li>
|
||||
<li class="sk-li">Open Standard Notes again</li>
|
||||
</ol>
|
||||
<h2 class="sk-h2">
|
||||
Granting Standard Notes access to your system password service from the command line
|
||||
</h2>
|
||||
<p class="sk-p">
|
||||
Run the following command:<br />
|
||||
<code>snap connect standard-notes:password-manager-service</code>
|
||||
</p>
|
||||
</div>
|
||||
<p>
|
||||
<em>
|
||||
Note: Password Service may also be referred to as keyring, saved passwords, stored passwords,
|
||||
password manager, passwords, or secrets, depending on your Linux configuration.
|
||||
</em>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
BIN
packages/desktop/app/icon/Icon-256x256.png
Normal file
|
After Width: | Height: | Size: 7 KiB |
BIN
packages/desktop/app/icon/Icon-512x512.png
Normal file
|
After Width: | Height: | Size: 15 KiB |
113
packages/desktop/app/index.html
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<!--
|
||||
We need to set 'unsafe-eval' to use wasm.
|
||||
https://bugs.chromium.org/p/chromium/issues/detail?id=948834
|
||||
-->
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="
|
||||
default-src 'self' blob:;
|
||||
script-src 'self' 'unsafe-eval';
|
||||
worker-src blob:;
|
||||
connect-src * data:;
|
||||
style-src 'unsafe-inline' 'self' http://localhost:* http://127.0.0.1:45653;
|
||||
frame-src * blob:;
|
||||
"
|
||||
/>
|
||||
|
||||
<meta content="IE=edge" http-equiv="X-UA-Compatible" />
|
||||
<meta content="width=device-width, initial-scale=1" name="viewport" />
|
||||
<meta name="theme-color" content="#ffffff" />
|
||||
|
||||
<meta content="Standard Notes" name="apple-mobile-web-app-title" />
|
||||
<meta content="Standard Notes" name="application-name" />
|
||||
|
||||
<script src="web/app.js"></script>
|
||||
<script src="javascripts/renderer/renderer.js"></script>
|
||||
|
||||
<link rel="stylesheet" media="all" href="web/app.css" />
|
||||
<link rel="stylesheet" media="all" href="stylesheets/renderer.css" />
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="desktop-title-bar">
|
||||
<div class="title-bar-left-buttons">
|
||||
<button id="menu-btn">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="feather feather-menu"
|
||||
>
|
||||
<line x1="3" y1="12" x2="21" y2="12"></line>
|
||||
<line x1="3" y1="6" x2="21" y2="6"></line>
|
||||
<line x1="3" y1="18" x2="21" y2="18"></line>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="title-bar-right-buttons">
|
||||
<button id="min-btn">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="feather feather-minus"
|
||||
>
|
||||
<line x1="5" y1="12" x2="19" y2="12"></line>
|
||||
</svg>
|
||||
</button>
|
||||
<button id="max-btn">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="feather feather-maximize-2"
|
||||
>
|
||||
<polyline points="15 3 21 3 21 9"></polyline>
|
||||
<polyline points="9 21 3 21 3 15"></polyline>
|
||||
<line x1="21" y1="3" x2="14" y2="10"></line>
|
||||
<line x1="3" y1="21" x2="10" y2="14"></line>
|
||||
</svg>
|
||||
</button>
|
||||
<button id="close-btn">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="feather feather-x"
|
||||
>
|
||||
<line x1="18" y1="6" x2="6" y2="18"></line>
|
||||
<line x1="6" y1="6" x2="18" y2="18"></line>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
126
packages/desktop/app/index.ts
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
import { app, ipcMain, shell } from 'electron'
|
||||
import path from 'path'
|
||||
import fs from 'fs-extra'
|
||||
import log from 'electron-log'
|
||||
import './@types/modules'
|
||||
import { initializeApplication } from './application'
|
||||
import { isSnap } from './javascripts/Main/Types/Constants'
|
||||
import { isTesting } from './javascripts/Main/Utils/Utils'
|
||||
import { setupTesting } from './javascripts/Main/Utils/Testing'
|
||||
import { CommandLineArgs } from './javascripts/Shared/CommandLineArgs'
|
||||
import { Store, StoreKeys } from './javascripts/Main/Store'
|
||||
import { Paths } from './javascripts/Main/Types/Paths'
|
||||
import { enableExperimentalFeaturesForFileAccessFix } from './enableExperimentalWebFeatures'
|
||||
|
||||
enableExperimentalFeaturesForFileAccessFix()
|
||||
|
||||
require('@electron/remote/main').initialize()
|
||||
|
||||
/** Allow a custom userData path to be used. */
|
||||
const userDataPathIndex = process.argv.indexOf(CommandLineArgs.UserDataPath)
|
||||
|
||||
if (userDataPathIndex > 0) {
|
||||
let userDataPath = process.argv[userDataPathIndex + 1]
|
||||
if (typeof userDataPath === 'string') {
|
||||
userDataPath = path.resolve(userDataPath)
|
||||
|
||||
/** Make sure the path is actually a writeable folder */
|
||||
try {
|
||||
fs.closeSync(fs.openSync(path.join(userDataPath, 'sn-test-file'), 'w'))
|
||||
} catch (e) {
|
||||
console.error('Failed to write to provided user data path. Aborting')
|
||||
app.exit(1)
|
||||
}
|
||||
|
||||
app.setPath('userData', userDataPath)
|
||||
}
|
||||
} else if (isSnap) {
|
||||
migrateSnapStorage()
|
||||
}
|
||||
|
||||
if (isTesting()) {
|
||||
setupTesting()
|
||||
}
|
||||
|
||||
log.transports.file.level = 'info'
|
||||
|
||||
process.on('uncaughtException', (err) => {
|
||||
console.error('Uncaught exception', err)
|
||||
})
|
||||
|
||||
initializeApplication({
|
||||
app,
|
||||
shell,
|
||||
ipcMain,
|
||||
})
|
||||
|
||||
/**
|
||||
* By default, app.get('userData') points to the snap's current revision
|
||||
* folder. This causes issues when updating the snap while the app is
|
||||
* running, because it will not copy over anything that is saved to
|
||||
* localStorage or IndexedDB after the installation has completed.
|
||||
*
|
||||
* To counteract this, we change the userData directory to be the snap's
|
||||
* 'common' directory, shared by all revisions.
|
||||
* We also migrate existing content in the the default user folder to the
|
||||
* common directory.
|
||||
*/
|
||||
function migrateSnapStorage() {
|
||||
const snapUserCommonDir = process.env['SNAP_USER_COMMON']
|
||||
if (!snapUserCommonDir) {
|
||||
return
|
||||
}
|
||||
|
||||
const legacyUserDataPath = app.getPath('userData')
|
||||
app.setPath('userData', snapUserCommonDir)
|
||||
console.log(`Set user data dir to ${snapUserCommonDir}`)
|
||||
|
||||
const legacyFiles = fs
|
||||
.readdirSync(legacyUserDataPath)
|
||||
.filter(
|
||||
(fileName) =>
|
||||
fileName !== 'SS' &&
|
||||
fileName !== 'SingletonLock' &&
|
||||
fileName !== 'SingletonCookie' &&
|
||||
fileName !== 'Dictionaries' &&
|
||||
fileName !== 'Standard Notes',
|
||||
)
|
||||
|
||||
if (legacyFiles.length) {
|
||||
for (const fileName of legacyFiles) {
|
||||
const fullFilePath = path.join(legacyUserDataPath, fileName)
|
||||
const dest = snapUserCommonDir
|
||||
console.log(`Migration: moving ${fullFilePath} to ${dest}`)
|
||||
try {
|
||||
fs.moveSync(fullFilePath, path.join(dest, fileName), {
|
||||
overwrite: false,
|
||||
})
|
||||
} catch (error: any) {
|
||||
console.error(`Migration: error occured while moving ${fullFilePath} to ${dest}:`, error?.message ?? error)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Migration: finished moving contents to ${snapUserCommonDir}.`)
|
||||
|
||||
const snapUserData = process.env['SNAP_USER_DATA']
|
||||
const store = new Store(snapUserCommonDir)
|
||||
if (snapUserData && store.data.backupsLocation.startsWith(path.resolve(snapUserData, '..'))) {
|
||||
/**
|
||||
* Backups location has not been altered by the user. Move it to the
|
||||
* user documents directory
|
||||
*/
|
||||
console.log(`Migration: moving ${store.data.backupsLocation} to ${Paths.documentsDir}`)
|
||||
const newLocation = path.join(Paths.documentsDir, path.basename(store.data.backupsLocation))
|
||||
try {
|
||||
fs.copySync(store.data.backupsLocation, newLocation)
|
||||
} catch (error: any) {
|
||||
console.error(
|
||||
`Migration: error occured while moving ${store.data.backupsLocation} to ${Paths.documentsDir}:`,
|
||||
error?.message ?? error,
|
||||
)
|
||||
}
|
||||
store.set(StoreKeys.BackupsLocation, newLocation)
|
||||
console.log('Migration: finished moving backups directory.')
|
||||
}
|
||||
}
|
||||
}
|
||||
245
packages/desktop/app/javascripts/Main/Backups/BackupsManager.ts
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
import { dialog, WebContents, shell } from 'electron'
|
||||
import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
import { AppMessageType, MessageType } from '../../../../test/TestIpcMessage'
|
||||
import { AppState } from '../../../application'
|
||||
import { MessageToWebApp } from '../../Shared/IpcMessages'
|
||||
import { BackupsManagerInterface } from './BackupsManagerInterface'
|
||||
import {
|
||||
deleteDir,
|
||||
deleteDirContents,
|
||||
ensureDirectoryExists,
|
||||
FileDoesNotExist,
|
||||
moveFiles,
|
||||
openDirectoryPicker,
|
||||
} from '../Utils/FileUtils'
|
||||
import { Paths } from '../Types/Paths'
|
||||
import { StoreKeys } from '../Store'
|
||||
import { backups as str } from '../Strings'
|
||||
import { handleTestMessage, send } from '../Utils/Testing'
|
||||
import { isTesting, last } from '../Utils/Utils'
|
||||
|
||||
function log(...message: any) {
|
||||
console.log('BackupsManager:', ...message)
|
||||
}
|
||||
|
||||
function logError(...message: any) {
|
||||
console.error('BackupsManager:', ...message)
|
||||
}
|
||||
|
||||
export const enum EnsureRecentBackupExists {
|
||||
Success = 0,
|
||||
BackupsAreDisabled = 1,
|
||||
FailedToCreateBackup = 2,
|
||||
}
|
||||
|
||||
export const BackupsDirectoryName = 'Standard Notes Backups'
|
||||
const BackupFileExtension = '.txt'
|
||||
|
||||
function backupFileNameToDate(string: string): number {
|
||||
string = path.basename(string, '.txt')
|
||||
const dateTimeDelimiter = string.indexOf('T')
|
||||
const date = string.slice(0, dateTimeDelimiter)
|
||||
|
||||
const time = string.slice(dateTimeDelimiter + 1).replace(/-/g, ':')
|
||||
return Date.parse(date + 'T' + time)
|
||||
}
|
||||
|
||||
function dateToSafeFilename(date: Date) {
|
||||
return date.toISOString().replace(/:/g, '-')
|
||||
}
|
||||
|
||||
async function copyDecryptScript(location: string) {
|
||||
try {
|
||||
await ensureDirectoryExists(location)
|
||||
await fs.copyFile(Paths.decryptScript, path.join(location, path.basename(Paths.decryptScript)))
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
export function createBackupsManager(webContents: WebContents, appState: AppState): BackupsManagerInterface {
|
||||
let backupsLocation = appState.store.get(StoreKeys.BackupsLocation)
|
||||
let backupsDisabled = appState.store.get(StoreKeys.BackupsDisabled)
|
||||
let needsBackup = false
|
||||
|
||||
if (!backupsDisabled) {
|
||||
void copyDecryptScript(backupsLocation)
|
||||
}
|
||||
|
||||
determineLastBackupDate(backupsLocation)
|
||||
.then((date) => appState.setBackupCreationDate(date))
|
||||
.catch(console.error)
|
||||
|
||||
async function setBackupsLocation(location: string) {
|
||||
const previousLocation = backupsLocation
|
||||
if (previousLocation === location) {
|
||||
return
|
||||
}
|
||||
|
||||
const newLocation = path.join(location, BackupsDirectoryName)
|
||||
let previousLocationFiles = await fs.readdir(previousLocation)
|
||||
const backupFiles = previousLocationFiles
|
||||
.filter((fileName) => fileName.endsWith(BackupFileExtension))
|
||||
.map((fileName) => path.join(previousLocation, fileName))
|
||||
|
||||
await moveFiles(backupFiles, newLocation)
|
||||
await copyDecryptScript(newLocation)
|
||||
|
||||
previousLocationFiles = await fs.readdir(previousLocation)
|
||||
if (previousLocationFiles.length === 0 || previousLocationFiles[0] === path.basename(Paths.decryptScript)) {
|
||||
await deleteDir(previousLocation)
|
||||
}
|
||||
|
||||
/** Wait for the operation to be successful before saving new location */
|
||||
backupsLocation = newLocation
|
||||
appState.store.set(StoreKeys.BackupsLocation, backupsLocation)
|
||||
}
|
||||
|
||||
async function saveBackupData(data: any) {
|
||||
if (backupsDisabled) {
|
||||
return
|
||||
}
|
||||
|
||||
let success: boolean
|
||||
let name: string | undefined
|
||||
|
||||
try {
|
||||
name = await writeDataToFile(data)
|
||||
log(`Data backup successfully saved: ${name}`)
|
||||
success = true
|
||||
appState.setBackupCreationDate(Date.now())
|
||||
} catch (err) {
|
||||
success = false
|
||||
logError('An error occurred saving backup file', err)
|
||||
}
|
||||
|
||||
webContents.send(MessageToWebApp.FinishedSavingBackup, { success })
|
||||
|
||||
if (isTesting()) {
|
||||
send(AppMessageType.SavedBackup)
|
||||
}
|
||||
|
||||
return name
|
||||
}
|
||||
|
||||
function performBackup() {
|
||||
if (backupsDisabled) {
|
||||
return
|
||||
}
|
||||
|
||||
webContents.send(MessageToWebApp.PerformAutomatedBackup)
|
||||
}
|
||||
|
||||
async function writeDataToFile(data: any): Promise<string> {
|
||||
await ensureDirectoryExists(backupsLocation)
|
||||
|
||||
const name = dateToSafeFilename(new Date()) + BackupFileExtension
|
||||
const filePath = path.join(backupsLocation, name)
|
||||
await fs.writeFile(filePath, data)
|
||||
return name
|
||||
}
|
||||
|
||||
let interval: NodeJS.Timeout | undefined
|
||||
function beginBackups() {
|
||||
if (interval) {
|
||||
clearInterval(interval)
|
||||
}
|
||||
|
||||
needsBackup = true
|
||||
const hoursInterval = 12
|
||||
const seconds = hoursInterval * 60 * 60
|
||||
const milliseconds = seconds * 1000
|
||||
interval = setInterval(performBackup, milliseconds)
|
||||
}
|
||||
|
||||
function toggleBackupsStatus() {
|
||||
backupsDisabled = !backupsDisabled
|
||||
appState.store.set(StoreKeys.BackupsDisabled, backupsDisabled)
|
||||
/** Create a backup on reactivation. */
|
||||
if (!backupsDisabled) {
|
||||
performBackup()
|
||||
}
|
||||
}
|
||||
|
||||
if (isTesting()) {
|
||||
handleTestMessage(MessageType.DataArchive, (data: any) => saveBackupData(data))
|
||||
handleTestMessage(MessageType.BackupsAreEnabled, () => !backupsDisabled)
|
||||
handleTestMessage(MessageType.ToggleBackupsEnabled, toggleBackupsStatus)
|
||||
handleTestMessage(MessageType.BackupsLocation, () => backupsLocation)
|
||||
handleTestMessage(MessageType.PerformBackup, performBackup)
|
||||
handleTestMessage(MessageType.CopyDecryptScript, copyDecryptScript)
|
||||
handleTestMessage(MessageType.ChangeBackupsLocation, setBackupsLocation)
|
||||
}
|
||||
|
||||
return {
|
||||
get backupsAreEnabled() {
|
||||
return !backupsDisabled
|
||||
},
|
||||
get backupsLocation() {
|
||||
return backupsLocation
|
||||
},
|
||||
saveBackupData,
|
||||
performBackup,
|
||||
beginBackups,
|
||||
toggleBackupsStatus,
|
||||
async backupsCount(): Promise<number> {
|
||||
let files = await fs.readdir(backupsLocation)
|
||||
files = files.filter((fileName) => fileName.endsWith(BackupFileExtension))
|
||||
return files.length
|
||||
},
|
||||
applicationDidBlur() {
|
||||
if (needsBackup) {
|
||||
needsBackup = false
|
||||
performBackup()
|
||||
}
|
||||
},
|
||||
viewBackups() {
|
||||
void shell.openPath(backupsLocation)
|
||||
},
|
||||
async deleteBackups() {
|
||||
await deleteDirContents(backupsLocation)
|
||||
return copyDecryptScript(backupsLocation)
|
||||
},
|
||||
|
||||
async changeBackupsLocation() {
|
||||
const path = await openDirectoryPicker()
|
||||
|
||||
if (!path) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await setBackupsLocation(path)
|
||||
performBackup()
|
||||
} catch (e) {
|
||||
logError(e)
|
||||
void dialog.showMessageBox({
|
||||
message: str().errorChangingDirectory(e),
|
||||
})
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function determineLastBackupDate(backupsLocation: string): Promise<number | null> {
|
||||
try {
|
||||
const files = (await fs.readdir(backupsLocation))
|
||||
.filter((filename) => filename.endsWith(BackupFileExtension) && !Number.isNaN(backupFileNameToDate(filename)))
|
||||
.sort()
|
||||
const lastBackupFileName = last(files)
|
||||
if (!lastBackupFileName) {
|
||||
return null
|
||||
}
|
||||
const backupDate = backupFileNameToDate(lastBackupFileName)
|
||||
if (Number.isNaN(backupDate)) {
|
||||
return null
|
||||
}
|
||||
return backupDate
|
||||
} catch (error: any) {
|
||||
if (error.code !== FileDoesNotExist) {
|
||||
console.error(error)
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
export interface BackupsManagerInterface {
|
||||
backupsAreEnabled: boolean
|
||||
toggleBackupsStatus(): void
|
||||
backupsLocation: string
|
||||
backupsCount(): Promise<number>
|
||||
applicationDidBlur(): void
|
||||
changeBackupsLocation(): void
|
||||
beginBackups(): void
|
||||
performBackup(): void
|
||||
deleteBackups(): Promise<void>
|
||||
viewBackups(): void
|
||||
saveBackupData(data: unknown): void
|
||||
}
|
||||
115
packages/desktop/app/javascripts/Main/ExtensionsServer.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import fs from 'fs'
|
||||
import http, { IncomingMessage, ServerResponse } from 'http'
|
||||
import mime from 'mime-types'
|
||||
import path from 'path'
|
||||
import { URL } from 'url'
|
||||
import { FileDoesNotExist } from './Utils/FileUtils'
|
||||
import { Paths } from './Types/Paths'
|
||||
import { extensions as str } from './Strings'
|
||||
|
||||
const Protocol = 'http'
|
||||
|
||||
function logError(...message: any) {
|
||||
console.error('extServer:', ...message)
|
||||
}
|
||||
|
||||
function log(...message: any) {
|
||||
console.log('extServer:', ...message)
|
||||
}
|
||||
|
||||
export function normalizeFilePath(requestUrl: string, host: string): string {
|
||||
const isThirdPartyComponent = requestUrl.startsWith('/Extensions')
|
||||
const isNativeComponent = requestUrl.startsWith('/components')
|
||||
if (!isThirdPartyComponent && !isNativeComponent) {
|
||||
throw new Error(`URL '${requestUrl}' falls outside of the extensions/features domain.`)
|
||||
}
|
||||
|
||||
const removedPrefix = requestUrl.replace('/components', '').replace('/Extensions', '')
|
||||
|
||||
const base = `${Protocol}://${host}`
|
||||
const url = new URL(removedPrefix, base)
|
||||
|
||||
/**
|
||||
* Normalize path (parse '..' and '.') so that we prevent path traversal by
|
||||
* joining a fully resolved path to the Extensions dir.
|
||||
*/
|
||||
const modifiedReqUrl = path.normalize(url.pathname)
|
||||
if (isThirdPartyComponent) {
|
||||
return path.join(Paths.extensionsDir, modifiedReqUrl)
|
||||
} else {
|
||||
return path.join(Paths.components, modifiedReqUrl)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRequest(request: IncomingMessage, response: ServerResponse) {
|
||||
try {
|
||||
if (!request.url) {
|
||||
throw new Error('No url.')
|
||||
}
|
||||
if (!request.headers.host) {
|
||||
throw new Error('No `host` header.')
|
||||
}
|
||||
|
||||
const filePath = normalizeFilePath(request.url, request.headers.host)
|
||||
|
||||
const stat = await fs.promises.lstat(filePath)
|
||||
|
||||
if (!stat.isFile()) {
|
||||
throw new Error('Client requested something that is not a file.')
|
||||
}
|
||||
|
||||
const mimeType = mime.lookup(path.parse(filePath).ext)
|
||||
|
||||
response.setHeader('Access-Control-Allow-Origin', '*')
|
||||
response.setHeader('Cache-Control', 'max-age=604800')
|
||||
response.setHeader('Content-Type', `${mimeType}; charset=utf-8`)
|
||||
|
||||
const data = fs.readFileSync(filePath)
|
||||
|
||||
response.writeHead(200)
|
||||
|
||||
response.end(data)
|
||||
} catch (error: any) {
|
||||
onRequestError(error, response)
|
||||
}
|
||||
}
|
||||
|
||||
function onRequestError(error: Error | { code: string }, response: ServerResponse) {
|
||||
let responseCode: number
|
||||
let message: string
|
||||
|
||||
if ('code' in error && error.code === FileDoesNotExist) {
|
||||
responseCode = 404
|
||||
message = str().missingExtension
|
||||
} else {
|
||||
logError(error)
|
||||
responseCode = 500
|
||||
message = str().unableToLoadExtension
|
||||
}
|
||||
|
||||
response.writeHead(responseCode)
|
||||
response.end(message)
|
||||
}
|
||||
|
||||
export function createExtensionsServer(): string {
|
||||
const port = 45653
|
||||
const ip = '127.0.0.1'
|
||||
const host = `${Protocol}://${ip}:${port}`
|
||||
|
||||
const initCallback = () => {
|
||||
log(`Server started at ${host}`)
|
||||
}
|
||||
|
||||
try {
|
||||
http
|
||||
.createServer(handleRequest)
|
||||
.listen(port, ip, initCallback)
|
||||
.on('error', (err) => {
|
||||
console.error('Error listening on extServer', err)
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error creating ext server', error)
|
||||
}
|
||||
|
||||
return host
|
||||
}
|
||||
|
|
@ -0,0 +1,156 @@
|
|||
import { FileBackupsDevice, FileBackupsMapping } from '@web/Application/Device/DesktopSnjsExports'
|
||||
import { AppState } from 'app/application'
|
||||
import { StoreKeys } from '../Store'
|
||||
import {
|
||||
ensureDirectoryExists,
|
||||
moveDirContents,
|
||||
openDirectoryPicker,
|
||||
readJSONFile,
|
||||
writeFile,
|
||||
writeJSONFile,
|
||||
} from '../Utils/FileUtils'
|
||||
import { FileDownloader } from './FileDownloader'
|
||||
import { shell } from 'electron'
|
||||
|
||||
export const FileBackupsConstantsV1 = {
|
||||
Version: '1.0.0',
|
||||
MetadataFileName: 'metadata.sn.json',
|
||||
BinaryFileName: 'file.encrypted',
|
||||
}
|
||||
|
||||
export class FilesBackupManager implements FileBackupsDevice {
|
||||
constructor(private appState: AppState) {}
|
||||
|
||||
public isFilesBackupsEnabled(): Promise<boolean> {
|
||||
return Promise.resolve(this.appState.store.get(StoreKeys.FileBackupsEnabled))
|
||||
}
|
||||
|
||||
public async enableFilesBackups(): Promise<void> {
|
||||
const currentLocation = await this.getFilesBackupsLocation()
|
||||
|
||||
if (!currentLocation) {
|
||||
const result = await this.changeFilesBackupsLocation()
|
||||
|
||||
if (!result) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
this.appState.store.set(StoreKeys.FileBackupsEnabled, true)
|
||||
|
||||
const mapping = this.getMappingFileFromDisk()
|
||||
|
||||
if (!mapping) {
|
||||
await this.saveFilesBackupsMappingFile(this.defaultMappingFileValue())
|
||||
}
|
||||
}
|
||||
|
||||
public disableFilesBackups(): Promise<void> {
|
||||
this.appState.store.set(StoreKeys.FileBackupsEnabled, false)
|
||||
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
public async changeFilesBackupsLocation(): Promise<string | undefined> {
|
||||
const newPath = await openDirectoryPicker()
|
||||
|
||||
if (!newPath) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const oldPath = await this.getFilesBackupsLocation()
|
||||
|
||||
if (oldPath) {
|
||||
await moveDirContents(oldPath, newPath)
|
||||
}
|
||||
|
||||
this.appState.store.set(StoreKeys.FileBackupsLocation, newPath)
|
||||
|
||||
return newPath
|
||||
}
|
||||
|
||||
public getFilesBackupsLocation(): Promise<string> {
|
||||
return Promise.resolve(this.appState.store.get(StoreKeys.FileBackupsLocation))
|
||||
}
|
||||
|
||||
private getMappingFileLocation(): string {
|
||||
const base = this.appState.store.get(StoreKeys.FileBackupsLocation)
|
||||
return `${base}/info.json`
|
||||
}
|
||||
|
||||
private async getMappingFileFromDisk(): Promise<FileBackupsMapping | undefined> {
|
||||
return readJSONFile<FileBackupsMapping>(this.getMappingFileLocation())
|
||||
}
|
||||
|
||||
private defaultMappingFileValue(): FileBackupsMapping {
|
||||
return { version: FileBackupsConstantsV1.Version, files: {} }
|
||||
}
|
||||
|
||||
async getFilesBackupsMappingFile(): Promise<FileBackupsMapping> {
|
||||
const data = await this.getMappingFileFromDisk()
|
||||
|
||||
if (!data) {
|
||||
return this.defaultMappingFileValue()
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
async openFilesBackupsLocation(): Promise<void> {
|
||||
const location = await this.getFilesBackupsLocation()
|
||||
|
||||
void shell.openPath(location)
|
||||
}
|
||||
|
||||
async saveFilesBackupsMappingFile(file: FileBackupsMapping): Promise<'success' | 'failed'> {
|
||||
await writeJSONFile(this.getMappingFileLocation(), file)
|
||||
|
||||
return 'success'
|
||||
}
|
||||
|
||||
async saveFilesBackupsFile(
|
||||
uuid: string,
|
||||
metaFile: string,
|
||||
downloadRequest: {
|
||||
chunkSizes: number[]
|
||||
valetToken: string
|
||||
url: string
|
||||
},
|
||||
): Promise<'success' | 'failed'> {
|
||||
const backupsDir = await this.getFilesBackupsLocation()
|
||||
|
||||
const fileDir = `${backupsDir}/${uuid}`
|
||||
const metaFilePath = `${fileDir}/${FileBackupsConstantsV1.MetadataFileName}`
|
||||
const binaryPath = `${fileDir}/${FileBackupsConstantsV1.BinaryFileName}`
|
||||
|
||||
await ensureDirectoryExists(fileDir)
|
||||
|
||||
await writeFile(metaFilePath, metaFile)
|
||||
|
||||
const downloader = new FileDownloader(
|
||||
downloadRequest.chunkSizes,
|
||||
downloadRequest.valetToken,
|
||||
downloadRequest.url,
|
||||
binaryPath,
|
||||
)
|
||||
|
||||
const result = await downloader.run()
|
||||
|
||||
if (result === 'success') {
|
||||
const mapping = await this.getFilesBackupsMappingFile()
|
||||
|
||||
mapping.files[uuid] = {
|
||||
backedUpOn: new Date(),
|
||||
absolutePath: fileDir,
|
||||
relativePath: uuid,
|
||||
metadataFileName: FileBackupsConstantsV1.MetadataFileName,
|
||||
binaryFileName: FileBackupsConstantsV1.BinaryFileName,
|
||||
version: FileBackupsConstantsV1.Version,
|
||||
}
|
||||
|
||||
await this.saveFilesBackupsMappingFile(mapping)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
import { WriteStream, createWriteStream } from 'fs'
|
||||
import { downloadData } from './FileNetworking'
|
||||
|
||||
export class FileDownloader {
|
||||
writeStream: WriteStream
|
||||
|
||||
constructor(private chunkSizes: number[], private valetToken: string, private url: string, filePath: string) {
|
||||
this.writeStream = createWriteStream(filePath, { flags: 'a' })
|
||||
}
|
||||
|
||||
public async run(): Promise<'success' | 'failed'> {
|
||||
const result = await this.downloadChunk(0, 0)
|
||||
|
||||
this.writeStream.close()
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
private async downloadChunk(chunkIndex = 0, contentRangeStart: number): Promise<'success' | 'failed'> {
|
||||
const pullChunkSize = this.chunkSizes[chunkIndex]
|
||||
|
||||
const headers = {
|
||||
'x-valet-token': this.valetToken,
|
||||
'x-chunk-size': pullChunkSize.toString(),
|
||||
range: `bytes=${contentRangeStart}-`,
|
||||
}
|
||||
|
||||
const response = await downloadData(this.writeStream, this.url, headers)
|
||||
|
||||
if (!String(response.status).startsWith('2')) {
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
const contentRangeHeader = response.headers['content-range'] as string
|
||||
if (!contentRangeHeader) {
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
const matches = contentRangeHeader.match(/(^[a-zA-Z][\w]*)\s+(\d+)\s?-\s?(\d+)?\s?\/?\s?(\d+|\*)?/)
|
||||
if (!matches || matches.length !== 5) {
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
const rangeStart = +matches[2]
|
||||
const rangeEnd = +matches[3]
|
||||
const totalSize = +matches[4]
|
||||
|
||||
if (rangeEnd < totalSize - 1) {
|
||||
return this.downloadChunk(++chunkIndex, rangeStart + pullChunkSize)
|
||||
}
|
||||
|
||||
return 'success'
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import { WriteStream } from 'fs'
|
||||
import axios, { AxiosResponseHeaders, AxiosRequestHeaders } from 'axios'
|
||||
|
||||
export async function downloadData(
|
||||
writeStream: WriteStream,
|
||||
url: string,
|
||||
headers: AxiosRequestHeaders,
|
||||
): Promise<{
|
||||
headers: AxiosResponseHeaders
|
||||
status: number
|
||||
}> {
|
||||
const response = await axios.get(url, {
|
||||
responseType: 'arraybuffer',
|
||||
headers: headers,
|
||||
})
|
||||
|
||||
if (String(response.status).startsWith('2')) {
|
||||
writeStream.write(response.data)
|
||||
}
|
||||
|
||||
return { headers: response.headers, status: response.status }
|
||||
}
|
||||
104
packages/desktop/app/javascripts/Main/Keychain/Keychain.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import { app, BrowserWindow, ipcMain } from 'electron'
|
||||
import keytar from 'keytar'
|
||||
import { isLinux } from '../Types/Platforms'
|
||||
import { AppName } from '../Strings'
|
||||
import { keychainAccessIsUserConfigurable } from '../Types/Constants'
|
||||
import { isDev, isTesting } from '../Utils/Utils'
|
||||
import { MessageToMainProcess } from '../../Shared/IpcMessages'
|
||||
import { Urls, Paths } from '../Types/Paths'
|
||||
import { Store, StoreKeys } from '../Store'
|
||||
import { KeychainInterface } from './KeychainInterface'
|
||||
|
||||
const ServiceName = isTesting() ? AppName + ' (Testing)' : isDev() ? AppName + ' (Development)' : AppName
|
||||
const AccountName = 'Standard Notes Account'
|
||||
|
||||
async function ensureKeychainAccess(store: Store): Promise<BrowserWindow | undefined> {
|
||||
if (!isLinux()) {
|
||||
/** Assume keychain is accessible */
|
||||
return
|
||||
}
|
||||
const useNativeKeychain = store.get(StoreKeys.UseNativeKeychain)
|
||||
if (useNativeKeychain === null) {
|
||||
/**
|
||||
* App has never attempted to access keychain before. Do it and set the
|
||||
* store value according to what happens
|
||||
*/
|
||||
try {
|
||||
await getKeychainValue()
|
||||
store.set(StoreKeys.UseNativeKeychain, true)
|
||||
} catch (_) {
|
||||
/** Can't access keychain. */
|
||||
if (keychainAccessIsUserConfigurable) {
|
||||
return askForKeychainAccess(store)
|
||||
} else {
|
||||
/** User can't configure keychain access, fall back to local storage */
|
||||
store.set(StoreKeys.UseNativeKeychain, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function askForKeychainAccess(store: Store): Promise<BrowserWindow> {
|
||||
const window = new BrowserWindow({
|
||||
width: 540,
|
||||
height: 400,
|
||||
center: true,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
preload: Paths.grantLinuxPasswordsAccessJs,
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
},
|
||||
autoHideMenuBar: true,
|
||||
})
|
||||
|
||||
window.on('ready-to-show', window.show)
|
||||
|
||||
void window.loadURL(Urls.grantLinuxPasswordsAccessHtml)
|
||||
|
||||
const quit = () => {
|
||||
app.quit()
|
||||
}
|
||||
ipcMain.once(MessageToMainProcess.Quit, quit)
|
||||
window.once('close', quit)
|
||||
|
||||
ipcMain.on(MessageToMainProcess.LearnMoreAboutKeychainAccess, () => {
|
||||
window.setSize(window.getSize()[0], 600, true)
|
||||
})
|
||||
|
||||
return new Promise((resolve) => {
|
||||
ipcMain.once(MessageToMainProcess.UseLocalstorageForKeychain, () => {
|
||||
store.set(StoreKeys.UseNativeKeychain, false)
|
||||
ipcMain.removeListener(MessageToMainProcess.Quit, quit)
|
||||
window.removeListener('close', quit)
|
||||
resolve(window)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function getKeychainValue(): Promise<unknown> {
|
||||
try {
|
||||
const value = await keytar.getPassword(ServiceName, AccountName)
|
||||
if (value) {
|
||||
return JSON.parse(value)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function setKeychainValue(value: unknown): Promise<void> {
|
||||
return keytar.setPassword(ServiceName, AccountName, JSON.stringify(value))
|
||||
}
|
||||
|
||||
function clearKeychainValue(): Promise<boolean> {
|
||||
return keytar.deletePassword(ServiceName, AccountName)
|
||||
}
|
||||
|
||||
export const Keychain: KeychainInterface = {
|
||||
ensureKeychainAccess,
|
||||
getKeychainValue,
|
||||
setKeychainValue,
|
||||
clearKeychainValue,
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
import { BrowserWindow } from 'electron'
|
||||
import { Store } from '../Store'
|
||||
|
||||
export interface KeychainInterface {
|
||||
ensureKeychainAccess(store: Store): Promise<BrowserWindow | undefined>
|
||||
getKeychainValue(): Promise<unknown>
|
||||
setKeychainValue(value: unknown): Promise<void>
|
||||
clearKeychainValue(): Promise<boolean>
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
export interface MenuManagerInterface {
|
||||
reload(): void
|
||||
popupMenu(): void
|
||||
}
|
||||
667
packages/desktop/app/javascripts/Main/Menus/Menus.ts
Normal file
|
|
@ -0,0 +1,667 @@
|
|||
import { AppState } from 'app/application'
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
ContextMenuParams,
|
||||
dialog,
|
||||
Menu,
|
||||
MenuItemConstructorOptions,
|
||||
shell,
|
||||
WebContents,
|
||||
} from 'electron'
|
||||
import { autorun } from 'mobx'
|
||||
import { autoUpdatingAvailable } from '../Types/Constants'
|
||||
import { isLinux, isMac } from '../Types/Platforms'
|
||||
import { Store, StoreKeys } from '../Store'
|
||||
import { appMenu as str, contextMenu } from '../Strings'
|
||||
import { handleTestMessage } from '../Utils/Testing'
|
||||
import { TrayManager } from '../TrayManager'
|
||||
import { SpellcheckerManager } from './../SpellcheckerManager'
|
||||
import { BackupsManagerInterface } from './../Backups/BackupsManagerInterface'
|
||||
import { MessageType } from './../../../../test/TestIpcMessage'
|
||||
import { checkForUpdate, openChangelog, showUpdateInstallationDialog } from '../UpdateManager'
|
||||
import { isDev, isTesting } from '../Utils/Utils'
|
||||
import { MenuManagerInterface } from './MenuManagerInterface'
|
||||
|
||||
export const enum MenuId {
|
||||
SpellcheckerLanguages = 'SpellcheckerLanguages',
|
||||
}
|
||||
|
||||
const Separator: MenuItemConstructorOptions = {
|
||||
type: 'separator',
|
||||
}
|
||||
|
||||
export function buildContextMenu(webContents: WebContents, params: ContextMenuParams): Menu {
|
||||
if (!params.isEditable) {
|
||||
return Menu.buildFromTemplate([
|
||||
{
|
||||
role: 'copy',
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
return Menu.buildFromTemplate([
|
||||
...suggestionsMenu(params.selectionText, params.misspelledWord, params.dictionarySuggestions, webContents),
|
||||
Separator,
|
||||
{
|
||||
role: 'undo',
|
||||
},
|
||||
{
|
||||
role: 'redo',
|
||||
},
|
||||
Separator,
|
||||
{
|
||||
role: 'cut',
|
||||
},
|
||||
{
|
||||
role: 'copy',
|
||||
},
|
||||
{
|
||||
role: 'paste',
|
||||
},
|
||||
{
|
||||
role: 'pasteAndMatchStyle',
|
||||
},
|
||||
{
|
||||
role: 'selectAll',
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
function suggestionsMenu(
|
||||
selection: string,
|
||||
misspelledWord: string,
|
||||
suggestions: string[],
|
||||
webContents: WebContents,
|
||||
): MenuItemConstructorOptions[] {
|
||||
if (misspelledWord.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
const learnSpelling = {
|
||||
label: contextMenu().learnSpelling,
|
||||
click() {
|
||||
webContents.session.addWordToSpellCheckerDictionary(misspelledWord)
|
||||
},
|
||||
}
|
||||
|
||||
if (suggestions.length === 0) {
|
||||
return [
|
||||
{
|
||||
label: contextMenu().noSuggestions,
|
||||
enabled: false,
|
||||
},
|
||||
Separator,
|
||||
learnSpelling,
|
||||
]
|
||||
}
|
||||
|
||||
return [
|
||||
...suggestions.map((suggestion) => ({
|
||||
label: suggestion,
|
||||
click() {
|
||||
webContents.replaceMisspelling(suggestion)
|
||||
},
|
||||
})),
|
||||
Separator,
|
||||
learnSpelling,
|
||||
]
|
||||
}
|
||||
|
||||
export function createMenuManager({
|
||||
window,
|
||||
appState,
|
||||
backupsManager,
|
||||
trayManager,
|
||||
store,
|
||||
spellcheckerManager,
|
||||
}: {
|
||||
window: Electron.BrowserWindow
|
||||
appState: AppState
|
||||
backupsManager: BackupsManagerInterface
|
||||
trayManager: TrayManager
|
||||
store: Store
|
||||
spellcheckerManager?: SpellcheckerManager
|
||||
}): MenuManagerInterface {
|
||||
let menu: Menu
|
||||
|
||||
if (isTesting()) {
|
||||
// eslint-disable-next-line no-var
|
||||
var hasReloaded = false
|
||||
// eslint-disable-next-line no-var
|
||||
var hasReloadedTimeout: any
|
||||
handleTestMessage(MessageType.AppMenuItems, () =>
|
||||
menu.items.map((item) => ({
|
||||
label: item.label,
|
||||
role: item.role,
|
||||
submenu: {
|
||||
items: item.submenu?.items?.map((subItem) => ({
|
||||
id: subItem.id,
|
||||
label: subItem.label,
|
||||
})),
|
||||
},
|
||||
})),
|
||||
)
|
||||
handleTestMessage(MessageType.ClickLanguage, (code) => {
|
||||
menu.getMenuItemById(MessageType.ClickLanguage + code)!.click()
|
||||
})
|
||||
handleTestMessage(MessageType.HasReloadedMenu, () => hasReloaded)
|
||||
}
|
||||
|
||||
function reload() {
|
||||
if (isTesting()) {
|
||||
// eslint-disable-next-line block-scoped-var
|
||||
hasReloaded = true
|
||||
// eslint-disable-next-line block-scoped-var
|
||||
clearTimeout(hasReloadedTimeout)
|
||||
// eslint-disable-next-line block-scoped-var
|
||||
hasReloadedTimeout = setTimeout(() => {
|
||||
// eslint-disable-next-line block-scoped-var
|
||||
hasReloaded = false
|
||||
}, 300)
|
||||
}
|
||||
|
||||
menu = Menu.buildFromTemplate([
|
||||
...(isMac() ? [macAppMenu(app.name)] : []),
|
||||
editMenu(spellcheckerManager, reload),
|
||||
viewMenu(window, store, reload),
|
||||
windowMenu(store, trayManager, reload),
|
||||
backupsMenu(backupsManager, reload),
|
||||
updateMenu(window, appState),
|
||||
...(isLinux() ? [keyringMenu(window, store)] : []),
|
||||
helpMenu(window, shell),
|
||||
])
|
||||
Menu.setApplicationMenu(menu)
|
||||
}
|
||||
autorun(() => {
|
||||
reload()
|
||||
})
|
||||
|
||||
return {
|
||||
reload,
|
||||
popupMenu() {
|
||||
if (isDev()) {
|
||||
/** Check the state */
|
||||
if (!menu) {
|
||||
throw new Error('called popupMenu() before loading')
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line no-unused-expressions
|
||||
menu?.popup()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const enum Roles {
|
||||
Undo = 'undo',
|
||||
Redo = 'redo',
|
||||
Cut = 'cut',
|
||||
Copy = 'copy',
|
||||
Paste = 'paste',
|
||||
PasteAndMatchStyle = 'pasteAndMatchStyle',
|
||||
SelectAll = 'selectAll',
|
||||
Reload = 'reload',
|
||||
ToggleDevTools = 'toggleDevTools',
|
||||
ResetZoom = 'resetZoom',
|
||||
ZoomIn = 'zoomIn',
|
||||
ZoomOut = 'zoomOut',
|
||||
ToggleFullScreen = 'togglefullscreen',
|
||||
Window = 'window',
|
||||
Minimize = 'minimize',
|
||||
Close = 'close',
|
||||
Help = 'help',
|
||||
About = 'about',
|
||||
Services = 'services',
|
||||
Hide = 'hide',
|
||||
HideOthers = 'hideOthers',
|
||||
UnHide = 'unhide',
|
||||
Quit = 'quit',
|
||||
StartSeeking = 'startSpeaking',
|
||||
StopSeeking = 'stopSpeaking',
|
||||
Zoom = 'zoom',
|
||||
Front = 'front',
|
||||
}
|
||||
|
||||
const KeyCombinations = {
|
||||
CmdOrCtrlW: 'CmdOrCtrl + W',
|
||||
CmdOrCtrlM: 'CmdOrCtrl + M',
|
||||
AltM: 'Alt + m',
|
||||
}
|
||||
|
||||
const enum MenuItemTypes {
|
||||
CheckBox = 'checkbox',
|
||||
Radio = 'radio',
|
||||
}
|
||||
|
||||
const Urls = {
|
||||
Support: 'mailto:help@standardnotes.com',
|
||||
Website: 'https://standardnotes.com',
|
||||
GitHub: 'https://github.com/standardnotes',
|
||||
Slack: 'https://standardnotes.com/slack',
|
||||
Twitter: 'https://twitter.com/StandardNotes',
|
||||
GitHubReleases: 'https://github.com/standardnotes/desktop/releases',
|
||||
}
|
||||
|
||||
function macAppMenu(appName: string): MenuItemConstructorOptions {
|
||||
return {
|
||||
role: 'appMenu',
|
||||
label: appName,
|
||||
submenu: [
|
||||
{
|
||||
role: Roles.About,
|
||||
},
|
||||
Separator,
|
||||
{
|
||||
role: Roles.Services,
|
||||
submenu: [],
|
||||
},
|
||||
Separator,
|
||||
{
|
||||
role: Roles.Hide,
|
||||
},
|
||||
{
|
||||
role: Roles.HideOthers,
|
||||
},
|
||||
{
|
||||
role: Roles.UnHide,
|
||||
},
|
||||
Separator,
|
||||
{
|
||||
role: Roles.Quit,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function editMenu(spellcheckerManager: SpellcheckerManager | undefined, reload: () => any): MenuItemConstructorOptions {
|
||||
if (isDev()) {
|
||||
/** Check for invalid state */
|
||||
if (!isMac() && spellcheckerManager === undefined) {
|
||||
throw new Error('spellcheckerManager === undefined')
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
role: 'editMenu',
|
||||
label: str().edit,
|
||||
submenu: [
|
||||
{
|
||||
role: Roles.Undo,
|
||||
},
|
||||
{
|
||||
role: Roles.Redo,
|
||||
},
|
||||
Separator,
|
||||
{
|
||||
role: Roles.Cut,
|
||||
},
|
||||
{
|
||||
role: Roles.Copy,
|
||||
},
|
||||
{
|
||||
role: Roles.Paste,
|
||||
},
|
||||
{
|
||||
role: Roles.PasteAndMatchStyle,
|
||||
},
|
||||
{
|
||||
role: Roles.SelectAll,
|
||||
},
|
||||
...(isMac() ? [Separator, macSpeechMenu()] : [spellcheckerMenu(spellcheckerManager!, reload)]),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function macSpeechMenu(): MenuItemConstructorOptions {
|
||||
return {
|
||||
label: str().speech,
|
||||
submenu: [
|
||||
{
|
||||
role: Roles.StopSeeking,
|
||||
},
|
||||
{
|
||||
role: Roles.StopSeeking,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function spellcheckerMenu(spellcheckerManager: SpellcheckerManager, reload: () => any): MenuItemConstructorOptions {
|
||||
return {
|
||||
id: MenuId.SpellcheckerLanguages,
|
||||
label: str().spellcheckerLanguages,
|
||||
submenu: spellcheckerManager.languages().map(
|
||||
({ name, code, enabled }): MenuItemConstructorOptions => ({
|
||||
...(isTesting() ? { id: MessageType.ClickLanguage + code } : {}),
|
||||
label: name,
|
||||
type: MenuItemTypes.CheckBox,
|
||||
checked: enabled,
|
||||
click: () => {
|
||||
if (enabled) {
|
||||
spellcheckerManager.removeLanguage(code)
|
||||
} else {
|
||||
spellcheckerManager.addLanguage(code)
|
||||
}
|
||||
reload()
|
||||
},
|
||||
}),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
function viewMenu(window: Electron.BrowserWindow, store: Store, reload: () => any): MenuItemConstructorOptions {
|
||||
return {
|
||||
label: str().view,
|
||||
submenu: [
|
||||
{
|
||||
role: Roles.Reload,
|
||||
},
|
||||
{
|
||||
role: Roles.ToggleDevTools,
|
||||
},
|
||||
Separator,
|
||||
{
|
||||
role: Roles.ResetZoom,
|
||||
},
|
||||
{
|
||||
role: Roles.ZoomIn,
|
||||
},
|
||||
{
|
||||
role: Roles.ZoomOut,
|
||||
},
|
||||
Separator,
|
||||
{
|
||||
role: Roles.ToggleFullScreen,
|
||||
},
|
||||
...(isMac() ? [] : [Separator, ...menuBarOptions(window, store, reload)]),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function menuBarOptions(window: Electron.BrowserWindow, store: Store, reload: () => any) {
|
||||
const useSystemMenuBar = store.get(StoreKeys.UseSystemMenuBar)
|
||||
let isMenuBarVisible = store.get(StoreKeys.MenuBarVisible)
|
||||
window.setMenuBarVisibility(isMenuBarVisible)
|
||||
return [
|
||||
{
|
||||
visible: !isMac() && useSystemMenuBar,
|
||||
label: str().hideMenuBar,
|
||||
accelerator: KeyCombinations.AltM,
|
||||
click: () => {
|
||||
isMenuBarVisible = !isMenuBarVisible
|
||||
window.setMenuBarVisibility(isMenuBarVisible)
|
||||
store.set(StoreKeys.MenuBarVisible, isMenuBarVisible)
|
||||
},
|
||||
},
|
||||
{
|
||||
label: str().useThemedMenuBar,
|
||||
type: MenuItemTypes.CheckBox,
|
||||
checked: !useSystemMenuBar,
|
||||
click: () => {
|
||||
store.set(StoreKeys.UseSystemMenuBar, !useSystemMenuBar)
|
||||
reload()
|
||||
void dialog.showMessageBox({
|
||||
title: str().preferencesChanged.title,
|
||||
message: str().preferencesChanged.message,
|
||||
})
|
||||
},
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function windowMenu(store: Store, trayManager: TrayManager, reload: () => any): MenuItemConstructorOptions {
|
||||
return {
|
||||
role: Roles.Window,
|
||||
submenu: [
|
||||
{
|
||||
role: Roles.Minimize,
|
||||
},
|
||||
{
|
||||
role: Roles.Close,
|
||||
},
|
||||
Separator,
|
||||
...(isMac() ? macWindowItems() : [minimizeToTrayItem(store, trayManager, reload)]),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function macWindowItems(): MenuItemConstructorOptions[] {
|
||||
return [
|
||||
{
|
||||
label: str().close,
|
||||
accelerator: KeyCombinations.CmdOrCtrlW,
|
||||
role: Roles.Close,
|
||||
},
|
||||
{
|
||||
label: str().minimize,
|
||||
accelerator: KeyCombinations.CmdOrCtrlM,
|
||||
role: Roles.Minimize,
|
||||
},
|
||||
{
|
||||
label: str().zoom,
|
||||
role: Roles.Zoom,
|
||||
},
|
||||
Separator,
|
||||
{
|
||||
label: str().bringAllToFront,
|
||||
role: Roles.Front,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function minimizeToTrayItem(store: Store, trayManager: TrayManager, reload: () => any) {
|
||||
const minimizeToTray = trayManager.shouldMinimizeToTray()
|
||||
return {
|
||||
label: str().minimizeToTrayOnClose,
|
||||
type: MenuItemTypes.CheckBox,
|
||||
checked: minimizeToTray,
|
||||
click() {
|
||||
store.set(StoreKeys.MinimizeToTray, !minimizeToTray)
|
||||
if (trayManager.shouldMinimizeToTray()) {
|
||||
trayManager.createTrayIcon()
|
||||
} else {
|
||||
trayManager.destroyTrayIcon()
|
||||
}
|
||||
reload()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function backupsMenu(archiveManager: BackupsManagerInterface, reload: () => any) {
|
||||
return {
|
||||
label: str().backups,
|
||||
submenu: [
|
||||
{
|
||||
label: archiveManager.backupsAreEnabled ? str().disableAutomaticBackups : str().enableAutomaticBackups,
|
||||
click() {
|
||||
archiveManager.toggleBackupsStatus()
|
||||
reload()
|
||||
},
|
||||
},
|
||||
Separator,
|
||||
{
|
||||
label: str().changeBackupsLocation,
|
||||
click() {
|
||||
archiveManager.changeBackupsLocation()
|
||||
},
|
||||
},
|
||||
{
|
||||
label: str().openBackupsLocation,
|
||||
click() {
|
||||
void shell.openPath(archiveManager.backupsLocation)
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function updateMenu(window: BrowserWindow, appState: AppState) {
|
||||
const updateState = appState.updates
|
||||
let label
|
||||
if (updateState.checkingForUpdate) {
|
||||
label = str().checkingForUpdate
|
||||
} else if (updateState.updateNeeded) {
|
||||
label = str().updateAvailable
|
||||
} else {
|
||||
label = str().updates
|
||||
}
|
||||
const submenu: MenuItemConstructorOptions[] = []
|
||||
const structure = { label, submenu }
|
||||
|
||||
if (autoUpdatingAvailable) {
|
||||
if (updateState.autoUpdateDownloaded && updateState.latestVersion) {
|
||||
submenu.push({
|
||||
label: str().installPendingUpdate(updateState.latestVersion),
|
||||
click() {
|
||||
void showUpdateInstallationDialog(window, appState)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
submenu.push({
|
||||
type: 'checkbox',
|
||||
checked: updateState.enableAutoUpdate,
|
||||
label: str().enableAutomaticUpdates,
|
||||
click() {
|
||||
updateState.toggleAutoUpdate()
|
||||
},
|
||||
})
|
||||
|
||||
submenu.push(Separator)
|
||||
}
|
||||
|
||||
const latestVersion = updateState.latestVersion
|
||||
|
||||
submenu.push({
|
||||
label: str().yourVersion(appState.version),
|
||||
})
|
||||
|
||||
submenu.push({
|
||||
label: latestVersion ? str().latestVersion(latestVersion) : str().releaseNotes,
|
||||
click() {
|
||||
openChangelog(updateState)
|
||||
},
|
||||
})
|
||||
|
||||
if (latestVersion) {
|
||||
submenu.push({
|
||||
label: str().viewReleaseNotes(latestVersion),
|
||||
click() {
|
||||
openChangelog(updateState)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (autoUpdatingAvailable) {
|
||||
submenu.push(Separator)
|
||||
|
||||
if (!updateState.checkingForUpdate) {
|
||||
submenu.push({
|
||||
label: str().checkForUpdate,
|
||||
click() {
|
||||
void checkForUpdate(appState, updateState, true)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (updateState.lastCheck && !updateState.checkingForUpdate) {
|
||||
submenu.push({
|
||||
label: str().lastUpdateCheck(updateState.lastCheck),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return structure
|
||||
}
|
||||
|
||||
function helpMenu(window: Electron.BrowserWindow, shell: Electron.Shell) {
|
||||
return {
|
||||
role: Roles.Help,
|
||||
submenu: [
|
||||
{
|
||||
label: str().emailSupport,
|
||||
click() {
|
||||
void shell.openExternal(Urls.Support)
|
||||
},
|
||||
},
|
||||
{
|
||||
label: str().website,
|
||||
click() {
|
||||
void shell.openExternal(Urls.Website)
|
||||
},
|
||||
},
|
||||
{
|
||||
label: str().gitHub,
|
||||
click() {
|
||||
void shell.openExternal(Urls.GitHub)
|
||||
},
|
||||
},
|
||||
{
|
||||
label: str().slack,
|
||||
click() {
|
||||
void shell.openExternal(Urls.Slack)
|
||||
},
|
||||
},
|
||||
{
|
||||
label: str().twitter,
|
||||
click() {
|
||||
void shell.openExternal(Urls.Twitter)
|
||||
},
|
||||
},
|
||||
Separator,
|
||||
{
|
||||
label: str().toggleErrorConsole,
|
||||
click() {
|
||||
window.webContents.toggleDevTools()
|
||||
},
|
||||
},
|
||||
{
|
||||
label: str().openDataDirectory,
|
||||
click() {
|
||||
const userDataPath = app.getPath('userData')
|
||||
void shell.openPath(userDataPath)
|
||||
},
|
||||
},
|
||||
{
|
||||
label: str().clearCacheAndReload,
|
||||
async click() {
|
||||
await window.webContents.session.clearCache()
|
||||
window.reload()
|
||||
},
|
||||
},
|
||||
Separator,
|
||||
{
|
||||
label: str().version(app.getVersion()),
|
||||
click() {
|
||||
void shell.openExternal(Urls.GitHubReleases)
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/** It's called keyring on Ubuntu */
|
||||
function keyringMenu(window: BrowserWindow, store: Store): MenuItemConstructorOptions {
|
||||
const useNativeKeychain = store.get(StoreKeys.UseNativeKeychain)
|
||||
return {
|
||||
label: str().security.security,
|
||||
submenu: [
|
||||
{
|
||||
enabled: !useNativeKeychain,
|
||||
checked: useNativeKeychain ?? false,
|
||||
type: 'checkbox',
|
||||
label: str().security.useKeyringtoStorePassword,
|
||||
async click() {
|
||||
store.set(StoreKeys.UseNativeKeychain, true)
|
||||
const { response } = await dialog.showMessageBox(window, {
|
||||
message: str().security.enabledKeyringAccessMessage,
|
||||
buttons: [str().security.enabledKeyringQuitNow, str().security.enabledKeyringPostpone],
|
||||
})
|
||||
if (response === 0) {
|
||||
app.quit()
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
75
packages/desktop/app/javascripts/Main/Packages/Networking.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import { IncomingMessage, net } from 'electron'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { pipeline as pipelineFn } from 'stream'
|
||||
import { promisify } from 'util'
|
||||
import { MessageType } from '../../../../test/TestIpcMessage'
|
||||
import { ensureDirectoryExists } from '../Utils/FileUtils'
|
||||
import { handleTestMessage } from '../Utils/Testing'
|
||||
import { isTesting } from '../Utils/Utils'
|
||||
|
||||
const pipeline = promisify(pipelineFn)
|
||||
|
||||
if (isTesting()) {
|
||||
handleTestMessage(MessageType.GetJSON, getJSON)
|
||||
handleTestMessage(MessageType.DownloadFile, downloadFile)
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads a file to the specified destination.
|
||||
* @param filePath path to the saved file (will be created if it does
|
||||
* not exist)
|
||||
*/
|
||||
export async function downloadFile(url: string, filePath: string): Promise<void> {
|
||||
await ensureDirectoryExists(path.dirname(filePath))
|
||||
const response = await get(url)
|
||||
await pipeline(
|
||||
/**
|
||||
* IncomingMessage doesn't implement *every* property of ReadableStream
|
||||
* but still all the ones that pipeline needs
|
||||
* @see https://www.electronjs.org/docs/api/incoming-message
|
||||
*/
|
||||
response as any,
|
||||
fs.createWriteStream(filePath),
|
||||
)
|
||||
}
|
||||
|
||||
export async function getJSON<T>(url: string): Promise<T | undefined> {
|
||||
const response = await get(url)
|
||||
let data = ''
|
||||
return new Promise((resolve, reject) => {
|
||||
response
|
||||
.on('data', (chunk) => {
|
||||
data += chunk
|
||||
})
|
||||
.on('error', reject)
|
||||
.on('end', () => {
|
||||
try {
|
||||
const parsed = JSON.parse(data)
|
||||
resolve(parsed)
|
||||
} catch (error) {
|
||||
resolve(undefined)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export function get(url: string): Promise<IncomingMessage> {
|
||||
const enum Method {
|
||||
Get = 'GET',
|
||||
}
|
||||
const enum RedirectMode {
|
||||
Follow = 'follow',
|
||||
}
|
||||
|
||||
return new Promise<IncomingMessage>((resolve, reject) => {
|
||||
const request = net.request({
|
||||
url,
|
||||
method: Method.Get,
|
||||
redirect: RedirectMode.Follow,
|
||||
})
|
||||
request.on('response', resolve)
|
||||
request.on('error', reject)
|
||||
request.end()
|
||||
})
|
||||
}
|
||||
374
packages/desktop/app/javascripts/Main/Packages/PackageManager.ts
Normal file
|
|
@ -0,0 +1,374 @@
|
|||
import compareVersions from 'compare-versions'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { MessageToWebApp } from '../../Shared/IpcMessages'
|
||||
import {
|
||||
debouncedJSONDiskWriter,
|
||||
deleteDir,
|
||||
deleteDirContents,
|
||||
ensureDirectoryExists,
|
||||
extractNestedZip,
|
||||
FileDoesNotExist,
|
||||
readJSONFile,
|
||||
} from '../Utils/FileUtils'
|
||||
import { downloadFile, getJSON } from './Networking'
|
||||
import { Paths } from '../Types/Paths'
|
||||
import { AppName } from '../Strings'
|
||||
import { timeout } from '../Utils/Utils'
|
||||
import log from 'electron-log'
|
||||
import { Component, MappingFile, PackageManagerInterface, SyncTask, PackageInfo } from './PackageManagerInterface'
|
||||
|
||||
function logMessage(...message: any) {
|
||||
log.info('PackageManager:', ...message)
|
||||
}
|
||||
|
||||
function logError(...message: any) {
|
||||
console.error('PackageManager:', ...message)
|
||||
}
|
||||
|
||||
/**
|
||||
* Safe component mapping manager that queues its disk writes
|
||||
*/
|
||||
class MappingFileHandler {
|
||||
static async create() {
|
||||
let mapping: MappingFile
|
||||
|
||||
try {
|
||||
const result = await readJSONFile<MappingFile>(Paths.extensionsMappingJson)
|
||||
mapping = result || {}
|
||||
} catch (error: any) {
|
||||
/**
|
||||
* Mapping file might be absent (first start, corrupted data)
|
||||
*/
|
||||
if (error.code === FileDoesNotExist) {
|
||||
await ensureDirectoryExists(path.dirname(Paths.extensionsMappingJson))
|
||||
} else {
|
||||
logError(error)
|
||||
}
|
||||
mapping = {}
|
||||
}
|
||||
|
||||
return new MappingFileHandler(mapping)
|
||||
}
|
||||
|
||||
constructor(private mapping: MappingFile) {}
|
||||
|
||||
get = (componendId: string) => {
|
||||
return this.mapping[componendId]
|
||||
}
|
||||
|
||||
set = (componentId: string, location: string, version: string) => {
|
||||
this.mapping[componentId] = {
|
||||
location,
|
||||
version,
|
||||
}
|
||||
this.writeToDisk()
|
||||
}
|
||||
|
||||
remove = (componentId: string) => {
|
||||
delete this.mapping[componentId]
|
||||
this.writeToDisk()
|
||||
}
|
||||
|
||||
getInstalledVersionForComponent = async (component: Component): Promise<string> => {
|
||||
const version = this.get(component.uuid)?.version
|
||||
if (version) {
|
||||
return version
|
||||
}
|
||||
|
||||
/**
|
||||
* If the mapping has no version (pre-3.5 installs) check the component's
|
||||
* package.json file
|
||||
*/
|
||||
const paths = pathsForComponent(component)
|
||||
const packagePath = path.join(paths.absolutePath, 'package.json')
|
||||
const response = await readJSONFile<{ version: string }>(packagePath)
|
||||
if (!response) {
|
||||
return ''
|
||||
}
|
||||
this.set(component.uuid, paths.relativePath, response.version)
|
||||
return response.version
|
||||
}
|
||||
|
||||
private writeToDisk = debouncedJSONDiskWriter(100, Paths.extensionsMappingJson, () => this.mapping)
|
||||
}
|
||||
|
||||
export async function initializePackageManager(webContents: Electron.WebContents): Promise<PackageManagerInterface> {
|
||||
const syncTasks: SyncTask[] = []
|
||||
let isRunningTasks = false
|
||||
|
||||
const mapping = await MappingFileHandler.create()
|
||||
|
||||
return {
|
||||
syncComponents: async (components: Component[]) => {
|
||||
logMessage(
|
||||
'received sync event for:',
|
||||
components
|
||||
.map(
|
||||
({ content, deleted }) =>
|
||||
// eslint-disable-next-line camelcase
|
||||
`${content?.name} (${content?.package_info?.version}) ` + `(deleted: ${deleted})`,
|
||||
)
|
||||
.join(', '),
|
||||
)
|
||||
syncTasks.push({ components })
|
||||
|
||||
if (isRunningTasks) {
|
||||
return
|
||||
}
|
||||
|
||||
isRunningTasks = true
|
||||
await runTasks(webContents, mapping, syncTasks)
|
||||
isRunningTasks = false
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function runTasks(webContents: Electron.WebContents, mapping: MappingFileHandler, tasks: SyncTask[]) {
|
||||
while (tasks.length > 0) {
|
||||
try {
|
||||
const oppositeTask = await runTask(webContents, mapping, tasks[0], tasks.slice(1))
|
||||
if (oppositeTask) {
|
||||
tasks.splice(tasks.indexOf(oppositeTask), 1)
|
||||
}
|
||||
} catch (error) {
|
||||
logError(error)
|
||||
} finally {
|
||||
/** Remove the task from the queue. */
|
||||
tasks.splice(0, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param nextTasks the tasks that follow this one. Useful to see if we
|
||||
* need to run it at all (for example in the case of a succession of
|
||||
* install/uninstall)
|
||||
* @returns If a task opposite to this one was found, returns that tas without
|
||||
* doing anything. Otherwise undefined.
|
||||
*/
|
||||
async function runTask(
|
||||
webContents: Electron.WebContents,
|
||||
mapping: MappingFileHandler,
|
||||
task: SyncTask,
|
||||
nextTasks: SyncTask[],
|
||||
): Promise<SyncTask | undefined> {
|
||||
const maxTries = 3
|
||||
/** Try to execute the task with up to three tries. */
|
||||
for (let tries = 1; tries <= maxTries; tries++) {
|
||||
try {
|
||||
if (task.components.length === 1 && nextTasks.length > 0) {
|
||||
/**
|
||||
* This is a single-component task, AKA an installation or
|
||||
* deletion
|
||||
*/
|
||||
const component = task.components[0]
|
||||
/**
|
||||
* See if there is a task opposite to this one, to avoid doing
|
||||
* unnecessary processing
|
||||
*/
|
||||
const oppositeTask = nextTasks.find((otherTask) => {
|
||||
if (otherTask.components.length > 1) {
|
||||
/** Only check single-component tasks. */
|
||||
return false
|
||||
}
|
||||
const otherComponent = otherTask.components[0]
|
||||
return component.uuid === otherComponent.uuid && component.deleted !== otherComponent.deleted
|
||||
})
|
||||
if (oppositeTask) {
|
||||
/** Found an opposite task. return it to the caller and do nothing */
|
||||
return oppositeTask
|
||||
}
|
||||
}
|
||||
await syncComponents(webContents, mapping, task.components)
|
||||
/** Everything went well, leave the loop */
|
||||
return
|
||||
} catch (error) {
|
||||
if (tries < maxTries) {
|
||||
continue
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function syncComponents(webContents: Electron.WebContents, mapping: MappingFileHandler, components: Component[]) {
|
||||
/**
|
||||
* Incoming `components` are what should be installed. For every component,
|
||||
* check the filesystem and see if that component is installed. If not,
|
||||
* install it.
|
||||
*/
|
||||
await Promise.all(
|
||||
components.map(async (component) => {
|
||||
if (component.deleted) {
|
||||
/** Uninstall */
|
||||
logMessage(`Uninstalling ${component.content?.name}`)
|
||||
await uninstallComponent(mapping, component.uuid)
|
||||
return
|
||||
}
|
||||
|
||||
// eslint-disable-next-line camelcase
|
||||
if (!component.content?.package_info) {
|
||||
logMessage('Package info is null, skipping')
|
||||
return
|
||||
}
|
||||
|
||||
const paths = pathsForComponent(component)
|
||||
const version = component.content.package_info.version
|
||||
if (!component.content.local_url) {
|
||||
/**
|
||||
* We have a component but it is not mapped to anything on the file system
|
||||
*/
|
||||
await installComponent(webContents, mapping, component, component.content.package_info, version)
|
||||
} else {
|
||||
try {
|
||||
/** Will trigger an error if the directory does not exist. */
|
||||
await fs.promises.lstat(paths.absolutePath)
|
||||
if (!component.content.autoupdateDisabled) {
|
||||
await checkForUpdate(webContents, mapping, component)
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error.code === FileDoesNotExist) {
|
||||
/** We have a component but no content. Install the component */
|
||||
await installComponent(webContents, mapping, component, component.content.package_info, version)
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async function checkForUpdate(webContents: Electron.WebContents, mapping: MappingFileHandler, component: Component) {
|
||||
const installedVersion = await mapping.getInstalledVersionForComponent(component)
|
||||
|
||||
const latestUrl = component.content?.package_info?.latest_url
|
||||
if (!latestUrl) {
|
||||
return
|
||||
}
|
||||
|
||||
const latestJson = await getJSON<PackageInfo>(latestUrl)
|
||||
if (!latestJson) {
|
||||
return
|
||||
}
|
||||
|
||||
const latestVersion = latestJson.version
|
||||
logMessage(
|
||||
`Checking for update for ${component.content?.name}\n` +
|
||||
`Latest: ${latestVersion} | Installed: ${installedVersion}`,
|
||||
)
|
||||
|
||||
if (compareVersions(latestVersion, installedVersion) === 1) {
|
||||
/** Latest version is greater than installed version */
|
||||
logMessage('Downloading new version', latestVersion)
|
||||
await installComponent(webContents, mapping, component, latestJson, latestVersion)
|
||||
}
|
||||
}
|
||||
|
||||
async function installComponent(
|
||||
webContents: Electron.WebContents,
|
||||
mapping: MappingFileHandler,
|
||||
component: Component,
|
||||
packageInfo: PackageInfo,
|
||||
version: string,
|
||||
) {
|
||||
if (!component.content) {
|
||||
return
|
||||
}
|
||||
const downloadUrl = packageInfo.download_url
|
||||
if (!downloadUrl) {
|
||||
return
|
||||
}
|
||||
const name = component.content.name
|
||||
|
||||
logMessage('Installing ', name, downloadUrl)
|
||||
|
||||
const sendInstalledMessage = (component: Component, error?: { message: string; tag: string }) => {
|
||||
if (error) {
|
||||
logError(`Error when installing component ${name}: ` + error.message)
|
||||
} else {
|
||||
logMessage(`Installed component ${name} (${version})`)
|
||||
}
|
||||
webContents.send(MessageToWebApp.InstallComponentComplete, {
|
||||
component,
|
||||
error,
|
||||
})
|
||||
}
|
||||
|
||||
const paths = pathsForComponent(component)
|
||||
try {
|
||||
logMessage(`Downloading from ${downloadUrl}`)
|
||||
/** Download the zip and clear the component's directory in parallel */
|
||||
await Promise.all([
|
||||
downloadFile(downloadUrl, paths.downloadPath),
|
||||
(async () => {
|
||||
/** Clear the component's directory before extracting the zip. */
|
||||
await ensureDirectoryExists(paths.absolutePath)
|
||||
await deleteDirContents(paths.absolutePath)
|
||||
})(),
|
||||
])
|
||||
|
||||
logMessage('Extracting', paths.downloadPath, 'to', paths.absolutePath)
|
||||
await extractNestedZip(paths.downloadPath, paths.absolutePath)
|
||||
|
||||
let main = 'index.html'
|
||||
try {
|
||||
/** Try to read 'sn.main' field from 'package.json' file */
|
||||
const packageJsonPath = path.join(paths.absolutePath, 'package.json')
|
||||
const packageJson = await readJSONFile<{
|
||||
sn?: { main?: string }
|
||||
version?: string
|
||||
}>(packageJsonPath)
|
||||
|
||||
if (packageJson?.sn?.main) {
|
||||
main = packageJson.sn.main
|
||||
}
|
||||
} catch (error) {
|
||||
logError(error)
|
||||
}
|
||||
|
||||
component.content.local_url = 'sn://' + paths.relativePath + '/' + main
|
||||
component.content.package_info.download_url = packageInfo.download_url
|
||||
component.content.package_info.latest_url = packageInfo.latest_url
|
||||
component.content.package_info.url = packageInfo.url
|
||||
component.content.package_info.version = packageInfo.version
|
||||
mapping.set(component.uuid, paths.relativePath, version)
|
||||
|
||||
sendInstalledMessage(component)
|
||||
} catch (error: any) {
|
||||
logMessage(`Error while installing ${component.content.name}`, error.message)
|
||||
|
||||
/**
|
||||
* Waiting five seconds prevents clients from spamming install requests
|
||||
* of faulty components
|
||||
*/
|
||||
const fiveSeconds = 5000
|
||||
await timeout(fiveSeconds)
|
||||
|
||||
sendInstalledMessage(component, {
|
||||
message: error.message,
|
||||
tag: 'error-downloading',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function pathsForComponent(component: Pick<Component, 'content'>) {
|
||||
const relativePath = path.join(Paths.extensionsDirRelative, component.content!.package_info.identifier)
|
||||
return {
|
||||
relativePath,
|
||||
absolutePath: path.join(Paths.userDataDir, relativePath),
|
||||
downloadPath: path.join(Paths.tempDir, AppName, 'downloads', component.content!.name + '.zip'),
|
||||
}
|
||||
}
|
||||
|
||||
async function uninstallComponent(mapping: MappingFileHandler, uuid: string) {
|
||||
const componentMapping = mapping.get(uuid)
|
||||
if (!componentMapping || !componentMapping.location) {
|
||||
/** No mapping for component */
|
||||
return
|
||||
}
|
||||
await deleteDir(path.join(Paths.userDataDir, componentMapping.location))
|
||||
mapping.remove(uuid)
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
export interface PackageManagerInterface {
|
||||
syncComponents(components: Component[]): Promise<void>
|
||||
}
|
||||
|
||||
export interface Component {
|
||||
uuid: string
|
||||
deleted: boolean
|
||||
content?: {
|
||||
name?: string
|
||||
autoupdateDisabled: boolean
|
||||
local_url?: string
|
||||
package_info: PackageInfo
|
||||
}
|
||||
}
|
||||
|
||||
export type PackageInfo = {
|
||||
identifier: string
|
||||
version: string
|
||||
download_url: string
|
||||
latest_url: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export interface SyncTask {
|
||||
components: Component[]
|
||||
}
|
||||
|
||||
export interface MappingFile {
|
||||
[key: string]: Readonly<ComponentMapping> | undefined
|
||||
}
|
||||
|
||||
export interface ComponentMapping {
|
||||
location: string
|
||||
version?: string
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export interface RemoteDataInterface {
|
||||
destroySensitiveDirectories(): void
|
||||
}
|
||||
204
packages/desktop/app/javascripts/Main/Remote/RemoteBridge.ts
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
import { CrossProcessBridge } from '../../Renderer/CrossProcessBridge'
|
||||
import { Store, StoreKeys } from '../Store'
|
||||
|
||||
const path = require('path')
|
||||
const rendererPath = path.join('file://', __dirname, '/renderer.js')
|
||||
|
||||
import { app, BrowserWindow } from 'electron'
|
||||
import { KeychainInterface } from '../Keychain/KeychainInterface'
|
||||
import { BackupsManagerInterface } from '../Backups/BackupsManagerInterface'
|
||||
import { PackageManagerInterface, Component } from '../Packages/PackageManagerInterface'
|
||||
import { SearchManagerInterface } from '../Search/SearchManagerInterface'
|
||||
import { RemoteDataInterface } from './DataInterface'
|
||||
import { MenuManagerInterface } from '../Menus/MenuManagerInterface'
|
||||
import { FileBackupsDevice, FileBackupsMapping } from '@web/Application/Device/DesktopSnjsExports'
|
||||
|
||||
/**
|
||||
* Read https://github.com/electron/remote to understand how electron/remote works.
|
||||
* RemoteBridge is imported from the Preload process but is declared and created on the main process.
|
||||
*/
|
||||
export class RemoteBridge implements CrossProcessBridge {
|
||||
constructor(
|
||||
private window: BrowserWindow,
|
||||
private keychain: KeychainInterface,
|
||||
private backups: BackupsManagerInterface,
|
||||
private packages: PackageManagerInterface,
|
||||
private search: SearchManagerInterface,
|
||||
private data: RemoteDataInterface,
|
||||
private menus: MenuManagerInterface,
|
||||
private fileBackups: FileBackupsDevice,
|
||||
) {}
|
||||
|
||||
get exposableValue(): CrossProcessBridge {
|
||||
return {
|
||||
extServerHost: this.extServerHost,
|
||||
useNativeKeychain: this.useNativeKeychain,
|
||||
isMacOS: this.isMacOS,
|
||||
appVersion: this.appVersion,
|
||||
useSystemMenuBar: this.useSystemMenuBar,
|
||||
rendererPath: this.rendererPath,
|
||||
closeWindow: this.closeWindow.bind(this),
|
||||
minimizeWindow: this.minimizeWindow.bind(this),
|
||||
maximizeWindow: this.maximizeWindow.bind(this),
|
||||
unmaximizeWindow: this.unmaximizeWindow.bind(this),
|
||||
isWindowMaximized: this.isWindowMaximized.bind(this),
|
||||
getKeychainValue: this.getKeychainValue.bind(this),
|
||||
setKeychainValue: this.setKeychainValue.bind(this),
|
||||
clearKeychainValue: this.clearKeychainValue.bind(this),
|
||||
localBackupsCount: this.localBackupsCount.bind(this),
|
||||
viewlocalBackups: this.viewlocalBackups.bind(this),
|
||||
deleteLocalBackups: this.deleteLocalBackups.bind(this),
|
||||
displayAppMenu: this.displayAppMenu.bind(this),
|
||||
saveDataBackup: this.saveDataBackup.bind(this),
|
||||
syncComponents: this.syncComponents.bind(this),
|
||||
onMajorDataChange: this.onMajorDataChange.bind(this),
|
||||
onSearch: this.onSearch.bind(this),
|
||||
onInitialDataLoad: this.onInitialDataLoad.bind(this),
|
||||
destroyAllData: this.destroyAllData.bind(this),
|
||||
getFilesBackupsMappingFile: this.getFilesBackupsMappingFile.bind(this),
|
||||
saveFilesBackupsFile: this.saveFilesBackupsFile.bind(this),
|
||||
isFilesBackupsEnabled: this.isFilesBackupsEnabled.bind(this),
|
||||
enableFilesBackups: this.enableFilesBackups.bind(this),
|
||||
disableFilesBackups: this.disableFilesBackups.bind(this),
|
||||
changeFilesBackupsLocation: this.changeFilesBackupsLocation.bind(this),
|
||||
getFilesBackupsLocation: this.getFilesBackupsLocation.bind(this),
|
||||
openFilesBackupsLocation: this.openFilesBackupsLocation.bind(this),
|
||||
}
|
||||
}
|
||||
|
||||
get extServerHost() {
|
||||
return Store.get(StoreKeys.ExtServerHost)
|
||||
}
|
||||
|
||||
get useNativeKeychain() {
|
||||
return Store.get(StoreKeys.UseNativeKeychain) ?? true
|
||||
}
|
||||
|
||||
get rendererPath() {
|
||||
return rendererPath
|
||||
}
|
||||
|
||||
get isMacOS() {
|
||||
return process.platform === 'darwin'
|
||||
}
|
||||
|
||||
get appVersion() {
|
||||
return app.getVersion()
|
||||
}
|
||||
|
||||
get useSystemMenuBar() {
|
||||
return Store.get(StoreKeys.UseSystemMenuBar)
|
||||
}
|
||||
|
||||
closeWindow() {
|
||||
this.window.close()
|
||||
}
|
||||
|
||||
minimizeWindow() {
|
||||
this.window.minimize()
|
||||
}
|
||||
|
||||
maximizeWindow() {
|
||||
this.window.maximize()
|
||||
}
|
||||
|
||||
unmaximizeWindow() {
|
||||
this.window.unmaximize()
|
||||
}
|
||||
|
||||
isWindowMaximized() {
|
||||
return this.window.isMaximized()
|
||||
}
|
||||
|
||||
async getKeychainValue() {
|
||||
return this.keychain.getKeychainValue()
|
||||
}
|
||||
|
||||
async setKeychainValue(value: unknown) {
|
||||
return this.keychain.setKeychainValue(value)
|
||||
}
|
||||
|
||||
async clearKeychainValue() {
|
||||
return this.keychain.clearKeychainValue()
|
||||
}
|
||||
|
||||
async localBackupsCount() {
|
||||
return this.backups.backupsCount()
|
||||
}
|
||||
|
||||
viewlocalBackups() {
|
||||
this.backups.viewBackups()
|
||||
}
|
||||
|
||||
async deleteLocalBackups() {
|
||||
return this.backups.deleteBackups()
|
||||
}
|
||||
|
||||
syncComponents(components: Component[]) {
|
||||
void this.packages.syncComponents(components)
|
||||
}
|
||||
|
||||
onMajorDataChange() {
|
||||
this.backups.performBackup()
|
||||
}
|
||||
|
||||
onSearch(text: string) {
|
||||
this.search.findInPage(text)
|
||||
}
|
||||
|
||||
onInitialDataLoad() {
|
||||
this.backups.beginBackups()
|
||||
}
|
||||
|
||||
destroyAllData() {
|
||||
this.data.destroySensitiveDirectories()
|
||||
}
|
||||
|
||||
saveDataBackup(data: unknown) {
|
||||
this.backups.saveBackupData(data)
|
||||
}
|
||||
|
||||
displayAppMenu() {
|
||||
this.menus.popupMenu()
|
||||
}
|
||||
|
||||
getFilesBackupsMappingFile(): Promise<FileBackupsMapping> {
|
||||
return this.fileBackups.getFilesBackupsMappingFile()
|
||||
}
|
||||
|
||||
saveFilesBackupsFile(
|
||||
uuid: string,
|
||||
metaFile: string,
|
||||
downloadRequest: {
|
||||
chunkSizes: number[]
|
||||
valetToken: string
|
||||
url: string
|
||||
},
|
||||
): Promise<'success' | 'failed'> {
|
||||
return this.fileBackups.saveFilesBackupsFile(uuid, metaFile, downloadRequest)
|
||||
}
|
||||
|
||||
public isFilesBackupsEnabled(): Promise<boolean> {
|
||||
return this.fileBackups.isFilesBackupsEnabled()
|
||||
}
|
||||
|
||||
public enableFilesBackups(): Promise<void> {
|
||||
return this.fileBackups.enableFilesBackups()
|
||||
}
|
||||
|
||||
public disableFilesBackups(): Promise<void> {
|
||||
return this.fileBackups.disableFilesBackups()
|
||||
}
|
||||
|
||||
public changeFilesBackupsLocation(): Promise<string | undefined> {
|
||||
return this.fileBackups.changeFilesBackupsLocation()
|
||||
}
|
||||
|
||||
public getFilesBackupsLocation(): Promise<string> {
|
||||
return this.fileBackups.getFilesBackupsLocation()
|
||||
}
|
||||
|
||||
public openFilesBackupsLocation(): Promise<void> {
|
||||
return this.fileBackups.openFilesBackupsLocation()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import { WebContents } from 'electron'
|
||||
import { SearchManagerInterface } from './SearchManagerInterface'
|
||||
|
||||
export function initializeSearchManager(webContents: WebContents): SearchManagerInterface {
|
||||
return {
|
||||
findInPage(text: string) {
|
||||
webContents.stopFindInPage('clearSelection')
|
||||
if (text && text.length > 0) {
|
||||
// This option arrangement is required to avoid an issue where clicking on a
|
||||
// different note causes scroll to jump.
|
||||
webContents.findInPage(text)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export interface SearchManagerInterface {
|
||||
findInPage(text: string): void
|
||||
}
|
||||
214
packages/desktop/app/javascripts/Main/SpellcheckerManager.ts
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
/* eslint-disable no-inline-comments */
|
||||
import { isMac } from './Types/Platforms'
|
||||
import { Store, StoreKeys } from './Store'
|
||||
import { isDev } from './Utils/Utils'
|
||||
|
||||
export enum Language {
|
||||
AF = 'af',
|
||||
ID = 'id',
|
||||
CA = 'ca',
|
||||
CS = 'cs',
|
||||
CY = 'cy',
|
||||
DA = 'da',
|
||||
DE = 'de',
|
||||
SH = 'sh',
|
||||
ET = 'et',
|
||||
EN_AU = 'en-AU',
|
||||
EN_CA = 'en-CA',
|
||||
EN_GB = 'en-GB',
|
||||
EN_US = 'en-US',
|
||||
ES = 'es',
|
||||
ES_419 = 'es-419',
|
||||
ES_ES = 'es-ES',
|
||||
ES_US = 'es-US',
|
||||
ES_MX = 'es-MX',
|
||||
ES_AR = 'es-AR',
|
||||
FO = 'fo',
|
||||
FR = 'fr',
|
||||
HR = 'hr',
|
||||
IT = 'it',
|
||||
PL = 'pl',
|
||||
LV = 'lv',
|
||||
LT = 'lt',
|
||||
HU = 'hu',
|
||||
NL = 'nl',
|
||||
NB = 'nb',
|
||||
PT_BR = 'pt-BR',
|
||||
PT_PT = 'pt-PT',
|
||||
RO = 'ro',
|
||||
SQ = 'sq',
|
||||
SK = 'sk',
|
||||
SL = 'sl',
|
||||
SV = 'sv',
|
||||
VI = 'vi',
|
||||
TR = 'tr',
|
||||
EL = 'el',
|
||||
BG = 'bg',
|
||||
RU = 'ru',
|
||||
SR = 'sr',
|
||||
TG = 'tg',
|
||||
UK = 'uk',
|
||||
HY = 'hy',
|
||||
HE = 'he',
|
||||
FA = 'fa',
|
||||
HI = 'hi',
|
||||
TA = 'ta',
|
||||
KO = 'ko',
|
||||
}
|
||||
|
||||
function isLanguage(language: any): language is Language {
|
||||
return Object.values(Language).includes(language)
|
||||
}
|
||||
|
||||
function log(...message: any) {
|
||||
console.log('spellcheckerMaager:', ...message)
|
||||
}
|
||||
|
||||
export interface SpellcheckerManager {
|
||||
languages(): Array<{
|
||||
code: string
|
||||
name: string
|
||||
enabled: boolean
|
||||
}>
|
||||
addLanguage(code: string): void
|
||||
removeLanguage(code: string): void
|
||||
}
|
||||
|
||||
export function createSpellcheckerManager(
|
||||
store: Store,
|
||||
webContents: Electron.WebContents,
|
||||
userLocale: string,
|
||||
): SpellcheckerManager | undefined {
|
||||
/**
|
||||
* On MacOS the system spellchecker is used and every related Electron method
|
||||
* is a no-op. Return early to prevent unnecessary code execution/allocations
|
||||
*/
|
||||
if (isMac()) {
|
||||
return
|
||||
}
|
||||
|
||||
const session = webContents.session
|
||||
|
||||
/**
|
||||
* Mapping of language codes predominantly based on
|
||||
* https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
|
||||
*/
|
||||
const LanguageCodes: Readonly<Record<Language, string>> = {
|
||||
af: 'Afrikaans' /** Afrikaans */,
|
||||
id: 'Bahasa Indonesia' /** Indonesian */,
|
||||
ca: 'Català, Valencià' /** Catalan, Valencian */,
|
||||
cs: 'Čeština, Český Jazyk' /** Czech */,
|
||||
cy: 'Cymraeg' /** Welsh */,
|
||||
da: 'Dansk' /** Danish */,
|
||||
de: 'Deutsch' /** German */,
|
||||
sh: 'Deutsch, Schaffhausen' /** German, Canton of Schaffhausen */,
|
||||
et: 'Eesti, Eesti Keel' /** Estonian */,
|
||||
'en-AU': 'English, Australia',
|
||||
'en-CA': 'English, Canada',
|
||||
'en-GB': 'English, Great Britain',
|
||||
'en-US': 'English, United States',
|
||||
es: 'Español' /** Spanish, Castilian */,
|
||||
'es-419': 'Español, America Latina' /** Spanish, Latin American */,
|
||||
'es-ES': 'Español, España' /** Spanish, Spain */,
|
||||
'es-US': 'Español, Estados Unidos de América' /** Spanish, United States */,
|
||||
'es-MX': 'Español, Estados Unidos Mexicanos' /** Spanish, Mexico */,
|
||||
'es-AR': 'Español, República Argentina' /** Spanish, Argentine Republic */,
|
||||
fo: 'Føroyskt' /** Faroese */,
|
||||
fr: 'Français' /** French */,
|
||||
hr: 'Hrvatski Jezik' /** Croatian */,
|
||||
it: 'Italiano' /** Italian */,
|
||||
pl: 'Język Polski, Polszczyzna' /** Polish */,
|
||||
lv: 'Latviešu Valoda' /** Latvian */,
|
||||
lt: 'Lietuvių Kalba' /** Lithuanian */,
|
||||
hu: 'Magyar' /** Hungarian */,
|
||||
nl: 'Nederlands, Vlaams' /** Dutch, Flemish */,
|
||||
nb: 'Norsk Bokmål' /** Norwegian Bokmål */,
|
||||
'pt-BR': 'Português, Brasil' /** Portuguese, Brazil */,
|
||||
'pt-PT': 'Português, República Portuguesa' /** Portuguese, Portugal */,
|
||||
ro: 'Română' /** Romanian, Moldavian, Moldovan */,
|
||||
sq: 'Shqip' /** Albanian */,
|
||||
sk: 'Slovenčina, Slovenský Jazyk' /** Slovak */,
|
||||
sl: 'Slovenski Jezik, Slovenščina' /** Slovenian */,
|
||||
sv: 'Svenska' /** Swedish */,
|
||||
vi: 'Tiếng Việt' /** Vietnamese */,
|
||||
tr: 'Türkçe' /** Turkish */,
|
||||
el: 'ελληνικά' /** Greek */,
|
||||
bg: 'български език' /** Bulgarian */,
|
||||
ru: 'Русский' /** Russian */,
|
||||
sr: 'српски језик' /** Serbian */,
|
||||
tg: 'тоҷикӣ, toçikī, تاجیکی' /** Tajik */,
|
||||
uk: 'Українська' /** Ukrainian */,
|
||||
hy: 'Հայերեն' /** Armenian */,
|
||||
he: 'עברית' /** Hebrew */,
|
||||
fa: 'فارسی' /** Persian */,
|
||||
hi: 'हिन्दी, हिंदी' /** Hindi */,
|
||||
ta: 'தமிழ்' /** Tamil */,
|
||||
ko: '한국어' /** Korean */,
|
||||
}
|
||||
|
||||
const availableSpellCheckerLanguages = Object.values(Language).filter((language) =>
|
||||
session.availableSpellCheckerLanguages.includes(language),
|
||||
)
|
||||
|
||||
if (isDev() && availableSpellCheckerLanguages.length !== session.availableSpellCheckerLanguages.length) {
|
||||
/** This means that not every available language has been accounted for. */
|
||||
const firstOutlier = session.availableSpellCheckerLanguages.find(
|
||||
(language, index) => availableSpellCheckerLanguages[index] !== language,
|
||||
)
|
||||
throw new Error(`Found unsupported language code: ${firstOutlier}`)
|
||||
}
|
||||
|
||||
setSpellcheckerLanguages()
|
||||
|
||||
function setSpellcheckerLanguages() {
|
||||
const { session } = webContents
|
||||
let selectedCodes = store.get(StoreKeys.SelectedSpellCheckerLanguageCodes)
|
||||
|
||||
if (selectedCodes === null) {
|
||||
/** First-time setup. Set a default language */
|
||||
selectedCodes = determineDefaultSpellcheckerLanguageCodes(session.availableSpellCheckerLanguages, userLocale)
|
||||
store.set(StoreKeys.SelectedSpellCheckerLanguageCodes, selectedCodes)
|
||||
}
|
||||
session.setSpellCheckerLanguages([...selectedCodes])
|
||||
}
|
||||
|
||||
function determineDefaultSpellcheckerLanguageCodes(
|
||||
availableSpellCheckerLanguages: string[],
|
||||
userLocale: string,
|
||||
): Set<Language> {
|
||||
const localeIsSupported = availableSpellCheckerLanguages.includes(userLocale)
|
||||
if (localeIsSupported && isLanguage(userLocale)) {
|
||||
return new Set([userLocale])
|
||||
} else {
|
||||
log(`Spellchecker doesn't support locale '${userLocale}'.`)
|
||||
return new Set()
|
||||
}
|
||||
}
|
||||
|
||||
function selectedLanguageCodes(): Set<Language> {
|
||||
return store.get(StoreKeys.SelectedSpellCheckerLanguageCodes) || new Set()
|
||||
}
|
||||
|
||||
return {
|
||||
languages() {
|
||||
const codes = selectedLanguageCodes()
|
||||
return availableSpellCheckerLanguages.map((code) => ({
|
||||
code,
|
||||
name: LanguageCodes[code],
|
||||
enabled: codes.has(code),
|
||||
}))
|
||||
},
|
||||
addLanguage(code: Language) {
|
||||
const selectedCodes = selectedLanguageCodes()
|
||||
selectedCodes.add(code)
|
||||
store.set(StoreKeys.SelectedSpellCheckerLanguageCodes, selectedCodes)
|
||||
session.setSpellCheckerLanguages(Array.from(selectedCodes))
|
||||
},
|
||||
removeLanguage(code: Language) {
|
||||
const selectedCodes = selectedLanguageCodes()
|
||||
selectedCodes.delete(code)
|
||||
store.set(StoreKeys.SelectedSpellCheckerLanguageCodes, selectedCodes)
|
||||
session.setSpellCheckerLanguages(Array.from(selectedCodes))
|
||||
},
|
||||
}
|
||||
}
|
||||
185
packages/desktop/app/javascripts/Main/Store.ts
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { MessageType } from '../../../test/TestIpcMessage'
|
||||
import { Language } from './SpellcheckerManager'
|
||||
import { ensureIsBoolean, isTesting, isDev, isBoolean } from './Utils/Utils'
|
||||
import { FileDoesNotExist } from './Utils/FileUtils'
|
||||
import { BackupsDirectoryName } from './Backups/BackupsManager'
|
||||
import { handleTestMessage } from './Utils/Testing'
|
||||
|
||||
const app = process.type === 'browser' ? require('electron').app : require('@electron/remote').app
|
||||
|
||||
function logError(...message: any) {
|
||||
console.error('store:', ...message)
|
||||
}
|
||||
|
||||
export enum StoreKeys {
|
||||
ExtServerHost = 'extServerHost',
|
||||
UseSystemMenuBar = 'useSystemMenuBar',
|
||||
MenuBarVisible = 'isMenuBarVisible',
|
||||
BackupsLocation = 'backupsLocation',
|
||||
BackupsDisabled = 'backupsDisabled',
|
||||
MinimizeToTray = 'minimizeToTray',
|
||||
EnableAutoUpdate = 'enableAutoUpdates',
|
||||
ZoomFactor = 'zoomFactor',
|
||||
SelectedSpellCheckerLanguageCodes = 'selectedSpellCheckerLanguageCodes',
|
||||
UseNativeKeychain = 'useNativeKeychain',
|
||||
|
||||
FileBackupsEnabled = 'fileBackupsEnabled',
|
||||
FileBackupsLocation = 'fileBackupsLocation',
|
||||
}
|
||||
|
||||
interface StoreData {
|
||||
[StoreKeys.ExtServerHost]: string
|
||||
[StoreKeys.UseSystemMenuBar]: boolean
|
||||
[StoreKeys.MenuBarVisible]: boolean
|
||||
[StoreKeys.BackupsLocation]: string
|
||||
[StoreKeys.BackupsDisabled]: boolean
|
||||
[StoreKeys.MinimizeToTray]: boolean
|
||||
[StoreKeys.EnableAutoUpdate]: boolean
|
||||
[StoreKeys.UseNativeKeychain]: boolean | null
|
||||
[StoreKeys.ZoomFactor]: number
|
||||
[StoreKeys.SelectedSpellCheckerLanguageCodes]: Set<Language> | null
|
||||
[StoreKeys.FileBackupsEnabled]: boolean
|
||||
[StoreKeys.FileBackupsLocation]: string
|
||||
}
|
||||
|
||||
function createSanitizedStoreData(data: any = {}): StoreData {
|
||||
return {
|
||||
[StoreKeys.MenuBarVisible]: ensureIsBoolean(data[StoreKeys.MenuBarVisible], true),
|
||||
[StoreKeys.UseSystemMenuBar]: ensureIsBoolean(data[StoreKeys.UseSystemMenuBar], false),
|
||||
[StoreKeys.BackupsDisabled]: ensureIsBoolean(data[StoreKeys.BackupsDisabled], false),
|
||||
[StoreKeys.MinimizeToTray]: ensureIsBoolean(data[StoreKeys.MinimizeToTray], false),
|
||||
[StoreKeys.EnableAutoUpdate]: ensureIsBoolean(data[StoreKeys.EnableAutoUpdate], true),
|
||||
[StoreKeys.UseNativeKeychain]: isBoolean(data[StoreKeys.UseNativeKeychain])
|
||||
? data[StoreKeys.UseNativeKeychain]
|
||||
: null,
|
||||
[StoreKeys.ExtServerHost]: data[StoreKeys.ExtServerHost],
|
||||
[StoreKeys.BackupsLocation]: sanitizeBackupsLocation(data[StoreKeys.BackupsLocation]),
|
||||
[StoreKeys.ZoomFactor]: sanitizeZoomFactor(data[StoreKeys.ZoomFactor]),
|
||||
[StoreKeys.SelectedSpellCheckerLanguageCodes]: sanitizeSpellCheckerLanguageCodes(
|
||||
data[StoreKeys.SelectedSpellCheckerLanguageCodes],
|
||||
),
|
||||
[StoreKeys.FileBackupsEnabled]: ensureIsBoolean(data[StoreKeys.FileBackupsEnabled], false),
|
||||
[StoreKeys.FileBackupsLocation]: data[StoreKeys.FileBackupsLocation],
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeZoomFactor(factor?: any): number {
|
||||
if (typeof factor === 'number' && factor > 0) {
|
||||
return factor
|
||||
} else {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeBackupsLocation(location?: unknown): string {
|
||||
const defaultPath = path.join(
|
||||
isTesting() ? app.getPath('userData') : isDev() ? app.getPath('documents') : app.getPath('home'),
|
||||
BackupsDirectoryName,
|
||||
)
|
||||
|
||||
if (typeof location !== 'string') {
|
||||
return defaultPath
|
||||
}
|
||||
|
||||
try {
|
||||
const stat = fs.lstatSync(location)
|
||||
if (stat.isDirectory()) {
|
||||
return location
|
||||
}
|
||||
/** Path points to something other than a directory */
|
||||
return defaultPath
|
||||
} catch (e) {
|
||||
/** Path does not point to a valid directory */
|
||||
logError(e)
|
||||
return defaultPath
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeSpellCheckerLanguageCodes(languages?: unknown): Set<Language> | null {
|
||||
if (!languages) {
|
||||
return null
|
||||
}
|
||||
if (!Array.isArray(languages)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const set = new Set<Language>()
|
||||
const validLanguages = Object.values(Language)
|
||||
for (const language of languages) {
|
||||
if (validLanguages.includes(language)) {
|
||||
set.add(language)
|
||||
}
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
export function serializeStoreData(data: StoreData): string {
|
||||
return JSON.stringify(data, (_key, value) => {
|
||||
if (value instanceof Set) {
|
||||
return Array.from(value)
|
||||
}
|
||||
return value
|
||||
})
|
||||
}
|
||||
|
||||
function parseDataFile(filePath: string) {
|
||||
try {
|
||||
const fileData = fs.readFileSync(filePath)
|
||||
const userData = JSON.parse(fileData.toString())
|
||||
return createSanitizedStoreData(userData)
|
||||
} catch (error: any) {
|
||||
console.log('Error reading store file', error)
|
||||
if (error.code !== FileDoesNotExist) {
|
||||
logError(error)
|
||||
}
|
||||
|
||||
return createSanitizedStoreData({})
|
||||
}
|
||||
}
|
||||
|
||||
export class Store {
|
||||
static instance: Store
|
||||
readonly path: string
|
||||
readonly data: StoreData
|
||||
|
||||
static getInstance(): Store {
|
||||
if (!this.instance) {
|
||||
/**
|
||||
* Renderer process has to get `app` module via `remote`, whereas the main process
|
||||
* can get it directly app.getPath('userData') will return a string of the user's
|
||||
* app data directory path.
|
||||
* TODO(baptiste): stop using Store in the renderer process.
|
||||
*/
|
||||
const userDataPath = app.getPath('userData')
|
||||
this.instance = new Store(userDataPath)
|
||||
}
|
||||
return this.instance
|
||||
}
|
||||
|
||||
static get<T extends keyof StoreData>(key: T): StoreData[T] {
|
||||
return this.getInstance().get(key)
|
||||
}
|
||||
|
||||
constructor(userDataPath: string) {
|
||||
this.path = path.join(userDataPath, 'user-preferences.json')
|
||||
this.data = parseDataFile(this.path)
|
||||
|
||||
if (isTesting()) {
|
||||
handleTestMessage(MessageType.StoreSettingsLocation, () => this.path)
|
||||
handleTestMessage(MessageType.StoreSet, (key, value) => {
|
||||
this.set(key, value)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
get<T extends keyof StoreData>(key: T): StoreData[T] {
|
||||
return this.data[key]
|
||||
}
|
||||
|
||||
set<T extends keyof StoreData>(key: T, val: StoreData[T]): void {
|
||||
this.data[key] = val
|
||||
fs.writeFileSync(this.path, serializeStoreData(this.data))
|
||||
}
|
||||
}
|
||||
160
packages/desktop/app/javascripts/Main/Strings/english.ts
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
import { Strings } from './types'
|
||||
|
||||
export function createEnglishStrings(): Strings {
|
||||
return {
|
||||
appMenu: {
|
||||
edit: 'Edit',
|
||||
view: 'View',
|
||||
hideMenuBar: 'Hide Menu Bar',
|
||||
useThemedMenuBar: 'Use Themed Menu Bar',
|
||||
minimizeToTrayOnClose: 'Minimize To Tray On Close',
|
||||
backups: 'Backups',
|
||||
enableAutomaticUpdates: 'Enable Automatic Updates',
|
||||
automaticUpdatesDisabled: 'Automatic Updates Disabled',
|
||||
disableAutomaticBackups: 'Disable Automatic Backups',
|
||||
enableAutomaticBackups: 'Enable Automatic Backups',
|
||||
changeBackupsLocation: 'Change Backups Location',
|
||||
openBackupsLocation: 'Open Backups Location',
|
||||
emailSupport: 'Email Support',
|
||||
website: 'Website',
|
||||
gitHub: 'GitHub',
|
||||
slack: 'Slack',
|
||||
twitter: 'Twitter',
|
||||
toggleErrorConsole: 'Toggle Error Console',
|
||||
openDataDirectory: 'Open Data Directory',
|
||||
clearCacheAndReload: 'Clear Cache and Reload',
|
||||
speech: 'Speech',
|
||||
close: 'Close',
|
||||
minimize: 'Minimize',
|
||||
zoom: 'Zoom',
|
||||
bringAllToFront: 'Bring All to Front',
|
||||
checkForUpdate: 'Check for Update',
|
||||
checkingForUpdate: 'Checking for update…',
|
||||
updateAvailable: '(1) Update Available',
|
||||
updates: 'Updates',
|
||||
releaseNotes: 'Release Notes',
|
||||
openDownloadLocation: 'Open Download Location',
|
||||
downloadingUpdate: 'Downloading Update…',
|
||||
manuallyDownloadUpdate: 'Manually Download Update',
|
||||
spellcheckerLanguages: 'Spellchecker Languages',
|
||||
installPendingUpdate(versionNumber: string) {
|
||||
return `Install Pending Update (${versionNumber})`
|
||||
},
|
||||
lastUpdateCheck(date: Date) {
|
||||
return `Last checked ${date.toLocaleString()}`
|
||||
},
|
||||
version(number: string) {
|
||||
return `Version: ${number}`
|
||||
},
|
||||
yourVersion(number: string) {
|
||||
return `Your Version: ${number}`
|
||||
},
|
||||
latestVersion(number: string) {
|
||||
return `Latest Version: ${number}`
|
||||
},
|
||||
viewReleaseNotes(versionNumber: string) {
|
||||
return `View ${versionNumber} Release Notes`
|
||||
},
|
||||
preferencesChanged: {
|
||||
title: 'Preference Changed',
|
||||
message:
|
||||
'Your menu bar preference has been saved. Please restart the ' + 'application for the change to take effect.',
|
||||
},
|
||||
security: {
|
||||
security: 'Security',
|
||||
useKeyringtoStorePassword: 'Use password storage to store password',
|
||||
enabledKeyringAccessMessage:
|
||||
"Standard Notes will try to use your system's password storage " +
|
||||
'facility to store your password the next time you start it.',
|
||||
enabledKeyringQuitNow: 'Quit Now',
|
||||
enabledKeyringPostpone: 'Postpone',
|
||||
},
|
||||
},
|
||||
contextMenu: {
|
||||
learnSpelling: 'Learn Spelling',
|
||||
noSuggestions: 'No Suggestions',
|
||||
},
|
||||
tray: {
|
||||
show: 'Show',
|
||||
hide: 'Hide',
|
||||
quit: 'Quit',
|
||||
},
|
||||
extensions: {
|
||||
missingExtension:
|
||||
'The extension was not found on your system, possibly because it is ' +
|
||||
"still downloading. If the extension doesn't load, " +
|
||||
'try uninstalling then reinstalling the extension.',
|
||||
unableToLoadExtension:
|
||||
'Unable to load extension. Please restart the application and ' +
|
||||
'try again. If the issue persists, try uninstalling then ' +
|
||||
'reinstalling the extension.',
|
||||
},
|
||||
updates: {
|
||||
automaticUpdatesEnabled: {
|
||||
title: 'Automatic Updates Enabled.',
|
||||
message:
|
||||
'Automatic updates have been enabled. Please note that ' +
|
||||
'this functionality is currently in beta, and that you are advised ' +
|
||||
'to periodically check in and ensure you are running the ' +
|
||||
'latest version.',
|
||||
},
|
||||
finishedChecking: {
|
||||
title: 'Finished checking for updates.',
|
||||
error(description: string) {
|
||||
return (
|
||||
'An issue occurred while checking for updates. ' +
|
||||
'Please try again.\nIf this issue persists please contact ' +
|
||||
`support with the following information: ${description}`
|
||||
)
|
||||
},
|
||||
updateAvailable(newVersion: string) {
|
||||
return (
|
||||
`A new update is available (version ${newVersion}). ` +
|
||||
'You can wait for the app to update itself, or manually ' +
|
||||
'download and install this update.'
|
||||
)
|
||||
},
|
||||
noUpdateAvailable(currentVersion: string) {
|
||||
return `Your version (${currentVersion}) is the latest available version.`
|
||||
},
|
||||
},
|
||||
updateReady: {
|
||||
title: 'Update Ready',
|
||||
message(version: string) {
|
||||
return `A new update (version ${version}) is ready to install.`
|
||||
},
|
||||
quitAndInstall: 'Quit and Install',
|
||||
installLater: 'Install Later',
|
||||
noRecentBackupMessage:
|
||||
'An update is ready to install, but your backups folder does not ' +
|
||||
'appear to contain a recent enough backup. Please download a ' +
|
||||
'backup manually before proceeding with the installation.',
|
||||
noRecentBackupDetail(lastBackupDate: number | null) {
|
||||
const downloadInstructions =
|
||||
'You can download a backup from the Account menu ' + 'in the bottom-left corner of the app.'
|
||||
const lastAutomaticBackup =
|
||||
lastBackupDate === null
|
||||
? 'Your backups folder is empty.'
|
||||
: `Your latest automatic backup is from ${new Date(lastBackupDate).toLocaleString()}.`
|
||||
return `${downloadInstructions}\n${lastAutomaticBackup}`
|
||||
},
|
||||
noRecentBackupChecbox: 'I have downloaded a backup, proceed with installation',
|
||||
},
|
||||
errorDownloading: {
|
||||
title: 'Error Downloading',
|
||||
message: 'An error occurred while trying to download your ' + 'update file. Please try again.',
|
||||
},
|
||||
unknownVersionName: 'Unknown',
|
||||
},
|
||||
backups: {
|
||||
errorChangingDirectory(error: any): string {
|
||||
return (
|
||||
'An error occurred while changing your backups directory. ' +
|
||||
'If this issue persists, please contact support with the following ' +
|
||||
'information: \n' +
|
||||
JSON.stringify(error)
|
||||
)
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
42
packages/desktop/app/javascripts/Main/Strings/french.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { Strings } from './types'
|
||||
import { createEnglishStrings } from './english'
|
||||
import { isDev } from '../Utils/Utils'
|
||||
|
||||
export function createFrenchStrings(): Strings {
|
||||
const fallback = createEnglishStrings()
|
||||
if (!isDev()) {
|
||||
/**
|
||||
* Le Français est une langue expérimentale.
|
||||
* Don't show it in production yet.
|
||||
*/
|
||||
return fallback
|
||||
}
|
||||
return {
|
||||
appMenu: {
|
||||
...fallback.appMenu,
|
||||
edit: 'Édition',
|
||||
view: 'Affichage',
|
||||
},
|
||||
contextMenu: {
|
||||
learnSpelling: "Mémoriser l'orthographe",
|
||||
noSuggestions: 'Aucune suggestion',
|
||||
},
|
||||
tray: {
|
||||
show: 'Afficher',
|
||||
hide: 'Masquer',
|
||||
quit: 'Quitter',
|
||||
},
|
||||
extensions: fallback.extensions,
|
||||
updates: fallback.updates,
|
||||
backups: {
|
||||
errorChangingDirectory(error: any): string {
|
||||
return (
|
||||
"Une erreur s'est produite lors du déplacement du dossier de " +
|
||||
'sauvegardes. Si le problème est récurrent, contactez le support ' +
|
||||
'technique (en anglais) avec les informations suivantes:\n' +
|
||||
JSON.stringify(error)
|
||||
)
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
70
packages/desktop/app/javascripts/Main/Strings/index.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import { createEnglishStrings } from './english'
|
||||
import { createFrenchStrings } from './french'
|
||||
import { Strings } from './types'
|
||||
import { isDev } from '../Utils/Utils'
|
||||
|
||||
let strings: Strings
|
||||
|
||||
/**
|
||||
* MUST be called (once) before using any other export in this file.
|
||||
* @param locale The user's locale
|
||||
* @see https://www.electronjs.org/docs/api/locales
|
||||
*/
|
||||
export function initializeStrings(locale: string): void {
|
||||
if (isDev()) {
|
||||
if (strings) {
|
||||
throw new Error('`strings` has already been initialized')
|
||||
}
|
||||
}
|
||||
|
||||
if (strings) {
|
||||
return
|
||||
}
|
||||
|
||||
strings = stringsForLocale(locale)
|
||||
}
|
||||
|
||||
export function str(): Strings {
|
||||
if (isDev()) {
|
||||
if (!strings) {
|
||||
throw new Error('tried to access strings before they were initialized.')
|
||||
}
|
||||
}
|
||||
return strings
|
||||
}
|
||||
|
||||
export function appMenu() {
|
||||
return str().appMenu
|
||||
}
|
||||
|
||||
export function contextMenu() {
|
||||
return str().contextMenu
|
||||
}
|
||||
|
||||
export function tray() {
|
||||
return str().tray
|
||||
}
|
||||
|
||||
export function extensions() {
|
||||
return str().extensions
|
||||
}
|
||||
|
||||
export function updates() {
|
||||
return str().updates
|
||||
}
|
||||
|
||||
export function backups() {
|
||||
return str().backups
|
||||
}
|
||||
|
||||
function stringsForLocale(locale: string): Strings {
|
||||
if (locale === 'en' || locale.startsWith('en-')) {
|
||||
return createEnglishStrings()
|
||||
} else if (locale === 'fr' || locale.startsWith('fr-')) {
|
||||
return createFrenchStrings()
|
||||
}
|
||||
|
||||
return createEnglishStrings()
|
||||
}
|
||||
|
||||
export const AppName = 'Standard Notes'
|
||||
109
packages/desktop/app/javascripts/Main/Strings/types.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
export interface Strings {
|
||||
appMenu: AppMenuStrings
|
||||
contextMenu: ContextMenuStrings
|
||||
tray: TrayStrings
|
||||
extensions: ExtensionsStrings
|
||||
updates: UpdateStrings
|
||||
backups: BackupsStrings
|
||||
}
|
||||
|
||||
interface AppMenuStrings {
|
||||
edit: string
|
||||
view: string
|
||||
hideMenuBar: string
|
||||
useThemedMenuBar: string
|
||||
minimizeToTrayOnClose: string
|
||||
backups: string
|
||||
enableAutomaticUpdates: string
|
||||
automaticUpdatesDisabled: string
|
||||
disableAutomaticBackups: string
|
||||
enableAutomaticBackups: string
|
||||
changeBackupsLocation: string
|
||||
openBackupsLocation: string
|
||||
emailSupport: string
|
||||
website: string
|
||||
gitHub: string
|
||||
slack: string
|
||||
twitter: string
|
||||
toggleErrorConsole: string
|
||||
openDataDirectory: string
|
||||
clearCacheAndReload: string
|
||||
speech: string
|
||||
close: string
|
||||
minimize: string
|
||||
zoom: string
|
||||
bringAllToFront: string
|
||||
checkForUpdate: string
|
||||
checkingForUpdate: string
|
||||
updateAvailable: string
|
||||
updates: string
|
||||
releaseNotes: string
|
||||
openDownloadLocation: string
|
||||
downloadingUpdate: string
|
||||
manuallyDownloadUpdate: string
|
||||
spellcheckerLanguages: string
|
||||
installPendingUpdate(versionNumber: string): string
|
||||
lastUpdateCheck(date: Date): string
|
||||
version(number: string): string
|
||||
yourVersion(number: string): string
|
||||
latestVersion(number: string): string
|
||||
viewReleaseNotes(versionNumber: string): string
|
||||
preferencesChanged: {
|
||||
title: string
|
||||
message: string
|
||||
}
|
||||
security: {
|
||||
security: string
|
||||
useKeyringtoStorePassword: string
|
||||
enabledKeyringAccessMessage: string
|
||||
enabledKeyringQuitNow: string
|
||||
enabledKeyringPostpone: string
|
||||
}
|
||||
}
|
||||
|
||||
interface ContextMenuStrings {
|
||||
learnSpelling: string
|
||||
noSuggestions: string
|
||||
}
|
||||
|
||||
interface TrayStrings {
|
||||
show: string
|
||||
hide: string
|
||||
quit: string
|
||||
}
|
||||
|
||||
interface ExtensionsStrings {
|
||||
unableToLoadExtension: string
|
||||
missingExtension: string
|
||||
}
|
||||
|
||||
interface UpdateStrings {
|
||||
automaticUpdatesEnabled: {
|
||||
title: string
|
||||
message: string
|
||||
}
|
||||
finishedChecking: {
|
||||
title: string
|
||||
error(description: string): string
|
||||
updateAvailable(newVersion: string): string
|
||||
noUpdateAvailable(currentVersion: string): string
|
||||
}
|
||||
updateReady: {
|
||||
title: string
|
||||
message(version: string): string
|
||||
quitAndInstall: string
|
||||
installLater: string
|
||||
noRecentBackupMessage: string
|
||||
noRecentBackupDetail(lastBackupDate: number | null): string
|
||||
noRecentBackupChecbox: string
|
||||
}
|
||||
errorDownloading: {
|
||||
title: string
|
||||
message: string
|
||||
}
|
||||
unknownVersionName: string
|
||||
}
|
||||
|
||||
interface BackupsStrings {
|
||||
errorChangingDirectory(error: any): string
|
||||
}
|
||||
109
packages/desktop/app/javascripts/Main/TrayManager.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import { Menu, Tray } from 'electron'
|
||||
import path from 'path'
|
||||
import { isLinux, isWindows } from './Types/Platforms'
|
||||
import { Store, StoreKeys } from './Store'
|
||||
import { AppName, tray as str } from './Strings'
|
||||
import { isDev } from './Utils/Utils'
|
||||
|
||||
const icon = path.join(__dirname, '/icon/Icon-256x256.png')
|
||||
|
||||
export interface TrayManager {
|
||||
shouldMinimizeToTray(): boolean
|
||||
createTrayIcon(): void
|
||||
destroyTrayIcon(): void
|
||||
}
|
||||
|
||||
export function createTrayManager(window: Electron.BrowserWindow, store: Store): TrayManager {
|
||||
let tray: Tray | undefined
|
||||
let updateContextMenu: (() => void) | undefined
|
||||
|
||||
function showWindow() {
|
||||
window.show()
|
||||
|
||||
if (isLinux()) {
|
||||
/* On some versions of GNOME the window may not be on top when
|
||||
restored. */
|
||||
window.setAlwaysOnTop(true)
|
||||
window.focus()
|
||||
window.setAlwaysOnTop(false)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
shouldMinimizeToTray() {
|
||||
return store.get(StoreKeys.MinimizeToTray)
|
||||
},
|
||||
|
||||
createTrayIcon() {
|
||||
tray = new Tray(icon)
|
||||
tray.setToolTip(AppName)
|
||||
|
||||
if (isWindows()) {
|
||||
/* On Windows, right-clicking invokes the menu, as opposed to
|
||||
left-clicking for the other platforms. So we map left-clicking
|
||||
to the conventional action of showing the app. */
|
||||
tray.on('click', showWindow)
|
||||
}
|
||||
|
||||
const SHOW_WINDOW_ID = 'SHOW_WINDOW'
|
||||
const HIDE_WINDOW_ID = 'HIDE_WINDOW'
|
||||
const trayContextMenu = Menu.buildFromTemplate([
|
||||
{
|
||||
id: SHOW_WINDOW_ID,
|
||||
label: str().show,
|
||||
click: showWindow,
|
||||
},
|
||||
{
|
||||
id: HIDE_WINDOW_ID,
|
||||
label: str().hide,
|
||||
click() {
|
||||
window.hide()
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'separator',
|
||||
},
|
||||
{
|
||||
role: 'quit',
|
||||
label: str().quit,
|
||||
},
|
||||
])
|
||||
|
||||
updateContextMenu = function updateContextMenu() {
|
||||
if (window.isVisible()) {
|
||||
trayContextMenu.getMenuItemById(SHOW_WINDOW_ID)!.visible = false
|
||||
trayContextMenu.getMenuItemById(HIDE_WINDOW_ID)!.visible = true
|
||||
} else {
|
||||
trayContextMenu.getMenuItemById(SHOW_WINDOW_ID)!.visible = true
|
||||
trayContextMenu.getMenuItemById(HIDE_WINDOW_ID)!.visible = false
|
||||
}
|
||||
|
||||
tray!.setContextMenu(trayContextMenu)
|
||||
}
|
||||
updateContextMenu()
|
||||
|
||||
window.on('hide', updateContextMenu)
|
||||
window.on('focus', updateContextMenu)
|
||||
window.on('blur', updateContextMenu)
|
||||
},
|
||||
|
||||
destroyTrayIcon() {
|
||||
if (isDev()) {
|
||||
/** Check our state */
|
||||
if (!updateContextMenu) {
|
||||
throw new Error('updateContextMenu === undefined')
|
||||
}
|
||||
if (!tray) {
|
||||
throw new Error('tray === undefined')
|
||||
}
|
||||
}
|
||||
|
||||
window.off('hide', updateContextMenu!)
|
||||
window.off('focus', updateContextMenu!)
|
||||
window.off('blur', updateContextMenu!)
|
||||
tray!.destroy()
|
||||
tray = undefined
|
||||
updateContextMenu = undefined
|
||||
},
|
||||
}
|
||||
}
|
||||
6
packages/desktop/app/javascripts/Main/Types/Constants.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
/** Build-time constants */
|
||||
declare const IS_SNAP: boolean
|
||||
|
||||
export const isSnap = IS_SNAP
|
||||
export const autoUpdatingAvailable = !isSnap
|
||||
export const keychainAccessIsUserConfigurable = isSnap
|
||||
69
packages/desktop/app/javascripts/Main/Types/Paths.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import path from 'path'
|
||||
import index from '../../../index.html'
|
||||
import grantLinuxPasswordsAccess from '../../../grantLinuxPasswordsAccess.html'
|
||||
import decryptScript from 'decrypt/dist/decrypt.html'
|
||||
import { app } from 'electron'
|
||||
|
||||
function url(fileName: string): string {
|
||||
if ('APP_RELATIVE_PATH' in process.env) {
|
||||
return path.join('file://', __dirname, process.env.APP_RELATIVE_PATH as string, fileName)
|
||||
}
|
||||
return path.join('file://', __dirname, fileName)
|
||||
}
|
||||
|
||||
function filePath(fileName: string): string {
|
||||
if ('APP_RELATIVE_PATH' in process.env) {
|
||||
return path.join(__dirname, process.env.APP_RELATIVE_PATH as string, fileName)
|
||||
}
|
||||
return path.join(__dirname, fileName)
|
||||
}
|
||||
|
||||
export const Urls = {
|
||||
get indexHtml(): string {
|
||||
return url(index)
|
||||
},
|
||||
get grantLinuxPasswordsAccessHtml(): string {
|
||||
return url(grantLinuxPasswordsAccess)
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* App paths can be modified at runtime, most frequently at startup, so don't
|
||||
* store the results of these getters in long-lived constants (like static class
|
||||
* fields).
|
||||
*/
|
||||
export const Paths = {
|
||||
get userDataDir(): string {
|
||||
return app.getPath('userData')
|
||||
},
|
||||
get documentsDir(): string {
|
||||
return app.getPath('documents')
|
||||
},
|
||||
get tempDir(): string {
|
||||
return app.getPath('temp')
|
||||
},
|
||||
get extensionsDirRelative(): string {
|
||||
return 'Extensions'
|
||||
},
|
||||
get extensionsDir(): string {
|
||||
return path.join(Paths.userDataDir, 'Extensions')
|
||||
},
|
||||
get extensionsMappingJson(): string {
|
||||
return path.join(Paths.extensionsDir, 'mapping.json')
|
||||
},
|
||||
get windowPositionJson(): string {
|
||||
return path.join(Paths.userDataDir, 'window-position.json')
|
||||
},
|
||||
get decryptScript(): string {
|
||||
return filePath(decryptScript)
|
||||
},
|
||||
get preloadJs(): string {
|
||||
return path.join(__dirname, 'javascripts/renderer/preload.js')
|
||||
},
|
||||
get components(): string {
|
||||
return `${app.getAppPath()}/dist/web/components`
|
||||
},
|
||||
get grantLinuxPasswordsAccessJs(): string {
|
||||
return path.join(__dirname, 'javascripts/renderer/grantLinuxPasswordsAccess.js')
|
||||
},
|
||||
}
|
||||
31
packages/desktop/app/javascripts/Main/Types/Platforms.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
/**
|
||||
* TODO(baptiste): precompute these booleans at compile-time
|
||||
* (requires one webpack build per platform)
|
||||
*/
|
||||
|
||||
export function isWindows(): boolean {
|
||||
return process.platform === 'win32'
|
||||
}
|
||||
export function isMac(): boolean {
|
||||
return process.platform === 'darwin'
|
||||
}
|
||||
export function isLinux(): boolean {
|
||||
return process.platform === 'linux'
|
||||
}
|
||||
|
||||
export type InstallerKey = 'mac' | 'windows' | 'appimage_64' | 'appimage_32'
|
||||
export function getInstallerKey(): InstallerKey {
|
||||
if (isWindows()) {
|
||||
return 'windows'
|
||||
} else if (isMac()) {
|
||||
return 'mac'
|
||||
} else if (isLinux()) {
|
||||
if (process.arch === 'x32') {
|
||||
return 'appimage_32'
|
||||
} else {
|
||||
return 'appimage_64'
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Unknown platform: ${process.platform}`)
|
||||
}
|
||||
}
|
||||
249
packages/desktop/app/javascripts/Main/UpdateManager.ts
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
import compareVersions from 'compare-versions'
|
||||
import { BrowserWindow, dialog, shell } from 'electron'
|
||||
import electronLog from 'electron-log'
|
||||
import { autoUpdater } from 'electron-updater'
|
||||
import { action, autorun, computed, makeObservable, observable } from 'mobx'
|
||||
import { autoUpdatingAvailable } from './Types/Constants'
|
||||
import { MessageType } from '../../../test/TestIpcMessage'
|
||||
import { AppState } from '../../application'
|
||||
import { BackupsManagerInterface } from './Backups/BackupsManagerInterface'
|
||||
import { StoreKeys } from './Store'
|
||||
import { updates as str } from './Strings'
|
||||
import { handleTestMessage } from './Utils/Testing'
|
||||
import { isTesting } from './Utils/Utils'
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function logError(...message: any) {
|
||||
console.error('updateManager:', ...message)
|
||||
}
|
||||
|
||||
if (isTesting()) {
|
||||
// eslint-disable-next-line no-var
|
||||
var notifiedStateUpdate = false
|
||||
}
|
||||
|
||||
export class UpdateState {
|
||||
latestVersion: string | null = null
|
||||
enableAutoUpdate: boolean
|
||||
checkingForUpdate = false
|
||||
autoUpdateDownloaded = false
|
||||
lastCheck: Date | null = null
|
||||
|
||||
constructor(private appState: AppState) {
|
||||
this.enableAutoUpdate = autoUpdatingAvailable && appState.store.get(StoreKeys.EnableAutoUpdate)
|
||||
makeObservable(this, {
|
||||
latestVersion: observable,
|
||||
enableAutoUpdate: observable,
|
||||
checkingForUpdate: observable,
|
||||
autoUpdateDownloaded: observable,
|
||||
lastCheck: observable,
|
||||
|
||||
updateNeeded: computed,
|
||||
|
||||
toggleAutoUpdate: action,
|
||||
setCheckingForUpdate: action,
|
||||
autoUpdateHasBeenDownloaded: action,
|
||||
checkedForUpdate: action,
|
||||
})
|
||||
|
||||
if (isTesting()) {
|
||||
handleTestMessage(MessageType.UpdateState, () => ({
|
||||
lastCheck: this.lastCheck,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
get updateNeeded(): boolean {
|
||||
if (this.latestVersion) {
|
||||
return compareVersions(this.latestVersion, this.appState.version) === 1
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
toggleAutoUpdate(): void {
|
||||
this.enableAutoUpdate = !this.enableAutoUpdate
|
||||
this.appState.store.set(StoreKeys.EnableAutoUpdate, this.enableAutoUpdate)
|
||||
}
|
||||
|
||||
setCheckingForUpdate(checking: boolean): void {
|
||||
this.checkingForUpdate = checking
|
||||
}
|
||||
|
||||
autoUpdateHasBeenDownloaded(version: string | null): void {
|
||||
this.autoUpdateDownloaded = true
|
||||
this.latestVersion = version
|
||||
}
|
||||
|
||||
checkedForUpdate(latestVersion: string | null): void {
|
||||
this.lastCheck = new Date()
|
||||
this.latestVersion = latestVersion
|
||||
}
|
||||
}
|
||||
|
||||
let updatesSetup = false
|
||||
|
||||
export function setupUpdates(window: BrowserWindow, appState: AppState, backupsManager: BackupsManagerInterface): void {
|
||||
if (!autoUpdatingAvailable) {
|
||||
return
|
||||
}
|
||||
if (updatesSetup) {
|
||||
throw Error('Already set up updates.')
|
||||
}
|
||||
const { store } = appState
|
||||
|
||||
autoUpdater.logger = electronLog
|
||||
|
||||
const updateState = appState.updates
|
||||
|
||||
function checkUpdateSafety(): boolean {
|
||||
let canUpdate: boolean
|
||||
if (appState.store.get(StoreKeys.BackupsDisabled)) {
|
||||
canUpdate = true
|
||||
} else {
|
||||
canUpdate = updateState.enableAutoUpdate && isLessThanOneHourFromNow(appState.lastBackupDate)
|
||||
}
|
||||
autoUpdater.autoInstallOnAppQuit = canUpdate
|
||||
autoUpdater.autoDownload = canUpdate
|
||||
return canUpdate
|
||||
}
|
||||
autorun(checkUpdateSafety)
|
||||
|
||||
const oneHour = 1 * 60 * 60 * 1000
|
||||
setInterval(checkUpdateSafety, oneHour)
|
||||
|
||||
autoUpdater.on('update-downloaded', (info: { version?: string }) => {
|
||||
window.webContents.send('update-available', null)
|
||||
updateState.autoUpdateHasBeenDownloaded(info.version || null)
|
||||
})
|
||||
|
||||
autoUpdater.on('error', logError)
|
||||
autoUpdater.on('update-available', (info: { version?: string }) => {
|
||||
updateState.checkedForUpdate(info.version || null)
|
||||
if (updateState.enableAutoUpdate) {
|
||||
const canUpdate = checkUpdateSafety()
|
||||
if (!canUpdate) {
|
||||
backupsManager.performBackup()
|
||||
}
|
||||
}
|
||||
})
|
||||
autoUpdater.on('update-not-available', (info: { version?: string }) => {
|
||||
updateState.checkedForUpdate(info.version || null)
|
||||
})
|
||||
|
||||
updatesSetup = true
|
||||
|
||||
if (isTesting()) {
|
||||
handleTestMessage(MessageType.AutoUpdateEnabled, () => store.get(StoreKeys.EnableAutoUpdate))
|
||||
handleTestMessage(MessageType.CheckForUpdate, () => checkForUpdate(appState, updateState))
|
||||
// eslint-disable-next-line block-scoped-var
|
||||
handleTestMessage(MessageType.UpdateManagerNotifiedStateChange, () => notifiedStateUpdate)
|
||||
} else {
|
||||
void checkForUpdate(appState, updateState)
|
||||
}
|
||||
}
|
||||
|
||||
export function openChangelog(state: UpdateState): void {
|
||||
const url = 'https://github.com/standardnotes/desktop/releases'
|
||||
if (state.latestVersion) {
|
||||
void shell.openExternal(`${url}/tag/v${state.latestVersion}`)
|
||||
} else {
|
||||
void shell.openExternal(url)
|
||||
}
|
||||
}
|
||||
|
||||
function quitAndInstall(window: BrowserWindow) {
|
||||
setTimeout(() => {
|
||||
// index.js prevents close event on some platforms
|
||||
window.removeAllListeners('close')
|
||||
window.close()
|
||||
autoUpdater.quitAndInstall(false)
|
||||
}, 0)
|
||||
}
|
||||
|
||||
function isLessThanOneHourFromNow(date: number | null) {
|
||||
const now = Date.now()
|
||||
const onHourMs = 1 * 60 * 60 * 1000
|
||||
return now - (date ?? 0) < onHourMs
|
||||
}
|
||||
|
||||
export async function showUpdateInstallationDialog(parentWindow: BrowserWindow, appState: AppState): Promise<void> {
|
||||
if (!appState.updates.latestVersion) {
|
||||
return
|
||||
}
|
||||
|
||||
if (appState.lastBackupDate && isLessThanOneHourFromNow(appState.lastBackupDate)) {
|
||||
const result = await dialog.showMessageBox(parentWindow, {
|
||||
type: 'info',
|
||||
title: str().updateReady.title,
|
||||
message: str().updateReady.message(appState.updates.latestVersion),
|
||||
buttons: [str().updateReady.installLater, str().updateReady.quitAndInstall],
|
||||
cancelId: 0,
|
||||
})
|
||||
|
||||
const buttonIndex = result.response
|
||||
if (buttonIndex === 1) {
|
||||
quitAndInstall(parentWindow)
|
||||
}
|
||||
} else {
|
||||
const cancelId = 0
|
||||
const result = await dialog.showMessageBox({
|
||||
type: 'warning',
|
||||
title: str().updateReady.title,
|
||||
message: str().updateReady.noRecentBackupMessage,
|
||||
detail: str().updateReady.noRecentBackupDetail(appState.lastBackupDate),
|
||||
checkboxLabel: str().updateReady.noRecentBackupChecbox,
|
||||
checkboxChecked: false,
|
||||
buttons: [str().updateReady.installLater, str().updateReady.quitAndInstall],
|
||||
cancelId,
|
||||
})
|
||||
|
||||
if (!result.checkboxChecked || result.response === cancelId) {
|
||||
return
|
||||
}
|
||||
quitAndInstall(parentWindow)
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkForUpdate(appState: AppState, state: UpdateState, userTriggered = false): Promise<void> {
|
||||
if (!autoUpdatingAvailable) {
|
||||
return
|
||||
}
|
||||
|
||||
if (state.enableAutoUpdate || userTriggered) {
|
||||
state.setCheckingForUpdate(true)
|
||||
|
||||
try {
|
||||
const result = await autoUpdater.checkForUpdates()
|
||||
|
||||
if (!result) {
|
||||
return
|
||||
}
|
||||
|
||||
state.checkedForUpdate(result.updateInfo.version)
|
||||
|
||||
if (userTriggered) {
|
||||
let message
|
||||
if (state.updateNeeded && state.latestVersion) {
|
||||
message = str().finishedChecking.updateAvailable(state.latestVersion)
|
||||
} else {
|
||||
message = str().finishedChecking.noUpdateAvailable(appState.version)
|
||||
}
|
||||
|
||||
void dialog.showMessageBox({
|
||||
title: str().finishedChecking.title,
|
||||
message,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
if (userTriggered) {
|
||||
void dialog.showMessageBox({
|
||||
title: str().finishedChecking.title,
|
||||
message: str().finishedChecking.error(JSON.stringify(error)),
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
state.setCheckingForUpdate(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
272
packages/desktop/app/javascripts/Main/Utils/FileUtils.ts
Normal file
|
|
@ -0,0 +1,272 @@
|
|||
import fs, { PathLike } from 'fs'
|
||||
import { debounce } from 'lodash'
|
||||
import path from 'path'
|
||||
import yauzl from 'yauzl'
|
||||
import { removeFromArray } from '../Utils/Utils'
|
||||
import { dialog } from 'electron'
|
||||
|
||||
export const FileDoesNotExist = 'ENOENT'
|
||||
export const FileAlreadyExists = 'EEXIST'
|
||||
const CrossDeviceLink = 'EXDEV'
|
||||
const OperationNotPermitted = 'EPERM'
|
||||
const DeviceIsBusy = 'EBUSY'
|
||||
|
||||
export function debouncedJSONDiskWriter(durationMs: number, location: string, data: () => unknown): () => void {
|
||||
let writingToDisk = false
|
||||
return debounce(async () => {
|
||||
if (writingToDisk) {
|
||||
return
|
||||
}
|
||||
writingToDisk = true
|
||||
try {
|
||||
await writeJSONFile(location, data())
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
} finally {
|
||||
writingToDisk = false
|
||||
}
|
||||
}, durationMs)
|
||||
}
|
||||
|
||||
export async function openDirectoryPicker(): Promise<string | undefined> {
|
||||
const result = await dialog.showOpenDialog({
|
||||
properties: ['openDirectory', 'showHiddenFiles', 'createDirectory'],
|
||||
})
|
||||
|
||||
return result.filePaths[0]
|
||||
}
|
||||
|
||||
export async function readJSONFile<T>(filepath: string): Promise<T | undefined> {
|
||||
try {
|
||||
const data = await fs.promises.readFile(filepath, 'utf8')
|
||||
return JSON.parse(data)
|
||||
} catch (error) {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export function readJSONFileSync<T>(filepath: string): T {
|
||||
const data = fs.readFileSync(filepath, 'utf8')
|
||||
return JSON.parse(data)
|
||||
}
|
||||
|
||||
export async function writeJSONFile(filepath: string, data: unknown): Promise<void> {
|
||||
await ensureDirectoryExists(path.dirname(filepath))
|
||||
await fs.promises.writeFile(filepath, JSON.stringify(data, null, 2), 'utf8')
|
||||
}
|
||||
|
||||
export async function writeFile(filepath: string, data: string): Promise<void> {
|
||||
await ensureDirectoryExists(path.dirname(filepath))
|
||||
await fs.promises.writeFile(filepath, data, 'utf8')
|
||||
}
|
||||
|
||||
export function writeJSONFileSync(filepath: string, data: unknown): void {
|
||||
fs.writeFileSync(filepath, JSON.stringify(data, null, 2), 'utf8')
|
||||
}
|
||||
|
||||
export async function ensureDirectoryExists(dirPath: string): Promise<void> {
|
||||
try {
|
||||
const stat = await fs.promises.lstat(dirPath)
|
||||
if (!stat.isDirectory()) {
|
||||
throw new Error('Tried to create a directory where a file of the same ' + `name already exists: ${dirPath}`)
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error.code === FileDoesNotExist) {
|
||||
/**
|
||||
* No directory here. Make sure there is a *parent* directory, and then
|
||||
* create it.
|
||||
*/
|
||||
await ensureDirectoryExists(path.dirname(dirPath))
|
||||
|
||||
/** Now that its parent(s) exist, create the directory */
|
||||
try {
|
||||
await fs.promises.mkdir(dirPath)
|
||||
} catch (error: any) {
|
||||
if (error.code === FileAlreadyExists) {
|
||||
/**
|
||||
* A concurrent process must have created the directory already.
|
||||
* Make sure it *is* a directory and not something else.
|
||||
*/
|
||||
await ensureDirectoryExists(dirPath)
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a directory (handling recursion.)
|
||||
* @param {string} dirPath the path of the directory
|
||||
*/
|
||||
export async function deleteDir(dirPath: string): Promise<void> {
|
||||
try {
|
||||
await deleteDirContents(dirPath)
|
||||
} catch (error: any) {
|
||||
if (error.code === FileDoesNotExist) {
|
||||
/** Directory has already been deleted. */
|
||||
return
|
||||
}
|
||||
throw error
|
||||
}
|
||||
await fs.promises.rmdir(dirPath)
|
||||
}
|
||||
|
||||
export async function deleteDirContents(dirPath: string): Promise<void> {
|
||||
/**
|
||||
* Scan the directory up to ten times, to handle cases where files are being added while
|
||||
* the directory's contents are being deleted
|
||||
*/
|
||||
for (let i = 1, maxTries = 10; i < maxTries; i++) {
|
||||
const children = await fs.promises.readdir(dirPath, {
|
||||
withFileTypes: true,
|
||||
})
|
||||
|
||||
if (children.length === 0) {
|
||||
break
|
||||
}
|
||||
|
||||
for (const child of children) {
|
||||
const childPath = path.join(dirPath, child.name)
|
||||
if (child.isDirectory()) {
|
||||
await deleteDirContents(childPath)
|
||||
try {
|
||||
await fs.promises.rmdir(childPath)
|
||||
} catch (error) {
|
||||
if (error !== FileDoesNotExist) {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
} else {
|
||||
await deleteFile(childPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isChildOfDir(parent: string, potentialChild: string) {
|
||||
const relative = path.relative(parent, potentialChild)
|
||||
return relative && !relative.startsWith('..') && !path.isAbsolute(relative)
|
||||
}
|
||||
|
||||
export async function moveDirContents(srcDir: string, destDir: string): Promise<void[]> {
|
||||
let fileNames = await fs.promises.readdir(srcDir)
|
||||
await ensureDirectoryExists(destDir)
|
||||
|
||||
if (isChildOfDir(srcDir, destDir)) {
|
||||
fileNames = fileNames.filter((name) => {
|
||||
return !isChildOfDir(destDir, path.join(srcDir, name))
|
||||
})
|
||||
removeFromArray(fileNames, path.basename(destDir))
|
||||
}
|
||||
|
||||
return moveFiles(
|
||||
fileNames.map((fileName) => path.join(srcDir, fileName)),
|
||||
destDir,
|
||||
)
|
||||
}
|
||||
|
||||
export async function extractNestedZip(source: string, dest: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
yauzl.open(source, { lazyEntries: true, autoClose: true }, (err, zipFile) => {
|
||||
let cancelled = false
|
||||
const tryReject = (err: Error) => {
|
||||
if (!cancelled) {
|
||||
cancelled = true
|
||||
reject(err)
|
||||
}
|
||||
}
|
||||
if (err) {
|
||||
return tryReject(err)
|
||||
}
|
||||
if (!zipFile) {
|
||||
return tryReject(new Error('zipFile === undefined'))
|
||||
}
|
||||
|
||||
zipFile.readEntry()
|
||||
zipFile.on('close', resolve)
|
||||
zipFile.on('entry', (entry) => {
|
||||
if (cancelled) {
|
||||
return
|
||||
}
|
||||
if (entry.fileName.endsWith('/')) {
|
||||
/** entry is a directory, skip and read next entry */
|
||||
zipFile.readEntry()
|
||||
return
|
||||
}
|
||||
|
||||
zipFile.openReadStream(entry, async (err, stream) => {
|
||||
if (cancelled) {
|
||||
return
|
||||
}
|
||||
if (err) {
|
||||
return tryReject(err)
|
||||
}
|
||||
if (!stream) {
|
||||
return tryReject(new Error('stream === undefined'))
|
||||
}
|
||||
stream.on('error', tryReject)
|
||||
const filepath = path.join(
|
||||
dest,
|
||||
/**
|
||||
* Remove the first element of the entry's path, which is the base
|
||||
* directory we want to ignore
|
||||
*/
|
||||
entry.fileName.substring(entry.fileName.indexOf('/') + 1),
|
||||
)
|
||||
try {
|
||||
await ensureDirectoryExists(path.dirname(filepath))
|
||||
} catch (error: any) {
|
||||
return tryReject(error)
|
||||
}
|
||||
const writeStream = fs.createWriteStream(filepath).on('error', tryReject).on('error', tryReject)
|
||||
|
||||
stream.pipe(writeStream).on('close', () => {
|
||||
zipFile.readEntry()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export async function moveFiles(sources: string[], destDir: string): Promise<void[]> {
|
||||
await ensureDirectoryExists(destDir)
|
||||
return Promise.all(sources.map((fileName) => moveFile(fileName, path.join(destDir, path.basename(fileName)))))
|
||||
}
|
||||
|
||||
async function moveFile(source: PathLike, destination: PathLike) {
|
||||
try {
|
||||
await fs.promises.rename(source, destination)
|
||||
} catch (error: any) {
|
||||
if (error.code === CrossDeviceLink) {
|
||||
/** Fall back to copying and then deleting. */
|
||||
await fs.promises.copyFile(source, destination)
|
||||
await fs.promises.unlink(source)
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes a file, handling EPERM and EBUSY errors on Windows. */
|
||||
export async function deleteFile(filePath: PathLike): Promise<void> {
|
||||
for (let i = 1, maxTries = 10; i < maxTries; i++) {
|
||||
try {
|
||||
await fs.promises.unlink(filePath)
|
||||
break
|
||||
} catch (error: any) {
|
||||
if (error.code === OperationNotPermitted || error.code === DeviceIsBusy) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
continue
|
||||
} else if (error.code === FileDoesNotExist) {
|
||||
/** Already deleted */
|
||||
break
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
61
packages/desktop/app/javascripts/Main/Utils/Testing.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import { app, BrowserWindow } from 'electron'
|
||||
import { AppMessageType, MessageType, TestIPCMessage } from '../../../../test/TestIpcMessage'
|
||||
import { isTesting } from '../Utils/Utils'
|
||||
|
||||
const messageHandlers: {
|
||||
[key in MessageType]?: (...args: any) => unknown
|
||||
} = {}
|
||||
|
||||
export function handleTestMessage(type: MessageType, handler: (...args: any) => unknown): void {
|
||||
if (!isTesting()) {
|
||||
throw Error('Tried to invoke test handler in non-test build.')
|
||||
}
|
||||
|
||||
messageHandlers[type] = handler
|
||||
}
|
||||
|
||||
export function send(type: AppMessageType, data?: unknown): void {
|
||||
if (!isTesting()) {
|
||||
return
|
||||
}
|
||||
|
||||
process.send!({ type, data })
|
||||
}
|
||||
|
||||
export function setupTesting(): void {
|
||||
process.on('message', async (message: TestIPCMessage) => {
|
||||
const handler = messageHandlers[message.type]
|
||||
|
||||
if (!handler) {
|
||||
process.send!({
|
||||
id: message.id,
|
||||
reject: `No handler registered for message type ${MessageType[message.type]}`,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
let returnValue = handler(...message.args)
|
||||
if (returnValue instanceof Promise) {
|
||||
returnValue = await returnValue
|
||||
}
|
||||
process.send!({
|
||||
id: message.id,
|
||||
resolve: returnValue,
|
||||
})
|
||||
} catch (error: any) {
|
||||
process.send!({
|
||||
id: message.id,
|
||||
reject: error.toString(),
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
handleTestMessage(MessageType.WindowCount, () => BrowserWindow.getAllWindows().length)
|
||||
|
||||
app.on('ready', () => {
|
||||
setTimeout(() => {
|
||||
send(AppMessageType.Ready)
|
||||
}, 200)
|
||||
})
|
||||
}
|
||||
44
packages/desktop/app/javascripts/Main/Utils/Utils.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { CommandLineArgs } from '../../Shared/CommandLineArgs'
|
||||
|
||||
export function isDev(): boolean {
|
||||
return process.env.NODE_ENV === 'development'
|
||||
}
|
||||
|
||||
export function isTesting(): boolean {
|
||||
return isDev() && process.argv.includes(CommandLineArgs.Testing)
|
||||
}
|
||||
|
||||
export function isBoolean(arg: unknown): arg is boolean {
|
||||
return typeof arg === 'boolean'
|
||||
}
|
||||
|
||||
export function ensureIsBoolean(arg: unknown, fallbackValue: boolean): boolean {
|
||||
if (isBoolean(arg)) {
|
||||
return arg
|
||||
}
|
||||
return fallbackValue
|
||||
}
|
||||
|
||||
export function stringOrNull(arg: unknown): string | null {
|
||||
if (typeof arg === 'string') {
|
||||
return arg
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Ensures a path's drive letter is lowercase. */
|
||||
export function lowercaseDriveLetter(filePath: string): string {
|
||||
return filePath.replace(/^\/[A-Z]:\//, (letter) => letter.toLowerCase())
|
||||
}
|
||||
|
||||
export function timeout(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
export function removeFromArray<T>(array: T[], toRemove: T): void {
|
||||
array.splice(array.indexOf(toRemove), 1)
|
||||
}
|
||||
|
||||
export function last<T>(array: T[]): T | undefined {
|
||||
return array[array.length - 1]
|
||||
}
|
||||
333
packages/desktop/app/javascripts/Main/Window.ts
Normal file
|
|
@ -0,0 +1,333 @@
|
|||
import { BrowserWindow, Rectangle, screen, Shell } from 'electron'
|
||||
import fs from 'fs'
|
||||
import { debounce } from 'lodash'
|
||||
import path from 'path'
|
||||
import { AppMessageType, MessageType } from '../../../test/TestIpcMessage'
|
||||
import { AppState } from '../../application'
|
||||
import { MessageToWebApp } from '../Shared/IpcMessages'
|
||||
import { createBackupsManager } from './Backups/BackupsManager'
|
||||
import { BackupsManagerInterface } from './Backups/BackupsManagerInterface'
|
||||
import { buildContextMenu, createMenuManager } from './Menus/Menus'
|
||||
import { initializePackageManager } from './Packages/PackageManager'
|
||||
import { isMac, isWindows } from './Types/Platforms'
|
||||
import { initializeSearchManager } from './Search/SearchManager'
|
||||
import { createSpellcheckerManager } from './SpellcheckerManager'
|
||||
import { Store, StoreKeys } from './Store'
|
||||
import { handleTestMessage, send } from './Utils/Testing'
|
||||
import { createTrayManager, TrayManager } from './TrayManager'
|
||||
import { checkForUpdate, setupUpdates } from './UpdateManager'
|
||||
import { isTesting, lowercaseDriveLetter } from './Utils/Utils'
|
||||
import { initializeZoomManager } from './ZoomManager'
|
||||
import { Paths } from './Types/Paths'
|
||||
import { clearSensitiveDirectories } from '@standardnotes/electron-clear-data'
|
||||
import { RemoteBridge } from './Remote/RemoteBridge'
|
||||
import { Keychain } from './Keychain/Keychain'
|
||||
import { MenuManagerInterface } from './Menus/MenuManagerInterface'
|
||||
import { FilesBackupManager } from './FileBackups/FileBackupsManager'
|
||||
|
||||
const WINDOW_DEFAULT_WIDTH = 1100
|
||||
const WINDOW_DEFAULT_HEIGHT = 800
|
||||
const WINDOW_MIN_WIDTH = 300
|
||||
const WINDOW_MIN_HEIGHT = 400
|
||||
|
||||
export interface WindowState {
|
||||
window: Electron.BrowserWindow
|
||||
menuManager: MenuManagerInterface
|
||||
backupsManager: BackupsManagerInterface
|
||||
trayManager: TrayManager
|
||||
}
|
||||
|
||||
function hideWindowsTaskbarPreviewThumbnail(window: BrowserWindow) {
|
||||
if (isWindows()) {
|
||||
window.setThumbnailClip({ x: 0, y: 0, width: 1, height: 1 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function createWindowState({
|
||||
shell,
|
||||
appState,
|
||||
appLocale,
|
||||
teardown,
|
||||
}: {
|
||||
shell: Shell
|
||||
appLocale: string
|
||||
appState: AppState
|
||||
teardown: () => void
|
||||
}): Promise<WindowState> {
|
||||
const window = await createWindow(appState.store)
|
||||
|
||||
const services = await createWindowServices(window, appState, appLocale)
|
||||
|
||||
require('@electron/remote/main').enable(window.webContents)
|
||||
;(global as any).RemoteBridge = new RemoteBridge(
|
||||
window,
|
||||
Keychain,
|
||||
services.backupsManager,
|
||||
services.packageManager,
|
||||
services.searchManager,
|
||||
{
|
||||
destroySensitiveDirectories: () => {
|
||||
const restart = true
|
||||
clearSensitiveDirectories(restart)
|
||||
},
|
||||
},
|
||||
services.menuManager,
|
||||
services.fileBackupsManager,
|
||||
)
|
||||
|
||||
const shouldOpenUrl = (url: string) => url.startsWith('http') || url.startsWith('mailto')
|
||||
|
||||
window.on('closed', teardown)
|
||||
|
||||
window.on('show', () => {
|
||||
void checkForUpdate(appState, appState.updates, false)
|
||||
hideWindowsTaskbarPreviewThumbnail(window)
|
||||
})
|
||||
|
||||
window.on('focus', () => {
|
||||
window.webContents.send(MessageToWebApp.WindowFocused, null)
|
||||
})
|
||||
|
||||
window.on('blur', () => {
|
||||
window.webContents.send(MessageToWebApp.WindowBlurred, null)
|
||||
services.backupsManager.applicationDidBlur()
|
||||
})
|
||||
|
||||
window.once('ready-to-show', () => {
|
||||
window.show()
|
||||
})
|
||||
|
||||
window.on('close', (event) => {
|
||||
if (!appState.willQuitApp && (isMac() || services.trayManager.shouldMinimizeToTray())) {
|
||||
/**
|
||||
* On MacOS, closing a window does not quit the app. On Window and Linux,
|
||||
* it only does if you haven't enabled minimize to tray.
|
||||
*/
|
||||
event.preventDefault()
|
||||
/**
|
||||
* Handles Mac full screen issue where pressing close results
|
||||
* in a black screen.
|
||||
*/
|
||||
if (window.isFullScreen()) {
|
||||
window.setFullScreen(false)
|
||||
}
|
||||
window.hide()
|
||||
}
|
||||
})
|
||||
|
||||
window.webContents.session.setSpellCheckerDictionaryDownloadURL('https://dictionaries.standardnotes.org/9.4.4/')
|
||||
|
||||
/** handle link clicks */
|
||||
window.webContents.on('new-window', (event, url) => {
|
||||
if (shouldOpenUrl(url)) {
|
||||
void shell.openExternal(url)
|
||||
}
|
||||
event.preventDefault()
|
||||
})
|
||||
|
||||
/**
|
||||
* handle link clicks (this event is fired instead of 'new-window' when
|
||||
* target is not set to _blank, such as with window.location.assign)
|
||||
*/
|
||||
window.webContents.on('will-navigate', (event, url) => {
|
||||
/** Check for windowUrl equality in the case of window.reload() calls. */
|
||||
if (fileUrlsAreEqual(url, appState.startUrl)) {
|
||||
return
|
||||
}
|
||||
if (shouldOpenUrl(url)) {
|
||||
void shell.openExternal(url)
|
||||
}
|
||||
event.preventDefault()
|
||||
})
|
||||
|
||||
window.webContents.on('context-menu', (_event, params) => {
|
||||
buildContextMenu(window.webContents, params).popup()
|
||||
})
|
||||
|
||||
return {
|
||||
window,
|
||||
...services,
|
||||
}
|
||||
}
|
||||
|
||||
async function createWindow(store: Store): Promise<Electron.BrowserWindow> {
|
||||
const useSystemMenuBar = store.get(StoreKeys.UseSystemMenuBar)
|
||||
const position = await getPreviousWindowPosition()
|
||||
const window = new BrowserWindow({
|
||||
...position.bounds,
|
||||
minWidth: WINDOW_MIN_WIDTH,
|
||||
minHeight: WINDOW_MIN_HEIGHT,
|
||||
show: false,
|
||||
icon: path.join(__dirname, '/icon/Icon-512x512.png'),
|
||||
titleBarStyle: isMac() || useSystemMenuBar ? 'hiddenInset' : undefined,
|
||||
frame: isMac() ? false : useSystemMenuBar,
|
||||
webPreferences: {
|
||||
spellcheck: true,
|
||||
nodeIntegration: isTesting(),
|
||||
contextIsolation: true,
|
||||
preload: Paths.preloadJs,
|
||||
},
|
||||
})
|
||||
if (position.isFullScreen) {
|
||||
window.setFullScreen(true)
|
||||
}
|
||||
|
||||
if (position.isMaximized) {
|
||||
window.maximize()
|
||||
}
|
||||
persistWindowPosition(window)
|
||||
|
||||
if (isTesting()) {
|
||||
handleTestMessage(MessageType.SpellCheckerLanguages, () => window.webContents.session.getSpellCheckerLanguages())
|
||||
handleTestMessage(MessageType.SetLocalStorageValue, async (key, value) => {
|
||||
await window.webContents.executeJavaScript(`localStorage.setItem("${key}", "${value}")`)
|
||||
window.webContents.session.flushStorageData()
|
||||
})
|
||||
handleTestMessage(MessageType.SignOut, () => window.webContents.executeJavaScript('window.device.onSignOut(false)'))
|
||||
window.webContents.once('did-finish-load', () => {
|
||||
send(AppMessageType.WindowLoaded)
|
||||
})
|
||||
}
|
||||
|
||||
return window
|
||||
}
|
||||
|
||||
async function createWindowServices(window: Electron.BrowserWindow, appState: AppState, appLocale: string) {
|
||||
const packageManager = await initializePackageManager(window.webContents)
|
||||
const searchManager = initializeSearchManager(window.webContents)
|
||||
initializeZoomManager(window, appState.store)
|
||||
|
||||
const backupsManager = createBackupsManager(window.webContents, appState)
|
||||
const updateManager = setupUpdates(window, appState, backupsManager)
|
||||
const trayManager = createTrayManager(window, appState.store)
|
||||
const spellcheckerManager = createSpellcheckerManager(appState.store, window.webContents, appLocale)
|
||||
|
||||
if (isTesting()) {
|
||||
handleTestMessage(MessageType.SpellCheckerManager, () => spellcheckerManager)
|
||||
}
|
||||
|
||||
const menuManager = createMenuManager({
|
||||
appState,
|
||||
window,
|
||||
backupsManager,
|
||||
trayManager,
|
||||
store: appState.store,
|
||||
spellcheckerManager,
|
||||
})
|
||||
|
||||
const fileBackupsManager = new FilesBackupManager(appState)
|
||||
|
||||
return {
|
||||
backupsManager,
|
||||
updateManager,
|
||||
trayManager,
|
||||
spellcheckerManager,
|
||||
menuManager,
|
||||
packageManager,
|
||||
searchManager,
|
||||
fileBackupsManager,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check file urls for equality by decoding components
|
||||
* In packaged app, spaces in navigation events urls can contain %20
|
||||
* but not in windowUrl.
|
||||
*/
|
||||
function fileUrlsAreEqual(a: string, b: string): boolean {
|
||||
/** Catch exceptions in case of malformed urls. */
|
||||
try {
|
||||
/**
|
||||
* Craft URL objects to eliminate production URL values that can
|
||||
* contain "#!/" suffixes (on Windows)
|
||||
*/
|
||||
let aPath = new URL(decodeURIComponent(a)).pathname
|
||||
let bPath = new URL(decodeURIComponent(b)).pathname
|
||||
if (isWindows()) {
|
||||
/** On Windows, drive letter casing is inconsistent */
|
||||
aPath = lowercaseDriveLetter(aPath)
|
||||
bPath = lowercaseDriveLetter(bPath)
|
||||
}
|
||||
return aPath === bPath
|
||||
} catch (error) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
interface WindowPosition {
|
||||
bounds: Rectangle
|
||||
isMaximized: boolean
|
||||
isFullScreen: boolean
|
||||
}
|
||||
|
||||
async function getPreviousWindowPosition() {
|
||||
let position: WindowPosition
|
||||
try {
|
||||
position = JSON.parse(await fs.promises.readFile(path.join(Paths.userDataDir, 'window-position.json'), 'utf8'))
|
||||
} catch (e) {
|
||||
return {
|
||||
bounds: {
|
||||
width: WINDOW_DEFAULT_WIDTH,
|
||||
height: WINDOW_DEFAULT_HEIGHT,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const options: Partial<Rectangle> = {}
|
||||
const bounds = position.bounds
|
||||
if (bounds) {
|
||||
/** Validate coordinates. Keep them if the window can fit on a screen */
|
||||
const area = screen.getDisplayMatching(bounds).workArea
|
||||
if (
|
||||
bounds.x >= area.x &&
|
||||
bounds.y >= area.y &&
|
||||
bounds.x + bounds.width <= area.x + area.width &&
|
||||
bounds.y + bounds.height <= area.y + area.height
|
||||
) {
|
||||
options.x = bounds.x
|
||||
options.y = bounds.y
|
||||
}
|
||||
if (bounds.width <= area.width || bounds.height <= area.height) {
|
||||
options.width = bounds.width
|
||||
options.height = bounds.height
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isMaximized: position.isMaximized,
|
||||
isFullScreen: position.isFullScreen,
|
||||
bounds: {
|
||||
width: WINDOW_DEFAULT_WIDTH,
|
||||
height: WINDOW_DEFAULT_HEIGHT,
|
||||
...options,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function persistWindowPosition(window: BrowserWindow) {
|
||||
let writingToDisk = false
|
||||
|
||||
const saveWindowBounds = debounce(async () => {
|
||||
const position: WindowPosition = {
|
||||
bounds: window.getNormalBounds(),
|
||||
isMaximized: window.isMaximized(),
|
||||
isFullScreen: window.isFullScreen(),
|
||||
}
|
||||
|
||||
if (writingToDisk) {
|
||||
return
|
||||
}
|
||||
|
||||
writingToDisk = true
|
||||
try {
|
||||
await fs.promises.writeFile(Paths.windowPositionJson, JSON.stringify(position), 'utf-8')
|
||||
} catch (error) {
|
||||
console.error('Could not write to window-position.json', error)
|
||||
} finally {
|
||||
writingToDisk = false
|
||||
}
|
||||
}, 500)
|
||||
|
||||
window.on('resize', saveWindowBounds)
|
||||
window.on('move', saveWindowBounds)
|
||||
}
|
||||
16
packages/desktop/app/javascripts/Main/ZoomManager.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { BrowserWindow } from 'electron'
|
||||
import { Store, StoreKeys } from './Store'
|
||||
|
||||
export function initializeZoomManager(window: BrowserWindow, store: Store): void {
|
||||
window.webContents.on('dom-ready', () => {
|
||||
const zoomFactor = store.get(StoreKeys.ZoomFactor)
|
||||
if (zoomFactor) {
|
||||
window.webContents.zoomFactor = zoomFactor
|
||||
}
|
||||
})
|
||||
|
||||
window.on('close', () => {
|
||||
const zoomFactor = window.webContents.zoomFactor
|
||||
store.set(StoreKeys.ZoomFactor, zoomFactor)
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
import { Component } from '../Main/Packages/PackageManagerInterface'
|
||||
import { FileBackupsDevice } from '@web/Application/Device/DesktopSnjsExports'
|
||||
|
||||
export interface CrossProcessBridge extends FileBackupsDevice {
|
||||
get extServerHost(): string
|
||||
|
||||
get useNativeKeychain(): boolean
|
||||
|
||||
get rendererPath(): string
|
||||
|
||||
get isMacOS(): boolean
|
||||
|
||||
get appVersion(): string
|
||||
|
||||
get useSystemMenuBar(): boolean
|
||||
|
||||
closeWindow(): void
|
||||
|
||||
minimizeWindow(): void
|
||||
|
||||
maximizeWindow(): void
|
||||
|
||||
unmaximizeWindow(): void
|
||||
|
||||
isWindowMaximized(): boolean
|
||||
|
||||
getKeychainValue(): Promise<unknown>
|
||||
|
||||
setKeychainValue: (value: unknown) => Promise<void>
|
||||
|
||||
clearKeychainValue(): Promise<boolean>
|
||||
|
||||
localBackupsCount(): Promise<number>
|
||||
|
||||
viewlocalBackups(): void
|
||||
|
||||
deleteLocalBackups(): Promise<void>
|
||||
|
||||
saveDataBackup(data: unknown): void
|
||||
|
||||
displayAppMenu(): void
|
||||
|
||||
syncComponents(components: Component[]): void
|
||||
|
||||
onMajorDataChange(): void
|
||||
|
||||
onSearch(text: string): void
|
||||
|
||||
onInitialDataLoad(): void
|
||||
|
||||
destroyAllData(): void
|
||||
}
|
||||
154
packages/desktop/app/javascripts/Renderer/DesktopDevice.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
import { WebOrDesktopDevice } from '@web/Application/Device/WebOrDesktopDevice'
|
||||
import { Component } from '../Main/Packages/PackageManagerInterface'
|
||||
import {
|
||||
RawKeychainValue,
|
||||
Environment,
|
||||
DesktopDeviceInterface,
|
||||
FileBackupsMapping,
|
||||
} from '@web/Application/Device/DesktopSnjsExports'
|
||||
import { CrossProcessBridge } from './CrossProcessBridge'
|
||||
|
||||
const FallbackLocalStorageKey = 'keychain'
|
||||
|
||||
export class DesktopDevice extends WebOrDesktopDevice implements DesktopDeviceInterface {
|
||||
public environment: Environment.Desktop = Environment.Desktop
|
||||
|
||||
constructor(
|
||||
private remoteBridge: CrossProcessBridge,
|
||||
private useNativeKeychain: boolean,
|
||||
public extensionsServerHost: string,
|
||||
appVersion: string,
|
||||
) {
|
||||
super(appVersion)
|
||||
}
|
||||
|
||||
async getKeychainValue() {
|
||||
if (this.useNativeKeychain) {
|
||||
const keychainValue = await this.remoteBridge.getKeychainValue()
|
||||
return keychainValue
|
||||
} else {
|
||||
const value = window.localStorage.getItem(FallbackLocalStorageKey)
|
||||
if (value) {
|
||||
return JSON.parse(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async setKeychainValue(value: RawKeychainValue) {
|
||||
if (this.useNativeKeychain) {
|
||||
await this.remoteBridge.setKeychainValue(value)
|
||||
} else {
|
||||
window.localStorage.setItem(FallbackLocalStorageKey, JSON.stringify(value))
|
||||
}
|
||||
}
|
||||
|
||||
async clearRawKeychainValue() {
|
||||
if (this.useNativeKeychain) {
|
||||
await this.remoteBridge.clearKeychainValue()
|
||||
} else {
|
||||
window.localStorage.removeItem(FallbackLocalStorageKey)
|
||||
}
|
||||
}
|
||||
|
||||
syncComponents(components: Component[]) {
|
||||
this.remoteBridge.syncComponents(components)
|
||||
}
|
||||
|
||||
onMajorDataChange() {
|
||||
this.remoteBridge.onMajorDataChange()
|
||||
}
|
||||
|
||||
onSearch(text: string) {
|
||||
this.remoteBridge.onSearch(text)
|
||||
}
|
||||
|
||||
onInitialDataLoad() {
|
||||
this.remoteBridge.onInitialDataLoad()
|
||||
}
|
||||
|
||||
async clearAllDataFromDevice(workspaceIdentifiers: string[]): Promise<{ killsApplication: boolean }> {
|
||||
await super.clearAllDataFromDevice(workspaceIdentifiers)
|
||||
|
||||
this.remoteBridge.destroyAllData()
|
||||
|
||||
return { killsApplication: true }
|
||||
}
|
||||
|
||||
async downloadBackup() {
|
||||
const receiver = window.webClient
|
||||
|
||||
receiver.didBeginBackup()
|
||||
|
||||
try {
|
||||
const data = await receiver.requestBackupFile()
|
||||
if (data) {
|
||||
this.remoteBridge.saveDataBackup(data)
|
||||
} else {
|
||||
receiver.didFinishBackup(false)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
receiver.didFinishBackup(false)
|
||||
}
|
||||
}
|
||||
|
||||
async localBackupsCount() {
|
||||
return this.remoteBridge.localBackupsCount()
|
||||
}
|
||||
|
||||
viewlocalBackups() {
|
||||
this.remoteBridge.viewlocalBackups()
|
||||
}
|
||||
|
||||
async deleteLocalBackups() {
|
||||
return this.remoteBridge.deleteLocalBackups()
|
||||
}
|
||||
|
||||
public isFilesBackupsEnabled(): Promise<boolean> {
|
||||
return this.remoteBridge.isFilesBackupsEnabled()
|
||||
}
|
||||
|
||||
public enableFilesBackups(): Promise<void> {
|
||||
return this.remoteBridge.enableFilesBackups()
|
||||
}
|
||||
|
||||
public disableFilesBackups(): Promise<void> {
|
||||
return this.remoteBridge.disableFilesBackups()
|
||||
}
|
||||
|
||||
public changeFilesBackupsLocation(): Promise<string | undefined> {
|
||||
return this.remoteBridge.changeFilesBackupsLocation()
|
||||
}
|
||||
|
||||
public getFilesBackupsLocation(): Promise<string> {
|
||||
return this.remoteBridge.getFilesBackupsLocation()
|
||||
}
|
||||
|
||||
async getFilesBackupsMappingFile(): Promise<FileBackupsMapping> {
|
||||
return this.remoteBridge.getFilesBackupsMappingFile()
|
||||
}
|
||||
|
||||
async openFilesBackupsLocation(): Promise<void> {
|
||||
return this.remoteBridge.openFilesBackupsLocation()
|
||||
}
|
||||
|
||||
async saveFilesBackupsFile(
|
||||
uuid: string,
|
||||
metaFile: string,
|
||||
downloadRequest: {
|
||||
chunkSizes: number[]
|
||||
valetToken: string
|
||||
url: string
|
||||
},
|
||||
): Promise<'success' | 'failed'> {
|
||||
return this.remoteBridge.saveFilesBackupsFile(uuid, metaFile, downloadRequest)
|
||||
}
|
||||
|
||||
async performHardReset(): Promise<void> {
|
||||
console.error('performHardReset is not yet implemented')
|
||||
}
|
||||
|
||||
isDeviceDestroyed(): boolean {
|
||||
return false
|
||||
}
|
||||
}
|
||||
42
packages/desktop/app/javascripts/Renderer/Preload.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { MessageToWebApp } from '../Shared/IpcMessages'
|
||||
const { ipcRenderer } = require('electron')
|
||||
const path = require('path')
|
||||
const rendererPath = path.join('file://', __dirname, '/renderer.js')
|
||||
const RemoteBridge = require('@electron/remote').getGlobal('RemoteBridge')
|
||||
const { contextBridge } = require('electron')
|
||||
|
||||
process.once('loaded', function () {
|
||||
contextBridge.exposeInMainWorld('electronRemoteBridge', RemoteBridge.exposableValue)
|
||||
|
||||
listenForIpcEventsFromMainProcess()
|
||||
})
|
||||
|
||||
function listenForIpcEventsFromMainProcess() {
|
||||
const sendMessageToRenderProcess = (message: string, payload = {}) => {
|
||||
window.postMessage(JSON.stringify({ message, data: payload }), rendererPath)
|
||||
}
|
||||
|
||||
ipcRenderer.on(MessageToWebApp.UpdateAvailable, function (_event, data) {
|
||||
sendMessageToRenderProcess(MessageToWebApp.UpdateAvailable, data)
|
||||
})
|
||||
|
||||
ipcRenderer.on(MessageToWebApp.PerformAutomatedBackup, function (_event, data) {
|
||||
sendMessageToRenderProcess(MessageToWebApp.PerformAutomatedBackup, data)
|
||||
})
|
||||
|
||||
ipcRenderer.on(MessageToWebApp.FinishedSavingBackup, function (_event, data) {
|
||||
sendMessageToRenderProcess(MessageToWebApp.FinishedSavingBackup, data)
|
||||
})
|
||||
|
||||
ipcRenderer.on(MessageToWebApp.WindowBlurred, function (_event, data) {
|
||||
sendMessageToRenderProcess(MessageToWebApp.WindowBlurred, data)
|
||||
})
|
||||
|
||||
ipcRenderer.on(MessageToWebApp.WindowFocused, function (_event, data) {
|
||||
sendMessageToRenderProcess(MessageToWebApp.WindowFocused, data)
|
||||
})
|
||||
|
||||
ipcRenderer.on(MessageToWebApp.InstallComponentComplete, function (_event, data) {
|
||||
sendMessageToRenderProcess(MessageToWebApp.InstallComponentComplete, data)
|
||||
})
|
||||
}
|
||||
164
packages/desktop/app/javascripts/Renderer/Renderer.ts
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
import { DesktopDevice } from './DesktopDevice'
|
||||
import { MessageToWebApp } from '../Shared/IpcMessages'
|
||||
import { DesktopClientRequiresWebMethods } from '@web/Application/Device/DesktopSnjsExports'
|
||||
import { StartApplication } from '@web/Application/Device/StartApplication'
|
||||
import { CrossProcessBridge } from './CrossProcessBridge'
|
||||
|
||||
declare const DEFAULT_SYNC_SERVER: string
|
||||
declare const WEBSOCKET_URL: string
|
||||
declare const ENABLE_UNFINISHED_FEATURES: string
|
||||
declare const PURCHASE_URL: string
|
||||
declare const PLANS_URL: string
|
||||
declare const DASHBOARD_URL: string
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
device: DesktopDevice
|
||||
electronRemoteBridge: CrossProcessBridge
|
||||
dashboardUrl: string
|
||||
webClient: DesktopClientRequiresWebMethods
|
||||
electronAppVersion: string
|
||||
enableUnfinishedFeatures: boolean
|
||||
plansUrl: string
|
||||
purchaseUrl: string
|
||||
startApplication: StartApplication
|
||||
zip: any
|
||||
}
|
||||
}
|
||||
|
||||
const loadWindowVarsRequiredByWebApp = () => {
|
||||
window.dashboardUrl = DASHBOARD_URL
|
||||
window.enableUnfinishedFeatures = ENABLE_UNFINISHED_FEATURES === 'true'
|
||||
window.plansUrl = PLANS_URL
|
||||
window.purchaseUrl = PURCHASE_URL
|
||||
}
|
||||
|
||||
const loadAndStartApplication = async () => {
|
||||
const remoteBridge: CrossProcessBridge = window.electronRemoteBridge
|
||||
|
||||
await configureWindow(remoteBridge)
|
||||
|
||||
window.device = await createDesktopDevice(remoteBridge)
|
||||
|
||||
window.startApplication(DEFAULT_SYNC_SERVER, window.device, window.enableUnfinishedFeatures, WEBSOCKET_URL)
|
||||
|
||||
listenForMessagesSentFromMainToPreloadToUs(window.device)
|
||||
}
|
||||
|
||||
window.onload = () => {
|
||||
loadWindowVarsRequiredByWebApp()
|
||||
|
||||
void loadAndStartApplication()
|
||||
}
|
||||
|
||||
/** @returns whether the keychain structure is up to date or not */
|
||||
async function migrateKeychain(remoteBridge: CrossProcessBridge): Promise<boolean> {
|
||||
if (!remoteBridge.useNativeKeychain) {
|
||||
/** User chose not to use keychain, do not migrate. */
|
||||
return false
|
||||
}
|
||||
|
||||
const key = 'keychain'
|
||||
const localStorageValue = window.localStorage.getItem(key)
|
||||
|
||||
if (localStorageValue) {
|
||||
/** Migrate to native keychain */
|
||||
console.warn('Migrating keychain from localStorage to native keychain.')
|
||||
window.localStorage.removeItem(key)
|
||||
await remoteBridge.setKeychainValue(JSON.parse(localStorageValue))
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
async function createDesktopDevice(remoteBridge: CrossProcessBridge): Promise<DesktopDevice> {
|
||||
const useNativeKeychain = await migrateKeychain(remoteBridge)
|
||||
const extensionsServerHost = remoteBridge.extServerHost
|
||||
const appVersion = remoteBridge.appVersion
|
||||
|
||||
return new DesktopDevice(remoteBridge, useNativeKeychain, extensionsServerHost, appVersion)
|
||||
}
|
||||
|
||||
async function configureWindow(remoteBridge: CrossProcessBridge) {
|
||||
const isMacOS = remoteBridge.isMacOS
|
||||
const useSystemMenuBar = remoteBridge.useSystemMenuBar
|
||||
const appVersion = remoteBridge.appVersion
|
||||
|
||||
window.electronAppVersion = appVersion
|
||||
|
||||
/*
|
||||
Title bar events
|
||||
*/
|
||||
document.getElementById('menu-btn')!.addEventListener('click', () => {
|
||||
remoteBridge.displayAppMenu()
|
||||
})
|
||||
|
||||
document.getElementById('min-btn')!.addEventListener('click', () => {
|
||||
remoteBridge.minimizeWindow()
|
||||
})
|
||||
|
||||
document.getElementById('max-btn')!.addEventListener('click', async () => {
|
||||
if (remoteBridge.isWindowMaximized()) {
|
||||
remoteBridge.unmaximizeWindow()
|
||||
} else {
|
||||
remoteBridge.maximizeWindow()
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('close-btn')!.addEventListener('click', () => {
|
||||
remoteBridge.closeWindow()
|
||||
})
|
||||
|
||||
// For Mac inset window
|
||||
const sheet = document.styleSheets[0]
|
||||
if (isMacOS) {
|
||||
sheet.insertRule('#navigation { padding-top: 25px !important; }', sheet.cssRules.length)
|
||||
}
|
||||
|
||||
if (isMacOS || useSystemMenuBar) {
|
||||
// !important is important here because #desktop-title-bar has display: flex.
|
||||
sheet.insertRule('#desktop-title-bar { display: none !important; }', sheet.cssRules.length)
|
||||
} else {
|
||||
/* Use custom title bar. Take the sn-titlebar-height off of
|
||||
the app content height so its not overflowing */
|
||||
sheet.insertRule('body { padding-top: var(--sn-desktop-titlebar-height); }', sheet.cssRules.length)
|
||||
sheet.insertRule(
|
||||
`.main-ui-view { height: calc(100vh - var(--sn-desktop-titlebar-height)) !important;
|
||||
min-height: calc(100vh - var(--sn-desktop-titlebar-height)) !important; }`,
|
||||
sheet.cssRules.length,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function listenForMessagesSentFromMainToPreloadToUs(device: DesktopDevice) {
|
||||
window.addEventListener('message', async (event) => {
|
||||
// We don't have access to the full file path.
|
||||
if (event.origin !== 'file://') {
|
||||
return
|
||||
}
|
||||
let payload
|
||||
try {
|
||||
payload = JSON.parse(event.data)
|
||||
} catch (e) {
|
||||
// message doesn't belong to us
|
||||
return
|
||||
}
|
||||
const receiver = window.webClient
|
||||
const message = payload.message
|
||||
const data = payload.data
|
||||
|
||||
if (message === MessageToWebApp.WindowBlurred) {
|
||||
receiver.windowLostFocus()
|
||||
} else if (message === MessageToWebApp.WindowFocused) {
|
||||
receiver.windowGainedFocus()
|
||||
} else if (message === MessageToWebApp.InstallComponentComplete) {
|
||||
receiver.onComponentInstallationComplete(data.component, data.error)
|
||||
} else if (message === MessageToWebApp.UpdateAvailable) {
|
||||
receiver.updateAvailable()
|
||||
} else if (message === MessageToWebApp.PerformAutomatedBackup) {
|
||||
void device.downloadBackup()
|
||||
} else if (message === MessageToWebApp.FinishedSavingBackup) {
|
||||
receiver.didFinishBackup(data.success)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
/* eslint-disable no-undef */
|
||||
const { ipcRenderer } = require('electron')
|
||||
import { MessageToMainProcess } from '../Shared/IpcMessages'
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
document.getElementById('use-storage-button').addEventListener('click', () => {
|
||||
ipcRenderer.send(MessageToMainProcess.UseLocalstorageForKeychain)
|
||||
})
|
||||
|
||||
document.getElementById('quit-button').addEventListener('click', () => {
|
||||
ipcRenderer.send(MessageToMainProcess.Quit)
|
||||
})
|
||||
|
||||
const learnMoreButton = document.getElementById('learn-more')
|
||||
learnMoreButton.addEventListener('click', (event) => {
|
||||
ipcRenderer.send(MessageToMainProcess.LearnMoreAboutKeychainAccess)
|
||||
event.preventDefault()
|
||||
const moreInfo = document.getElementById('more-info')
|
||||
moreInfo.style.display = 'block'
|
||||
learnMoreButton.style.display = 'none'
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
export const CommandLineArgs = {
|
||||
Testing: '--testing-INSECURE',
|
||||
UserDataPath: '--experimental-user-data-path',
|
||||
}
|
||||
14
packages/desktop/app/javascripts/Shared/IpcMessages.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
export enum MessageToWebApp {
|
||||
UpdateAvailable = 'update-available',
|
||||
PerformAutomatedBackup = 'download-backup',
|
||||
FinishedSavingBackup = 'finished-saving-backup',
|
||||
WindowBlurred = 'window-blurred',
|
||||
WindowFocused = 'window-focused',
|
||||
InstallComponentComplete = 'install-component-complete',
|
||||
}
|
||||
|
||||
export enum MessageToMainProcess {
|
||||
UseLocalstorageForKeychain = 'UseLocalstorageForKeychain',
|
||||
LearnMoreAboutKeychainAccess = 'LearnMoreAboutKeychainAccess',
|
||||
Quit = 'Quit',
|
||||
}
|
||||
11
packages/desktop/app/package.json
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"name": "standard-notes",
|
||||
"productName": "Standard Notes",
|
||||
"description": "An end-to-end encrypted notes app for digitalists and professionals.",
|
||||
"author": "Standard Notes <help@standardnotes.com>",
|
||||
"version": "3.20.2",
|
||||
"main": "./dist/index.js",
|
||||
"dependencies": {
|
||||
"keytar": "^7.9.0"
|
||||
}
|
||||
}
|
||||
83
packages/desktop/app/stylesheets/renderer.css
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
:root {
|
||||
--sn-desktop-titlebar-height: 35px;
|
||||
--sn-desktop-titlebar-icon-font-size: 16px;
|
||||
}
|
||||
|
||||
/* To offset frameless window nav buttons on Mac */
|
||||
.mac-desktop #editor-column,
|
||||
.mac-desktop #notes-column {
|
||||
transition: 0.15s padding ease;
|
||||
}
|
||||
|
||||
.mac-desktop #app.collapsed-notes.collapsed-navigation #editor-column {
|
||||
padding-top: 18px;
|
||||
}
|
||||
|
||||
.mac-desktop #app.collapsed-navigation #notes-column {
|
||||
padding-top: 18px;
|
||||
}
|
||||
|
||||
panel-resizer {
|
||||
-webkit-app-region: no-drag;
|
||||
}
|
||||
|
||||
#desktop-title-bar {
|
||||
-webkit-app-region: drag;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
height: var(--sn-desktop-titlebar-height);
|
||||
line-height: var(--sn-desktop-titlebar-height);
|
||||
vertical-align: middle;
|
||||
background: var(--sn-stylekit-contrast-background-color) !important;
|
||||
border-bottom: 1px solid var(--sn-stylekit-contrast-border-color);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
z-index: 99999;
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
#desktop-title-bar button {
|
||||
-webkit-app-region: no-drag;
|
||||
margin: 0;
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 0 10px;
|
||||
color: var(--sn-stylekit-contrast-foreground-color);
|
||||
vertical-align: middle;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
#desktop-title-bar button svg {
|
||||
max-width: var(--sn-desktop-titlebar-icon-font-size);
|
||||
}
|
||||
|
||||
#desktop-title-bar button:hover svg,
|
||||
#desktop-title-bar button:focus svg {
|
||||
color: var(--sn-stylekit-info-color);
|
||||
}
|
||||
#desktop-title-bar button:focus {
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
#desktop-title-bar .title-bar-left-buttons,
|
||||
#desktop-title-bar .title-bar-right-buttons {
|
||||
font-size: 0;
|
||||
}
|
||||
|
||||
/* Required for BrowserWindow titleBarStyle: 'hiddenInset' */
|
||||
.mac-desktop #navigation,
|
||||
.mac-desktop #navigation .section-title-bar,
|
||||
.mac-desktop #notes-title-bar,
|
||||
.mac-desktop #editor-title-bar,
|
||||
.mac-desktop #lock-screen {
|
||||
-webkit-app-region: drag;
|
||||
}
|
||||
|
||||
input,
|
||||
#navigation #navigation-content,
|
||||
.component-view-container,
|
||||
.panel-resizer {
|
||||
-webkit-app-region: no-drag;
|
||||
}
|
||||
448
packages/desktop/app/yarn.lock
Normal file
|
|
@ -0,0 +1,448 @@
|
|||
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||
# yarn lockfile v1
|
||||
|
||||
|
||||
ansi-regex@^2.0.0:
|
||||
version "2.1.1"
|
||||
resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df"
|
||||
integrity sha1-w7M6te42DYbg5ijwRorn7yfWVN8=
|
||||
|
||||
ansi-regex@^5.0.1:
|
||||
version "5.0.1"
|
||||
resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304"
|
||||
integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==
|
||||
|
||||
aproba@^1.0.3:
|
||||
version "1.2.0"
|
||||
resolved "https://registry.yarnpkg.com/aproba/-/aproba-1.2.0.tgz#6802e6264efd18c790a1b0d517f0f2627bf2c94a"
|
||||
integrity sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==
|
||||
|
||||
are-we-there-yet@~1.1.2:
|
||||
version "1.1.7"
|
||||
resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-1.1.7.tgz#b15474a932adab4ff8a50d9adfa7e4e926f21146"
|
||||
integrity sha512-nxwy40TuMiUGqMyRHgCSWZ9FM4VAoRP4xUYSTv5ImRog+h9yISPbVH7H8fASCIzYn9wlEv4zvFL7uKDMCFQm3g==
|
||||
dependencies:
|
||||
delegates "^1.0.0"
|
||||
readable-stream "^2.0.6"
|
||||
|
||||
base64-js@^1.3.1:
|
||||
version "1.5.1"
|
||||
resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a"
|
||||
integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==
|
||||
|
||||
bl@^4.0.3:
|
||||
version "4.1.0"
|
||||
resolved "https://registry.yarnpkg.com/bl/-/bl-4.1.0.tgz#451535264182bec2fbbc83a62ab98cf11d9f7b3a"
|
||||
integrity sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==
|
||||
dependencies:
|
||||
buffer "^5.5.0"
|
||||
inherits "^2.0.4"
|
||||
readable-stream "^3.4.0"
|
||||
|
||||
buffer@^5.5.0:
|
||||
version "5.7.1"
|
||||
resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.7.1.tgz#ba62e7c13133053582197160851a8f648e99eed0"
|
||||
integrity sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==
|
||||
dependencies:
|
||||
base64-js "^1.3.1"
|
||||
ieee754 "^1.1.13"
|
||||
|
||||
chownr@^1.1.1:
|
||||
version "1.1.4"
|
||||
resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b"
|
||||
integrity sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==
|
||||
|
||||
code-point-at@^1.0.0:
|
||||
version "1.1.0"
|
||||
resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77"
|
||||
integrity sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=
|
||||
|
||||
console-control-strings@^1.0.0, console-control-strings@~1.1.0:
|
||||
version "1.1.0"
|
||||
resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e"
|
||||
integrity sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=
|
||||
|
||||
core-util-is@~1.0.0:
|
||||
version "1.0.3"
|
||||
resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.3.tgz#a6042d3634c2b27e9328f837b965fac83808db85"
|
||||
integrity sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==
|
||||
|
||||
decompress-response@^6.0.0:
|
||||
version "6.0.0"
|
||||
resolved "https://registry.yarnpkg.com/decompress-response/-/decompress-response-6.0.0.tgz#ca387612ddb7e104bd16d85aab00d5ecf09c66fc"
|
||||
integrity sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==
|
||||
dependencies:
|
||||
mimic-response "^3.1.0"
|
||||
|
||||
deep-extend@^0.6.0:
|
||||
version "0.6.0"
|
||||
resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac"
|
||||
integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==
|
||||
|
||||
delegates@^1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a"
|
||||
integrity sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=
|
||||
|
||||
detect-libc@^2.0.0:
|
||||
version "2.0.1"
|
||||
resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.0.1.tgz#e1897aa88fa6ad197862937fbc0441ef352ee0cd"
|
||||
integrity sha512-463v3ZeIrcWtdgIg6vI6XUncguvr2TnGl4SzDXinkt9mSLpBJKXT3mW6xT3VQdDN11+WVs29pgvivTc4Lp8v+w==
|
||||
|
||||
emoji-regex@^8.0.0:
|
||||
version "8.0.0"
|
||||
resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37"
|
||||
integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==
|
||||
|
||||
end-of-stream@^1.1.0, end-of-stream@^1.4.1:
|
||||
version "1.4.4"
|
||||
resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0"
|
||||
integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==
|
||||
dependencies:
|
||||
once "^1.4.0"
|
||||
|
||||
expand-template@^2.0.3:
|
||||
version "2.0.3"
|
||||
resolved "https://registry.yarnpkg.com/expand-template/-/expand-template-2.0.3.tgz#6e14b3fcee0f3a6340ecb57d2e8918692052a47c"
|
||||
integrity sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==
|
||||
|
||||
fs-constants@^1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.yarnpkg.com/fs-constants/-/fs-constants-1.0.0.tgz#6be0de9be998ce16af8afc24497b9ee9b7ccd9ad"
|
||||
integrity sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==
|
||||
|
||||
gauge@~2.7.3:
|
||||
version "2.7.4"
|
||||
resolved "https://registry.yarnpkg.com/gauge/-/gauge-2.7.4.tgz#2c03405c7538c39d7eb37b317022e325fb018bf7"
|
||||
integrity sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=
|
||||
dependencies:
|
||||
aproba "^1.0.3"
|
||||
console-control-strings "^1.0.0"
|
||||
has-unicode "^2.0.0"
|
||||
object-assign "^4.1.0"
|
||||
signal-exit "^3.0.0"
|
||||
string-width "^1.0.1"
|
||||
strip-ansi "^3.0.1"
|
||||
wide-align "^1.1.0"
|
||||
|
||||
github-from-package@0.0.0:
|
||||
version "0.0.0"
|
||||
resolved "https://registry.yarnpkg.com/github-from-package/-/github-from-package-0.0.0.tgz#97fb5d96bfde8973313f20e8288ef9a167fa64ce"
|
||||
integrity sha1-l/tdlr/eiXMxPyDoKI75oWf6ZM4=
|
||||
|
||||
has-unicode@^2.0.0:
|
||||
version "2.0.1"
|
||||
resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9"
|
||||
integrity sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=
|
||||
|
||||
ieee754@^1.1.13:
|
||||
version "1.2.1"
|
||||
resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352"
|
||||
integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==
|
||||
|
||||
inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.3:
|
||||
version "2.0.4"
|
||||
resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c"
|
||||
integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==
|
||||
|
||||
ini@~1.3.0:
|
||||
version "1.3.8"
|
||||
resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.8.tgz#a29da425b48806f34767a4efce397269af28432c"
|
||||
integrity sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==
|
||||
|
||||
is-fullwidth-code-point@^1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb"
|
||||
integrity sha1-754xOG8DGn8NZDr4L95QxFfvAMs=
|
||||
dependencies:
|
||||
number-is-nan "^1.0.0"
|
||||
|
||||
is-fullwidth-code-point@^3.0.0:
|
||||
version "3.0.0"
|
||||
resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d"
|
||||
integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==
|
||||
|
||||
isarray@~1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11"
|
||||
integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=
|
||||
|
||||
keytar@^7.9.0:
|
||||
version "7.9.0"
|
||||
resolved "https://registry.yarnpkg.com/keytar/-/keytar-7.9.0.tgz#4c6225708f51b50cbf77c5aae81721964c2918cb"
|
||||
integrity sha512-VPD8mtVtm5JNtA2AErl6Chp06JBfy7diFQ7TQQhdpWOl6MrCRB+eRbvAZUsbGQS9kiMq0coJsy0W0vHpDCkWsQ==
|
||||
dependencies:
|
||||
node-addon-api "^4.3.0"
|
||||
prebuild-install "^7.0.1"
|
||||
|
||||
lru-cache@^6.0.0:
|
||||
version "6.0.0"
|
||||
resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94"
|
||||
integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==
|
||||
dependencies:
|
||||
yallist "^4.0.0"
|
||||
|
||||
mimic-response@^3.1.0:
|
||||
version "3.1.0"
|
||||
resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9"
|
||||
integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==
|
||||
|
||||
minimist@^1.2.0, minimist@^1.2.3:
|
||||
version "1.2.5"
|
||||
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602"
|
||||
integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==
|
||||
|
||||
mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3:
|
||||
version "0.5.3"
|
||||
resolved "https://registry.yarnpkg.com/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113"
|
||||
integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==
|
||||
|
||||
napi-build-utils@^1.0.1:
|
||||
version "1.0.2"
|
||||
resolved "https://registry.yarnpkg.com/napi-build-utils/-/napi-build-utils-1.0.2.tgz#b1fddc0b2c46e380a0b7a76f984dd47c41a13806"
|
||||
integrity sha512-ONmRUqK7zj7DWX0D9ADe03wbwOBZxNAfF20PlGfCWQcD3+/MakShIHrMqx9YwPTfxDdF1zLeL+RGZiR9kGMLdg==
|
||||
|
||||
node-abi@^3.3.0:
|
||||
version "3.8.0"
|
||||
resolved "https://registry.yarnpkg.com/node-abi/-/node-abi-3.8.0.tgz#679957dc8e7aa47b0a02589dbfde4f77b29ccb32"
|
||||
integrity sha512-tzua9qWWi7iW4I42vUPKM+SfaF0vQSLAm4yO5J83mSwB7GeoWrDKC/K+8YCnYNwqP5duwazbw2X9l4m8SC2cUw==
|
||||
dependencies:
|
||||
semver "^7.3.5"
|
||||
|
||||
node-addon-api@^4.3.0:
|
||||
version "4.3.0"
|
||||
resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-4.3.0.tgz#52a1a0b475193e0928e98e0426a0d1254782b77f"
|
||||
integrity sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==
|
||||
|
||||
npmlog@^4.0.1:
|
||||
version "4.1.2"
|
||||
resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-4.1.2.tgz#08a7f2a8bf734604779a9efa4ad5cc717abb954b"
|
||||
integrity sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==
|
||||
dependencies:
|
||||
are-we-there-yet "~1.1.2"
|
||||
console-control-strings "~1.1.0"
|
||||
gauge "~2.7.3"
|
||||
set-blocking "~2.0.0"
|
||||
|
||||
number-is-nan@^1.0.0:
|
||||
version "1.0.1"
|
||||
resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d"
|
||||
integrity sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=
|
||||
|
||||
object-assign@^4.1.0:
|
||||
version "4.1.1"
|
||||
resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863"
|
||||
integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=
|
||||
|
||||
once@^1.3.1, once@^1.4.0:
|
||||
version "1.4.0"
|
||||
resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"
|
||||
integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E=
|
||||
dependencies:
|
||||
wrappy "1"
|
||||
|
||||
prebuild-install@^7.0.1:
|
||||
version "7.0.1"
|
||||
resolved "https://registry.yarnpkg.com/prebuild-install/-/prebuild-install-7.0.1.tgz#c10075727c318efe72412f333e0ef625beaf3870"
|
||||
integrity sha512-QBSab31WqkyxpnMWQxubYAHR5S9B2+r81ucocew34Fkl98FhvKIF50jIJnNOBmAZfyNV7vE5T6gd3hTVWgY6tg==
|
||||
dependencies:
|
||||
detect-libc "^2.0.0"
|
||||
expand-template "^2.0.3"
|
||||
github-from-package "0.0.0"
|
||||
minimist "^1.2.3"
|
||||
mkdirp-classic "^0.5.3"
|
||||
napi-build-utils "^1.0.1"
|
||||
node-abi "^3.3.0"
|
||||
npmlog "^4.0.1"
|
||||
pump "^3.0.0"
|
||||
rc "^1.2.7"
|
||||
simple-get "^4.0.0"
|
||||
tar-fs "^2.0.0"
|
||||
tunnel-agent "^0.6.0"
|
||||
|
||||
process-nextick-args@~2.0.0:
|
||||
version "2.0.1"
|
||||
resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2"
|
||||
integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==
|
||||
|
||||
pump@^3.0.0:
|
||||
version "3.0.0"
|
||||
resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.0.tgz#b4a2116815bde2f4e1ea602354e8c75565107a64"
|
||||
integrity sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==
|
||||
dependencies:
|
||||
end-of-stream "^1.1.0"
|
||||
once "^1.3.1"
|
||||
|
||||
rc@^1.2.7:
|
||||
version "1.2.8"
|
||||
resolved "https://registry.yarnpkg.com/rc/-/rc-1.2.8.tgz#cd924bf5200a075b83c188cd6b9e211b7fc0d3ed"
|
||||
integrity sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==
|
||||
dependencies:
|
||||
deep-extend "^0.6.0"
|
||||
ini "~1.3.0"
|
||||
minimist "^1.2.0"
|
||||
strip-json-comments "~2.0.1"
|
||||
|
||||
readable-stream@^2.0.6:
|
||||
version "2.3.7"
|
||||
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.7.tgz#1eca1cf711aef814c04f62252a36a62f6cb23b57"
|
||||
integrity sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==
|
||||
dependencies:
|
||||
core-util-is "~1.0.0"
|
||||
inherits "~2.0.3"
|
||||
isarray "~1.0.0"
|
||||
process-nextick-args "~2.0.0"
|
||||
safe-buffer "~5.1.1"
|
||||
string_decoder "~1.1.1"
|
||||
util-deprecate "~1.0.1"
|
||||
|
||||
readable-stream@^3.1.1, readable-stream@^3.4.0:
|
||||
version "3.6.0"
|
||||
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz#337bbda3adc0706bd3e024426a286d4b4b2c9198"
|
||||
integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==
|
||||
dependencies:
|
||||
inherits "^2.0.3"
|
||||
string_decoder "^1.1.1"
|
||||
util-deprecate "^1.0.1"
|
||||
|
||||
safe-buffer@^5.0.1, safe-buffer@~5.2.0:
|
||||
version "5.2.1"
|
||||
resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6"
|
||||
integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==
|
||||
|
||||
safe-buffer@~5.1.0, safe-buffer@~5.1.1:
|
||||
version "5.1.2"
|
||||
resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d"
|
||||
integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==
|
||||
|
||||
semver@^7.3.5:
|
||||
version "7.3.5"
|
||||
resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.5.tgz#0b621c879348d8998e4b0e4be94b3f12e6018ef7"
|
||||
integrity sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==
|
||||
dependencies:
|
||||
lru-cache "^6.0.0"
|
||||
|
||||
set-blocking@~2.0.0:
|
||||
version "2.0.0"
|
||||
resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7"
|
||||
integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc=
|
||||
|
||||
signal-exit@^3.0.0:
|
||||
version "3.0.6"
|
||||
resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.6.tgz#24e630c4b0f03fea446a2bd299e62b4a6ca8d0af"
|
||||
integrity sha512-sDl4qMFpijcGw22U5w63KmD3cZJfBuFlVNbVMKje2keoKML7X2UzWbc4XrmEbDwg0NXJc3yv4/ox7b+JWb57kQ==
|
||||
|
||||
simple-concat@^1.0.0:
|
||||
version "1.0.1"
|
||||
resolved "https://registry.yarnpkg.com/simple-concat/-/simple-concat-1.0.1.tgz#f46976082ba35c2263f1c8ab5edfe26c41c9552f"
|
||||
integrity sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==
|
||||
|
||||
simple-get@^4.0.0:
|
||||
version "4.0.1"
|
||||
resolved "https://registry.yarnpkg.com/simple-get/-/simple-get-4.0.1.tgz#4a39db549287c979d352112fa03fd99fd6bc3543"
|
||||
integrity sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==
|
||||
dependencies:
|
||||
decompress-response "^6.0.0"
|
||||
once "^1.3.1"
|
||||
simple-concat "^1.0.0"
|
||||
|
||||
string-width@^1.0.1:
|
||||
version "1.0.2"
|
||||
resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3"
|
||||
integrity sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=
|
||||
dependencies:
|
||||
code-point-at "^1.0.0"
|
||||
is-fullwidth-code-point "^1.0.0"
|
||||
strip-ansi "^3.0.0"
|
||||
|
||||
"string-width@^1.0.2 || 2 || 3 || 4":
|
||||
version "4.2.3"
|
||||
resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
|
||||
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
|
||||
dependencies:
|
||||
emoji-regex "^8.0.0"
|
||||
is-fullwidth-code-point "^3.0.0"
|
||||
strip-ansi "^6.0.1"
|
||||
|
||||
string_decoder@^1.1.1:
|
||||
version "1.3.0"
|
||||
resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e"
|
||||
integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==
|
||||
dependencies:
|
||||
safe-buffer "~5.2.0"
|
||||
|
||||
string_decoder@~1.1.1:
|
||||
version "1.1.1"
|
||||
resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8"
|
||||
integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==
|
||||
dependencies:
|
||||
safe-buffer "~5.1.0"
|
||||
|
||||
strip-ansi@^3.0.0, strip-ansi@^3.0.1:
|
||||
version "3.0.1"
|
||||
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf"
|
||||
integrity sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=
|
||||
dependencies:
|
||||
ansi-regex "^2.0.0"
|
||||
|
||||
strip-ansi@^6.0.1:
|
||||
version "6.0.1"
|
||||
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
|
||||
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
|
||||
dependencies:
|
||||
ansi-regex "^5.0.1"
|
||||
|
||||
strip-json-comments@~2.0.1:
|
||||
version "2.0.1"
|
||||
resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a"
|
||||
integrity sha1-PFMZQukIwml8DsNEhYwobHygpgo=
|
||||
|
||||
tar-fs@^2.0.0:
|
||||
version "2.1.1"
|
||||
resolved "https://registry.yarnpkg.com/tar-fs/-/tar-fs-2.1.1.tgz#489a15ab85f1f0befabb370b7de4f9eb5cbe8784"
|
||||
integrity sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==
|
||||
dependencies:
|
||||
chownr "^1.1.1"
|
||||
mkdirp-classic "^0.5.2"
|
||||
pump "^3.0.0"
|
||||
tar-stream "^2.1.4"
|
||||
|
||||
tar-stream@^2.1.4:
|
||||
version "2.2.0"
|
||||
resolved "https://registry.yarnpkg.com/tar-stream/-/tar-stream-2.2.0.tgz#acad84c284136b060dc3faa64474aa9aebd77287"
|
||||
integrity sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==
|
||||
dependencies:
|
||||
bl "^4.0.3"
|
||||
end-of-stream "^1.4.1"
|
||||
fs-constants "^1.0.0"
|
||||
inherits "^2.0.3"
|
||||
readable-stream "^3.1.1"
|
||||
|
||||
tunnel-agent@^0.6.0:
|
||||
version "0.6.0"
|
||||
resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd"
|
||||
integrity sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=
|
||||
dependencies:
|
||||
safe-buffer "^5.0.1"
|
||||
|
||||
util-deprecate@^1.0.1, util-deprecate@~1.0.1:
|
||||
version "1.0.2"
|
||||
resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
|
||||
integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=
|
||||
|
||||
wide-align@^1.1.0:
|
||||
version "1.1.5"
|
||||
resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.5.tgz#df1d4c206854369ecf3c9a4898f1b23fbd9d15d3"
|
||||
integrity sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==
|
||||
dependencies:
|
||||
string-width "^1.0.2 || 2 || 3 || 4"
|
||||
|
||||
wrappy@1:
|
||||
version "1.0.2"
|
||||
resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
|
||||
integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=
|
||||
|
||||
yallist@^4.0.0:
|
||||
version "4.0.0"
|
||||
resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72"
|
||||
integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==
|
||||
30
packages/desktop/babel.config.js
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
module.exports = function (api) {
|
||||
api.cache(true)
|
||||
|
||||
const presets = [
|
||||
[
|
||||
'@babel/preset-env',
|
||||
{
|
||||
targets: {
|
||||
electron: 9,
|
||||
},
|
||||
},
|
||||
],
|
||||
]
|
||||
|
||||
const ignore = [
|
||||
'./app/compiled',
|
||||
'./app/assets',
|
||||
'./app/stylesheets',
|
||||
'./app/dist',
|
||||
'./app/node_modules',
|
||||
'./node_modules',
|
||||
'./package.json',
|
||||
'./npm-debug.log',
|
||||
]
|
||||
|
||||
return {
|
||||
ignore,
|
||||
presets,
|
||||
}
|
||||
}
|
||||
14
packages/desktop/build/entitlements.mac.inherit.plist
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-dyld-environment-variables</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
BIN
packages/desktop/build/icon.icns
Executable file
BIN
packages/desktop/build/icon.ico
Executable file
|
After Width: | Height: | Size: 361 KiB |
BIN
packages/desktop/build/icon.iconset/icon_128x128.png
Normal file
|
After Width: | Height: | Size: 2.9 KiB |
BIN
packages/desktop/build/icon.iconset/icon_128x128@2x.png
Normal file
|
After Width: | Height: | Size: 7.4 KiB |
BIN
packages/desktop/build/icon.iconset/icon_16x16.png
Normal file
|
After Width: | Height: | Size: 503 B |
BIN
packages/desktop/build/icon.iconset/icon_16x16@2x.png
Normal file
|
After Width: | Height: | Size: 853 B |
BIN
packages/desktop/build/icon.iconset/icon_256x256.png
Normal file
|
After Width: | Height: | Size: 6.7 KiB |
BIN
packages/desktop/build/icon.iconset/icon_256x256@2x.png
Normal file
|
After Width: | Height: | Size: 17 KiB |
BIN
packages/desktop/build/icon.iconset/icon_32x32.png
Normal file
|
After Width: | Height: | Size: 853 B |
BIN
packages/desktop/build/icon.iconset/icon_32x32@2x.png
Normal file
|
After Width: | Height: | Size: 1.1 KiB |
BIN
packages/desktop/build/icon.iconset/icon_512x512.png
Normal file
|
After Width: | Height: | Size: 17 KiB |
BIN
packages/desktop/build/icon.iconset/icon_512x512@2x.png
Normal file
|
After Width: | Height: | Size: 47 KiB |
BIN
packages/desktop/build/icon/Icon-512x512.png
Normal file
|
After Width: | Height: | Size: 15 KiB |
7
packages/desktop/build/installer.nsh
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
!macro customInit
|
||||
; Delete any previous uninstall registry key to ensure the installer doesn't hang at 30%
|
||||
; https://github.com/electron-userland/electron-builder/issues/4057#issuecomment-557570476
|
||||
; https://github.com/electron-userland/electron-builder/issues/4092
|
||||
DeleteRegKey HKCU "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{${UNINSTALL_APP_KEY}}"
|
||||
DeleteRegKey HKCU "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\${UNINSTALL_APP_KEY}"
|
||||
!macroend
|
||||
3
packages/desktop/commitlint.config.js
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
module.exports = {
|
||||
extends: ['@commitlint/config-conventional'],
|
||||
};
|
||||
143
packages/desktop/desktop.webpack.common.js
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
const env = process.env.NODE_ENV ?? 'production'
|
||||
require('dotenv').config({
|
||||
path: `.env.${env}`,
|
||||
})
|
||||
|
||||
const path = require('path')
|
||||
const CopyPlugin = require('copy-webpack-plugin')
|
||||
const webpack = require('webpack')
|
||||
const { DefinePlugin } = require('webpack')
|
||||
const TerserPlugin = require('terser-webpack-plugin')
|
||||
|
||||
module.exports = function ({ onlyTranspileTypescript = false, experimentalFeatures = false, snap = false } = {}) {
|
||||
const moduleConfig = {
|
||||
rules: [
|
||||
{
|
||||
test: /\.ts$/,
|
||||
use: [
|
||||
'babel-loader',
|
||||
{
|
||||
loader: 'ts-loader',
|
||||
options: {
|
||||
transpileOnly: onlyTranspileTypescript,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
test: /\.js$/,
|
||||
exclude: /node_modules/,
|
||||
loader: 'babel-loader',
|
||||
},
|
||||
{
|
||||
sideEffects: true,
|
||||
test: /\.(png|html)$/i,
|
||||
loader: 'file-loader',
|
||||
options: {
|
||||
name: '[name].[ext]',
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const resolve = {
|
||||
extensions: ['.ts', '.js'],
|
||||
alias: {
|
||||
'@web': path.resolve(__dirname, '../web/src/javascripts'),
|
||||
},
|
||||
}
|
||||
|
||||
const EXPERIMENTAL_FEATURES = JSON.stringify(experimentalFeatures)
|
||||
const IS_SNAP = JSON.stringify(snap ? true : false)
|
||||
|
||||
const electronMainConfig = {
|
||||
entry: {
|
||||
index: './app/index.ts',
|
||||
},
|
||||
output: {
|
||||
path: path.resolve(__dirname, 'app', 'dist'),
|
||||
filename: 'index.js',
|
||||
},
|
||||
devtool: 'inline-cheap-source-map',
|
||||
target: 'electron-main',
|
||||
node: {
|
||||
__dirname: false,
|
||||
},
|
||||
resolve,
|
||||
module: moduleConfig,
|
||||
externals: {
|
||||
keytar: 'commonjs keytar',
|
||||
},
|
||||
optimization: {
|
||||
minimizer: [
|
||||
new TerserPlugin({
|
||||
exclude: ['web', 'node_modules'],
|
||||
}),
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
new DefinePlugin({
|
||||
EXPERIMENTAL_FEATURES,
|
||||
IS_SNAP,
|
||||
}),
|
||||
new CopyPlugin({
|
||||
patterns: [
|
||||
{
|
||||
from: '../web/dist',
|
||||
to: 'web',
|
||||
},
|
||||
{
|
||||
from: '../../node_modules/@standardnotes/components/dist/',
|
||||
to: 'web/components',
|
||||
},
|
||||
{
|
||||
from: 'app/node_modules',
|
||||
to: 'node_modules',
|
||||
},
|
||||
{
|
||||
from: 'app/stylesheets/renderer.css',
|
||||
to: 'stylesheets/renderer.css',
|
||||
},
|
||||
{
|
||||
from: 'app/icon',
|
||||
to: 'icon',
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}
|
||||
|
||||
const electronRendererConfig = {
|
||||
entry: {
|
||||
preload: './app/javascripts/Renderer/Preload.ts',
|
||||
renderer: './app/javascripts/Renderer/Renderer.ts',
|
||||
grantLinuxPasswordsAccess: './app/javascripts/Renderer/grantLinuxPasswordsAccess.js',
|
||||
},
|
||||
output: {
|
||||
path: path.resolve(__dirname, 'app', 'dist', 'javascripts', 'renderer'),
|
||||
publicPath: '/',
|
||||
},
|
||||
target: 'electron-renderer',
|
||||
devtool: 'inline-cheap-source-map',
|
||||
node: {
|
||||
__dirname: false,
|
||||
},
|
||||
resolve,
|
||||
module: moduleConfig,
|
||||
externals: {
|
||||
electron: 'commonjs electron',
|
||||
},
|
||||
plugins: [
|
||||
new webpack.DefinePlugin({
|
||||
DEFAULT_SYNC_SERVER: JSON.stringify(process.env.DEFAULT_SYNC_SERVER || 'https://api.standardnotes.com'),
|
||||
PURCHASE_URL: JSON.stringify(process.env.PURCHASE_URL),
|
||||
PLANS_URL: JSON.stringify(process.env.PLANS_URL),
|
||||
DASHBOARD_URL: JSON.stringify(process.env.DASHBOARD_URL),
|
||||
EXPERIMENTAL_FEATURES,
|
||||
WEBSOCKET_URL: JSON.stringify(process.env.WEBSOCKET_URL),
|
||||
ENABLE_UNFINISHED_FEATURES: JSON.stringify(process.env.ENABLE_UNFINISHED_FEATURES),
|
||||
}),
|
||||
],
|
||||
}
|
||||
return [electronMainConfig, electronRendererConfig]
|
||||
}
|
||||
14
packages/desktop/desktop.webpack.dev.js
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
const { merge } = require('webpack-merge');
|
||||
const common = require('./desktop.webpack.common.js');
|
||||
|
||||
module.exports = (env) =>
|
||||
common({
|
||||
...env,
|
||||
onlyTranspileTypescript: true,
|
||||
experimentalFeatures: true,
|
||||
}).map((config) =>
|
||||
merge(config, {
|
||||
mode: 'development',
|
||||
devtool: 'inline-cheap-source-map',
|
||||
})
|
||||
);
|
||||
10
packages/desktop/desktop.webpack.prod.js
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
const { merge } = require('webpack-merge');
|
||||
const common = require('./desktop.webpack.common.js');
|
||||
|
||||
module.exports = (env) =>
|
||||
common(env).map((config) =>
|
||||
merge(config, {
|
||||
mode: 'production',
|
||||
devtool: 'source-map',
|
||||
})
|
||||
);
|
||||
4
packages/desktop/dev-app-update.yml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
owner: standardnotes
|
||||
repo: app
|
||||
provider: github
|
||||
updaterCacheDirName: standard-notes-updater
|
||||
3
packages/desktop/linter.tsconfig.json
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"extends": "../../node_modules/@standardnotes/config/src/linter.tsconfig.json"
|
||||
}
|
||||
161
packages/desktop/package.json
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
{
|
||||
"name": "@standardnotes/desktop",
|
||||
"main": "./app/dist/index.js",
|
||||
"version": "3.20.2",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/standardnotes/app"
|
||||
},
|
||||
"scripts": {
|
||||
"build:remove-unpacked": "rimraf dist/{linux-*,mac,win-*}",
|
||||
"build": "yarn run webpack --config desktop.webpack.prod.js",
|
||||
"change-version": "node ../../scripts/desktop/change-version.mjs",
|
||||
"clean:build": "rimraf app/dist/",
|
||||
"clean:tests": "rimraf test/data/tmp/",
|
||||
"clean": "npm-run-all --parallel clean:*",
|
||||
"dev": "NODE_ENV=development webpack --config desktop.webpack.dev.js --watch",
|
||||
"format": "prettier --write .",
|
||||
"lint:eslint": "eslint app/index.ts app/application.ts app/javascripts/**/*.ts",
|
||||
"lint:formatting": "prettier --check .",
|
||||
"lint:types": "tsc --noEmit",
|
||||
"lint": "npm-run-all --parallel lint:*",
|
||||
"postinstall": "electron-builder install-app-deps",
|
||||
"release": "node ../../scripts/desktop/build.mjs mainstream",
|
||||
"release:mac": "node ../../scripts/desktop/build.mjs mac",
|
||||
"setup": "yarn --ignore-engines && yarn --ignore-engines --cwd ./app",
|
||||
"start": "electron ./app --enable-logging --icon _icon/icon.png",
|
||||
"ava": "rimraf test/data/tmp && ava --serial"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^0.27.2",
|
||||
"compare-versions": "^4.1.3",
|
||||
"decrypt": "github:standardnotes/decrypt#master",
|
||||
"electron-log": "^4.4.6",
|
||||
"electron-updater": "^5.0.1",
|
||||
"fs-extra": "^10.1.0",
|
||||
"mime-types": "^2.1.35",
|
||||
"mobx": "^6.5.0",
|
||||
"@standardnotes/web": "^3.20.4",
|
||||
"@electron/remote": "^2.0.8",
|
||||
"electron": "17.4.2",
|
||||
"lodash": "^4.17.21",
|
||||
"dotenv": "^16.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.17.10",
|
||||
"@babel/preset-env": "^7.17.10",
|
||||
"@commitlint/config-conventional": "^16.2.4",
|
||||
"@standardnotes/electron-clear-data": "1.1.1",
|
||||
"@types/lodash": "^4.14.182",
|
||||
"@types/mime-types": "^2.1.1",
|
||||
"@types/node": "^17.0.31",
|
||||
"@types/proxyquire": "^1.3.28",
|
||||
"@types/yauzl": "^2.10.0",
|
||||
"@typescript-eslint/eslint-plugin": "^5.22.0",
|
||||
"@typescript-eslint/parser": "^5.22.0",
|
||||
"ava": "^4.2.0",
|
||||
"babel-eslint": "^10.1.0",
|
||||
"babel-loader": "^8.2.5",
|
||||
"commitlint": "^16.2.4",
|
||||
"copy-webpack-plugin": "^10.2.4",
|
||||
"electron-builder": "23.0.3",
|
||||
"electron-notarize": "^1.2.1",
|
||||
"eslint": "^8.14.0",
|
||||
"eslint-config-prettier": "^8.5.0",
|
||||
"eslint-plugin-import": "^2.26.0",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-promise": "^6.0.0",
|
||||
"file-loader": "^6.2.0",
|
||||
"husky": "^7.0.4",
|
||||
"mime-types": "^2.1.35",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"pre-push": "^0.1.2",
|
||||
"prettier": "^2.6.2",
|
||||
"proxyquire": "^2.1.3",
|
||||
"rimraf": "^3.0.2",
|
||||
"terser-webpack-plugin": "^5.3.1",
|
||||
"ts-loader": "^9.3.0",
|
||||
"ts-node": "^10.7.0",
|
||||
"typescript": "^4.6.4",
|
||||
"webpack": "^5.72.0",
|
||||
"webpack-cli": "^4.9.2",
|
||||
"webpack-merge": "^5.8.0"
|
||||
},
|
||||
"build": {
|
||||
"electronVersion": "17.4.2",
|
||||
"appId": "org.standardnotes.standardnotes",
|
||||
"artifactName": "${name}-${version}-${os}-${arch}.${ext}",
|
||||
"afterSign": "../../scripts/desktop/afterSignHook.js",
|
||||
"files": [
|
||||
"compiled/**/*",
|
||||
"dist/**/*",
|
||||
"stylesheets/**/*",
|
||||
"assets/**/*",
|
||||
"icon/**/*"
|
||||
],
|
||||
"protocols": [
|
||||
{
|
||||
"name": "Standard Notes",
|
||||
"schemes": [
|
||||
"standardnotes"
|
||||
]
|
||||
}
|
||||
],
|
||||
"mac": {
|
||||
"category": "public.app-category.productivity",
|
||||
"hardenedRuntime": true,
|
||||
"entitlements": "./build/entitlements.mac.inherit.plist",
|
||||
"entitlementsInherit": "./build/entitlements.mac.inherit.plist",
|
||||
"target": [
|
||||
"dmg",
|
||||
"zip"
|
||||
]
|
||||
},
|
||||
"win": {
|
||||
"certificateSubjectName": "Standard Notes Ltd.",
|
||||
"publisherName": "Standard Notes Ltd.",
|
||||
"signDlls": true
|
||||
},
|
||||
"nsis": {
|
||||
"deleteAppDataOnUninstall": true
|
||||
},
|
||||
"linux": {
|
||||
"category": "Office",
|
||||
"icon": "build/icon/",
|
||||
"desktop": {
|
||||
"StartupWMClass": "standard notes"
|
||||
},
|
||||
"target": [
|
||||
"AppImage"
|
||||
]
|
||||
},
|
||||
"snap": {
|
||||
"plugs": [
|
||||
"default",
|
||||
"password-manager-service"
|
||||
]
|
||||
}
|
||||
},
|
||||
"husky": {
|
||||
"hooks": {
|
||||
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
|
||||
}
|
||||
},
|
||||
"ava": {
|
||||
"concurrency": 0,
|
||||
"extensions": [
|
||||
"ts"
|
||||
],
|
||||
"files": [
|
||||
"test/*.spec.ts"
|
||||
],
|
||||
"require": [
|
||||
"ts-node/register/transpile-only"
|
||||
],
|
||||
"verbose": true
|
||||
},
|
||||
"pre-push": [
|
||||
"lint"
|
||||
]
|
||||
}
|
||||
52
packages/desktop/test/TestIpcMessage.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
export interface TestIPCMessage {
|
||||
id: number
|
||||
type: MessageType
|
||||
args: any[]
|
||||
}
|
||||
|
||||
export interface TestIPCMessageResult {
|
||||
id: number
|
||||
resolve?: any
|
||||
reject?: any
|
||||
}
|
||||
|
||||
export interface AppTestMessage {
|
||||
type: AppMessageType
|
||||
}
|
||||
|
||||
export enum AppMessageType {
|
||||
Ready,
|
||||
WindowLoaded,
|
||||
SavedBackup,
|
||||
Log,
|
||||
}
|
||||
|
||||
export enum MessageType {
|
||||
WindowCount,
|
||||
StoreData,
|
||||
StoreSettingsLocation,
|
||||
StoreSet,
|
||||
SetLocalStorageValue,
|
||||
AppMenuItems,
|
||||
SpellCheckerManager,
|
||||
SpellCheckerLanguages,
|
||||
ClickLanguage,
|
||||
BackupsAreEnabled,
|
||||
ToggleBackupsEnabled,
|
||||
BackupsLocation,
|
||||
PerformBackup,
|
||||
ChangeBackupsLocation,
|
||||
CopyDecryptScript,
|
||||
MenuReloaded,
|
||||
UpdateState,
|
||||
CheckForUpdate,
|
||||
UpdateManagerNotifiedStateChange,
|
||||
Relaunch,
|
||||
DataArchive,
|
||||
GetJSON,
|
||||
DownloadFile,
|
||||
AutoUpdateEnabled,
|
||||
HasReloadedMenu,
|
||||
AppStateCall,
|
||||
SignOut,
|
||||
}
|
||||