commit 96b16c62d95552884ac665b3cb5e79f0f21aa481 Author: D. Scott Boggs Date: Sun Nov 27 09:44:43 2022 -0500 initial state; elefren 0.22.0 diff --git a/.cargo-ok b/.cargo-ok new file mode 100644 index 0000000..b5754e2 --- /dev/null +++ b/.cargo-ok @@ -0,0 +1 @@ +ok \ No newline at end of file diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json new file mode 100644 index 0000000..8dcfab9 --- /dev/null +++ b/.cargo_vcs_info.json @@ -0,0 +1,5 @@ +{ + "git": { + "sha1": "17c727f5c615eed921d0095d1b6f49e44024025d" + } +} diff --git a/.clog.toml b/.clog.toml new file mode 100644 index 0000000..a853fbd --- /dev/null +++ b/.clog.toml @@ -0,0 +1,3 @@ +[clog] +changelog = "CHANGELOG.md" + diff --git a/.env.sample b/.env.sample new file mode 100644 index 0000000..693aa30 --- /dev/null +++ b/.env.sample @@ -0,0 +1,5 @@ +export TOKEN='snakeoil' +export CLIENT_ID='' +export CLIENT_SECRET='' +export REDIRECT='' +export BASE='https://mastodon.social' diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7111969 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +target +Cargo.lock +.env +mastodon-data.toml* +libtest.rmeta diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..8d8f57e --- /dev/null +++ b/.travis.yml @@ -0,0 +1,42 @@ +sudo: required +language: rust +dist: trusty +addons: + apt: + packages: + - libssl-dev +cache: + directories: + - $HOME/.cargo +env: + - ELEFREN_FEATURES="--features toml" + - ELEFREN_FEATURES="--features json" + - ELEFREN_FEATURES="--features all" + - ELEFREN_FEATURES="" +os: + - linux + - osx +rust: + - stable + - beta + - nightly +script: + - cargo test $ELEFREN_FEATURES +matrix: + include: + - name: "Coverage" + rust: nightly + before_cache: RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install -f cargo-tarpaulin + script: cargo build --features all + after_success: cargo tarpaulin --ciserver travis-ci --coveralls $TRAVIS_JOB_ID --features all + + - name: "rustfmt" + rust: nightly + before_script: rustup component add rustfmt-preview + script: cargo fmt --all -- --check + + allow_failures: + - rust: nightly +notifications: + email: + on_success: never diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..2c859eb --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,22 @@ +{ + "cSpell.words": [ + "Creds", + "deserialise", + "Elefren", + "favourite", + "favourited", + "indoc", + "isolang", + "querystring", + "reblog", + "reqwest", + "tomlcrate", + "tungstenite", + "Unauth", + "unendorse", + "unfavourite", + "unfollow", + "unmute", + "unreblog" + ] +} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..9bfe7b4 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,190 @@ + +## v0.18.0 (2019-01-05) + +#### Breaking Changes + +* Change `Registered::complete` to take the receiver by reference + +#### Features + +* Add `Registered::into_parts` and `Registered::from_parts` +* Add `FromStr` implementation for `Scopes` + + +## v0.17.0 (2018-12-12) + +#### Bug Fixes + +* Fixes `follow` to return a `Relationship` [6f63fef](6f63fef0b2414099c55e36107aab785f689d19b6) + +#### Features + +* Add `follows_me` and `followed_by_me` shortcut methods [4dd4042](4dd40422b3de11aaadcfc600317c0df3556b38f5) + +#### Breaking Changes + +* Change `u64` ids to `&str` [9a08058](9a080583f0577d3f77eaf7be55758835c56ea61e) +* Fixes `follow` to return a `Relationship` [6f63fef](6f63fef0b2414099c55e36107aab785f689d19b6) + + +## v0.16.0 (2018-10-03) + +This release upgrades reqwest, our http client dependency, from 0.8.8 -> +0.9.0 + + +## v0.15.2 + +This is a bugfix release + + +## v0.15.1 + +This is a bugfix release + + +## v0.15.0 (2018-09-15) + +This release adds support for all new API endpoints introduced in Mastodon 2.4.* and 2.5.0 + +#### Features + +* **scopes:** Implement granular OAuth scopes ([e284894d](e284894d), closes [#44](44)) +* **helpers:** cli::authenticate ([034bd4e6](034bd4e6)) +* **client:** Implement client.update\_credentials ([a57c7e2f](a57c7e2f)) +* **status:** Add language code to status builer ([989d9a59](989d9a59), closes [#55](55)) +* **client:** Implement profile metadata update ([0ad1e374](0ad1e374), closes [#54](54)) +* **search:** Implement `GET /api/v2/search` ([28192e11](28192e11)) +* **client:** Implement push notifciations endpoints ([690b029d](690b029d), closes [#53](53)) +* **client:** Add `replies_count` property to `Status` entities ([7d752a9f](7d752a9f), closes [#73](73)) +* **client:** Implement Keyword filtering API ([7d164cb8](7d164cb8), closes [#71](71)) +* **client:** Implement the Follow Suggestions API ([7de1bdc0](7de1bdc0), closes [#72](72)) +* **client:** Implement the Endorsements API ([1f0ba184](1f0ba184), closes [#74](74)) + +#### Breaking Changes + +* **scopes:** Implement granular OAuth scopes ([e284894d](e284894d)) (closes [#44](44)) + +#### Bug Fixes + +* **client:** change return value of client.unfollow to `Relationship` ([20a9c69a](20a9c69a)) +* **client:** change `POST /search` to `GET /search` ([34e2c008](34e2c008)) + + + +## v0.14.0 (2018-08-29) + +#### Features + +* **helpers:** add json helper module ([46871da4](46871da4)) + +#### Breaking Changes + +* **client:** fix broken paged\_routes\_with\_id methods ([c66c305d](c66c305d), closes [#42](42)) + +#### Bug Fixes + +* **client:** fix broken paged\_routes\_with\_id methods ([c66c305d](c66c305d), closes [#42](42)) + + +# 0.13 (2018/08/27) + +## Features + +- `Registration` now duplicates the `AppBuilder` API, so you can + replace: + + ``` + let app = App::builder(); + app.client_name("test-client"); + + let registration = Registration::new("http://example.com") + .register(app)?; + ``` + + with this: + + ``` + let registration = Registration::new("http://example.com") + .client_name("test-client") + .build()?; + ``` + + You can still call use the `Registration` & `AppBuilder` APIs like + before, but any App passed to `.register` will supercede anything app + config set on the `Registration` object itself. + + In future releases, this will become a hard error. + +- `elefren::status_builder::StatusBuilder::new()` now takes anything + that implements `Display` instead of specifically an owned `String` + +## Breaking Changes + +- The `elefren::data::toml` module has been moved to + `elefren::helpers::toml` +- Because of the changes to `Registration`, the `elefren::apps::prelude` + module has been removed. The types that are still necessary from that + prelude have been moved to `elefren::prelude`, but + `elefren::apps::App` will have to be imported separately +- `elefren::entities::account::CredientialsBuilder` has been moved to + `elefren::entities::account::CredentialsBuilder` (note the spelling + difference) +- `Registered::complete` now takes a `&str` instead of a `String` + +## Compatibility + +- `elefren::entities::instance::Instance` now has the `max_toot_chars` + property, for use with the Pleroma and Glitch-soc APIs + +# 0.12 (2018/08/23) + +## Features + +- `Page::items_iter` added, abstracts over "next_page" logic +- `elefen::prelude` and `elefen::apps::prelude` modules added to more + easily import all necessary types +- Helpers added to allow serialization & deseriasization of `Data` types + to `toml` + +## Breaking Changes + +- Combined all parameters to `mastodon.statuses` (except `id`) to their + own type, `StatusesRequest` +- All API methods on `Mastodon` type moved into a trait, + `MastodonClient`, to enable better mocking during tests +- `Mastodon::from_data(Data)` was changed to `Mastodon::from(Data)` +- `AppBuilder` was changed, use `App::builder()` instead +- `Registration` was broken up to enable better registration flow + +## Documentation + +- All API methods now have doc comments +- All docs were updated for the new breaking changes + +## Compatibility + +- Login to pleroma instances was fixed + +# 0.11 +- Added more examples to `examples` directory. +- Fixed `follow` and `unfollow` routes. +- Updated `moved` field to be `Box`. + +# 0.10 + +- Added the ability to handle paged entities like favourites and such.(Only favourites in prerelease) +- Added optional `source` and `moved` fields to `Account`. +- Added `Source` struct to match with the `Account.source` field. +- Added `CredientialsBuilder` struct for updating profile using + `verify_credientials`. +- Attachment now handles being sent an empty object, which is converted + to `None`. +- Added ombed data fields to `Card`. +- Added `version` and `urls` fields to `Instance`. +- Added `id`, `muting_notifications`, and `domain_blocking` to `Relationship`. +- Added `emojis`, `language`, and `pinned` fields to `Status` +- Added `Emoji` struct. +- Added `List` and `Mention` structs(matching routes not added yet). +- Added example that prints your profile. +- Updated dependencies diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..cb857fa --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,99 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "elefren" +version = "0.22.0" +authors = ["Aaron Power ", "Paul Woolcock "] +description = "A wrapper around the Mastodon API." +readme = "README.md" +keywords = ["api", "web", "social", "mastodon", "wrapper"] +categories = ["web-programming", "web-programming::http-client", "api-bindings"] +license = "MIT/Apache-2.0" +repository = "https://github.com/pwoolcoc/elefren.git" +[package.metadata.docs.rs] +features = ["all"] +[dependencies.chrono] +version = "0.4" +features = ["serde"] + +[dependencies.doc-comment] +version = "0.3" + +[dependencies.envy] +version = "0.4.0" +optional = true + +[dependencies.hyper-old-types] +version = "0.11.0" + +[dependencies.isolang] +version = "1.0" +features = ["serde_serialize"] + +[dependencies.log] +version = "0.4" + +[dependencies.reqwest] +version = "0.9" +default-features = false + +[dependencies.serde] +version = "1" + +[dependencies.serde_derive] +version = "1" + +[dependencies.serde_json] +version = "1" + +[dependencies.serde_qs] +version = "0.4.5" + +[dependencies.serde_urlencoded] +version = "0.6.1" + +[dependencies.tap-reader] +version = "1" + +[dependencies.toml] +version = "0.5.0" +optional = true + +[dependencies.try_from] +version = "0.3.2" + +[dependencies.tungstenite] +version = "0.10.1" + +[dependencies.url] +version = "1" +[dev-dependencies.indoc] +version = "0.3.1" + +[dev-dependencies.pretty_env_logger] +version = "0.3.0" + +[dev-dependencies.skeptic] +version = "0.13.3" + +[dev-dependencies.tempfile] +version = "3.0.3" +[build-dependencies.skeptic] +version = "0.13.3" + +[features] +all = ["toml", "json", "env"] +default = ["reqwest/default-tls"] +env = ["envy"] +json = [] +rustls-tls = ["reqwest/rustls-tls"] diff --git a/LICENCE-APACHE b/LICENCE-APACHE new file mode 100644 index 0000000..97fdf99 --- /dev/null +++ b/LICENCE-APACHE @@ -0,0 +1,13 @@ +Copyright 2016 Aaron Power + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/LICENCE-MIT b/LICENCE-MIT new file mode 100644 index 0000000..0e95451 --- /dev/null +++ b/LICENCE-MIT @@ -0,0 +1,21 @@ +MIT License (MIT) + +Copyright (c) 2016 Aaron Power + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..1c9c7fb --- /dev/null +++ b/Makefile @@ -0,0 +1,8 @@ +DOCS := $(PWD)/docs + +book: $(DOCS)/guide/index.html + +$(DOCS)/guide/index.html: $(DOCS)/src/*.md + cd docs && mdbook build + +.PHONY: book diff --git a/README.md b/README.md new file mode 100644 index 0000000..55bf18f --- /dev/null +++ b/README.md @@ -0,0 +1,100 @@ +# Elefren + +## A Wrapper for the Mastodon API. + +[![Build Status](https://travis-ci.org/pwoolcoc/elefren.svg?branch=master)](https://travis-ci.org/pwoolcoc/elefren) +[![Build Status](https://ci.appveyor.com/api/projects/status/qeigk3nmmps52wxv?svg=true)](https://ci.appveyor.com/project/pwoolcoc/elefren) +[![Coverage Status](https://coveralls.io/repos/github/pwoolcoc/elefren/badge.svg?branch=master&service=github)](https://coveralls.io/github/pwoolcoc/elefren?branch=master) +[![crates.io](https://img.shields.io/crates/v/elefren.svg)](https://crates.io/crates/elefren) +[![Docs](https://docs.rs/elefren/badge.svg)](https://docs.rs/elefren) +[![MIT/APACHE-2.0](https://img.shields.io/crates/l/elefren.svg)](https://crates.io/crates/elefren) + +[Documentation](https://docs.rs/elefren/) + +A wrapper around the [API](https://github.com/tootsuite/documentation/blob/master/docs/Using-the-API/API.md#tag) for [Mastodon](https://mastodon.social/) + +## Installation + +To add `elefren` to your project, add the following to the +`[dependencies]` section of your `Cargo.toml` + +```toml +elefren = "0.22" +``` + +## Example + +In your `Cargo.toml`, make sure you enable the `toml` feature: + +```toml +[dependencies] +elefren = { version = "0.22", features = ["toml"] } +``` + +```rust,no_run +// src/main.rs +extern crate elefren; + +use std::error::Error; + +use elefren::prelude::*; +use elefren::helpers::toml; // requires `features = ["toml"]` +use elefren::helpers::cli; + +fn main() -> Result<(), Box> { + let mastodon = if let Ok(data) = toml::from_file("mastodon-data.toml") { + Mastodon::from(data) + } else { + register()? + }; + + let you = mastodon.verify_credentials()?; + + println!("{:#?}", you); + + Ok(()) +} + +fn register() -> Result> { + let registration = Registration::new("https://mastodon.social") + .client_name("elefren-examples") + .build()?; + let mastodon = cli::authenticate(registration)?; + + // Save app data for using on the next run. + toml::to_file(&*mastodon, "mastodon-data.toml")?; + + Ok(mastodon) +} +``` + +It also supports the [Streaming API](https://docs.joinmastodon.org/api/streaming): + +```no_run +use elefren::prelude::*; +use elefren::entities::event::Event; + +use std::error::Error; + +fn main() -> Result<(), Box> { + let data = Data { + base: "".into(), + client_id: "".into(), + client_secret: "".into(), + redirect: "".into(), + token: "".into(), + }; + + let client = Mastodon::from(data); + + for event in client.streaming_user()? { + match event { + Event::Update(ref status) => { /* .. */ }, + Event::Notification(ref notification) => { /* .. */ }, + Event::Delete(ref id) => { /* .. */ }, + Event::FiltersChanged => { /* .. */ }, + } + } + Ok(()) +} +``` diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 0000000..6087033 --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,29 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + OTHER_TARGET: i686-pc-windows-msvc + MAKE_TARGETS: test-unit-x86_64-pc-windows-msvc + TOOLCHAIN: stable + - TARGET: x86_64-pc-windows-msvc + OTHER_TARGET: i686-pc-windows-msvc + MAKE_TARGETS: test-unit-x86_64-pc-windows-msvc + TOOLCHAIN: beta + - TARGET: x86_64-pc-windows-msvc + OTHER_TARGET: i686-pc-windows-msvc + MAKE_TARGETS: test-unit-x86_64-pc-windows-msvc + TOOLCHAIN: nightly + +install: + - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe + - rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain %TOOLCHAIN% + - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin + - rustup target add %OTHER_TARGET% + - rustc -V + - cargo -V + +clone_depth: 1 + +build: false + +test_script: + - cargo test --features all diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..34ca6e2 --- /dev/null +++ b/build.rs @@ -0,0 +1,20 @@ +#[cfg(feature = "toml")] +extern crate skeptic; + +#[cfg(feature = "toml")] +fn main() { + skeptic::generate_doc_tests(&["README.md"]); +} + +#[cfg(not(feature = "toml"))] +fn main() { + // tests/skeptic.rs still expects a file to be at OUT_DIR/skeptic-tests.rs, so + // make a dummy one + use std::{env, fs::OpenOptions, path::Path}; + let out_dir = Path::new(&env::var("OUT_DIR").expect("no out_dir set")).join("skeptic-tests.rs"); + OpenOptions::new() + .create(true) + .write(true) + .open(out_dir) + .expect("couldn't write to file"); +} diff --git a/docs/book.toml b/docs/book.toml new file mode 100644 index 0000000..a711481 --- /dev/null +++ b/docs/book.toml @@ -0,0 +1,8 @@ +[book] +authors = ["Paul Woolcock"] +multilingual = false +src = "src" +title = "Elefren Guide" + +[build] +build-dir = "guide" diff --git a/docs/guide/.nojekyll b/docs/guide/.nojekyll new file mode 100644 index 0000000..8631215 --- /dev/null +++ b/docs/guide/.nojekyll @@ -0,0 +1 @@ +This file makes sure that Github Pages doesn't process mdBook's output. \ No newline at end of file diff --git a/docs/guide/FontAwesome/css/font-awesome.css b/docs/guide/FontAwesome/css/font-awesome.css new file mode 100644 index 0000000..ee4e978 --- /dev/null +++ b/docs/guide/FontAwesome/css/font-awesome.css @@ -0,0 +1,4 @@ +/*! + * Font Awesome 4.4.0 by @davegandy - http://fontawesome.io - @fontawesome + * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) + */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.4.0');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.4.0') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff2?v=4.4.0') format('woff2'),url('../fonts/fontawesome-webfont.woff?v=4.4.0') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.4.0') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.4.0#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571429em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14285714em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left{margin-right:.3em}.fa.fa-pull-right{margin-left:.3em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1);-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1);-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:"\f000"}.fa-music:before{content:"\f001"}.fa-search:before{content:"\f002"}.fa-envelope-o:before{content:"\f003"}.fa-heart:before{content:"\f004"}.fa-star:before{content:"\f005"}.fa-star-o:before{content:"\f006"}.fa-user:before{content:"\f007"}.fa-film:before{content:"\f008"}.fa-th-large:before{content:"\f009"}.fa-th:before{content:"\f00a"}.fa-th-list:before{content:"\f00b"}.fa-check:before{content:"\f00c"}.fa-remove:before,.fa-close:before,.fa-times:before{content:"\f00d"}.fa-search-plus:before{content:"\f00e"}.fa-search-minus:before{content:"\f010"}.fa-power-off:before{content:"\f011"}.fa-signal:before{content:"\f012"}.fa-gear:before,.fa-cog:before{content:"\f013"}.fa-trash-o:before{content:"\f014"}.fa-home:before{content:"\f015"}.fa-file-o:before{content:"\f016"}.fa-clock-o:before{content:"\f017"}.fa-road:before{content:"\f018"}.fa-download:before{content:"\f019"}.fa-arrow-circle-o-down:before{content:"\f01a"}.fa-arrow-circle-o-up:before{content:"\f01b"}.fa-inbox:before{content:"\f01c"}.fa-play-circle-o:before{content:"\f01d"}.fa-rotate-right:before,.fa-repeat:before{content:"\f01e"}.fa-refresh:before{content:"\f021"}.fa-list-alt:before{content:"\f022"}.fa-lock:before{content:"\f023"}.fa-flag:before{content:"\f024"}.fa-headphones:before{content:"\f025"}.fa-volume-off:before{content:"\f026"}.fa-volume-down:before{content:"\f027"}.fa-volume-up:before{content:"\f028"}.fa-qrcode:before{content:"\f029"}.fa-barcode:before{content:"\f02a"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-book:before{content:"\f02d"}.fa-bookmark:before{content:"\f02e"}.fa-print:before{content:"\f02f"}.fa-camera:before{content:"\f030"}.fa-font:before{content:"\f031"}.fa-bold:before{content:"\f032"}.fa-italic:before{content:"\f033"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.fa-align-left:before{content:"\f036"}.fa-align-center:before{content:"\f037"}.fa-align-right:before{content:"\f038"}.fa-align-justify:before{content:"\f039"}.fa-list:before{content:"\f03a"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-indent:before{content:"\f03c"}.fa-video-camera:before{content:"\f03d"}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:"\f03e"}.fa-pencil:before{content:"\f040"}.fa-map-marker:before{content:"\f041"}.fa-adjust:before{content:"\f042"}.fa-tint:before{content:"\f043"}.fa-edit:before,.fa-pencil-square-o:before{content:"\f044"}.fa-share-square-o:before{content:"\f045"}.fa-check-square-o:before{content:"\f046"}.fa-arrows:before{content:"\f047"}.fa-step-backward:before{content:"\f048"}.fa-fast-backward:before{content:"\f049"}.fa-backward:before{content:"\f04a"}.fa-play:before{content:"\f04b"}.fa-pause:before{content:"\f04c"}.fa-stop:before{content:"\f04d"}.fa-forward:before{content:"\f04e"}.fa-fast-forward:before{content:"\f050"}.fa-step-forward:before{content:"\f051"}.fa-eject:before{content:"\f052"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-plus-circle:before{content:"\f055"}.fa-minus-circle:before{content:"\f056"}.fa-times-circle:before{content:"\f057"}.fa-check-circle:before{content:"\f058"}.fa-question-circle:before{content:"\f059"}.fa-info-circle:before{content:"\f05a"}.fa-crosshairs:before{content:"\f05b"}.fa-times-circle-o:before{content:"\f05c"}.fa-check-circle-o:before{content:"\f05d"}.fa-ban:before{content:"\f05e"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrow-down:before{content:"\f063"}.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-expand:before{content:"\f065"}.fa-compress:before{content:"\f066"}.fa-plus:before{content:"\f067"}.fa-minus:before{content:"\f068"}.fa-asterisk:before{content:"\f069"}.fa-exclamation-circle:before{content:"\f06a"}.fa-gift:before{content:"\f06b"}.fa-leaf:before{content:"\f06c"}.fa-fire:before{content:"\f06d"}.fa-eye:before{content:"\f06e"}.fa-eye-slash:before{content:"\f070"}.fa-warning:before,.fa-exclamation-triangle:before{content:"\f071"}.fa-plane:before{content:"\f072"}.fa-calendar:before{content:"\f073"}.fa-random:before{content:"\f074"}.fa-comment:before{content:"\f075"}.fa-magnet:before{content:"\f076"}.fa-chevron-up:before{content:"\f077"}.fa-chevron-down:before{content:"\f078"}.fa-retweet:before{content:"\f079"}.fa-shopping-cart:before{content:"\f07a"}.fa-folder:before{content:"\f07b"}.fa-folder-open:before{content:"\f07c"}.fa-arrows-v:before{content:"\f07d"}.fa-arrows-h:before{content:"\f07e"}.fa-bar-chart-o:before,.fa-bar-chart:before{content:"\f080"}.fa-twitter-square:before{content:"\f081"}.fa-facebook-square:before{content:"\f082"}.fa-camera-retro:before{content:"\f083"}.fa-key:before{content:"\f084"}.fa-gears:before,.fa-cogs:before{content:"\f085"}.fa-comments:before{content:"\f086"}.fa-thumbs-o-up:before{content:"\f087"}.fa-thumbs-o-down:before{content:"\f088"}.fa-star-half:before{content:"\f089"}.fa-heart-o:before{content:"\f08a"}.fa-sign-out:before{content:"\f08b"}.fa-linkedin-square:before{content:"\f08c"}.fa-thumb-tack:before{content:"\f08d"}.fa-external-link:before{content:"\f08e"}.fa-sign-in:before{content:"\f090"}.fa-trophy:before{content:"\f091"}.fa-github-square:before{content:"\f092"}.fa-upload:before{content:"\f093"}.fa-lemon-o:before{content:"\f094"}.fa-phone:before{content:"\f095"}.fa-square-o:before{content:"\f096"}.fa-bookmark-o:before{content:"\f097"}.fa-phone-square:before{content:"\f098"}.fa-twitter:before{content:"\f099"}.fa-facebook-f:before,.fa-facebook:before{content:"\f09a"}.fa-github:before{content:"\f09b"}.fa-unlock:before{content:"\f09c"}.fa-credit-card:before{content:"\f09d"}.fa-feed:before,.fa-rss:before{content:"\f09e"}.fa-hdd-o:before{content:"\f0a0"}.fa-bullhorn:before{content:"\f0a1"}.fa-bell:before{content:"\f0f3"}.fa-certificate:before{content:"\f0a3"}.fa-hand-o-right:before{content:"\f0a4"}.fa-hand-o-left:before{content:"\f0a5"}.fa-hand-o-up:before{content:"\f0a6"}.fa-hand-o-down:before{content:"\f0a7"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-globe:before{content:"\f0ac"}.fa-wrench:before{content:"\f0ad"}.fa-tasks:before{content:"\f0ae"}.fa-filter:before{content:"\f0b0"}.fa-briefcase:before{content:"\f0b1"}.fa-arrows-alt:before{content:"\f0b2"}.fa-group:before,.fa-users:before{content:"\f0c0"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-cloud:before{content:"\f0c2"}.fa-flask:before{content:"\f0c3"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-copy:before,.fa-files-o:before{content:"\f0c5"}.fa-paperclip:before{content:"\f0c6"}.fa-save:before,.fa-floppy-o:before{content:"\f0c7"}.fa-square:before{content:"\f0c8"}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:"\f0c9"}.fa-list-ul:before{content:"\f0ca"}.fa-list-ol:before{content:"\f0cb"}.fa-strikethrough:before{content:"\f0cc"}.fa-underline:before{content:"\f0cd"}.fa-table:before{content:"\f0ce"}.fa-magic:before{content:"\f0d0"}.fa-truck:before{content:"\f0d1"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-square:before{content:"\f0d3"}.fa-google-plus-square:before{content:"\f0d4"}.fa-google-plus:before{content:"\f0d5"}.fa-money:before{content:"\f0d6"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-up:before{content:"\f0d8"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-columns:before{content:"\f0db"}.fa-unsorted:before,.fa-sort:before{content:"\f0dc"}.fa-sort-down:before,.fa-sort-desc:before{content:"\f0dd"}.fa-sort-up:before,.fa-sort-asc:before{content:"\f0de"}.fa-envelope:before{content:"\f0e0"}.fa-linkedin:before{content:"\f0e1"}.fa-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-legal:before,.fa-gavel:before{content:"\f0e3"}.fa-dashboard:before,.fa-tachometer:before{content:"\f0e4"}.fa-comment-o:before{content:"\f0e5"}.fa-comments-o:before{content:"\f0e6"}.fa-flash:before,.fa-bolt:before{content:"\f0e7"}.fa-sitemap:before{content:"\f0e8"}.fa-umbrella:before{content:"\f0e9"}.fa-paste:before,.fa-clipboard:before{content:"\f0ea"}.fa-lightbulb-o:before{content:"\f0eb"}.fa-exchange:before{content:"\f0ec"}.fa-cloud-download:before{content:"\f0ed"}.fa-cloud-upload:before{content:"\f0ee"}.fa-user-md:before{content:"\f0f0"}.fa-stethoscope:before{content:"\f0f1"}.fa-suitcase:before{content:"\f0f2"}.fa-bell-o:before{content:"\f0a2"}.fa-coffee:before{content:"\f0f4"}.fa-cutlery:before{content:"\f0f5"}.fa-file-text-o:before{content:"\f0f6"}.fa-building-o:before{content:"\f0f7"}.fa-hospital-o:before{content:"\f0f8"}.fa-ambulance:before{content:"\f0f9"}.fa-medkit:before{content:"\f0fa"}.fa-fighter-jet:before{content:"\f0fb"}.fa-beer:before{content:"\f0fc"}.fa-h-square:before{content:"\f0fd"}.fa-plus-square:before{content:"\f0fe"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angle-down:before{content:"\f107"}.fa-desktop:before{content:"\f108"}.fa-laptop:before{content:"\f109"}.fa-tablet:before{content:"\f10a"}.fa-mobile-phone:before,.fa-mobile:before{content:"\f10b"}.fa-circle-o:before{content:"\f10c"}.fa-quote-left:before{content:"\f10d"}.fa-quote-right:before{content:"\f10e"}.fa-spinner:before{content:"\f110"}.fa-circle:before{content:"\f111"}.fa-mail-reply:before,.fa-reply:before{content:"\f112"}.fa-github-alt:before{content:"\f113"}.fa-folder-o:before{content:"\f114"}.fa-folder-open-o:before{content:"\f115"}.fa-smile-o:before{content:"\f118"}.fa-frown-o:before{content:"\f119"}.fa-meh-o:before{content:"\f11a"}.fa-gamepad:before{content:"\f11b"}.fa-keyboard-o:before{content:"\f11c"}.fa-flag-o:before{content:"\f11d"}.fa-flag-checkered:before{content:"\f11e"}.fa-terminal:before{content:"\f120"}.fa-code:before{content:"\f121"}.fa-mail-reply-all:before,.fa-reply-all:before{content:"\f122"}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:"\f123"}.fa-location-arrow:before{content:"\f124"}.fa-crop:before{content:"\f125"}.fa-code-fork:before{content:"\f126"}.fa-unlink:before,.fa-chain-broken:before{content:"\f127"}.fa-question:before{content:"\f128"}.fa-info:before{content:"\f129"}.fa-exclamation:before{content:"\f12a"}.fa-superscript:before{content:"\f12b"}.fa-subscript:before{content:"\f12c"}.fa-eraser:before{content:"\f12d"}.fa-puzzle-piece:before{content:"\f12e"}.fa-microphone:before{content:"\f130"}.fa-microphone-slash:before{content:"\f131"}.fa-shield:before{content:"\f132"}.fa-calendar-o:before{content:"\f133"}.fa-fire-extinguisher:before{content:"\f134"}.fa-rocket:before{content:"\f135"}.fa-maxcdn:before{content:"\f136"}.fa-chevron-circle-left:before{content:"\f137"}.fa-chevron-circle-right:before{content:"\f138"}.fa-chevron-circle-up:before{content:"\f139"}.fa-chevron-circle-down:before{content:"\f13a"}.fa-html5:before{content:"\f13b"}.fa-css3:before{content:"\f13c"}.fa-anchor:before{content:"\f13d"}.fa-unlock-alt:before{content:"\f13e"}.fa-bullseye:before{content:"\f140"}.fa-ellipsis-h:before{content:"\f141"}.fa-ellipsis-v:before{content:"\f142"}.fa-rss-square:before{content:"\f143"}.fa-play-circle:before{content:"\f144"}.fa-ticket:before{content:"\f145"}.fa-minus-square:before{content:"\f146"}.fa-minus-square-o:before{content:"\f147"}.fa-level-up:before{content:"\f148"}.fa-level-down:before{content:"\f149"}.fa-check-square:before{content:"\f14a"}.fa-pencil-square:before{content:"\f14b"}.fa-external-link-square:before{content:"\f14c"}.fa-share-square:before{content:"\f14d"}.fa-compass:before{content:"\f14e"}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:"\f150"}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:"\f151"}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:"\f152"}.fa-euro:before,.fa-eur:before{content:"\f153"}.fa-gbp:before{content:"\f154"}.fa-dollar:before,.fa-usd:before{content:"\f155"}.fa-rupee:before,.fa-inr:before{content:"\f156"}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:"\f157"}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:"\f158"}.fa-won:before,.fa-krw:before{content:"\f159"}.fa-bitcoin:before,.fa-btc:before{content:"\f15a"}.fa-file:before{content:"\f15b"}.fa-file-text:before{content:"\f15c"}.fa-sort-alpha-asc:before{content:"\f15d"}.fa-sort-alpha-desc:before{content:"\f15e"}.fa-sort-amount-asc:before{content:"\f160"}.fa-sort-amount-desc:before{content:"\f161"}.fa-sort-numeric-asc:before{content:"\f162"}.fa-sort-numeric-desc:before{content:"\f163"}.fa-thumbs-up:before{content:"\f164"}.fa-thumbs-down:before{content:"\f165"}.fa-youtube-square:before{content:"\f166"}.fa-youtube:before{content:"\f167"}.fa-xing:before{content:"\f168"}.fa-xing-square:before{content:"\f169"}.fa-youtube-play:before{content:"\f16a"}.fa-dropbox:before{content:"\f16b"}.fa-stack-overflow:before{content:"\f16c"}.fa-instagram:before{content:"\f16d"}.fa-flickr:before{content:"\f16e"}.fa-adn:before{content:"\f170"}.fa-bitbucket:before{content:"\f171"}.fa-bitbucket-square:before{content:"\f172"}.fa-tumblr:before{content:"\f173"}.fa-tumblr-square:before{content:"\f174"}.fa-long-arrow-down:before{content:"\f175"}.fa-long-arrow-up:before{content:"\f176"}.fa-long-arrow-left:before{content:"\f177"}.fa-long-arrow-right:before{content:"\f178"}.fa-apple:before{content:"\f179"}.fa-windows:before{content:"\f17a"}.fa-android:before{content:"\f17b"}.fa-linux:before{content:"\f17c"}.fa-dribbble:before{content:"\f17d"}.fa-skype:before{content:"\f17e"}.fa-foursquare:before{content:"\f180"}.fa-trello:before{content:"\f181"}.fa-female:before{content:"\f182"}.fa-male:before{content:"\f183"}.fa-gittip:before,.fa-gratipay:before{content:"\f184"}.fa-sun-o:before{content:"\f185"}.fa-moon-o:before{content:"\f186"}.fa-archive:before{content:"\f187"}.fa-bug:before{content:"\f188"}.fa-vk:before{content:"\f189"}.fa-weibo:before{content:"\f18a"}.fa-renren:before{content:"\f18b"}.fa-pagelines:before{content:"\f18c"}.fa-stack-exchange:before{content:"\f18d"}.fa-arrow-circle-o-right:before{content:"\f18e"}.fa-arrow-circle-o-left:before{content:"\f190"}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:"\f191"}.fa-dot-circle-o:before{content:"\f192"}.fa-wheelchair:before{content:"\f193"}.fa-vimeo-square:before{content:"\f194"}.fa-turkish-lira:before,.fa-try:before{content:"\f195"}.fa-plus-square-o:before{content:"\f196"}.fa-space-shuttle:before{content:"\f197"}.fa-slack:before{content:"\f198"}.fa-envelope-square:before{content:"\f199"}.fa-wordpress:before{content:"\f19a"}.fa-openid:before{content:"\f19b"}.fa-institution:before,.fa-bank:before,.fa-university:before{content:"\f19c"}.fa-mortar-board:before,.fa-graduation-cap:before{content:"\f19d"}.fa-yahoo:before{content:"\f19e"}.fa-google:before{content:"\f1a0"}.fa-reddit:before{content:"\f1a1"}.fa-reddit-square:before{content:"\f1a2"}.fa-stumbleupon-circle:before{content:"\f1a3"}.fa-stumbleupon:before{content:"\f1a4"}.fa-delicious:before{content:"\f1a5"}.fa-digg:before{content:"\f1a6"}.fa-pied-piper:before{content:"\f1a7"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-drupal:before{content:"\f1a9"}.fa-joomla:before{content:"\f1aa"}.fa-language:before{content:"\f1ab"}.fa-fax:before{content:"\f1ac"}.fa-building:before{content:"\f1ad"}.fa-child:before{content:"\f1ae"}.fa-paw:before{content:"\f1b0"}.fa-spoon:before{content:"\f1b1"}.fa-cube:before{content:"\f1b2"}.fa-cubes:before{content:"\f1b3"}.fa-behance:before{content:"\f1b4"}.fa-behance-square:before{content:"\f1b5"}.fa-steam:before{content:"\f1b6"}.fa-steam-square:before{content:"\f1b7"}.fa-recycle:before{content:"\f1b8"}.fa-automobile:before,.fa-car:before{content:"\f1b9"}.fa-cab:before,.fa-taxi:before{content:"\f1ba"}.fa-tree:before{content:"\f1bb"}.fa-spotify:before{content:"\f1bc"}.fa-deviantart:before{content:"\f1bd"}.fa-soundcloud:before{content:"\f1be"}.fa-database:before{content:"\f1c0"}.fa-file-pdf-o:before{content:"\f1c1"}.fa-file-word-o:before{content:"\f1c2"}.fa-file-excel-o:before{content:"\f1c3"}.fa-file-powerpoint-o:before{content:"\f1c4"}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:"\f1c5"}.fa-file-zip-o:before,.fa-file-archive-o:before{content:"\f1c6"}.fa-file-sound-o:before,.fa-file-audio-o:before{content:"\f1c7"}.fa-file-movie-o:before,.fa-file-video-o:before{content:"\f1c8"}.fa-file-code-o:before{content:"\f1c9"}.fa-vine:before{content:"\f1ca"}.fa-codepen:before{content:"\f1cb"}.fa-jsfiddle:before{content:"\f1cc"}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:"\f1cd"}.fa-circle-o-notch:before{content:"\f1ce"}.fa-ra:before,.fa-rebel:before{content:"\f1d0"}.fa-ge:before,.fa-empire:before{content:"\f1d1"}.fa-git-square:before{content:"\f1d2"}.fa-git:before{content:"\f1d3"}.fa-y-combinator-square:before,.fa-yc-square:before,.fa-hacker-news:before{content:"\f1d4"}.fa-tencent-weibo:before{content:"\f1d5"}.fa-qq:before{content:"\f1d6"}.fa-wechat:before,.fa-weixin:before{content:"\f1d7"}.fa-send:before,.fa-paper-plane:before{content:"\f1d8"}.fa-send-o:before,.fa-paper-plane-o:before{content:"\f1d9"}.fa-history:before{content:"\f1da"}.fa-circle-thin:before{content:"\f1db"}.fa-header:before{content:"\f1dc"}.fa-paragraph:before{content:"\f1dd"}.fa-sliders:before{content:"\f1de"}.fa-share-alt:before{content:"\f1e0"}.fa-share-alt-square:before{content:"\f1e1"}.fa-bomb:before{content:"\f1e2"}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:"\f1e3"}.fa-tty:before{content:"\f1e4"}.fa-binoculars:before{content:"\f1e5"}.fa-plug:before{content:"\f1e6"}.fa-slideshare:before{content:"\f1e7"}.fa-twitch:before{content:"\f1e8"}.fa-yelp:before{content:"\f1e9"}.fa-newspaper-o:before{content:"\f1ea"}.fa-wifi:before{content:"\f1eb"}.fa-calculator:before{content:"\f1ec"}.fa-paypal:before{content:"\f1ed"}.fa-google-wallet:before{content:"\f1ee"}.fa-cc-visa:before{content:"\f1f0"}.fa-cc-mastercard:before{content:"\f1f1"}.fa-cc-discover:before{content:"\f1f2"}.fa-cc-amex:before{content:"\f1f3"}.fa-cc-paypal:before{content:"\f1f4"}.fa-cc-stripe:before{content:"\f1f5"}.fa-bell-slash:before{content:"\f1f6"}.fa-bell-slash-o:before{content:"\f1f7"}.fa-trash:before{content:"\f1f8"}.fa-copyright:before{content:"\f1f9"}.fa-at:before{content:"\f1fa"}.fa-eyedropper:before{content:"\f1fb"}.fa-paint-brush:before{content:"\f1fc"}.fa-birthday-cake:before{content:"\f1fd"}.fa-area-chart:before{content:"\f1fe"}.fa-pie-chart:before{content:"\f200"}.fa-line-chart:before{content:"\f201"}.fa-lastfm:before{content:"\f202"}.fa-lastfm-square:before{content:"\f203"}.fa-toggle-off:before{content:"\f204"}.fa-toggle-on:before{content:"\f205"}.fa-bicycle:before{content:"\f206"}.fa-bus:before{content:"\f207"}.fa-ioxhost:before{content:"\f208"}.fa-angellist:before{content:"\f209"}.fa-cc:before{content:"\f20a"}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:"\f20b"}.fa-meanpath:before{content:"\f20c"}.fa-buysellads:before{content:"\f20d"}.fa-connectdevelop:before{content:"\f20e"}.fa-dashcube:before{content:"\f210"}.fa-forumbee:before{content:"\f211"}.fa-leanpub:before{content:"\f212"}.fa-sellsy:before{content:"\f213"}.fa-shirtsinbulk:before{content:"\f214"}.fa-simplybuilt:before{content:"\f215"}.fa-skyatlas:before{content:"\f216"}.fa-cart-plus:before{content:"\f217"}.fa-cart-arrow-down:before{content:"\f218"}.fa-diamond:before{content:"\f219"}.fa-ship:before{content:"\f21a"}.fa-user-secret:before{content:"\f21b"}.fa-motorcycle:before{content:"\f21c"}.fa-street-view:before{content:"\f21d"}.fa-heartbeat:before{content:"\f21e"}.fa-venus:before{content:"\f221"}.fa-mars:before{content:"\f222"}.fa-mercury:before{content:"\f223"}.fa-intersex:before,.fa-transgender:before{content:"\f224"}.fa-transgender-alt:before{content:"\f225"}.fa-venus-double:before{content:"\f226"}.fa-mars-double:before{content:"\f227"}.fa-venus-mars:before{content:"\f228"}.fa-mars-stroke:before{content:"\f229"}.fa-mars-stroke-v:before{content:"\f22a"}.fa-mars-stroke-h:before{content:"\f22b"}.fa-neuter:before{content:"\f22c"}.fa-genderless:before{content:"\f22d"}.fa-facebook-official:before{content:"\f230"}.fa-pinterest-p:before{content:"\f231"}.fa-whatsapp:before{content:"\f232"}.fa-server:before{content:"\f233"}.fa-user-plus:before{content:"\f234"}.fa-user-times:before{content:"\f235"}.fa-hotel:before,.fa-bed:before{content:"\f236"}.fa-viacoin:before{content:"\f237"}.fa-train:before{content:"\f238"}.fa-subway:before{content:"\f239"}.fa-medium:before{content:"\f23a"}.fa-yc:before,.fa-y-combinator:before{content:"\f23b"}.fa-optin-monster:before{content:"\f23c"}.fa-opencart:before{content:"\f23d"}.fa-expeditedssl:before{content:"\f23e"}.fa-battery-4:before,.fa-battery-full:before{content:"\f240"}.fa-battery-3:before,.fa-battery-three-quarters:before{content:"\f241"}.fa-battery-2:before,.fa-battery-half:before{content:"\f242"}.fa-battery-1:before,.fa-battery-quarter:before{content:"\f243"}.fa-battery-0:before,.fa-battery-empty:before{content:"\f244"}.fa-mouse-pointer:before{content:"\f245"}.fa-i-cursor:before{content:"\f246"}.fa-object-group:before{content:"\f247"}.fa-object-ungroup:before{content:"\f248"}.fa-sticky-note:before{content:"\f249"}.fa-sticky-note-o:before{content:"\f24a"}.fa-cc-jcb:before{content:"\f24b"}.fa-cc-diners-club:before{content:"\f24c"}.fa-clone:before{content:"\f24d"}.fa-balance-scale:before{content:"\f24e"}.fa-hourglass-o:before{content:"\f250"}.fa-hourglass-1:before,.fa-hourglass-start:before{content:"\f251"}.fa-hourglass-2:before,.fa-hourglass-half:before{content:"\f252"}.fa-hourglass-3:before,.fa-hourglass-end:before{content:"\f253"}.fa-hourglass:before{content:"\f254"}.fa-hand-grab-o:before,.fa-hand-rock-o:before{content:"\f255"}.fa-hand-stop-o:before,.fa-hand-paper-o:before{content:"\f256"}.fa-hand-scissors-o:before{content:"\f257"}.fa-hand-lizard-o:before{content:"\f258"}.fa-hand-spock-o:before{content:"\f259"}.fa-hand-pointer-o:before{content:"\f25a"}.fa-hand-peace-o:before{content:"\f25b"}.fa-trademark:before{content:"\f25c"}.fa-registered:before{content:"\f25d"}.fa-creative-commons:before{content:"\f25e"}.fa-gg:before{content:"\f260"}.fa-gg-circle:before{content:"\f261"}.fa-tripadvisor:before{content:"\f262"}.fa-odnoklassniki:before{content:"\f263"}.fa-odnoklassniki-square:before{content:"\f264"}.fa-get-pocket:before{content:"\f265"}.fa-wikipedia-w:before{content:"\f266"}.fa-safari:before{content:"\f267"}.fa-chrome:before{content:"\f268"}.fa-firefox:before{content:"\f269"}.fa-opera:before{content:"\f26a"}.fa-internet-explorer:before{content:"\f26b"}.fa-tv:before,.fa-television:before{content:"\f26c"}.fa-contao:before{content:"\f26d"}.fa-500px:before{content:"\f26e"}.fa-amazon:before{content:"\f270"}.fa-calendar-plus-o:before{content:"\f271"}.fa-calendar-minus-o:before{content:"\f272"}.fa-calendar-times-o:before{content:"\f273"}.fa-calendar-check-o:before{content:"\f274"}.fa-industry:before{content:"\f275"}.fa-map-pin:before{content:"\f276"}.fa-map-signs:before{content:"\f277"}.fa-map-o:before{content:"\f278"}.fa-map:before{content:"\f279"}.fa-commenting:before{content:"\f27a"}.fa-commenting-o:before{content:"\f27b"}.fa-houzz:before{content:"\f27c"}.fa-vimeo:before{content:"\f27d"}.fa-black-tie:before{content:"\f27e"}.fa-fonticons:before{content:"\f280"} diff --git a/docs/guide/FontAwesome/fonts/FontAwesome.ttf b/docs/guide/FontAwesome/fonts/FontAwesome.ttf new file mode 100644 index 0000000..d7994e1 Binary files /dev/null and b/docs/guide/FontAwesome/fonts/FontAwesome.ttf differ diff --git a/docs/guide/FontAwesome/fonts/fontawesome-webfont.eot b/docs/guide/FontAwesome/fonts/fontawesome-webfont.eot new file mode 100644 index 0000000..a30335d Binary files /dev/null and b/docs/guide/FontAwesome/fonts/fontawesome-webfont.eot differ diff --git a/docs/guide/FontAwesome/fonts/fontawesome-webfont.svg b/docs/guide/FontAwesome/fonts/fontawesome-webfont.svg new file mode 100644 index 0000000..6fd19ab --- /dev/null +++ b/docs/guide/FontAwesome/fonts/fontawesome-webfont.svg @@ -0,0 +1,640 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/guide/FontAwesome/fonts/fontawesome-webfont.ttf b/docs/guide/FontAwesome/fonts/fontawesome-webfont.ttf new file mode 100644 index 0000000..d7994e1 Binary files /dev/null and b/docs/guide/FontAwesome/fonts/fontawesome-webfont.ttf differ diff --git a/docs/guide/FontAwesome/fonts/fontawesome-webfont.woff b/docs/guide/FontAwesome/fonts/fontawesome-webfont.woff new file mode 100644 index 0000000..6fd4ede Binary files /dev/null and b/docs/guide/FontAwesome/fonts/fontawesome-webfont.woff differ diff --git a/docs/guide/FontAwesome/fonts/fontawesome-webfont.woff2 b/docs/guide/FontAwesome/fonts/fontawesome-webfont.woff2 new file mode 100644 index 0000000..5560193 Binary files /dev/null and b/docs/guide/FontAwesome/fonts/fontawesome-webfont.woff2 differ diff --git a/docs/guide/ayu-highlight.css b/docs/guide/ayu-highlight.css new file mode 100644 index 0000000..786063f --- /dev/null +++ b/docs/guide/ayu-highlight.css @@ -0,0 +1,71 @@ +/* +Based off of the Ayu theme +Original by Dempfi (https://github.com/dempfi/ayu) +*/ + +.hljs { + display: block; + overflow-x: auto; + background: #191f26; + color: #e6e1cf; + padding: 0.5em; +} + +.hljs-comment, +.hljs-quote, +.hljs-meta { + color: #5c6773; + font-style: italic; +} + +.hljs-variable, +.hljs-template-variable, +.hljs-attribute, +.hljs-attr, +.hljs-regexp, +.hljs-link, +.hljs-selector-id, +.hljs-selector-class { + color: #ff7733; +} + +.hljs-number, +.hljs-builtin-name, +.hljs-literal, +.hljs-type, +.hljs-params { + color: #ffee99; +} + +.hljs-string, +.hljs-bullet { + color: #b8cc52; +} + +.hljs-title, +.hljs-built_in, +.hljs-section { + color: #ffb454; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-symbol { + color: #ff7733; +} + +.hljs-name { + color: #36a3d9; +} + +.hljs-tag { + color: #00568d; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} diff --git a/docs/guide/book.js b/docs/guide/book.js new file mode 100644 index 0000000..c9c2f4d --- /dev/null +++ b/docs/guide/book.js @@ -0,0 +1,600 @@ +"use strict"; + +// Fix back button cache problem +window.onunload = function () { }; + +// Global variable, shared between modules +function playpen_text(playpen) { + let code_block = playpen.querySelector("code"); + + if (window.ace && code_block.classList.contains("editable")) { + let editor = window.ace.edit(code_block); + return editor.getValue(); + } else { + return code_block.textContent; + } +} + +(function codeSnippets() { + // Hide Rust code lines prepended with a specific character + var hiding_character = "#"; + + function fetch_with_timeout(url, options, timeout = 6000) { + return Promise.race([ + fetch(url, options), + new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeout)) + ]); + } + + var playpens = Array.from(document.querySelectorAll(".playpen")); + if (playpens.length > 0) { + fetch_with_timeout("https://play.rust-lang.org/meta/crates", { + headers: { + 'Content-Type': "application/json", + }, + method: 'POST', + mode: 'cors', + }) + .then(response => response.json()) + .then(response => { + // get list of crates available in the rust playground + let playground_crates = response.crates.map(item => item["id"]); + playpens.forEach(block => handle_crate_list_update(block, playground_crates)); + }); + } + + function handle_crate_list_update(playpen_block, playground_crates) { + // update the play buttons after receiving the response + update_play_button(playpen_block, playground_crates); + + // and install on change listener to dynamically update ACE editors + if (window.ace) { + let code_block = playpen_block.querySelector("code"); + if (code_block.classList.contains("editable")) { + let editor = window.ace.edit(code_block); + editor.addEventListener("change", function (e) { + update_play_button(playpen_block, playground_crates); + }); + } + } + } + + // updates the visibility of play button based on `no_run` class and + // used crates vs ones available on http://play.rust-lang.org + function update_play_button(pre_block, playground_crates) { + var play_button = pre_block.querySelector(".play-button"); + + // skip if code is `no_run` + if (pre_block.querySelector('code').classList.contains("no_run")) { + play_button.classList.add("hidden"); + return; + } + + // get list of `extern crate`'s from snippet + var txt = playpen_text(pre_block); + var re = /extern\s+crate\s+([a-zA-Z_0-9]+)\s*;/g; + var snippet_crates = []; + var item; + while (item = re.exec(txt)) { + snippet_crates.push(item[1]); + } + + // check if all used crates are available on play.rust-lang.org + var all_available = snippet_crates.every(function (elem) { + return playground_crates.indexOf(elem) > -1; + }); + + if (all_available) { + play_button.classList.remove("hidden"); + } else { + play_button.classList.add("hidden"); + } + } + + function run_rust_code(code_block) { + var result_block = code_block.querySelector(".result"); + if (!result_block) { + result_block = document.createElement('code'); + result_block.className = 'result hljs language-bash'; + + code_block.append(result_block); + } + + let text = playpen_text(code_block); + + var params = { + version: "stable", + optimize: "0", + code: text + }; + + if (text.indexOf("#![feature") !== -1) { + params.version = "nightly"; + } + + result_block.innerText = "Running..."; + + fetch_with_timeout("https://play.rust-lang.org/evaluate.json", { + headers: { + 'Content-Type': "application/json", + }, + method: 'POST', + mode: 'cors', + body: JSON.stringify(params) + }) + .then(response => response.json()) + .then(response => result_block.innerText = response.result) + .catch(error => result_block.innerText = "Playground Communication: " + error.message); + } + + // Syntax highlighting Configuration + hljs.configure({ + tabReplace: ' ', // 4 spaces + languages: [], // Languages used for auto-detection + }); + + if (window.ace) { + // language-rust class needs to be removed for editable + // blocks or highlightjs will capture events + Array + .from(document.querySelectorAll('code.editable')) + .forEach(function (block) { block.classList.remove('language-rust'); }); + + Array + .from(document.querySelectorAll('code:not(.editable)')) + .forEach(function (block) { hljs.highlightBlock(block); }); + } else { + Array + .from(document.querySelectorAll('code')) + .forEach(function (block) { hljs.highlightBlock(block); }); + } + + // Adding the hljs class gives code blocks the color css + // even if highlighting doesn't apply + Array + .from(document.querySelectorAll('code')) + .forEach(function (block) { block.classList.add('hljs'); }); + + Array.from(document.querySelectorAll("code.language-rust")).forEach(function (block) { + + var code_block = block; + var pre_block = block.parentNode; + // hide lines + var lines = code_block.innerHTML.split("\n"); + var first_non_hidden_line = false; + var lines_hidden = false; + var trimmed_line = ""; + + for (var n = 0; n < lines.length; n++) { + trimmed_line = lines[n].trim(); + if (trimmed_line[0] == hiding_character && trimmed_line[1] != hiding_character) { + if (first_non_hidden_line) { + lines[n] = "" + "\n" + lines[n].replace(/(\s*)# ?/, "$1") + ""; + } + else { + lines[n] = "" + lines[n].replace(/(\s*)# ?/, "$1") + "\n" + ""; + } + lines_hidden = true; + } + else if (first_non_hidden_line) { + lines[n] = "\n" + lines[n]; + } + else { + first_non_hidden_line = true; + } + if (trimmed_line[0] == hiding_character && trimmed_line[1] == hiding_character) { + lines[n] = lines[n].replace("##", "#") + } + } + code_block.innerHTML = lines.join(""); + + // If no lines were hidden, return + if (!lines_hidden) { return; } + + var buttons = document.createElement('div'); + buttons.className = 'buttons'; + buttons.innerHTML = ""; + + // add expand button + pre_block.insertBefore(buttons, pre_block.firstChild); + + pre_block.querySelector('.buttons').addEventListener('click', function (e) { + if (e.target.classList.contains('fa-expand')) { + var lines = pre_block.querySelectorAll('span.hidden'); + + e.target.classList.remove('fa-expand'); + e.target.classList.add('fa-compress'); + e.target.title = 'Hide lines'; + e.target.setAttribute('aria-label', e.target.title); + + Array.from(lines).forEach(function (line) { + line.classList.remove('hidden'); + line.classList.add('unhidden'); + }); + } else if (e.target.classList.contains('fa-compress')) { + var lines = pre_block.querySelectorAll('span.unhidden'); + + e.target.classList.remove('fa-compress'); + e.target.classList.add('fa-expand'); + e.target.title = 'Show hidden lines'; + e.target.setAttribute('aria-label', e.target.title); + + Array.from(lines).forEach(function (line) { + line.classList.remove('unhidden'); + line.classList.add('hidden'); + }); + } + }); + }); + + Array.from(document.querySelectorAll('pre code')).forEach(function (block) { + var pre_block = block.parentNode; + if (!pre_block.classList.contains('playpen')) { + var buttons = pre_block.querySelector(".buttons"); + if (!buttons) { + buttons = document.createElement('div'); + buttons.className = 'buttons'; + pre_block.insertBefore(buttons, pre_block.firstChild); + } + + var clipButton = document.createElement('button'); + clipButton.className = 'fa fa-copy clip-button'; + clipButton.title = 'Copy to clipboard'; + clipButton.setAttribute('aria-label', clipButton.title); + clipButton.innerHTML = ''; + + buttons.insertBefore(clipButton, buttons.firstChild); + } + }); + + // Process playpen code blocks + Array.from(document.querySelectorAll(".playpen")).forEach(function (pre_block) { + // Add play button + var buttons = pre_block.querySelector(".buttons"); + if (!buttons) { + buttons = document.createElement('div'); + buttons.className = 'buttons'; + pre_block.insertBefore(buttons, pre_block.firstChild); + } + + var runCodeButton = document.createElement('button'); + runCodeButton.className = 'fa fa-play play-button'; + runCodeButton.hidden = true; + runCodeButton.title = 'Run this code'; + runCodeButton.setAttribute('aria-label', runCodeButton.title); + + var copyCodeClipboardButton = document.createElement('button'); + copyCodeClipboardButton.className = 'fa fa-copy clip-button'; + copyCodeClipboardButton.innerHTML = ''; + copyCodeClipboardButton.title = 'Copy to clipboard'; + copyCodeClipboardButton.setAttribute('aria-label', copyCodeClipboardButton.title); + + buttons.insertBefore(runCodeButton, buttons.firstChild); + buttons.insertBefore(copyCodeClipboardButton, buttons.firstChild); + + runCodeButton.addEventListener('click', function (e) { + run_rust_code(pre_block); + }); + + let code_block = pre_block.querySelector("code"); + if (window.ace && code_block.classList.contains("editable")) { + var undoChangesButton = document.createElement('button'); + undoChangesButton.className = 'fa fa-history reset-button'; + undoChangesButton.title = 'Undo changes'; + undoChangesButton.setAttribute('aria-label', undoChangesButton.title); + + buttons.insertBefore(undoChangesButton, buttons.firstChild); + + undoChangesButton.addEventListener('click', function () { + let editor = window.ace.edit(code_block); + editor.setValue(editor.originalCode); + editor.clearSelection(); + }); + } + }); +})(); + +(function themes() { + var html = document.querySelector('html'); + var themeToggleButton = document.getElementById('theme-toggle'); + var themePopup = document.getElementById('theme-list'); + var themeColorMetaTag = document.querySelector('meta[name="theme-color"]'); + var stylesheets = { + ayuHighlight: document.querySelector("[href$='ayu-highlight.css']"), + tomorrowNight: document.querySelector("[href$='tomorrow-night.css']"), + highlight: document.querySelector("[href$='highlight.css']"), + }; + + function showThemes() { + themePopup.style.display = 'block'; + themeToggleButton.setAttribute('aria-expanded', true); + themePopup.querySelector("button#" + document.body.className).focus(); + } + + function hideThemes() { + themePopup.style.display = 'none'; + themeToggleButton.setAttribute('aria-expanded', false); + themeToggleButton.focus(); + } + + function set_theme(theme) { + let ace_theme; + + if (theme == 'coal' || theme == 'navy') { + stylesheets.ayuHighlight.disabled = true; + stylesheets.tomorrowNight.disabled = false; + stylesheets.highlight.disabled = true; + + ace_theme = "ace/theme/tomorrow_night"; + } else if (theme == 'ayu') { + stylesheets.ayuHighlight.disabled = false; + stylesheets.tomorrowNight.disabled = true; + stylesheets.highlight.disabled = true; + + ace_theme = "ace/theme/tomorrow_night"; + } else { + stylesheets.ayuHighlight.disabled = true; + stylesheets.tomorrowNight.disabled = true; + stylesheets.highlight.disabled = false; + + ace_theme = "ace/theme/dawn"; + } + + setTimeout(function () { + themeColorMetaTag.content = getComputedStyle(document.body).backgroundColor; + }, 1); + + if (window.ace && window.editors) { + window.editors.forEach(function (editor) { + editor.setTheme(ace_theme); + }); + } + + var previousTheme; + try { previousTheme = localStorage.getItem('mdbook-theme'); } catch (e) { } + if (previousTheme === null || previousTheme === undefined) { previousTheme = 'light'; } + + try { localStorage.setItem('mdbook-theme', theme); } catch (e) { } + + document.body.className = theme; + html.classList.remove(previousTheme); + html.classList.add(theme); + } + + // Set theme + var theme; + try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } + if (theme === null || theme === undefined) { theme = 'light'; } + + set_theme(theme); + + themeToggleButton.addEventListener('click', function () { + if (themePopup.style.display === 'block') { + hideThemes(); + } else { + showThemes(); + } + }); + + themePopup.addEventListener('click', function (e) { + var theme = e.target.id || e.target.parentElement.id; + set_theme(theme); + }); + + themePopup.addEventListener('focusout', function(e) { + // e.relatedTarget is null in Safari and Firefox on macOS (see workaround below) + if (!!e.relatedTarget && !themeToggleButton.contains(e.relatedTarget) && !themePopup.contains(e.relatedTarget)) { + hideThemes(); + } + }); + + // Should not be needed, but it works around an issue on macOS & iOS: https://github.com/rust-lang-nursery/mdBook/issues/628 + document.addEventListener('click', function(e) { + if (themePopup.style.display === 'block' && !themeToggleButton.contains(e.target) && !themePopup.contains(e.target)) { + hideThemes(); + } + }); + + document.addEventListener('keydown', function (e) { + if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; } + if (!themePopup.contains(e.target)) { return; } + + switch (e.key) { + case 'Escape': + e.preventDefault(); + hideThemes(); + break; + case 'ArrowUp': + e.preventDefault(); + var li = document.activeElement.parentElement; + if (li && li.previousElementSibling) { + li.previousElementSibling.querySelector('button').focus(); + } + break; + case 'ArrowDown': + e.preventDefault(); + var li = document.activeElement.parentElement; + if (li && li.nextElementSibling) { + li.nextElementSibling.querySelector('button').focus(); + } + break; + case 'Home': + e.preventDefault(); + themePopup.querySelector('li:first-child button').focus(); + break; + case 'End': + e.preventDefault(); + themePopup.querySelector('li:last-child button').focus(); + break; + } + }); +})(); + +(function sidebar() { + var html = document.querySelector("html"); + var sidebar = document.getElementById("sidebar"); + var sidebarLinks = document.querySelectorAll('#sidebar a'); + var sidebarToggleButton = document.getElementById("sidebar-toggle"); + var firstContact = null; + + function showSidebar() { + html.classList.remove('sidebar-hidden') + html.classList.add('sidebar-visible'); + Array.from(sidebarLinks).forEach(function (link) { + link.setAttribute('tabIndex', 0); + }); + sidebarToggleButton.setAttribute('aria-expanded', true); + sidebar.setAttribute('aria-hidden', false); + try { localStorage.setItem('mdbook-sidebar', 'visible'); } catch (e) { } + } + + function hideSidebar() { + html.classList.remove('sidebar-visible') + html.classList.add('sidebar-hidden'); + Array.from(sidebarLinks).forEach(function (link) { + link.setAttribute('tabIndex', -1); + }); + sidebarToggleButton.setAttribute('aria-expanded', false); + sidebar.setAttribute('aria-hidden', true); + try { localStorage.setItem('mdbook-sidebar', 'hidden'); } catch (e) { } + } + + // Toggle sidebar + sidebarToggleButton.addEventListener('click', function sidebarToggle() { + if (html.classList.contains("sidebar-hidden")) { + showSidebar(); + } else if (html.classList.contains("sidebar-visible")) { + hideSidebar(); + } else { + if (getComputedStyle(sidebar)['transform'] === 'none') { + hideSidebar(); + } else { + showSidebar(); + } + } + }); + + document.addEventListener('touchstart', function (e) { + firstContact = { + x: e.touches[0].clientX, + time: Date.now() + }; + }, { passive: true }); + + document.addEventListener('touchmove', function (e) { + if (!firstContact) + return; + + var curX = e.touches[0].clientX; + var xDiff = curX - firstContact.x, + tDiff = Date.now() - firstContact.time; + + if (tDiff < 250 && Math.abs(xDiff) >= 150) { + if (xDiff >= 0 && firstContact.x < Math.min(document.body.clientWidth * 0.25, 300)) + showSidebar(); + else if (xDiff < 0 && curX < 300) + hideSidebar(); + + firstContact = null; + } + }, { passive: true }); + + // Scroll sidebar to current active section + var activeSection = sidebar.querySelector(".active"); + if (activeSection) { + sidebar.scrollTop = activeSection.offsetTop; + } +})(); + +(function chapterNavigation() { + document.addEventListener('keydown', function (e) { + if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; } + if (window.search && window.search.hasFocus()) { return; } + + switch (e.key) { + case 'ArrowRight': + e.preventDefault(); + var nextButton = document.querySelector('.nav-chapters.next'); + if (nextButton) { + window.location.href = nextButton.href; + } + break; + case 'ArrowLeft': + e.preventDefault(); + var previousButton = document.querySelector('.nav-chapters.previous'); + if (previousButton) { + window.location.href = previousButton.href; + } + break; + } + }); +})(); + +(function clipboard() { + var clipButtons = document.querySelectorAll('.clip-button'); + + function hideTooltip(elem) { + elem.firstChild.innerText = ""; + elem.className = 'fa fa-copy clip-button'; + } + + function showTooltip(elem, msg) { + elem.firstChild.innerText = msg; + elem.className = 'fa fa-copy tooltipped'; + } + + var clipboardSnippets = new Clipboard('.clip-button', { + text: function (trigger) { + hideTooltip(trigger); + let playpen = trigger.closest("pre"); + return playpen_text(playpen); + } + }); + + Array.from(clipButtons).forEach(function (clipButton) { + clipButton.addEventListener('mouseout', function (e) { + hideTooltip(e.currentTarget); + }); + }); + + clipboardSnippets.on('success', function (e) { + e.clearSelection(); + showTooltip(e.trigger, "Copied!"); + }); + + clipboardSnippets.on('error', function (e) { + showTooltip(e.trigger, "Clipboard error!"); + }); +})(); + +(function scrollToTop () { + var menuTitle = document.querySelector('.menu-title'); + + menuTitle.addEventListener('click', function () { + document.scrollingElement.scrollTo({ top: 0, behavior: 'smooth' }); + }); +})(); + +(function autoHideMenu() { + var menu = document.getElementById('menu-bar'); + + var previousScrollTop = document.scrollingElement.scrollTop; + + document.addEventListener('scroll', function () { + if (menu.classList.contains('folded') && document.scrollingElement.scrollTop < previousScrollTop) { + menu.classList.remove('folded'); + } else if (!menu.classList.contains('folded') && document.scrollingElement.scrollTop > previousScrollTop) { + menu.classList.add('folded'); + } + + if (!menu.classList.contains('bordered') && document.scrollingElement.scrollTop > 0) { + menu.classList.add('bordered'); + } + + if (menu.classList.contains('bordered') && document.scrollingElement.scrollTop === 0) { + menu.classList.remove('bordered'); + } + + previousScrollTop = document.scrollingElement.scrollTop; + }, { passive: true }); +})(); diff --git a/docs/guide/chapter_1.html b/docs/guide/chapter_1.html new file mode 100644 index 0000000..5ed75f3 --- /dev/null +++ b/docs/guide/chapter_1.html @@ -0,0 +1,184 @@ + + + + + + Chapter 1 - Elefren Guide + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+
+

Chapter 1

+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/guide/clipboard.min.js b/docs/guide/clipboard.min.js new file mode 100644 index 0000000..1993676 --- /dev/null +++ b/docs/guide/clipboard.min.js @@ -0,0 +1,7 @@ +/*! + * clipboard.js v1.6.1 + * https://zenorocha.github.io/clipboard.js + * + * Licensed MIT © Zeno Rocha + */ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.Clipboard=e()}}(function(){var e,t,n;return function e(t,n,o){function i(a,c){if(!n[a]){if(!t[a]){var l="function"==typeof require&&require;if(!c&&l)return l(a,!0);if(r)return r(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var s=n[a]={exports:{}};t[a][0].call(s.exports,function(e){var n=t[a][1][e];return i(n?n:e)},s,s.exports,e,t,n,o)}return n[a].exports}for(var r="function"==typeof require&&require,a=0;a0&&void 0!==arguments[0]?arguments[0]:{};this.action=t.action,this.emitter=t.emitter,this.target=t.target,this.text=t.text,this.trigger=t.trigger,this.selectedText=""}},{key:"initSelection",value:function e(){this.text?this.selectFake():this.target&&this.selectTarget()}},{key:"selectFake",value:function e(){var t=this,n="rtl"==document.documentElement.getAttribute("dir");this.removeFake(),this.fakeHandlerCallback=function(){return t.removeFake()},this.fakeHandler=document.body.addEventListener("click",this.fakeHandlerCallback)||!0,this.fakeElem=document.createElement("textarea"),this.fakeElem.style.fontSize="12pt",this.fakeElem.style.border="0",this.fakeElem.style.padding="0",this.fakeElem.style.margin="0",this.fakeElem.style.position="absolute",this.fakeElem.style[n?"right":"left"]="-9999px";var o=window.pageYOffset||document.documentElement.scrollTop;this.fakeElem.style.top=o+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,document.body.appendChild(this.fakeElem),this.selectedText=(0,i.default)(this.fakeElem),this.copyText()}},{key:"removeFake",value:function e(){this.fakeHandler&&(document.body.removeEventListener("click",this.fakeHandlerCallback),this.fakeHandler=null,this.fakeHandlerCallback=null),this.fakeElem&&(document.body.removeChild(this.fakeElem),this.fakeElem=null)}},{key:"selectTarget",value:function e(){this.selectedText=(0,i.default)(this.target),this.copyText()}},{key:"copyText",value:function e(){var t=void 0;try{t=document.execCommand(this.action)}catch(e){t=!1}this.handleResult(t)}},{key:"handleResult",value:function e(t){this.emitter.emit(t?"success":"error",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})}},{key:"clearSelection",value:function e(){this.target&&this.target.blur(),window.getSelection().removeAllRanges()}},{key:"destroy",value:function e(){this.removeFake()}},{key:"action",set:function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"copy";if(this._action=t,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function e(){return this._action}},{key:"target",set:function e(t){if(void 0!==t){if(!t||"object"!==("undefined"==typeof t?"undefined":r(t))||1!==t.nodeType)throw new Error('Invalid "target" value, use a valid Element');if("copy"===this.action&&t.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if("cut"===this.action&&(t.hasAttribute("readonly")||t.hasAttribute("disabled")))throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');this._target=t}},get:function e(){return this._target}}]),e}();e.exports=c})},{select:5}],8:[function(t,n,o){!function(i,r){if("function"==typeof e&&e.amd)e(["module","./clipboard-action","tiny-emitter","good-listener"],r);else if("undefined"!=typeof o)r(n,t("./clipboard-action"),t("tiny-emitter"),t("good-listener"));else{var a={exports:{}};r(a,i.clipboardAction,i.tinyEmitter,i.goodListener),i.clipboard=a.exports}}(this,function(e,t,n,o){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function c(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function l(e,t){var n="data-clipboard-"+e;if(t.hasAttribute(n))return t.getAttribute(n)}var u=i(t),s=i(n),f=i(o),d=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{};this.action="function"==typeof t.action?t.action:this.defaultAction,this.target="function"==typeof t.target?t.target:this.defaultTarget,this.text="function"==typeof t.text?t.text:this.defaultText}},{key:"listenClick",value:function e(t){var n=this;this.listener=(0,f.default)(t,"click",function(e){return n.onClick(e)})}},{key:"onClick",value:function e(t){var n=t.delegateTarget||t.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new u.default({action:this.action(n),target:this.target(n),text:this.text(n),trigger:n,emitter:this})}},{key:"defaultAction",value:function e(t){return l("action",t)}},{key:"defaultTarget",value:function e(t){var n=l("target",t);if(n)return document.querySelector(n)}},{key:"defaultText",value:function e(t){return l("text",t)}},{key:"destroy",value:function e(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)}}],[{key:"isSupported",value:function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:["copy","cut"],n="string"==typeof t?[t]:t,o=!!document.queryCommandSupported;return n.forEach(function(e){o=o&&!!document.queryCommandSupported(e)}),o}}]),t}(s.default);e.exports=h})},{"./clipboard-action":7,"good-listener":4,"tiny-emitter":6}]},{},[8])(8)}); \ No newline at end of file diff --git a/docs/guide/css/chrome.css b/docs/guide/css/chrome.css new file mode 100644 index 0000000..82883e6 --- /dev/null +++ b/docs/guide/css/chrome.css @@ -0,0 +1,417 @@ +/* CSS for UI elements (a.k.a. chrome) */ + +@import 'variables.css'; + +::-webkit-scrollbar { + background: var(--bg); +} +::-webkit-scrollbar-thumb { + background: var(--scrollbar); +} + +#searchresults a, +.content a:link, +a:visited, +a > .hljs { + color: var(--links); +} + +/* Menu Bar */ + +#menu-bar { + position: -webkit-sticky; + position: sticky; + top: 0; + z-index: 101; + margin: auto calc(0px - var(--page-padding)); +} +#menu-bar > #menu-bar-sticky-container { + display: flex; + flex-wrap: wrap; + background-color: var(--bg); + border-bottom-color: var(--bg); + border-bottom-width: 1px; + border-bottom-style: solid; +} +.js #menu-bar > #menu-bar-sticky-container { + transition: transform 0.3s; +} +#menu-bar.bordered > #menu-bar-sticky-container { + border-bottom-color: var(--table-border-color); +} +#menu-bar i, #menu-bar .icon-button { + position: relative; + padding: 0 8px; + z-index: 10; + line-height: 50px; + cursor: pointer; + transition: color 0.5s; +} +@media only screen and (max-width: 420px) { + #menu-bar i, #menu-bar .icon-button { + padding: 0 5px; + } +} + +.icon-button { + border: none; + background: none; + padding: 0; + color: inherit; +} +.icon-button i { + margin: 0; +} + +#print-button { + margin: 0 15px; +} + +html:not(.sidebar-visible) #menu-bar:not(:hover).folded > #menu-bar-sticky-container { + transform: translateY(-60px); +} + +.left-buttons { + display: flex; + margin: 0 5px; +} +.no-js .left-buttons { + display: none; +} + +.menu-title { + display: inline-block; + font-weight: 200; + font-size: 20px; + line-height: 50px; + text-align: center; + margin: 0; + flex: 1; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.js .menu-title { + cursor: pointer; +} + +.menu-bar, +.menu-bar:visited, +.nav-chapters, +.nav-chapters:visited, +.mobile-nav-chapters, +.mobile-nav-chapters:visited, +.menu-bar .icon-button, +.menu-bar a i { + color: var(--icons); +} + +.menu-bar i:hover, +.menu-bar .icon-button:hover, +.nav-chapters:hover, +.mobile-nav-chapters i:hover { + color: var(--icons-hover); +} + +/* Nav Icons */ + +.nav-chapters { + font-size: 2.5em; + text-align: center; + text-decoration: none; + + position: fixed; + top: 50px; /* Height of menu-bar */ + bottom: 0; + margin: 0; + max-width: 150px; + min-width: 90px; + + display: flex; + justify-content: center; + align-content: center; + flex-direction: column; + + transition: color 0.5s; +} + +.nav-chapters:hover { text-decoration: none; } + +.nav-wrapper { + margin-top: 50px; + display: none; +} + +.mobile-nav-chapters { + font-size: 2.5em; + text-align: center; + text-decoration: none; + width: 90px; + border-radius: 5px; + background-color: var(--sidebar-bg); +} + +.previous { + float: left; +} + +.next { + float: right; + right: var(--page-padding); +} + +@media only screen and (max-width: 1080px) { + .nav-wide-wrapper { display: none; } + .nav-wrapper { display: block; } +} + +@media only screen and (max-width: 1380px) { + .sidebar-visible .nav-wide-wrapper { display: none; } + .sidebar-visible .nav-wrapper { display: block; } +} + +/* Inline code */ + +:not(pre) > .hljs { + display: inline-block; + vertical-align: middle; + padding: 0.1em 0.3em; + border-radius: 3px; + color: var(--inline-code-color); +} + +a:hover > .hljs { + text-decoration: underline; +} + +pre { + position: relative; +} +pre > .buttons { + position: absolute; + z-index: 100; + right: 5px; + top: 5px; + + color: var(--sidebar-fg); + cursor: pointer; +} +pre > .buttons :hover { + color: var(--sidebar-active); +} +pre > .buttons i { + margin-left: 8px; +} +pre > .buttons button { + color: inherit; + background: transparent; + border: none; + cursor: inherit; +} +pre > .result { + margin-top: 10px; +} + +/* Search */ + +#searchresults a { + text-decoration: none; +} + +mark { + border-radius: 2px; + padding: 0 3px 1px 3px; + margin: 0 -3px -1px -3px; + background-color: var(--search-mark-bg); + transition: background-color 300ms linear; + cursor: pointer; +} + +mark.fade-out { + background-color: rgba(0,0,0,0) !important; + cursor: auto; +} + +.searchbar-outer { + margin-left: auto; + margin-right: auto; + max-width: var(--content-max-width); +} + +#searchbar { + width: 100%; + margin: 5px auto 0px auto; + padding: 10px 16px; + transition: box-shadow 300ms ease-in-out; + border: 1px solid var(--searchbar-border-color); + border-radius: 3px; + background-color: var(--searchbar-bg); + color: var(--searchbar-fg); +} +#searchbar:focus, +#searchbar.active { + box-shadow: 0 0 3px var(--searchbar-shadow-color); +} + +.searchresults-header { + font-weight: bold; + font-size: 1em; + padding: 18px 0 0 5px; + color: var(--searchresults-header-fg); +} + +.searchresults-outer { + margin-left: auto; + margin-right: auto; + max-width: var(--content-max-width); + border-bottom: 1px dashed var(--searchresults-border-color); +} + +ul#searchresults { + list-style: none; + padding-left: 20px; +} +ul#searchresults li { + margin: 10px 0px; + padding: 2px; + border-radius: 2px; +} +ul#searchresults li.focus { + background-color: var(--searchresults-li-bg); +} +ul#searchresults span.teaser { + display: block; + clear: both; + margin: 5px 0 0 20px; + font-size: 0.8em; +} +ul#searchresults span.teaser em { + font-weight: bold; + font-style: normal; +} + +/* Sidebar */ + +.sidebar { + position: fixed; + left: 0; + top: 0; + bottom: 0; + width: var(--sidebar-width); + overflow-y: auto; + padding: 10px 10px; + font-size: 0.875em; + box-sizing: border-box; + -webkit-overflow-scrolling: touch; + overscroll-behavior-y: contain; + background-color: var(--sidebar-bg); + color: var(--sidebar-fg); +} +.js .sidebar { + transition: transform 0.3s; /* Animation: slide away */ +} +.sidebar code { + line-height: 2em; +} +.sidebar-hidden .sidebar { + transform: translateX(calc(0px - var(--sidebar-width))); +} +.sidebar::-webkit-scrollbar { + background: var(--sidebar-bg); +} +.sidebar::-webkit-scrollbar-thumb { + background: var(--scrollbar); +} + +.sidebar-visible .page-wrapper { + transform: translateX(var(--sidebar-width)); +} +@media only screen and (min-width: 620px) { + .sidebar-visible .page-wrapper { + transform: none; + margin-left: var(--sidebar-width); + } +} + +.chapter { + list-style: none outside none; + padding-left: 0; + line-height: 2.2em; +} +.chapter li { + color: var(--sidebar-non-existant); +} +.chapter li a { + color: var(--sidebar-fg); + display: block; + padding: 0; + text-decoration: none; +} +.chapter li a:hover { text-decoration: none } +.chapter li .active, +a:hover { + /* Animate color change */ + color: var(--sidebar-active); +} + +.spacer { + width: 100%; + height: 3px; + margin: 5px 0px; +} +.chapter .spacer { + background-color: var(--sidebar-spacer); +} + +@media (-moz-touch-enabled: 1), (pointer: coarse) { + .chapter li a { padding: 5px 0; } + .spacer { margin: 10px 0; } +} + +.section { + list-style: none outside none; + padding-left: 20px; + line-height: 1.9em; +} + +/* Theme Menu Popup */ + +.theme-popup { + position: absolute; + left: 10px; + top: 50px; + z-index: 1000; + border-radius: 4px; + font-size: 0.7em; + color: var(--fg); + background: var(--theme-popup-bg); + border: 1px solid var(--theme-popup-border); + margin: 0; + padding: 0; + list-style: none; + display: none; +} +.theme-popup .default { + color: var(--icons); +} +.theme-popup .theme { + width: 100%; + border: 0; + margin: 0; + padding: 2px 10px; + line-height: 25px; + white-space: nowrap; + text-align: left; + cursor: pointer; + color: inherit; + background: inherit; + font-size: inherit; +} +.theme-popup .theme:hover { + background-color: var(--theme-hover); +} +.theme-popup .theme:hover:first-child, +.theme-popup .theme:hover:last-child { + border-top-left-radius: inherit; + border-top-right-radius: inherit; +} diff --git a/docs/guide/css/general.css b/docs/guide/css/general.css new file mode 100644 index 0000000..aedfb33 --- /dev/null +++ b/docs/guide/css/general.css @@ -0,0 +1,144 @@ +/* Base styles and content styles */ + +@import 'variables.css'; + +html { + font-family: "Open Sans", sans-serif; + color: var(--fg); + background-color: var(--bg); + text-size-adjust: none; +} + +body { + margin: 0; + font-size: 1rem; + overflow-x: hidden; +} + +code { + font-family: "Source Code Pro", Consolas, "Ubuntu Mono", Menlo, "DejaVu Sans Mono", monospace, monospace; + font-size: 0.875em; /* please adjust the ace font size accordingly in editor.js */ +} + +.left { float: left; } +.right { float: right; } +.hidden { display: none; } +.play-button.hidden { display: none; } + +h2, h3 { margin-top: 2.5em; } +h4, h5 { margin-top: 2em; } + +.header + .header h3, +.header + .header h4, +.header + .header h5 { + margin-top: 1em; +} + +a.header:target h1:before, +a.header:target h2:before, +a.header:target h3:before, +a.header:target h4:before { + display: inline-block; + content: "»"; + margin-left: -30px; + width: 30px; +} + +.page { + outline: 0; + padding: 0 var(--page-padding); +} +.page-wrapper { + box-sizing: border-box; +} +.js .page-wrapper { + transition: margin-left 0.3s ease, transform 0.3s ease; /* Animation: slide away */ +} + +.content { + overflow-y: auto; + padding: 0 15px; + padding-bottom: 50px; +} +.content main { + margin-left: auto; + margin-right: auto; + max-width: var(--content-max-width); +} +.content a { text-decoration: none; } +.content a:hover { text-decoration: underline; } +.content img { max-width: 100%; } +.content .header:link, +.content .header:visited { + color: var(--fg); +} +.content .header:link, +.content .header:visited:hover { + text-decoration: none; +} + +table { + margin: 0 auto; + border-collapse: collapse; +} +table td { + padding: 3px 20px; + border: 1px var(--table-border-color) solid; +} +table thead { + background: var(--table-header-bg); +} +table thead td { + font-weight: 700; + border: none; +} +table thead tr { + border: 1px var(--table-header-bg) solid; +} +/* Alternate background colors for rows */ +table tbody tr:nth-child(2n) { + background: var(--table-alternate-bg); +} + + +blockquote { + margin: 20px 0; + padding: 0 20px; + color: var(--fg); + background-color: var(--quote-bg); + border-top: .1em solid var(--quote-border); + border-bottom: .1em solid var(--quote-border); +} + + +:not(.footnote-definition) + .footnote-definition, +.footnote-definition + :not(.footnote-definition) { + margin-top: 2em; +} +.footnote-definition { + font-size: 0.9em; + margin: 0.5em 0; +} +.footnote-definition p { + display: inline; +} + +.tooltiptext { + position: absolute; + visibility: hidden; + color: #fff; + background-color: #333; + transform: translateX(-50%); /* Center by moving tooltip 50% of its width left */ + left: -8px; /* Half of the width of the icon */ + top: -35px; + font-size: 0.8em; + text-align: center; + border-radius: 6px; + padding: 5px 8px; + margin: 5px; + z-index: 1000; +} +.tooltipped .tooltiptext { + visibility: visible; +} + \ No newline at end of file diff --git a/docs/guide/css/print.css b/docs/guide/css/print.css new file mode 100644 index 0000000..5e690f7 --- /dev/null +++ b/docs/guide/css/print.css @@ -0,0 +1,54 @@ + +#sidebar, +#menu-bar, +.nav-chapters, +.mobile-nav-chapters { + display: none; +} + +#page-wrapper.page-wrapper { + transform: none; + margin-left: 0px; + overflow-y: initial; +} + +#content { + max-width: none; + margin: 0; + padding: 0; +} + +.page { + overflow-y: initial; +} + +code { + background-color: #666666; + border-radius: 5px; + + /* Force background to be printed in Chrome */ + -webkit-print-color-adjust: exact; +} + +pre > .buttons { + z-index: 2; +} + +a, a:visited, a:active, a:hover { + color: #4183c4; + text-decoration: none; +} + +h1, h2, h3, h4, h5, h6 { + page-break-inside: avoid; + page-break-after: avoid; +} + +pre, code { + page-break-inside: avoid; + white-space: pre-wrap; +} + +.fa { + display: none !important; +} diff --git a/docs/guide/css/variables.css b/docs/guide/css/variables.css new file mode 100644 index 0000000..29daa07 --- /dev/null +++ b/docs/guide/css/variables.css @@ -0,0 +1,210 @@ + +/* Globals */ + +:root { + --sidebar-width: 300px; + --page-padding: 15px; + --content-max-width: 750px; +} + +/* Themes */ + +.ayu { + --bg: hsl(210, 25%, 8%); + --fg: #c5c5c5; + + --sidebar-bg: #14191f; + --sidebar-fg: #c8c9db; + --sidebar-non-existant: #5c6773; + --sidebar-active: #ffb454; + --sidebar-spacer: #2d334f; + + --scrollbar: var(--sidebar-fg); + + --icons: #737480; + --icons-hover: #b7b9cc; + + --links: #0096cf; + + --inline-code-color: #ffb454; + + --theme-popup-bg: #14191f; + --theme-popup-border: #5c6773; + --theme-hover: #191f26; + + --quote-bg: hsl(226, 15%, 17%); + --quote-border: hsl(226, 15%, 22%); + + --table-border-color: hsl(210, 25%, 13%); + --table-header-bg: hsl(210, 25%, 28%); + --table-alternate-bg: hsl(210, 25%, 11%); + + --searchbar-border-color: #848484; + --searchbar-bg: #424242; + --searchbar-fg: #fff; + --searchbar-shadow-color: #d4c89f; + --searchresults-header-fg: #666; + --searchresults-border-color: #888; + --searchresults-li-bg: #252932; + --search-mark-bg: #e3b171; +} + +.coal { + --bg: hsl(200, 7%, 8%); + --fg: #98a3ad; + + --sidebar-bg: #292c2f; + --sidebar-fg: #a1adb8; + --sidebar-non-existant: #505254; + --sidebar-active: #3473ad; + --sidebar-spacer: #393939; + + --scrollbar: var(--sidebar-fg); + + --icons: #43484d; + --icons-hover: #b3c0cc; + + --links: #2b79a2; + + --inline-code-color: #c5c8c6;; + + --theme-popup-bg: #141617; + --theme-popup-border: #43484d; + --theme-hover: #1f2124; + + --quote-bg: hsl(234, 21%, 18%); + --quote-border: hsl(234, 21%, 23%); + + --table-border-color: hsl(200, 7%, 13%); + --table-header-bg: hsl(200, 7%, 28%); + --table-alternate-bg: hsl(200, 7%, 11%); + + --searchbar-border-color: #aaa; + --searchbar-bg: #b7b7b7; + --searchbar-fg: #000; + --searchbar-shadow-color: #aaa; + --searchresults-header-fg: #666; + --searchresults-border-color: #98a3ad; + --searchresults-li-bg: #2b2b2f; + --search-mark-bg: #355c7d; +} + +.light { + --bg: hsl(0, 0%, 100%); + --fg: #333333; + + --sidebar-bg: #fafafa; + --sidebar-fg: #364149; + --sidebar-non-existant: #aaaaaa; + --sidebar-active: #008cff; + --sidebar-spacer: #f4f4f4; + + --scrollbar: #cccccc; + + --icons: #cccccc; + --icons-hover: #333333; + + --links: #4183c4; + + --inline-code-color: #6e6b5e; + + --theme-popup-bg: #fafafa; + --theme-popup-border: #cccccc; + --theme-hover: #e6e6e6; + + --quote-bg: hsl(197, 37%, 96%); + --quote-border: hsl(197, 37%, 91%); + + --table-border-color: hsl(0, 0%, 95%); + --table-header-bg: hsl(0, 0%, 80%); + --table-alternate-bg: hsl(0, 0%, 97%); + + --searchbar-border-color: #aaa; + --searchbar-bg: #fafafa; + --searchbar-fg: #000; + --searchbar-shadow-color: #aaa; + --searchresults-header-fg: #666; + --searchresults-border-color: #888; + --searchresults-li-bg: #e4f2fe; + --search-mark-bg: #a2cff5; +} + +.navy { + --bg: hsl(226, 23%, 11%); + --fg: #bcbdd0; + + --sidebar-bg: #282d3f; + --sidebar-fg: #c8c9db; + --sidebar-non-existant: #505274; + --sidebar-active: #2b79a2; + --sidebar-spacer: #2d334f; + + --scrollbar: var(--sidebar-fg); + + --icons: #737480; + --icons-hover: #b7b9cc; + + --links: #2b79a2; + + --inline-code-color: #c5c8c6;; + + --theme-popup-bg: #161923; + --theme-popup-border: #737480; + --theme-hover: #282e40; + + --quote-bg: hsl(226, 15%, 17%); + --quote-border: hsl(226, 15%, 22%); + + --table-border-color: hsl(226, 23%, 16%); + --table-header-bg: hsl(226, 23%, 31%); + --table-alternate-bg: hsl(226, 23%, 14%); + + --searchbar-border-color: #aaa; + --searchbar-bg: #aeaec6; + --searchbar-fg: #000; + --searchbar-shadow-color: #aaa; + --searchresults-header-fg: #5f5f71; + --searchresults-border-color: #5c5c68; + --searchresults-li-bg: #242430; + --search-mark-bg: #a2cff5; +} + +.rust { + --bg: hsl(60, 9%, 87%); + --fg: #262625; + + --sidebar-bg: #3b2e2a; + --sidebar-fg: #c8c9db; + --sidebar-non-existant: #505254; + --sidebar-active: #e69f67; + --sidebar-spacer: #45373a; + + --scrollbar: var(--sidebar-fg); + + --icons: #737480; + --icons-hover: #262625; + + --links: #2b79a2; + + --inline-code-color: #6e6b5e; + + --theme-popup-bg: #e1e1db; + --theme-popup-border: #b38f6b; + --theme-hover: #99908a; + + --quote-bg: hsl(60, 5%, 75%); + --quote-border: hsl(60, 5%, 70%); + + --table-border-color: hsl(60, 9%, 82%); + --table-header-bg: #b3a497; + --table-alternate-bg: hsl(60, 9%, 84%); + + --searchbar-border-color: #aaa; + --searchbar-bg: #fafafa; + --searchbar-fg: #000; + --searchbar-shadow-color: #aaa; + --searchresults-header-fg: #666; + --searchresults-border-color: #888; + --searchresults-li-bg: #dec2a2; + --search-mark-bg: #e69f67; +} diff --git a/docs/guide/elasticlunr.min.js b/docs/guide/elasticlunr.min.js new file mode 100644 index 0000000..94b20dd --- /dev/null +++ b/docs/guide/elasticlunr.min.js @@ -0,0 +1,10 @@ +/** + * elasticlunr - http://weixsong.github.io + * Lightweight full-text search engine in Javascript for browser search and offline search. - 0.9.5 + * + * Copyright (C) 2017 Oliver Nightingale + * Copyright (C) 2017 Wei Song + * MIT Licensed + * @license + */ +!function(){function e(e){if(null===e||"object"!=typeof e)return e;var t=e.constructor();for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t}var t=function(e){var n=new t.Index;return n.pipeline.add(t.trimmer,t.stopWordFilter,t.stemmer),e&&e.call(n,n),n};t.version="0.9.5",lunr=t,t.utils={},t.utils.warn=function(e){return function(t){e.console&&console.warn&&console.warn(t)}}(this),t.utils.toString=function(e){return void 0===e||null===e?"":e.toString()},t.EventEmitter=function(){this.events={}},t.EventEmitter.prototype.addListener=function(){var e=Array.prototype.slice.call(arguments),t=e.pop(),n=e;if("function"!=typeof t)throw new TypeError("last argument must be a function");n.forEach(function(e){this.hasHandler(e)||(this.events[e]=[]),this.events[e].push(t)},this)},t.EventEmitter.prototype.removeListener=function(e,t){if(this.hasHandler(e)){var n=this.events[e].indexOf(t);-1!==n&&(this.events[e].splice(n,1),0==this.events[e].length&&delete this.events[e])}},t.EventEmitter.prototype.emit=function(e){if(this.hasHandler(e)){var t=Array.prototype.slice.call(arguments,1);this.events[e].forEach(function(e){e.apply(void 0,t)},this)}},t.EventEmitter.prototype.hasHandler=function(e){return e in this.events},t.tokenizer=function(e){if(!arguments.length||null===e||void 0===e)return[];if(Array.isArray(e)){var n=e.filter(function(e){return null===e||void 0===e?!1:!0});n=n.map(function(e){return t.utils.toString(e).toLowerCase()});var i=[];return n.forEach(function(e){var n=e.split(t.tokenizer.seperator);i=i.concat(n)},this),i}return e.toString().trim().toLowerCase().split(t.tokenizer.seperator)},t.tokenizer.defaultSeperator=/[\s\-]+/,t.tokenizer.seperator=t.tokenizer.defaultSeperator,t.tokenizer.setSeperator=function(e){null!==e&&void 0!==e&&"object"==typeof e&&(t.tokenizer.seperator=e)},t.tokenizer.resetSeperator=function(){t.tokenizer.seperator=t.tokenizer.defaultSeperator},t.tokenizer.getSeperator=function(){return t.tokenizer.seperator},t.Pipeline=function(){this._queue=[]},t.Pipeline.registeredFunctions={},t.Pipeline.registerFunction=function(e,n){n in t.Pipeline.registeredFunctions&&t.utils.warn("Overwriting existing registered function: "+n),e.label=n,t.Pipeline.registeredFunctions[n]=e},t.Pipeline.getRegisteredFunction=function(e){return e in t.Pipeline.registeredFunctions!=!0?null:t.Pipeline.registeredFunctions[e]},t.Pipeline.warnIfFunctionNotRegistered=function(e){var n=e.label&&e.label in this.registeredFunctions;n||t.utils.warn("Function is not registered with pipeline. This may cause problems when serialising the index.\n",e)},t.Pipeline.load=function(e){var n=new t.Pipeline;return e.forEach(function(e){var i=t.Pipeline.getRegisteredFunction(e);if(!i)throw new Error("Cannot load un-registered function: "+e);n.add(i)}),n},t.Pipeline.prototype.add=function(){var e=Array.prototype.slice.call(arguments);e.forEach(function(e){t.Pipeline.warnIfFunctionNotRegistered(e),this._queue.push(e)},this)},t.Pipeline.prototype.after=function(e,n){t.Pipeline.warnIfFunctionNotRegistered(n);var i=this._queue.indexOf(e);if(-1===i)throw new Error("Cannot find existingFn");this._queue.splice(i+1,0,n)},t.Pipeline.prototype.before=function(e,n){t.Pipeline.warnIfFunctionNotRegistered(n);var i=this._queue.indexOf(e);if(-1===i)throw new Error("Cannot find existingFn");this._queue.splice(i,0,n)},t.Pipeline.prototype.remove=function(e){var t=this._queue.indexOf(e);-1!==t&&this._queue.splice(t,1)},t.Pipeline.prototype.run=function(e){for(var t=[],n=e.length,i=this._queue.length,o=0;n>o;o++){for(var r=e[o],s=0;i>s&&(r=this._queue[s](r,o,e),void 0!==r&&null!==r);s++);void 0!==r&&null!==r&&t.push(r)}return t},t.Pipeline.prototype.reset=function(){this._queue=[]},t.Pipeline.prototype.get=function(){return this._queue},t.Pipeline.prototype.toJSON=function(){return this._queue.map(function(e){return t.Pipeline.warnIfFunctionNotRegistered(e),e.label})},t.Index=function(){this._fields=[],this._ref="id",this.pipeline=new t.Pipeline,this.documentStore=new t.DocumentStore,this.index={},this.eventEmitter=new t.EventEmitter,this._idfCache={},this.on("add","remove","update",function(){this._idfCache={}}.bind(this))},t.Index.prototype.on=function(){var e=Array.prototype.slice.call(arguments);return this.eventEmitter.addListener.apply(this.eventEmitter,e)},t.Index.prototype.off=function(e,t){return this.eventEmitter.removeListener(e,t)},t.Index.load=function(e){e.version!==t.version&&t.utils.warn("version mismatch: current "+t.version+" importing "+e.version);var n=new this;n._fields=e.fields,n._ref=e.ref,n.documentStore=t.DocumentStore.load(e.documentStore),n.pipeline=t.Pipeline.load(e.pipeline),n.index={};for(var i in e.index)n.index[i]=t.InvertedIndex.load(e.index[i]);return n},t.Index.prototype.addField=function(e){return this._fields.push(e),this.index[e]=new t.InvertedIndex,this},t.Index.prototype.setRef=function(e){return this._ref=e,this},t.Index.prototype.saveDocument=function(e){return this.documentStore=new t.DocumentStore(e),this},t.Index.prototype.addDoc=function(e,n){if(e){var n=void 0===n?!0:n,i=e[this._ref];this.documentStore.addDoc(i,e),this._fields.forEach(function(n){var o=this.pipeline.run(t.tokenizer(e[n]));this.documentStore.addFieldLength(i,n,o.length);var r={};o.forEach(function(e){e in r?r[e]+=1:r[e]=1},this);for(var s in r){var u=r[s];u=Math.sqrt(u),this.index[n].addToken(s,{ref:i,tf:u})}},this),n&&this.eventEmitter.emit("add",e,this)}},t.Index.prototype.removeDocByRef=function(e){if(e&&this.documentStore.isDocStored()!==!1&&this.documentStore.hasDoc(e)){var t=this.documentStore.getDoc(e);this.removeDoc(t,!1)}},t.Index.prototype.removeDoc=function(e,n){if(e){var n=void 0===n?!0:n,i=e[this._ref];this.documentStore.hasDoc(i)&&(this.documentStore.removeDoc(i),this._fields.forEach(function(n){var o=this.pipeline.run(t.tokenizer(e[n]));o.forEach(function(e){this.index[n].removeToken(e,i)},this)},this),n&&this.eventEmitter.emit("remove",e,this))}},t.Index.prototype.updateDoc=function(e,t){var t=void 0===t?!0:t;this.removeDocByRef(e[this._ref],!1),this.addDoc(e,!1),t&&this.eventEmitter.emit("update",e,this)},t.Index.prototype.idf=function(e,t){var n="@"+t+"/"+e;if(Object.prototype.hasOwnProperty.call(this._idfCache,n))return this._idfCache[n];var i=this.index[t].getDocFreq(e),o=1+Math.log(this.documentStore.length/(i+1));return this._idfCache[n]=o,o},t.Index.prototype.getFields=function(){return this._fields.slice()},t.Index.prototype.search=function(e,n){if(!e)return[];e="string"==typeof e?{any:e}:JSON.parse(JSON.stringify(e));var i=null;null!=n&&(i=JSON.stringify(n));for(var o=new t.Configuration(i,this.getFields()).get(),r={},s=Object.keys(e),u=0;u0&&t.push(e);for(var i in n)"docs"!==i&&"df"!==i&&this.expandToken(e+i,t,n[i]);return t},t.InvertedIndex.prototype.toJSON=function(){return{root:this.root}},t.Configuration=function(e,n){var e=e||"";if(void 0==n||null==n)throw new Error("fields should not be null");this.config={};var i;try{i=JSON.parse(e),this.buildUserConfig(i,n)}catch(o){t.utils.warn("user configuration parse failed, will use default configuration"),this.buildDefaultConfig(n)}},t.Configuration.prototype.buildDefaultConfig=function(e){this.reset(),e.forEach(function(e){this.config[e]={boost:1,bool:"OR",expand:!1}},this)},t.Configuration.prototype.buildUserConfig=function(e,n){var i="OR",o=!1;if(this.reset(),"bool"in e&&(i=e.bool||i),"expand"in e&&(o=e.expand||o),"fields"in e)for(var r in e.fields)if(n.indexOf(r)>-1){var s=e.fields[r],u=o;void 0!=s.expand&&(u=s.expand),this.config[r]={boost:s.boost||0===s.boost?s.boost:1,bool:s.bool||i,expand:u}}else t.utils.warn("field name in user configuration not found in index instance fields");else this.addAllFields2UserConfig(i,o,n)},t.Configuration.prototype.addAllFields2UserConfig=function(e,t,n){n.forEach(function(n){this.config[n]={boost:1,bool:e,expand:t}},this)},t.Configuration.prototype.get=function(){return this.config},t.Configuration.prototype.reset=function(){this.config={}},lunr.SortedSet=function(){this.length=0,this.elements=[]},lunr.SortedSet.load=function(e){var t=new this;return t.elements=e,t.length=e.length,t},lunr.SortedSet.prototype.add=function(){var e,t;for(e=0;e1;){if(r===e)return o;e>r&&(t=o),r>e&&(n=o),i=n-t,o=t+Math.floor(i/2),r=this.elements[o]}return r===e?o:-1},lunr.SortedSet.prototype.locationFor=function(e){for(var t=0,n=this.elements.length,i=n-t,o=t+Math.floor(i/2),r=this.elements[o];i>1;)e>r&&(t=o),r>e&&(n=o),i=n-t,o=t+Math.floor(i/2),r=this.elements[o];return r>e?o:e>r?o+1:void 0},lunr.SortedSet.prototype.intersect=function(e){for(var t=new lunr.SortedSet,n=0,i=0,o=this.length,r=e.length,s=this.elements,u=e.elements;;){if(n>o-1||i>r-1)break;s[n]!==u[i]?s[n]u[i]&&i++:(t.add(s[n]),n++,i++)}return t},lunr.SortedSet.prototype.clone=function(){var e=new lunr.SortedSet;return e.elements=this.toArray(),e.length=e.elements.length,e},lunr.SortedSet.prototype.union=function(e){var t,n,i;this.length>=e.length?(t=this,n=e):(t=e,n=this),i=t.clone();for(var o=0,r=n.toArray();o/g,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0===t.index}function a(e){return k.test(e)}function i(e){var n,t,r,i,o=e.className+" ";if(o+=e.parentNode?e.parentNode.className:"",t=B.exec(o))return w(t[1])?t[1]:"no-highlight";for(o=o.split(/\s+/),n=0,r=o.length;r>n;n++)if(i=o[n],a(i)||w(i))return i}function o(e){var n,t={},r=Array.prototype.slice.call(arguments,1);for(n in e)t[n]=e[n];return r.forEach(function(e){for(n in e)t[n]=e[n]}),t}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?a+=i.nodeValue.length:1===i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!==r[0].offset?e[0].offset"}function u(e){s+=""}function c(e){("start"===e.event?o:u)(e.node)}for(var l=0,s="",f=[];e.length||r.length;){var g=i();if(s+=n(a.substring(l,g[0].offset)),l=g[0].offset,g===e){f.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g===e&&g.length&&g[0].offset===l);f.reverse().forEach(o)}else"start"===g[0].event?f.push(g[0].node):f.pop(),c(g.splice(0,1)[0])}return s+n(a.substr(l))}function l(e){return e.v&&!e.cached_variants&&(e.cached_variants=e.v.map(function(n){return o(e,{v:null},n)})),e.cached_variants||e.eW&&[o(e)]||[e]}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var o={},u=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");o[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?u("keyword",a.k):x(a.k).forEach(function(e){u(e,a.k[e])}),a.k=o}a.lR=t(a.l||/\w+/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),null==a.r&&(a.r=1),a.c||(a.c=[]),a.c=Array.prototype.concat.apply([],a.c.map(function(e){return l("self"===e?a:e)})),a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var c=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=c.length?t(c.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e,n){var t,a;for(t=0,a=n.c.length;a>t;t++)if(r(n.c[t].bR,e))return n.c[t]}function u(e,n){if(r(e.eR,n)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?u(e.parent,n):void 0}function c(e,n){return!a&&r(n.iR,e)}function l(e,n){var t=N.cI?n[0].toLowerCase():n[0];return e.k.hasOwnProperty(t)&&e.k[t]}function p(e,n,t,r){var a=r?"":I.classPrefix,i='',i+n+o}function h(){var e,t,r,a;if(!E.k)return n(k);for(a="",t=0,E.lR.lastIndex=0,r=E.lR.exec(k);r;)a+=n(k.substring(t,r.index)),e=l(E,r),e?(B+=e[1],a+=p(e[0],n(r[0]))):a+=n(r[0]),t=E.lR.lastIndex,r=E.lR.exec(k);return a+n(k.substr(t))}function d(){var e="string"==typeof E.sL;if(e&&!y[E.sL])return n(k);var t=e?f(E.sL,k,!0,x[E.sL]):g(k,E.sL.length?E.sL:void 0);return E.r>0&&(B+=t.r),e&&(x[E.sL]=t.top),p(t.language,t.value,!1,!0)}function b(){L+=null!=E.sL?d():h(),k=""}function v(e){L+=e.cN?p(e.cN,"",!0):"",E=Object.create(e,{parent:{value:E}})}function m(e,n){if(k+=e,null==n)return b(),0;var t=o(n,E);if(t)return t.skip?k+=n:(t.eB&&(k+=n),b(),t.rB||t.eB||(k=n)),v(t,n),t.rB?0:n.length;var r=u(E,n);if(r){var a=E;a.skip?k+=n:(a.rE||a.eE||(k+=n),b(),a.eE&&(k=n));do E.cN&&(L+=C),E.skip||(B+=E.r),E=E.parent;while(E!==r.parent);return r.starts&&v(r.starts,""),a.rE?0:n.length}if(c(n,E))throw new Error('Illegal lexeme "'+n+'" for mode "'+(E.cN||"")+'"');return k+=n,n.length||1}var N=w(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var R,E=i||N,x={},L="";for(R=E;R!==N;R=R.parent)R.cN&&(L=p(R.cN,"",!0)+L);var k="",B=0;try{for(var M,j,O=0;;){if(E.t.lastIndex=O,M=E.t.exec(t),!M)break;j=m(t.substring(O,M.index),M[0]),O=M.index+j}for(m(t.substr(O)),R=E;R.parent;R=R.parent)R.cN&&(L+=C);return{r:B,value:L,language:e,top:E}}catch(T){if(T.message&&-1!==T.message.indexOf("Illegal"))return{r:0,value:n(t)};throw T}}function g(e,t){t=t||I.languages||x(y);var r={r:0,value:n(e)},a=r;return t.filter(w).forEach(function(n){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}),a.language&&(r.second_best=a),r}function p(e){return I.tabReplace||I.useBR?e.replace(M,function(e,n){return I.useBR&&"\n"===e?"
":I.tabReplace?n.replace(/\t/g,I.tabReplace):""}):e}function h(e,n,t){var r=n?L[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function d(e){var n,t,r,o,l,s=i(e);a(s)||(I.useBR?(n=document.createElementNS("http://www.w3.org/1999/xhtml","div"),n.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):n=e,l=n.textContent,r=s?f(s,l,!0):g(l),t=u(n),t.length&&(o=document.createElementNS("http://www.w3.org/1999/xhtml","div"),o.innerHTML=r.value,r.value=c(t,u(o),l)),r.value=p(r.value),e.innerHTML=r.value,e.className=h(e.className,s,r.language),e.result={language:r.language,re:r.r},r.second_best&&(e.second_best={language:r.second_best.language,re:r.second_best.r}))}function b(e){I=o(I,e)}function v(){if(!v.called){v.called=!0;var e=document.querySelectorAll("pre code");E.forEach.call(e,d)}}function m(){addEventListener("DOMContentLoaded",v,!1),addEventListener("load",v,!1)}function N(n,t){var r=y[n]=t(e);r.aliases&&r.aliases.forEach(function(e){L[e]=n})}function R(){return x(y)}function w(e){return e=(e||"").toLowerCase(),y[e]||y[L[e]]}var E=[],x=Object.keys,y={},L={},k=/^(no-?highlight|plain|text)$/i,B=/\blang(?:uage)?-([\w-]+)\b/i,M=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,C="
",I={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0};return e.highlight=f,e.highlightAuto=g,e.fixMarkup=p,e.highlightBlock=d,e.configure=b,e.initHighlighting=v,e.initHighlightingOnLoad=m,e.registerLanguage=N,e.listLanguages=R,e.getLanguage=w,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e});hljs.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"meta",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"comment",v:[{b:/Index: /,e:/$/},{b:/={3,}/,e:/$/},{b:/^\-{3}/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+{3}/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"addition",b:"^\\!",e:"$"}]}});hljs.registerLanguage("nginx",function(e){var r={cN:"variable",v:[{b:/\$\d+/},{b:/\$\{/,e:/}/},{b:"[\\$\\@]"+e.UIR}]},b={eW:!0,l:"[a-z/_]+",k:{literal:"on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll"},r:0,i:"=>",c:[e.HCM,{cN:"string",c:[e.BE,r],v:[{b:/"/,e:/"/},{b:/'/,e:/'/}]},{b:"([a-z]+):/",e:"\\s",eW:!0,eE:!0,c:[r]},{cN:"regexp",c:[e.BE,r],v:[{b:"\\s\\^",e:"\\s|{|;",rE:!0},{b:"~\\*?\\s+",e:"\\s|{|;",rE:!0},{b:"\\*(\\.[a-z\\-]+)+"},{b:"([a-z\\-]+\\.)+\\*"}]},{cN:"number",b:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{cN:"number",b:"\\b\\d+[kKmMgGdshdwy]*\\b",r:0},r]};return{aliases:["nginxconf"],c:[e.HCM,{b:e.UIR+"\\s+{",rB:!0,e:"{",c:[{cN:"section",b:e.UIR}],r:0},{b:e.UIR+"\\s",e:";|{",rB:!0,c:[{cN:"attribute",b:e.UIR,starts:b}],r:0}],i:"[^\\s\\}]"}});hljs.registerLanguage("objectivec",function(e){var t={cN:"built_in",b:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},_={keyword:"int float while char export sizeof typedef const struct for union unsigned long volatile static bool mutable if do return goto void enum else break extern asm case short default double register explicit signed typename this switch continue wchar_t inline readonly assign readwrite self @synchronized id typeof nonatomic super unichar IBOutlet IBAction strong weak copy in out inout bycopy byref oneway __strong __weak __block __autoreleasing @private @protected @public @try @property @end @throw @catch @finally @autoreleasepool @synthesize @dynamic @selector @optional @required @encode @package @import @defs @compatibility_alias __bridge __bridge_transfer __bridge_retained __bridge_retain __covariant __contravariant __kindof _Nonnull _Nullable _Null_unspecified __FUNCTION__ __PRETTY_FUNCTION__ __attribute__ getter setter retain unsafe_unretained nonnull nullable null_unspecified null_resettable class instancetype NS_DESIGNATED_INITIALIZER NS_UNAVAILABLE NS_REQUIRES_SUPER NS_RETURNS_INNER_POINTER NS_INLINE NS_AVAILABLE NS_DEPRECATED NS_ENUM NS_OPTIONS NS_SWIFT_UNAVAILABLE NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_REFINED_FOR_SWIFT NS_SWIFT_NAME NS_SWIFT_NOTHROW NS_DURING NS_HANDLER NS_ENDHANDLER NS_VALUERETURN NS_VOIDRETURN",literal:"false true FALSE TRUE nil YES NO NULL",built_in:"BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once"},i=/[a-zA-Z@][a-zA-Z0-9_]*/,n="@interface @class @protocol @implementation";return{aliases:["mm","objc","obj-c"],k:_,l:i,i:""}]}]},{cN:"class",b:"("+n.split(" ").join("|")+")\\b",e:"({|$)",eE:!0,k:n,l:i,c:[e.UTM]},{b:"\\."+e.UIR,r:0}]}});hljs.registerLanguage("xml",function(s){var e="[A-Za-z0-9\\._:-]+",t={eW:!0,i:/`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist"],cI:!0,c:[{cN:"meta",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},s.C("",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0}]},{cN:"tag",b:"|$)",e:">",k:{name:"style"},c:[t],starts:{e:"",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"|$)",e:">",k:{name:"script"},c:[t],starts:{e:"",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"meta",v:[{b:/<\?xml/,e:/\?>/,r:10},{b:/<\?\w+/,e:/\?>/}]},{cN:"tag",b:"",c:[{cN:"name",b:/[^\/><\s]+/,r:0},t]}]}});hljs.registerLanguage("handlebars",function(e){var a={"builtin-name":"each in with if else unless bindattr action collection debugger log outlet template unbound view yield"};return{aliases:["hbs","html.hbs","html.handlebars"],cI:!0,sL:"xml",c:[e.C("{{!(--)?","(--)?}}"),{cN:"template-tag",b:/\{\{[#\/]/,e:/\}\}/,c:[{cN:"name",b:/[a-zA-Z\.-]+/,k:a,starts:{eW:!0,r:0,c:[e.QSM]}}]},{cN:"template-variable",b:/\{\{/,e:/\}\}/,k:a}]}});hljs.registerLanguage("ini",function(e){var b={cN:"string",c:[e.BE],v:[{b:"'''",e:"'''",r:10},{b:'"""',e:'"""',r:10},{b:'"',e:'"'},{b:"'",e:"'"}]};return{aliases:["toml"],cI:!0,i:/\S/,c:[e.C(";","$"),e.HCM,{cN:"section",b:/^\s*\[+/,e:/\]+/},{b:/^[a-z0-9\[\]_-]+\s*=\s*/,e:"$",rB:!0,c:[{cN:"attr",b:/[a-z0-9\[\]_-]+/},{b:/=/,eW:!0,r:0,c:[{cN:"literal",b:/\bon|off|true|false|yes|no\b/},{cN:"variable",v:[{b:/\$[\w\d"][\w\d_]*/},{b:/\$\{(.*?)}/}]},b,{cN:"number",b:/([\+\-]+)?[\d]+_[\d_]+/},e.NM]}]}]}});hljs.registerLanguage("javascript",function(e){var r="[A-Za-z$_][0-9A-Za-z$_]*",t={keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},a={cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},n={cN:"subst",b:"\\$\\{",e:"\\}",k:t,c:[]},c={cN:"string",b:"`",e:"`",c:[e.BE,n]};n.c=[e.ASM,e.QSM,c,a,e.RM];var s=n.c.concat([e.CBCM,e.CLCM]);return{aliases:["js","jsx"],k:t,c:[{cN:"meta",r:10,b:/^\s*['"]use (strict|asm)['"]/},{cN:"meta",b:/^#!/,e:/$/},e.ASM,e.QSM,c,e.CLCM,e.CBCM,a,{b:/[{,]\s*/,r:0,c:[{b:r+"\\s*:",rB:!0,r:0,c:[{cN:"attr",b:r,r:0}]}]},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{cN:"function",b:"(\\(.*?\\)|"+r+")\\s*=>",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:r},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:t,c:s}]}]},{b://,sL:"xml",c:[{b:/<\w+\s*\/>/,skip:!0},{b:/<\w+/,e:/(\/\w+|\w+\/)>/,skip:!0,c:[{b:/<\w+\s*\/>/,skip:!0},"self"]}]}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:r}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:s}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor",e:/\{/,eE:!0}],i:/#(?!!)/}});hljs.registerLanguage("python",function(e){var r={keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10 None True False",built_in:"Ellipsis NotImplemented"},b={cN:"meta",b:/^(>>>|\.\.\.) /},c={cN:"subst",b:/\{/,e:/\}/,k:r,i:/#/},a={cN:"string",c:[e.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[b],r:10},{b:/(u|b)?r?"""/,e:/"""/,c:[b],r:10},{b:/(fr|rf|f)'''/,e:/'''/,c:[b,c]},{b:/(fr|rf|f)"""/,e:/"""/,c:[b,c]},{b:/(u|r|ur)'/,e:/'/,r:10},{b:/(u|r|ur)"/,e:/"/,r:10},{b:/(b|br)'/,e:/'/},{b:/(b|br)"/,e:/"/},{b:/(fr|rf|f)'/,e:/'/,c:[c]},{b:/(fr|rf|f)"/,e:/"/,c:[c]},e.ASM,e.QSM]},s={cN:"number",r:0,v:[{b:e.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:e.CNR+"[lLjJ]?"}]},i={cN:"params",b:/\(/,e:/\)/,c:["self",b,s,a]};return c.c=[a,s,b],{aliases:["py","gyp"],k:r,i:/(<\/|->|\?)|=>/,c:[b,s,a,e.HCM,{v:[{cN:"function",bK:"def"},{cN:"class",bK:"class"}],e:/:/,i:/[${=;\n,]/,c:[e.UTM,i,{b:/->/,eW:!0,k:"None"}]},{cN:"meta",b:/^[\t ]*@/,e:/$/},{b:/\b(print|exec)\(/}]}});hljs.registerLanguage("markdown",function(e){return{aliases:["md","mkdown","mkd"],c:[{cN:"section",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",r:0},{cN:"bullet",b:"^([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"quote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"^```w*s*$",e:"^```s*$"},{b:"`.+?`"},{b:"^( {4}| )",e:"$",r:0}]},{b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"string",b:"\\[",e:"\\]",eB:!0,rE:!0,r:0},{cN:"link",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"symbol",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],r:10},{b:/^\[[^\n]+\]:/,rB:!0,c:[{cN:"symbol",b:/\[/,e:/\]/,eB:!0,eE:!0},{cN:"link",b:/:\s*/,e:/$/,eB:!0}]}]}});hljs.registerLanguage("php",function(e){var c={b:"\\$+[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]*"},i={cN:"meta",b:/<\?(php)?|\?>/},t={cN:"string",c:[e.BE,i],v:[{b:'b"',e:'"'},{b:"b'",e:"'"},e.inherit(e.ASM,{i:null}),e.inherit(e.QSM,{i:null})]},a={v:[e.BNM,e.CNM]};return{aliases:["php3","php4","php5","php6"],cI:!0,k:"and include_once list abstract global private echo interface as static endswitch array null if endwhile or const for endforeach self var while isset public protected exit foreach throw elseif include __FILE__ empty require_once do xor return parent clone use __CLASS__ __LINE__ else break print eval new catch __METHOD__ case exception default die require __FUNCTION__ enddeclare final try switch continue endfor endif declare unset true false trait goto instanceof insteadof __DIR__ __NAMESPACE__ yield finally",c:[e.HCM,e.C("//","$",{c:[i]}),e.C("/\\*","\\*/",{c:[{cN:"doctag",b:"@[A-Za-z]+"}]}),e.C("__halt_compiler.+?;",!1,{eW:!0,k:"__halt_compiler",l:e.UIR}),{cN:"string",b:/<<<['"]?\w+['"]?$/,e:/^\w+;?$/,c:[e.BE,{cN:"subst",v:[{b:/\$\w+/},{b:/\{\$/,e:/\}/}]}]},i,{cN:"keyword",b:/\$this\b/},c,{b:/(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/},{cN:"function",bK:"function",e:/[;{]/,eE:!0,i:"\\$|\\[|%",c:[e.UTM,{cN:"params",b:"\\(",e:"\\)",c:["self",c,e.CBCM,t,a]}]},{cN:"class",bK:"class interface",e:"{",eE:!0,i:/[:\(\$"]/,c:[{bK:"extends implements"},e.UTM]},{bK:"namespace",e:";",i:/[\.']/,c:[e.UTM]},{bK:"use",e:";",c:[e.UTM]},{b:"=>"},t,a]}});hljs.registerLanguage("d",function(e){var t={keyword:"abstract alias align asm assert auto body break byte case cast catch class const continue debug default delete deprecated do else enum export extern final finally for foreach foreach_reverse|10 goto if immutable import in inout int interface invariant is lazy macro mixin module new nothrow out override package pragma private protected public pure ref return scope shared static struct super switch synchronized template this throw try typedef typeid typeof union unittest version void volatile while with __FILE__ __LINE__ __gshared|10 __thread __traits __DATE__ __EOF__ __TIME__ __TIMESTAMP__ __VENDOR__ __VERSION__",built_in:"bool cdouble cent cfloat char creal dchar delegate double dstring float function idouble ifloat ireal long real short string ubyte ucent uint ulong ushort wchar wstring",literal:"false null true"},r="(0|[1-9][\\d_]*)",a="(0|[1-9][\\d_]*|\\d[\\d_]*|[\\d_]+?\\d)",i="0[bB][01_]+",n="([\\da-fA-F][\\da-fA-F_]*|_[\\da-fA-F][\\da-fA-F_]*)",_="0[xX]"+n,c="([eE][+-]?"+a+")",d="("+a+"(\\.\\d*|"+c+")|\\d+\\."+a+a+"|\\."+r+c+"?)",o="(0[xX]("+n+"\\."+n+"|\\.?"+n+")[pP][+-]?"+a+")",s="("+r+"|"+i+"|"+_+")",l="("+o+"|"+d+")",u="\\\\(['\"\\?\\\\abfnrtv]|u[\\dA-Fa-f]{4}|[0-7]{1,3}|x[\\dA-Fa-f]{2}|U[\\dA-Fa-f]{8})|&[a-zA-Z\\d]{2,};",b={cN:"number",b:"\\b"+s+"(L|u|U|Lu|LU|uL|UL)?",r:0},f={cN:"number",b:"\\b("+l+"([fF]|L|i|[fF]i|Li)?|"+s+"(i|[fF]i|Li))",r:0},g={cN:"string",b:"'("+u+"|.)",e:"'",i:"."},h={b:u,r:0},p={cN:"string",b:'"',c:[h],e:'"[cwd]?'},m={cN:"string",b:'[rq]"',e:'"[cwd]?',r:5},w={cN:"string",b:"`",e:"`[cwd]?"},N={cN:"string",b:'x"[\\da-fA-F\\s\\n\\r]*"[cwd]?',r:10},A={cN:"string",b:'q"\\{',e:'\\}"'},F={cN:"meta",b:"^#!",e:"$",r:5},y={cN:"meta",b:"#(line)",e:"$",r:5},L={cN:"keyword",b:"@[a-zA-Z_][a-zA-Z_\\d]*"},v=e.C("\\/\\+","\\+\\/",{c:["self"],r:10});return{l:e.UIR,k:t,c:[e.CLCM,e.CBCM,v,N,p,m,w,A,f,b,g,F,y,L]}});hljs.registerLanguage("json",function(e){var i={literal:"true false null"},n=[e.QSM,e.CNM],r={e:",",eW:!0,eE:!0,c:n,k:i},t={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(r,{b:/:/})],i:"\\S"},c={b:"\\[",e:"\\]",c:[e.inherit(r)],i:"\\S"};return n.splice(n.length,0,t,c),{c:n,k:i,i:"\\S"}});hljs.registerLanguage("go",function(e){var t={keyword:"break default func interface select case map struct chan else goto package switch const fallthrough if range type continue for import return var go defer bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 uint16 uint32 uint64 int uint uintptr rune",literal:"true false iota nil",built_in:"append cap close complex copy imag len make new panic print println real recover delete"};return{aliases:["golang"],k:t,i:"{",e:"}"},n={v:[{b:/\$\d/},{b:/[\$%@](\^\w\b|#\w+(::\w+)*|{\w+}|\w+(::\w*)*)/},{b:/[\$%@][^\s\w{]/,r:0}]},i=[e.BE,r,n],o=[n,e.HCM,e.C("^\\=\\w","\\=cut",{eW:!0}),s,{cN:"string",c:i,v:[{b:"q[qwxr]?\\s*\\(",e:"\\)",r:5},{b:"q[qwxr]?\\s*\\[",e:"\\]",r:5},{b:"q[qwxr]?\\s*\\{",e:"\\}",r:5},{b:"q[qwxr]?\\s*\\|",e:"\\|",r:5},{b:"q[qwxr]?\\s*\\<",e:"\\>",r:5},{b:"qw\\s+q",e:"q",r:5},{b:"'",e:"'",c:[e.BE]},{b:'"',e:'"'},{b:"`",e:"`",c:[e.BE]},{b:"{\\w+}",c:[],r:0},{b:"-?\\w+\\s*\\=\\>",c:[],r:0}]},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\/\\/|"+e.RSR+"|\\b(split|return|print|reverse|grep)\\b)\\s*",k:"split return print reverse grep",r:0,c:[e.HCM,{cN:"regexp",b:"(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*",r:10},{cN:"regexp",b:"(m|qr)?/",e:"/[a-z]*",c:[e.BE],r:0}]},{cN:"function",bK:"sub",e:"(\\s*\\(.*?\\))?[;{]",eE:!0,r:5,c:[e.TM]},{b:"-\\w\\b",r:0},{b:"^__DATA__$",e:"^__END__$",sL:"mojolicious",c:[{b:"^@@.*",e:"$",cN:"comment"}]}];return r.c=o,s.c=o,{aliases:["pl","pm"],l:/[\w\.]+/,k:t,c:o}});hljs.registerLanguage("rust",function(e){var t="([ui](8|16|32|64|128|size)|f(32|64))?",r="alignof as be box break const continue crate do else enum extern false fn for if impl in let loop match mod mut offsetof once priv proc pub pure ref return self Self sizeof static struct super trait true type typeof unsafe unsized use virtual while where yield move default",n="drop i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64 str char bool Box Option Result String Vec Copy Send Sized Sync Drop Fn FnMut FnOnce ToOwned Clone Debug PartialEq PartialOrd Eq Ord AsRef AsMut Into From Default Iterator Extend IntoIterator DoubleEndedIterator ExactSizeIterator SliceConcatExt ToString assert! assert_eq! bitflags! bytes! cfg! col! concat! concat_idents! debug_assert! debug_assert_eq! env! panic! file! format! format_args! include_bin! include_str! line! local_data_key! module_path! option_env! print! println! select! stringify! try! unimplemented! unreachable! vec! write! writeln! macro_rules! assert_ne! debug_assert_ne!";return{aliases:["rs"],k:{keyword:r,literal:"true false Some None Ok Err",built_in:n},l:e.IR+"!?",i:""}]}});hljs.registerLanguage("ruby",function(e){var b="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",r={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},c={cN:"doctag",b:"@[A-Za-z]+"},a={b:"#<",e:">"},s=[e.C("#","$",{c:[c]}),e.C("^\\=begin","^\\=end",{c:[c],r:10}),e.C("^__END__","\\n$")],n={cN:"subst",b:"#\\{",e:"}",k:r},t={cN:"string",c:[e.BE,n],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{b:/<<(-?)\w+$/,e:/^\s*\w+$/}]},i={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:r},d=[t,a,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(s)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:b}),i].concat(s)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"symbol",b:":(?!\\s)",c:[t,{b:b}],r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:r},{b:"("+e.RSR+"|unless)\\s*",k:"unless",c:[a,{cN:"regexp",c:[e.BE,n],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(s),r:0}].concat(s);n.c=d,i.c=d;var l="[>?]>",o="[\\w#]+\\(\\w+\\):\\d+:\\d+>",u="(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>",w=[{b:/^\s*=>/,starts:{e:"$",c:d}},{cN:"meta",b:"^("+l+"|"+o+"|"+u+")",starts:{e:"$",c:d}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:r,i:/\/\*/,c:s.concat(w).concat(d)}});hljs.registerLanguage("makefile",function(e){var i={cN:"variable",v:[{b:"\\$\\("+e.UIR+"\\)",c:[e.BE]},{b:/\$[@%] *$",rE:!0,c:l.c,e:t.v[0].b},{b:"<%[%=-]?",e:"[%-]?%>",sL:"ruby",eB:!0,eE:!0,r:0},{cN:"type",b:"!!"+e.UIR},{cN:"meta",b:"&"+e.UIR+"$"},{cN:"meta",b:"\\*"+e.UIR+"$"},{cN:"bullet",b:"^ *-",r:0},e.HCM,{bK:b,k:{literal:b}},e.CNM,l]}});hljs.registerLanguage("css",function(e){var c="[a-zA-Z-][a-zA-Z0-9_-]*",t={b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{eW:!0,eE:!0,c:[{b:/[\w-]+\(/,rB:!0,c:[{cN:"built_in",b:/[\w-]+/},{b:/\(/,e:/\)/,c:[e.ASM,e.QSM]}]},e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"number",b:"#[0-9A-Fa-f]+"},{cN:"meta",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,{cN:"selector-id",b:/#[A-Za-z0-9_-]+/},{cN:"selector-class",b:/\.[A-Za-z0-9_-]+/},{cN:"selector-attr",b:/\[/,e:/\]/,i:"$"},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/},{b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{b:"@",e:"[{;]",i:/:/,c:[{cN:"keyword",b:/\w+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[e.ASM,e.QSM,e.CSSNM]}]},{cN:"selector-tag",b:c,r:0},{b:"{",e:"}",i:/\S/,c:[e.CBCM,t]}]}});hljs.registerLanguage("java",function(e){var a="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",t=a+"(<"+a+"(\\s*,\\s*"+a+")*>)?",r="false synchronized int abstract float private char boolean static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do",s="\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",c={cN:"number",b:s,r:0};return{aliases:["jsp"],k:r,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"new throw return else",r:0},{cN:"function",b:"("+t+"\\s+)+"+e.UIR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:r,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,k:r,r:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},c,{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("armasm",function(s){return{cI:!0,aliases:["arm"],l:"\\.?"+s.IR,k:{meta:".2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .arm .thumb .code16 .code32 .force_thumb .thumb_func .ltorg ALIAS ALIGN ARM AREA ASSERT ATTR CN CODE CODE16 CODE32 COMMON CP DATA DCB DCD DCDU DCDO DCFD DCFDU DCI DCQ DCQU DCW DCWU DN ELIF ELSE END ENDFUNC ENDIF ENDP ENTRY EQU EXPORT EXPORTAS EXTERN FIELD FILL FUNCTION GBLA GBLL GBLS GET GLOBAL IF IMPORT INCBIN INCLUDE INFO KEEP LCLA LCLL LCLS LTORG MACRO MAP MEND MEXIT NOFP OPT PRESERVE8 PROC QN READONLY RELOC REQUIRE REQUIRE8 RLIST FN ROUT SETA SETL SETS SN SPACE SUBT THUMB THUMBX TTL WHILE WEND ",built_in:"r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 pc lr sp ip sl sb fp a1 a2 a3 a4 v1 v2 v3 v4 v5 v6 v7 v8 f0 f1 f2 f3 f4 f5 f6 f7 p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 q0 q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 cpsr_c cpsr_x cpsr_s cpsr_f cpsr_cx cpsr_cxs cpsr_xs cpsr_xsf cpsr_sf cpsr_cxsf spsr_c spsr_x spsr_s spsr_f spsr_cx spsr_cxs spsr_xs spsr_xsf spsr_sf spsr_cxsf s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 s16 s17 s18 s19 s20 s21 s22 s23 s24 s25 s26 s27 s28 s29 s30 s31 d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 d16 d17 d18 d19 d20 d21 d22 d23 d24 d25 d26 d27 d28 d29 d30 d31 {PC} {VAR} {TRUE} {FALSE} {OPT} {CONFIG} {ENDIAN} {CODESIZE} {CPU} {FPU} {ARCHITECTURE} {PCSTOREOFFSET} {ARMASM_VERSION} {INTER} {ROPI} {RWPI} {SWST} {NOSWST} . @"},c:[{cN:"keyword",b:"\\b(adc|(qd?|sh?|u[qh]?)?add(8|16)?|usada?8|(q|sh?|u[qh]?)?(as|sa)x|and|adrl?|sbc|rs[bc]|asr|b[lx]?|blx|bxj|cbn?z|tb[bh]|bic|bfc|bfi|[su]bfx|bkpt|cdp2?|clz|clrex|cmp|cmn|cpsi[ed]|cps|setend|dbg|dmb|dsb|eor|isb|it[te]{0,3}|lsl|lsr|ror|rrx|ldm(([id][ab])|f[ds])?|ldr((s|ex)?[bhd])?|movt?|mvn|mra|mar|mul|[us]mull|smul[bwt][bt]|smu[as]d|smmul|smmla|mla|umlaal|smlal?([wbt][bt]|d)|mls|smlsl?[ds]|smc|svc|sev|mia([bt]{2}|ph)?|mrr?c2?|mcrr2?|mrs|msr|orr|orn|pkh(tb|bt)|rbit|rev(16|sh)?|sel|[su]sat(16)?|nop|pop|push|rfe([id][ab])?|stm([id][ab])?|str(ex)?[bhd]?|(qd?)?sub|(sh?|q|u[qh]?)?sub(8|16)|[su]xt(a?h|a?b(16)?)|srs([id][ab])?|swpb?|swi|smi|tst|teq|wfe|wfi|yield)(eq|ne|cs|cc|mi|pl|vs|vc|hi|ls|ge|lt|gt|le|al|hs|lo)?[sptrx]?",e:"\\s"},s.C("[;@]","$",{r:0}),s.CBCM,s.QSM,{cN:"string",b:"'",e:"[^\\\\]'",r:0},{cN:"title",b:"\\|",e:"\\|",i:"\\n",r:0},{cN:"number",v:[{b:"[#$=]?0x[0-9a-f]+"},{b:"[#$=]?0b[01]+"},{b:"[#$=]\\d+"},{b:"\\b\\d+"}],r:0},{cN:"symbol",v:[{b:"^[a-z_\\.\\$][a-z0-9_\\.\\$]+"},{b:"^\\s*[a-z_\\.\\$][a-z0-9_\\.\\$]+:"},{b:"[=#]\\w+"}],r:0}]}});hljs.registerLanguage("swift",function(e){var i={keyword:"__COLUMN__ __FILE__ __FUNCTION__ __LINE__ as as! as? associativity break case catch class continue convenience default defer deinit didSet do dynamic dynamicType else enum extension fallthrough false fileprivate final for func get guard if import in indirect infix init inout internal is lazy left let mutating nil none nonmutating open operator optional override postfix precedence prefix private protocol Protocol public repeat required rethrows return right self Self set static struct subscript super switch throw throws true try try! try? Type typealias unowned var weak where while willSet",literal:"true false nil",built_in:"abs advance alignof alignofValue anyGenerator assert assertionFailure bridgeFromObjectiveC bridgeFromObjectiveCUnconditional bridgeToObjectiveC bridgeToObjectiveCUnconditional c contains count countElements countLeadingZeros debugPrint debugPrintln distance dropFirst dropLast dump encodeBitsAsWords enumerate equal fatalError filter find getBridgedObjectiveCType getVaList indices insertionSort isBridgedToObjectiveC isBridgedVerbatimToObjectiveC isUniquelyReferenced isUniquelyReferencedNonObjC join lazy lexicographicalCompare map max maxElement min minElement numericCast overlaps partition posix precondition preconditionFailure print println quickSort readLine reduce reflect reinterpretCast reverse roundUpToAlignment sizeof sizeofValue sort split startsWith stride strideof strideofValue swap toString transcode underestimateCount unsafeAddressOf unsafeBitCast unsafeDowncast unsafeUnwrap unsafeReflect withExtendedLifetime withObjectAtPlusZero withUnsafePointer withUnsafePointerToObject withUnsafeMutablePointer withUnsafeMutablePointers withUnsafePointer withUnsafePointers withVaList zip"},t={cN:"type",b:"\\b[A-Z][\\wÀ-ʸ']*",r:0},n=e.C("/\\*","\\*/",{c:["self"]}),r={cN:"subst",b:/\\\(/,e:"\\)",k:i,c:[]},a={cN:"number",b:"\\b([\\d_]+(\\.[\\deE_]+)?|0x[a-fA-F0-9_]+(\\.[a-fA-F0-9p_]+)?|0b[01_]+|0o[0-7_]+)\\b",r:0},o=e.inherit(e.QSM,{c:[r,e.BE]});return r.c=[a],{k:i,c:[o,e.CLCM,n,t,a,{cN:"function",bK:"func",e:"{",eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{b://},{cN:"params",b:/\(/,e:/\)/,endsParent:!0,k:i,c:["self",a,o,e.CBCM,{b:":"}],i:/["']/}],i:/\[|%/},{cN:"class",bK:"struct protocol class extension enum",k:i,e:"\\{",eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][\u00C0-\u02B80-9A-Za-z$_]*/})]},{cN:"meta",b:"(@warn_unused_result|@exported|@lazy|@noescape|@NSCopying|@NSManaged|@objc|@convention|@required|@noreturn|@IBAction|@IBDesignable|@IBInspectable|@IBOutlet|@infix|@prefix|@postfix|@autoclosure|@testable|@available|@nonobjc|@NSApplicationMain|@UIApplicationMain)"},{bK:"import",e:/$/,c:[e.CLCM,n]}]}});hljs.registerLanguage("cpp",function(t){var e={cN:"keyword",b:"\\b[a-z\\d_]*_t\\b"},r={cN:"string",v:[{b:'(u8?|U)?L?"',e:'"',i:"\\n",c:[t.BE]},{b:'(u8?|U)?R"',e:'"',c:[t.BE]},{b:"'\\\\?.",e:"'",i:"."}]},s={cN:"number",v:[{b:"\\b(0b[01']+)"},{b:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{b:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],r:0},i={cN:"meta",b:/#\s*[a-z]+\b/,e:/$/,k:{"meta-keyword":"if else elif endif define undef warning error line pragma ifdef ifndef include"},c:[{b:/\\\n/,r:0},t.inherit(r,{cN:"meta-string"}),{cN:"meta-string",b:/<[^\n>]*>/,e:/$/,i:"\\n"},t.CLCM,t.CBCM]},a=t.IR+"\\s*\\(",c={keyword:"int float while private char catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignof constexpr decltype noexcept static_assert thread_local restrict _Bool complex _Complex _Imaginary atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and or not",built_in:"std string cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr",literal:"true false nullptr NULL"},n=[e,t.CLCM,t.CBCM,s,r];return{aliases:["c","cc","h","c++","h++","hpp"],k:c,i:"",k:c,c:["self",e]},{b:t.IR+"::",k:c},{v:[{b:/=/,e:/;/},{b:/\(/,e:/\)/},{bK:"new throw return else",e:/;/}],k:c,c:n.concat([{b:/\(/,e:/\)/,k:c,c:n.concat(["self"]),r:0}]),r:0},{cN:"function",b:"("+t.IR+"[\\*&\\s]+)+"+a,rB:!0,e:/[{;=]/,eE:!0,k:c,i:/[^\w\s\*&]/,c:[{b:a,rB:!0,c:[t.TM],r:0},{cN:"params",b:/\(/,e:/\)/,k:c,r:0,c:[t.CLCM,t.CBCM,r,s,e]},t.CLCM,t.CBCM,i]},{cN:"class",bK:"class struct",e:/[{;:]/,c:[{b://,c:["self"]},t.TM]}]),exports:{preprocessor:i,strings:r,k:c}}});hljs.registerLanguage("x86asm",function(s){return{cI:!0,l:"[.%]?"+s.IR,k:{keyword:"lock rep repe repz repne repnz xaquire xrelease bnd nobnd aaa aad aam aas adc add and arpl bb0_reset bb1_reset bound bsf bsr bswap bt btc btr bts call cbw cdq cdqe clc cld cli clts cmc cmp cmpsb cmpsd cmpsq cmpsw cmpxchg cmpxchg486 cmpxchg8b cmpxchg16b cpuid cpu_read cpu_write cqo cwd cwde daa das dec div dmint emms enter equ f2xm1 fabs fadd faddp fbld fbstp fchs fclex fcmovb fcmovbe fcmove fcmovnb fcmovnbe fcmovne fcmovnu fcmovu fcom fcomi fcomip fcomp fcompp fcos fdecstp fdisi fdiv fdivp fdivr fdivrp femms feni ffree ffreep fiadd ficom ficomp fidiv fidivr fild fimul fincstp finit fist fistp fisttp fisub fisubr fld fld1 fldcw fldenv fldl2e fldl2t fldlg2 fldln2 fldpi fldz fmul fmulp fnclex fndisi fneni fninit fnop fnsave fnstcw fnstenv fnstsw fpatan fprem fprem1 fptan frndint frstor fsave fscale fsetpm fsin fsincos fsqrt fst fstcw fstenv fstp fstsw fsub fsubp fsubr fsubrp ftst fucom fucomi fucomip fucomp fucompp fxam fxch fxtract fyl2x fyl2xp1 hlt ibts icebp idiv imul in inc incbin insb insd insw int int01 int1 int03 int3 into invd invpcid invlpg invlpga iret iretd iretq iretw jcxz jecxz jrcxz jmp jmpe lahf lar lds lea leave les lfence lfs lgdt lgs lidt lldt lmsw loadall loadall286 lodsb lodsd lodsq lodsw loop loope loopne loopnz loopz lsl lss ltr mfence monitor mov movd movq movsb movsd movsq movsw movsx movsxd movzx mul mwait neg nop not or out outsb outsd outsw packssdw packsswb packuswb paddb paddd paddsb paddsiw paddsw paddusb paddusw paddw pand pandn pause paveb pavgusb pcmpeqb pcmpeqd pcmpeqw pcmpgtb pcmpgtd pcmpgtw pdistib pf2id pfacc pfadd pfcmpeq pfcmpge pfcmpgt pfmax pfmin pfmul pfrcp pfrcpit1 pfrcpit2 pfrsqit1 pfrsqrt pfsub pfsubr pi2fd pmachriw pmaddwd pmagw pmulhriw pmulhrwa pmulhrwc pmulhw pmullw pmvgezb pmvlzb pmvnzb pmvzb pop popa popad popaw popf popfd popfq popfw por prefetch prefetchw pslld psllq psllw psrad psraw psrld psrlq psrlw psubb psubd psubsb psubsiw psubsw psubusb psubusw psubw punpckhbw punpckhdq punpckhwd punpcklbw punpckldq punpcklwd push pusha pushad pushaw pushf pushfd pushfq pushfw pxor rcl rcr rdshr rdmsr rdpmc rdtsc rdtscp ret retf retn rol ror rdm rsdc rsldt rsm rsts sahf sal salc sar sbb scasb scasd scasq scasw sfence sgdt shl shld shr shrd sidt sldt skinit smi smint smintold smsw stc std sti stosb stosd stosq stosw str sub svdc svldt svts swapgs syscall sysenter sysexit sysret test ud0 ud1 ud2b ud2 ud2a umov verr verw fwait wbinvd wrshr wrmsr xadd xbts xchg xlatb xlat xor cmove cmovz cmovne cmovnz cmova cmovnbe cmovae cmovnb cmovb cmovnae cmovbe cmovna cmovg cmovnle cmovge cmovnl cmovl cmovnge cmovle cmovng cmovc cmovnc cmovo cmovno cmovs cmovns cmovp cmovpe cmovnp cmovpo je jz jne jnz ja jnbe jae jnb jb jnae jbe jna jg jnle jge jnl jl jnge jle jng jc jnc jo jno js jns jpo jnp jpe jp sete setz setne setnz seta setnbe setae setnb setnc setb setnae setcset setbe setna setg setnle setge setnl setl setnge setle setng sets setns seto setno setpe setp setpo setnp addps addss andnps andps cmpeqps cmpeqss cmpleps cmpless cmpltps cmpltss cmpneqps cmpneqss cmpnleps cmpnless cmpnltps cmpnltss cmpordps cmpordss cmpunordps cmpunordss cmpps cmpss comiss cvtpi2ps cvtps2pi cvtsi2ss cvtss2si cvttps2pi cvttss2si divps divss ldmxcsr maxps maxss minps minss movaps movhps movlhps movlps movhlps movmskps movntps movss movups mulps mulss orps rcpps rcpss rsqrtps rsqrtss shufps sqrtps sqrtss stmxcsr subps subss ucomiss unpckhps unpcklps xorps fxrstor fxrstor64 fxsave fxsave64 xgetbv xsetbv xsave xsave64 xsaveopt xsaveopt64 xrstor xrstor64 prefetchnta prefetcht0 prefetcht1 prefetcht2 maskmovq movntq pavgb pavgw pextrw pinsrw pmaxsw pmaxub pminsw pminub pmovmskb pmulhuw psadbw pshufw pf2iw pfnacc pfpnacc pi2fw pswapd maskmovdqu clflush movntdq movnti movntpd movdqa movdqu movdq2q movq2dq paddq pmuludq pshufd pshufhw pshuflw pslldq psrldq psubq punpckhqdq punpcklqdq addpd addsd andnpd andpd cmpeqpd cmpeqsd cmplepd cmplesd cmpltpd cmpltsd cmpneqpd cmpneqsd cmpnlepd cmpnlesd cmpnltpd cmpnltsd cmpordpd cmpordsd cmpunordpd cmpunordsd cmppd comisd cvtdq2pd cvtdq2ps cvtpd2dq cvtpd2pi cvtpd2ps cvtpi2pd cvtps2dq cvtps2pd cvtsd2si cvtsd2ss cvtsi2sd cvtss2sd cvttpd2pi cvttpd2dq cvttps2dq cvttsd2si divpd divsd maxpd maxsd minpd minsd movapd movhpd movlpd movmskpd movupd mulpd mulsd orpd shufpd sqrtpd sqrtsd subpd subsd ucomisd unpckhpd unpcklpd xorpd addsubpd addsubps haddpd haddps hsubpd hsubps lddqu movddup movshdup movsldup clgi stgi vmcall vmclear vmfunc vmlaunch vmload vmmcall vmptrld vmptrst vmread vmresume vmrun vmsave vmwrite vmxoff vmxon invept invvpid pabsb pabsw pabsd palignr phaddw phaddd phaddsw phsubw phsubd phsubsw pmaddubsw pmulhrsw pshufb psignb psignw psignd extrq insertq movntsd movntss lzcnt blendpd blendps blendvpd blendvps dppd dpps extractps insertps movntdqa mpsadbw packusdw pblendvb pblendw pcmpeqq pextrb pextrd pextrq phminposuw pinsrb pinsrd pinsrq pmaxsb pmaxsd pmaxud pmaxuw pminsb pminsd pminud pminuw pmovsxbw pmovsxbd pmovsxbq pmovsxwd pmovsxwq pmovsxdq pmovzxbw pmovzxbd pmovzxbq pmovzxwd pmovzxwq pmovzxdq pmuldq pmulld ptest roundpd roundps roundsd roundss crc32 pcmpestri pcmpestrm pcmpistri pcmpistrm pcmpgtq popcnt getsec pfrcpv pfrsqrtv movbe aesenc aesenclast aesdec aesdeclast aesimc aeskeygenassist vaesenc vaesenclast vaesdec vaesdeclast vaesimc vaeskeygenassist vaddpd vaddps vaddsd vaddss vaddsubpd vaddsubps vandpd vandps vandnpd vandnps vblendpd vblendps vblendvpd vblendvps vbroadcastss vbroadcastsd vbroadcastf128 vcmpeq_ospd vcmpeqpd vcmplt_ospd vcmpltpd vcmple_ospd vcmplepd vcmpunord_qpd vcmpunordpd vcmpneq_uqpd vcmpneqpd vcmpnlt_uspd vcmpnltpd vcmpnle_uspd vcmpnlepd vcmpord_qpd vcmpordpd vcmpeq_uqpd vcmpnge_uspd vcmpngepd vcmpngt_uspd vcmpngtpd vcmpfalse_oqpd vcmpfalsepd vcmpneq_oqpd vcmpge_ospd vcmpgepd vcmpgt_ospd vcmpgtpd vcmptrue_uqpd vcmptruepd vcmplt_oqpd vcmple_oqpd vcmpunord_spd vcmpneq_uspd vcmpnlt_uqpd vcmpnle_uqpd vcmpord_spd vcmpeq_uspd vcmpnge_uqpd vcmpngt_uqpd vcmpfalse_ospd vcmpneq_ospd vcmpge_oqpd vcmpgt_oqpd vcmptrue_uspd vcmppd vcmpeq_osps vcmpeqps vcmplt_osps vcmpltps vcmple_osps vcmpleps vcmpunord_qps vcmpunordps vcmpneq_uqps vcmpneqps vcmpnlt_usps vcmpnltps vcmpnle_usps vcmpnleps vcmpord_qps vcmpordps vcmpeq_uqps vcmpnge_usps vcmpngeps vcmpngt_usps vcmpngtps vcmpfalse_oqps vcmpfalseps vcmpneq_oqps vcmpge_osps vcmpgeps vcmpgt_osps vcmpgtps vcmptrue_uqps vcmptrueps vcmplt_oqps vcmple_oqps vcmpunord_sps vcmpneq_usps vcmpnlt_uqps vcmpnle_uqps vcmpord_sps vcmpeq_usps vcmpnge_uqps vcmpngt_uqps vcmpfalse_osps vcmpneq_osps vcmpge_oqps vcmpgt_oqps vcmptrue_usps vcmpps vcmpeq_ossd vcmpeqsd vcmplt_ossd vcmpltsd vcmple_ossd vcmplesd vcmpunord_qsd vcmpunordsd vcmpneq_uqsd vcmpneqsd vcmpnlt_ussd vcmpnltsd vcmpnle_ussd vcmpnlesd vcmpord_qsd vcmpordsd vcmpeq_uqsd vcmpnge_ussd vcmpngesd vcmpngt_ussd vcmpngtsd vcmpfalse_oqsd vcmpfalsesd vcmpneq_oqsd vcmpge_ossd vcmpgesd vcmpgt_ossd vcmpgtsd vcmptrue_uqsd vcmptruesd vcmplt_oqsd vcmple_oqsd vcmpunord_ssd vcmpneq_ussd vcmpnlt_uqsd vcmpnle_uqsd vcmpord_ssd vcmpeq_ussd vcmpnge_uqsd vcmpngt_uqsd vcmpfalse_ossd vcmpneq_ossd vcmpge_oqsd vcmpgt_oqsd vcmptrue_ussd vcmpsd vcmpeq_osss vcmpeqss vcmplt_osss vcmpltss vcmple_osss vcmpless vcmpunord_qss vcmpunordss vcmpneq_uqss vcmpneqss vcmpnlt_usss vcmpnltss vcmpnle_usss vcmpnless vcmpord_qss vcmpordss vcmpeq_uqss vcmpnge_usss vcmpngess vcmpngt_usss vcmpngtss vcmpfalse_oqss vcmpfalsess vcmpneq_oqss vcmpge_osss vcmpgess vcmpgt_osss vcmpgtss vcmptrue_uqss vcmptruess vcmplt_oqss vcmple_oqss vcmpunord_sss vcmpneq_usss vcmpnlt_uqss vcmpnle_uqss vcmpord_sss vcmpeq_usss vcmpnge_uqss vcmpngt_uqss vcmpfalse_osss vcmpneq_osss vcmpge_oqss vcmpgt_oqss vcmptrue_usss vcmpss vcomisd vcomiss vcvtdq2pd vcvtdq2ps vcvtpd2dq vcvtpd2ps vcvtps2dq vcvtps2pd vcvtsd2si vcvtsd2ss vcvtsi2sd vcvtsi2ss vcvtss2sd vcvtss2si vcvttpd2dq vcvttps2dq vcvttsd2si vcvttss2si vdivpd vdivps vdivsd vdivss vdppd vdpps vextractf128 vextractps vhaddpd vhaddps vhsubpd vhsubps vinsertf128 vinsertps vlddqu vldqqu vldmxcsr vmaskmovdqu vmaskmovps vmaskmovpd vmaxpd vmaxps vmaxsd vmaxss vminpd vminps vminsd vminss vmovapd vmovaps vmovd vmovq vmovddup vmovdqa vmovqqa vmovdqu vmovqqu vmovhlps vmovhpd vmovhps vmovlhps vmovlpd vmovlps vmovmskpd vmovmskps vmovntdq vmovntqq vmovntdqa vmovntpd vmovntps vmovsd vmovshdup vmovsldup vmovss vmovupd vmovups vmpsadbw vmulpd vmulps vmulsd vmulss vorpd vorps vpabsb vpabsw vpabsd vpacksswb vpackssdw vpackuswb vpackusdw vpaddb vpaddw vpaddd vpaddq vpaddsb vpaddsw vpaddusb vpaddusw vpalignr vpand vpandn vpavgb vpavgw vpblendvb vpblendw vpcmpestri vpcmpestrm vpcmpistri vpcmpistrm vpcmpeqb vpcmpeqw vpcmpeqd vpcmpeqq vpcmpgtb vpcmpgtw vpcmpgtd vpcmpgtq vpermilpd vpermilps vperm2f128 vpextrb vpextrw vpextrd vpextrq vphaddw vphaddd vphaddsw vphminposuw vphsubw vphsubd vphsubsw vpinsrb vpinsrw vpinsrd vpinsrq vpmaddwd vpmaddubsw vpmaxsb vpmaxsw vpmaxsd vpmaxub vpmaxuw vpmaxud vpminsb vpminsw vpminsd vpminub vpminuw vpminud vpmovmskb vpmovsxbw vpmovsxbd vpmovsxbq vpmovsxwd vpmovsxwq vpmovsxdq vpmovzxbw vpmovzxbd vpmovzxbq vpmovzxwd vpmovzxwq vpmovzxdq vpmulhuw vpmulhrsw vpmulhw vpmullw vpmulld vpmuludq vpmuldq vpor vpsadbw vpshufb vpshufd vpshufhw vpshuflw vpsignb vpsignw vpsignd vpslldq vpsrldq vpsllw vpslld vpsllq vpsraw vpsrad vpsrlw vpsrld vpsrlq vptest vpsubb vpsubw vpsubd vpsubq vpsubsb vpsubsw vpsubusb vpsubusw vpunpckhbw vpunpckhwd vpunpckhdq vpunpckhqdq vpunpcklbw vpunpcklwd vpunpckldq vpunpcklqdq vpxor vrcpps vrcpss vrsqrtps vrsqrtss vroundpd vroundps vroundsd vroundss vshufpd vshufps vsqrtpd vsqrtps vsqrtsd vsqrtss vstmxcsr vsubpd vsubps vsubsd vsubss vtestps vtestpd vucomisd vucomiss vunpckhpd vunpckhps vunpcklpd vunpcklps vxorpd vxorps vzeroall vzeroupper pclmullqlqdq pclmulhqlqdq pclmullqhqdq pclmulhqhqdq pclmulqdq vpclmullqlqdq vpclmulhqlqdq vpclmullqhqdq vpclmulhqhqdq vpclmulqdq vfmadd132ps vfmadd132pd vfmadd312ps vfmadd312pd vfmadd213ps vfmadd213pd vfmadd123ps vfmadd123pd vfmadd231ps vfmadd231pd vfmadd321ps vfmadd321pd vfmaddsub132ps vfmaddsub132pd vfmaddsub312ps vfmaddsub312pd vfmaddsub213ps vfmaddsub213pd vfmaddsub123ps vfmaddsub123pd vfmaddsub231ps vfmaddsub231pd vfmaddsub321ps vfmaddsub321pd vfmsub132ps vfmsub132pd vfmsub312ps vfmsub312pd vfmsub213ps vfmsub213pd vfmsub123ps vfmsub123pd vfmsub231ps vfmsub231pd vfmsub321ps vfmsub321pd vfmsubadd132ps vfmsubadd132pd vfmsubadd312ps vfmsubadd312pd vfmsubadd213ps vfmsubadd213pd vfmsubadd123ps vfmsubadd123pd vfmsubadd231ps vfmsubadd231pd vfmsubadd321ps vfmsubadd321pd vfnmadd132ps vfnmadd132pd vfnmadd312ps vfnmadd312pd vfnmadd213ps vfnmadd213pd vfnmadd123ps vfnmadd123pd vfnmadd231ps vfnmadd231pd vfnmadd321ps vfnmadd321pd vfnmsub132ps vfnmsub132pd vfnmsub312ps vfnmsub312pd vfnmsub213ps vfnmsub213pd vfnmsub123ps vfnmsub123pd vfnmsub231ps vfnmsub231pd vfnmsub321ps vfnmsub321pd vfmadd132ss vfmadd132sd vfmadd312ss vfmadd312sd vfmadd213ss vfmadd213sd vfmadd123ss vfmadd123sd vfmadd231ss vfmadd231sd vfmadd321ss vfmadd321sd vfmsub132ss vfmsub132sd vfmsub312ss vfmsub312sd vfmsub213ss vfmsub213sd vfmsub123ss vfmsub123sd vfmsub231ss vfmsub231sd vfmsub321ss vfmsub321sd vfnmadd132ss vfnmadd132sd vfnmadd312ss vfnmadd312sd vfnmadd213ss vfnmadd213sd vfnmadd123ss vfnmadd123sd vfnmadd231ss vfnmadd231sd vfnmadd321ss vfnmadd321sd vfnmsub132ss vfnmsub132sd vfnmsub312ss vfnmsub312sd vfnmsub213ss vfnmsub213sd vfnmsub123ss vfnmsub123sd vfnmsub231ss vfnmsub231sd vfnmsub321ss vfnmsub321sd rdfsbase rdgsbase rdrand wrfsbase wrgsbase vcvtph2ps vcvtps2ph adcx adox rdseed clac stac xstore xcryptecb xcryptcbc xcryptctr xcryptcfb xcryptofb montmul xsha1 xsha256 llwpcb slwpcb lwpval lwpins vfmaddpd vfmaddps vfmaddsd vfmaddss vfmaddsubpd vfmaddsubps vfmsubaddpd vfmsubaddps vfmsubpd vfmsubps vfmsubsd vfmsubss vfnmaddpd vfnmaddps vfnmaddsd vfnmaddss vfnmsubpd vfnmsubps vfnmsubsd vfnmsubss vfrczpd vfrczps vfrczsd vfrczss vpcmov vpcomb vpcomd vpcomq vpcomub vpcomud vpcomuq vpcomuw vpcomw vphaddbd vphaddbq vphaddbw vphadddq vphaddubd vphaddubq vphaddubw vphaddudq vphadduwd vphadduwq vphaddwd vphaddwq vphsubbw vphsubdq vphsubwd vpmacsdd vpmacsdqh vpmacsdql vpmacssdd vpmacssdqh vpmacssdql vpmacsswd vpmacssww vpmacswd vpmacsww vpmadcsswd vpmadcswd vpperm vprotb vprotd vprotq vprotw vpshab vpshad vpshaq vpshaw vpshlb vpshld vpshlq vpshlw vbroadcasti128 vpblendd vpbroadcastb vpbroadcastw vpbroadcastd vpbroadcastq vpermd vpermpd vpermps vpermq vperm2i128 vextracti128 vinserti128 vpmaskmovd vpmaskmovq vpsllvd vpsllvq vpsravd vpsrlvd vpsrlvq vgatherdpd vgatherqpd vgatherdps vgatherqps vpgatherdd vpgatherqd vpgatherdq vpgatherqq xabort xbegin xend xtest andn bextr blci blcic blsi blsic blcfill blsfill blcmsk blsmsk blsr blcs bzhi mulx pdep pext rorx sarx shlx shrx tzcnt tzmsk t1mskc valignd valignq vblendmpd vblendmps vbroadcastf32x4 vbroadcastf64x4 vbroadcasti32x4 vbroadcasti64x4 vcompresspd vcompressps vcvtpd2udq vcvtps2udq vcvtsd2usi vcvtss2usi vcvttpd2udq vcvttps2udq vcvttsd2usi vcvttss2usi vcvtudq2pd vcvtudq2ps vcvtusi2sd vcvtusi2ss vexpandpd vexpandps vextractf32x4 vextractf64x4 vextracti32x4 vextracti64x4 vfixupimmpd vfixupimmps vfixupimmsd vfixupimmss vgetexppd vgetexpps vgetexpsd vgetexpss vgetmantpd vgetmantps vgetmantsd vgetmantss vinsertf32x4 vinsertf64x4 vinserti32x4 vinserti64x4 vmovdqa32 vmovdqa64 vmovdqu32 vmovdqu64 vpabsq vpandd vpandnd vpandnq vpandq vpblendmd vpblendmq vpcmpltd vpcmpled vpcmpneqd vpcmpnltd vpcmpnled vpcmpd vpcmpltq vpcmpleq vpcmpneqq vpcmpnltq vpcmpnleq vpcmpq vpcmpequd vpcmpltud vpcmpleud vpcmpnequd vpcmpnltud vpcmpnleud vpcmpud vpcmpequq vpcmpltuq vpcmpleuq vpcmpnequq vpcmpnltuq vpcmpnleuq vpcmpuq vpcompressd vpcompressq vpermi2d vpermi2pd vpermi2ps vpermi2q vpermt2d vpermt2pd vpermt2ps vpermt2q vpexpandd vpexpandq vpmaxsq vpmaxuq vpminsq vpminuq vpmovdb vpmovdw vpmovqb vpmovqd vpmovqw vpmovsdb vpmovsdw vpmovsqb vpmovsqd vpmovsqw vpmovusdb vpmovusdw vpmovusqb vpmovusqd vpmovusqw vpord vporq vprold vprolq vprolvd vprolvq vprord vprorq vprorvd vprorvq vpscatterdd vpscatterdq vpscatterqd vpscatterqq vpsraq vpsravq vpternlogd vpternlogq vptestmd vptestmq vptestnmd vptestnmq vpxord vpxorq vrcp14pd vrcp14ps vrcp14sd vrcp14ss vrndscalepd vrndscaleps vrndscalesd vrndscaless vrsqrt14pd vrsqrt14ps vrsqrt14sd vrsqrt14ss vscalefpd vscalefps vscalefsd vscalefss vscatterdpd vscatterdps vscatterqpd vscatterqps vshuff32x4 vshuff64x2 vshufi32x4 vshufi64x2 kandnw kandw kmovw knotw kortestw korw kshiftlw kshiftrw kunpckbw kxnorw kxorw vpbroadcastmb2q vpbroadcastmw2d vpconflictd vpconflictq vplzcntd vplzcntq vexp2pd vexp2ps vrcp28pd vrcp28ps vrcp28sd vrcp28ss vrsqrt28pd vrsqrt28ps vrsqrt28sd vrsqrt28ss vgatherpf0dpd vgatherpf0dps vgatherpf0qpd vgatherpf0qps vgatherpf1dpd vgatherpf1dps vgatherpf1qpd vgatherpf1qps vscatterpf0dpd vscatterpf0dps vscatterpf0qpd vscatterpf0qps vscatterpf1dpd vscatterpf1dps vscatterpf1qpd vscatterpf1qps prefetchwt1 bndmk bndcl bndcu bndcn bndmov bndldx bndstx sha1rnds4 sha1nexte sha1msg1 sha1msg2 sha256rnds2 sha256msg1 sha256msg2 hint_nop0 hint_nop1 hint_nop2 hint_nop3 hint_nop4 hint_nop5 hint_nop6 hint_nop7 hint_nop8 hint_nop9 hint_nop10 hint_nop11 hint_nop12 hint_nop13 hint_nop14 hint_nop15 hint_nop16 hint_nop17 hint_nop18 hint_nop19 hint_nop20 hint_nop21 hint_nop22 hint_nop23 hint_nop24 hint_nop25 hint_nop26 hint_nop27 hint_nop28 hint_nop29 hint_nop30 hint_nop31 hint_nop32 hint_nop33 hint_nop34 hint_nop35 hint_nop36 hint_nop37 hint_nop38 hint_nop39 hint_nop40 hint_nop41 hint_nop42 hint_nop43 hint_nop44 hint_nop45 hint_nop46 hint_nop47 hint_nop48 hint_nop49 hint_nop50 hint_nop51 hint_nop52 hint_nop53 hint_nop54 hint_nop55 hint_nop56 hint_nop57 hint_nop58 hint_nop59 hint_nop60 hint_nop61 hint_nop62 hint_nop63",built_in:"ip eip rip al ah bl bh cl ch dl dh sil dil bpl spl r8b r9b r10b r11b r12b r13b r14b r15b ax bx cx dx si di bp sp r8w r9w r10w r11w r12w r13w r14w r15w eax ebx ecx edx esi edi ebp esp eip r8d r9d r10d r11d r12d r13d r14d r15d rax rbx rcx rdx rsi rdi rbp rsp r8 r9 r10 r11 r12 r13 r14 r15 cs ds es fs gs ss st st0 st1 st2 st3 st4 st5 st6 st7 mm0 mm1 mm2 mm3 mm4 mm5 mm6 mm7 xmm0 xmm1 xmm2 xmm3 xmm4 xmm5 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 xmm16 xmm17 xmm18 xmm19 xmm20 xmm21 xmm22 xmm23 xmm24 xmm25 xmm26 xmm27 xmm28 xmm29 xmm30 xmm31 ymm0 ymm1 ymm2 ymm3 ymm4 ymm5 ymm6 ymm7 ymm8 ymm9 ymm10 ymm11 ymm12 ymm13 ymm14 ymm15 ymm16 ymm17 ymm18 ymm19 ymm20 ymm21 ymm22 ymm23 ymm24 ymm25 ymm26 ymm27 ymm28 ymm29 ymm30 ymm31 zmm0 zmm1 zmm2 zmm3 zmm4 zmm5 zmm6 zmm7 zmm8 zmm9 zmm10 zmm11 zmm12 zmm13 zmm14 zmm15 zmm16 zmm17 zmm18 zmm19 zmm20 zmm21 zmm22 zmm23 zmm24 zmm25 zmm26 zmm27 zmm28 zmm29 zmm30 zmm31 k0 k1 k2 k3 k4 k5 k6 k7 bnd0 bnd1 bnd2 bnd3 cr0 cr1 cr2 cr3 cr4 cr8 dr0 dr1 dr2 dr3 dr8 tr3 tr4 tr5 tr6 tr7 r0 r1 r2 r3 r4 r5 r6 r7 r0b r1b r2b r3b r4b r5b r6b r7b r0w r1w r2w r3w r4w r5w r6w r7w r0d r1d r2d r3d r4d r5d r6d r7d r0h r1h r2h r3h r0l r1l r2l r3l r4l r5l r6l r7l r8l r9l r10l r11l r12l r13l r14l r15l db dw dd dq dt ddq do dy dz resb resw resd resq rest resdq reso resy resz incbin equ times byte word dword qword nosplit rel abs seg wrt strict near far a32 ptr",meta:"%define %xdefine %+ %undef %defstr %deftok %assign %strcat %strlen %substr %rotate %elif %else %endif %if %ifmacro %ifctx %ifidn %ifidni %ifid %ifnum %ifstr %iftoken %ifempty %ifenv %error %warning %fatal %rep %endrep %include %push %pop %repl %pathsearch %depend %use %arg %stacksize %local %line %comment %endcomment .nolist __FILE__ __LINE__ __SECT__ __BITS__ __OUTPUT_FORMAT__ __DATE__ __TIME__ __DATE_NUM__ __TIME_NUM__ __UTC_DATE__ __UTC_TIME__ __UTC_DATE_NUM__ __UTC_TIME_NUM__ __PASS__ struc endstruc istruc at iend align alignb sectalign daz nodaz up down zero default option assume public bits use16 use32 use64 default section segment absolute extern global common cpu float __utf16__ __utf16le__ __utf16be__ __utf32__ __utf32le__ __utf32be__ __float8__ __float16__ __float32__ __float64__ __float80m__ __float80e__ __float128l__ __float128h__ __Infinity__ __QNaN__ __SNaN__ Inf NaN QNaN SNaN float8 float16 float32 float64 float80m float80e float128l float128h __FLOAT_DAZ__ __FLOAT_ROUND__ __FLOAT__"},c:[s.C(";","$",{r:0}),{cN:"number",v:[{b:"\\b(?:([0-9][0-9_]*)?\\.[0-9_]*(?:[eE][+-]?[0-9_]+)?|(0[Xx])?[0-9][0-9_]*\\.?[0-9_]*(?:[pP](?:[+-]?[0-9_]+)?)?)\\b",r:0},{b:"\\$[0-9][0-9A-Fa-f]*",r:0},{b:"\\b(?:[0-9A-Fa-f][0-9A-Fa-f_]*[Hh]|[0-9][0-9_]*[DdTt]?|[0-7][0-7_]*[QqOo]|[0-1][0-1_]*[BbYy])\\b"},{b:"\\b(?:0[Xx][0-9A-Fa-f_]+|0[DdTt][0-9_]+|0[QqOo][0-7_]+|0[BbYy][0-1_]+)\\b"}]},s.QSM,{cN:"string",v:[{b:"'",e:"[^\\\\]'"},{b:"`",e:"[^\\\\]`"}],r:0},{cN:"symbol",v:[{b:"^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)"},{b:"^\\s*%%[A-Za-z0-9_$#@~.?]*:"}],r:0},{cN:"subst",b:"%[0-9]+",r:0},{cN:"subst",b:"%!S+",r:0},{cN:"meta",b:/^\s*\.[\w_-]+/}]}});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/\b-?[a-z\._]+\b/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,s,a,t]}});hljs.registerLanguage("shell",function(s){return{aliases:["console"],c:[{cN:"meta",b:"^\\s{0,3}[\\w\\d\\[\\]()@-]*[>%$#]",starts:{e:"$",sL:"bash"}}]}});hljs.registerLanguage("http",function(e){var t="HTTP/[0-9\\.]+";return{aliases:["https"],i:"\\S",c:[{b:"^"+t,e:"$",c:[{cN:"number",b:"\\b\\d{3}\\b"}]},{b:"^[A-Z]+ (.*?) "+t+"$",rB:!0,e:"$",c:[{cN:"string",b:" ",e:" ",eB:!0,eE:!0},{b:t},{cN:"keyword",b:"[A-Z]+"}]},{cN:"attribute",b:"^\\w",e:": ",eE:!0,i:"\\n|\\s|=",starts:{e:"$",r:0}},{b:"\\n\\n",starts:{sL:[],eW:!0}}]}});hljs.registerLanguage("cs",function(e){var i={keyword:"abstract as base bool break byte case catch char checked const continue decimal default delegate do double enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long nameof object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual void volatile while add alias ascending async await by descending dynamic equals from get global group into join let on orderby partial remove select set value var where yield",literal:"null false true"},t={cN:"string",b:'@"',e:'"',c:[{b:'""'}]},r=e.inherit(t,{i:/\n/}),a={cN:"subst",b:"{",e:"}",k:i},c=e.inherit(a,{i:/\n/}),n={cN:"string",b:/\$"/,e:'"',i:/\n/,c:[{b:"{{"},{b:"}}"},e.BE,c]},s={cN:"string",b:/\$@"/,e:'"',c:[{b:"{{"},{b:"}}"},{b:'""'},a]},o=e.inherit(s,{i:/\n/,c:[{b:"{{"},{b:"}}"},{b:'""'},c]});a.c=[s,n,t,e.ASM,e.QSM,e.CNM,e.CBCM],c.c=[o,n,r,e.ASM,e.QSM,e.CNM,e.inherit(e.CBCM,{i:/\n/})];var l={v:[s,n,t,e.ASM,e.QSM]},b=e.IR+"(<"+e.IR+"(\\s*,\\s*"+e.IR+")*>)?(\\[\\])?";return{aliases:["csharp"],k:i,i:/::/,c:[e.C("///","$",{rB:!0,c:[{cN:"doctag",v:[{b:"///",r:0},{b:""},{b:""}]}]}),e.CLCM,e.CBCM,{cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elif endif define undef warning error line region endregion pragma checksum"}},l,e.CNM,{bK:"class interface",e:/[{;=]/,i:/[^\s:]/,c:[e.TM,e.CLCM,e.CBCM]},{bK:"namespace",e:/[{;=]/,i:/[^\s:]/,c:[e.inherit(e.TM,{b:"[a-zA-Z](\\.?\\w)*"}),e.CLCM,e.CBCM]},{cN:"meta",b:"^\\s*\\[",eB:!0,e:"\\]",eE:!0,c:[{cN:"meta-string",b:/"/,e:/"/}]},{bK:"new return throw await else",r:0},{cN:"function",b:"("+b+"\\s+)+"+e.IR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:i,c:[{b:e.IR+"\\s*\\(",rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:i,r:0,c:[l,e.CNM,e.CBCM]},e.CLCM,e.CBCM]}]}});hljs.registerLanguage("coffeescript",function(e){var c={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super yield import export from as default await then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",built_in:"npm require console print module global window document"},n="[A-Za-z$_][0-9A-Za-z$_]*",r={cN:"subst",b:/#\{/,e:/}/,k:c},i=[e.BNM,e.inherit(e.CNM,{starts:{e:"(\\s*/)?",r:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,r]},{b:/"/,e:/"/,c:[e.BE,r]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[r,e.HCM]},{b:"//[gim]*",r:0},{b:/\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/}]},{b:"@"+n},{sL:"javascript",eB:!0,eE:!0,v:[{b:"```",e:"```"},{b:"`",e:"`"}]}];r.c=i;var s=e.inherit(e.TM,{b:n}),t="(\\(.*\\))?\\s*\\B[-=]>",o={cN:"params",b:"\\([^\\(]",rB:!0,c:[{b:/\(/,e:/\)/,k:c,c:["self"].concat(i)}]};return{aliases:["coffee","cson","iced"],k:c,i:/\/\*/,c:i.concat([e.C("###","###"),e.HCM,{cN:"function",b:"^\\s*"+n+"\\s*=\\s*"+t,e:"[-=]>",rB:!0,c:[s,o]},{b:/[:\(,=]\s*/,r:0,c:[{cN:"function",b:t,e:"[-=]>",rB:!0,c:[o]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[s]},s]},{b:n+":",e:":",rB:!0,rE:!0,r:0}])}});hljs.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*#]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null",built_in:"array bigint binary bit blob boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t]},e.CBCM,t]}});hljs.registerLanguage("apache",function(e){var r={cN:"number",b:"[\\$%]\\d+"};return{aliases:["apacheconf"],cI:!0,c:[e.HCM,{cN:"section",b:""},{cN:"attribute",b:/\w+/,r:0,k:{nomarkup:"order deny allow setenv rewriterule rewriteengine rewritecond documentroot sethandler errordocument loadmodule options header listen serverroot servername"},starts:{e:/$/,r:0,k:{literal:"on off all"},c:[{cN:"meta",b:"\\s\\[",e:"\\]$"},{cN:"variable",b:"[\\$%]\\{",e:"\\}",c:["self",r]},r,e.QSM]}}],i:/\S/}});hljs.registerLanguage("haskell",function(e){var i={v:[e.C("--","$"),e.C("{-","-}",{c:["self"]})]},a={cN:"meta",b:"{-#",e:"#-}"},l={cN:"meta",b:"^#",e:"$"},c={cN:"type",b:"\\b[A-Z][\\w']*",r:0},n={b:"\\(",e:"\\)",i:'"',c:[a,l,{cN:"type",b:"\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"},e.inherit(e.TM,{b:"[_a-z][\\w']*"}),i]},s={b:"{",e:"}",c:n.c};return{aliases:["hs"],k:"let in if then else case of where do module import hiding qualified type data newtype deriving class instance as default infix infixl infixr foreign export ccall stdcall cplusplus jvm dotnet safe unsafe family forall mdo proc rec",c:[{bK:"module",e:"where",k:"module where",c:[n,i],i:"\\W\\.|;"},{b:"\\bimport\\b",e:"$",k:"import qualified as hiding",c:[n,i],i:"\\W\\.|;"},{cN:"class",b:"^(\\s*)?(class|instance)\\b",e:"where",k:"class family instance where",c:[c,n,i]},{cN:"class",b:"\\b(data|(new)?type)\\b",e:"$",k:"data family type newtype deriving",c:[a,c,n,s,i]},{bK:"default",e:"$",c:[c,n,i]},{bK:"infix infixl infixr",e:"$",c:[e.CNM,i]},{b:"\\bforeign\\b",e:"$",k:"foreign import export ccall stdcall cplusplus jvm dotnet safe unsafe",c:[c,e.QSM,i]},{cN:"meta",b:"#!\\/usr\\/bin\\/env runhaskell",e:"$"},a,l,e.QSM,e.CNM,c,e.inherit(e.TM,{b:"^[_a-z][\\w']*"}),i,{b:"->|<-"}]}});hljs.registerLanguage("scala",function(e){var t={cN:"meta",b:"@[A-Za-z]+"},a={cN:"subst",v:[{b:"\\$[A-Za-z0-9_]+"},{b:"\\${",e:"}"}]},r={cN:"string",v:[{b:'"',e:'"',i:"\\n",c:[e.BE]},{b:'"""',e:'"""',r:10},{b:'[a-z]+"',e:'"',i:"\\n",c:[e.BE,a]},{cN:"string",b:'[a-z]+"""',e:'"""',c:[a],r:10}]},c={cN:"symbol",b:"'\\w[\\w\\d_]*(?!')"},i={cN:"type",b:"\\b[A-Z][A-Za-z0-9_]*",r:0},s={cN:"title",b:/[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/,r:0},n={cN:"class",bK:"class object trait type",e:/[:={\[\n;]/,eE:!0,c:[{bK:"extends with",r:10},{b:/\[/,e:/\]/,eB:!0,eE:!0,r:0,c:[i]},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,r:0,c:[i]},s]},l={cN:"function",bK:"def",e:/[:={\[(\n;]/,eE:!0,c:[s]};return{k:{literal:"true false null",keyword:"type yield lazy override def with val var sealed abstract private trait object if forSome for while throw finally protected extends import final return else break new catch super class case package default try this match continue throws implicit"},c:[e.CLCM,e.CBCM,r,c,i,l,n,e.CNM,t]}}); \ No newline at end of file diff --git a/docs/guide/index.html b/docs/guide/index.html new file mode 100644 index 0000000..d518369 --- /dev/null +++ b/docs/guide/index.html @@ -0,0 +1,184 @@ + + + + + + Chapter 1 - Elefren Guide + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+
+

Chapter 1

+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/guide/mark.min.js b/docs/guide/mark.min.js new file mode 100644 index 0000000..1636231 --- /dev/null +++ b/docs/guide/mark.min.js @@ -0,0 +1,7 @@ +/*!*************************************************** +* mark.js v8.11.1 +* https://markjs.io/ +* Copyright (c) 2014–2018, Julian Kühnel +* Released under the MIT license https://git.io/vwTVl +*****************************************************/ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.Mark=t()}(this,function(){"use strict";var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},n=function(){function e(e,t){for(var n=0;n1&&void 0!==arguments[1])||arguments[1],i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:5e3;t(this,e),this.ctx=n,this.iframes=r,this.exclude=i,this.iframesTimeout=o}return n(e,[{key:"getContexts",value:function(){var e=[];return(void 0!==this.ctx&&this.ctx?NodeList.prototype.isPrototypeOf(this.ctx)?Array.prototype.slice.call(this.ctx):Array.isArray(this.ctx)?this.ctx:"string"==typeof this.ctx?Array.prototype.slice.call(document.querySelectorAll(this.ctx)):[this.ctx]:[]).forEach(function(t){var n=e.filter(function(e){return e.contains(t)}).length>0;-1!==e.indexOf(t)||n||e.push(t)}),e}},{key:"getIframeContents",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){},r=void 0;try{var i=e.contentWindow;if(r=i.document,!i||!r)throw new Error("iframe inaccessible")}catch(e){n()}r&&t(r)}},{key:"isIframeBlank",value:function(e){var t="about:blank",n=e.getAttribute("src").trim();return e.contentWindow.location.href===t&&n!==t&&n}},{key:"observeIframeLoad",value:function(e,t,n){var r=this,i=!1,o=null,a=function a(){if(!i){i=!0,clearTimeout(o);try{r.isIframeBlank(e)||(e.removeEventListener("load",a),r.getIframeContents(e,t,n))}catch(e){n()}}};e.addEventListener("load",a),o=setTimeout(a,this.iframesTimeout)}},{key:"onIframeReady",value:function(e,t,n){try{"complete"===e.contentWindow.document.readyState?this.isIframeBlank(e)?this.observeIframeLoad(e,t,n):this.getIframeContents(e,t,n):this.observeIframeLoad(e,t,n)}catch(e){n()}}},{key:"waitForIframes",value:function(e,t){var n=this,r=0;this.forEachIframe(e,function(){return!0},function(e){r++,n.waitForIframes(e.querySelector("html"),function(){--r||t()})},function(e){e||t()})}},{key:"forEachIframe",value:function(t,n,r){var i=this,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){},a=t.querySelectorAll("iframe"),s=a.length,c=0;a=Array.prototype.slice.call(a);var u=function(){--s<=0&&o(c)};s||u(),a.forEach(function(t){e.matches(t,i.exclude)?u():i.onIframeReady(t,function(e){n(t)&&(c++,r(e)),u()},u)})}},{key:"createIterator",value:function(e,t,n){return document.createNodeIterator(e,t,n,!1)}},{key:"createInstanceOnIframe",value:function(t){return new e(t.querySelector("html"),this.iframes)}},{key:"compareNodeIframe",value:function(e,t,n){if(e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_PRECEDING){if(null===t)return!0;if(t.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)return!0}return!1}},{key:"getIteratorNode",value:function(e){var t=e.previousNode();return{prevNode:t,node:null===t?e.nextNode():e.nextNode()&&e.nextNode()}}},{key:"checkIframeFilter",value:function(e,t,n,r){var i=!1,o=!1;return r.forEach(function(e,t){e.val===n&&(i=t,o=e.handled)}),this.compareNodeIframe(e,t,n)?(!1!==i||o?!1===i||o||(r[i].handled=!0):r.push({val:n,handled:!0}),!0):(!1===i&&r.push({val:n,handled:!1}),!1)}},{key:"handleOpenIframes",value:function(e,t,n,r){var i=this;e.forEach(function(e){e.handled||i.getIframeContents(e.val,function(e){i.createInstanceOnIframe(e).forEachNode(t,n,r)})})}},{key:"iterateThroughNodes",value:function(e,t,n,r,i){for(var o,a=this,s=this.createIterator(t,e,r),c=[],u=[],l=void 0,h=void 0;void 0,o=a.getIteratorNode(s),h=o.prevNode,l=o.node;)this.iframes&&this.forEachIframe(t,function(e){return a.checkIframeFilter(l,h,e,c)},function(t){a.createInstanceOnIframe(t).forEachNode(e,function(e){return u.push(e)},r)}),u.push(l);u.forEach(function(e){n(e)}),this.iframes&&this.handleOpenIframes(c,e,n,r),i()}},{key:"forEachNode",value:function(e,t,n){var r=this,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){},o=this.getContexts(),a=o.length;a||i(),o.forEach(function(o){var s=function(){r.iterateThroughNodes(e,o,t,n,function(){--a<=0&&i()})};r.iframes?r.waitForIframes(o,s):s()})}}],[{key:"matches",value:function(e,t){var n="string"==typeof t?[t]:t,r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector;if(r){var i=!1;return n.every(function(t){return!r.call(e,t)||(i=!0,!1)}),i}return!1}}]),e}(),o=function(){function e(n){t(this,e),this.opt=r({},{diacritics:!0,synonyms:{},accuracy:"partially",caseSensitive:!1,ignoreJoiners:!1,ignorePunctuation:[],wildcards:"disabled"},n)}return n(e,[{key:"create",value:function(e){return"disabled"!==this.opt.wildcards&&(e=this.setupWildcardsRegExp(e)),e=this.escapeStr(e),Object.keys(this.opt.synonyms).length&&(e=this.createSynonymsRegExp(e)),(this.opt.ignoreJoiners||this.opt.ignorePunctuation.length)&&(e=this.setupIgnoreJoinersRegExp(e)),this.opt.diacritics&&(e=this.createDiacriticsRegExp(e)),e=this.createMergedBlanksRegExp(e),(this.opt.ignoreJoiners||this.opt.ignorePunctuation.length)&&(e=this.createJoinersRegExp(e)),"disabled"!==this.opt.wildcards&&(e=this.createWildcardsRegExp(e)),e=this.createAccuracyRegExp(e),new RegExp(e,"gm"+(this.opt.caseSensitive?"":"i"))}},{key:"escapeStr",value:function(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}},{key:"createSynonymsRegExp",value:function(e){var t=this.opt.synonyms,n=this.opt.caseSensitive?"":"i",r=this.opt.ignoreJoiners||this.opt.ignorePunctuation.length?"\0":"";for(var i in t)if(t.hasOwnProperty(i)){var o=t[i],a="disabled"!==this.opt.wildcards?this.setupWildcardsRegExp(i):this.escapeStr(i),s="disabled"!==this.opt.wildcards?this.setupWildcardsRegExp(o):this.escapeStr(o);""!==a&&""!==s&&(e=e.replace(new RegExp("("+this.escapeStr(a)+"|"+this.escapeStr(s)+")","gm"+n),r+"("+this.processSynonyms(a)+"|"+this.processSynonyms(s)+")"+r))}return e}},{key:"processSynonyms",value:function(e){return(this.opt.ignoreJoiners||this.opt.ignorePunctuation.length)&&(e=this.setupIgnoreJoinersRegExp(e)),e}},{key:"setupWildcardsRegExp",value:function(e){return(e=e.replace(/(?:\\)*\?/g,function(e){return"\\"===e.charAt(0)?"?":""})).replace(/(?:\\)*\*/g,function(e){return"\\"===e.charAt(0)?"*":""})}},{key:"createWildcardsRegExp",value:function(e){var t="withSpaces"===this.opt.wildcards;return e.replace(/\u0001/g,t?"[\\S\\s]?":"\\S?").replace(/\u0002/g,t?"[\\S\\s]*?":"\\S*")}},{key:"setupIgnoreJoinersRegExp",value:function(e){return e.replace(/[^(|)\\]/g,function(e,t,n){var r=n.charAt(t+1);return/[(|)\\]/.test(r)||""===r?e:e+"\0"})}},{key:"createJoinersRegExp",value:function(e){var t=[],n=this.opt.ignorePunctuation;return Array.isArray(n)&&n.length&&t.push(this.escapeStr(n.join(""))),this.opt.ignoreJoiners&&t.push("\\u00ad\\u200b\\u200c\\u200d"),t.length?e.split(/\u0000+/).join("["+t.join("")+"]*"):e}},{key:"createDiacriticsRegExp",value:function(e){var t=this.opt.caseSensitive?"":"i",n=this.opt.caseSensitive?["aàáảãạăằắẳẵặâầấẩẫậäåāą","AÀÁẢÃẠĂẰẮẲẴẶÂẦẤẨẪẬÄÅĀĄ","cçćč","CÇĆČ","dđď","DĐĎ","eèéẻẽẹêềếểễệëěēę","EÈÉẺẼẸÊỀẾỂỄỆËĚĒĘ","iìíỉĩịîïī","IÌÍỈĨỊÎÏĪ","lł","LŁ","nñňń","NÑŇŃ","oòóỏõọôồốổỗộơởỡớờợöøō","OÒÓỎÕỌÔỒỐỔỖỘƠỞỠỚỜỢÖØŌ","rř","RŘ","sšśșş","SŠŚȘŞ","tťțţ","TŤȚŢ","uùúủũụưừứửữựûüůū","UÙÚỦŨỤƯỪỨỬỮỰÛÜŮŪ","yýỳỷỹỵÿ","YÝỲỶỸỴŸ","zžżź","ZŽŻŹ"]:["aàáảãạăằắẳẵặâầấẩẫậäåāąAÀÁẢÃẠĂẰẮẲẴẶÂẦẤẨẪẬÄÅĀĄ","cçćčCÇĆČ","dđďDĐĎ","eèéẻẽẹêềếểễệëěēęEÈÉẺẼẸÊỀẾỂỄỆËĚĒĘ","iìíỉĩịîïīIÌÍỈĨỊÎÏĪ","lłLŁ","nñňńNÑŇŃ","oòóỏõọôồốổỗộơởỡớờợöøōOÒÓỎÕỌÔỒỐỔỖỘƠỞỠỚỜỢÖØŌ","rřRŘ","sšśșşSŠŚȘŞ","tťțţTŤȚŢ","uùúủũụưừứửữựûüůūUÙÚỦŨỤƯỪỨỬỮỰÛÜŮŪ","yýỳỷỹỵÿYÝỲỶỸỴŸ","zžżźZŽŻŹ"],r=[];return e.split("").forEach(function(i){n.every(function(n){if(-1!==n.indexOf(i)){if(r.indexOf(n)>-1)return!1;e=e.replace(new RegExp("["+n+"]","gm"+t),"["+n+"]"),r.push(n)}return!0})}),e}},{key:"createMergedBlanksRegExp",value:function(e){return e.replace(/[\s]+/gim,"[\\s]+")}},{key:"createAccuracyRegExp",value:function(e){var t=this,n=this.opt.accuracy,r="string"==typeof n?n:n.value,i="";switch(("string"==typeof n?[]:n.limiters).forEach(function(e){i+="|"+t.escapeStr(e)}),r){case"partially":default:return"()("+e+")";case"complementary":return"()([^"+(i="\\s"+(i||this.escapeStr("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~¡¿")))+"]*"+e+"[^"+i+"]*)";case"exactly":return"(^|\\s"+i+")("+e+")(?=$|\\s"+i+")"}}}]),e}(),a=function(){function a(e){t(this,a),this.ctx=e,this.ie=!1;var n=window.navigator.userAgent;(n.indexOf("MSIE")>-1||n.indexOf("Trident")>-1)&&(this.ie=!0)}return n(a,[{key:"log",value:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"debug",r=this.opt.log;this.opt.debug&&"object"===(void 0===r?"undefined":e(r))&&"function"==typeof r[n]&&r[n]("mark.js: "+t)}},{key:"getSeparatedKeywords",value:function(e){var t=this,n=[];return e.forEach(function(e){t.opt.separateWordSearch?e.split(" ").forEach(function(e){e.trim()&&-1===n.indexOf(e)&&n.push(e)}):e.trim()&&-1===n.indexOf(e)&&n.push(e)}),{keywords:n.sort(function(e,t){return t.length-e.length}),length:n.length}}},{key:"isNumeric",value:function(e){return Number(parseFloat(e))==e}},{key:"checkRanges",value:function(e){var t=this;if(!Array.isArray(e)||"[object Object]"!==Object.prototype.toString.call(e[0]))return this.log("markRanges() will only accept an array of objects"),this.opt.noMatch(e),[];var n=[],r=0;return e.sort(function(e,t){return e.start-t.start}).forEach(function(e){var i=t.callNoMatchOnInvalidRanges(e,r),o=i.start,a=i.end;i.valid&&(e.start=o,e.length=a-o,n.push(e),r=a)}),n}},{key:"callNoMatchOnInvalidRanges",value:function(e,t){var n=void 0,r=void 0,i=!1;return e&&void 0!==e.start?(r=(n=parseInt(e.start,10))+parseInt(e.length,10),this.isNumeric(e.start)&&this.isNumeric(e.length)&&r-t>0&&r-n>0?i=!0:(this.log("Ignoring invalid or overlapping range: "+JSON.stringify(e)),this.opt.noMatch(e))):(this.log("Ignoring invalid range: "+JSON.stringify(e)),this.opt.noMatch(e)),{start:n,end:r,valid:i}}},{key:"checkWhitespaceRanges",value:function(e,t,n){var r=void 0,i=!0,o=n.length,a=t-o,s=parseInt(e.start,10)-a;return(r=(s=s>o?o:s)+parseInt(e.length,10))>o&&(r=o,this.log("End range automatically set to the max value of "+o)),s<0||r-s<0||s>o||r>o?(i=!1,this.log("Invalid range: "+JSON.stringify(e)),this.opt.noMatch(e)):""===n.substring(s,r).replace(/\s+/g,"")&&(i=!1,this.log("Skipping whitespace only range: "+JSON.stringify(e)),this.opt.noMatch(e)),{start:s,end:r,valid:i}}},{key:"getTextNodes",value:function(e){var t=this,n="",r=[];this.iterator.forEachNode(NodeFilter.SHOW_TEXT,function(e){r.push({start:n.length,end:(n+=e.textContent).length,node:e})},function(e){return t.matchesExclude(e.parentNode)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT},function(){e({value:n,nodes:r})})}},{key:"matchesExclude",value:function(e){return i.matches(e,this.opt.exclude.concat(["script","style","title","head","html"]))}},{key:"wrapRangeInTextNode",value:function(e,t,n){var r=this.opt.element?this.opt.element:"mark",i=e.splitText(t),o=i.splitText(n-t),a=document.createElement(r);return a.setAttribute("data-markjs","true"),this.opt.className&&a.setAttribute("class",this.opt.className),a.textContent=i.textContent,i.parentNode.replaceChild(a,i),o}},{key:"wrapRangeInMappedTextNode",value:function(e,t,n,r,i){var o=this;e.nodes.every(function(a,s){var c=e.nodes[s+1];if(void 0===c||c.start>t){if(!r(a.node))return!1;var u=t-a.start,l=(n>a.end?a.end:n)-a.start,h=e.value.substr(0,a.start),f=e.value.substr(l+a.start);if(a.node=o.wrapRangeInTextNode(a.node,u,l),e.value=h+f,e.nodes.forEach(function(t,n){n>=s&&(e.nodes[n].start>0&&n!==s&&(e.nodes[n].start-=l),e.nodes[n].end-=l)}),n-=l,i(a.node.previousSibling,a.start),!(n>a.end))return!1;t=a.end}return!0})}},{key:"wrapGroups",value:function(e,t,n,r){return r((e=this.wrapRangeInTextNode(e,t,t+n)).previousSibling),e}},{key:"separateGroups",value:function(e,t,n,r,i){for(var o=t.length,a=1;a-1&&r(t[a],e)&&(e=this.wrapGroups(e,s,t[a].length,i))}return e}},{key:"wrapMatches",value:function(e,t,n,r,i){var o=this,a=0===t?0:t+1;this.getTextNodes(function(t){t.nodes.forEach(function(t){t=t.node;for(var i=void 0;null!==(i=e.exec(t.textContent))&&""!==i[a];){if(o.opt.separateGroups)t=o.separateGroups(t,i,a,n,r);else{if(!n(i[a],t))continue;var s=i.index;if(0!==a)for(var c=1;c + + + + + Elefren Guide + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+
+

Chapter 1

+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/guide/searcher.js b/docs/guide/searcher.js new file mode 100644 index 0000000..7fd97d4 --- /dev/null +++ b/docs/guide/searcher.js @@ -0,0 +1,477 @@ +"use strict"; +window.search = window.search || {}; +(function search(search) { + // Search functionality + // + // You can use !hasFocus() to prevent keyhandling in your key + // event handlers while the user is typing their search. + + if (!Mark || !elasticlunr) { + return; + } + + //IE 11 Compatibility from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + if (!String.prototype.startsWith) { + String.prototype.startsWith = function(search, pos) { + return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + }; + } + + var search_wrap = document.getElementById('search-wrapper'), + searchbar = document.getElementById('searchbar'), + searchbar_outer = document.getElementById('searchbar-outer'), + searchresults = document.getElementById('searchresults'), + searchresults_outer = document.getElementById('searchresults-outer'), + searchresults_header = document.getElementById('searchresults-header'), + searchicon = document.getElementById('search-toggle'), + content = document.getElementById('content'), + + searchindex = null, + doc_urls = [], + results_options = { + teaser_word_count: 30, + limit_results: 30, + }, + search_options = { + bool: "AND", + expand: true, + fields: { + title: {boost: 1}, + body: {boost: 1}, + breadcrumbs: {boost: 0} + } + }, + mark_exclude = [], + marker = new Mark(content), + current_searchterm = "", + URL_SEARCH_PARAM = 'search', + URL_MARK_PARAM = 'highlight', + teaser_count = 0, + + SEARCH_HOTKEY_KEYCODE = 83, + ESCAPE_KEYCODE = 27, + DOWN_KEYCODE = 40, + UP_KEYCODE = 38, + SELECT_KEYCODE = 13; + + function hasFocus() { + return searchbar === document.activeElement; + } + + function removeChildren(elem) { + while (elem.firstChild) { + elem.removeChild(elem.firstChild); + } + } + + // Helper to parse a url into its building blocks. + function parseURL(url) { + var a = document.createElement('a'); + a.href = url; + return { + source: url, + protocol: a.protocol.replace(':',''), + host: a.hostname, + port: a.port, + params: (function(){ + var ret = {}; + var seg = a.search.replace(/^\?/,'').split('&'); + var len = seg.length, i = 0, s; + for (;i': '>', + '"': '"', + "'": ''' + }; + var repl = function(c) { return MAP[c]; }; + return function(s) { + return s.replace(/[&<>'"]/g, repl); + }; + })(); + + function formatSearchMetric(count, searchterm) { + if (count == 1) { + return count + " search result for '" + searchterm + "':"; + } else if (count == 0) { + return "No search results for '" + searchterm + "'."; + } else { + return count + " search results for '" + searchterm + "':"; + } + } + + function formatSearchResult(result, searchterms) { + var teaser = makeTeaser(escapeHTML(result.doc.body), searchterms); + teaser_count++; + + // The ?URL_MARK_PARAM= parameter belongs inbetween the page and the #heading-anchor + var url = doc_urls[result.ref].split("#"); + if (url.length == 1) { // no anchor found + url.push(""); + } + + return '' + result.doc.breadcrumbs + '' + + '' + + teaser + ''; + } + + function makeTeaser(body, searchterms) { + // The strategy is as follows: + // First, assign a value to each word in the document: + // Words that correspond to search terms (stemmer aware): 40 + // Normal words: 2 + // First word in a sentence: 8 + // Then use a sliding window with a constant number of words and count the + // sum of the values of the words within the window. Then use the window that got the + // maximum sum. If there are multiple maximas, then get the last one. + // Enclose the terms in . + var stemmed_searchterms = searchterms.map(function(w) { + return elasticlunr.stemmer(w.toLowerCase()); + }); + var searchterm_weight = 40; + var weighted = []; // contains elements of ["word", weight, index_in_document] + // split in sentences, then words + var sentences = body.toLowerCase().split('. '); + var index = 0; + var value = 0; + var searchterm_found = false; + for (var sentenceindex in sentences) { + var words = sentences[sentenceindex].split(' '); + value = 8; + for (var wordindex in words) { + var word = words[wordindex]; + if (word.length > 0) { + for (var searchtermindex in stemmed_searchterms) { + if (elasticlunr.stemmer(word).startsWith(stemmed_searchterms[searchtermindex])) { + value = searchterm_weight; + searchterm_found = true; + } + }; + weighted.push([word, value, index]); + value = 2; + } + index += word.length; + index += 1; // ' ' or '.' if last word in sentence + }; + index += 1; // because we split at a two-char boundary '. ' + }; + + if (weighted.length == 0) { + return body; + } + + var window_weight = []; + var window_size = Math.min(weighted.length, results_options.teaser_word_count); + + var cur_sum = 0; + for (var wordindex = 0; wordindex < window_size; wordindex++) { + cur_sum += weighted[wordindex][1]; + }; + window_weight.push(cur_sum); + for (var wordindex = 0; wordindex < weighted.length - window_size; wordindex++) { + cur_sum -= weighted[wordindex][1]; + cur_sum += weighted[wordindex + window_size][1]; + window_weight.push(cur_sum); + }; + + if (searchterm_found) { + var max_sum = 0; + var max_sum_window_index = 0; + // backwards + for (var i = window_weight.length - 1; i >= 0; i--) { + if (window_weight[i] > max_sum) { + max_sum = window_weight[i]; + max_sum_window_index = i; + } + }; + } else { + max_sum_window_index = 0; + } + + // add around searchterms + var teaser_split = []; + var index = weighted[max_sum_window_index][2]; + for (var i = max_sum_window_index; i < max_sum_window_index+window_size; i++) { + var word = weighted[i]; + if (index < word[2]) { + // missing text from index to start of `word` + teaser_split.push(body.substring(index, word[2])); + index = word[2]; + } + if (word[1] == searchterm_weight) { + teaser_split.push("") + } + index = word[2] + word[0].length; + teaser_split.push(body.substring(word[2], index)); + if (word[1] == searchterm_weight) { + teaser_split.push("") + } + }; + + return teaser_split.join(''); + } + + function init(config) { + results_options = config.results_options; + search_options = config.search_options; + searchbar_outer = config.searchbar_outer; + doc_urls = config.doc_urls; + searchindex = elasticlunr.Index.load(config.index); + + // Set up events + searchicon.addEventListener('click', function(e) { searchIconClickHandler(); }, false); + searchbar.addEventListener('keyup', function(e) { searchbarKeyUpHandler(); }, false); + document.addEventListener('keydown', function(e) { globalKeyHandler(e); }, false); + // If the user uses the browser buttons, do the same as if a reload happened + window.onpopstate = function(e) { doSearchOrMarkFromUrl(); }; + // Suppress "submit" events so the page doesn't reload when the user presses Enter + document.addEventListener('submit', function(e) { e.preventDefault(); }, false); + + // If reloaded, do the search or mark again, depending on the current url parameters + doSearchOrMarkFromUrl(); + } + + function unfocusSearchbar() { + // hacky, but just focusing a div only works once + var tmp = document.createElement('input'); + tmp.setAttribute('style', 'position: absolute; opacity: 0;'); + searchicon.appendChild(tmp); + tmp.focus(); + tmp.remove(); + } + + // On reload or browser history backwards/forwards events, parse the url and do search or mark + function doSearchOrMarkFromUrl() { + // Check current URL for search request + var url = parseURL(window.location.href); + if (url.params.hasOwnProperty(URL_SEARCH_PARAM) + && url.params[URL_SEARCH_PARAM] != "") { + showSearch(true); + searchbar.value = decodeURIComponent( + (url.params[URL_SEARCH_PARAM]+'').replace(/\+/g, '%20')); + searchbarKeyUpHandler(); // -> doSearch() + } else { + showSearch(false); + } + + if (url.params.hasOwnProperty(URL_MARK_PARAM)) { + var words = url.params[URL_MARK_PARAM].split(' '); + marker.mark(words, { + exclude: mark_exclude + }); + + var markers = document.querySelectorAll("mark"); + function hide() { + for (var i = 0; i < markers.length; i++) { + markers[i].classList.add("fade-out"); + window.setTimeout(function(e) { marker.unmark(); }, 300); + } + } + for (var i = 0; i < markers.length; i++) { + markers[i].addEventListener('click', hide); + } + } + } + + // Eventhandler for keyevents on `document` + function globalKeyHandler(e) { + if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey || e.target.type === 'textarea') { return; } + + if (e.keyCode === ESCAPE_KEYCODE) { + e.preventDefault(); + searchbar.classList.remove("active"); + setSearchUrlParameters("", + (searchbar.value.trim() !== "") ? "push" : "replace"); + if (hasFocus()) { + unfocusSearchbar(); + } + showSearch(false); + marker.unmark(); + } else if (!hasFocus() && e.keyCode === SEARCH_HOTKEY_KEYCODE) { + e.preventDefault(); + showSearch(true); + window.scrollTo(0, 0); + searchbar.select(); + } else if (hasFocus() && e.keyCode === DOWN_KEYCODE) { + e.preventDefault(); + unfocusSearchbar(); + searchresults.firstElementChild.classList.add("focus"); + } else if (!hasFocus() && (e.keyCode === DOWN_KEYCODE + || e.keyCode === UP_KEYCODE + || e.keyCode === SELECT_KEYCODE)) { + // not `:focus` because browser does annoying scrolling + var focused = searchresults.querySelector("li.focus"); + if (!focused) return; + e.preventDefault(); + if (e.keyCode === DOWN_KEYCODE) { + var next = focused.nextElementSibling; + if (next) { + focused.classList.remove("focus"); + next.classList.add("focus"); + } + } else if (e.keyCode === UP_KEYCODE) { + focused.classList.remove("focus"); + var prev = focused.previousElementSibling; + if (prev) { + prev.classList.add("focus"); + } else { + searchbar.select(); + } + } else { // SELECT_KEYCODE + window.location.assign(focused.querySelector('a')); + } + } + } + + function showSearch(yes) { + if (yes) { + search_wrap.classList.remove('hidden'); + searchicon.setAttribute('aria-expanded', 'true'); + } else { + search_wrap.classList.add('hidden'); + searchicon.setAttribute('aria-expanded', 'false'); + var results = searchresults.children; + for (var i = 0; i < results.length; i++) { + results[i].classList.remove("focus"); + } + } + } + + function showResults(yes) { + if (yes) { + searchresults_outer.classList.remove('hidden'); + } else { + searchresults_outer.classList.add('hidden'); + } + } + + // Eventhandler for search icon + function searchIconClickHandler() { + if (search_wrap.classList.contains('hidden')) { + showSearch(true); + window.scrollTo(0, 0); + searchbar.select(); + } else { + showSearch(false); + } + } + + // Eventhandler for keyevents while the searchbar is focused + function searchbarKeyUpHandler() { + var searchterm = searchbar.value.trim(); + if (searchterm != "") { + searchbar.classList.add("active"); + doSearch(searchterm); + } else { + searchbar.classList.remove("active"); + showResults(false); + removeChildren(searchresults); + } + + setSearchUrlParameters(searchterm, "push_if_new_search_else_replace"); + + // Remove marks + marker.unmark(); + } + + // Update current url with ?URL_SEARCH_PARAM= parameter, remove ?URL_MARK_PARAM and #heading-anchor . + // `action` can be one of "push", "replace", "push_if_new_search_else_replace" + // and replaces or pushes a new browser history item. + // "push_if_new_search_else_replace" pushes if there is no `?URL_SEARCH_PARAM=abc` yet. + function setSearchUrlParameters(searchterm, action) { + var url = parseURL(window.location.href); + var first_search = ! url.params.hasOwnProperty(URL_SEARCH_PARAM); + if (searchterm != "" || action == "push_if_new_search_else_replace") { + url.params[URL_SEARCH_PARAM] = searchterm; + delete url.params[URL_MARK_PARAM]; + url.hash = ""; + } else { + delete url.params[URL_SEARCH_PARAM]; + } + // A new search will also add a new history item, so the user can go back + // to the page prior to searching. A updated search term will only replace + // the url. + if (action == "push" || (action == "push_if_new_search_else_replace" && first_search) ) { + history.pushState({}, document.title, renderURL(url)); + } else if (action == "replace" || (action == "push_if_new_search_else_replace" && !first_search) ) { + history.replaceState({}, document.title, renderURL(url)); + } + } + + function doSearch(searchterm) { + + // Don't search the same twice + if (current_searchterm == searchterm) { return; } + else { current_searchterm = searchterm; } + + if (searchindex == null) { return; } + + // Do the actual search + var results = searchindex.search(searchterm, search_options); + var resultcount = Math.min(results.length, results_options.limit_results); + + // Display search metrics + searchresults_header.innerText = formatSearchMetric(resultcount, searchterm); + + // Clear and insert results + var searchterms = searchterm.split(' '); + removeChildren(searchresults); + for(var i = 0; i < resultcount ; i++){ + var resultElem = document.createElement('li'); + resultElem.innerHTML = formatSearchResult(results[i], searchterms); + searchresults.appendChild(resultElem); + } + + // Display results + showResults(true); + } + + fetch(path_to_root + 'searchindex.json') + .then(response => response.json()) + .then(json => init(json)) + .catch(error => { // Try to load searchindex.js if fetch failed + var script = document.createElement('script'); + script.src = path_to_root + 'searchindex.js'; + script.onload = () => init(window.search); + document.head.appendChild(script); + }); + + // Exported functions + search.hasFocus = hasFocus; +})(window.search); diff --git a/docs/guide/searchindex.js b/docs/guide/searchindex.js new file mode 100644 index 0000000..3b2b2c1 --- /dev/null +++ b/docs/guide/searchindex.js @@ -0,0 +1 @@ +window.search = {"doc_urls":["chapter_1.html#chapter-1"],"index":{"documentStore":{"docInfo":{"0":{"body":0,"breadcrumbs":2,"title":2}},"docs":{"0":{"body":"","breadcrumbs":"Chapter 1","id":"0","title":"Chapter 1"}},"length":1,"save":true},"fields":["title","body","breadcrumbs"],"index":{"body":{"root":{"1":{"df":1,"docs":{"0":{"tf":1.0}}},"c":{"df":0,"docs":{},"h":{"a":{"df":0,"docs":{},"p":{"df":0,"docs":{},"t":{"df":0,"docs":{},"e":{"df":0,"docs":{},"r":{"df":1,"docs":{"0":{"tf":1.0}}}}}}},"df":0,"docs":{}}},"df":0,"docs":{}}},"breadcrumbs":{"root":{"1":{"df":1,"docs":{"0":{"tf":1.4142135623730951}}},"c":{"df":0,"docs":{},"h":{"a":{"df":0,"docs":{},"p":{"df":0,"docs":{},"t":{"df":0,"docs":{},"e":{"df":0,"docs":{},"r":{"df":1,"docs":{"0":{"tf":1.4142135623730951}}}}}}},"df":0,"docs":{}}},"df":0,"docs":{}}},"title":{"root":{"1":{"df":1,"docs":{"0":{"tf":1.0}}},"c":{"df":0,"docs":{},"h":{"a":{"df":0,"docs":{},"p":{"df":0,"docs":{},"t":{"df":0,"docs":{},"e":{"df":0,"docs":{},"r":{"df":1,"docs":{"0":{"tf":1.0}}}}}}},"df":0,"docs":{}}},"df":0,"docs":{}}}},"pipeline":["trimmer","stopWordFilter","stemmer"],"ref":"id","version":"0.9.5"},"results_options":{"limit_results":30,"teaser_word_count":30},"search_options":{"bool":"OR","expand":true,"fields":{"body":{"boost":1},"breadcrumbs":{"boost":1},"title":{"boost":2}}}}; \ No newline at end of file diff --git a/docs/guide/searchindex.json b/docs/guide/searchindex.json new file mode 100644 index 0000000..8e3c2fc --- /dev/null +++ b/docs/guide/searchindex.json @@ -0,0 +1 @@ +{"doc_urls":["chapter_1.html#chapter-1"],"index":{"documentStore":{"docInfo":{"0":{"body":0,"breadcrumbs":2,"title":2}},"docs":{"0":{"body":"","breadcrumbs":"Chapter 1","id":"0","title":"Chapter 1"}},"length":1,"save":true},"fields":["title","body","breadcrumbs"],"index":{"body":{"root":{"1":{"df":1,"docs":{"0":{"tf":1.0}}},"c":{"df":0,"docs":{},"h":{"a":{"df":0,"docs":{},"p":{"df":0,"docs":{},"t":{"df":0,"docs":{},"e":{"df":0,"docs":{},"r":{"df":1,"docs":{"0":{"tf":1.0}}}}}}},"df":0,"docs":{}}},"df":0,"docs":{}}},"breadcrumbs":{"root":{"1":{"df":1,"docs":{"0":{"tf":1.4142135623730951}}},"c":{"df":0,"docs":{},"h":{"a":{"df":0,"docs":{},"p":{"df":0,"docs":{},"t":{"df":0,"docs":{},"e":{"df":0,"docs":{},"r":{"df":1,"docs":{"0":{"tf":1.4142135623730951}}}}}}},"df":0,"docs":{}}},"df":0,"docs":{}}},"title":{"root":{"1":{"df":1,"docs":{"0":{"tf":1.0}}},"c":{"df":0,"docs":{},"h":{"a":{"df":0,"docs":{},"p":{"df":0,"docs":{},"t":{"df":0,"docs":{},"e":{"df":0,"docs":{},"r":{"df":1,"docs":{"0":{"tf":1.0}}}}}}},"df":0,"docs":{}}},"df":0,"docs":{}}}},"pipeline":["trimmer","stopWordFilter","stemmer"],"ref":"id","version":"0.9.5"},"results_options":{"limit_results":30,"teaser_word_count":30},"search_options":{"bool":"OR","expand":true,"fields":{"body":{"boost":1},"breadcrumbs":{"boost":1},"title":{"boost":2}}}} \ No newline at end of file diff --git a/docs/guide/tomorrow-night.css b/docs/guide/tomorrow-night.css new file mode 100644 index 0000000..9788e08 --- /dev/null +++ b/docs/guide/tomorrow-night.css @@ -0,0 +1,96 @@ +/* Tomorrow Night Theme */ +/* http://jmblog.github.com/color-themes-for-google-code-highlightjs */ +/* Original theme - https://github.com/chriskempson/tomorrow-theme */ +/* http://jmblog.github.com/color-themes-for-google-code-highlightjs */ + +/* Tomorrow Comment */ +.hljs-comment { + color: #969896; +} + +/* Tomorrow Red */ +.hljs-variable, +.hljs-attribute, +.hljs-tag, +.hljs-regexp, +.ruby .hljs-constant, +.xml .hljs-tag .hljs-title, +.xml .hljs-pi, +.xml .hljs-doctype, +.html .hljs-doctype, +.css .hljs-id, +.css .hljs-class, +.css .hljs-pseudo { + color: #cc6666; +} + +/* Tomorrow Orange */ +.hljs-number, +.hljs-preprocessor, +.hljs-pragma, +.hljs-built_in, +.hljs-literal, +.hljs-params, +.hljs-constant { + color: #de935f; +} + +/* Tomorrow Yellow */ +.ruby .hljs-class .hljs-title, +.css .hljs-rule .hljs-attribute { + color: #f0c674; +} + +/* Tomorrow Green */ +.hljs-string, +.hljs-value, +.hljs-inheritance, +.hljs-header, +.hljs-name, +.ruby .hljs-symbol, +.xml .hljs-cdata { + color: #b5bd68; +} + +/* Tomorrow Aqua */ +.hljs-title, +.css .hljs-hexcolor { + color: #8abeb7; +} + +/* Tomorrow Blue */ +.hljs-function, +.python .hljs-decorator, +.python .hljs-title, +.ruby .hljs-function .hljs-title, +.ruby .hljs-title .hljs-keyword, +.perl .hljs-sub, +.javascript .hljs-title, +.coffeescript .hljs-title { + color: #81a2be; +} + +/* Tomorrow Purple */ +.hljs-keyword, +.javascript .hljs-function { + color: #b294bb; +} + +.hljs { + display: block; + overflow-x: auto; + background: #1d1f21; + color: #c5c8c6; + padding: 0.5em; + -webkit-text-size-adjust: none; +} + +.coffeescript .javascript, +.javascript .xml, +.tex .hljs-formula, +.xml .javascript, +.xml .vbscript, +.xml .css, +.xml .hljs-cdata { + opacity: 0.5; +} diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md new file mode 100644 index 0000000..7390c82 --- /dev/null +++ b/docs/src/SUMMARY.md @@ -0,0 +1,3 @@ +# Summary + +- [Chapter 1](./chapter_1.md) diff --git a/docs/src/chapter_1.md b/docs/src/chapter_1.md new file mode 100644 index 0000000..b743fda --- /dev/null +++ b/docs/src/chapter_1.md @@ -0,0 +1 @@ +# Chapter 1 diff --git a/examples/follow_profile.rs b/examples/follow_profile.rs new file mode 100644 index 0000000..84b2998 --- /dev/null +++ b/examples/follow_profile.rs @@ -0,0 +1,27 @@ +#![cfg_attr(not(feature = "toml"), allow(dead_code))] +#![cfg_attr(not(feature = "toml"), allow(unused_imports))] +#[macro_use] +extern crate pretty_env_logger; +extern crate elefren; +mod register; + +use register::MastodonClient; +use std::error; + +#[cfg(feature = "toml")] +fn main() -> Result<(), Box> { + let mastodon = register::get_mastodon_data()?; + let input = register::read_line("Enter the account id you'd like to follow: ")?; + let new_follow = mastodon.follow(input.trim())?; + + println!("{:#?}", new_follow); + Ok(()) +} + +#[cfg(not(feature = "toml"))] +fn main() { + println!( + "examples require the `toml` feature, run this command for this example:\n\ncargo run \ + --example follow_profile --features toml\n" + ); +} diff --git a/examples/follows_me.rs b/examples/follows_me.rs new file mode 100644 index 0000000..0df4414 --- /dev/null +++ b/examples/follows_me.rs @@ -0,0 +1,27 @@ +#![cfg_attr(not(feature = "toml"), allow(dead_code))] +#![cfg_attr(not(feature = "toml"), allow(unused_imports))] +#[macro_use] +extern crate pretty_env_logger; +extern crate elefren; +mod register; + +use register::MastodonClient; +use std::error; + +#[cfg(feature = "toml")] +fn main() -> Result<(), Box> { + let mastodon = register::get_mastodon_data()?; + for account in mastodon.follows_me()?.items_iter() { + println!("{}", account.acct); + } + + Ok(()) +} + +#[cfg(not(feature = "toml"))] +fn main() { + println!( + "examples require the `toml` feature, run this command for this example:\n\ncargo run \ + --example print_your_profile --features toml\n" + ); +} diff --git a/examples/home_timeline.rs b/examples/home_timeline.rs new file mode 100644 index 0000000..46519e3 --- /dev/null +++ b/examples/home_timeline.rs @@ -0,0 +1,27 @@ +#![cfg_attr(not(feature = "toml"), allow(dead_code))] +#![cfg_attr(not(feature = "toml"), allow(unused_imports))] +#[macro_use] +extern crate pretty_env_logger; +extern crate elefren; +mod register; + +use register::MastodonClient; +use std::error; + +#[cfg(feature = "toml")] +fn main() -> Result<(), Box> { + let mastodon = register::get_mastodon_data()?; + let tl = mastodon.get_home_timeline()?; + + println!("{:#?}", tl); + + Ok(()) +} + +#[cfg(not(feature = "toml"))] +fn main() { + println!( + "examples require the `toml` feature, run this command for this example:\n\ncargo run \ + --example print_your_profile --features toml\n" + ); +} diff --git a/examples/print_your_profile.rs b/examples/print_your_profile.rs new file mode 100644 index 0000000..cbcd372 --- /dev/null +++ b/examples/print_your_profile.rs @@ -0,0 +1,27 @@ +#![cfg_attr(not(feature = "toml"), allow(dead_code))] +#![cfg_attr(not(feature = "toml"), allow(unused_imports))] +#[macro_use] +extern crate pretty_env_logger; +extern crate elefren; +mod register; + +use register::MastodonClient; +use std::error; + +#[cfg(feature = "toml")] +fn main() -> Result<(), Box> { + let mastodon = register::get_mastodon_data()?; + let you = mastodon.verify_credentials()?; + + println!("{:#?}", you); + + Ok(()) +} + +#[cfg(not(feature = "toml"))] +fn main() { + println!( + "examples require the `toml` feature, run this command for this example:\n\ncargo run \ + --example print_your_profile --features toml\n" + ); +} diff --git a/examples/register/mod.rs b/examples/register/mod.rs new file mode 100644 index 0000000..d8dbaff --- /dev/null +++ b/examples/register/mod.rs @@ -0,0 +1,56 @@ +#![cfg_attr(not(feature = "toml"), allow(dead_code))] +#![cfg_attr(not(feature = "toml"), allow(unused_imports))] + +pub use elefren::prelude::*; + +use std::{error::Error, io}; + +use elefren::helpers::cli; +#[cfg(feature = "toml")] +use elefren::helpers::toml; + +#[allow(dead_code)] +#[cfg(feature = "toml")] +fn main() -> Result<(), Box> { + register()?; + Ok(()) +} + +#[allow(dead_code)] +#[cfg(feature = "toml")] +pub fn get_mastodon_data() -> Result> { + if let Ok(data) = toml::from_file("mastodon-data.toml") { + Ok(Mastodon::from(data)) + } else { + register() + } +} + +#[cfg(feature = "toml")] +pub fn register() -> Result> { + let website = read_line("Please enter your mastodon instance url:")?; + let registration = Registration::new(website.trim()) + .client_name("elefren-examples") + .scopes(Scopes::all()) + .website("https://github.com/pwoolcoc/elefren") + .build()?; + let mastodon = cli::authenticate(registration)?; + + // Save app data for using on the next run. + toml::to_file(&*mastodon, "mastodon-data.toml")?; + + Ok(mastodon) +} + +#[cfg(feature = "toml")] +pub fn read_line(message: &str) -> Result> { + println!("{}", message); + + let mut input = String::new(); + io::stdin().read_line(&mut input)?; + + Ok(input.trim().to_string()) +} + +#[cfg(not(feature = "toml"))] +fn main() {} diff --git a/examples/search.rs b/examples/search.rs new file mode 100644 index 0000000..ec13f6d --- /dev/null +++ b/examples/search.rs @@ -0,0 +1,28 @@ +#![cfg_attr(not(feature = "toml"), allow(dead_code))] +#![cfg_attr(not(feature = "toml"), allow(unused_imports))] +#[macro_use] +extern crate pretty_env_logger; +extern crate elefren; +mod register; + +use register::MastodonClient; +use std::error; + +#[cfg(feature = "toml")] +fn main() -> Result<(), Box> { + let mastodon = register::get_mastodon_data()?; + let input = register::read_line("Enter the term you'd like to search: ")?; + let result = mastodon.search(&input, false)?; + + println!("{:#?}", result); + + Ok(()) +} + +#[cfg(not(feature = "toml"))] +fn main() { + println!( + "examples require the `toml` feature, run this command for this example:\n\ncargo run \ + --example search --features toml\n" + ); +} diff --git a/examples/upload_photo.rs b/examples/upload_photo.rs new file mode 100644 index 0000000..a2e6688 --- /dev/null +++ b/examples/upload_photo.rs @@ -0,0 +1,27 @@ +#![cfg_attr(not(feature = "toml"), allow(dead_code))] +#![cfg_attr(not(feature = "toml"), allow(unused_imports))] +#[macro_use] +extern crate pretty_env_logger; +extern crate elefren; +mod register; + +use register::MastodonClient; +use std::error; + +#[cfg(feature = "toml")] +fn main() -> Result<(), Box> { + let mastodon = register::get_mastodon_data()?; + let input = register::read_line("Enter the path to the photo you'd like to post: ")?; + + mastodon.media(input.into())?; + + Ok(()) +} + +#[cfg(not(feature = "toml"))] +fn main() { + println!( + "examples require the `toml` feature, run this command for this example:\n\ncargo run \ + --example upload_photo --features toml\n" + ); +} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..e2b5e5b --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,16 @@ +format_strings = true +format_macro_matchers = true +imports_layout = "HorizontalVertical" +merge_imports = true +match_block_trailing_comma = true +merge_derives = true +newline_style = "Unix" +normalize_comments = true +reorder_impl_items = true +space_after_colon = true +space_before_colon = false +struct_lit_single_line = false +type_punctuation_density = "Wide" +use_field_init_shorthand = true +use_try_shorthand = true +wrap_comments = true diff --git a/src/apps.rs b/src/apps.rs new file mode 100644 index 0000000..7032932 --- /dev/null +++ b/src/apps.rs @@ -0,0 +1,233 @@ +use std::borrow::Cow; + +use try_from::TryInto; + +use errors::{Error, Result}; +use scopes::Scopes; + +/// Represents an application that can be registered with a mastodon instance +#[derive(Clone, Debug, Default, Serialize, PartialEq)] +pub struct App { + client_name: String, + redirect_uris: String, + scopes: Scopes, + #[serde(skip_serializing_if = "Option::is_none")] + website: Option, +} + +impl App { + /// Get an AppBuilder object + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::apps::App; + /// + /// let mut builder = App::builder(); + /// ``` + pub fn builder<'a>() -> AppBuilder<'a> { + AppBuilder::new() + } + + /// Retrieve the list of scopes that apply to this App + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// # use elefren::Error; + /// use elefren::{apps::App, scopes::Scopes}; + /// + /// # fn main() -> Result<(), Error> { + /// let mut builder = App::builder(); + /// builder.client_name("elefren-test"); + /// let app = builder.build()?; + /// let scopes = app.scopes(); + /// assert_eq!(scopes, &Scopes::read_all()); + /// # Ok(()) + /// # } + /// ``` + pub fn scopes(&self) -> &Scopes { + &self.scopes + } +} + +/// Builder struct for defining your application. +/// ``` +/// use elefren::apps::App; +/// use std::error::Error; +/// +/// # fn main() -> Result<(), Box> { +/// let mut builder = App::builder(); +/// builder.client_name("elefren_test"); +/// let app = builder.build()?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct AppBuilder<'a> { + client_name: Option>, + redirect_uris: Option>, + scopes: Option, + website: Option>, +} + +impl<'a> AppBuilder<'a> { + /// Creates a new AppBuilder object + pub fn new() -> Self { + Default::default() + } + + /// Name of the application. Will be displayed when the user is deciding to + /// grant permission. + /// + /// In order to turn this builder into an App, this needs to be provided + pub fn client_name>>(&mut self, name: I) -> &mut Self { + self.client_name = Some(name.into()); + self + } + + /// Where the user should be redirected after authorization + /// + /// If none is specified, the default is `urn:ietf:wg:oauth:2.0:oob` + pub fn redirect_uris>>(&mut self, uris: I) -> &mut Self { + self.redirect_uris = Some(uris.into()); + self + } + + /// Permission scope of the application. + /// + /// IF none is specified, the default is Scopes::read_all() + pub fn scopes(&mut self, scopes: Scopes) -> &mut Self { + self.scopes = Some(scopes); + self + } + + /// URL to the homepage of your application. + pub fn website>>(&mut self, website: I) -> &mut Self { + self.website = Some(website.into()); + self + } + + /// Attempts to convert this build into an `App` + /// + /// Will fail if no `client_name` was provided + pub fn build(self) -> Result { + Ok(App { + client_name: self + .client_name + .ok_or_else(|| Error::MissingField("client_name"))? + .into(), + redirect_uris: self + .redirect_uris + .unwrap_or_else(|| "urn:ietf:wg:oauth:2.0:oob".into()) + .into(), + scopes: self.scopes.unwrap_or_else(|| Scopes::read_all()), + website: self.website.map(|s| s.into()), + }) + } +} + +impl TryInto for App { + type Err = Error; + + fn try_into(self) -> Result { + Ok(self) + } +} + +impl<'a> TryInto for AppBuilder<'a> { + type Err = Error; + + fn try_into(self) -> Result { + Ok(self.build()?) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_app_builder() { + let builder = App::builder(); + assert_eq!(builder, AppBuilder::new()); + } + + #[test] + fn test_app_scopes() { + let mut builder = App::builder(); + builder.client_name("test").scopes(Scopes::all()); + let app = builder.build().expect("Couldn't build App"); + assert_eq!(app.scopes(), &Scopes::all()); + } + + #[test] + fn test_app_builder_all_methods() { + let mut builder = AppBuilder::new(); + builder.client_name("foo-test"); + builder.redirect_uris("http://example.com"); + builder.scopes(Scopes::read_all() | Scopes::write_all()); + builder.website("https://example.com"); + let app = builder.build().expect("Couldn't build App"); + assert_eq!( + app, + App { + client_name: "foo-test".to_string(), + redirect_uris: "http://example.com".to_string(), + scopes: Scopes::read_all() | Scopes::write_all(), + website: Some("https://example.com".to_string()), + } + ); + } + + #[test] + #[should_panic] + fn test_app_builder_build_fails_if_no_client_name_1() { + App::builder().build().expect("no client-name"); + } + + #[test] + #[should_panic] + fn test_app_builder_build_fails_if_no_client_name_2() { + let mut builder = App::builder(); + builder + .website("https://example.com") + .redirect_uris("https://example.com") + .scopes(Scopes::all()); + builder.build().expect("no client-name"); + } + + #[test] + fn test_app_try_into_app() { + let app = App { + client_name: "foo-test".to_string(), + redirect_uris: "http://example.com".to_string(), + scopes: Scopes::all(), + website: None, + }; + let expected = app.clone(); + let result = app.try_into().expect("Couldn't make App into App"); + assert_eq!(expected, result); + } + + #[test] + fn test_app_builder_try_into_app() { + let mut builder = App::builder(); + builder + .client_name("foo-test") + .redirect_uris("http://example.com") + .scopes(Scopes::all()); + let expected = App { + client_name: "foo-test".to_string(), + redirect_uris: "http://example.com".to_string(), + scopes: Scopes::all(), + website: None, + }; + let result = builder + .try_into() + .expect("Couldn't make AppBuilder into App"); + assert_eq!(expected, result); + } +} diff --git a/src/data.rs b/src/data.rs new file mode 100644 index 0000000..20dfd69 --- /dev/null +++ b/src/data.rs @@ -0,0 +1,17 @@ +use std::borrow::Cow; + +/// Raw data about mastodon app. Save `Data` using `serde` to prevent needing +/// to authenticate on every run. +#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] +pub struct Data { + /// Base url of instance eg. `https://mastodon.social`. + pub base: Cow<'static, str>, + /// The client's id given by the instance. + pub client_id: Cow<'static, str>, + /// The client's secret given by the instance. + pub client_secret: Cow<'static, str>, + /// Url to redirect back to your application from the instance signup. + pub redirect: Cow<'static, str>, + /// The client's access token. + pub token: Cow<'static, str>, +} diff --git a/src/entities/account.rs b/src/entities/account.rs new file mode 100644 index 0000000..499fb0a --- /dev/null +++ b/src/entities/account.rs @@ -0,0 +1,144 @@ +//! A module containing everything relating to a account returned from the api. + +use chrono::prelude::*; +use serde::de::{self, Deserialize, Deserializer, Unexpected}; +use status_builder; +use std::path::PathBuf; + +/// A struct representing an Account. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Account { + /// Equals `username` for local users, includes `@domain` for remote ones. + pub acct: String, + /// URL to the avatar image + pub avatar: String, + /// URL to the avatar static image (gif) + pub avatar_static: String, + /// The time the account was created. + pub created_at: DateTime, + /// The account's display name. + pub display_name: String, + /// The number of followers for the account. + pub followers_count: u64, + /// The number of accounts the given account is following. + pub following_count: u64, + /// URL to the header image. + pub header: String, + /// URL to the header static image (gif). + pub header_static: String, + /// The ID of the account. + pub id: String, + /// Boolean for when the account cannot be followed without waiting for + /// approval first. + pub locked: bool, + /// Biography of user. + pub note: String, + /// The number of statuses the account has made. + pub statuses_count: u64, + /// URL of the user's profile page (can be remote). + pub url: String, + /// The username of the account. + pub username: String, + /// An extra attribute given from `verify_credentials` giving defaults about + /// a user + pub source: Option, + /// If the owner decided to switch accounts, new account is in + /// this attribute + pub moved: Option>, + /// List of profile metadata fields + pub fields: Option>, + /// Boolean indicating whether this account is a bot or not + pub bot: Option, +} + +/// A single name: value pair from a user's profile +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct MetadataField { + /// name part of metadata + pub name: String, + /// value part of metadata + pub value: String, +} + +impl MetadataField { + pub(crate) fn new(name: &str, value: &str) -> MetadataField { + MetadataField { + name: name.into(), + value: value.into(), + } + } +} + +/// An extra object given from `verify_credentials` giving defaults about a user +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Source { + privacy: Option, + #[serde(deserialize_with = "string_or_bool")] + sensitive: bool, + note: Option, + fields: Option>, +} + +fn string_or_bool<'de, D: Deserializer<'de>>(val: D) -> ::std::result::Result { + #[derive(Clone, Debug, Deserialize, PartialEq)] + #[serde(untagged)] + pub enum BoolOrString { + Bool(bool), + Str(String), + } + + Ok(match BoolOrString::deserialize(val)? { + BoolOrString::Bool(b) => b, + BoolOrString::Str(ref s) => { + if s == "true" { + true + } else if s == "false" { + false + } else { + return Err(de::Error::invalid_value( + Unexpected::Str(s), + &"true or false", + )); + } + }, + }) +} + +#[derive(Debug, Default, Clone, Serialize, PartialEq)] +pub(crate) struct UpdateSource { + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) privacy: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) sensitive: Option, +} + +#[derive(Debug, Default, Serialize, PartialEq)] +pub(crate) struct Credentials { + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) display_name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) note: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) avatar: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) header: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) source: Option, + #[serde(serialize_with = "fields_attributes_ser::ser")] + pub(crate) fields_attributes: Vec, +} + +mod fields_attributes_ser { + use super::*; + use serde::ser::{SerializeMap, Serializer}; + pub(crate) fn ser(attrs: &Vec, serializer: S) -> Result + where + S: Serializer, + { + let mut map = serializer.serialize_map(Some(attrs.len()))?; + for (i, field) in attrs.iter().enumerate() { + map.serialize_entry(&i, &field)?; + } + map.end() + } +} diff --git a/src/entities/attachment.rs b/src/entities/attachment.rs new file mode 100644 index 0000000..740db19 --- /dev/null +++ b/src/entities/attachment.rs @@ -0,0 +1,63 @@ +//! Module containing everything related to media attachements. + +/// A struct representing a media attachment. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Attachment { + /// ID of the attachment. + pub id: String, + /// The media type of an attachment. + #[serde(rename = "type")] + pub media_type: MediaType, + /// URL of the locally hosted version of the image. + pub url: String, + /// For remote images, the remote URL of the original image. + pub remote_url: Option, + /// URL of the preview image. + pub preview_url: String, + /// Shorter URL for the image, for insertion into text + /// (only present on local images) + pub text_url: Option, + /// Meta information about the attachment. + pub meta: Option, + /// Noop will be removed. + pub description: Option, +} + +/// Information about the attachment itself. +#[derive(Debug, Deserialize, Clone, PartialEq)] +pub struct Meta { + /// Original version. + pub original: Option, + /// Smaller version. + pub small: Option, +} + +/// Dimensions of an attachement. +#[derive(Debug, Deserialize, Clone, PartialEq)] +pub struct ImageDetails { + /// width of attachment. + width: u64, + /// height of attachment. + height: u64, + /// A string of `widthxheight`. + size: Option, + /// The aspect ratio of the attachment. + aspect: Option, +} + +/// The type of media attachment. +#[derive(Debug, Deserialize, Clone, Copy, PartialEq)] +pub enum MediaType { + /// An image. + #[serde(rename = "image")] + Image, + /// A video file. + #[serde(rename = "video")] + Video, + /// A gifv format file. + #[serde(rename = "gifv")] + Gifv, + /// Unknown format. + #[serde(rename = "unknown")] + Unknown, +} diff --git a/src/entities/card.rs b/src/entities/card.rs new file mode 100644 index 0000000..ec9471c --- /dev/null +++ b/src/entities/card.rs @@ -0,0 +1,28 @@ +//! Module representing cards of statuses. + +/// A card of a status. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Card { + /// The url associated with the card. + pub url: String, + /// The title of the card. + pub title: String, + /// The card description. + pub description: String, + /// The image associated with the card, if any. + pub image: Option, + /// OEmbed data + author_name: Option, + /// OEmbed data + author_url: Option, + /// OEmbed data + provider_name: Option, + /// OEmbed data + provider_url: Option, + /// OEmbed data + html: Option, + /// OEmbed data + width: Option, + /// OEmbed data + height: Option, +} diff --git a/src/entities/context.rs b/src/entities/context.rs new file mode 100644 index 0000000..60a4ea2 --- /dev/null +++ b/src/entities/context.rs @@ -0,0 +1,13 @@ +//! A module about contexts of statuses. + +use super::status::Status; + +/// A context of a status returning a list of statuses it replied to and +/// statuses replied to it. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Context { + /// Statuses that were replied to. + pub ancestors: Vec, + /// Statuses that replied to this status. + pub descendants: Vec, +} diff --git a/src/entities/event.rs b/src/entities/event.rs new file mode 100644 index 0000000..101c677 --- /dev/null +++ b/src/entities/event.rs @@ -0,0 +1,14 @@ +use entities::{notification::Notification, status::Status}; + +#[derive(Debug, Clone)] +/// Events that come from the /streaming/user API call +pub enum Event { + /// Update event + Update(Status), + /// Notification event + Notification(Notification), + /// Delete event + Delete(String), + /// FiltersChanged event + FiltersChanged, +} diff --git a/src/entities/filter.rs b/src/entities/filter.rs new file mode 100644 index 0000000..29dcb27 --- /dev/null +++ b/src/entities/filter.rs @@ -0,0 +1,27 @@ +/// Represents a single Filter +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Filter { + id: String, + phrase: String, + context: Vec, + expires_at: Option, // TODO: timestamp + irreversible: bool, + whole_word: bool, +} + +/// Represents the various types of Filter contexts +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub enum FilterContext { + /// Represents the "home" context + #[serde(rename = "home")] + Home, + /// Represents the "notifications" context + #[serde(rename = "notifications")] + Notifications, + /// Represents the "public" context + #[serde(rename = "public")] + Public, + /// Represents the "thread" context + #[serde(rename = "thread")] + Thread, +} diff --git a/src/entities/instance.rs b/src/entities/instance.rs new file mode 100644 index 0000000..66d60ca --- /dev/null +++ b/src/entities/instance.rs @@ -0,0 +1,45 @@ +//! Module containing everything related to an instance. +use super::account::Account; + +/// A struct containing info of an instance. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Instance { + /// URI of the current instance + pub uri: String, + /// The instance's title. + pub title: String, + /// A description for the instance. + pub description: String, + /// An email address which can be used to contact the + /// instance administrator. + pub email: String, + /// The Mastodon version used by instance. + pub version: String, + /// Urls to the streaming api. + pub urls: Option, + /// Stats about the instance. + pub stats: Option, + /// Thumbnail of the server image. + pub thumbnail: Option, + /// List of languages used on the server. + pub languages: Option>, + /// Contact account for the server. + pub contact_account: Option, + /// The maximum number of characters allowed in a status + pub max_toot_chars: Option, +} + +/// Object containing url for streaming api. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct StreamingApi { + /// Url for streaming API, typically a `wss://` url. + pub streaming_api: String, +} + +/// Statistics about the Mastodon instance. +#[derive(Debug, Clone, Copy, Deserialize, PartialEq)] +pub struct Stats { + user_count: u64, + status_count: u64, + domain_count: u64, +} diff --git a/src/entities/itemsiter.rs b/src/entities/itemsiter.rs new file mode 100644 index 0000000..e8b3e76 --- /dev/null +++ b/src/entities/itemsiter.rs @@ -0,0 +1,95 @@ +use http_send::HttpSend; +use page::Page; +use serde::Deserialize; + +/// Abstracts away the `next_page` logic into a single stream of items +/// +/// ```no_run +/// # extern crate elefren; +/// # use elefren::prelude::*; +/// # use std::error::Error; +/// # fn main() -> Result<(), Box> { +/// # let data = Data { +/// # base: "".into(), +/// # client_id: "".into(), +/// # client_secret: "".into(), +/// # redirect: "".into(), +/// # token: "".into(), +/// # }; +/// let client = Mastodon::from(data); +/// let statuses = client.statuses("user-id", None)?; +/// for status in statuses.items_iter() { +/// // do something with `status` +/// } +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Clone)] +pub(crate) struct ItemsIter<'a, T: Clone + for<'de> Deserialize<'de>, H: 'a + HttpSend> { + page: Page<'a, T, H>, + buffer: Vec, + cur_idx: usize, + use_initial: bool, +} + +impl<'a, T: Clone + for<'de> Deserialize<'de>, H: HttpSend> ItemsIter<'a, T, H> { + pub(crate) fn new(page: Page<'a, T, H>) -> ItemsIter<'a, T, H> { + ItemsIter { + page, + buffer: vec![], + cur_idx: 0, + use_initial: true, + } + } + + fn need_next_page(&self) -> bool { + self.buffer.is_empty() || self.cur_idx == self.buffer.len() + } + + fn fill_next_page(&mut self) -> Option<()> { + let items = if let Ok(items) = self.page.next_page() { + items + } else { + return None; + }; + if let Some(items) = items { + if items.is_empty() { + return None; + } + self.buffer = items; + self.cur_idx = 0; + Some(()) + } else { + None + } + } +} + +impl<'a, T: Clone + for<'de> Deserialize<'de>, H: HttpSend> Iterator for ItemsIter<'a, T, H> { + type Item = T; + + fn next(&mut self) -> Option { + if self.use_initial { + if self.page.initial_items.is_empty() || self.cur_idx == self.page.initial_items.len() { + return None; + } + let idx = self.cur_idx; + if self.cur_idx == self.page.initial_items.len() - 1 { + self.cur_idx = 0; + self.use_initial = false; + } else { + self.cur_idx += 1; + } + Some(self.page.initial_items[idx].clone()) + } else { + if self.need_next_page() { + if self.fill_next_page().is_none() { + return None; + } + } + let idx = self.cur_idx; + self.cur_idx += 1; + Some(self.buffer[idx].clone()) + } + } +} diff --git a/src/entities/list.rs b/src/entities/list.rs new file mode 100644 index 0000000..8d640c8 --- /dev/null +++ b/src/entities/list.rs @@ -0,0 +1,6 @@ +/// Used for ser/de of list resources +#[derive(Clone, Debug, Deserialize, PartialEq)] +pub struct List { + id: String, + title: String, +} diff --git a/src/entities/mention.rs b/src/entities/mention.rs new file mode 100644 index 0000000..8c5a392 --- /dev/null +++ b/src/entities/mention.rs @@ -0,0 +1,12 @@ +/// Represents a `mention` used in a status +#[derive(Debug, Clone, PartialEq)] +pub struct Mention { + /// URL of user's profile (can be remote) + pub url: String, + /// The username of the account + pub username: String, + /// Equals username for local users, includes `@domain` for remote ones + pub acct: String, + /// Account ID + pub id: String, +} diff --git a/src/entities/mod.rs b/src/entities/mod.rs new file mode 100644 index 0000000..d5ad373 --- /dev/null +++ b/src/entities/mod.rs @@ -0,0 +1,59 @@ +/// Data structures for ser/de of account-related resources +pub mod account; +/// Data structures for ser/de of attachment-related resources +pub mod attachment; +/// Data structures for ser/de of card-related resources +pub mod card; +/// Data structures for ser/de of contetx-related resources +pub mod context; +/// Data structures for ser/de of streaming events +pub mod event; +/// Data structures for ser/de of filter-related resources +pub mod filter; +/// Data structures for ser/de of instance-related resources +pub mod instance; +pub(crate) mod itemsiter; +/// Data structures for ser/de of list-related resources +pub mod list; +/// Data structures for ser/de of mention-related resources +pub mod mention; +/// Data structures for ser/de of notification-related resources +pub mod notification; +/// Data structures for ser/de of push-subscription-related resources +pub mod push; +/// Data structures for ser/de of relationship-related resources +pub mod relationship; +/// Data structures for ser/de of report-related resources +pub mod report; +/// Data structures for ser/de of search-related resources +pub mod search_result; +/// Data structures for ser/de of status-related resources +pub mod status; + +/// An empty JSON object. +#[derive(Deserialize, Debug, Copy, Clone, PartialEq)] +pub struct Empty {} + +/// The purpose of this module is to alleviate imports of many common +/// structs by adding a glob import to the top of mastodon heavy +/// modules: +pub mod prelude { + pub use super::{ + account::{Account, Source}, + attachment::{Attachment, MediaType}, + card::Card, + context::Context, + event::Event, + filter::{Filter, FilterContext}, + instance::*, + list::List, + mention::Mention, + notification::Notification, + push::Subscription, + relationship::Relationship, + report::Report, + search_result::{SearchResult, SearchResultV2}, + status::{Application, Emoji, Status}, + Empty, + }; +} diff --git a/src/entities/notification.rs b/src/entities/notification.rs new file mode 100644 index 0000000..6ad4c37 --- /dev/null +++ b/src/entities/notification.rs @@ -0,0 +1,34 @@ +//! Module containing all info about notifications. + +use super::{account::Account, status::Status}; +use chrono::prelude::*; + +/// A struct containing info about a notification. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Notification { + /// The notification ID. + pub id: String, + /// The type of notification. + #[serde(rename = "type")] + pub notification_type: NotificationType, + /// The time the notification was created. + pub created_at: DateTime, + /// The Account sending the notification to the user. + pub account: Account, + /// The Status associated with the notification, if applicable. + pub status: Option, +} + +/// The type of notification. +#[derive(Debug, Clone, Copy, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum NotificationType { + /// Someone mentioned the application client in another status. + Mention, + /// Someone reblogged one of the application client's statuses. + Reblog, + /// Someone favourited one of the application client's statuses. + Favourite, + /// Someone followed the application client. + Follow, +} diff --git a/src/entities/push.rs b/src/entities/push.rs new file mode 100644 index 0000000..bcf826a --- /dev/null +++ b/src/entities/push.rs @@ -0,0 +1,67 @@ +/// Represents the `alerts` key of the `Subscription` object +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)] +pub struct Alerts { + /// flag for follow alerts + pub follow: Option, + /// flag for favourite alerts + pub favourite: Option, + /// flag for reblog alerts + pub reblog: Option, + /// flag for mention alerts + pub mention: Option, +} + +/// Represents a new Push subscription +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub struct Subscription { + /// The `id` of the subscription + pub id: String, + /// The endpoint of the subscription + pub endpoint: String, + /// The server key of the subscription + pub server_key: String, + /// The status of the alerts for this subscription + pub alerts: Option, +} + +pub(crate) mod add_subscription { + use super::Alerts; + + #[derive(Debug, Clone, PartialEq, Serialize, Default)] + pub(crate) struct Form { + pub(crate) subscription: Subscription, + pub(crate) data: Option, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Default)] + pub(crate) struct Subscription { + pub(crate) endpoint: String, + pub(crate) keys: Keys, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Default)] + pub(crate) struct Keys { + pub(crate) p256dh: String, + pub(crate) auth: String, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Default)] + pub(crate) struct Data { + pub(crate) alerts: Option, + } +} + +pub(crate) mod update_data { + use super::Alerts; + + #[derive(Debug, Clone, PartialEq, Serialize, Default)] + pub(crate) struct Data { + pub(crate) alerts: Option, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Default)] + pub(crate) struct Form { + pub(crate) id: String, + pub(crate) data: Data, + } +} diff --git a/src/entities/relationship.rs b/src/entities/relationship.rs new file mode 100644 index 0000000..35f3c99 --- /dev/null +++ b/src/entities/relationship.rs @@ -0,0 +1,31 @@ +//! module containing everything relating to a relationship with +//! another account. + +/// A struct containing information about a relationship with another account. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Relationship { + /// Target account id + pub id: String, + /// Whether the application client follows the account. + pub following: bool, + /// Whether the account follows the application client. + pub followed_by: bool, + /// Whether the application client blocks the account. + pub blocking: bool, + /// Whether the application client blocks the account. + pub muting: bool, + /// Whether the application client has requested to follow the account. + pub requested: bool, + /// Whether the user is also muting notifications + pub muting_notifications: bool, + /// Whether the user is currently blocking the accounts's domain + pub domain_blocking: bool, + /// Whether the user's reblogs will show up in the home timeline + pub showing_reblogs: bool, + /// Whether the user is currently endorsing the account + /// + /// This field is not techincally nullable with mastodon >= 2.5.0, but + /// making it `Option` here means we shouldn't get deser errors when + /// making calls to pleroma or mastodon<2.5.0 instances + pub endorsed: Option, +} diff --git a/src/entities/report.rs b/src/entities/report.rs new file mode 100644 index 0000000..2c3411b --- /dev/null +++ b/src/entities/report.rs @@ -0,0 +1,10 @@ +//! module containing information about a finished report of a user. + +/// A struct containing info about a report. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Report { + /// The ID of the report. + pub id: String, + /// The action taken in response to the report. + pub action_taken: String, +} diff --git a/src/entities/search_result.rs b/src/entities/search_result.rs new file mode 100644 index 0000000..d2df4c3 --- /dev/null +++ b/src/entities/search_result.rs @@ -0,0 +1,29 @@ +//! A module containing info relating to a search result. + +use super::{ + prelude::{Account, Status}, + status::Tag, +}; + +/// A struct containing results of a search. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct SearchResult { + /// An array of matched Accounts. + pub accounts: Vec, + /// An array of matched Statuses. + pub statuses: Vec, + /// An array of matched hashtags, as strings. + pub hashtags: Vec, +} + +/// A struct containing results of a search, with `Tag` objects in the +/// `hashtags` field +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct SearchResultV2 { + /// An array of matched Accounts. + pub accounts: Vec, + /// An array of matched Statuses. + pub statuses: Vec, + /// An array of matched hashtags, as `Tag` objects. + pub hashtags: Vec, +} diff --git a/src/entities/status.rs b/src/entities/status.rs new file mode 100644 index 0000000..65c6df8 --- /dev/null +++ b/src/entities/status.rs @@ -0,0 +1,107 @@ +//! Module containing all info relating to a status. + +use super::prelude::*; +use chrono::prelude::*; +use entities::card::Card; +use status_builder::Visibility; + +/// A status from the instance. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Status { + /// The ID of the status. + pub id: String, + /// A Fediverse-unique resource ID. + pub uri: String, + /// URL to the status page (can be remote) + pub url: Option, + /// The Account which posted the status. + pub account: Account, + /// The ID of the status this status is replying to, if the status is + /// a reply. + pub in_reply_to_id: Option, + /// The ID of the account this status is replying to, if the status is + /// a reply. + pub in_reply_to_account_id: Option, + /// If this status is a reblogged Status of another User. + pub reblog: Option>, + /// Body of the status; this will contain HTML + /// (remote HTML already sanitized) + pub content: String, + /// The time the status was created. + pub created_at: DateTime, + /// An array of Emoji + pub emojis: Vec, + /// The numbef or replies to this status. + pub replies_count: Option, + /// The number of reblogs for the status. + pub reblogs_count: u64, + /// The number of favourites for the status. + pub favourites_count: u64, + /// Whether the application client has reblogged the status. + pub reblogged: Option, + /// Whether the application client has favourited the status. + pub favourited: Option, + /// Whether media attachments should be hidden by default. + pub sensitive: bool, + /// If not empty, warning text that should be displayed before the actual + /// content. + pub spoiler_text: String, + /// The visibilty of the status. + pub visibility: Visibility, + /// An array of attachments. + pub media_attachments: Vec, + /// An array of mentions. + pub mentions: Vec, + /// An array of tags. + pub tags: Vec, + /// The associated card + pub card: Option, + /// Name of application used to post status. + pub application: Option, + /// The detected language for the status, if detected. + pub language: Option, + /// Whether this is the pinned status for the account that posted it. + pub pinned: Option, +} + +/// A mention of another user. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Mention { + /// URL of user's profile (can be remote). + pub url: String, + /// The username of the account. + pub username: String, + /// Equals `username` for local users, includes `@domain` for remote ones. + pub acct: String, + /// Account ID. + pub id: String, +} + +/// Struct representing an emoji within text. +#[derive(Clone, Debug, Deserialize, PartialEq)] +pub struct Emoji { + /// The shortcode of the emoji + pub shortcode: String, + /// URL to the emoji static image + pub static_url: String, + /// URL to the emoji image + pub url: String, +} + +/// Hashtags in the status. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Tag { + /// The hashtag, not including the preceding `#`. + pub name: String, + /// The URL of the hashtag. + pub url: String, +} + +/// Application details. +#[derive(Debug, Clone, Deserialize, PartialEq)] +pub struct Application { + /// Name of the application. + pub name: String, + /// Homepage URL of the application. + pub website: Option, +} diff --git a/src/errors.rs b/src/errors.rs new file mode 100644 index 0000000..f4d62b4 --- /dev/null +++ b/src/errors.rs @@ -0,0 +1,245 @@ +use std::{error, fmt, io::Error as IoError}; + +#[cfg(feature = "env")] +use envy::Error as EnvyError; +use hyper_old_types::Error as HeaderParseError; +use reqwest::{header::ToStrError as HeaderStrError, Error as HttpError, StatusCode}; +use serde_json::Error as SerdeError; +use serde_qs::Error as SerdeQsError; +use serde_urlencoded::ser::Error as UrlEncodedError; +#[cfg(feature = "toml")] +use tomlcrate::de::Error as TomlDeError; +#[cfg(feature = "toml")] +use tomlcrate::ser::Error as TomlSerError; +use url::ParseError as UrlError; +use tungstenite::error::Error as WebSocketError; + +/// Convience type over `std::result::Result` with `Error` as the error type. +pub type Result = ::std::result::Result; + +/// enum of possible errors encountered using the mastodon API. +#[derive(Debug)] +pub enum Error { + /// Error from the Mastodon API. This typically means something went + /// wrong with your authentication or data. + Api(ApiError), + /// Error deserialising to json. Typically represents a breaking change in + /// the Mastodon API + Serde(SerdeError), + /// Error serializing to url-encoded string + UrlEncoded(UrlEncodedError), + /// Error encountered in the HTTP backend while requesting a route. + Http(HttpError), + /// Wrapper around the `std::io::Error` struct. + Io(IoError), + /// Wrapper around the `url::ParseError` struct. + Url(UrlError), + /// Missing Client Id. + ClientIdRequired, + /// Missing Client Secret. + ClientSecretRequired, + /// Missing Access Token. + AccessTokenRequired, + /// Generic client error. + Client(StatusCode), + /// Generic server error. + Server(StatusCode), + /// MastodonBuilder & AppBuilder error + MissingField(&'static str), + #[cfg(feature = "toml")] + /// Error serializing to toml + TomlSer(TomlSerError), + #[cfg(feature = "toml")] + /// Error deserializing from toml + TomlDe(TomlDeError), + /// Error converting an http header to a string + HeaderStrError(HeaderStrError), + /// Error parsing the http Link header + HeaderParseError(HeaderParseError), + #[cfg(feature = "env")] + /// Error deserializing from the environment + Envy(EnvyError), + /// Error serializing to a query string + SerdeQs(SerdeQsError), + /// WebSocket error + WebSocket(WebSocketError), + /// Other errors + Other(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?}", self) + } +} + +impl error::Error for Error { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + Some(match *self { + Error::Api(ref e) => e, + Error::Serde(ref e) => e, + Error::UrlEncoded(ref e) => e, + Error::Http(ref e) => e, + Error::Io(ref e) => e, + Error::Url(ref e) => e, + #[cfg(feature = "toml")] + Error::TomlSer(ref e) => e, + #[cfg(feature = "toml")] + Error::TomlDe(ref e) => e, + Error::HeaderStrError(ref e) => e, + Error::HeaderParseError(ref e) => e, + #[cfg(feature = "env")] + Error::Envy(ref e) => e, + Error::SerdeQs(ref e) => e, + Error::WebSocket(ref e) => e, + + Error::Client(..) | Error::Server(..) => { + return None + }, + Error::ClientIdRequired => return None, + Error::ClientSecretRequired => return None, + Error::AccessTokenRequired => return None, + Error::MissingField(_) => return None, + Error::Other(..) => return None, + }) + } +} + +/// Error returned from the Mastodon API. +#[derive(Clone, Debug, Deserialize)] +pub struct ApiError { + /// The type of error. + pub error: Option, + /// The description of the error. + pub error_description: Option, +} + +impl fmt::Display for ApiError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?}", self) + } +} + +impl error::Error for ApiError {} + +macro_rules! from { + ($($(#[$met:meta])* $typ:ident, $variant:ident,)*) => { + $( + $(#[$met])* + impl From<$typ> for Error { + fn from(from: $typ) -> Self { + use Error::*; + $variant(from) + } + } + )* + } +} + +from! { + HttpError, Http, + IoError, Io, + SerdeError, Serde, + UrlEncodedError, UrlEncoded, + UrlError, Url, + ApiError, Api, + #[cfg(feature = "toml")] TomlSerError, TomlSer, + #[cfg(feature = "toml")] TomlDeError, TomlDe, + HeaderStrError, HeaderStrError, + HeaderParseError, HeaderParseError, + #[cfg(feature = "env")] EnvyError, Envy, + SerdeQsError, SerdeQs, + WebSocketError, WebSocket, + String, Other, +} + +#[macro_export] +/// Used to easily create errors from strings +macro_rules! format_err { + ( $( $arg:tt )* ) => { + { + use elefren::Error; + Error::Other(format!($($arg)*)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use reqwest; + use serde_json; + use serde_urlencoded; + use std::io; + + macro_rules! assert_is { + ($err:ident, $variant:pat) => { + assert!(match $err { + $variant => true, + _ => false, + }); + }; + } + + #[test] + fn from_http_error() { + let err: HttpError = reqwest::get("not an actual URL").unwrap_err(); + let err: Error = Error::from(err); + assert_is!(err, Error::Http(..)); + } + + #[test] + fn from_io_error() { + let err: IoError = io::Error::new(io::ErrorKind::Other, "other error"); + let err: Error = Error::from(err); + assert_is!(err, Error::Io(..)); + } + + #[test] + fn from_serde_error() { + let err: SerdeError = serde_json::from_str::<()>("not valid json").unwrap_err(); + let err: Error = Error::from(err); + assert_is!(err, Error::Serde(..)); + } + + #[test] + fn from_url_encoded_error() { + let err: UrlEncodedError = serde_urlencoded::ser::Error::Custom("error".into()); + let err: Error = Error::from(err); + assert_is!(err, Error::UrlEncoded(..)); + } + + #[test] + fn from_url_error() { + let err: UrlError = UrlError::EmptyHost; + let err: Error = Error::from(err); + assert_is!(err, Error::Url(..)); + } + + #[test] + fn from_api_error() { + let err: ApiError = ApiError { + error: None, + error_description: None, + }; + let err: Error = Error::from(err); + assert_is!(err, Error::Api(..)); + } + + #[cfg(feature = "toml")] + #[test] + fn from_toml_ser_error() { + let err: TomlSerError = TomlSerError::DateInvalid; + let err: Error = Error::from(err); + assert_is!(err, Error::TomlSer(..)); + } + + #[cfg(feature = "toml")] + #[test] + fn from_toml_de_error() { + use tomlcrate; + let err: TomlDeError = tomlcrate::from_str::<()>("not valid toml").unwrap_err(); + let err: Error = Error::from(err); + assert_is!(err, Error::TomlDe(..)); + } +} diff --git a/src/helpers/cli.rs b/src/helpers/cli.rs new file mode 100644 index 0000000..a1321d5 --- /dev/null +++ b/src/helpers/cli.rs @@ -0,0 +1,27 @@ +use std::io::{self, BufRead, Write}; + +use errors::Result; +use http_send::HttpSend; +use registration::Registered; +use Mastodon; + +/// Finishes the authentication process for the given `Registered` object, +/// using the command-line +pub fn authenticate(registration: Registered) -> Result> { + let url = registration.authorize_url()?; + + let stdout = io::stdout(); + let stdin = io::stdin(); + + let mut stdout = stdout.lock(); + let mut stdin = stdin.lock(); + + writeln!(&mut stdout, "Click this link to authorize: {}", url)?; + write!(&mut stdout, "Paste the returned authorization code: ")?; + stdout.flush()?; + + let mut input = String::new(); + stdin.read_line(&mut input)?; + let code = input.trim(); + Ok(registration.complete(code)?) +} diff --git a/src/helpers/env.rs b/src/helpers/env.rs new file mode 100644 index 0000000..1f13acb --- /dev/null +++ b/src/helpers/env.rs @@ -0,0 +1,81 @@ +use envy; + +use data::Data; +use Result; + +/// Attempts to deserialize a Data struct from the environment +pub fn from_env() -> Result { + Ok(envy::from_env()?) +} + +/// Attempts to deserialize a Data struct from the environment. All keys are +/// prefixed with the given prefix +pub fn from_env_prefixed(prefix: &str) -> Result { + Ok(envy::prefixed(prefix).from_env()?) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + env, + ops::FnOnce, + panic::{catch_unwind, UnwindSafe}, + }; + + fn withenv R + UnwindSafe, R>(prefix: Option<&'static str>, test: F) -> R { + env::set_var(makekey(prefix, "BASE"), "https://example.com"); + env::set_var(makekey(prefix, "CLIENT_ID"), "adbc01234"); + env::set_var(makekey(prefix, "CLIENT_SECRET"), "0987dcba"); + env::set_var(makekey(prefix, "REDIRECT"), "urn:ietf:wg:oauth:2.0:oob"); + env::set_var(makekey(prefix, "TOKEN"), "fedc5678"); + + let result = catch_unwind(test); + + env::remove_var(makekey(prefix, "BASE")); + env::remove_var(makekey(prefix, "CLIENT_ID")); + env::remove_var(makekey(prefix, "CLIENT_SECRET")); + env::remove_var(makekey(prefix, "REDIRECT")); + env::remove_var(makekey(prefix, "TOKEN")); + + fn makekey(prefix: Option<&'static str>, key: &str) -> String { + if let Some(prefix) = prefix { + format!("{}{}", prefix, key) + } else { + key.to_string() + } + } + + result.expect("failed") + } + + #[test] + fn test_from_env_no_prefix() { + let desered = withenv(None, || from_env()).expect("Couldn't deser"); + assert_eq!( + desered, + Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + } + ); + } + + #[test] + fn test_from_env_prefixed() { + let desered = withenv(Some("APP_"), || from_env_prefixed("APP_")).expect("Couldn't deser"); + assert_eq!( + desered, + Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + } + ); + } +} diff --git a/src/helpers/json.rs b/src/helpers/json.rs new file mode 100644 index 0000000..ab69890 --- /dev/null +++ b/src/helpers/json.rs @@ -0,0 +1,231 @@ +use std::{ + fs::{File, OpenOptions}, + io::{BufWriter, Read, Write}, + path::Path, +}; + +use serde_json; + +use data::Data; +use Result; + +/// Attempts to deserialize a Data struct from a string +pub fn from_str(s: &str) -> Result { + Ok(serde_json::from_str(s)?) +} + +/// Attempts to deserialize a Data struct from a slice of bytes +pub fn from_slice(s: &[u8]) -> Result { + Ok(serde_json::from_slice(s)?) +} + +/// Attempts to deserialize a Data struct from something that implements +/// the std::io::Read trait +pub fn from_reader(mut r: R) -> Result { + let mut buffer = Vec::new(); + r.read_to_end(&mut buffer)?; + from_slice(&buffer) +} + +/// Attempts to deserialize a Data struct from a file +pub fn from_file>(path: P) -> Result { + let path = path.as_ref(); + let file = File::open(path)?; + Ok(from_reader(file)?) +} + +/// Attempts to serialize a Data struct to a String +pub fn to_string(data: &Data) -> Result { + Ok(serde_json::to_string_pretty(data)?) +} + +/// Attempts to serialize a Data struct to a Vec of bytes +pub fn to_vec(data: &Data) -> Result> { + Ok(serde_json::to_vec(data)?) +} + +/// Attempts to serialize a Data struct to something that implements the +/// std::io::Write trait +pub fn to_writer(data: &Data, writer: W) -> Result<()> { + let mut buf_writer = BufWriter::new(writer); + let vec = to_vec(data)?; + buf_writer.write(&vec)?; + Ok(()) +} + +/// Attempts to serialize a Data struct to a file +/// +/// When opening the file, this will set the `.write(true)` and +/// `.truncate(true)` options, use the next method for more +/// fine-grained control +pub fn to_file>(data: &Data, path: P) -> Result<()> { + let mut options = OpenOptions::new(); + options.create(true).write(true).truncate(true); + to_file_with_options(data, path, options)?; + Ok(()) +} + +/// Attempts to serialize a Data struct to a file +pub fn to_file_with_options>( + data: &Data, + path: P, + options: OpenOptions, +) -> Result<()> { + let path = path.as_ref(); + let file = options.open(path)?; + to_writer(data, file)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{fs::OpenOptions, io::Cursor}; + use tempfile::{tempdir, NamedTempFile}; + + const DOC: &'static str = indoc!( + r#" + { + "base": "https://example.com", + "client_id": "adbc01234", + "client_secret": "0987dcba", + "redirect": "urn:ietf:wg:oauth:2.0:oob", + "token": "fedc5678" + } + "# + ); + + #[test] + fn test_from_str() { + let desered = from_str(DOC).expect("Couldn't deserialize Data"); + assert_eq!( + desered, + Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + } + ); + } + #[test] + fn test_from_slice() { + let doc = DOC.as_bytes(); + let desered = from_slice(&doc).expect("Couldn't deserialize Data"); + assert_eq!( + desered, + Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + } + ); + } + #[test] + fn test_from_reader() { + let doc = DOC.as_bytes(); + let doc = Cursor::new(doc); + let desered = from_reader(doc).expect("Couldn't deserialize Data"); + assert_eq!( + desered, + Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + } + ); + } + #[test] + fn test_from_file() { + let mut datafile = NamedTempFile::new().expect("Couldn't create tempfile"); + write!(&mut datafile, "{}", DOC).expect("Couldn't write Data to file"); + let desered = from_file(datafile.path()).expect("Couldn't deserialize Data"); + assert_eq!( + desered, + Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + } + ); + } + #[test] + fn test_to_string() { + let data = Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + }; + let s = to_string(&data).expect("Couldn't serialize Data"); + let desered = from_str(&s).expect("Couldn't deserialize Data"); + assert_eq!(data, desered); + } + #[test] + fn test_to_vec() { + let data = Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + }; + let v = to_vec(&data).expect("Couldn't write to vec"); + let desered = from_slice(&v).expect("Couldn't deserialize data"); + assert_eq!(data, desered); + } + #[test] + fn test_to_writer() { + let data = Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + }; + let mut buffer = Vec::new(); + to_writer(&data, &mut buffer).expect("Couldn't write to writer"); + let reader = Cursor::new(buffer); + let desered = from_reader(reader).expect("Couldn't deserialize Data"); + assert_eq!(data, desered); + } + #[test] + fn test_to_file() { + let data = Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + }; + let tempdir = tempdir().expect("Couldn't create tempdir"); + let filename = tempdir.path().join("mastodon-data.json"); + to_file(&data, &filename).expect("Couldn't write to file"); + let desered = from_file(&filename).expect("Couldn't deserialize Data"); + assert_eq!(data, desered); + } + #[test] + fn test_to_file_with_options() { + let data = Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + }; + let file = NamedTempFile::new().expect("Couldn't create tempfile"); + let mut options = OpenOptions::new(); + options.write(true).create(false).truncate(true); + to_file_with_options(&data, file.path(), options).expect("Couldn't write to file"); + let desered = from_file(file.path()).expect("Couldn't deserialize Data"); + assert_eq!(data, desered); + } +} diff --git a/src/helpers/mod.rs b/src/helpers/mod.rs new file mode 100644 index 0000000..57357b7 --- /dev/null +++ b/src/helpers/mod.rs @@ -0,0 +1,38 @@ +#[cfg(feature = "toml")] +/// Helpers for serializing to/deserializing from toml +/// +/// In order to use this module, set the "toml" feature in your Cargo.toml: +/// +/// ```toml,ignore +/// [dependencies.elefren] +/// version = "0.22" +/// features = ["toml"] +/// ``` +pub mod toml; + +#[cfg(feature = "json")] +/// Helpers for serializing to/deserializing from json +/// +/// In order to use this module, set the "json" feature in your Cargo.toml: +/// +/// ```toml,ignore +/// [dependencies.elefen] +/// version = "0.22" +/// features = ["json"] +/// ``` +pub mod json; + +#[cfg(feature = "env")] +/// Helpers for deserializing a `Data` struct from the environment +/// +/// In order to use this module, set the "env" feature in your Cargo.toml: +/// +/// ```toml,ignore +/// [dependencies.elefren] +/// version = "0.22" +/// features = ["env"] +/// ``` +pub mod env; + +/// Helpers for working with the command line +pub mod cli; diff --git a/src/helpers/toml.rs b/src/helpers/toml.rs new file mode 100644 index 0000000..be17783 --- /dev/null +++ b/src/helpers/toml.rs @@ -0,0 +1,229 @@ +use std::{ + fs::{File, OpenOptions}, + io::{BufWriter, Read, Write}, + path::Path, +}; + +use tomlcrate; + +use data::Data; +use Result; + +/// Attempts to deserialize a Data struct from a string +pub fn from_str(s: &str) -> Result { + Ok(tomlcrate::from_str(s)?) +} + +/// Attempts to deserialize a Data struct from a slice of bytes +pub fn from_slice(s: &[u8]) -> Result { + Ok(tomlcrate::from_slice(s)?) +} + +/// Attempts to deserialize a Data struct from something that implements +/// the std::io::Read trait +pub fn from_reader(mut r: R) -> Result { + let mut buffer = Vec::new(); + r.read_to_end(&mut buffer)?; + from_slice(&buffer) +} + +/// Attempts to deserialize a Data struct from a file +pub fn from_file>(path: P) -> Result { + let path = path.as_ref(); + let file = File::open(path)?; + Ok(from_reader(file)?) +} + +/// Attempts to serialize a Data struct to a String +pub fn to_string(data: &Data) -> Result { + Ok(tomlcrate::to_string_pretty(data)?) +} + +/// Attempts to serialize a Data struct to a Vec of bytes +pub fn to_vec(data: &Data) -> Result> { + Ok(tomlcrate::to_vec(data)?) +} + +/// Attempts to serialize a Data struct to something that implements the +/// std::io::Write trait +pub fn to_writer(data: &Data, writer: W) -> Result<()> { + let mut buf_writer = BufWriter::new(writer); + let vec = to_vec(data)?; + buf_writer.write(&vec)?; + Ok(()) +} + +/// Attempts to serialize a Data struct to a file +/// +/// When opening the file, this will set the `.write(true)` and +/// `.truncate(true)` options, use the next method for more +/// fine-grained control +pub fn to_file>(data: &Data, path: P) -> Result<()> { + let mut options = OpenOptions::new(); + options.create(true).write(true).truncate(true); + to_file_with_options(data, path, options)?; + Ok(()) +} + +/// Attempts to serialize a Data struct to a file +pub fn to_file_with_options>( + data: &Data, + path: P, + options: OpenOptions, +) -> Result<()> { + let path = path.as_ref(); + let file = options.open(path)?; + to_writer(data, file)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{fs::OpenOptions, io::Cursor}; + use tempfile::{tempdir, NamedTempFile}; + + const DOC: &'static str = indoc!( + r#" + base = "https://example.com" + client_id = "adbc01234" + client_secret = "0987dcba" + redirect = "urn:ietf:wg:oauth:2.0:oob" + token = "fedc5678" + "# + ); + + #[test] + fn test_from_str() { + let desered = from_str(DOC).expect("Couldn't deserialize Data"); + assert_eq!( + desered, + Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + } + ); + } + #[test] + fn test_from_slice() { + let doc = DOC.as_bytes(); + let desered = from_slice(&doc).expect("Couldn't deserialize Data"); + assert_eq!( + desered, + Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + } + ); + } + #[test] + fn test_from_reader() { + let doc = DOC.as_bytes(); + let doc = Cursor::new(doc); + let desered = from_reader(doc).expect("Couldn't deserialize Data"); + assert_eq!( + desered, + Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + } + ); + } + #[test] + fn test_from_file() { + let mut datafile = NamedTempFile::new().expect("Couldn't create tempfile"); + write!(&mut datafile, "{}", DOC).expect("Couldn't write Data to file"); + let desered = from_file(datafile.path()).expect("Couldn't deserialize Data"); + assert_eq!( + desered, + Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + } + ); + } + #[test] + fn test_to_string() { + let data = Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + }; + let s = to_string(&data).expect("Couldn't serialize Data"); + let desered = from_str(&s).expect("Couldn't deserialize Data"); + assert_eq!(data, desered); + } + #[test] + fn test_to_vec() { + let data = Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + }; + let v = to_vec(&data).expect("Couldn't write to vec"); + let desered = from_slice(&v).expect("Couldn't deserialize data"); + assert_eq!(data, desered); + } + #[test] + fn test_to_writer() { + let data = Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + }; + let mut buffer = Vec::new(); + to_writer(&data, &mut buffer).expect("Couldn't write to writer"); + let reader = Cursor::new(buffer); + let desered = from_reader(reader).expect("Couldn't deserialize Data"); + assert_eq!(data, desered); + } + #[test] + fn test_to_file() { + let data = Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + }; + let tempdir = tempdir().expect("Couldn't create tempdir"); + let filename = tempdir.path().join("mastodon-data.toml"); + to_file(&data, &filename).expect("Couldn't write to file"); + let desered = from_file(&filename).expect("Couldn't deserialize Data"); + assert_eq!(data, desered); + } + #[test] + fn test_to_file_with_options() { + let data = Data { + base: "https://example.com".into(), + client_id: "adbc01234".into(), + client_secret: "0987dcba".into(), + redirect: "urn:ietf:wg:oauth:2.0:oob".into(), + token: "fedc5678".into(), + }; + let file = NamedTempFile::new().expect("Couldn't create tempfile"); + let mut options = OpenOptions::new(); + options.write(true).create(false).truncate(true); + to_file_with_options(&data, file.path(), options).expect("Couldn't write to file"); + let desered = from_file(file.path()).expect("Couldn't deserialize Data"); + assert_eq!(data, desered); + } +} diff --git a/src/http_send.rs b/src/http_send.rs new file mode 100644 index 0000000..9c161f8 --- /dev/null +++ b/src/http_send.rs @@ -0,0 +1,26 @@ +use reqwest::{Client, Request, RequestBuilder, Response}; +use std::fmt::Debug; +use Result; + +/// Abstracts away the process of turning an HTTP request into an HTTP response +pub trait HttpSend: Clone + Debug { + /// Converts an HTTP request into an HTTP response + fn execute(&self, client: &Client, request: Request) -> Result; + + /// Convenience method so that .build() doesn't have to be called at every + /// call site + fn send(&self, client: &Client, builder: RequestBuilder) -> Result { + let request = builder.build()?; + self.execute(client, request) + } +} + +#[doc(hidden)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HttpSender; + +impl HttpSend for HttpSender { + fn execute(&self, client: &Client, request: Request) -> Result { + Ok(client.execute(request)?) + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..0f3d9d3 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,858 @@ +//! # Elefren: API Wrapper around the Mastodon API. +//! +//! Most of the api is documented on [Mastodon's website](https://docs.joinmastodon.org/client/intro/) +//! +//! ```no_run +//! # extern crate elefren; +//! # fn main() { +//! # try().unwrap(); +//! # } +//! # fn try() -> elefren::Result<()> { +//! use elefren::{helpers::cli, prelude::*}; +//! +//! let registration = Registration::new("https://mastodon.social") +//! .client_name("elefren_test") +//! .build()?; +//! let mastodon = cli::authenticate(registration)?; +//! +//! println!( +//! "{:?}", +//! mastodon +//! .get_home_timeline()? +//! .items_iter() +//! .take(100) +//! .collect::>() +//! ); +//! # Ok(()) +//! # } +//! ``` +//! +//! Elefren also supports Mastodon's Streaming API: +//! +//! # Example +//! +//! ```no_run +//! # extern crate elefren; +//! # use elefren::prelude::*; +//! # use std::error::Error; +//! use elefren::entities::event::Event; +//! # fn main() -> Result<(), Box> { +//! # let data = Data { +//! # base: "".into(), +//! # client_id: "".into(), +//! # client_secret: "".into(), +//! # redirect: "".into(), +//! # token: "".into(), +//! # }; +//! let client = Mastodon::from(data); +//! for event in client.streaming_user()? { +//! match event { +//! Event::Update(ref status) => { /* .. */ }, +//! Event::Notification(ref notification) => { /* .. */ }, +//! Event::Delete(ref id) => { /* .. */ }, +//! Event::FiltersChanged => { /* .. */ }, +//! } +//! } +//! # Ok(()) +//! # } +//! ``` + +#![deny( + missing_docs, + warnings, + missing_debug_implementations, + missing_copy_implementations, + trivial_casts, + trivial_numeric_casts, + unsafe_code, + unstable_features, + unused_import_braces, + unused_qualifications +)] + +#[macro_use] +extern crate log; +#[macro_use] +extern crate serde_derive; +#[macro_use] +extern crate doc_comment; +extern crate hyper_old_types; +extern crate isolang; +#[macro_use] +extern crate serde_json; +extern crate chrono; +extern crate reqwest; +extern crate serde; +extern crate serde_qs; +extern crate serde_urlencoded; +extern crate tap_reader; +extern crate try_from; +extern crate tungstenite; +extern crate url; + +#[cfg(feature = "env")] +extern crate envy; + +#[cfg(feature = "toml")] +extern crate toml as tomlcrate; + +#[cfg(test)] +extern crate tempfile; + +#[cfg(test)] +#[cfg_attr(all(test, any(feature = "toml", feature = "json")), macro_use)] +extern crate indoc; + +use std::{borrow::Cow, io::BufRead, ops}; + +use reqwest::{Client, RequestBuilder, Response}; +use tap_reader::Tap; +use tungstenite::client::AutoStream; + +use entities::prelude::*; +use http_send::{HttpSend, HttpSender}; +use page::Page; + +pub use data::Data; +pub use errors::{ApiError, Error, Result}; +pub use isolang::Language; +pub use mastodon_client::{MastodonClient, MastodonUnauthenticated}; +pub use registration::Registration; +pub use requests::{ + AddFilterRequest, + AddPushRequest, + StatusesRequest, + UpdateCredsRequest, + UpdatePushRequest, +}; +pub use status_builder::{NewStatus, StatusBuilder}; + +/// Registering your App +pub mod apps; +/// Contains the struct that holds the client auth data +pub mod data; +/// Entities returned from the API +pub mod entities; +/// Errors +pub mod errors; +/// Collection of helpers for serializing/deserializing `Data` objects +pub mod helpers; +/// Contains trait for converting `reqwest::Request`s to `reqwest::Response`s +pub mod http_send; +mod mastodon_client; +/// Handling multiple pages of entities. +pub mod page; +/// Registering your app. +pub mod registration; +/// Requests +pub mod requests; +/// OAuth Scopes +pub mod scopes; +/// Constructing a status +pub mod status_builder; +#[macro_use] +mod macros; +/// Automatically import the things you need +pub mod prelude { + pub use scopes::Scopes; + pub use Data; + pub use Mastodon; + pub use MastodonClient; + pub use NewStatus; + pub use Registration; + pub use StatusBuilder; + pub use StatusesRequest; +} + +/// Your mastodon application client, handles all requests to and from Mastodon. +#[derive(Clone, Debug)] +pub struct Mastodon { + client: Client, + http_sender: H, + /// Raw data about your mastodon instance. + pub data: Data, +} + +impl Mastodon { + methods![get, post, delete,]; + + fn route(&self, url: &str) -> String { + format!("{}{}", self.base, url) + } + + pub(crate) fn send(&self, req: RequestBuilder) -> Result { + Ok(self + .http_sender + .send(&self.client, req.bearer_auth(&self.token))?) + } +} + +impl From for Mastodon { + /// Creates a mastodon instance from the data struct. + fn from(data: Data) -> Mastodon { + let mut builder = MastodonBuilder::new(HttpSender); + builder.data(data); + builder + .build() + .expect("We know `data` is present, so this should be fine") + } +} + +impl MastodonClient for Mastodon { + type Stream = EventReader; + + paged_routes! { + (get) favourites: "favourites" => Status, + (get) blocks: "blocks" => Account, + (get) domain_blocks: "domain_blocks" => String, + (get) follow_requests: "follow_requests" => Account, + (get) get_home_timeline: "timelines/home" => Status, + (get) get_emojis: "custom_emojis" => Emoji, + (get) mutes: "mutes" => Account, + (get) notifications: "notifications" => Notification, + (get) reports: "reports" => Report, + (get (q: &'a str, #[serde(skip_serializing_if = "Option::is_none")] limit: Option, following: bool,)) search_accounts: "accounts/search" => Account, + (get) get_endorsements: "endorsements" => Account, + } + + paged_routes_with_id! { + (get) followers: "accounts/{}/followers" => Account, + (get) following: "accounts/{}/following" => Account, + (get) reblogged_by: "statuses/{}/reblogged_by" => Account, + (get) favourited_by: "statuses/{}/favourited_by" => Account, + } + + route! { + (delete (domain: String,)) unblock_domain: "domain_blocks" => Empty, + (get) instance: "instance" => Instance, + (get) verify_credentials: "accounts/verify_credentials" => Account, + (post (account_id: &str, status_ids: Vec<&str>, comment: String,)) report: "reports" => Report, + (post (domain: String,)) block_domain: "domain_blocks" => Empty, + (post (id: &str,)) authorize_follow_request: "accounts/follow_requests/authorize" => Empty, + (post (id: &str,)) reject_follow_request: "accounts/follow_requests/reject" => Empty, + (get (q: &'a str, resolve: bool,)) search: "search" => SearchResult, + (get (local: bool,)) get_public_timeline: "timelines/public" => Vec, + (post (uri: Cow<'static, str>,)) follows: "follows" => Account, + (post multipart (file: Cow<'static, str>,)) media: "media" => Attachment, + (post) clear_notifications: "notifications/clear" => Empty, + (post (id: &str,)) dismiss_notification: "notifications/dismiss" => Empty, + (get) get_push_subscription: "push/subscription" => Subscription, + (delete) delete_push_subscription: "push/subscription" => Empty, + (get) get_filters: "filters" => Vec, + (get) get_follow_suggestions: "suggestions" => Vec, + } + + route_v2! { + (get (q: &'a str, resolve: bool,)) search_v2: "search" => SearchResultV2, + } + + route_id! { + (get) get_account: "accounts/{}" => Account, + (post) follow: "accounts/{}/follow" => Relationship, + (post) unfollow: "accounts/{}/unfollow" => Relationship, + (post) block: "accounts/{}/block" => Relationship, + (post) unblock: "accounts/{}/unblock" => Relationship, + (get) mute: "accounts/{}/mute" => Relationship, + (get) unmute: "accounts/{}/unmute" => Relationship, + (get) get_notification: "notifications/{}" => Notification, + (get) get_status: "statuses/{}" => Status, + (get) get_context: "statuses/{}/context" => Context, + (get) get_card: "statuses/{}/card" => Card, + (post) reblog: "statuses/{}/reblog" => Status, + (post) unreblog: "statuses/{}/unreblog" => Status, + (post) favourite: "statuses/{}/favourite" => Status, + (post) unfavourite: "statuses/{}/unfavourite" => Status, + (delete) delete_status: "statuses/{}" => Empty, + (get) get_filter: "filters/{}" => Filter, + (delete) delete_filter: "filters/{}" => Empty, + (delete) delete_from_suggestions: "suggestions/{}" => Empty, + (post) endorse_user: "accounts/{}/pin" => Relationship, + (post) unendorse_user: "accounts/{}/unpin" => Relationship, + } + + fn add_filter(&self, request: &mut AddFilterRequest) -> Result { + let url = self.route("/api/v1/filters"); + let response = self.send(self.client.post(&url).json(&request))?; + + let status = response.status(); + + if status.is_client_error() { + return Err(Error::Client(status.clone())); + } else if status.is_server_error() { + return Err(Error::Server(status.clone())); + } + + deserialise(response) + } + + /// PUT /api/v1/filters/:id + fn update_filter(&self, id: &str, request: &mut AddFilterRequest) -> Result { + let url = self.route(&format!("/api/v1/filters/{}", id)); + let response = self.send(self.client.put(&url).json(&request))?; + + let status = response.status(); + + if status.is_client_error() { + return Err(Error::Client(status.clone())); + } else if status.is_server_error() { + return Err(Error::Server(status.clone())); + } + + deserialise(response) + } + + fn update_credentials(&self, builder: &mut UpdateCredsRequest) -> Result { + let changes = builder.build()?; + let url = self.route("/api/v1/accounts/update_credentials"); + let response = self.send(self.client.patch(&url).json(&changes))?; + + let status = response.status(); + + if status.is_client_error() { + return Err(Error::Client(status.clone())); + } else if status.is_server_error() { + return Err(Error::Server(status.clone())); + } + + deserialise(response) + } + + /// Post a new status to the account. + fn new_status(&self, status: NewStatus) -> Result { + let response = self.send( + self.client + .post(&self.route("/api/v1/statuses")) + .json(&status), + )?; + + deserialise(response) + } + + /// Get timeline filtered by a hashtag(eg. `#coffee`) either locally or + /// federated. + fn get_tagged_timeline(&self, hashtag: String, local: bool) -> Result> { + let base = "/api/v1/timelines/tag/"; + let url = if local { + self.route(&format!("{}{}?local=1", base, hashtag)) + } else { + self.route(&format!("{}{}", base, hashtag)) + }; + + self.get(url) + } + + /// Get statuses of a single account by id. Optionally only with pictures + /// and or excluding replies. + /// + /// # Example + /// + /// ```no_run + /// # extern crate elefren; + /// # use elefren::prelude::*; + /// # use std::error::Error; + /// # fn main() -> Result<(), Box> { + /// # let data = Data { + /// # base: "".into(), + /// # client_id: "".into(), + /// # client_secret: "".into(), + /// # redirect: "".into(), + /// # token: "".into(), + /// # }; + /// let client = Mastodon::from(data); + /// let statuses = client.statuses("user-id", None)?; + /// # Ok(()) + /// # } + /// ``` + /// + /// ```no_run + /// # extern crate elefren; + /// # use elefren::prelude::*; + /// # use std::error::Error; + /// # fn main() -> Result<(), Box> { + /// # let data = Data { + /// # base: "".into(), + /// # client_id: "".into(), + /// # client_secret: "".into(), + /// # redirect: "".into(), + /// # token: "".into(), + /// # }; + /// let client = Mastodon::from(data); + /// let mut request = StatusesRequest::new(); + /// request.only_media(); + /// let statuses = client.statuses("user-id", request)?; + /// # Ok(()) + /// # } + /// ``` + fn statuses<'a, 'b: 'a, S>(&'b self, id: &'b str, request: S) -> Result> + where + S: Into>>, + { + let mut url = format!("{}/api/v1/accounts/{}/statuses", self.base, id); + + if let Some(request) = request.into() { + url = format!("{}{}", url, request.to_querystring()?); + } + + let response = self.send(self.client.get(&url))?; + + Page::new(self, response) + } + + /// Returns the client account's relationship to a list of other accounts. + /// Such as whether they follow them or vice versa. + fn relationships(&self, ids: &[&str]) -> Result> { + let mut url = self.route("/api/v1/accounts/relationships?"); + + if ids.len() == 1 { + url += "id="; + url += &ids[0]; + } else { + for id in ids { + url += "id[]="; + url += &id; + url += "&"; + } + url.pop(); + } + + let response = self.send(self.client.get(&url))?; + + Page::new(self, response) + } + + /// Add a push notifications subscription + fn add_push_subscription(&self, request: &AddPushRequest) -> Result { + let request = request.build()?; + let response = self.send( + self.client + .post(&self.route("/api/v1/push/subscription")) + .json(&request), + )?; + + deserialise(response) + } + + /// Update the `data` portion of the push subscription associated with this + /// access token + fn update_push_data(&self, request: &UpdatePushRequest) -> Result { + let request = request.build(); + let response = self.send( + self.client + .put(&self.route("/api/v1/push/subscription")) + .json(&request), + )?; + + deserialise(response) + } + + /// Get all accounts that follow the authenticated user + fn follows_me(&self) -> Result> { + let me = self.verify_credentials()?; + Ok(self.followers(&me.id)?) + } + + /// Get all accounts that the authenticated user follows + fn followed_by_me(&self) -> Result> { + let me = self.verify_credentials()?; + Ok(self.following(&me.id)?) + } + + /// returns events that are relevant to the authorized user, i.e. home + /// timeline & notifications + /// + /// # Example + /// + /// ```no_run + /// # extern crate elefren; + /// # use elefren::prelude::*; + /// # use std::error::Error; + /// use elefren::entities::event::Event; + /// # fn main() -> Result<(), Box> { + /// # let data = Data { + /// # base: "".into(), + /// # client_id: "".into(), + /// # client_secret: "".into(), + /// # redirect: "".into(), + /// # token: "".into(), + /// # }; + /// let client = Mastodon::from(data); + /// for event in client.streaming_user()? { + /// match event { + /// Event::Update(ref status) => { /* .. */ }, + /// Event::Notification(ref notification) => { /* .. */ }, + /// Event::Delete(ref id) => { /* .. */ }, + /// Event::FiltersChanged => { /* .. */ }, + /// } + /// } + /// # Ok(()) + /// # } + /// ``` + fn streaming_user(&self) -> Result { + let mut url: url::Url = self.route("/api/v1/streaming").parse()?; + url.query_pairs_mut() + .append_pair("access_token", &self.token) + .append_pair("stream", "user"); + let mut url: url::Url = reqwest::get(url.as_str())?.url().as_str().parse()?; + let new_scheme = match url.scheme() { + "http" => "ws", + "https" => "wss", + x => return Err(Error::Other(format!("Bad URL scheme: {}", x))), + }; + url.set_scheme(new_scheme) + .map_err(|_| Error::Other("Bad URL scheme!".to_string()))?; + + let client = tungstenite::connect(url.as_str())?.0; + + Ok(EventReader(WebSocket(client))) + } + + /// returns all public statuses + fn streaming_public(&self) -> Result { + let mut url: url::Url = self.route("/api/v1/streaming").parse()?; + url.query_pairs_mut() + .append_pair("access_token", &self.token) + .append_pair("stream", "public"); + let mut url: url::Url = reqwest::get(url.as_str())?.url().as_str().parse()?; + let new_scheme = match url.scheme() { + "http" => "ws", + "https" => "wss", + x => return Err(Error::Other(format!("Bad URL scheme: {}", x))), + }; + url.set_scheme(new_scheme) + .map_err(|_| Error::Other("Bad URL scheme!".to_string()))?; + + let client = tungstenite::connect(url.as_str())?.0; + + Ok(EventReader(WebSocket(client))) + } + + /// Returns all local statuses + fn streaming_local(&self) -> Result { + let mut url: url::Url = self.route("/api/v1/streaming").parse()?; + url.query_pairs_mut() + .append_pair("access_token", &self.token) + .append_pair("stream", "public:local"); + let mut url: url::Url = reqwest::get(url.as_str())?.url().as_str().parse()?; + let new_scheme = match url.scheme() { + "http" => "ws", + "https" => "wss", + x => return Err(Error::Other(format!("Bad URL scheme: {}", x))), + }; + url.set_scheme(new_scheme) + .map_err(|_| Error::Other("Bad URL scheme!".to_string()))?; + + let client = tungstenite::connect(url.as_str())?.0; + + Ok(EventReader(WebSocket(client))) + } + + /// Returns all public statuses for a particular hashtag + fn streaming_public_hashtag(&self, hashtag: &str) -> Result { + let mut url: url::Url = self.route("/api/v1/streaming").parse()?; + url.query_pairs_mut() + .append_pair("access_token", &self.token) + .append_pair("stream", "hashtag") + .append_pair("tag", hashtag); + let mut url: url::Url = reqwest::get(url.as_str())?.url().as_str().parse()?; + let new_scheme = match url.scheme() { + "http" => "ws", + "https" => "wss", + x => return Err(Error::Other(format!("Bad URL scheme: {}", x))), + }; + url.set_scheme(new_scheme) + .map_err(|_| Error::Other("Bad URL scheme!".to_string()))?; + + let client = tungstenite::connect(url.as_str())?.0; + + Ok(EventReader(WebSocket(client))) + } + + /// Returns all local statuses for a particular hashtag + fn streaming_local_hashtag(&self, hashtag: &str) -> Result { + let mut url: url::Url = self.route("/api/v1/streaming").parse()?; + url.query_pairs_mut() + .append_pair("access_token", &self.token) + .append_pair("stream", "hashtag:local") + .append_pair("tag", hashtag); + let mut url: url::Url = reqwest::get(url.as_str())?.url().as_str().parse()?; + let new_scheme = match url.scheme() { + "http" => "ws", + "https" => "wss", + x => return Err(Error::Other(format!("Bad URL scheme: {}", x))), + }; + url.set_scheme(new_scheme) + .map_err(|_| Error::Other("Bad URL scheme!".to_string()))?; + + let client = tungstenite::connect(url.as_str())?.0; + + Ok(EventReader(WebSocket(client))) + } + + /// Returns statuses for a list + fn streaming_list(&self, list_id: &str) -> Result { + let mut url: url::Url = self.route("/api/v1/streaming").parse()?; + url.query_pairs_mut() + .append_pair("access_token", &self.token) + .append_pair("stream", "list") + .append_pair("list", list_id); + let mut url: url::Url = reqwest::get(url.as_str())?.url().as_str().parse()?; + let new_scheme = match url.scheme() { + "http" => "ws", + "https" => "wss", + x => return Err(Error::Other(format!("Bad URL scheme: {}", x))), + }; + url.set_scheme(new_scheme) + .map_err(|_| Error::Other("Bad URL scheme!".to_string()))?; + + let client = tungstenite::connect(url.as_str())?.0; + + Ok(EventReader(WebSocket(client))) + } + + /// Returns all direct messages + fn streaming_direct(&self) -> Result { + let mut url: url::Url = self.route("/api/v1/streaming").parse()?; + url.query_pairs_mut() + .append_pair("access_token", &self.token) + .append_pair("stream", "direct"); + let mut url: url::Url = reqwest::get(url.as_str())?.url().as_str().parse()?; + let new_scheme = match url.scheme() { + "http" => "ws", + "https" => "wss", + x => return Err(Error::Other(format!("Bad URL scheme: {}", x))), + }; + url.set_scheme(new_scheme) + .map_err(|_| Error::Other("Bad URL scheme!".to_string()))?; + + let client = tungstenite::connect(url.as_str())?.0; + + Ok(EventReader(WebSocket(client))) + } +} + +#[derive(Debug)] +/// WebSocket newtype so that EventStream can be implemented without coherency +/// issues +pub struct WebSocket(tungstenite::protocol::WebSocket); + +/// A type that streaming events can be read from +pub trait EventStream { + /// Read a message from this stream + fn read_message(&mut self) -> Result; +} + +impl EventStream for R { + fn read_message(&mut self) -> Result { + let mut buf = String::new(); + self.read_line(&mut buf)?; + Ok(buf) + } +} + +impl EventStream for WebSocket { + fn read_message(&mut self) -> Result { + Ok(self.0.read_message()?.into_text()?) + } +} + +#[derive(Debug)] +/// Iterator that produces events from a mastodon streaming API event stream +pub struct EventReader(R); +impl Iterator for EventReader { + type Item = Event; + + fn next(&mut self) -> Option { + let mut lines = Vec::new(); + loop { + if let Ok(line) = self.0.read_message() { + let line = line.trim().to_string(); + if line.starts_with(":") || line.is_empty() { + continue; + } + lines.push(line); + if let Ok(event) = self.make_event(&lines) { + lines.clear(); + return Some(event); + } else { + continue; + } + } + } + } +} + +impl EventReader { + fn make_event(&self, lines: &[String]) -> Result { + let event; + let data; + if let Some(event_line) = lines.iter().find(|line| line.starts_with("event:")) { + event = event_line[6..].trim().to_string(); + data = lines + .iter() + .find(|line| line.starts_with("data:")) + .map(|x| x[5..].trim().to_string()); + } else { + #[derive(Deserialize)] + struct Message { + pub event: String, + pub payload: Option, + } + let message = serde_json::from_str::(&lines[0])?; + event = message.event; + data = message.payload; + } + let event: &str = &event; + Ok(match event { + "notification" => { + let data = data.ok_or_else(|| { + Error::Other("Missing `data` line for notification".to_string()) + })?; + let notification = serde_json::from_str::(&data)?; + Event::Notification(notification) + }, + "update" => { + let data = + data.ok_or_else(|| Error::Other("Missing `data` line for update".to_string()))?; + let status = serde_json::from_str::(&data)?; + Event::Update(status) + }, + "delete" => { + let data = + data.ok_or_else(|| Error::Other("Missing `data` line for delete".to_string()))?; + Event::Delete(data) + }, + "filters_changed" => Event::FiltersChanged, + _ => return Err(Error::Other(format!("Unknown event `{}`", event))), + }) + } +} + +impl ops::Deref for Mastodon { + type Target = Data; + + fn deref(&self) -> &Self::Target { + &self.data + } +} + +struct MastodonBuilder { + client: Option, + http_sender: H, + data: Option, +} + +impl MastodonBuilder { + pub fn new(sender: H) -> Self { + MastodonBuilder { + http_sender: sender, + client: None, + data: None, + } + } + + pub fn client(&mut self, client: Client) -> &mut Self { + self.client = Some(client); + self + } + + pub fn data(&mut self, data: Data) -> &mut Self { + self.data = Some(data); + self + } + + pub fn build(self) -> Result> { + Ok(if let Some(data) = self.data { + Mastodon { + client: self.client.unwrap_or_else(|| Client::new()), + http_sender: self.http_sender, + data, + } + } else { + return Err(Error::MissingField("missing field 'data'")); + }) + } +} + +/// Client that can make unauthenticated calls to a mastodon instance +#[derive(Clone, Debug)] +pub struct MastodonUnauth { + client: Client, + http_sender: H, + base: url::Url, +} + +impl MastodonUnauth { + /// Create a new unauthenticated client + pub fn new(base: &str) -> Result> { + let base = if base.starts_with("https://") { + base.to_string() + } else { + format!("https://{}", base) + }; + Ok(MastodonUnauth { + client: Client::new(), + http_sender: HttpSender, + base: url::Url::parse(&base)?, + }) + } +} + +impl MastodonUnauth { + fn route(&self, url: &str) -> Result { + Ok(self.base.join(url)?) + } + + fn send(&self, req: RequestBuilder) -> Result { + Ok(self.http_sender.send(&self.client, req)?) + } +} + +impl MastodonUnauthenticated for MastodonUnauth { + /// GET /api/v1/statuses/:id + fn get_status(&self, id: &str) -> Result { + let route = self.route("/api/v1/statuses")?; + let route = route.join(id)?; + let response = self.send(self.client.get(route))?; + deserialise(response) + } + + /// GET /api/v1/statuses/:id/context + fn get_context(&self, id: &str) -> Result { + let route = self.route("/api/v1/statuses")?; + let route = route.join(id)?; + let route = route.join("context")?; + let response = self.send(self.client.get(route))?; + deserialise(response) + } + + /// GET /api/v1/statuses/:id/card + fn get_card(&self, id: &str) -> Result { + let route = self.route("/api/v1/statuses")?; + let route = route.join(id)?; + let route = route.join("card")?; + let response = self.send(self.client.get(route))?; + deserialise(response) + } +} + +// Convert the HTTP response body from JSON. Pass up deserialization errors +// transparently. +fn deserialise serde::Deserialize<'de>>(response: Response) -> Result { + let mut reader = Tap::new(response); + + match serde_json::from_reader(&mut reader) { + Ok(t) => { + debug!("{}", String::from_utf8_lossy(&reader.bytes)); + Ok(t) + }, + // If deserializing into the desired type fails try again to + // see if this is an error response. + Err(e) => { + error!("{}", String::from_utf8_lossy(&reader.bytes)); + if let Ok(error) = serde_json::from_slice(&reader.bytes) { + return Err(Error::Api(error)); + } + Err(e.into()) + }, + } +} diff --git a/src/macros.rs b/src/macros.rs new file mode 100644 index 0000000..0f9f1a2 --- /dev/null +++ b/src/macros.rs @@ -0,0 +1,364 @@ +macro_rules! methods { + ($($method:ident,)+) => { + $( + fn $method serde::Deserialize<'de>>(&self, url: String) + -> Result + { + let response = self.send( + self.client.$method(&url) + )?; + + deserialise(response) + } + )+ + }; +} + +macro_rules! paged_routes { + + (($method:ident) $name:ident: $url:expr => $ret:ty, $($rest:tt)*) => { + doc_comment! { + concat!( + "Equivalent to `", stringify!($method), " /api/v1/", + $url, + "`\n# Errors\nIf `access_token` is not set.", + "\n", + "```no_run", + "# extern crate elefren;\n", + "# use elefren::prelude::*;\n", + "# fn main() -> Result<(), Box<::std::error::Error>> {\n", + "# let data = Data {\n", + "# base: \"https://example.com\".into(),\n", + "# client_id: \"taosuah\".into(),\n", + "# client_secret: \"htnjdiuae\".into(),\n", + "# redirect: \"https://example.com\".into(),\n", + "# token: \"tsaohueaheis\".into(),\n", + "# };\n", + "let client = Mastodon::from(data);\n", + "client.", stringify!($name), "();\n", + "# Ok(())\n", + "# }\n", + "```" + ), + fn $name(&self) -> Result> { + let url = self.route(concat!("/api/v1/", $url)); + let response = self.send( + self.client.$method(&url) + )?; + + Page::new(self, response) + } + + } + + paged_routes!{$($rest)*} + }; + + ((get ($($(#[$m:meta])* $param:ident: $typ:ty,)*)) $name:ident: $url:expr => $ret:ty, $($rest:tt)*) => { + doc_comment! { + concat!( + "Equivalent to `get /api/v1/", + $url, + "`\n# Errors\nIf `access_token` is not set." + ), + fn $name<'a>(&self, $($param: $typ,)*) -> Result> { + use serde_urlencoded; + + #[derive(Serialize)] + struct Data<'a> { + $( + $( + #[$m] + )* + $param: $typ, + )* + #[serde(skip)] + _marker: ::std::marker::PhantomData<&'a ()>, + } + + let qs_data = Data { + $( + $param: $param, + )* + _marker: ::std::marker::PhantomData, + }; + + let qs = serde_urlencoded::to_string(&qs_data)?; + + let url = format!(concat!("/api/v1/", $url, "?{}"), &qs); + + let response = self.send( + self.client.get(&url) + )?; + + Page::new(self, response) + } + } + + paged_routes!{$($rest)*} + }; + + () => {} +} + +macro_rules! route_v2 { + ((get ($($param:ident: $typ:ty,)*)) $name:ident: $url:expr => $ret:ty, $($rest:tt)*) => { + doc_comment! { + concat!( + "Equivalent to `get /api/v2/", + $url, + "`\n# Errors\nIf `access_token` is not set." + ), + fn $name<'a>(&self, $($param: $typ,)*) -> Result<$ret> { + use serde_urlencoded; + + #[derive(Serialize)] + struct Data<'a> { + $( + $param: $typ, + )* + #[serde(skip)] + _marker: ::std::marker::PhantomData<&'a ()>, + } + + let qs_data = Data { + $( + $param: $param, + )* + _marker: ::std::marker::PhantomData, + }; + + let qs = serde_urlencoded::to_string(&qs_data)?; + + let url = format!(concat!("/api/v2/", $url, "?{}"), &qs); + + Ok(self.get(self.route(&url))?) + } + } + + route_v2!{$($rest)*} + }; + + () => {} +} + +macro_rules! route { + + ((post multipart ($($param:ident: $typ:ty,)*)) $name:ident: $url:expr => $ret:ty, $($rest:tt)*) => { + doc_comment! { + concat!( + "Equivalent to `post /api/v1/", + $url, + "`\n# Errors\nIf `access_token` is not set."), + fn $name(&self, $($param: $typ,)*) -> Result<$ret> { + use reqwest::multipart::Form; + + let form_data = Form::new() + $( + .file(stringify!($param), $param.as_ref())? + )*; + + let response = self.send( + self.client + .post(&self.route(concat!("/api/v1/", $url))) + .multipart(form_data) + )?; + + let status = response.status().clone(); + + if status.is_client_error() { + return Err(Error::Client(status)); + } else if status.is_server_error() { + return Err(Error::Server(status)); + } + + deserialise(response) + } + } + + route!{$($rest)*} + }; + + ((get ($($param:ident: $typ:ty,)*)) $name:ident: $url:expr => $ret:ty, $($rest:tt)*) => { + doc_comment! { + concat!( + "Equivalent to `get /api/v1/", + $url, + "`\n# Errors\nIf `access_token` is not set." + ), + fn $name<'a>(&self, $($param: $typ,)*) -> Result<$ret> { + use serde_urlencoded; + + #[derive(Serialize)] + struct Data<'a> { + $( + $param: $typ, + )* + #[serde(skip)] + _marker: ::std::marker::PhantomData<&'a ()>, + } + + let qs_data = Data { + $( + $param: $param, + )* + _marker: ::std::marker::PhantomData, + }; + + let qs = serde_urlencoded::to_string(&qs_data)?; + + let url = format!(concat!("/api/v1/", $url, "?{}"), &qs); + + Ok(self.get(self.route(&url))?) + } + } + + route!{$($rest)*} + }; + + (($method:ident ($($param:ident: $typ:ty,)*)) $name:ident: $url:expr => $ret:ty, $($rest:tt)*) => { + doc_comment! { + concat!( + "Equivalent to `", stringify!($method), " /api/v1/", + $url, + "`\n# Errors\nIf `access_token` is not set.", + ), + fn $name(&self, $($param: $typ,)*) -> Result<$ret> { + + let form_data = json!({ + $( + stringify!($param): $param, + )* + }); + + let response = self.send( + self.client.$method(&self.route(concat!("/api/v1/", $url))) + .json(&form_data) + )?; + + let status = response.status().clone(); + + if status.is_client_error() { + return Err(Error::Client(status)); + } else if status.is_server_error() { + return Err(Error::Server(status)); + } + + deserialise(response) + } + } + + route!{$($rest)*} + }; + + (($method:ident) $name:ident: $url:expr => $ret:ty, $($rest:tt)*) => { + doc_comment! { + concat!( + "Equivalent to `", stringify!($method), " /api/v1/", + $url, + "`\n# Errors\nIf `access_token` is not set.", + "\n", + "```no_run", + "# extern crate elefren;\n", + "# use elefren::prelude::*;\n", + "# fn main() -> Result<(), Box<::std::error::Error>> {\n", + "# let data = Data {\n", + "# base: \"https://example.com\".into(),\n", + "# client_id: \"taosuah\".into(),\n", + "# client_secret: \"htnjdiuae\".into(),\n", + "# redirect: \"https://example.com\".into(),\n", + "# token: \"tsaohueaheis\".into(),\n", + "# };\n", + "let client = Mastodon::from(data);\n", + "client.", stringify!($name), "();\n", + "# Ok(())\n", + "# }\n", + "```" + ), + fn $name(&self) -> Result<$ret> { + self.$method(self.route(concat!("/api/v1/", $url))) + } + } + + route!{$($rest)*} + }; + + () => {} +} + +macro_rules! route_id { + + ($(($method:ident) $name:ident: $url:expr => $ret:ty,)*) => { + $( + doc_comment! { + concat!( + "Equivalent to `", stringify!($method), " /api/v1/", + $url, + "`\n# Errors\nIf `access_token` is not set.", + "\n", + "```no_run", + "# extern crate elefren;\n", + "# use elefren::prelude::*;\n", + "# fn main() -> Result<(), Box<::std::error::Error>> {\n", + "# let data = Data {\n", + "# base: \"https://example.com\".into(),\n", + "# client_id: \"taosuah\".into(),\n", + "# client_secret: \"htnjdiuae\".into(),\n", + "# redirect: \"https://example.com\".into(),\n", + "# token: \"tsaohueaheis\".into(),\n", + "# };\n", + "let client = Mastodon::from(data);\n", + "client.", stringify!($name), "(\"42\");\n", + "# Ok(())\n", + "# }\n", + "```" + ), + fn $name(&self, id: &str) -> Result<$ret> { + self.$method(self.route(&format!(concat!("/api/v1/", $url), id))) + } + } + )* + } + +} +macro_rules! paged_routes_with_id { + + (($method:ident) $name:ident: $url:expr => $ret:ty, $($rest:tt)*) => { + doc_comment! { + concat!( + "Equivalent to `", stringify!($method), " /api/v1/", + $url, + "`\n# Errors\nIf `access_token` is not set.", + "\n", + "```no_run", + "# extern crate elefren;\n", + "# use elefren::prelude::*;\n", + "# fn main() -> Result<(), Box<::std::error::Error>> {\n", + "# let data = Data {\n", + "# base: \"https://example.com\".into(),\n", + "# client_id: \"taosuah\".into(),\n", + "# client_secret: \"htnjdiuae\".into(),\n", + "# redirect: \"https://example.com\".into(),\n", + "# token: \"tsaohueaheis\".into(),\n", + "# };\n", + "let client = Mastodon::from(data);\n", + "client.", stringify!($name), "(\"some-id\");\n", + "# Ok(())\n", + "# }\n", + "```" + ), + fn $name(&self, id: &str) -> Result> { + let url = self.route(&format!(concat!("/api/v1/", $url), id)); + let response = self.send( + self.client.$method(&url) + )?; + + Page::new(self, response) + } + } + + paged_routes_with_id!{$($rest)*} + }; + + () => {} +} diff --git a/src/mastodon_client.rs b/src/mastodon_client.rs new file mode 100644 index 0000000..6a63c7c --- /dev/null +++ b/src/mastodon_client.rs @@ -0,0 +1,388 @@ +use std::borrow::Cow; + +use entities::prelude::*; +use errors::Result; +use http_send::{HttpSend, HttpSender}; +use page::Page; +use requests::{ + AddFilterRequest, + AddPushRequest, + StatusesRequest, + UpdateCredsRequest, + UpdatePushRequest, +}; +use status_builder::NewStatus; + +/// Represents the set of methods that a Mastodon Client can do, so that +/// implementations might be swapped out for testing +#[allow(unused)] +pub trait MastodonClient { + /// Type that wraps streaming API streams + type Stream: Iterator; + + /// GET /api/v1/favourites + fn favourites(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/blocks + fn blocks(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/domain_blocks + fn domain_blocks(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/follow_requests + fn follow_requests(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/timelines/home + fn get_home_timeline(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/custom_emojis + fn get_emojis(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/mutes + fn mutes(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/notifications + fn notifications(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/reports + fn reports(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/accounts/:id/followers + fn followers(&self, id: &str) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/accounts/:id/following + fn following(&self, id: &str) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/statuses/:id/reblogged_by + fn reblogged_by(&self, id: &str) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/statuses/:id/favourited_by + fn favourited_by(&self, id: &str) -> Result> { + unimplemented!("This method was not implemented"); + } + /// DELETE /api/v1/domain_blocks + fn unblock_domain(&self, domain: String) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/instance + fn instance(&self) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/accounts/verify_credentials + fn verify_credentials(&self) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/reports + fn report(&self, account_id: &str, status_ids: Vec<&str>, comment: String) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/domain_blocks + fn block_domain(&self, domain: String) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/accounts/follow_requests/authorize + fn authorize_follow_request(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/accounts/follow_requests/reject + fn reject_follow_request(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/search + fn search<'a>(&self, q: &'a str, resolve: bool) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v2/search + fn search_v2<'a>(&self, q: &'a str, resolve: bool) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/follows + fn follows(&self, uri: Cow<'static, str>) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/media + fn media(&self, file: Cow<'static, str>) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/notifications/clear + fn clear_notifications(&self) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/notifications/dismiss + fn dismiss_notification(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/accounts/:id + fn get_account(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/accounts/:id/follow + fn follow(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/accounts/:id/unfollow + fn unfollow(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/accounts/:id/block + fn block(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/accounts/:id/unblock + fn unblock(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/accounts/:id/mute + fn mute(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/accounts/:id/unmute + fn unmute(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/notifications/:id + fn get_notification(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/statuses/:id + fn get_status(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/statuses/:id/context + fn get_context(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/statuses/:id/card + fn get_card(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/statuses/:id/reblog + fn reblog(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/statuses/:id/unreblog + fn unreblog(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/statuses/:id/favourite + fn favourite(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/statuses/:id/unfavourite + fn unfavourite(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// DELETE /api/v1/statuses/:id + fn delete_status(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// PATCH /api/v1/accounts/update_credentials + fn update_credentials(&self, builder: &mut UpdateCredsRequest) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/statuses + fn new_status(&self, status: NewStatus) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/timelines/public + fn get_public_timeline(&self, local: bool) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/timelines/tag/:hashtag + fn get_tagged_timeline(&self, hashtag: String, local: bool) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/accounts/:id/statuses + fn statuses<'a, 'b: 'a, S>(&'b self, id: &'b str, request: S) -> Result> + where + S: Into>>, + { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/accounts/relationships + fn relationships(&self, ids: &[&str]) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/accounts/search?q=:query&limit=:limit&following=:following + fn search_accounts( + &self, + query: &str, + limit: Option, + following: bool, + ) -> Result> { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/push/subscription + fn add_push_subscription(&self, request: &AddPushRequest) -> Result { + unimplemented!("This method was not implemented"); + } + /// PUT /api/v1/push/subscription + fn update_push_data(&self, request: &UpdatePushRequest) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/push/subscription + fn get_push_subscription(&self) -> Result { + unimplemented!("This method was not implemented"); + } + /// DELETE /api/v1/push/subscription + fn delete_push_subscription(&self) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/filters + fn get_filters(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/filters + fn add_filter(&self, request: &mut AddFilterRequest) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/filters/:id + fn get_filter(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// PUT /api/v1/filters/:id + fn update_filter(&self, id: &str, request: &mut AddFilterRequest) -> Result { + unimplemented!("This method was not implemented"); + } + /// DELETE /api/v1/filters/:id + fn delete_filter(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/suggestions + fn get_follow_suggestions(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// DELETE /api/v1/suggestions/:account_id + fn delete_from_suggestions(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/endorsements + fn get_endorsements(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/accounts/:id/pin + fn endorse_user(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// POST /api/v1/accounts/:id/unpin + fn unendorse_user(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// Shortcut for: `let me = client.verify_credentials(); client.followers()` + /// + /// ```no_run + /// # extern crate elefren; + /// # use std::error::Error; + /// # use elefren::prelude::*; + /// # fn main() -> Result<(), Box> { + /// # let data = Data { + /// # base: "".into(), + /// # client_id: "".into(), + /// # client_secret: "".into(), + /// # redirect: "".into(), + /// # token: "".into(), + /// # }; + /// # let client = Mastodon::from(data); + /// let follows_me = client.follows_me()?; + /// # Ok(()) + /// # } + fn follows_me(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + /// Shortcut for + /// `let me = client.verify_credentials(); client.following(&me.id)` + /// + /// ```no_run + /// # extern crate elefren; + /// # use std::error::Error; + /// # use elefren::prelude::*; + /// # fn main() -> Result<(), Box> { + /// # let data = Data { + /// # base: "".into(), + /// # client_id: "".into(), + /// # client_secret: "".into(), + /// # redirect: "".into(), + /// # token: "".into(), + /// # }; + /// # let client = Mastodon::from(data); + /// let follows_me = client.followed_by_me()?; + /// # Ok(()) + /// # } + fn followed_by_me(&self) -> Result> { + unimplemented!("This method was not implemented"); + } + + /// Returns events that are relevant to the authorized user, i.e. home + /// timeline and notifications + fn streaming_user(&self) -> Result { + unimplemented!("This method was not implemented"); + } + + /// Returns all public statuses + fn streaming_public(&self) -> Result { + unimplemented!("This method was not implemented"); + } + + /// Returns all local statuses + fn streaming_local(&self) -> Result { + unimplemented!("This method was not implemented"); + } + + /// Returns all public statuses for a particular hashtag + fn streaming_public_hashtag(&self, hashtag: &str) -> Result { + unimplemented!("This method was not implemented"); + } + + /// Returns all local statuses for a particular hashtag + fn streaming_local_hashtag(&self, hashtag: &str) -> Result { + unimplemented!("This method was not implemented"); + } + + /// Returns statuses for a list + fn streaming_list(&self, list_id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + + /// Returns all direct messages + fn streaming_direct(&self) -> Result { + unimplemented!("This method was not implemented"); + } +} + +/// Trait that represents clients that can make unauthenticated calls to a +/// mastodon instance +#[allow(unused)] +pub trait MastodonUnauthenticated { + /// GET /api/v1/statuses/:id + fn get_status(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/statuses/:id/context + fn get_context(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/statuses/:id/card + fn get_card(&self, id: &str) -> Result { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/statuses/:id/reblogged_by + fn reblogged_by(&self, id: &str) -> Result> { + unimplemented!("This method was not implemented"); + } + /// GET /api/v1/statuses/:id/favourited_by + fn favourited_by(&self, id: &str) -> Result> { + unimplemented!("This method was not implemented"); + } +} diff --git a/src/page.rs b/src/page.rs new file mode 100644 index 0000000..3a47ce6 --- /dev/null +++ b/src/page.rs @@ -0,0 +1,226 @@ +use super::{deserialise, Mastodon, Result}; +use entities::itemsiter::ItemsIter; +use hyper_old_types::header::{parsing, Link, RelationType}; +use reqwest::{header::LINK, Response}; +use serde::Deserialize; +use url::Url; + +use http_send::HttpSend; + +macro_rules! pages { + ($($direction:ident: $fun:ident),*) => { + + $( + doc_comment!(concat!( + "Method to retrieve the ", stringify!($direction), " page of results"), + pub fn $fun(&mut self) -> Result>> { + let url = match self.$direction.take() { + Some(s) => s, + None => return Ok(None), + }; + + let response = self.mastodon.send( + self.mastodon.client.get(url) + )?; + + let (prev, next) = get_links(&response)?; + self.next = next; + self.prev = prev; + + deserialise(response) + }); + )* + } +} + +/// Owned version of the `Page` struct in this module. Allows this to be more +/// easily stored for later use +/// +/// # Example +/// +/// ```no_run +/// # extern crate elefren; +/// # use elefren::Mastodon; +/// # use elefren::page::OwnedPage; +/// # use elefren::http_send::HttpSender; +/// # use elefren::entities::status::Status; +/// # use std::cell::RefCell; +/// # use elefren::prelude::*; +/// # fn main() -> Result<(), elefren::Error> { +/// # let data = Data { +/// # base: "".into(), +/// # client_id: "".into(), +/// # client_secret: "".into(), +/// # redirect: "".into(), +/// # token: "".into(), +/// # }; +/// struct HomeTimeline { +/// client: Mastodon, +/// page: RefCell>>, +/// } +/// let client = Mastodon::from(data); +/// let home = client.get_home_timeline()?.to_owned(); +/// let tl = HomeTimeline { +/// client, +/// page: RefCell::new(Some(home)), +/// }; +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Clone)] +pub struct OwnedPage Deserialize<'de>, H: HttpSend> { + mastodon: Mastodon, + next: Option, + prev: Option, + /// Initial set of items + pub initial_items: Vec, +} + +impl Deserialize<'de>, H: HttpSend> OwnedPage { + pages! { + next: next_page, + prev: prev_page + } +} + +impl<'a, T: for<'de> Deserialize<'de>, H: HttpSend> From> for OwnedPage { + fn from(page: Page<'a, T, H>) -> OwnedPage { + OwnedPage { + mastodon: page.mastodon.clone(), + next: page.next, + prev: page.prev, + initial_items: page.initial_items, + } + } +} + +/// Represents a single page of API results +#[derive(Debug, Clone)] +pub struct Page<'a, T: for<'de> Deserialize<'de>, H: 'a + HttpSend> { + mastodon: &'a Mastodon, + next: Option, + prev: Option, + /// Initial set of items + pub initial_items: Vec, +} + +impl<'a, T: for<'de> Deserialize<'de>, H: HttpSend> Page<'a, T, H> { + pages! { + next: next_page, + prev: prev_page + } + + pub(crate) fn new(mastodon: &'a Mastodon, response: Response) -> Result { + let (prev, next) = get_links(&response)?; + Ok(Page { + initial_items: deserialise(response)?, + next, + prev, + mastodon, + }) + } +} + +impl<'a, T: Clone + for<'de> Deserialize<'de>, H: HttpSend> Page<'a, T, H> { + /// Returns an owned version of this struct that doesn't borrow the client + /// that created it + /// + /// # Example + /// + /// ```no_run + /// # extern crate elefren; + /// # use elefren::Mastodon; + /// # use elefren::page::OwnedPage; + /// # use elefren::http_send::HttpSender; + /// # use elefren::entities::status::Status; + /// # use std::cell::RefCell; + /// # use elefren::prelude::*; + /// # fn main() -> Result<(), elefren::Error> { + /// # let data = Data { + /// # base: "".into(), + /// # client_id: "".into(), + /// # client_secret: "".into(), + /// # redirect: "".into(), + /// # token: "".into(), + /// # }; + /// struct HomeTimeline { + /// client: Mastodon, + /// page: RefCell>>, + /// } + /// let client = Mastodon::from(data); + /// let home = client.get_home_timeline()?.to_owned(); + /// let tl = HomeTimeline { + /// client, + /// page: RefCell::new(Some(home)), + /// }; + /// # Ok(()) + /// # } + /// ``` + pub fn to_owned(self) -> OwnedPage { + OwnedPage::from(self) + } + + /// Returns an iterator that provides a stream of `T`s + /// + /// This abstracts away the process of iterating over each item in a page, + /// then making an http call, then iterating over each item in the new + /// page, etc. The iterator provides a stream of `T`s, calling + /// `self.next_page()` + /// when necessary to get + /// more of them, until + /// there are no more items. + /// + /// # Example + /// + /// ```no_run + /// # extern crate elefren; + /// # use std::error::Error; + /// use elefren::prelude::*; + /// # fn main() -> Result<(), Box> { + /// # let data = Data { + /// # base: "".into(), + /// # client_id: "".into(), + /// # client_secret: "".into(), + /// # redirect: "".into(), + /// # token: "".into(), + /// # }; + /// let mastodon = Mastodon::from(data); + /// let req = StatusesRequest::new(); + /// let resp = mastodon.statuses("some-id", req)?; + /// for status in resp.items_iter() { + /// // do something with status + /// } + /// # Ok(()) + /// # } + /// ``` + pub fn items_iter(self) -> impl Iterator + 'a + where + T: 'a, + { + ItemsIter::new(self) + } +} + +fn get_links(response: &Response) -> Result<(Option, Option)> { + let mut prev = None; + let mut next = None; + + if let Some(link_header) = response.headers().get(LINK) { + let link_header = link_header.to_str()?; + let link_header = link_header.as_bytes(); + let link_header: Link = parsing::from_raw_str(&link_header)?; + for value in link_header.values() { + if let Some(relations) = value.rel() { + if relations.contains(&RelationType::Next) { + next = Some(Url::parse(value.link())?); + } + + if relations.contains(&RelationType::Prev) { + prev = Some(Url::parse(value.link())?); + } + } + } + } + + Ok((prev, next)) +} diff --git a/src/registration.rs b/src/registration.rs new file mode 100644 index 0000000..7aba7c5 --- /dev/null +++ b/src/registration.rs @@ -0,0 +1,430 @@ +use std::borrow::Cow; + +use reqwest::{Client, RequestBuilder, Response}; +use try_from::TryInto; +use url::percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET}; + +use apps::{App, AppBuilder}; +use http_send::{HttpSend, HttpSender}; +use scopes::Scopes; +use Data; +use Error; +use Mastodon; +use MastodonBuilder; +use Result; + +const DEFAULT_REDIRECT_URI: &'static str = "urn:ietf:wg:oauth:2.0:oob"; + +/// Handles registering your mastodon app to your instance. It is recommended +/// you cache your data struct to avoid registering on every run. +#[derive(Debug, Clone)] +pub struct Registration<'a, H: HttpSend = HttpSender> { + base: String, + client: Client, + app_builder: AppBuilder<'a>, + force_login: bool, + http_sender: H, +} + +#[derive(Deserialize)] +struct OAuth { + client_id: String, + client_secret: String, + #[serde(default = "default_redirect_uri")] + redirect_uri: String, +} + +fn default_redirect_uri() -> String { + DEFAULT_REDIRECT_URI.to_string() +} + +#[derive(Deserialize)] +struct AccessToken { + access_token: String, +} + +impl<'a> Registration<'a, HttpSender> { + /// Construct a new registration process to the instance of the `base` url. + /// ``` + /// use elefren::prelude::*; + /// + /// let registration = Registration::new("https://mastodon.social"); + /// ``` + pub fn new>(base: I) -> Self { + Registration { + base: base.into(), + client: Client::new(), + app_builder: AppBuilder::new(), + force_login: false, + http_sender: HttpSender, + } + } +} + +impl<'a, H: HttpSend> Registration<'a, H> { + #[allow(dead_code)] + pub(crate) fn with_sender>(base: I, http_sender: H) -> Self { + Registration { + base: base.into(), + client: Client::new(), + app_builder: AppBuilder::new(), + force_login: false, + http_sender, + } + } + + /// Sets the name of this app + /// + /// This is required, and if this isn't set then the AppBuilder::build + /// method will fail + pub fn client_name>>(&mut self, name: I) -> &mut Self { + self.app_builder.client_name(name.into()); + self + } + + /// Sets the redirect uris that this app uses + pub fn redirect_uris>>(&mut self, uris: I) -> &mut Self { + self.app_builder.redirect_uris(uris); + self + } + + /// Sets the scopes that this app requires + /// + /// The default for an app is Scopes::Read + pub fn scopes(&mut self, scopes: Scopes) -> &mut Self { + self.app_builder.scopes(scopes); + self + } + + /// Sets the optional "website" to register the app with + pub fn website>>(&mut self, website: I) -> &mut Self { + self.app_builder.website(website); + self + } + + /// Forces the user to re-login (useful if you need to re-auth as a + /// different user on the same instance + pub fn force_login(&mut self, force_login: bool) -> &mut Self { + self.force_login = force_login; + self + } + + fn send(&self, req: RequestBuilder) -> Result { + Ok(self.http_sender.send(&self.client, req)?) + } + + /// Register the given application + /// + /// ```no_run + /// # extern crate elefren; + /// # fn main () -> elefren::Result<()> { + /// use elefren::{apps::App, prelude::*}; + /// + /// let mut app = App::builder(); + /// app.client_name("elefren_test"); + /// + /// let registration = Registration::new("https://mastodon.social").register(app)?; + /// let url = registration.authorize_url()?; + /// // Here you now need to open the url in the browser + /// // And handle a the redirect url coming back with the code. + /// let code = String::from("RETURNED_FROM_BROWSER"); + /// let mastodon = registration.complete(&code)?; + /// + /// println!("{:?}", mastodon.get_home_timeline()?.initial_items); + /// # Ok(()) + /// # } + /// ``` + pub fn register>(&mut self, app: I) -> Result> + where + Error: From<>::Err>, + { + let app = app.try_into()?; + let oauth = self.send_app(&app)?; + + Ok(Registered { + base: self.base.clone(), + client: self.client.clone(), + client_id: oauth.client_id, + client_secret: oauth.client_secret, + redirect: oauth.redirect_uri, + scopes: app.scopes().clone(), + force_login: self.force_login, + http_sender: self.http_sender.clone(), + }) + } + + /// Register the application with the server from the `base` url. + /// + /// ```no_run + /// # extern crate elefren; + /// # fn main () -> elefren::Result<()> { + /// use elefren::prelude::*; + /// + /// let registration = Registration::new("https://mastodon.social") + /// .client_name("elefren_test") + /// .build()?; + /// let url = registration.authorize_url()?; + /// // Here you now need to open the url in the browser + /// // And handle a the redirect url coming back with the code. + /// let code = String::from("RETURNED_FROM_BROWSER"); + /// let mastodon = registration.complete(&code)?; + /// + /// println!("{:?}", mastodon.get_home_timeline()?.initial_items); + /// # Ok(()) + /// # } + /// ``` + pub fn build(&mut self) -> Result> { + let app: App = self.app_builder.clone().build()?; + let oauth = self.send_app(&app)?; + + Ok(Registered { + base: self.base.clone(), + client: self.client.clone(), + client_id: oauth.client_id, + client_secret: oauth.client_secret, + redirect: oauth.redirect_uri, + scopes: app.scopes().clone(), + force_login: self.force_login, + http_sender: self.http_sender.clone(), + }) + } + + fn send_app(&self, app: &App) -> Result { + let url = format!("{}/api/v1/apps", self.base); + Ok(self.send(self.client.post(&url).json(&app))?.json()?) + } +} + +impl Registered { + /// Skip having to retrieve the client id and secret from the server by + /// creating a `Registered` struct directly + /// + /// # Example + /// + /// ```no_run + /// # extern crate elefren; + /// # fn main() -> elefren::Result<()> { + /// use elefren::{prelude::*, registration::Registered}; + /// + /// let registration = Registered::from_parts( + /// "https://example.com", + /// "the-client-id", + /// "the-client-secret", + /// "https://example.com/redirect", + /// Scopes::read_all(), + /// false, + /// ); + /// let url = registration.authorize_url()?; + /// // Here you now need to open the url in the browser + /// // And handle a the redirect url coming back with the code. + /// let code = String::from("RETURNED_FROM_BROWSER"); + /// let mastodon = registration.complete(&code)?; + /// + /// println!("{:?}", mastodon.get_home_timeline()?.initial_items); + /// # Ok(()) + /// # } + /// ``` + pub fn from_parts( + base: &str, + client_id: &str, + client_secret: &str, + redirect: &str, + scopes: Scopes, + force_login: bool, + ) -> Registered { + Registered { + base: base.to_string(), + client: Client::new(), + client_id: client_id.to_string(), + client_secret: client_secret.to_string(), + redirect: redirect.to_string(), + scopes, + force_login, + http_sender: HttpSender, + } + } +} + +impl Registered { + fn send(&self, req: RequestBuilder) -> Result { + Ok(self.http_sender.send(&self.client, req)?) + } + + /// Returns the parts of the `Registered` struct that can be used to + /// recreate another `Registered` struct + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::{prelude::*, registration::Registered}; + /// # fn main() -> Result<(), Box> { + /// + /// let origbase = "https://example.social"; + /// let origclient_id = "some-client_id"; + /// let origclient_secret = "some-client-secret"; + /// let origredirect = "https://example.social/redirect"; + /// let origscopes = Scopes::all(); + /// let origforce_login = false; + /// + /// let registered = Registered::from_parts( + /// origbase, + /// origclient_id, + /// origclient_secret, + /// origredirect, + /// origscopes.clone(), + /// origforce_login, + /// ); + /// + /// let (base, client_id, client_secret, redirect, scopes, force_login) = registered.into_parts(); + /// + /// assert_eq!(origbase, &base); + /// assert_eq!(origclient_id, &client_id); + /// assert_eq!(origclient_secret, &client_secret); + /// assert_eq!(origredirect, &redirect); + /// assert_eq!(origscopes, scopes); + /// assert_eq!(origforce_login, force_login); + /// # Ok(()) + /// # } + /// ``` + pub fn into_parts(self) -> (String, String, String, String, Scopes, bool) { + ( + self.base, + self.client_id, + self.client_secret, + self.redirect, + self.scopes, + self.force_login, + ) + } + + /// Returns the full url needed for authorisation. This needs to be opened + /// in a browser. + pub fn authorize_url(&self) -> Result { + let scopes = format!("{}", self.scopes); + let scopes: String = utf8_percent_encode(&scopes, DEFAULT_ENCODE_SET).collect(); + let url = if self.force_login { + format!( + "{}/oauth/authorize?client_id={}&redirect_uri={}&scope={}&force_login=true&\ + response_type=code", + self.base, self.client_id, self.redirect, scopes, + ) + } else { + format!( + "{}/oauth/authorize?client_id={}&redirect_uri={}&scope={}&response_type=code", + self.base, self.client_id, self.redirect, scopes, + ) + }; + + Ok(url) + } + + /// Create an access token from the client id, client secret, and code + /// provided by the authorisation url. + pub fn complete(&self, code: &str) -> Result> { + let url = format!( + "{}/oauth/token?client_id={}&client_secret={}&code={}&grant_type=authorization_code&\ + redirect_uri={}", + self.base, self.client_id, self.client_secret, code, self.redirect + ); + + let token: AccessToken = self.send(self.client.post(&url))?.json()?; + + let data = Data { + base: self.base.clone().into(), + client_id: self.client_id.clone().into(), + client_secret: self.client_secret.clone().into(), + redirect: self.redirect.clone().into(), + token: token.access_token.into(), + }; + + let mut builder = MastodonBuilder::new(self.http_sender.clone()); + builder.client(self.client.clone()).data(data); + Ok(builder.build()?) + } +} + +/// Represents the state of the auth flow when the app has been registered but +/// the user is not authenticated +#[derive(Debug, Clone)] +pub struct Registered { + base: String, + client: Client, + client_id: String, + client_secret: String, + redirect: String, + scopes: Scopes, + force_login: bool, + http_sender: H, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_registration_new() { + let r = Registration::new("https://example.com"); + assert_eq!(r.base, "https://example.com".to_string()); + assert_eq!(r.app_builder, AppBuilder::new()); + assert_eq!(r.http_sender, HttpSender); + } + + #[test] + fn test_registration_with_sender() { + let r = Registration::with_sender("https://example.com", HttpSender); + assert_eq!(r.base, "https://example.com".to_string()); + assert_eq!(r.app_builder, AppBuilder::new()); + assert_eq!(r.http_sender, HttpSender); + } + + #[test] + fn test_set_client_name() { + let mut r = Registration::new("https://example.com"); + r.client_name("foo-test"); + + assert_eq!(r.base, "https://example.com".to_string()); + assert_eq!( + &mut r.app_builder, + AppBuilder::new().client_name("foo-test") + ); + } + + #[test] + fn test_set_redirect_uris() { + let mut r = Registration::new("https://example.com"); + r.redirect_uris("https://foo.com"); + + assert_eq!(r.base, "https://example.com".to_string()); + assert_eq!( + &mut r.app_builder, + AppBuilder::new().redirect_uris("https://foo.com") + ); + } + + #[test] + fn test_set_scopes() { + let mut r = Registration::new("https://example.com"); + r.scopes(Scopes::all()); + + assert_eq!(r.base, "https://example.com".to_string()); + assert_eq!(&mut r.app_builder, AppBuilder::new().scopes(Scopes::all())); + } + + #[test] + fn test_set_website() { + let mut r = Registration::new("https://example.com"); + r.website("https://website.example.com"); + + assert_eq!(r.base, "https://example.com".to_string()); + assert_eq!( + &mut r.app_builder, + AppBuilder::new().website("https://website.example.com") + ); + } + + #[test] + fn test_default_redirect_uri() { + assert_eq!(&default_redirect_uri()[..], DEFAULT_REDIRECT_URI); + } +} diff --git a/src/requests/filter.rs b/src/requests/filter.rs new file mode 100644 index 0000000..6f3c700 --- /dev/null +++ b/src/requests/filter.rs @@ -0,0 +1,154 @@ +use entities::filter::FilterContext; +use std::time::Duration; + +/// Form used to create a filter +/// +/// # Example +/// +/// ``` +/// # extern crate elefren; +/// # use std::error::Error; +/// use elefren::{entities::filter::FilterContext, requests::AddFilterRequest}; +/// # fn main() -> Result<(), Box> { +/// let request = AddFilterRequest::new("foo", FilterContext::Home); +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct AddFilterRequest { + phrase: String, + context: FilterContext, + irreversible: Option, + whole_word: Option, + #[serde(serialize_with = "serialize_duration::ser")] + expires_in: Option, +} + +impl AddFilterRequest { + /// Create a new AddFilterRequest + pub fn new(phrase: &str, context: FilterContext) -> AddFilterRequest { + AddFilterRequest { + phrase: phrase.to_string(), + context, + irreversible: None, + whole_word: None, + expires_in: None, + } + } + + /// Set `irreversible` to `true` + pub fn irreversible(&mut self) -> &mut Self { + self.irreversible = Some(true); + self + } + + /// Set `whole_word` to `true` + pub fn whole_word(&mut self) -> &mut Self { + self.whole_word = Some(true); + self + } + + /// Set `expires_in` to a duration + pub fn expires_in(&mut self, d: Duration) -> &mut Self { + self.expires_in = Some(d); + self + } +} + +mod serialize_duration { + use serde::ser::Serializer; + use std::time::Duration; + + pub(crate) fn ser(duration: &Option, s: S) -> Result + where + S: Serializer, + { + if let Some(d) = duration { + let sec = d.as_secs(); + s.serialize_u64(sec) + } else { + s.serialize_none() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json; + use std::time::Duration; + + #[test] + fn test_new() { + let request = AddFilterRequest::new("foo", FilterContext::Home); + assert_eq!( + request, + AddFilterRequest { + phrase: "foo".to_string(), + context: FilterContext::Home, + irreversible: None, + whole_word: None, + expires_in: None, + } + ) + } + + #[test] + fn test_irreversible() { + let mut request = AddFilterRequest::new("foo", FilterContext::Home); + request.irreversible(); + assert_eq!( + request, + AddFilterRequest { + phrase: "foo".to_string(), + context: FilterContext::Home, + irreversible: Some(true), + whole_word: None, + expires_in: None, + } + ) + } + + #[test] + fn test_whole_word() { + let mut request = AddFilterRequest::new("foo", FilterContext::Home); + request.whole_word(); + assert_eq!( + request, + AddFilterRequest { + phrase: "foo".to_string(), + context: FilterContext::Home, + irreversible: None, + whole_word: Some(true), + expires_in: None, + } + ) + } + + #[test] + fn test_expires_in() { + let mut request = AddFilterRequest::new("foo", FilterContext::Home); + request.expires_in(Duration::from_secs(300)); + assert_eq!( + request, + AddFilterRequest { + phrase: "foo".to_string(), + context: FilterContext::Home, + irreversible: None, + whole_word: None, + expires_in: Some(Duration::from_secs(300)), + } + ) + } + + #[test] + fn test_serialize_request() { + let mut request = AddFilterRequest::new("foo", FilterContext::Home); + request.expires_in(Duration::from_secs(300)); + let ser = serde_json::to_string(&request).expect("Couldn't serialize"); + assert_eq!( + ser, + r#"{"phrase":"foo","context":"home","irreversible":null,"whole_word":null,"expires_in":300}"# + ) + } +} diff --git a/src/requests/mod.rs b/src/requests/mod.rs new file mode 100644 index 0000000..375ebd1 --- /dev/null +++ b/src/requests/mod.rs @@ -0,0 +1,13 @@ +/// Data structure for the MastodonClient::add_filter method +pub use self::filter::AddFilterRequest; +/// Data structure for the MastodonClient::add_push_subscription method +pub use self::push::{AddPushRequest, Keys, UpdatePushRequest}; +/// Data structure for the MastodonClient::statuses method +pub use self::statuses::StatusesRequest; +/// Data structure for the MastodonClient::update_credentials method +pub use self::update_credentials::UpdateCredsRequest; + +mod filter; +mod push; +mod statuses; +mod update_credentials; diff --git a/src/requests/push.rs b/src/requests/push.rs new file mode 100644 index 0000000..c609b07 --- /dev/null +++ b/src/requests/push.rs @@ -0,0 +1,633 @@ +use entities::push::{add_subscription, update_data}; +use errors::Result; + +/// Container for the key & auth strings for an AddPushRequest +/// +/// # Example +/// +/// ``` +/// # extern crate elefren; +/// use elefren::requests::Keys; +/// +/// let keys = Keys::new("anetohias===", "oeatssah="); +/// ``` +#[derive(Debug, Default, Clone, PartialEq)] +pub struct Keys { + pub(crate) p256dh: String, + pub(crate) auth: String, +} + +impl Keys { + /// Create the `Keys` container + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::requests::Keys; + /// + /// let keys = Keys::new("anetohias===", "oeatssah="); + /// ``` + pub fn new(p256dh: &str, auth: &str) -> Keys { + Keys { + p256dh: p256dh.to_string(), + auth: auth.to_string(), + } + } +} + +/// Builder to pass to the Mastodon::add_push_subscription method +/// +/// # Example +/// +/// ```no_run +/// # extern crate elefren; +/// # use elefren::{MastodonClient, Mastodon, Data}; +/// # fn main() -> Result<(), elefren::Error> { +/// # let data = Data { +/// # base: "".into(), +/// # client_id: "".into(), +/// # client_secret: "".into(), +/// # redirect: "".into(), +/// # token: "".into(), +/// # }; +/// use elefren::requests::{AddPushRequest, Keys}; +/// +/// let client = Mastodon::from(data); +/// +/// let keys = Keys::new("stahesuahoei293ise===", "tasecoa,nmeozka=="); +/// let mut request = AddPushRequest::new("http://example.com/push/endpoint", &keys); +/// request.follow().reblog(); +/// +/// client.add_push_subscription(&request)?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Default, Clone, PartialEq)] +pub struct AddPushRequest { + endpoint: String, + + p256dh: String, + auth: String, + + follow: Option, + favourite: Option, + reblog: Option, + mention: Option, +} + +impl AddPushRequest { + /// Construct a new AddPushRequest + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::requests::{AddPushRequest, Keys}; + /// let keys = Keys::new("abcdef===", "foobar=="); + /// let push_endpoint = "https://example.com/push/endpoint"; + /// let request = AddPushRequest::new(push_endpoint, &keys); + /// ``` + pub fn new(endpoint: &str, keys: &Keys) -> AddPushRequest { + AddPushRequest { + endpoint: endpoint.to_string(), + p256dh: keys.p256dh.clone(), + auth: keys.auth.clone(), + ..Default::default() + } + } + + /// A flag that indicates if you want follow notifications pushed + /// + /// # Example + /// ``` + /// # extern crate elefren; + /// use elefren::requests::{AddPushRequest, Keys}; + /// let keys = Keys::new("abcdef===", "foobar=="); + /// let push_endpoint = "https://example.com/push/endpoint"; + /// let mut request = AddPushRequest::new(push_endpoint, &keys); + /// request.follow(); + /// ``` + pub fn follow(&mut self) -> &mut Self { + self.follow = Some(true); + self + } + + /// A flag that indicates if you want favourite notifications pushed + /// + /// # Example + /// ``` + /// # extern crate elefren; + /// use elefren::requests::{AddPushRequest, Keys}; + /// let keys = Keys::new("abcdef===", "foobar=="); + /// let push_endpoint = "https://example.com/push/endpoint"; + /// let mut request = AddPushRequest::new(push_endpoint, &keys); + /// request.favourite(); + /// ``` + pub fn favourite(&mut self) -> &mut Self { + self.favourite = Some(true); + self + } + + /// A flag that indicates if you want reblog notifications pushed + /// + /// # Example + /// ``` + /// # extern crate elefren; + /// use elefren::requests::{AddPushRequest, Keys}; + /// let keys = Keys::new("abcdef===", "foobar=="); + /// let push_endpoint = "https://example.com/push/endpoint"; + /// let mut request = AddPushRequest::new(push_endpoint, &keys); + /// request.reblog(); + /// ``` + pub fn reblog(&mut self) -> &mut Self { + self.reblog = Some(true); + self + } + + /// A flag that indicates if you want mention notifications pushed + /// + /// # Example + /// ``` + /// # extern crate elefren; + /// use elefren::requests::{AddPushRequest, Keys}; + /// let keys = Keys::new("abcdef===", "foobar=="); + /// let push_endpoint = "https://example.com/push/endpoint"; + /// let mut request = AddPushRequest::new(push_endpoint, &keys); + /// request.mention(); + /// ``` + pub fn mention(&mut self) -> &mut Self { + self.mention = Some(true); + self + } + + fn flags_present(&self) -> bool { + self.follow.is_some() + || self.favourite.is_some() + || self.reblog.is_some() + || self.mention.is_some() + } + + pub(crate) fn build(&self) -> Result { + use entities::push::{ + add_subscription::{Data, Form, Keys, Subscription}, + Alerts, + }; + let mut form = Form { + subscription: Subscription { + endpoint: self.endpoint.clone(), + keys: Keys { + p256dh: self.p256dh.clone(), + auth: self.auth.clone(), + }, + }, + data: None, + }; + if self.flags_present() { + let mut alerts = Alerts::default(); + + if let Some(follow) = self.follow { + alerts.follow = Some(follow); + } + + if let Some(favourite) = self.favourite { + alerts.favourite = Some(favourite); + } + + if let Some(reblog) = self.reblog { + alerts.reblog = Some(reblog); + } + + if let Some(mention) = self.mention { + alerts.mention = Some(mention); + } + + form.data = Some(Data { + alerts: Some(alerts), + }); + } + Ok(form) + } +} + +/// Builder to pass to the Mastodon::update_push_data method +/// +/// # Example +/// +/// ```no_run +/// # extern crate elefren; +/// # use elefren::{MastodonClient, Mastodon, Data}; +/// # fn main() -> Result<(), elefren::Error> { +/// # let data = Data { +/// # base: "".into(), +/// # client_id: "".into(), +/// # client_secret: "".into(), +/// # redirect: "".into(), +/// # token: "".into(), +/// # }; +/// use elefren::requests::UpdatePushRequest; +/// +/// let client = Mastodon::from(data); +/// +/// let mut request = UpdatePushRequest::new("foobar"); +/// request.follow(true).reblog(true); +/// +/// client.update_push_data(&request)?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Default, Clone, PartialEq, Serialize)] +pub struct UpdatePushRequest { + id: String, + follow: Option, + favourite: Option, + reblog: Option, + mention: Option, +} + +impl UpdatePushRequest { + /// Construct a new UpdatePushRequest + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::requests::UpdatePushRequest; + /// let request = UpdatePushRequest::new("some-id"); + /// ``` + pub fn new(id: &str) -> UpdatePushRequest { + UpdatePushRequest { + id: id.to_string(), + ..Default::default() + } + } + + /// A flag that indicates if you want follow notifications pushed + /// + /// # Example + /// ``` + /// # extern crate elefren; + /// use elefren::requests::UpdatePushRequest; + /// let mut request = UpdatePushRequest::new("foobar"); + /// request.follow(true); + /// ``` + pub fn follow(&mut self, follow: bool) -> &mut Self { + self.follow = Some(follow); + self + } + + /// A flag that indicates if you want favourite notifications pushed + /// + /// # Example + /// ``` + /// # extern crate elefren; + /// use elefren::requests::UpdatePushRequest; + /// let mut request = UpdatePushRequest::new("foobar"); + /// request.favourite(true); + /// ``` + pub fn favourite(&mut self, favourite: bool) -> &mut Self { + self.favourite = Some(favourite); + self + } + + /// A flag that indicates if you want reblog notifications pushed + /// + /// # Example + /// ``` + /// # extern crate elefren; + /// use elefren::requests::UpdatePushRequest; + /// let mut request = UpdatePushRequest::new("foobar"); + /// request.reblog(true); + /// ``` + pub fn reblog(&mut self, reblog: bool) -> &mut Self { + self.reblog = Some(reblog); + self + } + + /// A flag that indicates if you want mention notifications pushed + /// + /// # Example + /// ``` + /// # extern crate elefren; + /// use elefren::requests::UpdatePushRequest; + /// let mut request = UpdatePushRequest::new("foobar"); + /// request.mention(true); + /// ``` + pub fn mention(&mut self, mention: bool) -> &mut Self { + self.mention = Some(mention); + self + } + + fn flags_present(&self) -> bool { + self.follow.is_some() + || self.favourite.is_some() + || self.reblog.is_some() + || self.mention.is_some() + } + + pub(crate) fn build(&self) -> update_data::Form { + use entities::push::{ + update_data::{Data, Form}, + Alerts, + }; + + let mut form = Form { + id: self.id.clone(), + ..Default::default() + }; + + if self.flags_present() { + let mut alerts = Alerts::default(); + if let Some(follow) = self.follow { + alerts.follow = Some(follow); + } + if let Some(favourite) = self.favourite { + alerts.favourite = Some(favourite); + } + if let Some(reblog) = self.reblog { + alerts.reblog = Some(reblog); + } + if let Some(mention) = self.mention { + alerts.mention = Some(mention); + } + form.data = Data { + alerts: Some(alerts), + }; + } + form + } +} + +#[cfg(test)] +mod tests { + use super::*; + use entities::push::{add_subscription, update_data, Alerts}; + + #[test] + fn test_keys_new() { + let keys = Keys::new("anetohias===", "oeatssah="); + assert_eq!( + keys, + Keys { + p256dh: "anetohias===".to_string(), + auth: "oeatssah=".to_string() + } + ); + } + + #[test] + fn test_add_push_request_new() { + let endpoint = "https://example.com/push/endpoint"; + let keys = Keys::new("anetohias===", "oeatssah="); + let req = AddPushRequest::new(endpoint, &keys); + assert_eq!( + req, + AddPushRequest { + endpoint: "https://example.com/push/endpoint".to_string(), + p256dh: "anetohias===".to_string(), + auth: "oeatssah=".to_string(), + follow: None, + favourite: None, + reblog: None, + mention: None, + } + ); + } + #[test] + fn test_add_push_request_follow() { + let endpoint = "https://example.com/push/endpoint"; + let keys = Keys::new("anetohias===", "oeatssah="); + let mut req = AddPushRequest::new(endpoint, &keys); + req.follow(); + assert_eq!( + req, + AddPushRequest { + endpoint: "https://example.com/push/endpoint".to_string(), + p256dh: "anetohias===".to_string(), + auth: "oeatssah=".to_string(), + follow: Some(true), + favourite: None, + reblog: None, + mention: None, + } + ); + } + + #[test] + fn test_add_push_request_favourite() { + let endpoint = "https://example.com/push/endpoint"; + let keys = Keys::new("anetohias===", "oeatssah="); + let mut req = AddPushRequest::new(endpoint, &keys); + req.favourite(); + assert_eq!( + req, + AddPushRequest { + endpoint: "https://example.com/push/endpoint".to_string(), + p256dh: "anetohias===".to_string(), + auth: "oeatssah=".to_string(), + follow: None, + favourite: Some(true), + reblog: None, + mention: None, + } + ); + } + #[test] + fn test_add_push_request_reblog() { + let endpoint = "https://example.com/push/endpoint"; + let keys = Keys::new("anetohias===", "oeatssah="); + let mut req = AddPushRequest::new(endpoint, &keys); + req.reblog(); + assert_eq!( + req, + AddPushRequest { + endpoint: "https://example.com/push/endpoint".to_string(), + p256dh: "anetohias===".to_string(), + auth: "oeatssah=".to_string(), + follow: None, + favourite: None, + reblog: Some(true), + mention: None, + } + ); + } + #[test] + fn test_add_push_request_mention() { + let endpoint = "https://example.com/push/endpoint"; + let keys = Keys::new("anetohias===", "oeatssah="); + let mut req = AddPushRequest::new(endpoint, &keys); + req.mention(); + assert_eq!( + req, + AddPushRequest { + endpoint: "https://example.com/push/endpoint".to_string(), + p256dh: "anetohias===".to_string(), + auth: "oeatssah=".to_string(), + follow: None, + favourite: None, + reblog: None, + mention: Some(true), + } + ); + } + #[test] + fn test_add_push_request_build_no_flags() { + let endpoint = "https://example.com/push/endpoint"; + let keys = Keys::new("anetohias===", "oeatssah="); + let req = AddPushRequest::new(endpoint, &keys); + let form = req.build().expect("Couldn't build form"); + assert_eq!( + form, + add_subscription::Form { + subscription: add_subscription::Subscription { + endpoint: "https://example.com/push/endpoint".to_string(), + keys: add_subscription::Keys { + p256dh: "anetohias===".to_string(), + auth: "oeatssah=".to_string(), + }, + }, + data: None, + } + ); + } + + #[test] + fn test_add_push_request_build() { + let endpoint = "https://example.com/push/endpoint"; + let keys = Keys::new("anetohias===", "oeatssah="); + let mut req = AddPushRequest::new(endpoint, &keys); + req.follow().reblog(); + let form = req.build().expect("Couldn't build form"); + assert_eq!( + form, + add_subscription::Form { + subscription: add_subscription::Subscription { + endpoint: "https://example.com/push/endpoint".to_string(), + keys: add_subscription::Keys { + p256dh: "anetohias===".to_string(), + auth: "oeatssah=".to_string(), + }, + }, + data: Some(add_subscription::Data { + alerts: Some(Alerts { + follow: Some(true), + favourite: None, + reblog: Some(true), + mention: None, + }), + }), + } + ); + } + + #[test] + fn test_update_push_request_new() { + let req = UpdatePushRequest::new("some-id"); + assert_eq!( + req, + UpdatePushRequest { + id: "some-id".to_string(), + follow: None, + favourite: None, + reblog: None, + mention: None, + } + ); + } + + #[test] + fn test_update_push_request_follow() { + let mut req = UpdatePushRequest::new("some-id"); + req.follow(true); + assert_eq!( + req, + UpdatePushRequest { + id: "some-id".to_string(), + follow: Some(true), + favourite: None, + reblog: None, + mention: None, + } + ); + } + #[test] + fn test_update_push_request_favourite() { + let mut req = UpdatePushRequest::new("some-id"); + req.favourite(true); + assert_eq!( + req, + UpdatePushRequest { + id: "some-id".to_string(), + follow: None, + favourite: Some(true), + reblog: None, + mention: None, + } + ); + } + #[test] + fn test_update_push_request_reblog() { + let mut req = UpdatePushRequest::new("some-id"); + req.reblog(true); + assert_eq!( + req, + UpdatePushRequest { + id: "some-id".to_string(), + follow: None, + favourite: None, + reblog: Some(true), + mention: None, + } + ); + } + #[test] + fn test_update_push_request_mention() { + let mut req = UpdatePushRequest::new("some-id"); + req.mention(true); + assert_eq!( + req, + UpdatePushRequest { + id: "some-id".to_string(), + follow: None, + favourite: None, + reblog: None, + mention: Some(true), + } + ); + } + #[test] + fn test_update_push_request_build_no_flags() { + let req = UpdatePushRequest::new("some-id"); + let form = req.build(); + assert_eq!( + form, + update_data::Form { + id: "some-id".to_string(), + data: update_data::Data { + alerts: None, + }, + } + ); + } + + #[test] + fn test_update_push_request_build() { + let mut req = UpdatePushRequest::new("some-id"); + req.favourite(false); + let form = req.build(); + assert_eq!( + form, + update_data::Form { + id: "some-id".to_string(), + data: update_data::Data { + alerts: Some(Alerts { + follow: None, + favourite: Some(false), + reblog: None, + mention: None, + }), + }, + } + ); + } +} diff --git a/src/requests/statuses.rs b/src/requests/statuses.rs new file mode 100644 index 0000000..6e3da08 --- /dev/null +++ b/src/requests/statuses.rs @@ -0,0 +1,614 @@ +use errors::Error; +use serde_qs; +use std::{borrow::Cow, convert::Into}; + +mod bool_qs_serialize { + use serde::Serializer; + + pub fn is_false(b: &bool) -> bool { + !*b + } + + pub fn serialize(b: &bool, s: S) -> Result { + if *b { + s.serialize_i64(1) + } else { + s.serialize_i64(0) + } + } +} + +/// Builder for making a client.statuses() call +/// +/// # Example +/// +/// ``` +/// # extern crate elefren; +/// # use elefren::StatusesRequest; +/// let mut request = StatusesRequest::new(); +/// request.only_media().pinned().since_id("foo"); +/// # assert_eq!(&request.to_querystring().expect("Couldn't serialize qs")[..], "?only_media=1&pinned=1&since_id=foo"); +/// ``` +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct StatusesRequest<'a> { + #[serde(skip_serializing_if = "bool_qs_serialize::is_false")] + #[serde(serialize_with = "bool_qs_serialize::serialize")] + only_media: bool, + #[serde(skip_serializing_if = "bool_qs_serialize::is_false")] + #[serde(serialize_with = "bool_qs_serialize::serialize")] + exclude_replies: bool, + #[serde(skip_serializing_if = "bool_qs_serialize::is_false")] + #[serde(serialize_with = "bool_qs_serialize::serialize")] + pinned: bool, + #[serde(skip_serializing_if = "Option::is_none")] + max_id: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + since_id: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + limit: Option, + #[serde(skip_serializing_if = "Option::is_none")] + min_id: Option>, +} + +impl<'a> Into>> for &'a mut StatusesRequest<'a> { + fn into(self) -> Option> { + Some(StatusesRequest { + only_media: self.only_media, + exclude_replies: self.exclude_replies, + pinned: self.pinned, + max_id: self.max_id.clone(), + since_id: self.since_id.clone(), + limit: self.limit.clone(), + min_id: self.min_id.clone(), + }) + } +} + +impl<'a> StatusesRequest<'a> { + /// Construct a new `StatusesRequest` object + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// # use elefren::StatusesRequest; + /// let request = StatusesRequest::new(); + /// ``` + pub fn new() -> Self { + Self::default() + } + + /// Set the `?only_media=1` flag for the .statuses() request + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// # use elefren::StatusesRequest; + /// let mut request = StatusesRequest::new(); + /// assert_eq!(&request.only_media().to_querystring().expect("Couldn't serialize qs"), "?only_media=1"); + pub fn only_media(&mut self) -> &mut Self { + self.only_media = true; + self + } + + /// Set the `?exclude_replies=1` flag for the .statuses() request + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// # use elefren::StatusesRequest; + /// let mut request = StatusesRequest::new(); + /// assert_eq!( + /// &request + /// .exclude_replies() + /// .to_querystring() + /// .expect("Couldn't serialize qs"), + /// "?exclude_replies=1" + /// ); + /// ``` + pub fn exclude_replies(&mut self) -> &mut Self { + self.exclude_replies = true; + self + } + + /// Set the `?pinned=1` flag for the .statuses() request + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// # use elefren::StatusesRequest; + /// let mut request = StatusesRequest::new(); + /// assert_eq!( + /// &request + /// .pinned() + /// .to_querystring() + /// .expect("Couldn't serialize qs"), + /// "?pinned=1" + /// ); + /// ``` + pub fn pinned(&mut self) -> &mut Self { + self.pinned = true; + self + } + + /// Set the `?max_id=:max_id` flag for the .statuses() request + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// # use elefren::StatusesRequest; + /// let mut request = StatusesRequest::new(); + /// assert_eq!( + /// &request + /// .max_id("foo") + /// .to_querystring() + /// .expect("Couldn't serialize qs"), + /// "?max_id=foo" + /// ); + /// ``` + pub fn max_id>>(&mut self, max_id: S) -> &mut Self { + self.max_id = Some(max_id.into()); + self + } + + /// Set the `?since_id=:since_id` flag for the .statuses() request + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// # use elefren::StatusesRequest; + /// let mut request = StatusesRequest::new(); + /// assert_eq!( + /// &request + /// .since_id("foo") + /// .to_querystring() + /// .expect("Couldn't serialize qs"), + /// "?since_id=foo" + /// ); + /// ``` + pub fn since_id>>(&mut self, since_id: S) -> &mut Self { + self.since_id = Some(since_id.into()); + self + } + + /// Set the `?limit=:limit` flag for the .statuses() request + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// # use elefren::StatusesRequest; + /// let mut request = StatusesRequest::new(); + /// assert_eq!( + /// &request + /// .limit(10) + /// .to_querystring() + /// .expect("Couldn't serialize qs"), + /// "?limit=10" + /// ); + /// ``` + pub fn limit(&mut self, limit: usize) -> &mut Self { + self.limit = Some(limit); + self + } + + /// Set the `?min_id=:min_id` flag for the .statuses() request + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// # use elefren::StatusesRequest; + /// let mut request = StatusesRequest::new(); + /// assert_eq!( + /// &request + /// .min_id("foobar") + /// .to_querystring() + /// .expect("Couldn't serialize qs"), + /// "?min_id=foobar" + /// ); + /// ``` + pub fn min_id>>(&mut self, min_id: S) -> &mut Self { + self.min_id = Some(min_id.into()); + self + } + + /// Turns this builder into a querystring + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// # use elefren::StatusesRequest; + /// let mut request = StatusesRequest::new(); + /// assert_eq!( + /// &request + /// .limit(10) + /// .pinned() + /// .to_querystring() + /// .expect("Couldn't serialize qs"), + /// "?pinned=1&limit=10" + /// ); + /// ``` + pub fn to_querystring(&self) -> Result { + Ok(format!("?{}", serde_qs::to_string(&self)?)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_new() { + let request = StatusesRequest::new(); + assert_eq!( + request, + StatusesRequest { + only_media: false, + exclude_replies: false, + pinned: false, + max_id: None, + since_id: None, + limit: None, + min_id: None, + } + ); + } + + #[test] + fn test_only_media() { + let mut request = StatusesRequest::new(); + request.only_media(); + assert_eq!( + request, + StatusesRequest { + only_media: true, + exclude_replies: false, + pinned: false, + max_id: None, + since_id: None, + limit: None, + min_id: None, + } + ); + } + + #[test] + fn test_exclude_replies() { + let mut request = StatusesRequest::new(); + request.exclude_replies(); + assert_eq!( + request, + StatusesRequest { + only_media: false, + exclude_replies: true, + pinned: false, + max_id: None, + since_id: None, + limit: None, + min_id: None, + } + ); + } + #[test] + fn test_pinned() { + let mut request = StatusesRequest::new(); + request.pinned(); + assert_eq!( + request, + StatusesRequest { + only_media: false, + exclude_replies: false, + pinned: true, + max_id: None, + since_id: None, + limit: None, + min_id: None, + } + ); + } + #[test] + fn test_max_id() { + let mut request = StatusesRequest::new(); + request.max_id("foo"); + assert_eq!( + request, + StatusesRequest { + only_media: false, + exclude_replies: false, + pinned: false, + max_id: Some("foo".into()), + since_id: None, + limit: None, + min_id: None, + } + ); + } + #[test] + fn test_since_id() { + let mut request = StatusesRequest::new(); + request.since_id("foo"); + assert_eq!( + request, + StatusesRequest { + only_media: false, + exclude_replies: false, + pinned: false, + max_id: None, + since_id: Some("foo".into()), + limit: None, + min_id: None, + } + ); + } + #[test] + fn test_limit() { + let mut request = StatusesRequest::new(); + request.limit(42); + assert_eq!( + request, + StatusesRequest { + only_media: false, + exclude_replies: false, + pinned: false, + max_id: None, + since_id: None, + limit: Some(42), + min_id: None, + } + ); + } + #[test] + fn test_min_id() { + let mut request = StatusesRequest::new(); + request.min_id("foo"); + assert_eq!( + request, + StatusesRequest { + only_media: false, + exclude_replies: false, + pinned: false, + max_id: None, + since_id: None, + limit: None, + min_id: Some("foo".into()), + } + ); + } + #[test] + fn test_to_querystring() { + macro_rules! qs_test { + (|$r:ident| $b:block, $expected:expr) => { + { + let mut $r = StatusesRequest::new(); + $b + let qs = $r.to_querystring().expect("Failed to serialize querystring"); + assert_eq!(&qs, $expected); + } + } + } + + qs_test!( + |request| { + request.only_media(); + }, + "?only_media=1" + ); + qs_test!( + |request| { + request.exclude_replies(); + }, + "?exclude_replies=1" + ); + qs_test!( + |request| { + request.pinned(); + }, + "?pinned=1" + ); + qs_test!( + |request| { + request.max_id("foo"); + }, + "?max_id=foo" + ); + qs_test!( + |request| { + request.since_id("foo"); + }, + "?since_id=foo" + ); + qs_test!( + |request| { + request.limit(42); + }, + "?limit=42" + ); + qs_test!( + |request| { + request.only_media().exclude_replies(); + }, + "?only_media=1&exclude_replies=1" + ); + qs_test!( + |request| { + request.only_media().pinned(); + }, + "?only_media=1&pinned=1" + ); + qs_test!( + |request| { + request.only_media().max_id("foo"); + }, + "?only_media=1&max_id=foo" + ); + qs_test!( + |request| { + request.only_media().since_id("foo"); + }, + "?only_media=1&since_id=foo" + ); + qs_test!( + |request| { + request.only_media().limit(42); + }, + "?only_media=1&limit=42" + ); + qs_test!( + |request| { + request.exclude_replies().only_media(); + }, + "?only_media=1&exclude_replies=1" + ); + qs_test!( + |request| { + request.exclude_replies().pinned(); + }, + "?exclude_replies=1&pinned=1" + ); + qs_test!( + |request| { + request.exclude_replies().max_id("foo"); + }, + "?exclude_replies=1&max_id=foo" + ); + qs_test!( + |request| { + request.exclude_replies().since_id("foo"); + }, + "?exclude_replies=1&since_id=foo" + ); + qs_test!( + |request| { + request.exclude_replies().limit(42); + }, + "?exclude_replies=1&limit=42" + ); + qs_test!( + |request| { + request.pinned().only_media(); + }, + "?only_media=1&pinned=1" + ); + qs_test!( + |request| { + request.pinned().exclude_replies(); + }, + "?exclude_replies=1&pinned=1" + ); + qs_test!( + |request| { + request.pinned().max_id("foo"); + }, + "?pinned=1&max_id=foo" + ); + qs_test!( + |request| { + request.pinned().since_id("foo"); + }, + "?pinned=1&since_id=foo" + ); + qs_test!( + |request| { + request.pinned().limit(42); + }, + "?pinned=1&limit=42" + ); + qs_test!( + |request| { + request.max_id("foo").only_media(); + }, + "?only_media=1&max_id=foo" + ); + qs_test!( + |request| { + request.max_id("foo").exclude_replies(); + }, + "?exclude_replies=1&max_id=foo" + ); + qs_test!( + |request| { + request.max_id("foo").pinned(); + }, + "?pinned=1&max_id=foo" + ); + qs_test!( + |request| { + request.max_id("foo").since_id("foo"); + }, + "?max_id=foo&since_id=foo" + ); + qs_test!( + |request| { + request.max_id("foo").limit(42); + }, + "?max_id=foo&limit=42" + ); + qs_test!( + |request| { + request.since_id("foo").only_media(); + }, + "?only_media=1&since_id=foo" + ); + qs_test!( + |request| { + request.since_id("foo").exclude_replies(); + }, + "?exclude_replies=1&since_id=foo" + ); + qs_test!( + |request| { + request.since_id("foo").pinned(); + }, + "?pinned=1&since_id=foo" + ); + qs_test!( + |request| { + request.since_id("foo").max_id("foo"); + }, + "?max_id=foo&since_id=foo" + ); + qs_test!( + |request| { + request.since_id("foo").limit(42); + }, + "?since_id=foo&limit=42" + ); + qs_test!( + |request| { + request.limit(42).only_media(); + }, + "?only_media=1&limit=42" + ); + qs_test!( + |request| { + request.limit(42).exclude_replies(); + }, + "?exclude_replies=1&limit=42" + ); + qs_test!( + |request| { + request.limit(42).pinned(); + }, + "?pinned=1&limit=42" + ); + qs_test!( + |request| { + request.limit(42).max_id("foo"); + }, + "?max_id=foo&limit=42" + ); + qs_test!( + |request| { + request.limit(42).since_id("foo"); + }, + "?since_id=foo&limit=42" + ); + } +} diff --git a/src/requests/update_credentials.rs b/src/requests/update_credentials.rs new file mode 100644 index 0000000..7784cc3 --- /dev/null +++ b/src/requests/update_credentials.rs @@ -0,0 +1,327 @@ +use std::{ + fmt::Display, + path::{Path, PathBuf}, +}; + +use entities::account::{Credentials, MetadataField, UpdateSource}; +use errors::Result; +use status_builder; + +/// Builder to pass to the Mastodon::update_credentials method +/// +/// # Example +/// +/// ```no_run +/// # extern crate elefren; +/// # use elefren::Data; +/// # fn main() -> Result<(), elefren::Error> { +/// # let data = Data { +/// # base: "".into(), +/// # client_id: "".into(), +/// # client_secret: "".into(), +/// # redirect: "".into(), +/// # token: "".into(), +/// # }; +/// use elefren::{prelude::*, status_builder::Visibility, UpdateCredsRequest}; +/// +/// let client = Mastodon::from(data); +/// let mut builder = UpdateCredsRequest::new(); +/// +/// builder.privacy(Visibility::Unlisted); +/// +/// let result = client.update_credentials(&mut builder)?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Default, Clone, PartialEq)] +pub struct UpdateCredsRequest { + display_name: Option, + note: Option, + avatar: Option, + header: Option, + field_attributes: Vec, + + // UpdateSource fields + privacy: Option, + sensitive: Option, +} + +impl UpdateCredsRequest { + /// Create a new UpdateCredsRequest + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::UpdateCredsRequest; + /// + /// let mut builder = UpdateCredsRequest::new(); + /// ``` + pub fn new() -> UpdateCredsRequest { + Default::default() + } + + /// Set the new display_name value + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::UpdateCredsRequest; + /// + /// let mut builder = UpdateCredsRequest::new(); + /// + /// builder.display_name("my new display name"); + /// ``` + pub fn display_name(&mut self, name: D) -> &mut Self { + self.display_name = Some(name.to_string()); + self + } + + /// Set the new note value + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::UpdateCredsRequest; + /// + /// let mut builder = UpdateCredsRequest::new(); + /// + /// builder.note("my new note"); + /// ``` + pub fn note(&mut self, note: D) -> &mut Self { + self.note = Some(note.to_string()); + self + } + + /// Set the new avatar value + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::UpdateCredsRequest; + /// + /// let mut builder = UpdateCredsRequest::new(); + /// + /// builder.avatar("/path/to/my/new/avatar"); + /// ``` + pub fn avatar>(&mut self, path: P) -> &mut Self { + let path = path.as_ref(); + let path = path.to_path_buf(); + self.avatar = Some(path); + self + } + + /// Set the new header value + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::UpdateCredsRequest; + /// + /// let mut builder = UpdateCredsRequest::new(); + /// + /// builder.header("/path/to/my/new/header"); + /// ``` + pub fn header>(&mut self, path: P) -> &mut Self { + let path = path.as_ref(); + let path = path.to_path_buf(); + self.header = Some(path); + self + } + + /// Set the new privacy value + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::{status_builder::Visibility, UpdateCredsRequest}; + /// + /// let mut builder = UpdateCredsRequest::new(); + /// + /// builder.privacy(Visibility::Public); + /// ``` + pub fn privacy(&mut self, privacy: status_builder::Visibility) -> &mut Self { + self.privacy = Some(privacy); + self + } + + /// Set the new sensitive value + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::UpdateCredsRequest; + /// + /// let mut builder = UpdateCredsRequest::new(); + /// + /// builder.sensitive(true); + /// ``` + pub fn sensitive(&mut self, sensitive: bool) -> &mut Self { + self.sensitive = Some(sensitive); + self + } + + /// Add a metadata field + /// + /// # Example + /// + /// ``` + /// # extern crate elefren; + /// use elefren::UpdateCredsRequest; + /// + /// let mut builder = UpdateCredsRequest::new(); + /// + /// builder.field_attribute("some key", "some value"); + /// ``` + pub fn field_attribute(&mut self, name: &str, value: &str) -> &mut Self { + self.field_attributes.push(MetadataField::new(name, value)); + self + } + + pub(crate) fn build(&mut self) -> Result { + Ok(Credentials { + display_name: self.display_name.clone(), + note: self.note.clone(), + avatar: self.avatar.clone(), + header: self.avatar.clone(), + source: Some(UpdateSource { + privacy: self.privacy.clone(), + sensitive: self.sensitive.clone(), + }), + fields_attributes: self.field_attributes.clone(), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use entities::account::{Credentials, MetadataField, UpdateSource}; + use status_builder::Visibility; + + #[test] + fn test_update_creds_request_new() { + let builder = UpdateCredsRequest::new(); + assert_eq!( + builder, + UpdateCredsRequest { + ..Default::default() + } + ); + } + + #[test] + fn test_update_creds_request_display_name() { + let mut builder = UpdateCredsRequest::new(); + builder.display_name("foo"); + assert_eq!( + builder, + UpdateCredsRequest { + display_name: Some("foo".into()), + ..Default::default() + } + ); + } + + #[test] + fn test_update_creds_request_note() { + let mut builder = UpdateCredsRequest::new(); + builder.note("foo"); + assert_eq!( + builder, + UpdateCredsRequest { + note: Some("foo".into()), + ..Default::default() + } + ); + } + + #[test] + fn test_update_creds_request_avatar() { + let mut builder = UpdateCredsRequest::new(); + builder.avatar("/path/to/avatar.png"); + assert_eq!( + builder, + UpdateCredsRequest { + avatar: Some(Path::new("/path/to/avatar.png").to_path_buf()), + ..Default::default() + } + ); + } + + #[test] + fn test_update_creds_request_header() { + let mut builder = UpdateCredsRequest::new(); + builder.header("/path/to/header.png"); + assert_eq!( + builder, + UpdateCredsRequest { + header: Some(Path::new("/path/to/header.png").to_path_buf()), + ..Default::default() + } + ); + } + + #[test] + fn test_update_creds_request_privacy() { + let mut builder = UpdateCredsRequest::new(); + builder.privacy(Visibility::Public); + assert_eq!( + builder, + UpdateCredsRequest { + privacy: Some(Visibility::Public), + ..Default::default() + } + ); + } + + #[test] + fn test_update_creds_request_sensitive() { + let mut builder = UpdateCredsRequest::new(); + builder.sensitive(true); + assert_eq!( + builder, + UpdateCredsRequest { + sensitive: Some(true), + ..Default::default() + } + ); + } + + #[test] + fn test_update_creds_request_field_attribute() { + let mut builder = UpdateCredsRequest::new(); + builder.field_attribute("foo", "bar"); + assert_eq!( + builder, + UpdateCredsRequest { + field_attributes: vec![MetadataField::new("foo", "bar")], + ..Default::default() + } + ); + } + + #[test] + fn test_update_creds_request_build() { + let mut builder = UpdateCredsRequest::new(); + builder.display_name("test").note("a note"); + let creds = builder.build().expect("Couldn't build Credentials"); + assert_eq!( + creds, + Credentials { + display_name: Some("test".into()), + note: Some("a note".into()), + source: Some(UpdateSource { + ..Default::default() + }), + ..Default::default() + } + ); + } +} diff --git a/src/scopes.rs b/src/scopes.rs new file mode 100644 index 0000000..2cab0d2 --- /dev/null +++ b/src/scopes.rs @@ -0,0 +1,818 @@ +use std::{ + cmp::{Ordering, PartialEq, PartialOrd}, + collections::HashSet, + fmt, + ops::BitOr, + str::FromStr, +}; + +use serde::ser::{Serialize, Serializer}; + +use errors::Error; +use serde::{Deserialize, Deserializer}; +use serde::de::{self, Visitor}; + +/// Represents a set of OAuth scopes +/// +/// # Example +/// +/// ```rust +/// use elefren::prelude::*; +/// +/// let read = Scopes::read_all(); +/// let write = Scopes::write_all(); +/// let follow = Scopes::follow(); +/// let all = read | write | follow; +/// ``` +#[derive(Clone)] +pub struct Scopes { + scopes: HashSet, +} + +impl FromStr for Scopes { + type Err = Error; + + fn from_str(s: &str) -> Result { + let mut set = HashSet::new(); + for scope in s.split_whitespace() { + let scope = Scope::from_str(&scope)?; + set.insert(scope); + } + Ok(Scopes { + scopes: set, + }) + } +} + +impl Serialize for Scopes { + fn serialize(&self, serializer: S) -> ::std::result::Result + where + S: Serializer, + { + let repr = format!("{}", self); + serializer.serialize_str(&repr) + } +} + +struct DeserializeScopesVisitor; + +impl<'de> Visitor<'de> for DeserializeScopesVisitor { + type Value = Scopes; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + write!(formatter, "space separated scopes") + } + + fn visit_str(self, v: &str) -> Result + where E: de::Error + { + Scopes::from_str(v).map_err(de::Error::custom) + } +} + +impl<'de> Deserialize<'de> for Scopes { + fn deserialize(deserializer: D) -> Result>::Error> where + D: Deserializer<'de> { + deserializer.deserialize_str(DeserializeScopesVisitor) + } +} + +impl Scopes { + /// Represents all available oauth scopes: "read write follow push" + /// + /// ``` + /// # extern crate elefren; + /// # use std::error::Error; + /// use elefren::scopes::Scopes; + /// + /// # fn main() -> Result<(), Box> { + /// let scope = Scopes::all(); + /// assert_eq!(&format!("{}", scope), "read write follow push"); + /// # Ok(()) + /// # } + /// ``` + pub fn all() -> Scopes { + Scopes::read_all() | Scopes::write_all() | Scopes::follow() | Scopes::push() + } + + /// Represents the full "read" scope + /// + /// ``` + /// # extern crate elefren; + /// # use std::error::Error; + /// use elefren::scopes::Scopes; + /// + /// # fn main() -> Result<(), Box> { + /// let scope = Scopes::read_all(); + /// assert_eq!(&format!("{}", scope), "read"); + /// # Ok(()) + /// # } + /// ``` + pub fn read_all() -> Scopes { + Scopes::_read(None) + } + + /// Represents a specific "read:___" scope + /// + /// ``` + /// # extern crate elefren; + /// # use std::error::Error; + /// use elefren::scopes::{Read, Scopes}; + /// + /// # fn main() -> Result<(), Box> { + /// let scope = Scopes::read(Read::Accounts); + /// assert_eq!(&format!("{}", scope), "read:accounts"); + /// # Ok(()) + /// # } + /// ``` + pub fn read(subscope: Read) -> Scopes { + Scopes::_read(Some(subscope)) + } + + /// Represents the full "write" scope + /// + /// ``` + /// # extern crate elefren; + /// # use std::error::Error; + /// use elefren::scopes::Scopes; + /// + /// # fn main() -> Result<(), Box> { + /// let scope = Scopes::write_all(); + /// assert_eq!(&format!("{}", scope), "write"); + /// # Ok(()) + /// # } + /// ``` + pub fn write_all() -> Scopes { + Scopes::_write(None) + } + + /// Represents a specific "write:___" scope + /// + /// ``` + /// # extern crate elefren; + /// # use std::error::Error; + /// use elefren::scopes::{Scopes, Write}; + /// + /// # fn main() -> Result<(), Box> { + /// let scope = Scopes::write(Write::Accounts); + /// assert_eq!(&format!("{}", scope), "write:accounts"); + /// # Ok(()) + /// # } + /// ``` + pub fn write(subscope: Write) -> Scopes { + Scopes::_write(Some(subscope)) + } + + /// Represents the "follow" scope + /// + /// ``` + /// # extern crate elefren; + /// # use std::error::Error; + /// use elefren::scopes::Scopes; + /// + /// # fn main() -> Result<(), Box> { + /// let scope = Scopes::follow(); + /// assert_eq!(&format!("{}", scope), "follow"); + /// # Ok(()) + /// # } + /// ``` + pub fn follow() -> Scopes { + Scopes::new(Scope::Follow) + } + + /// Represents the full "push" scope + /// + /// ``` + /// # extern crate elefren; + /// # use std::error::Error; + /// use elefren::scopes::Scopes; + /// + /// # fn main() -> Result<(), Box> { + /// let scope = Scopes::push(); + /// assert_eq!(&format!("{}", scope), "push"); + /// # Ok(()) + /// # } + /// ``` + pub fn push() -> Scopes { + Scopes::new(Scope::Push) + } + + /// Combines 2 scopes together + /// + /// # Example + /// + /// ```rust + /// use elefren::prelude::*; + /// + /// let read = Scopes::read_all(); + /// let write = Scopes::write_all(); + /// let read_write = read.and(write); + /// ``` + pub fn and(self, other: Scopes) -> Scopes { + let newset: HashSet<_> = self + .scopes + .union(&other.scopes) + .into_iter() + .map(|s| *s) + .collect(); + Scopes { + scopes: newset, + } + } + + fn _write(subscope: Option) -> Scopes { + Scopes::new(Scope::Write(subscope)) + } + + fn _read(subscope: Option) -> Scopes { + Scopes::new(Scope::Read(subscope)) + } + + fn new(scope: Scope) -> Scopes { + let mut set = HashSet::new(); + set.insert(scope); + Scopes { + scopes: set, + } + } +} + +impl BitOr for Scopes { + type Output = Scopes; + + fn bitor(self, other: Scopes) -> Self::Output { + self.and(other) + } +} + +impl PartialEq for Scopes { + fn eq(&self, other: &Scopes) -> bool { + self.scopes + .symmetric_difference(&other.scopes) + .next() + .is_none() + } +} + +impl Default for Scopes { + fn default() -> Scopes { + Scopes::read_all() + } +} + +impl fmt::Debug for Scopes { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "[")?; + for scope in &self.scopes { + write!(f, "{:?}", &scope)?; + } + Ok(write!(f, "]")?) + } +} + +impl fmt::Display for Scopes { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut start = true; + let scopes = { + let mut scopes = self.scopes.iter().collect::>(); + scopes.sort(); + scopes + }; + for scope in &scopes { + if !start { + write!(f, " ")?; + } else { + start = false; + } + write!(f, "{}", &scope)?; + } + Ok(()) + } +} + +/// Permission scope of the application. +/// [Details on what each permission provides][1] +/// [1]: https://github.com/tootsuite/documentation/blob/master/Using-the-API/OAuth-details.md) +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Hash, Serialize)] +enum Scope { + /// Read only permissions. + #[serde(rename = "read")] + Read(Option), + /// Write only permissions. + #[serde(rename = "write")] + Write(Option), + /// Only permission to add and remove followers. + #[serde(rename = "follow")] + Follow, + /// Push permissions + #[serde(rename = "push")] + Push, +} + +impl FromStr for Scope { + type Err = Error; + + fn from_str(s: &str) -> Result { + Ok(match s { + "read" => Scope::Read(None), + "write" => Scope::Write(None), + "follow" => Scope::Follow, + "push" => Scope::Push, + read if read.starts_with("read:") => { + let r: Read = Read::from_str(&read[5..])?; + Scope::Read(Some(r)) + }, + write if write.starts_with("write:") => { + let w: Write = Write::from_str(&write[6..])?; + Scope::Write(Some(w)) + }, + _ => return Err(Error::Other("Unknown scope".to_string())), + }) + } +} + +impl Ord for Scope { + fn cmp(&self, other: &Scope) -> Ordering { + match (*self, *other) { + (Scope::Read(None), Scope::Read(None)) => Ordering::Equal, + (Scope::Read(None), Scope::Read(Some(..))) => Ordering::Less, + (Scope::Read(Some(..)), Scope::Read(None)) => Ordering::Greater, + (Scope::Read(Some(ref a)), Scope::Read(Some(ref b))) => a.cmp(b), + + (Scope::Write(None), Scope::Write(None)) => Ordering::Equal, + (Scope::Write(None), Scope::Write(Some(..))) => Ordering::Less, + (Scope::Write(Some(..)), Scope::Write(None)) => Ordering::Greater, + (Scope::Write(Some(ref a)), Scope::Write(Some(ref b))) => a.cmp(b), + + (Scope::Read(..), Scope::Write(..)) => Ordering::Less, + (Scope::Read(..), Scope::Follow) => Ordering::Less, + (Scope::Read(..), Scope::Push) => Ordering::Less, + + (Scope::Write(..), Scope::Read(..)) => Ordering::Greater, + (Scope::Write(..), Scope::Follow) => Ordering::Less, + (Scope::Write(..), Scope::Push) => Ordering::Less, + + (Scope::Follow, Scope::Read(..)) => Ordering::Greater, + (Scope::Follow, Scope::Write(..)) => Ordering::Greater, + (Scope::Follow, Scope::Follow) => Ordering::Equal, + (Scope::Follow, Scope::Push) => Ordering::Less, + + (Scope::Push, Scope::Push) => Ordering::Equal, + (Scope::Push, _) => Ordering::Greater, + } + } +} + +impl fmt::Display for Scope { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Scope::*; + let s = match *self { + Read(Some(ref r)) => return fmt::Display::fmt(r, f), + Read(None) => "read", + Write(Some(ref w)) => return fmt::Display::fmt(w, f), + Write(None) => "write", + Follow => "follow", + Push => "push", + }; + write!(f, "{}", s) + } +} + +impl Default for Scope { + fn default() -> Self { + Scope::Read(None) + } +} + +/// Represents the granular "read:___" oauth scopes +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)] +pub enum Read { + /// Accounts + #[serde(rename = "accounts")] + Accounts, + /// Blocks + #[serde(rename = "blocks")] + Blocks, + /// Favourites + #[serde(rename = "favourites")] + Favourites, + /// Filters + #[serde(rename = "filters")] + Filters, + /// Follows + #[serde(rename = "follows")] + Follows, + /// Lists + #[serde(rename = "lists")] + Lists, + /// Mutes + #[serde(rename = "mutes")] + Mutes, + /// Notifications + #[serde(rename = "notifications")] + Notifications, + /// Reports + #[serde(rename = "reports")] + Reports, + /// Search + #[serde(rename = "search")] + Search, + /// Statuses + #[serde(rename = "statuses")] + Statuses, +} + +impl FromStr for Read { + type Err = Error; + + fn from_str(s: &str) -> Result { + Ok(match s { + "accounts" => Read::Accounts, + "blocks" => Read::Blocks, + "favourites" => Read::Favourites, + "filters" => Read::Filters, + "follows" => Read::Follows, + "lists" => Read::Lists, + "mutes" => Read::Mutes, + "notifications" => Read::Notifications, + "reports" => Read::Reports, + "search" => Read::Search, + "statuses" => Read::Statuses, + _ => return Err(Error::Other("Unknown 'read' subcategory".to_string())), + }) + } +} + +impl PartialOrd for Read { + fn partial_cmp(&self, other: &Read) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Read { + fn cmp(&self, other: &Read) -> Ordering { + let a = format!("{:?}", self); + let b = format!("{:?}", other); + a.cmp(&b) + } +} + +impl fmt::Display for Read { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "read:{}", + match *self { + Read::Accounts => "accounts", + Read::Blocks => "blocks", + Read::Favourites => "favourites", + Read::Filters => "filters", + Read::Follows => "follows", + Read::Lists => "lists", + Read::Mutes => "mutes", + Read::Notifications => "notifications", + Read::Reports => "reports", + Read::Search => "search", + Read::Statuses => "statuses", + } + ) + } +} + +/// Represents the granular "write:___" oauth scopes +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)] +pub enum Write { + /// Accounts + #[serde(rename = "accounts")] + Accounts, + /// Blocks + #[serde(rename = "blocks")] + Blocks, + /// Favourites + #[serde(rename = "favourites")] + Favourites, + /// Filters + #[serde(rename = "filters")] + Filters, + /// Follows + #[serde(rename = "follows")] + Follows, + /// Lists + #[serde(rename = "lists")] + Lists, + /// Media + #[serde(rename = "media")] + Media, + /// Mutes + #[serde(rename = "mutes")] + Mutes, + /// Notifications + #[serde(rename = "notifications")] + Notifications, + /// Reports + #[serde(rename = "reports")] + Reports, + /// Statuses + #[serde(rename = "statuses")] + Statuses, +} + +impl FromStr for Write { + type Err = Error; + + fn from_str(s: &str) -> Result { + Ok(match s { + "accounts" => Write::Accounts, + "blocks" => Write::Blocks, + "favourites" => Write::Favourites, + "filters" => Write::Filters, + "follows" => Write::Follows, + "lists" => Write::Lists, + "media" => Write::Media, + "mutes" => Write::Mutes, + "notifications" => Write::Notifications, + "reports" => Write::Reports, + "statuses" => Write::Statuses, + _ => return Err(Error::Other("Unknown 'write' subcategory".to_string())), + }) + } +} + +impl PartialOrd for Write { + fn partial_cmp(&self, other: &Write) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Write { + fn cmp(&self, other: &Write) -> Ordering { + let a = format!("{:?}", self); + let b = format!("{:?}", other); + a.cmp(&b) + } +} + +impl fmt::Display for Write { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "write:{}", + match *self { + Write::Accounts => "accounts", + Write::Blocks => "blocks", + Write::Favourites => "favourites", + Write::Filters => "filters", + Write::Follows => "follows", + Write::Lists => "lists", + Write::Media => "media", + Write::Mutes => "mutes", + Write::Notifications => "notifications", + Write::Reports => "reports", + Write::Statuses => "statuses", + } + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json; + + #[test] + fn test_write_cmp() { + let tests = [ + (Write::Accounts, Write::Blocks), + (Write::Blocks, Write::Favourites), + (Write::Favourites, Write::Filters), + (Write::Filters, Write::Follows), + (Write::Follows, Write::Lists), + (Write::Lists, Write::Media), + (Write::Media, Write::Mutes), + (Write::Mutes, Write::Notifications), + (Write::Notifications, Write::Reports), + (Write::Reports, Write::Statuses), + ]; + + for (a, b) in &tests { + assert!(a < b); + assert!(b > a); + } + } + + #[test] + fn test_read_cmp() { + let tests = [ + (Read::Accounts, Read::Blocks), + (Read::Blocks, Read::Favourites), + (Read::Favourites, Read::Filters), + (Read::Filters, Read::Follows), + (Read::Follows, Read::Lists), + (Read::Lists, Read::Mutes), + (Read::Mutes, Read::Notifications), + (Read::Notifications, Read::Reports), + (Read::Reports, Read::Search), + (Read::Search, Read::Statuses), + ]; + for (a, b) in &tests { + assert!(a < b); + assert!(b > a); + } + } + + #[test] + fn test_scope_cmp() { + let tests = [ + (Scope::Read(None), Scope::Read(Some(Read::Accounts))), + (Scope::Read(None), Scope::Read(Some(Read::Blocks))), + (Scope::Read(None), Scope::Read(Some(Read::Favourites))), + (Scope::Read(None), Scope::Read(Some(Read::Filters))), + (Scope::Read(None), Scope::Read(Some(Read::Follows))), + (Scope::Read(None), Scope::Read(Some(Read::Lists))), + (Scope::Read(None), Scope::Read(Some(Read::Mutes))), + (Scope::Read(None), Scope::Read(Some(Read::Notifications))), + (Scope::Read(None), Scope::Read(Some(Read::Reports))), + (Scope::Read(None), Scope::Read(Some(Read::Search))), + (Scope::Read(None), Scope::Read(Some(Read::Statuses))), + (Scope::Read(Some(Read::Statuses)), Scope::Write(None)), + (Scope::Read(Some(Read::Mutes)), Scope::Follow), + (Scope::Read(None), Scope::Push), + (Scope::Write(None), Scope::Write(Some(Write::Accounts))), + (Scope::Write(None), Scope::Write(Some(Write::Blocks))), + (Scope::Write(None), Scope::Write(Some(Write::Favourites))), + (Scope::Write(None), Scope::Write(Some(Write::Filters))), + (Scope::Write(None), Scope::Write(Some(Write::Follows))), + (Scope::Write(None), Scope::Write(Some(Write::Lists))), + (Scope::Write(None), Scope::Write(Some(Write::Media))), + (Scope::Write(None), Scope::Write(Some(Write::Mutes))), + (Scope::Write(None), Scope::Write(Some(Write::Notifications))), + (Scope::Write(None), Scope::Write(Some(Write::Reports))), + (Scope::Write(None), Scope::Write(Some(Write::Statuses))), + (Scope::Write(Some(Write::Statuses)), Scope::Follow), + (Scope::Write(Some(Write::Follows)), Scope::Push), + ]; + + for (a, b) in &tests { + assert!(a < b); + } + } + + #[test] + fn test_scope_display() { + let values = [ + Scope::Read(None), + Scope::Read(Some(Read::Accounts)), + Scope::Read(Some(Read::Blocks)), + Scope::Read(Some(Read::Favourites)), + Scope::Read(Some(Read::Filters)), + Scope::Read(Some(Read::Follows)), + Scope::Read(Some(Read::Lists)), + Scope::Read(Some(Read::Mutes)), + Scope::Read(Some(Read::Notifications)), + Scope::Read(Some(Read::Reports)), + Scope::Read(Some(Read::Search)), + Scope::Read(Some(Read::Statuses)), + Scope::Write(None), + Scope::Write(Some(Write::Accounts)), + Scope::Write(Some(Write::Blocks)), + Scope::Write(Some(Write::Favourites)), + Scope::Write(Some(Write::Filters)), + Scope::Write(Some(Write::Follows)), + Scope::Write(Some(Write::Lists)), + Scope::Write(Some(Write::Media)), + Scope::Write(Some(Write::Mutes)), + Scope::Write(Some(Write::Notifications)), + Scope::Write(Some(Write::Reports)), + Scope::Write(Some(Write::Statuses)), + Scope::Follow, + Scope::Push, + ]; + + let expecteds = [ + "read".to_string(), + "read:accounts".to_string(), + "read:blocks".to_string(), + "read:favourites".to_string(), + "read:filters".to_string(), + "read:follows".to_string(), + "read:lists".to_string(), + "read:mutes".to_string(), + "read:notifications".to_string(), + "read:reports".to_string(), + "read:search".to_string(), + "read:statuses".to_string(), + "write".to_string(), + "write:accounts".to_string(), + "write:blocks".to_string(), + "write:favourites".to_string(), + "write:filters".to_string(), + "write:follows".to_string(), + "write:lists".to_string(), + "write:media".to_string(), + "write:mutes".to_string(), + "write:notifications".to_string(), + "write:reports".to_string(), + "write:statuses".to_string(), + "follow".to_string(), + "push".to_string(), + ]; + + let tests = values.iter().zip(expecteds.iter()); + + for (value, expected) in tests { + let result = value.to_string(); + assert_eq!(&result, expected); + } + } + + #[test] + fn test_scopes_default() { + let default: Scope = Default::default(); + assert_eq!(default, Scope::Read(None)); + } + + #[test] + fn test_scopes_display() { + let tests = [ + ( + Scopes::read(Read::Accounts) | Scopes::follow(), + "read:accounts follow", + ), + ( + Scopes::read(Read::Follows) | Scopes::read(Read::Accounts) | Scopes::write_all(), + "read:accounts read:follows write", + ), + ]; + + for (a, b) in &tests { + assert_eq!(&format!("{}", a), b); + } + } + + #[test] + fn test_scopes_serialize_deserialize() { + let tests = [ + ( + Scopes::read_all() | Scopes::write(Write::Notifications) | Scopes::follow(), + "read write:notifications follow", + ), + (Scopes::follow() | Scopes::push(), "follow push"), + ]; + + for (a, b) in &tests { + let ser = serde_json::to_string(&a).expect("Couldn't serialize Scopes"); + let expected = format!("\"{}\"", b); + assert_eq!(&ser, &expected); + + let des : Scopes = serde_json::from_str(&ser).expect("Couldn't deserialize Scopes"); + assert_eq!(&des, a); + } + } + + #[test] + fn test_scope_from_str() { + let tests = [ + ("read", Scope::Read(None)), + ("read:accounts", Scope::Read(Some(Read::Accounts))), + ("read:blocks", Scope::Read(Some(Read::Blocks))), + ("read:favourites", Scope::Read(Some(Read::Favourites))), + ("read:filters", Scope::Read(Some(Read::Filters))), + ("read:follows", Scope::Read(Some(Read::Follows))), + ("read:lists", Scope::Read(Some(Read::Lists))), + ("read:mutes", Scope::Read(Some(Read::Mutes))), + ("read:notifications", Scope::Read(Some(Read::Notifications))), + ("read:reports", Scope::Read(Some(Read::Reports))), + ("read:search", Scope::Read(Some(Read::Search))), + ("read:statuses", Scope::Read(Some(Read::Statuses))), + ("write", Scope::Write(None)), + ("write:accounts", Scope::Write(Some(Write::Accounts))), + ("write:blocks", Scope::Write(Some(Write::Blocks))), + ("write:favourites", Scope::Write(Some(Write::Favourites))), + ("write:filters", Scope::Write(Some(Write::Filters))), + ("write:follows", Scope::Write(Some(Write::Follows))), + ("write:lists", Scope::Write(Some(Write::Lists))), + ("write:media", Scope::Write(Some(Write::Media))), + ("write:mutes", Scope::Write(Some(Write::Mutes))), + ( + "write:notifications", + Scope::Write(Some(Write::Notifications)), + ), + ("write:reports", Scope::Write(Some(Write::Reports))), + ("write:statuses", Scope::Write(Some(Write::Statuses))), + ("follow", Scope::Follow), + ("push", Scope::Push), + ]; + for (source, expected) in &tests { + let result = Scope::from_str(source).expect(&format!("Couldn't parse '{}'", &source)); + assert_eq!(result, *expected); + } + } + + #[test] + fn test_scopes_str_round_trip() { + let original = "read write follow push"; + let scopes = Scopes::from_str(original).expect("Couldn't convert to Scopes"); + let result = format!("{}", scopes); + assert_eq!(original, result); + } +} diff --git a/src/status_builder.rs b/src/status_builder.rs new file mode 100644 index 0000000..15a24eb --- /dev/null +++ b/src/status_builder.rs @@ -0,0 +1,366 @@ +use isolang::Language; + +/// A builder pattern struct for constructing a status. +/// +/// # Example +/// +/// ``` +/// # extern crate elefren; +/// # use elefren::{Language, StatusBuilder}; +/// +/// # fn main() -> Result<(), elefren::Error> { +/// let status = StatusBuilder::new() +/// .status("a status") +/// .sensitive(true) +/// .spoiler_text("a CW") +/// .language(Language::Eng) +/// .build()?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Default, Clone, PartialEq)] +pub struct StatusBuilder { + status: Option, + in_reply_to_id: Option, + media_ids: Option>, + sensitive: Option, + spoiler_text: Option, + content_type: Option, + visibility: Option, + language: Option, +} + +impl StatusBuilder { + /// Create a StatusBuilder object + /// + /// # Example + /// + /// ```rust,no_run + /// # use elefren::prelude::*; + /// # use elefren::status_builder::Visibility; + /// # fn main() -> Result<(), elefren::Error> { + /// # let data = Data { + /// # base: "".into(), + /// # client_id: "".into(), + /// # client_secret: "".into(), + /// # redirect: "".into(), + /// # token: "".into(), + /// # }; + /// # let client = Mastodon::from(data); + /// let status = StatusBuilder::new() + /// .status("a status") + /// .visibility(Visibility::Public) + /// .build()?; + /// client.new_status(status)?; + /// # Ok(()) + /// # } + /// ``` + pub fn new() -> StatusBuilder { + StatusBuilder::default() + } + + /// Set the text for the post + /// + /// # Example + /// + /// ```rust + /// # use elefren::prelude::*; + /// # fn main() -> Result<(), elefren::Error> { + /// let status = StatusBuilder::new().status("awoooooo").build()?; + /// # Ok(()) + /// # } + /// ``` + pub fn status>(&mut self, status: I) -> &mut Self { + self.status = Some(status.into()); + self + } + + /// Set the in_reply_to_id for the post + /// + /// # Example + /// + /// ```rust + /// # use elefren::prelude::*; + /// # fn main() -> Result<(), elefren::Error> { + /// let status = StatusBuilder::new() + /// .status("awooooo") + /// .in_reply_to("12345") + /// .build()?; + /// # Ok(()) + /// # } + /// ``` + pub fn in_reply_to>(&mut self, id: I) -> &mut Self { + self.in_reply_to_id = Some(id.into()); + self + } + + /// Set the media_ids for the post + /// + /// # Example + /// + /// ```rust + /// # use elefren::prelude::*; + /// # fn main() -> Result<(), elefren::Error> { + /// let status = StatusBuilder::new().media_ids(&["foo", "bar"]).build()?; + /// # Ok(()) + /// # } + /// ``` + pub fn media_ids>( + &mut self, + ids: I, + ) -> &mut Self { + self.media_ids = Some(ids.into_iter().map(|s| s.to_string()).collect::>()); + self + } + + /// Set the sensitive attribute for the post + /// + /// # Example + /// + /// ```rust + /// # use elefren::prelude::*; + /// # fn main() -> Result<(), elefren::Error> { + /// let status = StatusBuilder::new() + /// .media_ids(&["foo", "bar"]) + /// .sensitive(true) + /// .build()?; + /// # Ok(()) + /// # } + /// ``` + pub fn sensitive(&mut self, sensitive: bool) -> &mut Self { + self.sensitive = Some(sensitive); + self + } + + /// Set the spoiler text/CW for the post + /// + /// # Example + /// + /// ```rust + /// # use elefren::prelude::*; + /// # fn main() -> Result<(), elefren::Error> { + /// let status = StatusBuilder::new() + /// .status("awoooo!!") + /// .spoiler_text("awoo inside") + /// .build()?; + /// # Ok(()) + /// # } + /// ``` + pub fn spoiler_text>(&mut self, spoiler_text: I) -> &mut Self { + self.spoiler_text = Some(spoiler_text.into()); + self + } + + /// Set the content type of the post + /// + /// This is a Pleroma and Glitch-soc extension of the API. + /// + /// # Possible values + /// - `text/plain` + /// - `text/html` + /// - `text/markdown` + /// - `text/bbcode` (Pleroma only) + /// + /// The set of supported content types may vary by server. + /// + /// # Example + /// + /// ```rust + /// # use elefren::prelude::*; + /// # fn main() -> Result<(), elefren::Error> { + /// let status = StatusBuilder::new() + /// .status("thicc") + /// .content_type("text/html") + /// .build()?; + /// # Ok(()) + /// # } + /// ``` + pub fn content_type>(&mut self, content_type: I) -> &mut Self { + self.content_type = Some(content_type.into()); + self + } + + /// Set the visibility for the post + /// + /// # Example + /// + /// ```rust + /// # use elefren::prelude::*; + /// # use elefren::status_builder::Visibility; + /// # fn main() -> Result<(), elefren::Error> { + /// let status = StatusBuilder::new() + /// .status("awooooooo") + /// .visibility(Visibility::Public) + /// .build()?; + /// # Ok(()) + /// # } + /// ``` + pub fn visibility(&mut self, visibility: Visibility) -> &mut Self { + self.visibility = Some(visibility); + self + } + + /// Set the language for the post + /// + /// # Example + /// + /// ```rust + /// # use elefren::prelude::*; + /// # use elefren::Language; + /// # fn main() -> Result<(), elefren::Error> { + /// let status = StatusBuilder::new() + /// .status("awoo!!!!") + /// .language(Language::Eng) + /// .build()?; + /// # Ok(()) + /// # } + /// ``` + pub fn language(&mut self, language: Language) -> &mut Self { + self.language = Some(language); + self + } + + /// Constructs a NewStatus + /// + /// # Example + /// + /// ```rust + /// # use elefren::prelude::*; + /// # fn main() -> Result<(), elefren::Error> { + /// let status = StatusBuilder::new().status("awoo!").build()?; + /// # Ok(()) + /// # } + /// ``` + pub fn build(&self) -> Result { + if self.status.is_none() && self.media_ids.is_none() { + return Err(crate::Error::Other( + "status text or media ids are required in order to post a status".to_string(), + )); + } + Ok(NewStatus { + status: self.status.clone(), + in_reply_to_id: self.in_reply_to_id.clone(), + media_ids: self.media_ids.clone(), + sensitive: self.sensitive.clone(), + spoiler_text: self.spoiler_text.clone(), + visibility: self.visibility.clone(), + language: self.language.clone(), + content_type: self.content_type.clone(), + }) + } +} + +/// Represents a post that can be sent to the POST /api/v1/status endpoint +#[derive(Debug, Default, Clone, Serialize, PartialEq)] +pub struct NewStatus { + #[serde(skip_serializing_if = "Option::is_none")] + status: Option, + #[serde(skip_serializing_if = "Option::is_none")] + in_reply_to_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + media_ids: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + sensitive: Option, + #[serde(skip_serializing_if = "Option::is_none")] + spoiler_text: Option, + #[serde(skip_serializing_if = "Option::is_none")] + visibility: Option, + #[serde(skip_serializing_if = "Option::is_none")] + language: Option, + #[serde(skip_serializing_if = "Option::is_none")] + content_type: Option, +} + +/// The visibility of a status. +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum Visibility { + /// A Direct message to a user + Direct, + /// Only available to followers + Private, + /// Not shown in public timelines + Unlisted, + /// Posted to public timelines + Public, +} + +impl Default for Visibility { + fn default() -> Self { + Visibility::Public + } +} + +#[cfg(test)] +mod tests { + use super::*; + use isolang::Language; + use serde_json; + + #[test] + fn test_new() { + let s = StatusBuilder::new() + .status("a status") + .build() + .expect("Couldn't build status"); + let expected = NewStatus { + status: Some("a status".to_string()), + in_reply_to_id: None, + media_ids: None, + sensitive: None, + spoiler_text: None, + visibility: None, + language: None, + content_type: None, + }; + assert_eq!(s, expected); + } + + #[test] + fn test_default_visibility() { + let v: Visibility = Default::default(); + assert_eq!(v, Visibility::Public); + } + + #[test] + fn test_serialize_visibility() { + assert_eq!( + serde_json::to_string(&Visibility::Direct).expect("couldn't serialize visibility"), + "\"direct\"".to_string() + ); + assert_eq!( + serde_json::to_string(&Visibility::Private).expect("couldn't serialize visibility"), + "\"private\"".to_string() + ); + assert_eq!( + serde_json::to_string(&Visibility::Unlisted).expect("couldn't serialize visibility"), + "\"unlisted\"".to_string() + ); + assert_eq!( + serde_json::to_string(&Visibility::Public).expect("couldn't serialize visibility"), + "\"public\"".to_string() + ); + } + + #[test] + fn test_serialize_status() { + let status = StatusBuilder::new() + .status("a status") + .build() + .expect("Couldn't build status"); + assert_eq!( + serde_json::to_string(&status).expect("Couldn't serialize status"), + "{\"status\":\"a status\"}".to_string() + ); + + let status = StatusBuilder::new() + .status("a status") + .language(Language::Eng) + .build() + .expect("Couldn't build status"); + assert_eq!( + serde_json::to_string(&status).expect("Couldn't serialize status"), + "{\"status\":\"a status\",\"language\":\"eng\"}" + ); + } +} diff --git a/tests/skeptic.rs b/tests/skeptic.rs new file mode 100644 index 0000000..ff46c9c --- /dev/null +++ b/tests/skeptic.rs @@ -0,0 +1 @@ +include!(concat!(env!("OUT_DIR"), "/skeptic-tests.rs"));