branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>KosmosKosmos/october-simplenavigation<file_sep>/classes/filesystem.php <?php namespace Zollerboy\Navigation\Classes; /** * Filesystem helper class */ class Filesystem { /** * Create a new File at the given path with the given content. * @param string $filePath The path, where the file will be saved. * @param array $fileContent The content of the file, split in lines. Default = [] * @return void */ public function createFile(string $filePath, array $fileContent = []) { $file = fopen($filePath, "w"); fwrite($file, implode($fileContent)); fclose($file); } /** * Rename a file at the given path with the given new path and edit the content with the replaceRegex. * @param string $filePath The path, where the file was stored. * @param string $newFilePath The path, where the file will be stored. * @param array $replaceRegex An array, where key and value are both regex strings. All matches of the key will be replaced with the value. * @return void */ public function updateFile(string $filePath, string $newFilePath, array $replaceRegex = []) { rename($filePath, $newFilePath); $fileContent = preg_replace(array_keys($replaceRegex), $replaceRegex, file($newFilePath)); $file = fopen($newFilePath, "w"); fwrite($file, implode($fileContent)); fclose($file); } /** * Deletes a file at the given path. * @param string $filePath The path where the file was stored. * @return void */ public function deleteFile(string $filePath) { unlink($filePath); } } <file_sep>/updates/create_table_items.php <?php namespace Zollerboy\Navigation\Updates; use Schema; use October\Rain\Database\Updates\Migration; /** * create_table_items.php */ class CreateTableItems extends Migration { public function up() { Schema::create('zollerboy_navigation_items', function ($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->integer('parent_id')->nullable(); $table->integer('order'); $table->string('title'); $table->string('description')->nullable(); $table->integer('access')->default(1); $table->timestamps(); }); } public function down() { Schema::drop('zollerboy_navigation_items'); } } ?> <file_sep>/models/NavigationItem.php <?php namespace Zollerboy\Navigation\Models; use Model; use Cms\Classes\Page; use Cms\Classes\Theme; use Zollerboy\Navigation\Classes\Filesystem; /** * NavigationItem Model */ class NavigationItem extends Model { /** * @var string The database table used by the model. */ public $table = 'zollerboy_navigation_items'; /** * @var array Guarded fields */ protected $guarded = ['*']; /** * @var array Fillable fields */ protected $fillable = []; /** * @var array Relations */ public $hasOne = []; public $hasMany = [ "sub_items" => ['Zollerboy\Navigation\Models\NavigationItem', "key" => "parent_id"] ]; public $belongsTo = [ "parent" => "Zollerboy\Navigation\Models\NavigationItem" ]; public $belongsToMany = []; public $morphTo = []; public $morphOne = []; public $morphMany = []; public $attachOne = []; public $attachMany = []; public $appends = ["newpage"]; public function getNewPageAttribute() { return 0; } public function afterFetch() { $this->link_change = $this->link; } public function beforeCreate() { $this->order = NavigationItem::where('parent_id', $this->parent_id)->orderBy('order', 'DESC')->pluck('order')->first() + 1; if ($this->link_new !== null) { $this->link = $this->link_new; unset($this->link_new); $currentTheme = Theme::getEditTheme(); $currentThemeDirectory = $currentTheme->getDirName(); $pageFilename = "page" . str_replace("/", "-", $this->link) . ".htm"; $contentFilename = "content" . str_replace("/", "-", $this->link) . ".htm"; $pageFilePath = themes_path() . "/" . $currentThemeDirectory . "/pages/" . $pageFilename; $contentFilePath = themes_path() . "/" . $currentThemeDirectory . "/content/" . $contentFilename; $pageFileContents = [ "title = \"" . $this->title . "\"\n", "url = \"" . $this->link . "\"\n", "layout = \"default\"\n", "is_hidden = 0\n", "\n", "[contenteditor]\n", "==\n", "{% component 'contenteditor' file=\"" . $contentFilename . "\" %}\n" ]; Filesystem::createFile($pageFilename, $pageFileContents); Filesystem::createFile($contentFilePath); } unset($this->new_page); } public function beforeUpdate() { $currentTheme = Theme::getEditTheme(); $currentThemeDirectory = $currentTheme->getDirName(); $pageFilename = "page" . str_replace("/", "-", $this->link) . ".htm"; $contentFilename = "content" . str_replace("/", "-", $this->link) . ".htm"; $pageFilePath = themes_path() . "/" . $currentThemeDirectory . "/pages/" . $pageFilename; $contentFilePath = themes_path() . "/" . $currentThemeDirectory . "/content/" . $contentFilename; $newPageFilename = "page" . str_replace("/", "-", $this->link_change) . ".htm"; $newContentFilename = "content" . str_replace("/", "-", $this->link_change) . ".htm"; $newPageFilePath = themes_path() . "/" . $currentThemeDirectory . "/pages/" . $newPageFilename; $newContentFilePath = themes_path() . "/" . $currentThemeDirectory . "/content/" . $newContentFilename; $newPageReplaceRegex = [ "/title = \"[\w \-]+\"/" => "title = \"" . $this->title . "\"", "/url = \"[a-z\.\-\/]+\"/" => "url = \"" . $this->link_change . "\"", "/\{% component 'contenteditor' file=\"[a-z\.\-]+\" %\}/" => "/\{% component 'contenteditor' file=\"" . $newContentFilename . "\" %\}/" ]; Filesystem::updateFile($pageFilePath, $newPageFilePath, $newPageReplaceRegex); Filesystem::updateFile($contentFilePath, $newContentFilePath); $this->link = $this->link_change; unset($this->link_change); } public function beforeDelete() { var_dump(post()); } public function getLinks($fieldName, $value, $formData) { $links = array(); $currentTheme = Theme::getEditTheme(); $pages = Page::listInTheme($currentTheme, true); foreach ($pages as $page) { $links[$page->url] = $page->url . " (" . $page->title . ")"; } return $links; } } <file_sep>/controllers/NavigationItems.php <?php namespace Zollerboy\Navigation\Controllers; use BackendMenu; use Backend\Classes\Controller; /** * Navigation Items Back-end Controller */ class NavigationItems extends Controller { public $implement = [ 'Backend.Behaviors.FormController', 'Backend.Behaviors.ListController' ]; public $formConfig = 'config_form.yaml'; public $listConfig = 'config_list.yaml'; public function __construct() { parent::__construct(); BackendMenu::setContext('Zollerboy.Navigation', 'navigation', 'navigationitems'); $this->addCss('/plugins/zollerboy/navigation/assets/css/jquery-ui.min.css'); $this->addJs('/plugins/zollerboy/navigation/assets/javascript/jquery-ui.min.js'); } } <file_sep>/updates/update_table_items.php <?php namespace Zollerboy\Navigation\Updates; use Schema; use October\Rain\Database\Updates\Migration; /** * update_table_items.php */ class UpdateTableItems extends Migration { public function up() { Schema::table('zollerboy_navigation_items', function ($table) { $table->string('link'); }); } public function down() { Schema::table('zollerboy_navigation_items', function ($table) { $table->dropColumn('link'); }); } } ?>
fe93b448ae58737de3396c253e31b3fc4c19c576
[ "PHP" ]
5
PHP
KosmosKosmos/october-simplenavigation
ed433b1fcb468e8c932edc37afdd8ceb4b609443
f2e1d0dc940f5118183c3a9c693d938369ac8539
refs/heads/master
<file_sep>#!/usr/bin/python # -*- coding: utf-8 -*- """ ====================================================== Qustions ====================================================== """ import re def question_two(): """ reference to inner array duplicated 3 times """ # [[][][]] x = [[]]*3 #[[a],[a],[a]] x[0].append('a') #[[a, b],[a, b],[a, b]] x[1].append('b') #[[a, b, c],[a, b, c],[a, b, c]] x[2].append('c') #[[d],[a, b, c],[a, b, c]] x[0] = ['d'] def email_checker(email): """ Email Valdation """ if not type(email) == str: return False splited_mail = email.split('@') if not len(splited_mail) == 2: return False name, domen = splited_mail len_name = len(name) len_domen = len(domen) if not ( 256 >= len_domen >= 3): return False if not ( 128 >= len_name > 0): return False domen_rule = ur'^([a-z0-9_][a-z0-9-_]*)\.([a-z0-9_][a-z0-9-_]*)$' matched = re.match(domen_rule, domen) if not matched: return False domen_second, domen_first = matched.groups() end_checker = lambda x_str: x_str.endswith('-') checked_with_dash = map(end_checker, [domen_first, domen_second]) if any(checked_with_dash): return False good_name_symbols = '[a-z0-9"!,:\-_]' name_dots_rule = ur'^%s*\.\.%s*$'%(good_name_symbols, good_name_symbols) matched = re.match(name_dots_rule, name) if matched: return False splited_name = name.split('\"') if len(splited_name) % 2 == 0: return False rule = ur'^%s*$'%good_name_symbols for quoted in splited_name[1::2]: matched = re.match(rule, quoted) if matched: continue else: return False rule = ur'^[a-z0-9".\-_]*$' for unquoted in splited_name[::2]: matched = re.match(rule, unquoted) if matched: continue else: return False return True<file_sep>#!/usr/bin/python # -*- coding: utf-8 -*- """ ====================================================== Tests ====================================================== """ import unittest import string lower_words_digits = string.lowercase + string.digits from tasks import * class TestMail(unittest.TestCase): def test_email_name_length(self): good_mail = 'n'*128 + '@domen.ru' self.assertTrue( email_checker(good_mail), msg='check: %s'%good_mail) bad_mail = 'n'*129 + '@domen.ru' self.assertFalse( email_checker(bad_mail), msg='check: %s'%bad_mail) def test_email_domen_length(self): good_mail = [ 'name@a.' + 'm'*254, 'name@' + 'm'*254 + '.a' ] bad_mail = [ 'name@a.' + 'm'*255, 'name@' + 'm'*255 + '.a' ] for mail in good_mail: self.assertTrue( email_checker(mail), msg='check: %s'%mail) for mail in bad_mail: self.assertFalse( email_checker(mail), msg='check: %s'%mail) def test_dots_in_mail_name(self): good_mail = '<EMAIL>' self.assertTrue( email_checker(good_mail), msg='check: %s'%good_mail) bad_mail = '<EMAIL>' self.assertFalse( email_checker(bad_mail), msg='check: %s'%bad_mail) def test_quotes_in_mail_name(self): good_mail = 'first"and"<EMAIL>' self.assertTrue( email_checker(good_mail), msg='check: %s'%good_mail) bad_mail = 'n"am"e"<EMAIL>' self.assertFalse( email_checker(bad_mail), msg='check: %s'%bad_mail) def test_emaeil_checker(self): bad_strings_domen = [ '@domen.ru', 'namedomen.ru', 'name@tw', 'name@a.' + 'b'*255, '<EMAIL>-' '<EMAIL>-' '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>-', ] bas_strings_name = [ 'n'*129 + '@a.' + 'm'*254, '<EMAIL>', '@domen.ru', 'name"<EMAIL>', 'na!me""<EMAIL>', 'na"me""<EMAIL>', # '<EMAIL>', # '<EMAIL>', ] good_string_name = [ lower_words_digits + '@domen.ru', 'aaaaa"qqqqqq"aaaaa' + '@domen.ru', 'aa"ab"ad"!!,:fd"aaaaa' + '@domen.ru', ] for good_mail in good_string_name: self.assertTrue( email_checker(good_mail), msg='check: %s'%good_mail ) for bad_mail in bad_strings_domen + bas_strings_name: self.assertFalse( email_checker(bad_mail), msg='check: %s'%bad_mail ) if __name__ == "__main__": unittest.main()<file_sep>EntryTasks ==========
b0ce80029500b2691d5915c19d02dab9885d6ce6
[ "Markdown", "Python" ]
3
Python
maxim-popkov/EntryTasks
9b316434909eb4be5fdd3dffddf376e7207dd1a6
473616799d4f735ba01620574512c844a5171344
refs/heads/main
<repo_name>eyjohn/scratch-binary-compat<file_sep>/windll/CMakeLists.txt cmake_minimum_required(VERSION 3.10) project(windll VERSION 1.0.0 DESCRIPTION "Windows dynamic loading test libraries and applications.") set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) add_library(liba SHARED liba.c) set_target_properties(liba PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION 1 PUBLIC_HEADER "liba.h") add_library(libb SHARED libb.c) set_target_properties(libb PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION 1 PUBLIC_HEADER "libb.h") target_link_libraries(libb liba) add_library(libc SHARED libc.c) set_target_properties(libc PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION 1 PUBLIC_HEADER "libc.h") target_link_libraries(libc liba) add_executable(app app.c) if (UNIX) target_link_libraries(app dl) endif (UNIX) <file_sep>/src/clib/clib.h #include <stdbool.h> typedef void (*STRING_CALLBACK)(const char *); typedef void (*INT_CALLBACK)(int); void set_callbacks(STRING_CALLBACK cb1, INT_CALLBACK cb2); bool are_callbacks_set(); void call_string_callback(const char *value); void call_int_callback(int value); <file_sep>/windll/libb.c #include <stdio.h> #include "liba.h" #include "libb.h" void libbDoStuff() { printf("LibB Counter Value: %d\n", incrementAndGetCounter()); }<file_sep>/src/alib.c #include "alib.h" int hello_world() { return 6; }<file_sep>/src/atest.c #include <dlfcn.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char* line = NULL; size_t len = 0; ssize_t nread; int (*hello_world)(); for (;;) { puts("library path:"); if (getline(&line, &len, stdin) == -1) break; line[strlen(line) - 1] = '\0'; void* handle = dlopen(line, RTLD_NOW); if (handle) { printf("woop\n"); *(void**)(&hello_world) = dlsym(handle, "hello_world"); if (hello_world) { printf("hello_world %d\n", hello_world()); } else { puts(dlerror()); } dlclose(handle); } else { puts(dlerror()); } } }<file_sep>/windll/liba.h int incrementAndGetCounter();<file_sep>/src/alib.h int hello_world();<file_sep>/windll/app.c #include <string.h> #ifdef __linux__ #include <dlfcn.h> typedef void* Handle; Handle open_lib(const char* filename) { char basename[100] = ""; strcat(strcat(strcat(basename, "./lib"), filename), ".so"); return dlopen(basename, RTLD_NOW); } void* open_symbol(Handle handle, const char* symbol) { return dlsym(handle, symbol); } #define CALLBACK #elif _WIN32 #include <windows.h> typedef HINSTANCE Handle; Handle open_lib(const char* filename) { char basename[100] = ""; strcat(strcat(basename, filename), ".dll"); return LoadLibrary(basename); } void* open_symbol(Handle handle, const char* symbol) { return GetProcAddress(handle, symbol); } #endif typedef void(CALLBACK* DoStuff)(); int main() { Handle libbInst = open_lib("libb"); // puts(dlerror()); DoStuff libbDoStuff = (DoStuff)open_symbol(libbInst, "libbDoStuff"); // puts(dlerror()); Handle libcInst = open_lib("libc"); DoStuff libcDoStuff = (DoStuff)open_symbol(libcInst, "libcDoStuff"); libbDoStuff(); libcDoStuff(); libbDoStuff(); libcDoStuff(); return 0; }<file_sep>/windll/libc.h void libcDoStuff();<file_sep>/src/clib/clib.c #include "clib.h" #include <stddef.h> static bool callbacks_set = false; static STRING_CALLBACK string_callback = NULL; static INT_CALLBACK int_callback = NULL; void set_callbacks(STRING_CALLBACK cb1, INT_CALLBACK cb2) { string_callback = cb1; int_callback = cb2; callbacks_set = true; } bool are_callbacks_set() { return callbacks_set; } void call_string_callback(const char *val) { string_callback(val); } void call_int_callback(int val) { int_callback(val); } <file_sep>/windll/liba.c #include "liba.h" static int counter = 0; int incrementAndGetCounter() { return ++counter; }<file_sep>/src/cpplib/cpplib.h #include <memory> #include <string> extern "C" { #include <clib.h> } namespace cpplib { class Handler { public: virtual ~Handler() = default; virtual void handle_string(std::string_view) = 0; virtual void handle_int(int) = 0; static void register_global_handler(std::shared_ptr<Handler> handler); static std::shared_ptr<Handler> global_handler(); }; namespace detail { class GlobalHandler : public Handler { public: void handle_string(std::string_view) override; void handle_int(int) override; }; namespace { std::shared_ptr<Handler> global_handler_singleton; std::shared_ptr<Handler> custom_handler_singleton; inline void string_callback(const char* val) { custom_handler_singleton->handle_string(val); } inline void int_callback(int val) { custom_handler_singleton->handle_int(val); } } // namespace } // namespace detail inline void Handler::register_global_handler(std::shared_ptr<Handler> handler) { detail::global_handler_singleton = std::make_shared<detail::GlobalHandler>(); detail::custom_handler_singleton = handler; set_callbacks(detail::string_callback, detail::int_callback); } inline std::shared_ptr<Handler> Handler::global_handler() { return detail::global_handler_singleton; } inline void detail::GlobalHandler::handle_string(std::string_view value) { call_string_callback(value.data()); } inline void detail::GlobalHandler::handle_int(int value) { call_int_callback(value); } } // namespace cpplib<file_sep>/src/cpplib/cpplib.cpp #include "cpplib.h" namespace cpplib {} // namespace cpplib<file_sep>/windll/README.md # WINDLL Windows dynamic loading test libraries and applications. ## Output ```text ./app.exe LibB Counter Value: 1 LibC Counter Value: 2 LibB Counter Value: 3 LibC Counter Value: 4 ```<file_sep>/windll/libc.c #include <stdio.h> #include "liba.h" #include "libc.h" void libcDoStuff() { printf("LibC Counter Value: %d\n", incrementAndGetCounter()); }<file_sep>/src/capp.c #include <clib.h> #include <stdio.h> void handle_string(const char* value) { printf("Got String: %s\n", value); } void handle_int(int value) { printf("Got String: %d\n", value); } int main() { set_callbacks(handle_string, handle_int); call_string_callback("hello"); call_int_callback(5); return 0; }<file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.10) project(scratch-binary-compat VERSION 1.0.0 DESCRIPTION "Applications for testing binary compatibility of compiled modules.") include(GNUInstallDirs) set(CMAKE_CXX_STANDARD 17) add_library(clib SHARED src/clib/clib.c) set_target_properties(clib PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION 1 PUBLIC_HEADER "src/clib/clib.h") # add_library(cpplib SHARED src/cpplib/cpplib.cpp) add_library(cpplib INTERFACE) target_include_directories(cpplib INTERFACE src/clib) target_link_libraries(cpplib INTERFACE clib) # set_target_properties(cpplib PROPERTIES # # VERSION ${PROJECT_VERSION} # # SOVERSION 1 # PUBLIC_HEADER "src/cpplib/cpplib.h") add_executable(capp src/capp.c) target_link_libraries(capp clib) target_include_directories(capp PUBLIC src/clib) add_executable(cppapp src/cppapp.cpp) target_link_libraries(cppapp clib) target_include_directories(cppapp PUBLIC src/cpplib src/clib) install(TARGETS clib cpplib capp cppapp LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) <file_sep>/windll/libb.h void libbDoStuff();<file_sep>/src/cppapp.cpp #include <cpplib.h> #include <iostream> #include <memory> namespace { class AppHandler : public cpplib::Handler { void handle_string(std::string_view value) override { std::cout << "AppHandler: string - " << value << std::endl; } void handle_int(int value) override { std::cout << "AppHandler: int - " << value << std::endl; } }; } // namespace int main() { std::shared_ptr<cpplib::Handler> handler = std::make_shared<AppHandler>(); cpplib::Handler::register_global_handler(handler); cpplib::Handler::global_handler()->handle_string("hello"); cpplib::Handler::global_handler()->handle_int(5); }
0f35d3e1fa4407dd70a41d8453a27420db6635c1
[ "Markdown", "C", "CMake", "C++" ]
19
CMake
eyjohn/scratch-binary-compat
5867819a287a219229c7294d1b443d781b7ade45
439dadebbbc9250ef92236404a1ba0dbdfa23889
refs/heads/main
<file_sep>#Loading the required Packages install.packages("caTools") library("caTools") library(readxl) #Setting the working directory setwd("D:/GRIP") #Importing the Data studentsData <- read_xlsx("StudentGradesandScores.xlsx") #Check if data is imported correct View(studentsData) str(studentsData) head(studentsData) tail(studentsData) #Split the data into Training and Testing split = sample.split(studentsData$Hours,SplitRatio = 0.7) trainingSet <- subset(studentsData, split == TRUE) View(trainingSet) testSet <- subset(studentsData, split == FALSE) View(testSet) #Fitting linear regression to the training set l_model <- lm(Scores ~ Hours, trainingSet) summary(l_model) coef(l_model) plot(studentsData$Hours,studentsData$Scores) testSet$yPred <- predict(l_model,testSet) View(testSet) newStudent = data.frame(Hours = 9.25) PredictedValue <- predict(l_model,newStudent) PredictedValue #Equation : 2.927549 + (9.6328) * x #Score expected for a student who studies for 9.25hrs/day 2.927549 + (9.6328) * 9.25 92.03
0df25b038ac0a1e8afe980e4365e47795ec056cc
[ "R" ]
1
R
suneethag/SparksFoundation-DSTask1-StudentScore
9d8f69edba2fa681f9e56fa0a0414856a920b45d
a76e29d2211b7bc0ed16f5f9904f9338ca75e965
refs/heads/master
<file_sep>import React from 'react'; import styled from 'styled-components'; const Container = styled.div``; const Label = styled.label` font-size: var(--small-size); color: var(--snow-color); margin: 0; `; const Input = styled.input` font-family: 'Roboto'; font-weight: bold; font-size: var(--xlarge-size); width: 100%; background: transparent; color: var(--nobel-color); padding: .3rem 0; border: none; border-bottom: 1px var(--nobel-color) solid; transition: all .1s linear; &:focus { outline: none; border-bottom-color: var(--snow-color); } `; const SearchInput = ({ label, placeholder, value, onChange }) => ( <Container> <Label>{label}</Label> <Input placeholder={placeholder} value={value} onChange={event => onChange(event.target.value)} /> </Container> ); export default SearchInput; <file_sep>const ACCESS_TOKEN = '<KEY>'; const API_URL = 'https://api.spotify.com/v1'; export default { fetchAlbums: query => fetch(`${API_URL}/search?q=${query}&type=album&limit=5`, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: `Bearer ${ACCESS_TOKEN}` }, }).then(res => res.json()) }; <file_sep>import { createStore, combineReducers, applyMiddleware, compose } from 'redux'; import createSagaMiddleware from 'redux-saga'; import { all, fork } from 'redux-saga/effects'; import { authReducer, authSaga } from 'store/auth'; import { albumsReducer, albumsSaga } from 'store/albums'; const sagaMiddleware = createSagaMiddleware(); const reducers = combineReducers({ auth: authReducer, albums: albumsReducer }); function* sagas() { yield all([fork(authSaga), fork(albumsSaga)]); } const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore(reducers, composeEnhancers(applyMiddleware(sagaMiddleware))); sagaMiddleware.run(sagas); export default store; <file_sep>import React from 'react'; import styled from 'styled-components'; import Image from 'components/Image'; const Container = styled.div` display: flex; background: var(--nero-color); @media (max-width: 576px) { flex-direction: column; } `; const LeftSide = styled.div` color: #FFF; padding: 1rem 3rem 0 1rem; `; const RightSide = styled.div` flex: 1; padding: 4rem 8rem 8rem 1rem; @media (max-width: 576px) { padding: 0; } `; const Theme = ({ children }) => ( <Container> <LeftSide> <Image name="logo" size="50px" /> </LeftSide> <RightSide> {children} </RightSide> </Container> ); export default Theme; <file_sep>import styled from 'styled-components'; export const Figure = styled.figure` width: ${props => props.size}; `; export const Img = styled.img` width: 100%; height: 100%; object-fit: cover; `; <file_sep>import React from 'react'; import styled from 'styled-components'; import Card from 'components/Card'; const Container = styled.div``; const Content = styled.div` display: grid; grid-template-columns: repeat(5, 1fr); grid-gap: 3rem; `; const Title = styled.h2` font-size: var(--large-size); font-weight: normal; color: white; margin: 5rem 0 2rem; `; const ListCards = ({ search, data }) => ( <Container> <Title>{`Resultados encontrados para "${search}"`}</Title> <Content> {data.map(item => <Card data={item} />)} </Content> </Container> ); export default ListCards; <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Types as albumsTypes } from 'store/albums'; import Theme from 'containers/Theme'; import SearchInput from './components/SearchInput'; import ListCards from './components/ListCards'; class MainScreen extends Component { constructor() { super(); this.state = { search: '' }; } onSearch = search => { const { fetchAlbum } = this.props; this.setState({ search }, () => fetchAlbum(search)); } componentDidMount() { const { search } = this.props.match.params; if (search) { this.onSearch(search.split('-').join(' ')); } } render() { const { search } = this.state; const { albums } = this.props; return ( <Theme> <SearchInput label="Busque por artistas, álbuns ou músicas" placeholder="Comece a escrever..." value={search} onChange={this.onSearch} /> {albums.items && <ListCards search={search} data={albums.items} />} </Theme> ); } } const mapStateToProps = state => ({ albums: state.albums.current }); const mapDispatchToProps = dispatch => ({ fetchAlbum: search => dispatch({ type: 'albums/GET_ALBUM', search }), }); export default connect(mapStateToProps, mapDispatchToProps)(MainScreen); <file_sep>import React from 'react'; import Image from 'components/Image'; import { Container, Title, ArtistName } from './components'; const Card = ({ data }) => ( <Container> <Image src={data.images[0].url} size="100%" /> <Title>{data.name}</Title> <ArtistName>{data.artists[0].name}</ArtistName> </Container> ); export default Card; <file_sep>import React from 'react'; import images from 'assets/images'; import { Figure, Img } from './components'; const Image = ({ name, src, size }) => ( <Figure size={size}> <Img src={name ? images[name] : src} /> </Figure> ); export default Image; <file_sep>import React from 'react'; const NotFoundScreen = () => <div><p>A página não existe!</p></div>; export default NotFoundScreen; <file_sep>import { put, takeEvery } from 'redux-saga/effects'; export const Types = { LOGIN: 'auth/LOGIN', LOGIN_SUCCESS: 'auth/LOGIN_SUCCESS', LOGIN_FAILURE: 'auth/LOGIN_FAILURE' }; const initialState = { loading: false, logged: false }; export const authReducer = (state = initialState, action = {}) => { switch (action.type) { case Types.LOGIN: return { ...state, loading: true }; case Types.LOGIN_SUCCESS: return { ...state, logged: true, loading: false }; case Types.LOGIN_FAILURE: return { ...state, loading: false }; default: return state; } }; function* login() { try { const response = yield fetch('http://localhost:8888/login', { // mode: 'no-cors', // headers: { // 'Access-Control-Allow-Origin': 'http://localhost:3000' // } }); console.log('responsew', response); yield put({ type: Types.LOGIN_SUCCESS }); } catch (err) { yield put({ type: Types.LOGIN_FAILURE }); } } export function* authSaga() { yield takeEvery(Types.LOGIN, login); }
4e65935dd4abaa8fc333c1626d3ce66fbdf596cd
[ "JavaScript" ]
11
JavaScript
izanf/teste-xpi
e0399d2ef4b0e9556f28795a7ab5a37a056d6d04
6dba7172303fc06a0e5671acf7bd12b4e5e743b5
refs/heads/master
<repo_name>hvctgr/SeoCV<file_sep>/README.md # SEO CV Modificación de [fantastiCV](https://github.com/hvctgr/fantastiCV) para optimizarla de cara al SEO. ## Consideraciones en el maquetado - El title se ha cambiado a el nombre del personaje, la etiqueta alternativa es otro nombre que puede tener el personaje. - Se han juntado en un archivo los estilos y en otro los scripts. - Para el menu de navegación. Se unifica en uno para mobile y desktop, se utiliza la etiqueta `i` para diferenciar los iconos del texto descriptivo que está entre `span`. - De forma general, cada una de las secciones contiene un `header`, donde se ubica el banner con nombre de cada sección, y un `div` con el contenido de la sección a efectos de manejar los estilos. - Todas las etiquetas `div` que anteriormente envolvían a imágenes o vídeo se han cambiado por `figure`. Además, en aquellas que no eran logos se les ha añadido un `figcaption`. - El footer ha pasado a listarse como 3 elementos `li` (imagen e iconos a enlaces externos). ## Consideraciones en los microdatos - En la sección donde se introduce al personaje se hace uso de `CreativeWork` para resaltar el nombre de la obra, el genero y el autor. - Al tratarse de un personaje ficticio, he considerado a sus maestros como `Organization` al tratarse de escuelas/estilos de artes marciales. - Para las batallas me he decantado por el schema `InteractAction` dado que se corresponden a una interacción con otras personas u organizaciones. - En el apartado curiosidades he dudado entre `ListItem` e `ItemList`. Me he decantado por `ListItem` porque en este caso se muestran una serie de curiosidades sin tener que ver las unas con las otras e `ItemList` requería especificar una posición. - Al ser curiosidades, no se resalta nada de ellas. - Como en la sección de Contacto no hay ningún información destacable no se han añadido microdatos. ## Herramientas utilizadas: Para comprobar la estructuración y contenido de la web se ha utilizado: - [Herramienta de pruebas de datos estructurados de Google](https://search.google.com/structured-data/testing-tool). - Plugin para chrome de [headingsMap](https://chrome.google.com/webstore/detail/headingsmap/flbjommegcjonpdmenkdiocclhjacmbi).<file_sep>/js/app.js /* Display menu */ console.log('cargo js') /* Form */ function setForm() { let form = document.querySelector('#contact') let oContact = {} form.addEventListener('submit', enviar) function enviar(oEv) { oEv.preventDefault() oContact.name = document.querySelector('#name').value oContact.email = document.querySelector('#email').value oContact.phone = document.querySelector('#phone').value oContact.message = document.querySelector('#message').value oContact.selection = getSelector(document.querySelector('#selection')) console.log("Formulario enviado!") console.log(oContact) } function getSelector(nodo) { let i = nodo.selectedIndex if (nodo[i].value == "other"){ let otherFieldValue = document.querySelector('#other-field').value return otherFieldValue }else{ return nodo[i].value } } } function selectionChange() { let selectElement = document.querySelector('#selection') let otherField = document.querySelector('#other-field') selectElement.addEventListener('change', showOtherField) function showOtherField() { let index = selectElement.selectedIndex let fieldValue = selectElement[index].value if ( fieldValue == "other"){ otherField.classList.remove('hidden-field') }else { otherField.classList.add('hidden-field') } } } /* Word counter */ function wordCount() { let maxWords = 150 let wordsInserted let textArea = document.querySelector('#message') let textMessage = document.querySelector('#message').value let textWordLeft = document.querySelector('#wordsLeft') textArea.addEventListener('keyup', wordInserted) textArea.addEventListener('keydown', writeCharacter) function wordInserted() { wordsInserted = textMessage.trim().split(/\s+/).length textMessage = document.querySelector('#message').value textWordLeft.innerHTML = maxWords-wordsInserted } function writeCharacter() { if (wordsInserted > maxWords-1) { if (event.keyCode == 46 || event.keyCode == 8) { } else if (event.keyCode < 48 || event.keyCode > 57) { event.preventDefault(); } } } } /* Scrollspy */ function setScroll() { let aMenuItems = document.querySelectorAll("nav.tablet a") let aSections = document.querySelectorAll("section") let oOffsets = [] prepareNavigation() window.addEventListener('scroll', changeMenuStyle) function prepareNavigation() { aSections.forEach( (item) => oOffsets['#' + item.id] = item.offsetTop ) } function changeMenuStyle() { let pageOffset = window.pageYOffset let menuItem = 0 if (pageOffset >= oOffsets['#home'] && pageOffset < oOffsets['#whoiam']) { menuItem = 0 } else if (pageOffset >= oOffsets['#whoiam'] && pageOffset < oOffsets['#studies']) { menuItem = 1 } else if (pageOffset >= oOffsets['#studies'] && pageOffset < oOffsets['#work']) { menuItem = 2 } else if (pageOffset >= oOffsets['#work'] && pageOffset < oOffsets['#about']) { menuItem = 3 } else if (pageOffset >= oOffsets['#about'] && pageOffset < oOffsets['#contact']) { menuItem = 4 } else { menuItem = 5 } aMenuItems.forEach( (item) => item.classList.remove('active') ) aMenuItems[menuItem].classList.add('active') } } /* Show more */ function showMoreWork(){ let moreWork1 = document.querySelector('.show-more-work1') let infoWork1 = document.querySelector('.work-info-work1') let moreWork2 = document.querySelector('.show-more-work2') let infoWork2 = document.querySelector('.work-info-work2') let moreWork3 = document.querySelector('.show-more-work3') let infoWork3 = document.querySelector('.work-info-work3') let moreWork4 = document.querySelector('.show-more-work4') let infoWork4 = document.querySelector('.work-info-work4') moreWork1.addEventListener('click', function(){showInformation(moreWork1, infoWork1)}) moreWork2.addEventListener('click', function(){showInformation(moreWork2, infoWork2)}) moreWork3.addEventListener('click', function(){showInformation(moreWork3, infoWork3)}) moreWork4.addEventListener('click', function(){showInformation(moreWork4, infoWork4)}) function showInformation(moreWork, infoWork){ console.log(moreWork) console.log(infoWork) infoWork.classList.toggle('hidden-field') moreWork.classList.toggle('fa-chevron-up') } }
f84bf826fae7e6389a7799e09dd41ae6541fbefc
[ "Markdown", "JavaScript" ]
2
Markdown
hvctgr/SeoCV
2442fdfc01e2ec6bad53785a68872fac82562445
d643042b400927d04840d437c7a7eb5ef8348b44
refs/heads/master
<repo_name>jackbicknell14/surftone<file_sep>/README.md # Surftone Streaming music for fans. ## How to use + Activate a python3 [virtualenvironment](https://www.geeksforgeeks.org/python-virtual-environment/). + `pip -r install requirements.txt` + `python manage.py runserver` ## Report bugs If you have any problem in using this software, please raise an issue in the [github page](https://github.com/jackbicknell14/surftone). ## Licence No licence yet, nonetheless we are not responsible for any possible damange this software may cause to you or your computer.<file_sep>/requirements.txt Django==2.1.7 django-crispy-forms==1.7.2 Pillow==5.4.1 pytz==2018.9 <file_sep>/home/templates/home/about.html {% extends "home/base.html" %} {% block content %} <div class="jumbotron"> <h1>This is Surftone.</h1> <p class="lead">Streaming for fans, built by the artists.</p> </div> {% endblock content %}<file_sep>/home/forms.py from django import forms from .models import Song class SongForm(forms.ModelForm): class Meta: model = Song fields = ('artist', 'title', 'audio_file',)<file_sep>/home/models.py from django.db import models class Song(models.Model): artist = models.CharField(max_length=255, blank=True) title = models.CharField(max_length=255, blank=True) audio_file = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True)<file_sep>/home/views.py from django.shortcuts import render, redirect from users.forms import UserRegisterForm from django.core.files.storage import FileSystemStorage from .forms import SongForm from .models import Song from django.views.generic import ListView def home(request): if request.user.is_authenticated: return render(request, 'home/dashboard.html', {'title': 'Welcome to Divyd!'}) else: if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserRegisterForm() return render(request, 'home/home.html', {'form': form}) def about(request): return render(request, 'home/about.html', {'title': 'About'}) def blog(request): return render(request, 'home/blog.html', {'title': 'About'}) def upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'home/upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'home/upload.html') def model_form_upload(request): if request.method == 'POST': form = SongForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('surftone-home') else: form = SongForm() return render(request, 'home/model_form_upload.html', { 'form': form }) def play(request): data = Song.objects.last() print(data) return render(request, 'home/play.html', {'data': data}) class SongListView(ListView): model = Song template_name = 'home/play.html' # <app>/<model>_<viewtype>.html context_object_name = 'songs' ordering = ['-uploaded_at'] paginate_by = 5 def dashboard(request): return render(request, 'home/dashboard.html', {'title': 'About'}) <file_sep>/home/urls.py from django.urls import path from . import views from users import views as users urlpatterns = [ path('', views.home, name="surftone-home"), path('blog/', views.blog, name="surftone-blog"), path('about/', views.about, name="surftone-about"), path('profile/', users.profile, name="surftone-profile"), path('upload/', views.model_form_upload, name="surftone-upload"), path('play', views.SongListView.as_view(), name="surftone-play"), path('dashboard/', views.dashboard, name="surftone-dashboard") ]
a71f04bc5560537fbdf4bcea3fcc7805db89a709
[ "Markdown", "Python", "Text", "HTML" ]
7
Markdown
jackbicknell14/surftone
007c3c143e88f60ad4cf6a87e07fa1d2d65f969d
07fc5a92e919122edd0e57ed4143ae0d352c5079
refs/heads/master
<repo_name>CiarlantiniD/Estatalaizer<file_sep>/variable.js var questions = [ { "question": "¿Es azul?", "name": "q1", "goodAnswer": 1, "badAnswer": 3, "points": 20, "options": [ "Rojo", "Violeta", "Naranja", "Azul", "Verde" ] }, { "question": "¿Madera?", "name": "q2", "goodAnswer": 1, "badAnswer": 3, "points": 30, "options": [ "Plastico", "Roble", "Cuero", "Porcelana", "Madera" ] }, { "question": "¿Pregunta agregada por CSV?", "name": "q3", "goodAnswer": 1, "badAnswer": 3, "points": 20, "options": [ "Respuesta 1", "Respuesta 2", "Respuesta 3", "Respuesta 4", "Respuesta 5" ] }, { "question": "¿Pregunta agregada por CSV?", "name": "q4", "goodAnswer": 1, "badAnswer": 3, "points": 20, "options": [ "Respuesta 1", "Respuesta 2", "Respuesta 3", "Respuesta 4", "Respuesta 5" ] }, { "question": "¿Pregunta agregada por CSV?", "name": "q5", "goodAnswer": 1, "badAnswer": 3, "points": 20, "options": [ "Respuesta 1", "Respuesta 2", "Respuesta 3", "Respuesta 4", "Respuesta 5" ] }, { "question": "¿Pregunta agregada por CSV?", "name": "q6", "goodAnswer": 1, "badAnswer": 3, "points": 20, "options": [ "Respuesta 1", "Respuesta 2", "Respuesta 3", "Respuesta 4", "Respuesta 5" ] }, { "question": "¿Pregunta agregada por CSV?", "name": "q7", "goodAnswer": 1, "badAnswer": 3, "points": 20, "options": [ "Respuesta 1", "Respuesta 2", "Respuesta 3", "Respuesta 4", "Respuesta 5" ] } ]<file_sep>/controller.js var points; var maxPoints; function SetMaxPoints(){ maxPoints = 0; for(i = 0; i < questions.length;i++){ maxPoints += questions[i].points; } } function BodyLoader(){ SetMaxPoints(); $("#alerta").hide(); $("#Resultado").hide(); for(i = 0; i < questions.length; i++ ){ var div = document.createElement("div"); var title = document.createElement("h4"); var index = i + 1; var node = document.createTextNode(index + ". " + questions[i].question); title.appendChild(node); div.appendChild(title); for(j = 0; j < questions[i].options.length; j++ ){ var indexInput = j + 1; var divform = document.createElement("div"); divform.classList.add('form-check'); var input = document.createElement("INPUT"); input.classList.add("form-check-input"); input.setAttribute("type", "radio"); input.setAttribute("name", questions[i].name); input.setAttribute("id", questions[i].name); input.setAttribute("value", indexInput.toString()); var labelText = document.createTextNode(questions[i].options[j]); var label = document.createElement("label"); label.classList.add('form-check-label'); divform.appendChild(input); label.appendChild(labelText); divform.appendChild(label); div.appendChild(divform); } var element = document.getElementById("Formulario"); element.appendChild(div); } } function GetResultAnswerPonits(){ points = 0; for(i = 0; i < questions.length; i++){ var checkRadioStatus = false; var radios = document.getElementsByName(questions[i].name); for (var j = 0, length = radios.length; j < length; j++){ if (radios[j].checked && radios[j].value == questions[i].goodAnswer){ checkRadioStatus = true; points += questions[i].points; break; } else if(radios[j].checked && radios[j].value == questions[i].badAnswer){ checkRadioStatus = true; var halfPoints = Number(questions[i].points) / 2; points += halfPoints; break; }else if (radios[j].checked){ checkRadioStatus = true; } } if(!checkRadioStatus){ $( "#alerta" ).show( "fold"); return false; } } return true; } function GetResult(){ window.scrollTo(0, 0); if(GetResultAnswerPonits()){ var showresult = (Number(points) * 100) / Number(maxPoints); showresult = Math.ceil(showresult); document.getElementById("points").textContent = "Resultado " + showresult.toString() + "%"; $( "#progressbar" ).progressbar( {value : points, max : maxPoints} ); if(Number(showresult) > 90){ $( "#progressbar" ).addClass("verygood"); } else if(Number(showresult) > 70){ $( "#progressbar" ).addClass("good"); } else if(Number(showresult) > 50){ $( "#progressbar" ).addClass("regular"); } else if(Number(showresult) > 30){ $( "#progressbar" ).addClass("bad"); } else{ $( "#progressbar" ).addClass("verybad"); } jQuery("#Preguntas").fadeOut("slow",function(){$("#Resultado").fadeIn("slow");}); } }
d6b51f4a7bd51f8435f4621eb9f454f9f829ce71
[ "JavaScript" ]
2
JavaScript
CiarlantiniD/Estatalaizer
e2744f8173b5ce3cf118bfd51fab44cf88f6ceb0
d2984e7bc755307040b447a0fcbc6bb9d06f03b3
refs/heads/1.12
<repo_name>TeamAvion/Tesla-Powered-Thingies<file_sep>/src/main/kotlin/net/ndrei/teslapoweredthingies/config/Config.kt package net.ndrei.teslapoweredthingies.config import net.ndrei.teslapoweredthingies.MOD_ID import java.io.File object Config { lateinit var configFolder: File private set fun init(modConfigurationDirectory: File) { this.configFolder = File(modConfigurationDirectory, MOD_ID) this.configFolder.mkdirs() } } <file_sep>/src/main/kotlin/net/ndrei/teslapoweredthingies/config/configutils.kt package net.ndrei.teslapoweredthingies.config import com.google.gson.GsonBuilder import com.google.gson.JsonElement import com.google.gson.JsonObject import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraft.util.JsonUtils import net.minecraft.util.ResourceLocation import net.minecraftforge.fluids.FluidRegistry import net.minecraftforge.fluids.FluidStack import net.minecraftforge.oredict.OreDictionary import net.ndrei.teslacorelib.utils.copyWithSize import net.ndrei.teslapoweredthingies.MOD_ID import net.ndrei.teslapoweredthingies.TeslaThingiesMod import java.io.BufferedWriter import java.io.File import java.io.FileWriter fun readExtraRecipesFile(fileName: String, callback: (json: JsonObject) -> Unit) { val GSON = GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create() val config = File(Config.configFolder, "$fileName-base.json") if (!config.exists()) { val stream = Config.javaClass.getResourceAsStream("/assets/$MOD_ID/extra-recipes/$fileName.json") if (stream == null) { TeslaThingiesMod.logger.error("Could not locate extra recipes base resource file: '$fileName.json'.") } else { stream.use { s -> if (config.createNewFile()) { val writer = BufferedWriter(FileWriter(config, false)) writer.use { outs -> s.bufferedReader().use { ins -> var line = ins.readLine() while (line != null) { outs.write(line + "\n") line = ins.readLine() } } } } else { TeslaThingiesMod.logger.error("Could not create extra recipes file: '${config.path}'.") } } } } fun readFile(file: File) { if (file.exists()) { file.bufferedReader().use { val json = JsonUtils.fromJson(GSON, it, JsonElement::class.java) if (json != null) { if (json.isJsonArray) { json.asJsonArray.forEach { if (it.isJsonObject) { callback(it.asJsonObject) } } } else if (json.isJsonObject) { callback(json.asJsonObject) } } } } } readFile(config) readFile(File(Config.configFolder, "$fileName-extra.json")) } fun JsonObject.readFluidStack(memberName: String): FluidStack? { val json = JsonUtils.getJsonObject(this, memberName) ?: return null val fluid = JsonUtils.getString(json, "name", "") .let { FluidRegistry.getFluid(it) } ?: return null val amount = JsonUtils.getInt(json, "quantity", 0) return if (amount <= 0) null else FluidStack(fluid, amount) } fun JsonObject.readItemStacks(memberName: String): List<ItemStack> { val json = JsonUtils.getJsonObject(this, memberName) ?: return listOf() return json.readItemStacks() } fun JsonObject.readItemStacks(): List<ItemStack> { val item = JsonUtils.getString(this, "name", "") .let { val registryName = if (it.isNullOrEmpty()) null else ResourceLocation(it) if ((registryName != null) && Item.REGISTRY.containsKey(registryName)) Item.REGISTRY.getObject(registryName) else null } if (item != null) { val meta = JsonUtils.getInt(this, "meta", 0) val amount = JsonUtils.getInt(this, "quantity", 1) return listOf(ItemStack(item, amount, meta)) } else { val ore = JsonUtils.getString(this, "ore", "") if (!ore.isNullOrEmpty()) { val amount = JsonUtils.getInt(this, "quantity", 1) return OreDictionary.getOres(ore) .map { it.copyWithSize(amount) } } } return listOf() } fun JsonObject.readItemStack(memberName: String) = this.readItemStacks(memberName).firstOrNull() fun JsonObject.readItemStack() = this.readItemStacks().firstOrNull() <file_sep>/src/main/kotlin/net/ndrei/teslapoweredthingies/machines/poweredkiln/PoweredKilnBlock.kt package net.ndrei.teslapoweredthingies.machines.poweredkiln import net.minecraft.init.Blocks import net.minecraft.init.Items import net.minecraft.item.ItemStack import net.minecraft.item.crafting.IRecipe import net.minecraftforge.oredict.ShapedOreRecipe import net.ndrei.teslacorelib.annotations.AutoRegisterBlock import net.ndrei.teslacorelib.items.MachineCaseItem import net.ndrei.teslapoweredthingies.machines.BaseThingyBlock /** * Created by CF on 2017-07-06. */ @AutoRegisterBlock object PoweredKilnBlock : BaseThingyBlock<PoweredKilnEntity>("powered_kiln", PoweredKilnEntity::class.java) { override val recipe: IRecipe? get() = ShapedOreRecipe(null, ItemStack(this, 1), "fff", "scs", "sxs", 'f', Blocks.FURNACE, 'c', MachineCaseItem, 's', Blocks.STONE, 'x', Items.FLINT_AND_STEEL ) } <file_sep>/src/main/kotlin/net/ndrei/teslapoweredthingies/machines/BaseThingyGenerator.kt package net.ndrei.teslapoweredthingies.machines import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer import net.ndrei.teslacorelib.gui.IGuiContainerPiece import net.ndrei.teslacorelib.tileentities.ElectricGenerator import net.ndrei.teslapoweredthingies.gui.OpenJEICategoryPiece /** * Created by CF on 2017-07-06. */ abstract class BaseThingyGenerator(typeId: Int) : ElectricGenerator(typeId) { override fun getGuiContainerPieces(container: BasicTeslaGuiContainer<*>): MutableList<IGuiContainerPiece> { val list = super.getGuiContainerPieces(container) list.add(OpenJEICategoryPiece(this.getBlockType())) return list } }<file_sep>/README.md # Tesla-Powered-Thingies [![](http://cf.way2muchnoise.eu/tesla-powered-thingies.svg)](https://minecraft.curseforge.com/projects/tesla-powered-thingies) [![](http://cf.way2muchnoise.eu/versions/tesla-powered-thingies.svg)](https://minecraft.curseforge.com/projects/tesla-powered-thingies) [![](https://img.shields.io/badge/Discord-Team%20Avion's%20Cat%20Mods-blue.svg)](https://discord.gg/WqrCtcK) A collection of various Tesla powered machines <file_sep>/src/main/kotlin/net/ndrei/teslapoweredthingies/items/AshItem.kt package net.ndrei.teslapoweredthingies.items import net.ndrei.teslacorelib.annotations.AutoRegisterItem /** * Created by CF on 2017-06-30. */ @AutoRegisterItem object AshItem : BaseThingyItem("ash") { // override val recipe: IRecipe? // get() = ShapedOreRecipe(null, ItemStack(Items.DYE, 1, 15), // "xx", // "xx", // 'x', this // ) } <file_sep>/src/main/kotlin/net/ndrei/teslapoweredthingies/machines/liquidxpstorage/LiquidXPStorageEntity.kt package net.ndrei.teslapoweredthingies.machines.liquidxpstorage import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer import net.minecraft.init.Items import net.minecraft.inventory.Slot import net.minecraft.item.EnumDyeColor import net.minecraft.item.ItemStack import net.minecraft.tileentity.TileEntity import net.minecraftforge.fluids.Fluid import net.minecraftforge.fluids.FluidUtil import net.minecraftforge.fluids.capability.CapabilityFluidHandler import net.minecraftforge.items.ItemStackHandler import net.ndrei.teslacorelib.compatibility.ItemStackUtil import net.ndrei.teslacorelib.containers.BasicTeslaContainer import net.ndrei.teslacorelib.containers.FilteredSlot import net.ndrei.teslacorelib.gui.BasicRenderedGuiPiece import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer import net.ndrei.teslacorelib.gui.IGuiContainerPiece import net.ndrei.teslacorelib.inventory.BoundingRectangle import net.ndrei.teslacorelib.inventory.ColoredItemHandler import net.ndrei.teslacorelib.inventory.FilteredFluidTank import net.ndrei.teslacorelib.inventory.FluidTank import net.ndrei.teslacorelib.tileentities.SidedTileEntity import net.ndrei.teslapoweredthingies.client.Textures import net.ndrei.teslapoweredthingies.fluids.LiquidXPFluid import net.ndrei.teslapoweredthingies.render.LiquidXPStorageSpecialRenderer /** * Created by CF on 2017-07-07. */ class LiquidXPStorageEntity : SidedTileEntity(LiquidXPStorageEntity::class.java.name.hashCode()) { private lateinit var inputItems: ItemStackHandler private lateinit var outputItems: ItemStackHandler private lateinit var xpTank: FilteredFluidTank //#region inventories override fun initializeInventories() { super.initializeInventories() this.inputItems = object : ItemStackHandler(2) { override fun getStackLimit(slot: Int, stack: ItemStack): Int { if (slot == 0) { return 1 } return super.getStackLimit(slot, stack) } override fun onContentsChanged(slot: Int) { this@LiquidXPStorageEntity.markDirty() } } this.outputItems = object : ItemStackHandler(2) { // override fun getStackLimit(slot: Int, stack: ItemStack): Int { // if (slot == 1) { // return 1 // } // return super.getStackLimit(slot, stack) // } override fun onContentsChanged(slot: Int) { this@LiquidXPStorageEntity.markDirty() } } this.xpTank = FilteredFluidTank(LiquidXPFluid, object : FluidTank(1500) { override fun onContentsChanged() { this@LiquidXPStorageEntity.markDirty() } }) super.addInventory(object : ColoredItemHandler(this.inputItems, EnumDyeColor.GREEN, "Input Liquid Containers", BoundingRectangle(56, 25, 18, 54)) { override fun canInsertItem(slot: Int, stack: ItemStack): Boolean { return slot == 0 && this@LiquidXPStorageEntity.isValidInContainer(stack) } override fun canExtractItem(slot: Int): Boolean { return slot == 1 } override fun getSlots(container: BasicTeslaContainer<*>): MutableList<Slot> { val slots = mutableListOf<Slot>() val box = this.boundingBox if (!box.isEmpty) { slots.add(FilteredSlot(this.itemHandlerForContainer, 0, box.left + 1, box.top + 1)) slots.add(FilteredSlot(this.itemHandlerForContainer, 1, box.left + 1, box.top + 1 + 36)) } return slots } override fun getGuiContainerPieces(container: BasicTeslaGuiContainer<*>): MutableList<IGuiContainerPiece> = mutableListOf() }) super.addInventoryToStorage(this.inputItems, "income") super.addFluidTank(this.xpTank, EnumDyeColor.LIME, "Liquid XP", BoundingRectangle(79, 25, 18, 54)) super.addInventory(object : ColoredItemHandler(this.outputItems, EnumDyeColor.PURPLE, "Output Liquid Containers", BoundingRectangle(102, 25, 18, 54)) { override fun canInsertItem(slot: Int, stack: ItemStack): Boolean { return slot == 0 && this@LiquidXPStorageEntity.isValidOutContainer(stack) } override fun canExtractItem(slot: Int): Boolean { return slot == 1 } override fun getSlots(container: BasicTeslaContainer<*>): MutableList<Slot> { val slots = mutableListOf<Slot>() val box = this.boundingBox if (!box.isEmpty) { slots.add(FilteredSlot(this.itemHandlerForContainer, 0, box.left + 1, box.top + 1)) slots.add(FilteredSlot(this.itemHandlerForContainer, 1, box.left + 1, box.top + 1 + 36)) } return slots } override fun getGuiContainerPieces(container: BasicTeslaGuiContainer<*>): MutableList<IGuiContainerPiece> = mutableListOf() }) super.addInventoryToStorage(this.outputItems, "outcome") } private fun isValidInContainer(stack: ItemStack): Boolean { if (!ItemStackUtil.isEmpty(stack)) { if (stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { val handler = stack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null) if (handler != null) { val tanks = handler.tankProperties if (tanks != null && tanks.size > 0) { for (tank in tanks) { if (tank.canDrain()) { val content = tank.contents if (content != null && content.amount > 0 && content.fluid === LiquidXPFluid) { return true } } } } } } } return false } private fun isValidOutContainer(stack: ItemStack): Boolean { if (!ItemStackUtil.isEmpty(stack)) { val item = stack.item if (item === Items.GLASS_BOTTLE || item === Items.BUCKET) { return true } if (stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { val handler = stack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null) if (handler != null) { val tanks = handler.tankProperties if (tanks != null && tanks.size > 0) { for (tank in tanks) { if (tank.canFill()) { val content = tank.contents if (content == null || content.amount < tank.capacity && content.fluid === LiquidXPFluid) { return true } } } } } } } return false } override fun shouldAddFluidItemsInventory(): Boolean { return false } //#endregion //#region gui override fun getGuiContainerPieces(container: BasicTeslaGuiContainer<*>): MutableList<IGuiContainerPiece> { val list = super.getGuiContainerPieces(container) list.add(BasicRenderedGuiPiece(56, 25, 64, 54, Textures.FARM_TEXTURES.resource, 65, 1)) return list } override fun getRenderers(): MutableList<TileEntitySpecialRenderer<in TileEntity>> { val list = super.getRenderers() list.add(LiquidXPStorageSpecialRenderer) return list } //#endregion private var delay = 0 override fun innerUpdate() { if (this.getWorld().isRemote) { return } if (--this.delay > 0) { return } var transferred = 0 //#region process inputs val i_stack = this.inputItems.getStackInSlot(0) val capacity = this.xpTank.capacity - this.xpTank.fluidAmount if (!i_stack.isEmpty && (capacity > 0)) { if (i_stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { val initial = this.xpTank.fluidAmount val result = FluidUtil.tryEmptyContainer(i_stack, this.fluidHandler, Fluid.BUCKET_VOLUME, null, true) if (result.isSuccess && !ItemStack.areItemStacksEqual(result.getResult(), i_stack)) { val r_stack = result.getResult() this.inputItems.setStackInSlot(0, r_stack) if (!r_stack.isEmpty && this.isEmptyFluidContainer(r_stack)) { this.inputItems.setStackInSlot(0, this.inputItems.insertItem(1, r_stack, false)) } transferred += this.xpTank.fluidAmount - initial } } } //#endregion //#region process outputs val o_stack = this.outputItems.getStackInSlot(0) val maxDrain = this.xpTank.fluidAmount if (!o_stack.isEmpty && (maxDrain > 0)) { if (o_stack.item === Items.GLASS_BOTTLE) { //#region glass bottle -> experience bottle if (maxDrain >= 15) { val existing = this.outputItems.getStackInSlot(1) var result = ItemStack.EMPTY if (existing.isEmpty) { result = ItemStack(Items.EXPERIENCE_BOTTLE, 1) } else if (existing.count < existing.maxStackSize) { result = ItemStackUtil.copyWithSize(existing, ItemStackUtil.getSize(existing) + 1) } if (!result.isEmpty) { this.outputItems.setStackInSlot(1, result) this.xpTank.drain(15, true) i_stack.shrink(1) if (i_stack.count == 0) { this.outputItems.setStackInSlot(0, ItemStack.EMPTY) } transferred += 15 } } //#endregion } else if (o_stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null) && this.outputItems.getStackInSlot(1).isEmpty) { val toFill = Math.max(maxDrain, Fluid.BUCKET_VOLUME) val initial = this.xpTank.fluidAmount val bucket = ItemStackUtil.copyWithSize(o_stack, 1) val result = FluidUtil.tryFillContainer(bucket, this.fluidHandler, toFill, null, true) if (result.isSuccess) { // stack = result.getResult() // this.outputItems.insertItem(1, stack, false) this.outputItems.setStackInSlot(1, result.getResult()) this.outputItems.getStackInSlot(0).shrink(1) transferred += initial - this.xpTank.fluidAmount } } } //#endregion if (transferred > 0) { this.delay = Math.max(5, transferred / 50) this.forceSync() } else if (this.delay < 0) { this.delay = 0 } } private fun isEmptyFluidContainer(stack: ItemStack): Boolean { val fluid = FluidUtil.getFluidContained(stack) return fluid == null || fluid.amount == 0 } val fillPercent: Float get() = this.xpTank.fluidAmount.toFloat() / this.xpTank.capacity.toFloat() } <file_sep>/src/main/kotlin/net/ndrei/teslapoweredthingies/machines/ElectricFarmMachine.kt package net.ndrei.teslapoweredthingies.machines import net.minecraft.client.renderer.GlStateManager import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer import net.minecraft.item.EnumDyeColor import net.minecraft.item.ItemStack import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumFacing import net.minecraft.util.math.AxisAlignedBB import net.minecraftforge.items.ItemHandlerHelper import net.minecraftforge.items.ItemStackHandler import net.ndrei.teslacorelib.compatibility.ItemStackUtil import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer import net.ndrei.teslacorelib.gui.IGuiContainerPiece import net.ndrei.teslacorelib.gui.LockedInventoryTogglePiece import net.ndrei.teslacorelib.gui.SideDrawerPiece import net.ndrei.teslacorelib.inventory.BoundingRectangle import net.ndrei.teslacorelib.inventory.ColoredItemHandler import net.ndrei.teslacorelib.inventory.LockableItemHandler import net.ndrei.teslacorelib.render.IWorkAreaProvider import net.ndrei.teslacorelib.render.WorkingAreaRenderer import net.ndrei.teslacorelib.utils.BlockCube import net.ndrei.teslacorelib.utils.BlockPosUtils import net.ndrei.teslapoweredthingies.client.Textures import net.ndrei.teslapoweredthingies.common.GuiPieceSide import net.ndrei.teslapoweredthingies.items.MachineRangeAddonTier1 import net.ndrei.teslapoweredthingies.items.MachineRangeAddonTier2 /** * Created by CF on 2017-07-06. */ abstract class ElectricFarmMachine protected constructor(typeId: Int) : BaseThingyMachine(typeId), IWorkAreaProvider { protected var inStackHandler: ItemStackHandler? = null protected var filteredInStackHandler: ColoredItemHandler? = null protected var outStackHandler: ItemStackHandler? = null //#region inventories & gui methods override fun initializeInventories() { super.initializeInventories() this.initializeInputInventory() this.initializeOutputInventory() } protected open val inputSlots: Int get() = 3 protected open fun initializeInputInventory() { val inputSlots = this.inputSlots if (inputSlots > 0) { this.inStackHandler = if (this.lockableInputInventory) object : LockableItemHandler(Math.max(0, Math.min(3, inputSlots))) { override fun onContentsChanged(slot: Int) { this@ElectricFarmMachine.markDirty() } } else object : ItemStackHandler(Math.max(0, Math.min(3, inputSlots))) { override fun onContentsChanged(slot: Int) { this@ElectricFarmMachine.markDirty() } } this.filteredInStackHandler = object : ColoredItemHandler(this.inStackHandler!!, EnumDyeColor.GREEN, "Input Items", this.getInputInventoryBounds(this.inStackHandler!!.slots, 1)) { override fun canInsertItem(slot: Int, stack: ItemStack) = (if (this.innerHandler is LockableItemHandler) this.innerHandler.canInsertItem(slot, stack) else true) && this@ElectricFarmMachine.acceptsInputStack(slot, stack) override fun canExtractItem(slot: Int) = false } super.addInventory(this.filteredInStackHandler) super.addInventoryToStorage(this.inStackHandler!!, "inputs") } else { this.inStackHandler = null } } protected open val lockableInputInventory: Boolean get() = true protected open val lockableInputLockPosition: GuiPieceSide get() = GuiPieceSide.NONE protected open fun getInputInventoryBounds(columns: Int, rows: Int) = BoundingRectangle(115 + (3 - columns) * 9, 25, 18 * columns, 18 * rows) protected open fun acceptsInputStack(slot: Int, stack: ItemStack) = true protected open val outputSlots: Int get() = 6 protected fun initializeOutputInventory() { val outputSlots = this.outputSlots if (outputSlots > 0) { this.outStackHandler = object : ItemStackHandler(Math.max(0, Math.min(6, outputSlots))) { override fun onContentsChanged(slot: Int) { this@ElectricFarmMachine.markDirty() } } val columns = Math.min(3, this.outStackHandler!!.slots) val rows = Math.min(2, this.outStackHandler!!.slots / columns) super.addInventory(object : ColoredItemHandler(this.outStackHandler!!, EnumDyeColor.PURPLE, "Output Items", this.getOutputInventoryBounds(columns, rows)) { override fun canInsertItem(slot: Int, stack: ItemStack) = false override fun canExtractItem(slot: Int) = true }) super.addInventoryToStorage(this.outStackHandler!!, "outputs") } else { this.outStackHandler = null } } protected open fun getOutputInventoryBounds(columns: Int, rows: Int) = BoundingRectangle(115, 43, 18 * columns, 18 * rows) override fun getGuiContainerPieces(container: BasicTeslaGuiContainer<*>): MutableList<IGuiContainerPiece> { val list = super.getGuiContainerPieces(container) if (this.lockableInputInventory && (this.lockableInputLockPosition != GuiPieceSide.NONE) && (this.filteredInStackHandler != null)) { val box = this.filteredInStackHandler!!.boundingBox if (!box.isEmpty) list.add(LockedInventoryTogglePiece( when (this.lockableInputLockPosition) { GuiPieceSide.LEFT -> box.left - 16 else -> box.right + 2 // assume RIGHT }, box.top + 2, this, this.filteredInStackHandler!!.color) ) } if (this.hasWorkArea) { list.add(object: SideDrawerPiece(SideDrawerPiece.findFreeSpot(list)) { override fun renderState(container: BasicTeslaGuiContainer<*>, state: Int, box: BoundingRectangle) { Textures.MACHINES_TEXTURES.bind(container) GlStateManager.enableBlend() GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA) container.drawTexturedModalRect( box.left, box.top + 1, 99, if (this@ElectricFarmMachine.showWorkArea) 21 else 7, 14, 14) GlStateManager.disableBlend() } override fun getStateToolTip(state: Int) = listOf( if (this@ElectricFarmMachine.showWorkArea) "Hide work area" else "Show work area" ) override fun clicked() { this@ElectricFarmMachine.showWorkArea = !this@ElectricFarmMachine.showWorkArea } }) } return list } override fun getRenderers(): MutableList<TileEntitySpecialRenderer<in TileEntity>> { val list = super.getRenderers() if (this.hasWorkArea && this.showWorkArea) { list.add(WorkingAreaRenderer) } return list } //#endregion //#region write/read/sync methods // override fun readFromNBT(compound: NBTTagCompound) { // super.readFromNBT(compound) // if (compound.hasKey("income")) { // this.inStackHandler!!.deserializeNBT(compound.getCompoundTag("income")) // } // if (compound.hasKey("outcome")) { // this.outStackHandler!!.deserializeNBT(compound.getCompoundTag("outcome")) // } // } // // override fun writeToNBT(compound: NBTTagCompound): NBTTagCompound { // var compound = compound // compound = super.writeToNBT(compound) // // if (this.inStackHandler != null) { // compound.setTag("income", this.inStackHandler!!.serializeNBT()) // } // if (this.outStackHandler != null) { // compound.setTag("outcome", this.outStackHandler!!.serializeNBT()) // } // // return compound // } //#endregion open fun supportsRangeAddons() = true protected val range: Int get() = this.getRange(3, 3) protected fun getRange(base: Int, perTier: Int): Int { val tier1 = if (this.hasAddon(MachineRangeAddonTier1::class.java)) 1 else 0 val tier2 = tier1 * if (this.hasAddon(MachineRangeAddonTier2::class.java)) 1 else 0 return base + (tier1 + tier2) * perTier } protected fun getWorkArea(facing: EnumFacing, height: Int): BlockCube { return BlockPosUtils.getCube(this.getPos(), facing, this.range, height) } // open val groundArea: BlockCube // get() = this.getWorkArea(this.facing.opposite, 1) protected fun spawnOverloadedItem(stack: ItemStack): Boolean { // TODO: readd config option for this // if (MekfarmMod.config.allowMachinesToSpawnItems()) { return null != super.spawnItemFromFrontSide(stack) // } // return false } fun outputItems(loot: ItemStack) = loot.isEmpty || this.outputItems(listOf(loot)) fun outputItems(loot: List<ItemStack>): Boolean { if (loot.isNotEmpty()) { for (lootStack in loot) { var remaining = if (this.filteredInStackHandler == null) ItemStackUtil.insertItemInExistingStacks(this.inStackHandler, lootStack, false) else ItemHandlerHelper.insertItemStacked(this.filteredInStackHandler, lootStack, false) if (!ItemStackUtil.isEmpty(remaining)) { remaining = ItemHandlerHelper.insertItem(this.outStackHandler, lootStack, false) } if (!ItemStackUtil.isEmpty(remaining)) { return this.spawnOverloadedItem(remaining) } } } return true } open val hasWorkArea: Boolean = true var showWorkArea: Boolean = false override fun getWorkArea(): BlockCube = this.getWorkArea(this.facing.opposite, 1) override fun getWorkAreaColor(): Int = 0x54CBFF override fun getRenderBoundingBox(): AxisAlignedBB { return super.getRenderBoundingBox().union(this.getWorkArea().boundingBox) } } <file_sep>/src/main/kotlin/net/ndrei/teslapoweredthingies/machines/incinerator/IncineratorBlock.kt package net.ndrei.teslapoweredthingies.machines.incinerator import net.minecraft.init.Blocks import net.minecraft.init.Items import net.minecraft.item.ItemStack import net.minecraft.item.crafting.IRecipe import net.minecraftforge.oredict.ShapedOreRecipe import net.ndrei.teslacorelib.annotations.AutoRegisterBlock import net.ndrei.teslacorelib.items.MachineCaseItem import net.ndrei.teslapoweredthingies.machines.BaseThingyBlock /** * Created by CF on 2017-06-30. */ @AutoRegisterBlock object IncineratorBlock : BaseThingyBlock<IncineratorEntity>("incinerator", IncineratorEntity::class.java) { override val recipe: IRecipe? get() = ShapedOreRecipe(null, ItemStack(this, 1), "sfs", "scs", "sgs", 'f', Blocks.FURNACE, 'c', MachineCaseItem, 's', Blocks.STONE, 'g', Items.FLINT_AND_STEEL ) } <file_sep>/src/main/kotlin/net/ndrei/teslapoweredthingies/machines/poweredkiln/PoweredKilnRecipes.kt package net.ndrei.teslapoweredthingies.machines.poweredkiln import net.minecraft.item.ItemStack import net.minecraft.item.crafting.FurnaceRecipes import net.ndrei.teslacorelib.utils.copyWithSize import net.ndrei.teslacorelib.utils.equalsIgnoreSize /** * Created by CF on 2017-07-06. */ object PoweredKilnRecipes { private val recipes = mutableListOf<PoweredKilnRecipe>() fun registerRecipe(input: ItemStack, output: ItemStack) { this.recipes.add(PoweredKilnRecipe(input, output)) } fun getRecipes() = this.recipes.toList() fun findRecipe(input: ItemStack) = this.recipes.firstOrNull { it.input.equalsIgnoreSize(input) } ?: FurnaceRecipes.instance().getSmeltingResult(input).let { if (it.isEmpty) null else PoweredKilnRecipe(input.copyWithSize(1), it) } fun hasRecipe(stack: ItemStack) = (this.findRecipe(stack) != null) }<file_sep>/src/main/kotlin/net/ndrei/teslapoweredthingies/common/CommonProxy.kt package net.ndrei.teslapoweredthingies.common import net.minecraftforge.fml.common.event.FMLPostInitializationEvent import net.minecraftforge.fml.common.event.FMLPreInitializationEvent import net.minecraftforge.fml.relauncher.Side import net.ndrei.teslacorelib.BaseProxy import net.ndrei.teslapoweredthingies.config.Config import net.ndrei.teslapoweredthingies.machines.fluidburner.FluidBurnerRecipes import net.ndrei.teslapoweredthingies.machines.incinerator.IncineratorRecipes /** * Created by CF on 2017-06-30. */ @Suppress("unused") open class CommonProxy(side: Side) : BaseProxy(side) { constructor() : this(Side.SERVER) override fun preInit(ev: FMLPreInitializationEvent) { super.preInit(ev) Config.init(ev.modConfigurationDirectory) } override fun postInit(ev: FMLPostInitializationEvent) { super.postInit(ev) IncineratorRecipes.registerRecipes() FluidBurnerRecipes.registerRecipes() } } <file_sep>/src/main/kotlin/net/ndrei/teslapoweredthingies/machines/incinerator/IncineratorEntity.kt package net.ndrei.teslapoweredthingies.machines.incinerator import net.minecraft.entity.item.EntityItem import net.minecraft.item.EnumDyeColor import net.minecraft.item.ItemStack import net.minecraftforge.items.ItemHandlerHelper import net.minecraftforge.items.ItemStackHandler import net.ndrei.teslacorelib.compatibility.ItemStackUtil import net.ndrei.teslacorelib.gui.BasicRenderedGuiPiece import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer import net.ndrei.teslacorelib.gui.IGuiContainerPiece import net.ndrei.teslacorelib.inventory.BoundingRectangle import net.ndrei.teslacorelib.inventory.ColoredItemHandler import net.ndrei.teslapoweredthingies.client.Textures import net.ndrei.teslapoweredthingies.gui.GeneratorBurnPiece import net.ndrei.teslapoweredthingies.gui.IWorkItemProvider import net.ndrei.teslapoweredthingies.gui.ItemStackPiece import net.ndrei.teslapoweredthingies.machines.BaseThingyGenerator /** * Created by CF on 2017-06-30. */ class IncineratorEntity : BaseThingyGenerator(IncineratorEntity::class.java.name.hashCode()), IWorkItemProvider { private var inputs: ItemStackHandler? = null private var outputs: ItemStackHandler? = null private var currentItem: ItemStackHandler? = null //#region inventory & gui override fun initializeInventories() { super.initializeInventories() this.inputs = object : ItemStackHandler(1) { override fun onContentsChanged(slot: Int) { this@IncineratorEntity.markDirty() } } super.addInventory(object : ColoredItemHandler(this.inputs!!, EnumDyeColor.GREEN, "Input Items", BoundingRectangle(61, 43, 18, 18)) { override fun canExtractItem(slot: Int): Boolean { return false } override fun canInsertItem(slot: Int, stack: ItemStack): Boolean { if (stack.isEmpty) { return false } return IncineratorRecipes.isFuel(stack) } }) super.addInventoryToStorage(this.inputs!!, "inv_inputs") this.outputs = object : ItemStackHandler(3) { override fun onContentsChanged(slot: Int) { this@IncineratorEntity.markDirty() } } super.addInventory(object : ColoredItemHandler(this.outputs!!, EnumDyeColor.PURPLE, "Output Items", BoundingRectangle(133, 25, 18, 54)) { override fun canInsertItem(slot: Int, stack: ItemStack): Boolean { return false } }) super.addInventoryToStorage(this.outputs!!, "inv_outputs") this.currentItem = object : ItemStackHandler(1) { override fun onContentsChanged(slot: Int) { this@IncineratorEntity.markDirty() } } super.addInventoryToStorage(this.currentItem!!, "inv_current") } override fun getGuiContainerPieces(container: BasicTeslaGuiContainer<*>): MutableList<IGuiContainerPiece> { val pieces = super.getGuiContainerPieces(container) pieces.add(BasicRenderedGuiPiece(79, 41, 54, 22, Textures.MACHINES_TEXTURES.resource, 24, 4)) pieces.add(GeneratorBurnPiece(99, 64, this)) pieces.add(object : ItemStackPiece(95, 41, 22, 22, this@IncineratorEntity) { override fun drawForegroundTopLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, mouseX: Int, mouseY: Int) { if (!this.isInside(container, mouseX, mouseY)) { return } val lines = GeneratorBurnPiece.getTooltipLines(this@IncineratorEntity) if (lines != null && lines.size > 0) { container.drawTooltip(lines, mouseX - guiX, mouseY - guiY) } } }) return pieces } override val workItem: ItemStack get() = if (this.currentItem == null) ItemStack.EMPTY else this.currentItem!!.getStackInSlot(0) //#endregion override fun consumeFuel(): Long { if (this.currentItem!!.getStackInSlot(0).isEmpty) { var stack = this.inputs!!.extractItem(0, 1, true) if (!stack.isEmpty) { val power = IncineratorRecipes.getPower(stack) if (power > 0) { stack = this.inputs!!.extractItem(0, 1, false) if (!stack.isEmpty) { this.currentItem!!.setStackInSlot(0, stack) return power } } } } return 0 } override fun fuelConsumed() { val stack = this.currentItem!!.getStackInSlot(0) if (!ItemStackUtil.isEmpty(stack)) { val secondary = IncineratorRecipes.getSecondaryOutputs(stack.item) if (secondary != null && secondary.size > 0) { for (so in secondary) { val chance = this.getWorld().rand.nextFloat() // TeslaThingiesMod.logger.info("Change: " + chance + " vs " + so.chance); if (chance <= so.chance) { var thing = so.getPossibleOutput() if (!ItemStackUtil.isEmpty(thing)) { thing = ItemHandlerHelper.insertItem(this.outputs, thing.copy(), false) if (!ItemStackUtil.isEmpty(thing)) { val spawnPos = this.pos.offset(super.facing) this.getWorld().spawnEntity( EntityItem(this.getWorld(), spawnPos.x.toDouble(), spawnPos.y.toDouble(), spawnPos.z.toDouble(), thing)) } super.forceSync() } } } } } this.currentItem!!.setStackInSlot(0, ItemStack.EMPTY) } override val energyOutputRate: Long get() = 40 override val energyFillRate: Long get() = 40 } <file_sep>/src/main/kotlin/net/ndrei/teslapoweredthingies/TeslaThingiesMod.kt package net.ndrei.teslapoweredthingies import net.minecraft.creativetab.CreativeTabs import net.minecraft.item.ItemStack import net.minecraft.world.World import net.minecraft.world.WorldServer import net.minecraftforge.common.util.FakePlayer import net.minecraftforge.common.util.FakePlayerFactory import net.minecraftforge.fluids.FluidRegistry import net.minecraftforge.fml.common.Mod import net.minecraftforge.fml.common.SidedProxy import net.minecraftforge.fml.common.event.FMLConstructionEvent import net.minecraftforge.fml.common.event.FMLInitializationEvent import net.minecraftforge.fml.common.event.FMLPostInitializationEvent import net.minecraftforge.fml.common.event.FMLPreInitializationEvent import net.ndrei.teslapoweredthingies.common.CommonProxy import net.ndrei.teslapoweredthingies.items.TeslaPlantSeeds import net.ndrei.teslapoweredthingies.machines.fluidburner.FluidBurnerBlock import org.apache.logging.log4j.Logger /** * Created by CF on 2017-06-30. */ @Mod(modid = MOD_ID, version = MOD_VERSION, name = MOD_NAME, dependencies = MOD_DEPENDENCIES, acceptedMinecraftVersions = MOD_MC_VERSION, useMetadata = true, modLanguage = "kotlin", modLanguageAdapter = "net.shadowfacts.forgelin.KotlinAdapter") object TeslaThingiesMod { const val MODID = MOD_ID @SidedProxy(clientSide = "net.ndrei.teslapoweredthingies.client.ClientProxy", serverSide = "net.ndrei.teslapoweredthingies.common.CommonProxy") lateinit var proxy: CommonProxy lateinit var logger: Logger val creativeTab: CreativeTabs = object : CreativeTabs("Tesla Powered Thingies") { override fun getIconItemStack() = ItemStack(FluidBurnerBlock) override fun getTabIconItem() = this.iconItemStack } @Mod.EventHandler fun construction(event: FMLConstructionEvent) { // Use forge universal bucket FluidRegistry.enableUniversalBucket() } @Mod.EventHandler fun preInit(event: FMLPreInitializationEvent) { TeslaThingiesMod.logger = event.modLog proxy.preInit(event) } @Mod.EventHandler fun init(e: FMLInitializationEvent) { proxy.init(e) TeslaPlantSeeds.registerSeeds() } @Mod.EventHandler fun postInit(e: FMLPostInitializationEvent) { proxy.postInit(e) } private val fakePlayers = mutableMapOf<String, FakePlayer>() fun getFakePlayer(world: World?): FakePlayer? { val key = if (world != null && world.provider != null) String.format("%d", world.provider.dimension) else null if (key != null) { if (fakePlayers.containsKey(key)) { return fakePlayers[key] } if (world is WorldServer) { val player = FakePlayerFactory.getMinecraft(world) // FakePlayer(world, ) fakePlayers[key] = player return player } } return null } } <file_sep>/changelog.md # 1.0.7 - fixed 'powered kiln' recipes to support vanilla items - 'item compound producer' is no longer WIP - 'fluid solidifier' JEI screen got an update # 1.0.8 - added 'fluid compound producer' (combines fluids into other fluids) - added config files for extra recipes to various machines - "{registry_name}-base.json" - this is the default recipes config generated by the mod - "{registry_name}-extra.json" - extra recipes file that is loaded, if it exists, but will never be created/overwrited by the mod - check "-base.json" files for examples of the recipe structure
5582186b9f9525d0016ad201a8e1ce36e56192a2
[ "Markdown", "Kotlin" ]
14
Kotlin
TeamAvion/Tesla-Powered-Thingies
702e0b3a2a2759d2affc0f27b80adddb3df53686
66a0b2584ed31409c06aff786bd19bda513f4a31
refs/heads/master
<file_sep>#pragma once #include "BinaryNode.h" #include <queue> class BinaryTree { private: BinaryNode* m_root; public: BinaryTree(int data); ~BinaryTree(); BinaryNode* GetRoot(); void push(int data); std::queue<int> BFExplore(); BinaryNode* RecursiveSearch(int value, BinaryNode* start); };<file_sep>#include <iostream> #include <vector> #include "sort.h" #include "Tree.h" #include "BinaryTree.h" int main() { BinaryTree tree = BinaryTree(10); tree.push(5); tree.push(7); tree.push(11); tree.push(3); /*std::vector<int> arr{ 5, 3, 6, 1, 0}; //std::vector<char> arrC{ '#','o', '#','o', '#','o', '#','o', '#','o', '#','o'}; for (int i = 0; i < arr.size(); i++) { std::cout << arr[i] << "-"; } /*sort::mergeSort(arr); std::cout << "\n"; for (int i = 0; i < arr.size(); i++) { std::cout << arr[i] << "-"; }*/ //std::cout << "\n" << others::max(arr); /*Tree tree = Tree(1); tree.GetRoot()->SetLeftChild(1); tree.GetRoot()->SetRightChild(2); tree.GetRoot()->GetLeftChild()->SetLeftChild(3); tree.GetRoot()->GetLeftChild()->GetLeftChild()->SetLeftChild(4);*/ std::queue<int> bfs = tree.BFExplore(); BinaryNode* node = tree.RecursiveSearch(7, tree.GetRoot()); std::cout << node << "\n"; std::cout << node->GetData() << "\n"; while (!bfs.empty()) { std::cout << bfs.front() << " "; bfs.pop(); } //std::cout << others::fibonacci(50); } <file_sep>#include "BinaryNode.h" BinaryNode::BinaryNode(int data) : m_data{data} { m_leftChild = nullptr; m_rightChild = nullptr; } void BinaryNode::SetLeftChild(BinaryNode* node) { m_leftChild = node; } void BinaryNode::SetLeftChild(int data) { m_leftChild = new BinaryNode(data); } void BinaryNode::SetRightChild(BinaryNode* node) { m_rightChild = node; } void BinaryNode::SetRightChild(int data) { m_rightChild = new BinaryNode(data); } void BinaryNode::SetData(int data) { m_data = data; } int BinaryNode::GetData() { return m_data; } BinaryNode* BinaryNode::GetLeftChild() { return m_leftChild; } BinaryNode* BinaryNode::GetRightChild() { return m_rightChild; } BinaryNode::~BinaryNode() { delete m_leftChild; delete m_rightChild; } <file_sep>#pragma once class BinaryNode { private: int m_data; BinaryNode* m_leftChild; BinaryNode* m_rightChild; public: BinaryNode(int data); void SetLeftChild(BinaryNode* node); void SetLeftChild(int data); void SetRightChild(BinaryNode* node); void SetRightChild(int data); void SetData(int data); int GetData(); BinaryNode* GetLeftChild(); BinaryNode* GetRightChild(); ~BinaryNode(); }; <file_sep>#include "sort.h" void sort::selection(std::vector<int>& arr) { int n = arr.size(); for (int i = 0; i < n-1; i++) { int min = i; for (int j = 0; j < n; j++) { if (arr[j] < arr[min]) min = j; } if (i != min) { int temp = arr[min]; arr[min] = arr[i]; arr[i] = temp; } } } void sort::bubble(std::vector<int>& arr) { int n = arr.size(); for (int i = n; i > 1; i--) { bool sorted = true; for (int j = 0; j < i-1; j++) { if (arr[j+1] < arr[j]) { int temp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = temp; sorted = false; } } if (sorted) return; } } void sort::sortchars(std::vector<char>& arr) { int n = arr.size(); for (int i = n; i > 1; i--) { bool sorted = true; for (int j = 0; j < i-1; j++) { if (arr[j+1] == '#') { int temp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = temp; sorted = false; } } if (sorted) return; } } void sort::merge(std::vector<int>& input1, std::vector<int>& input2, std::vector<int>& output) { int i = 0; int j = 0; int k = 0; while (i < input1.size() && j < input2.size()) { if (input1[i] < input2[j]) { output[k] = input1[i]; i++; } else { output[k] = input2[j]; j++; } k++; } if (i == input1.size()) { for (int c = j; c < input2.size(); c++) { output[k] = input2[c]; k++; } } else { for (int b = i; b < input1.size(); b++) { output[k] = input1[b]; k++; } } } void sort::mergeSort(std::vector<int>& input) { std::vector<int> B{}; std::vector<int> C{}; if (input.size() > 1) { for (int i = 0; i < input.size()/2; i++) { B.push_back(input[i]); } for (int i = input.size()/2; i < input.size(); i++) { C.push_back(input[i]); } mergeSort(B); mergeSort(C); merge(B, C, input); } } int others::fibonacci(int n) { if (n == 0) return 0; if (n == 1) return 1; return fibonacci(n - 1) + fibonacci(n - 2); } int others::max(std::vector<int>& input) { if (input.size() > 2) { std::vector<int> B{}; std::vector<int> C{}; for (int i = 0; i < input.size() / 2; i++) { B.push_back(input[i]); } for (int i = input.size() / 2; i < input.size(); i++) { C.push_back(input[i]); } int maxB = max(B); int maxC = max(C); if (maxB > maxC) return maxB; else return maxC; } else if (input.size() == 2) { if (input[0] > input[1]) return input[0]; else return input[1]; } else { return input[0]; } }<file_sep>#include "BinaryTree.h" BinaryTree::BinaryTree(int data) { m_root = new BinaryNode(data); } BinaryNode* BinaryTree::GetRoot() { return m_root; } BinaryTree::~BinaryTree() { delete m_root; } void BinaryTree::push(int data) { BinaryNode* node = m_root; while (true) { if (data > node->GetData()) { if (node->GetRightChild() == nullptr) { node->SetRightChild(new BinaryNode(data)); return; } else { node = node->GetRightChild(); } } else if (data < node->GetData()) { if (node->GetLeftChild() == nullptr) { node->SetLeftChild(new BinaryNode(data)); return; } else { node = node->GetLeftChild(); } } else return; } } std::queue<int> BinaryTree::BFExplore() { std::queue<BinaryNode*> visited = {}; std::queue<int> output = {}; visited.push(m_root); output.push(m_root->GetData()); while (!visited.empty()) { BinaryNode* v = visited.front(); visited.pop(); BinaryNode* adjacentEdges[2] = { v->GetLeftChild(), v->GetRightChild() }; for (BinaryNode* edge : adjacentEdges) { if (edge != nullptr) { visited.push(edge); output.push(edge->GetData()); } } } return output; } BinaryNode* BinaryTree::RecursiveSearch(int value, BinaryNode* start) { if (start == nullptr) return nullptr; if (value == start->GetData()) return start; if (value > start->GetData()) RecursiveSearch(value, start->GetRightChild()); if (value > start->GetData()) RecursiveSearch(value, start->GetLeftChild()); }<file_sep>#include "Tree.h" #include "BinaryNode.h" #include <queue> Tree::Tree(int data) { m_root = new BinaryNode(data); } BinaryNode* Tree::GetRoot() { return m_root; } std::queue<int> Tree::BFSearch() { std::queue<BinaryNode*> visited = {}; std::queue<int> output = {}; visited.push(m_root); output.push(m_root->GetData()); while (!visited.empty()) { BinaryNode* v = visited.front(); visited.pop(); BinaryNode *adjacentEdges[2] = { v->GetLeftChild(), v->GetRightChild() }; for (BinaryNode* edge : adjacentEdges) { if (edge != nullptr) { visited.push(edge); output.push(edge->GetData()); } } } return output; } Tree::~Tree() { delete m_root; }<file_sep>#pragma once #include "BinaryNode.h" #include <queue> class Tree { private: BinaryNode* m_root; public: Tree(int data); ~Tree(); BinaryNode* GetRoot(); std::queue<int> BFSearch(); };<file_sep>#pragma once #include <vector> namespace sort { void selection(std::vector<int>& arr); void bubble(std::vector<int>& arr); void sortchars(std::vector<char>& arr); void mergeSort(std::vector<int>& input); void merge(std::vector<int>& input1, std::vector<int>& input2, std::vector<int>& output); } namespace others { int fibonacci(int n); int max(std::vector<int>& input); }
6449867a9902b05084380ff5d3fbd180a673d233
[ "C++" ]
9
C++
MyNamesRaph/Algorithms
5dbc40edcc43c87c0e167b5ac69763d6651c4a71
5fc7f8c95cdac7fc18922fc04c30ccc0d7a9fda0
refs/heads/master
<file_sep>const video = document.querySelector("#video"); //var remoteControl = new RemoteControl(video); var recognition = new webkitSpeechRecognition(); const Http = new XMLHttpRequest(); recognition.continuous = true; recognition.interimResults = true; recognition.lang = "en-US"; recognition.continuous = true; recognition.start(); //responsiveVoice.speak("hello world"); recognition.onresult = (event) => { for (let i = event.resultIndex; i < event.results.length; ++i) { if (event.results[i].isFinal) { console.log(event.results[i][0]); $("p").text(event.results[i][0].transcript.trim()); if (event.results[i][0].transcript.trim() == "open") { const url = 'https://localhost:8000/test'; Http.open("GET", url); Http.send(); console.log('sent') Http.onreadystatechange = (e) => { if (Http.responseText) { $("p").text("Server answer is " + Http.responseText); //responsiveVoice.speak("Server answer is " + Http.responseText); } else { $("p").text("Server is down cannot be proceed"); //responsiveVoice.speak("Server is down cannot be proceed"); } } } else if (event.results[i][0].transcript.trim() == "info") { const url = 'http://localhost:8001/info'; Http.open("GET", url); Http.send(); console.log('sent') Http.onreadystatechange = (e) => { console.log(Http.responseText); $("p").text("Server answer is " + Http.responseText + "."); } } } } }<file_sep>const express = require('express'); const http = require('http'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser({ extended: true })); app.use(express.static(__dirname + '/public')); http.createServer(app).listen(8001, () => { console.log('Server started on port ' + 8001); }); app.get('/', (req, res) => { res.sendFile(__dirname + '/public/index.html'); }); app.get('/info', (req, res) => { var osvar = process.platform; res.send(osvar); });
e632716fe9fe0af4c66e5630d7ac5af9ea0b2a5e
[ "JavaScript" ]
2
JavaScript
aliasosx/letterp-voice
91d3ba6dae3addaf519a150cbc8c7ba2ab19f1b2
5910f84d7bb2698c8c07b2fae70440c14ae65752
refs/heads/main
<repo_name>Montasir-Rishad/Software-Project-I--20201009<file_sep>/Software Project(I)/Telephone Bill.c #include<stdio.h> #include<conio.h> #include<string.h> #include<stdlib.h> #include<time.h> #include<windows.h> #include<process.h> #define LEN 20 int r,q; void gotoxy(int x,int y){ COORD coord; coord.X=x; coord.Y=y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord); } int custNameValidation(char *str)//Customer-Name validation { int j; for(j=0; j<strlen(str); j++ ) { if(!((str[j]>=65 && str[j]<=90)||(str[j]>96 && str[j]<123)||str[j]==46||str[j]==45)||strlen(str)>8 ) { //printf(" Error !!!\n"); break; } } if(j==strlen(str)) return 1; else return 0; } int customerAddValidation(char *str)//Customer-address validation { int j; for(j=0; j<strlen(str); j++ ) { //if(!((str[j]>=65 && str[j]<=90)||(str[j]>96 && str[j]<123)||str[j]==46||str[j]==45)||strlen(str)>8 ) //if(!((str[j]>=65 && str[j]<=90)||(str[j]>96 && str[j]<123)||str[j]==46||str[j]==45)||strlen(str)>10 ) if(!((str[j]>=65 && str[j]<=90)||(str[j]>=48 && str[j]<=57)||(str[j]>96 && str[j]<123)||(str[j]>=44 && str[j]<=47)||str[j]==35||str[j]==59)||strlen(str)>10) { //printf(" Error !!!\n"); break; } } if(j==strlen(str)) return 1; else return 0; } /////// int telNumberValidation(char *str)//Telephone Number Validation { int j; for(j=0; j<strlen(str); j++) { if(!((str[j]>=48 && str[j]<=57)||str[j]==43)||strlen(str)!=8 ) { break; } } if(j==strlen(str)) return 1; else return 0; } int callMinuteValidation(char *str)// Minute validation { int j; for(j=0; j<strlen(str); j++) { if(!((str[j]>=48 && str[j]<=57)||str[j]==46)||strlen(str)>5 ) { break; } } if(j==strlen(str)) return 1; else return 0; } /// int customerNumValidation(char *str)//Customer Number Validation { int j; for(j=0; j<strlen(str); j++) { if(!(str[j]>=48 && str[j]<=57)||strlen(str)>6 ) { break; } } if(j==strlen(str)) return 1; else return 0; } /// int main() { char pass[LEN]; char ch=0; int i=0,ck=0,flag=1,month_num; float pwd; char A[100]="rishad",B[100],strMonth[100],minStr[100]; char custname1[20],custname2[20],custname3[20], address1[20], address2[20],address3[20]; char telnumber[15],date[15],month[20]; char customernum[15]; float minlocal,minnwd,minisd,tlocal,tnwd,tisd,stotal,gtotal,vat; float monthlyrent=100.00,ratelocal=1.50,ratenwd=3.50,rateisd=6.0; time_t now ; struct tm *info; char buffer[80]; time(&now); info = localtime( &now ); strftime(buffer,80,"%x", info); printf("\n\tExecuting Time \t\t\t: %s",ctime(&now)); /*MY CSE PROJECT<MONTASIR..17102033.DATE of COMPLETION: 13/10/17-16/03/18.[FRIDAY]. Last Update : 30-MARCH-2018.[FRIDAY]. Submission TO: <NAME>. //<NAME>*/ printf("\n\n\tEnter USER_NAME\t\t\t:\a "); scanf("%s",&B); if(strcmpi(A,B)==0) { printf("\n\a\t^^^^^^^^^^^Welcome Mr. <NAME>^^^^^^^^^^^\a\n"); while(i<LEN) pass[i++]='\0'; printf("\n\n\tPASSWORD\t\t :\a \t"); ch=getch(); i=0; while((ch!='\r')) { if(ch!='\b') { pass[i++]=ch; putch('*'); } else { if(i>0) { pass[--i]='\0'; putch(ch); putch(' '); putch(ch); } } ch=getch(); } if(strcmp(pass,"1234")==0) { //scanf("%f",&pwd); //if(pwd==1234){ printf("\n\n\t^^^^^^^^^^^CONGRATULATIONS.PASSWORD IS CORRECT^^^^^^^^^^^\n\a\a\a"); printf("\n\t\t(-_-) YOU ARE WELCOME__FILL UP THE DIRECTORY BELOW (-_-)\n\n\n\a\a\a"); system("pause"); system("cls"); while(1) { flag=1; while(flag) { printf("\n\n\n\n\n\n\n\n\n\n\n\t\t\tEnter Customer No: "); scanf("%s",customernum); ck=customerNumValidation(customernum); if(ck) { break; } else printf("Error!\n"); } system("cls"); flag=1; while(flag) { printf("Full name of the CUSTOMER (%s) :\a "); scanf("%s%s%s",&custname1,&custname2,&custname3); ck=custNameValidation(custname1); if(ck) { ck=custNameValidation(custname2); if(ck) { ck=custNameValidation(custname3); if(ck) { flag=0; } else printf("Error!\n"); } else printf("Error!\n"); } else printf("Error!\n"); } printf("Date of Bill\t\t :\a "); printf("%s\n", buffer ); //printf("\t : %s",ctime(&now)); //scanf("%s",&date); flag=1; while(flag) { printf("Address\t\t\t :\a "); scanf("%s%s%s",&address1,&address2,address3); ck=customerAddValidation(address1); if(ck) { ck=customerAddValidation(address2); if(ck) { ck=customerAddValidation(address3); if(ck) { flag=0; } else printf("Error!\n"); } else printf("Error!\n"); } else printf("Error!\n"); } ///// flag=1; while(flag) { printf("Telephone number(last 8 dig) :+88044\a"); scanf("%s",telnumber); ck=telNumberValidation(telnumber); if(ck) { break; } else printf("Error!\n"); } flag =1; while(flag) { printf("MONTH (press :1-12)\t :\a "); scanf("%s",&strMonth); flag=0; if((strcmp(strMonth,"1")==0)) printf("\tJanuary.\n"); else if((strcmp(strMonth,"2")==0)) printf("\tFEBRUARY.\n"); else if((strcmp(strMonth,"3")==0)) printf("\tMARCH.\n"); else if((strcmp(strMonth,"4")==0)) printf("\tAPRIL.\n"); else if((strcmp(strMonth,"5")==0)) printf("\tMAY.\n"); else if((strcmp(strMonth,"6")==0)) printf("\tJUNE.\n"); else if((strcmp(strMonth,"7")==0)) printf("\tJULY.\n"); else if((strcmp(strMonth,"8")==0)) printf("\tAUGUST.\n"); else if((strcmp(strMonth,"9")==0)) printf("\tSEPTEMBER.\n"); else if((strcmp(strMonth,"10")==0)) printf("\tOCTOBER.\n"); else if((strcmp(strMonth,"11")==0)) printf("\tNOVEMBER.\n"); else if((strcmp(strMonth,"12")==0)) printf("\tDECEMBER.\n"); else { flag=1; printf("Error!\n"); } } printf("\n"); flag=1; while(flag) { printf("Minutes in LOCAL call\t :\a "); scanf("%s",&minStr); ck=callMinuteValidation(minStr); if(ck) { minlocal=(float)atof(minStr); break; } else printf("Error!\n"); } flag=1; while(flag) { printf("Minutes in NWD call \t :\a "); scanf("%s",&minStr); ck=callMinuteValidation(minStr); if(ck) { minnwd=(float)atof(minStr); break; } else printf("Error!\n"); } flag=1; while(flag) { printf("Minutes in ISD call \t :\a "); scanf("%s",&minStr); ck=callMinuteValidation(minStr); if(ck) { minisd=(float)atof(minStr); break; } else printf("Error!\n"); } tlocal=minlocal*ratelocal; tnwd=minnwd*ratenwd; tisd=minisd*rateisd; stotal=tlocal+tnwd+tisd+monthlyrent; vat=stotal*0.30; gtotal=stotal+vat; //int r,q; gotoxy(32,36); printf("Loading....."); gotoxy(32,38); for(r=1;r<=20;r++) { for(q=0;q<=10000000;q++);{ printf("%c",177); printf("%c",177); } } system("cls"); printf("\n\n\n\n*************************TELEPHONE BILL*************************\n\n\n"); //printf("\n\n\n\t\t\t*****TELEPHONE BILL*****\n\n\n"); //printf("\t\t\tFor the month : %dth",(month_num)); printf("\t\t\tFor the month : %sth",(strMonth)); //strMonth[100] printf("\n.............................................................\n"); printf("Name : %s %s %s",custname1,custname2,custname3); //printf("%s\n", buffer ); printf("\t\t\tDate : %s",buffer); printf("\nAddress: %s %s %s",address1,address2,address3); //printf("\t\t\tDate : %s",buffer); //printf("\nAddress: %s %s %s",address1,address2,address3); printf("\t\t\tTelephone: +8809%s",telnumber); printf("\n\n\nType\t\tMINUTE\t\tRate\t\tTotal TK"); printf("\n\n........................................................"); printf("\nLocal"); printf("\t\t%0.1f",minlocal); printf("\t\t%0.1f",ratelocal); printf("\t\t%0.1f",tlocal); printf("\nNWD"); printf("\t\t%0.1f",minnwd); printf("\t\t%0.1f",ratenwd); printf("\t\t%0.1f",tnwd); printf("\nForeign"); printf("\t\t%0.1f",minisd); printf("\t\t%0.1f",rateisd); printf("\t\t%0.1f",tisd); printf("\nMonthly Rent\t\t\t100.00"); printf("\nVAT\t\t\t\t%0.2f",vat); printf("\n........................................................\n"); printf("Grand Total: \t\t\t\t In TK:%0.2f\n\n\n\a\a\a",gtotal); system("pause"); system("cls"); } } else { printf("\n\t\tError..PASSWORD"); main(); } } else { printf("\n\t\tError..USER_NAME"); main(); } getch(); return 0; }
30ecdc7afeb8802d38be4e078ddff5b33048f56a
[ "C" ]
1
C
Montasir-Rishad/Software-Project-I--20201009
a9051a5245658cce910109af276ae53121df9491
9b1346bcf8b38466a25b2d4526ef3ff3fd08e05c
refs/heads/main
<repo_name>Aarmaaa/Book-Donation-93<file_sep>/Donate.js import React from 'react'; import { StyleSheet, Text, View , FlatList, TouchableOpacity} from 'react-native'; import {ListItem} from "react-native-elements"; import firebase from "firebase"; import db from '../config'; export default class Donate extends React.Component { constructor(){ super() this.state={ requestedBooks: [] } } getRequestedBooks=()=>{ db.collection("requested_books").onSnapshot((doc)=>{ var requestedBooks = doc.docs.map(document=> document.data()) this.setState({ requestedBooks: requestedBooks }) }) } componentDidMount(){ this.getRequestedBooks(); } keyExtractor=(item, index)=> index.toString(); renderItem=(item, index)=>{ return( <ListItem key={index} title={item.book_name} subtitle={item.reason} titleStyle={{color:"black", fontWeight:"bold"}} bottomDivider rightElement={ <TouchableOpacity style={styles.button} > <Text style = {{color: "#ffff"}}>view</Text> </TouchableOpacity> } /> ) } render(){ return ( <View style={styles.container}> <View style={styles.headerContainer} > <Text style = {styles.title}>Donate Books</Text> </View> <View style = {{flex: 1}}> {this.state.requestedBooks.length === 0 ? (<View><Text style = {{fontSize: 20}}>No Request Aviable </Text></View>) : ( <FlatList keyExtractor={this.keyExtractor} data={this.state.requestedBooks} renderItem={this.renderItem} /> )} </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, title :{ fontSize:65, fontWeight:'300', paddingBottom:30, color : '#ff3d00', }, headerContainer:{ flex:0.4, justifyContent:'center', alignItems:'center', }, button:{ width:100, height:30, justifyContent:'center', alignItems:'center', backgroundColor:"#ff5722", shadowColor: "#000", shadowOffset: { width: 0, height: 8 } } })<file_sep>/App.js import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import {createSwitchNavigator,createAppContainer} from 'react-navigation' import Login from './Screens/Login'; import Donate from './Screens/Donate'; import DrawerNavigator from './Navigation/DrawerNavigator'; export default function App() { return ( /* <AppConatiner/> ); */ <Donate/> ) } const switchNavigator = createSwitchNavigator({ Login: {screen: Login}, DrawerNavigator: {screen: DrawerNavigator} }) const AppConatiner = createAppContainer(switchNavigator) <file_sep>/DrawerNavigator.js import React from "react"; import {createDrawerNavigator} from 'react-navigation-drawer'; import { Tab } from "./TabNavigator"; import SideBarMenu from './SideBarMenu'; export const Drawer = createDrawerNavigator({ Home: {screen: Tab}}, { contentComponent:SideBarMenu }, { initialRouteName: "Home" } )<file_sep>/Request.js import React from 'react'; import { StyleSheet, Text, View,TextInput, TouchableOpacity, KeyboardAvoidingView, Alert } from 'react-native'; import firebase from 'firebase'; import db from '../config'; export default class Request extends React.Component { constructor(){ super() this.state={ userId: firebase.auth().currentUser.email, bookName: "", reasonToRequest: "" } } addRequest=(bookName, reason)=>{ db.collection("requested_books").add({ user_id : this.state.userId, book_name : this.state.bookName, reason : this.state.reasonToRequest, request_id : this.createUniqueId() }) Alert.alert("Book requested Succesfully") this.setState({ bookName : "", reasonToRequest: "", }) } createUniqueId(){ return Math.random().toString(36) } render(){ return ( <View style={styles.container}> <View style={styles.headerContainer} > <Text style = {styles.title}>Request Book</Text> </View> <KeyboardAvoidingView style = {styles.keyBoardStyle}> <TextInput placeholder="Book Name" style={styles.inputs} onChangeText={(data)=>{ this.setState({ bookName: data }) }} value={this.state.bookName} /> <TextInput placeholder="Why do do need the book" style={[styles.inputs, {height: 300}]} onChangeText={(data)=>{ this.setState({ reasonToRequest: data }) }} value={this.state.reasonToRequest} multiline={true} numberOfLines={8} /> <TouchableOpacity style={styles.button} > <Text>Confirm Request</Text> </TouchableOpacity> </KeyboardAvoidingView> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, title :{ fontSize:65, fontWeight:'300', paddingBottom:30, color : '#ff3d00', }, headerContainer:{ flex:0.4, justifyContent:'center', alignItems:'center', }, inputs:{ width:"75%", height:35, alignSelf:'center', borderColor:'#ffab91', borderRadius:10, borderWidth:1, marginTop:20, padding:10, }, keyBoardStyle : { flex:1, alignItems:'center', justifyContent:'center' }, button:{ width:"75%", height:50, justifyContent:'center', alignItems:'center', borderRadius:10, backgroundColor:"#ff5722", shadowColor: "#000", shadowOffset: { width: 0, height: 8, }, shadowOpacity: 0.44, shadowRadius: 10.32, elevation: 16, marginTop:20 }, })<file_sep>/SettingScreen.js import React from 'react'; import {View, Text} from 'react-native'; import firebase from "firebase"; import db from '../config'; export default class Setting extends React.Component{ constructor(){ super() this.state={ emailId: "", first_name: "", last_name:"", address: "", contact: "" } } getUserDetails=() => { var email = firebase.auth().currentUser.email db.collection('users').where('email_id', '==', email ).get() .then((document) => { document.forEach((doc) => { var data = doc.data() this.setState({ emailId: data.email_id, first_name: data.first_name, last_name: data.last_name, address: data.address, contact: data.contact }) }) }) } componentDidMount(){ this.getUserDetails(); } render(){ return( <View> {/* i have to do it */} </View> ) } }
fce567690bdb0cd12bd5a591320150de7e842adb
[ "JavaScript" ]
5
JavaScript
Aarmaaa/Book-Donation-93
1c80ec1dda02382e1fdbfd6e936b50a0fe14cfd5
3e41f1d6cab859e006eef38f1f8beb4275288424
refs/heads/master
<repo_name>dupontdenis/update-courses-mongodb<file_sep>/app_api/controllers/courses.js const mongoose = require('mongoose'); const Courses = require('../models/courses'); mongoose.connect('mongodb://localhost/my_courses', { useUnifiedTopology: true, useNewUrlParser: true }); const debug = require('debug')('app_api'); const coursesReadAll = async (req, res) => { debug("API--- coursesReadAll ---"); const courses = await Courses.find({}); res.json({ courses: courses }); } const coursesCreateOne = async (req, res) => { debug("API--- coursesCreateOne ---"); await Courses.create(req.body, (error, course) => { res.json(course); }) } const coursesReadOne = async (req, res) => { debug("API--- coursesReadOne ---"); const course = await Courses.findById(req.params.id) if (!course) res.status(404).send(`The course with id:${req.params.id} was not found`) res.send(course); } const coursesUpdateOne = async (req, res) => { debug("API--- coursesUpdateOne ---"); const course = new Courses( { name: req.body.name, info: req.body.info, _id: req.params.id } ); Courses.findByIdAndUpdate(req.params.id, course, {}, function (err, thecourse) { if (err) { return next(err); } // Successful - redirect to genre detail page. res.send(thecourse); }); } const coursesDeleteOne = async (req, res) => { debug("API--- coursesDeleteOne ---"); const course = await Courses.findByIdAndDelete(req.params.id) if (!course) res.status(404).send(`The course with id:${req.params.id} was not found`) res.send(null); } module.exports = { coursesReadAll, coursesCreateOne, coursesReadOne, coursesUpdateOne, coursesDeleteOne };<file_sep>/public/javascripts/delete.js //const axios = require('axios'); console.log("bravo"); document.querySelector(".delete").addEventListener("click",()=>{ console.log('super'); })<file_sep>/app_api/routes/index.js const express = require('express'); const router = express.Router(); const ctrlCourses = require('../controllers/courses'); router .route('/courses') .get(ctrlCourses.coursesReadAll) .post(ctrlCourses.coursesCreateOne); router .route('/courses/:id') .get(ctrlCourses.coursesReadOne) .put(ctrlCourses.coursesUpdateOne) .delete(ctrlCourses.coursesDeleteOne) module.exports = router;
10924d9e22743f54f276f0d1a856f6347dca24f9
[ "JavaScript" ]
3
JavaScript
dupontdenis/update-courses-mongodb
295dc3ca8957cc8030ffd60da0478cecccd13fdb
2edfaaf0de2a4f060bc6425a628e704ab98eccb3
refs/heads/master
<repo_name>r2dev/fakejira<file_sep>/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; // import firebase from 'firebase'; // const config = { // apiKey: '', // databaseURL: 'https://tracking-6329f.firebaseio.com/', // }; // firebase.initializeApp(config); // const database = firebase.database(); // database.ref('task').set([1,2,3]) ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister(); <file_sep>/src/App.js import React, { Component } from "react"; import Column from "./components/Column"; /** * @todo * 1. adding column and task, change order, change type */ export default class App extends Component { state = { value: "", dropdownV: "", todo: { order: ["s1", "s2", "s3", "s4", "s5", "s6", "s7"], s1: 21, s2: 22, s3: 33, s4: 44, s5: 55, s6: 66, s7: 77 }, column: ["todo", "in progress", "completed"] }; componentDidMount() {} componentWillUnmount() {} handleInput = e => { this.setState({ value: e.target.value }); }; handleDropdownChange = e => { this.setState({ dropdownV: e.target.value }); }; render() { return ( <div> {/* <form onSubmit={this.handleSubmit}> <input value={this.state.value} onChange={this.handleInput} /> <select value={this.state.dropdownV} onChange={this.handleDropdownChange} > <option value="">-select-</option> {this.state.column.map(item => ( <option value={item}>{item}</option> ))} </select> <input type="submit" value="submit" /> </form> */} <div style={{ height: "80vh", width: "100%", maxWidth: "100vw", backgroundColor: "#ffb6c1", padding: "16px 0", overflowX: "auto", display: "flex" }} > {/* {this.state.column.map(item => ( */} <Column title={"todo"} data={this.state.todo.order.map(item => this.state.todo[item])} /> {/* ))} */} </div> </div> ); } }
762a6c8d9209cdc7e79ab9648f6de0dfcbce8898
[ "JavaScript" ]
2
JavaScript
r2dev/fakejira
8fb74d00baab85ce8f50b473f7898bc1f221ce9c
045beb42e50a3f717eba8266eb6447b1730abc45
refs/heads/master
<file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Factories\HasFactory; class Pet extends Model { use HasFactory; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'subscription_id', 'name', 'gender', 'photo', 'breed', 'birth_date', 'lifestage', 'activity', 'body_type', 'weight', ]; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = [ 'subscription_id', ]; public function subscription(){ return $this->belongsTo(Subscription::class); } public function customer(){ return $this->hasOneThrough(Subscription::class, Customer::class); } } <file_sep><?php use Laravel\Lumen\Testing\DatabaseMigrations; use Laravel\Lumen\Testing\DatabaseTransactions; class CustomerTest extends TestCase { /** * A basic test example. * * @return void */ public function testExample() { $this->get('/customers/1'); $this->response->assertJson([ 'valid' => true, ]); } /** * /customers [GET] */ public function testShouldReturnAllCustomers(){ $this->get("customers", []); $this->seeStatusCode(200); } /** * /customers/id [GET] */ public function testShouldReturnCustomer(){ $this->get("customers/2", []); $this->seeStatusCode(200); } /** * /customers [POST] */ public function testShouldCreateCustomer(){ $parameters = [ 'name' => '<NAME>', 'gender' => 'female', 'birth_date' => '1999-07-28', 'email' => '<EMAIL>' ]; $this->post("customers", $parameters, []); $this->seeStatusCode(200); } /** * /customers/id [PUT] */ public function testShouldUpdateCustomer(){ $parameters = [ 'name' => '<NAME>', 'gender' => 'male', 'birth_date' => '1985-07-25' ]; $this->put("customers/4", $parameters, []); $this->seeStatusCode(200); } /** * /customers/id [DELETE] */ public function testShouldDeleteCustomer(){ $this->delete("customers/5", [], []); $this->seeStatusCode(410); } } <file_sep><?php namespace Database\Factories; use App\Models\Subscription; use App\Models\Customer; use Illuminate\Database\Eloquent\Factories\Factory; class SubscriptionFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Subscription::class; public function getWeight($price){ switch ($price) { case 20: return 3; break; case 30: return 6; break; case 45: return 12; break; } } /** * Define the model's default state. * * @return array */ public function definition() { $base_price = $this->faker->randomElement([20, 30, 45]); $last_order = $this->faker->dateTimeBetween('-1 month', '-1 day')->format('Y-m-d'); $discount = 15; // Percentual discount return [ 'customer_id' => $this->faker->unique()->numberBetween(1, Customer::count() - 1), 'base_price' => $base_price, 'total_price' => $base_price - ($base_price * ($discount / 100)), 'weight' => $this->getWeight($base_price), 'protein' => $this->faker->randomElement(['chicken', 'salmon']), 'last_order_date' => $last_order, 'next_order_date' => date('Y-m-d', strtotime($last_order . ' +4 weeks')), ]; } } <file_sep><?php use Laravel\Lumen\Testing\DatabaseMigrations; use Laravel\Lumen\Testing\DatabaseTransactions; class PetsTest extends TestCase { /** * /pets [GET] */ public function testShouldReturnAllPets(){ $this->get("pets", []); $this->seeStatusCode(200); } /** * /pets/id [GET] */ public function testShouldReturnPet(){ $this->get("pets/2", []); $this->seeStatusCode(200); } /** * /pets [POST] */ public function testShouldCreatePet(){ $parameters = [ 'subscription_id' => 3, 'name' => 'Thor', 'gender' => 'male', 'birth_date' => '2015-07-21', 'lifestage' => 'Senior', 'weight' => 19.00, 'photo' => '', 'breed' => 'Fila Brasileiro', 'activity' => 'Normal', 'body_type' => 'Normal' ]; $this->post("pets", $parameters, []); $this->seeStatusCode(200); } /** * /pets/id [PUT] */ public function testShouldUpdatePet(){ $parameters = [ 'name' => 'Thor', 'gender' => 'male', 'breed' => 'Fila Brasileiro', 'birth_date' => '2014-07-21', 'lifestage' => 'Senior', 'activity' => 'Normal', 'body_type' => 'Fat', 'weight' => 27, ]; $this->put("pets/4", $parameters, []); $this->seeStatusCode(200); } /** * /pets/id [DELETE] */ public function testShouldDeletePet(){ $this->delete("pets/5", [], []); $this->seeStatusCode(410); } } <file_sep><?php namespace App\Services; use App\Repositories\Contracts\SubscriptionRepositoryInterface; use Illuminate\Http\Request; use App\Models\Subscription; use Illuminate\Support\Facades\Validator; class SubscriptionService { private $subscriptionRepository; public function __construct(SubscriptionRepositoryInterface $subscriptionRepository) { $this->subscriptionRepository = $subscriptionRepository; } public function getAll(){ $subscriptions = $this->subscriptionRepository->getAll(); $data['valid'] = true; $data['data']['subscriptions'] = $subscriptions; return response()->json($data); } public function get($id){ $subscription = $this->subscriptionRepository->get($id); if($subscription){ $data['valid'] = true; $data['data']['subscription'] = $subscription; }else{ $data['valid'] = false; $data['errors'] = 'Subscription not found...'; } return response()->json($data); } public function store(Request $request){ $validator = Validator::make($request->all(), [ 'base_price' => 'required|numeric|between:20,45', 'total_price' => 'required|numeric|between:17,45', 'next_order_date' => 'required|date|date_format:Y-m-d|after_or_equal:tomorrow', ]); if ($validator->fails()) { $data['valid'] = false; $data['message'] = 'Validation fails!'; $data['errors'] = $validator->errors(); }else{ $has_subscription = $this->subscriptionRepository->getBy('customer_id', $request->get('customer_id')); if($has_subscription){ $data['valid'] = false; $data['errors'] = 'This customer already has a subscription...'; }else{ $subscription = $this->subscriptionRepository->store($request); if($subscription){ $data['valid'] = true; $data['message'] = 'Subscription has been created!'; $data['data']['subscription'] = $subscription; }else{ $data['valid'] = false; $data['errors'] = 'Subscription cannot be saved...'; } } } return response()->json($data); } public function update($id, Request $request){ $validator = Validator::make($request->all(), [ 'base_price' => 'numeric|between:20,45', 'total_price' => 'numeric|between:17,45', 'next_order_date' => 'required|date|date_format:Y-m-d|after_or_equal:tomorrow', ]); if ($validator->fails()) { $data['valid'] = false; $data['message'] = 'Validation fails!'; $data['errors'] = $validator->errors(); }else{ $subscription = $this->subscriptionRepository->update($id, $request); if($subscription){ $data['valid'] = true; $data['message'] = 'Subscription has been updated!'; $data['data']['subscription'] = $this->subscriptionRepository->get($id); }else{ $data['valid'] = false; $data['errors'] = 'Subscription cannot be updated...'; } } return response()->json($data); } public function destroy($id){ $subscription = $this->subscriptionRepository->get($id); if($subscription){ Subscription::where('id', $id)->delete(); $data['valid'] = true; $data['message'] = 'Subscription has been deleted!'; $data['data']['subscription'] = $subscription; return response()->json($data, 410); }else{ $data['valid'] = false; $data['errors'] = 'Subscription not found...'; return response()->json($data, 200); } } public function pets($id){ $subscription = $this->subscriptionRepository->get($id); if($subscription){ $data['valid'] = true; $data['data']['subscription'] = $subscription; $data['data']['subscription']['pets'] = $subscription->pets; }else{ $data['valid'] = false; $data['errors'] = 'Subscription pets not found...'; } return response()->json($data); } public function dispatch($id){ $subscription = $this->subscriptionRepository->get($id); if($subscription){ $subscription->update([ 'last_order_date' => date('Y-m-d'), 'next_order_date' => date('Y-m-d', strtotime('+ 4 weeks')) ]); $data['valid'] = true; $data['message'] = 'Subscription has been dispatched!'; $data['data']['subscription'] = $subscription; }else{ $data['valid'] = false; $data['errors'] = 'Subscription cannot be dispatched...'; } return response()->json($data); } }<file_sep><?php namespace App\Services; use App\Repositories\Contracts\PetRepositoryInterface; use Illuminate\Http\Request; use App\Models\Pet; use Illuminate\Support\Facades\Validator; class PetService { private $petRepository; public function __construct(PetRepositoryInterface $petRepository) { $this->petRepository = $petRepository; } public function getAll(){ $pets = $this->petRepository->getAll(); $data['valid'] = true; $data['data']['pets'] = $pets; return response()->json($data); } public function get($id){ $pet = $this->petRepository->get($id); if($pet){ $data['valid'] = true; $data['data']['pet'] = $pet; }else{ $data['valid'] = false; $data['errors'] = 'Pet not found...'; } return response()->json($data); } public function subscription($id){ $pet = $this->petRepository->get($id); if($pet){ $data['valid'] = true; $data['data']['pet'] = $pet; $data['data']['pet']['subscription'] = $pet->subscription; }else{ $data['valid'] = false; $data['errors'] = 'Subscription from this pet not found...'; } return response()->json($data); } public function store(Request $request){ $pet = $this->petRepository->store($request); if($pet){ $data['valid'] = true; $data['message'] = 'Pet has been created!'; $data['data']['pet'] = $pet; }else{ $data['valid'] = false; $data['errors'] = 'Pet cannot be saved...'; } return response()->json($data, 200); } public function update($id, Request $request){ $pet = $this->petRepository->update($id, $request); if($pet){ $data['valid'] = true; $data['message'] = 'Pet has been updated!'; $data['data']['pet'] = $this->petRepository->get($id); }else{ $data['valid'] = false; $data['errors'] = 'Pet cannot be updated...'; } return response()->json($data, 200); } public function destroy($id){ $pet = $this->petRepository->get($id); if($pet){ $this->petRepository->destroy($id); $data['valid'] = true; $data['message'] = 'Pet has been deleted!'; $data['data']['pet'] = $pet; }else{ $data['valid'] = false; $data['errors'] = 'Pet not found...'; } return response()->json($data, 410); } }<file_sep><?php namespace App\Models; use Illuminate\Auth\Authenticatable; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Laravel\Lumen\Auth\Authorizable; class Customer extends Model implements AuthenticatableContract, AuthorizableContract { use Authenticatable, Authorizable, HasFactory; const RULE_CUSTOMER = [ 'name' => 'required', 'birth_date' => 'required|date|date_format:Y-m-d|before:-18 years', 'gender' => 'required|in:male,female', 'email' => 'required|email|unique:customers' ]; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'gender', 'birth_date', 'email', ]; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = [ 'password', ]; public function subscription(){ return $this->hasOne(Subscription::class); } public function pets() { return $this->hasManyThrough(Pet::class, Subscription::class); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Services\CustomerService; class CustomerController extends Controller { private $customerService; public function __construct(CustomerService $customerService) { $this->customerService = $customerService; } public function index(){ return $this->customerService->getAll(); } public function show($id){ return $this->customerService->get($id); } public function store(Request $request){ return $this->customerService->store($request); } public function update($id, Request $request){ return $this->customerService->update($id, $request); } public function destroy($id){ return $this->customerService->destroy($id); } public function profile($id){ return $this->customerService->profile($id); } public function subscription($id){ return $this->customerService->subscription($id); } public function pets($id){ return $this->customerService->pets($id); } public function dispatch($id){ return $this->customerService->dispatch($id); } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePetsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('pets', function (Blueprint $table) { $table->id(); $table->bigInteger('subscription_id')->unsigned(); $table->foreign('subscription_id')->references('id')->on('subscriptions')->onDelete('cascade'); $table->string('name', 255); $table->enum('gender', ['male', 'female']); $table->date('birth_date')->nullable(); $table->enum('lifestage', ['Puppy', 'Adult', 'Senior'])->nullable(); $table->decimal('weight', 8, 2); $table->string('photo', 255)->nullable(); $table->string('breed', 255)->nullable(); $table->enum('activity', ['Lazy', 'Normal', 'Active'])->nullable(); $table->enum('body_type', ['Skinny', 'Normal', 'Fat'])->nullable(); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('pets'); } } <file_sep># Barkyn API ## Challenge resume: Create an rest API using PHP or Golang, that allows the management of customers, subscriptions and pets, in accordance with the specifications passed by Barkyn in [this link](https://gist.github.com/barkyndev/3048763d21f80a3b6355f10ee7510b6a). ## Technologies In this challenge I decided to use Lumen micro-framework by Laravel, widely used for creating APIs and microservices being one of the fastest micro-frameworks available. Documentation for the framework can be found on the [Lumen website](https://lumen.laravel.com/docs). The all what I used in this project was: Lumen micro-framework PHP - MySQL - Docker - PhpUnit - Postman ## Running the project 1 ```git clone <EMAIL>:ggwebdev/barkyn-gabriel.git``` 2 ```cd barkyn-gabriel``` 3 ```composer install``` to install Lumen dependencies 4 ```docker-compose up -d``` to up running the containers. 5 ```docker exec app-app php artisan migrate:fresh --seed --force``` to run migrations and seeds 6 ```docker exec app-app php vendor/phpunit/phpunit/phpunit``` to run the units tests 7 Import the ```Barkyn.postman_collection.json``` file, located in the project's root folder, into Postman to access the project's collections and see the API working! Thats all. I hope I have achieved the challenge objective. =) <NAME> <file_sep>version: '3' volumes: app-mysql-data: driver: local services: mysql: image: mysql:latest container_name: app-mysql volumes: - app-mysql-data:/var/lib/mysql ports: - "3307:3306" environment: - MYSQL_ROOT_PASSWORD=<PASSWORD> - MYSQL_DATABASE=barkyn - MYSQL_USER=barkyn - MYSQL_PASSWORD=<PASSWORD> app: image: ambientum/php:7.4-nginx tty: true container_name: app-app # command: bash -c "while true; do echo Barkyn is Up; sleep 2; done" volumes: - .:/var/www/app ports: - "8000:8080" links: - mysql <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Services\SubscriptionService; class SubscriptionController extends Controller { private $subscriptionService; public function __construct(SubscriptionService $subscriptionService) { $this->subscriptionService = $subscriptionService; } public function index(){ return $this->subscriptionService->getAll(); } public function show($id){ return $this->subscriptionService->get($id); } public function store(Request $request){ return $this->subscriptionService->store($request); } public function update($id, Request $request){ return $this->subscriptionService->update($id, $request); } public function destroy($id){ return $this->subscriptionService->destroy($id); } public function pets($id){ return $this->subscriptionService->pets($id); } public function dispatch($id){ return $this->subscriptionService->dispatch($id); } } <file_sep><?php namespace App\Repositories; use App\Repositories\Contracts\SubscriptionRepositoryInterface; use Illuminate\Http\Request; use App\Models\Subscription; class SubscriptionRepositoryEloquent implements SubscriptionRepositoryInterface { private $model; public function __construct(Subscription $subscription){ $this->model = $subscription; } public function getAll(){ return $this->model->all(); } public function get($id){ return $this->model->find($id); } public function getBy($key, $value){ return $this->model->where($key, $value)->first(); } public function store(Request $request){ return $this->model->create($request->all()); } public function update($id, Request $request){ return $this->model->find($id)->update($request->all()); } public function destroy($id){ return $this->model->find($id)->delete(); } }<file_sep><?php namespace Database\Factories; use App\Models\Pet; use App\Models\Subscription; use Illuminate\Database\Eloquent\Factories\Factory; class PetFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Pet::class; /** * Define the model's default state. * * @return array */ public function definition() { $ch = curl_init('https://dog.ceo/api/breeds/image/random'); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'GET', CURLOPT_RETURNTRANSFER => 1, ]); $response = json_decode(curl_exec($ch), true); curl_close($ch); $photo = $response['message']; $breed = explode('/', explode('/breeds/', $photo)[1])[0]; $gender = $this->faker->randomElement(['male', 'female']); return [ 'subscription_id' => $this->faker->numberBetween(1, Subscription::count()), 'name' => $this->faker->firstName($gender), 'gender' => $gender, 'photo' => $photo, 'breed' => ucwords(str_replace('-', ' ', $breed)), 'birth_date' => $this->faker->dateTimeBetween('-10 years', '-1 week')->format('Y-m-d'), 'lifestage' => $this->faker->randomElement(['Puppy', 'Adult', 'Senior']), 'activity' => $this->faker->randomElement(['Lazy', 'Normal', 'Active']), 'body_type' => $this->faker->randomElement(['Skinny', 'Normal', 'Fat']), 'weight' => $this->faker->randomFloat(3, $min = 3, $max = 20), ]; } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateSubscriptionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('subscriptions', function (Blueprint $table) { $table->id(); $table->bigInteger('customer_id')->unsigned(); $table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade'); $table->decimal('base_price', 18, 2)->nullable(); $table->decimal('total_price', 18, 2)->nullable(); $table->decimal('weight', 18, 2)->nullable(); $table->string('protein', 255)->nullable(); $table->date('last_order_date')->nullable(); $table->date('next_order_date')->nullable(); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('sobscriptions'); } } <file_sep><?php use Laravel\Lumen\Testing\DatabaseMigrations; use Laravel\Lumen\Testing\DatabaseTransactions; class SubscriptionsTest extends TestCase { /** * /subscriptions [GET] */ public function testShouldReturnAllSubscriptions(){ $this->get("subscriptions", []); $this->seeStatusCode(200); } /** * /subscriptions/id [GET] */ public function testShouldReturnSubscription(){ $this->get("subscriptions/2", []); $this->seeStatusCode(200); } /** * /subscriptions [POST] */ public function testShouldCreateSubscription(){ $parameters = [ 'customer_id' => 1, 'base_price' => 20, 'total_price' => 17, 'weight' => 3.00, 'protein' => 'chicken' ]; $this->post("subscriptions", $parameters, []); $this->seeStatusCode(200); } /** * /subscriptions/id [PUT] */ public function testShouldUpdateSubscription(){ $parameters = [ 'last_order_date' => date('Y-m-d'), 'next_order_date' => date('Y-m-d', strtotime('+ 4 weeks')) ]; $this->put("subscriptions/4", $parameters, []); $this->seeStatusCode(200); } /** * /subscriptions/id [DELETE] */ public function testShouldDeleteSubscription(){ $this->delete("subscriptions/5", [], []); $this->seeStatusCode(410); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Factories\HasFactory; class Subscription extends Model { use HasFactory; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'customer_id', 'base_price', 'total_price', 'weight', 'protein', 'last_order_date', 'next_order_date', ]; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = [ 'customer_id', ]; public function customer(){ return $this->belongsTo(Customer::class); } public function pets(){ return $this->hasMany(Pet::class); } } <file_sep>copy ./run.sh /tmp ENTRYPOINT ["/tmp/run.sh"]<file_sep><?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { $models = ['Customer', 'Subscription', 'Pet']; foreach ($models as $model) { $this->app->bind("App\Repositories\Contracts\\{$model}RepositoryInterface", "App\Repositories\\{$model}RepositoryEloquent"); } } } <file_sep><?php namespace App\Repositories; use App\Repositories\Contracts\PetRepositoryInterface; use Illuminate\Http\Request; use App\Models\Pet; class PetRepositoryEloquent implements PetRepositoryInterface { private $model; public function __construct(Pet $pet){ $this->model = $pet; } public function getAll(){ return $this->model->all(); } public function get($id){ return $this->model->find($id); } public function store(Request $request){ return $this->model->create($request->all()); } public function update($id, Request $request){ return $this->model->find($id)->update($request->all()); } public function destroy($id){ return $this->model->find($id)->delete(); } }<file_sep><?php namespace App\Services; use App\Repositories\Contracts\CustomerRepositoryInterface; use Illuminate\Http\Request; use App\Models\Customer; // use Symfony\Component\HttpFoundation\Response; use Illuminate\Support\Facades\Validator; class CustomerService { private $customerRepository; public function __construct(CustomerRepositoryInterface $customerRepository) { $this->customerRepository = $customerRepository; } public function getAll(){ $customers = $this->customerRepository->getAll(); $data['valid'] = true; $data['data']['customers'] = $customers; return response()->json($data); } public function get($id){ $customer = $this->customerRepository->get($id); if($customer){ $data['valid'] = true; $data['data']['customer'] = $customer; }else{ $data['valid'] = false; $data['errors'] = 'Customer not found...'; } return response()->json($data); } public function store(Request $request){ $validator = Validator::make($request->all(), Customer::RULE_CUSTOMER); if ($validator->fails()) { $data['valid'] = false; $data['message'] = 'Validation fails!'; $data['errors'] = $validator->errors(); }else{ $customer = $this->customerRepository->store($request); if($customer){ $data['valid'] = true; $data['message'] = 'Customer has been created!'; $data['data']['customer'] = $customer; }else{ $data['valid'] = false; $data['errors'] = 'Customer cannot be saved...'; } } return response()->json($data); } public function update($id, Request $request){ $validator = Validator::make($request->all(), [ 'name' => 'required', 'birth_date' => 'required|date|date_format:Y-m-d|before:-18 years', 'gender' => 'required|in:male,female', 'email' => 'required|email|unique:customers,id,'.$id ]); if ($validator->fails()) { $data['valid'] = false; $data['message'] = 'Validation fails!'; $data['errors'] = $validator->errors(); }else{ $customer = $this->customerRepository->update($id, $request); if($customer){ $data['valid'] = true; $data['message'] = 'Customer has been updated!'; $data['data']['customer'] = Customer::find($id); }else{ $data['valid'] = false; $data['errors'] = 'Customer cannot be updated...'; } } return response()->json($data); } public function destroy($id){ $customer = $this->customerRepository->get($id); if($customer){ $this->customerRepository->destroy($id); $data['valid'] = true; $data['message'] = 'Customer has been deleted!'; $data['data']['customer'] = $customer; }else{ $data['valid'] = false; $data['errors'] = 'Customer not found...'; } return response()->json($data, 410); } public function profile($id){ $customer = $this->customerRepository->get($id); if($customer){ $data['valid'] = true; $data['data']['customer'] = $customer; $data['data']['customer']['subscription'] = $customer->subscription; $data['data']['customer']['subscription']['pets'] = $customer->subscription->pets; }else{ $data['valid'] = false; $data['errors'] = 'Customer not found...'; } return response()->json($data); } public function subscription($id){ $customer = $this->customerRepository->get($id); if($customer){ $data['valid'] = true; $data['data']['customer'] = $customer; $data['data']['customer']['subscription'] = $customer->subscription; }else{ $data['valid'] = false; $data['errors'] = 'Customer subscription not found...'; } return response()->json($data); } public function pets($id){ $customer = $this->customerRepository->get($id); if($customer){ $data['valid'] = true; $data['data']['customer'] = $customer; $data['data']['customer']['pets'] = $customer->pets; }else{ $data['valid'] = false; $data['errors'] = 'Customer pets not found...'; } return response()->json($data); } public function dispatch($id){ $customer = $this->customerRepository->get($id); if($customer){ $customer->subscription()->update([ 'last_order_date' => date('Y-m-d'), 'next_order_date' => date('Y-m-d', strtotime('+ 4 weeks')) ]); $data['valid'] = true; $data['message'] = 'Subscription has been dispatched!'; $data['data']['customer'] = $customer; $data['data']['customer']['subscription'] = $customer->subscription; }else{ $data['valid'] = false; $data['errors'] = 'Customer subscription cannot be dispatched...'; } return response()->json($data); } }<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Services\PetService; class PetController extends Controller { private $petService; public function __construct(PetService $petService) { $this->petService = $petService; } public function index(){ return $this->petService->getAll(); } public function show($id){ return $this->petService->get($id); } public function store(Request $request){ return $this->petService->store($request); } public function update($id, Request $request){ return $this->petService->update($id, $request); } public function destroy($id){ return $this->petService->destroy($id); } }
1b234403b15042c453c8a694242bb1a96e416117
[ "Markdown", "Dockerfile", "YAML", "PHP" ]
22
PHP
ggwebdev/barkyn-gabriel
3b17313fd2fd0b4dcb2e3218df7798d4e2b407e0
b40cfdd4604b398f44e193af7e326e8e547de753
refs/heads/main
<repo_name>drGarbinsky/dactylmanu-ball<file_sep>/i2c.ino #include <Arduino.h> #include <i2c_driver.h> #include <i2c_driver_wire.h> #define SECONDARY_ADDR 8 void kbReadBytes(); void setupI2c(bool isPrimary) { if (isPrimary) { Wire.setClock(100000); println("Primary i2c initialized."); Wire.begin(); } else { Wire.begin(SECONDARY_ADDR); // join i2c bus with address #slave Wire.onRequest(kbReadBytes); // register event } } void kbReadBytes() { uint8_t data[sizeof(keyBuffer) + sizeof(ballMotionBuffer)]; memcpy(data, &keyBuffer, sizeof(keyBuffer)); memcpy(data + sizeof(keyBuffer), &ballMotionBuffer, sizeof(ballMotionBuffer)); Wire.write(data, sizeof(data)); initKeyBuf(); //clear buff after sending initBallBuf(); } bool readSecondary() { byte idx = 0; Wire.requestFrom(SECONDARY_ADDR, keyBufSize + 4); while (Wire.available() && idx < keyBufSize) { // peripheral may send less than requested char c = Wire.read(); // receive a byte as character keyBuffer[idx++] = c; // receive a byte as character } idx = 0; while (Wire.available() && idx < 2) { ballMotionBuffer[idx++] = Wire.read(); } for (int i = 0; i < keyBufSize; i++) { if (keyBuffer[i++] != 0) { return true; } } for (int i = 0; i < ballBufSize; i++) { if (ballMotionBuffer[i++] != 0) { return true; } } return false; }<file_sep>/Map.ino //left map - break is currently set to insert 209 int currentLayer = 0; const byte mod = 255; const byte lms = 254; const byte rms = 253; const byte bms = 252; const byte layers = 2; const byte macro1 = 250; const byte macro2 = 249; const byte macro3 = 248; const byte macro4 = 247; const byte colMask = 0xE0; const byte rowMask = 0X1C; int leftKeyMap[layers][rowCount][colCount] = { { { KEY_EQUAL, KEY_1, KEY_2, KEY_3, KEY_4, KEY_5 }, { KEY_ESC, KEY_Q, KEY_W, KEY_E, KEY_R, KEY_T }, { KEY_TAB, KEY_A, KEY_S, KEY_D, KEY_F, KEY_G }, { KEY_LEFT_SHIFT, KEY_Z, KEY_X, KEY_C, KEY_V, KEY_B }, { KEY_MEDIA_PLAY_PAUSE, KEY_TILDE, KEY_PAGE_UP, KEY_HOME, bms, KEY_DELETE }, { 0, 0, KEY_PAGE_DOWN, KEY_END, KEY_BACKSPACE, mod }, { 0, 0, KEY_MEDIA_VOLUME_DEC, KEY_MEDIA_VOLUME_INC, KEY_LEFT_CTRL, KEY_LEFT_ALT } }, { { KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, mod }, { 0, 0, 0, 0, 0, 0 } } }; // right map int rightKeyMap[layers][rowCount][colCount] = { { { KEY_6, KEY_7, KEY_8, KEY_9, KEY_0, KEY_MINUS }, { KEY_Y, KEY_U, KEY_I, KEY_O, KEY_P, KEY_BACKSLASH }, { KEY_H, KEY_J, KEY_K, KEY_L, KEY_SEMICOLON, KEY_QUOTE }, { KEY_N, KEY_M, KEY_COMMA, KEY_PERIOD, KEY_RIGHT_BRACE, KEY_SLASH }, { lms, rms, KEY_UP, KEY_LEFT_BRACE, KEY_RIGHT, KEY_RIGHT_CTRL }, { mod, KEY_SPACE, KEY_DOWN, KEY_LEFT, 0, 0 }, { KEY_MEDIA_NEXT_TRACK, KEY_ENTER, KEY_RIGHT_SHIFT, KEY_RIGHT_GUI, 0, 0 } }, { { KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12 }, { 0, 0, 0, 0, 0, 0 }, { lms, rms, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { mod, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 } } }; int (*keyMap)[rowCount][colCount] = rightKeyMap; void processKeyStates(bool isRight, int keyBufSize, byte* keysBuffer) { if (isRight == false) { keyMap = leftKeyMap; } else { keyMap = rightKeyMap; } for (int i = 0; i < keyBufSize && i < 6; i++) { if (keysBuffer[i] != 0) { byte col = (keysBuffer[i] & colMask) >> 5; byte row = (keysBuffer[i] & rowMask) >> 2; byte btnState = keysBuffer[i] & 1; handleKeyPress(keyMap[currentLayer][row][col], btnState, i); keysBuffer[i] = 0; } } //Keyboard.send_now(); } void handleKeyPress(int key, byte btnState, int keyIndex) { if (btnState == 1) { if (key == lms) { Mouse.press(MOUSE_LEFT); } else if (key == rms) { Mouse.press(MOUSE_RIGHT); } else if (key == bms) { Mouse.press(MOUSE_BACK); }else if (key == mod) { currentLayer = 1; println("layer 1"); } else if (key == macro1) { // Keyboard.press(135); // Keyboard.press(132); // Keyboard.press(216); println("macro1 pressed"); } else if (key == macro2) { // Keyboard.press(135); // Keyboard.press(132); // Keyboard.press(215); println("macro2 pressed"); } else { Keyboard.press(key); //keyboard_keys[keyIndex] = key; printInt(int(key)); println(" pressed"); } } else { if (key == lms) { Mouse.release(MOUSE_LEFT); } else if (key == rms) { Mouse.release(MOUSE_RIGHT); } else if (key == bms) { Mouse.release(MOUSE_BACK); }else if (key == mod) { currentLayer = 0; println("layer 0"); } else if (key == macro1) { // Keyboard.release(135); // Keyboard.release(132); // Keyboard.release(216); println("macro1 release"); } else if (key == macro2) { // Keyboard.release(135); // Keyboard.release(132); // Keyboard.release(215); println("macro2 release"); } else { Keyboard.release(key); printInt(int(key)); println(" released"); } } }<file_sep>/SROM.ino // the firmeware that is uploaded in the ADNS each time it boots #include <avr/pgmspace.h> // Firmware "ORCA3_ROW_SROMxE8" const unsigned short firmware_length = 4094; const unsigned char firmware_data[] PROGMEM = { 0x01, 0xe8, 0xba, 0x26, 0x0b, 0xb2, 0xbe, 0xfe, 0x7e, 0x5f, 0x3c, 0xdb, 0x15, 0xa8, 0xb3, 0xe4, 0x2b, 0xb5, 0xe8, 0x53, 0x07, 0x6d, 0x3b, 0xd1, 0x20, 0xc2, 0x06, 0x6f, 0x3d, 0xd9, 0x11, 0xa0, 0xc2, 0xe7, 0x2d, 0xb9, 0xd1, 0x20, 0xa3, 0xa5, 0xc8, 0xf3, 0x64, 0x4a, 0xf7, 0x4d, 0x18, 0x93, 0xa4, 0xca, 0xf7, 0x6c, 0x5a, 0x36, 0xee, 0x5e, 0x3e, 0xfe, 0x7e, 0x7e, 0x5f, 0x1d, 0x99, 0xb0, 0xc3, 0xe5, 0x29, 0xd3, 0x03, 0x65, 0x48, 0x12, 0x87, 0x6d, 0x58, 0x32, 0xe6, 0x2f, 0xdc, 0x3a, 0xf2, 0x4f, 0xfd, 0x59, 0x11, 0x81, 0x61, 0x21, 0xc0, 0x02, 0x86, 0x8e, 0x7f, 0x5d, 0x38, 0xf2, 0x47, 0x0c, 0x7b, 0x55, 0x28, 0xb3, 0xe4, 0x4a, 0x16, 0xab, 0xbf, 0xdd, 0x38, 0xf2, 0x66, 0x4e, 0xff, 0x5d, 0x19, 0x91, 0xa0, 0xa3, 0xa5, 0xc8, 0x12, 0xa6, 0xaf, 0xdc, 0x3a, 0xd1, 0x41, 0x60, 0x75, 0x58, 0x24, 0x92, 0xd4, 0x72, 0x6c, 0xe0, 0x2f, 0xfd, 0x23, 0x8d, 0x1c, 0x5b, 0xb2, 0x97, 0x36, 0x3d, 0x0b, 0xa2, 0x49, 0xb1, 0x58, 0xf2, 0x1f, 0xc0, 0xcb, 0xf8, 0x41, 0x4f, 0xcd, 0x1e, 0x6b, 0x39, 0xa7, 0x2b, 0xe9, 0x30, 0x16, 0x83, 0xd2, 0x0e, 0x47, 0x8f, 0xe3, 0xb1, 0xdf, 0xa2, 0x15, 0xdb, 0x5d, 0x30, 0xc5, 0x1a, 0xab, 0x31, 0x99, 0xf3, 0xfa, 0xb2, 0x86, 0x69, 0xad, 0x7a, 0xe8, 0xa7, 0x18, 0x6a, 0xcc, 0xc8, 0x65, 0x23, 0x87, 0xa8, 0x5f, 0xf5, 0x21, 0x59, 0x75, 0x09, 0x71, 0x45, 0x55, 0x25, 0x4b, 0xda, 0xa1, 0xc3, 0xf7, 0x41, 0xab, 0x59, 0xd9, 0x74, 0x12, 0x55, 0x5f, 0xbc, 0xaf, 0xd9, 0xfd, 0xb0, 0x1e, 0xa3, 0x0f, 0xff, 0xde, 0x11, 0x16, 0x6a, 0xae, 0x0e, 0xe1, 0x5d, 0x3c, 0x10, 0x43, 0x9a, 0xa1, 0x0b, 0x24, 0x8f, 0x0d, 0x7f, 0x0b, 0x5e, 0x4c, 0x42, 0xa4, 0x84, 0x2c, 0x40, 0xd0, 0x55, 0x39, 0xe6, 0x4b, 0xf8, 0x9b, 0x2f, 0xdc, 0x28, 0xff, 0xfa, 0xb5, 0x85, 0x19, 0xe5, 0x28, 0xa1, 0x77, 0xaa, 0x73, 0xf3, 0x03, 0xc7, 0x62, 0xa6, 0x91, 0x18, 0xc9, 0xb0, 0xcd, 0x05, 0xdc, 0xca, 0x81, 0x26, 0x1a, 0x47, 0x40, 0xda, 0x36, 0x7d, 0x6a, 0x53, 0xc8, 0x5a, 0x77, 0x5d, 0x19, 0xa4, 0x1b, 0x23, 0x83, 0xd0, 0xb2, 0xaa, 0x0e, 0xbf, 0x77, 0x4e, 0x3a, 0x3b, 0x59, 0x00, 0x31, 0x0d, 0x02, 0x1b, 0x88, 0x7a, 0xd4, 0xbd, 0x9d, 0xcc, 0x58, 0x04, 0x69, 0xf6, 0x3b, 0xca, 0x42, 0xe2, 0xfd, 0xc3, 0x3d, 0x39, 0xc5, 0xd0, 0x71, 0xe4, 0xc8, 0xb7, 0x3e, 0x3f, 0xc8, 0xe9, 0xca, 0xc9, 0x3f, 0x04, 0x4e, 0x1b, 0x79, 0xca, 0xa5, 0x61, 0xc2, 0xed, 0x1d, 0xa6, 0xda, 0x5a, 0xe9, 0x7f, 0x65, 0x8c, 0xbe, 0x12, 0x6e, 0xa4, 0x5b, 0x33, 0x2f, 0x84, 0x28, 0x9c, 0x1c, 0x88, 0x2d, 0xff, 0x07, 0xbf, 0xa6, 0xd7, 0x5a, 0x88, 0x86, 0xb0, 0x3f, 0xf6, 0x31, 0x5b, 0x11, 0x6d, 0xf5, 0x58, 0xeb, 0x58, 0x02, 0x9e, 0xb5, 0x9a, 0xb1, 0xff, 0x25, 0x9d, 0x8b, 0x4f, 0xb6, 0x0a, 0xf9, 0xea, 0x3e, 0x3f, 0x21, 0x09, 0x65, 0x21, 0x22, 0xfe, 0x3d, 0x4e, 0x11, 0x5b, 0x9e, 0x5a, 0x59, 0x8b, 0xdd, 0xd8, 0xce, 0xd6, 0xd9, 0x59, 0xd2, 0x1e, 0xfd, 0xef, 0x0d, 0x1b, 0xd9, 0x61, 0x7f, 0xd7, 0x2d, 0xad, 0x62, 0x09, 0xe5, 0x22, 0x63, 0xea, 0xc7, 0x31, 0xd9, 0xa1, 0x38, 0x80, 0x5c, 0xa7, 0x32, 0x82, 0xec, 0x1b, 0xa2, 0x49, 0x5a, 0x06, 0xd2, 0x7c, 0xc9, 0x96, 0x57, 0xbb, 0x17, 0x75, 0xfc, 0x7a, 0x8f, 0x0d, 0x77, 0xb5, 0x7a, 0x8e, 0x3e, 0xf4, 0xba, 0x2f, 0x69, 0x13, 0x26, 0xd6, 0xd9, 0x21, 0x60, 0x2f, 0x21, 0x3e, 0x87, 0xee, 0xfd, 0x87, 0x16, 0x0d, 0xc8, 0x08, 0x00, 0x25, 0x71, 0xac, 0x2c, 0x03, 0x2a, 0x37, 0x2d, 0xb3, 0x34, 0x09, 0x91, 0xe3, 0x06, 0x2c, 0x38, 0x37, 0x95, 0x3b, 0x17, 0x7a, 0xaf, 0xac, 0x99, 0x55, 0xab, 0x41, 0x39, 0x5f, 0x8e, 0xa6, 0x43, 0x80, 0x03, 0x88, 0x6f, 0x7d, 0xbd, 0x5a, 0xb4, 0x2b, 0x32, 0x23, 0x5a, 0xa9, 0x31, 0x32, 0x39, 0x4c, 0x5b, 0xf4, 0x6b, 0xaf, 0x66, 0x6f, 0x3c, 0x8e, 0x2d, 0x82, 0x97, 0x9f, 0x4a, 0x01, 0xdc, 0x99, 0x98, 0x00, 0xec, 0x38, 0x7a, 0x79, 0x70, 0xa6, 0x85, 0xd6, 0x21, 0x63, 0x0d, 0x45, 0x9a, 0x2e, 0x5e, 0xa7, 0xb1, 0xea, 0x66, 0x6a, 0xbc, 0x62, 0x2d, 0x7b, 0x7d, 0x85, 0xea, 0x95, 0x2f, 0xc0, 0xe8, 0x6f, 0x35, 0xa0, 0x3a, 0x02, 0x25, 0xbc, 0xb2, 0x5f, 0x5c, 0x43, 0x96, 0xcc, 0x26, 0xd2, 0x16, 0xb4, 0x96, 0x73, 0xd7, 0x13, 0xc7, 0xae, 0x53, 0x15, 0x31, 0x89, 0x68, 0x66, 0x6d, 0x2c, 0x92, 0x1f, 0xcc, 0x5b, 0xa7, 0x8f, 0x5d, 0xbb, 0xc9, 0xdb, 0xe8, 0x3b, 0x9d, 0x61, 0x74, 0x8b, 0x05, 0xa1, 0x58, 0x52, 0x68, 0xee, 0x3d, 0x39, 0x79, 0xa0, 0x9b, 0xdd, 0xe1, 0x55, 0xc9, 0x60, 0xeb, 0xad, 0xb8, 0x5b, 0xc2, 0x5a, 0xb5, 0x2c, 0x18, 0x55, 0xa9, 0x50, 0xc3, 0xf6, 0x72, 0x5f, 0xcc, 0xe2, 0xf4, 0x55, 0xb5, 0xd6, 0xb5, 0x4a, 0x99, 0xa5, 0x28, 0x74, 0x97, 0x18, 0xe8, 0xc0, 0x84, 0x89, 0x50, 0x03, 0x86, 0x4d, 0x1a, 0xb7, 0x09, 0x90, 0xa2, 0x01, 0x04, 0xbb, 0x73, 0x62, 0xcb, 0x97, 0x22, 0x70, 0x5d, 0x52, 0x41, 0x8e, 0xd9, 0x90, 0x15, 0xaa, 0xab, 0x0a, 0x31, 0x65, 0xb4, 0xda, 0xd0, 0xee, 0x24, 0xc9, 0x41, 0x91, 0x1e, 0xbc, 0x46, 0x70, 0x40, 0x9d, 0xda, 0x0e, 0x2a, 0xe4, 0xb2, 0x4c, 0x9f, 0xf2, 0xfc, 0xf3, 0x84, 0x17, 0x44, 0x1e, 0xd7, 0xca, 0x23, 0x1f, 0x3f, 0x5a, 0x22, 0x3d, 0xaf, 0x9b, 0x2d, 0xfc, 0x41, 0xad, 0x26, 0xb4, 0x45, 0x67, 0x0b, 0x80, 0x0e, 0xf9, 0x61, 0x37, 0xec, 0x3b, 0xf4, 0x4b, 0x14, 0xdf, 0x5a, 0x0c, 0x3a, 0x50, 0x0b, 0x14, 0x0c, 0x72, 0xae, 0xc6, 0xc5, 0xec, 0x35, 0x53, 0x2d, 0x59, 0xed, 0x91, 0x74, 0xe2, 0xc4, 0xc8, 0xf2, 0x25, 0x6b, 0x97, 0x6f, 0xc9, 0x76, 0xce, 0xa9, 0xb1, 0x99, 0x8f, 0x5a, 0x92, 0x3b, 0xc4, 0x8d, 0x54, 0x50, 0x40, 0x72, 0xd6, 0x90, 0x83, 0xfc, 0xe5, 0x49, 0x8b, 0x17, 0xf5, 0xfd, 0x6b, 0x8d, 0x32, 0x02, 0xe9, 0x0a, 0xfe, 0xbf, 0x00, 0x6b, 0xa3, 0xad, 0x5f, 0x09, 0x4b, 0x97, 0x2b, 0x00, 0x58, 0x65, 0x2e, 0x07, 0x49, 0x0a, 0x3b, 0x6b, 0x2e, 0x50, 0x6c, 0x1d, 0xac, 0xb7, 0x6a, 0x26, 0xd8, 0x13, 0xa4, 0xca, 0x16, 0xae, 0xab, 0x93, 0xb9, 0x1c, 0x1c, 0xb4, 0x47, 0x6a, 0x38, 0x36, 0x17, 0x27, 0xc9, 0x7f, 0xc7, 0x64, 0xcb, 0x89, 0x58, 0xc5, 0x61, 0xc2, 0xc6, 0xea, 0x15, 0x0b, 0x34, 0x0c, 0x5d, 0x61, 0x76, 0x6e, 0x2b, 0x62, 0x40, 0x92, 0xa3, 0x6c, 0xef, 0xf4, 0xe4, 0xc3, 0xa1, 0xa8, 0xf5, 0x94, 0x79, 0x0d, 0xd1, 0x3d, 0xcb, 0x3d, 0x40, 0xb6, 0xd0, 0xf0, 0x10, 0x54, 0xd8, 0x47, 0x25, 0x51, 0xc5, 0x41, 0x79, 0x00, 0xe5, 0xa0, 0x72, 0xde, 0xbb, 0x3b, 0x62, 0x17, 0xf6, 0xbc, 0x5d, 0x00, 0x76, 0x2e, 0xa7, 0x3b, 0xb6, 0xf1, 0x98, 0x72, 0x59, 0x2a, 0x73, 0xb0, 0x21, 0xd6, 0x49, 0xe0, 0xc0, 0xd5, 0xeb, 0x02, 0x7d, 0x4b, 0x41, 0x28, 0x70, 0x2d, 0xec, 0x2b, 0x71, 0x1f, 0x0b, 0xb9, 0x71, 0x63, 0x06, 0xe6, 0xbc, 0x60, 0xbb, 0xf4, 0x9a, 0x62, 0x43, 0x09, 0x18, 0x4e, 0x93, 0x06, 0x4d, 0x76, 0xfa, 0x7f, 0xbd, 0x02, 0xe4, 0x50, 0x91, 0x12, 0xe5, 0x86, 0xff, 0x64, 0x1e, 0xaf, 0x7e, 0xb3, 0xb2, 0xde, 0x89, 0xc1, 0xa2, 0x6f, 0x40, 0x7b, 0x41, 0x51, 0x63, 0xea, 0x25, 0xd1, 0x97, 0x57, 0x92, 0xa8, 0x45, 0xa1, 0xa5, 0x45, 0x21, 0x43, 0x7f, 0x83, 0x15, 0x29, 0xd0, 0x30, 0x53, 0x32, 0xb4, 0x5a, 0x17, 0x96, 0xbc, 0xc2, 0x68, 0xa9, 0xb7, 0xaf, 0xac, 0xdf, 0xf1, 0xe3, 0x89, 0xba, 0x24, 0x79, 0x54, 0xc6, 0x14, 0x07, 0x1c, 0x1e, 0x0d, 0x3a, 0x6b, 0xe5, 0x3d, 0x4e, 0x10, 0x60, 0x96, 0xec, 0x6c, 0xda, 0x47, 0xae, 0x03, 0x25, 0x39, 0x1d, 0x74, 0xc8, 0xac, 0x6a, 0xf2, 0x6b, 0x05, 0x2a, 0x9a, 0xe7, 0xe8, 0x92, 0xd6, 0xc2, 0x6d, 0xfa, 0xe8, 0xa7, 0x9d, 0x5f, 0x48, 0xc9, 0x75, 0xf1, 0x66, 0x6a, 0xdb, 0x5d, 0x9a, 0xcd, 0x27, 0xdd, 0xb9, 0x24, 0x04, 0x9c, 0x18, 0xc2, 0x6d, 0x0c, 0x91, 0x34, 0x48, 0x42, 0x6f, 0xe9, 0x59, 0x70, 0xc4, 0x7e, 0x81, 0x0e, 0x32, 0x0a, 0x93, 0x48, 0xb0, 0xc0, 0x15, 0x9e, 0x05, 0xac, 0x36, 0x16, 0xcb, 0x59, 0x65, 0xa0, 0x83, 0xdf, 0x3e, 0xda, 0xfb, 0x1d, 0x1a, 0xdb, 0x65, 0xec, 0x9a, 0xc6, 0xc3, 0x8e, 0x3c, 0x45, 0xfd, 0xc8, 0xf5, 0x1c, 0x6a, 0x67, 0x0d, 0x8f, 0x99, 0x7d, 0x30, 0x21, 0x8c, 0xea, 0x22, 0x87, 0x65, 0xc9, 0xb2, 0x4c, 0xe4, 0x1b, 0x46, 0xba, 0x54, 0xbd, 0x7c, 0xca, 0xd5, 0x8f, 0x5b, 0xa5, 0x01, 0x04, 0xd8, 0x0a, 0x16, 0xbf, 0xb9, 0x50, 0x2e, 0x37, 0x2f, 0x64, 0xf3, 0x70, 0x11, 0x02, 0x05, 0x31, 0x9b, 0xa0, 0xb2, 0x01, 0x5e, 0x4f, 0x19, 0xc9, 0xd4, 0xea, 0xa1, 0x79, 0x54, 0x53, 0xa7, 0xde, 0x2f, 0x49, 0xd3, 0xd1, 0x63, 0xb5, 0x03, 0x15, 0x4e, 0xbf, 0x04, 0xb3, 0x26, 0x8b, 0x20, 0xb2, 0x45, 0xcf, 0xcd, 0x5b, 0x82, 0x32, 0x88, 0x61, 0xa7, 0xa8, 0xb2, 0xa0, 0x72, 0x96, 0xc0, 0xdb, 0x2b, 0xe2, 0x5f, 0xba, 0xe3, 0xf5, 0x8a, 0xde, 0xf1, 0x18, 0x01, 0x16, 0x40, 0xd9, 0x86, 0x12, 0x09, 0x18, 0x1b, 0x05, 0x0c, 0xb1, 0xb5, 0x47, 0xe2, 0x43, 0xab, 0xfe, 0x92, 0x63, 0x7e, 0x95, 0x2b, 0xf0, 0xaf, 0xe1, 0xf1, 0xc3, 0x4a, 0xff, 0x2b, 0x09, 0xbb, 0x4a, 0x0e, 0x9a, 0xc4, 0xd8, 0x64, 0x7d, 0x83, 0xa0, 0x4f, 0x44, 0xdb, 0xc4, 0xa8, 0x58, 0xef, 0xfc, 0x9e, 0x77, 0xf9, 0xa6, 0x8f, 0x58, 0x8b, 0x12, 0xf4, 0xe9, 0x81, 0x12, 0x47, 0x51, 0x41, 0x83, 0xef, 0xf6, 0x73, 0xbc, 0x8e, 0x0f, 0x4c, 0x8f, 0x4e, 0x69, 0x90, 0x77, 0x29, 0x5d, 0x92, 0xb0, 0x6d, 0x06, 0x67, 0x29, 0x60, 0xbd, 0x4b, 0x17, 0xc8, 0x89, 0x69, 0x28, 0x29, 0xd6, 0x78, 0xcb, 0x11, 0x4c, 0xba, 0x8b, 0x68, 0xae, 0x7e, 0x9f, 0xef, 0x95, 0xda, 0xe2, 0x9e, 0x7f, 0xe9, 0x55, 0xe5, 0xe1, 0xe2, 0xb7, 0xe6, 0x5f, 0xbb, 0x2c, 0xa2, 0xe6, 0xee, 0xc7, 0x0a, 0x60, 0xa9, 0xd1, 0x80, 0xdf, 0x7f, 0xd6, 0x97, 0xab, 0x1d, 0x22, 0x25, 0xfc, 0x79, 0x23, 0xe0, 0xae, 0xc5, 0xef, 0x16, 0xa4, 0xa1, 0x0f, 0x92, 0xa9, 0xc7, 0xe3, 0x3a, 0x55, 0xdf, 0x62, 0x49, 0xd9, 0xf5, 0x84, 0x49, 0xc5, 0x90, 0x34, 0xd3, 0xe1, 0xac, 0x99, 0x21, 0xb1, 0x02, 0x76, 0x4a, 0xfa, 0xd4, 0xbb, 0xa4, 0x9c, 0xa2, 0xe2, 0xcb, 0x3d, 0x3b, 0x14, 0x75, 0x60, 0xd1, 0x02, 0xb4, 0xa3, 0xb4, 0x72, 0x06, 0xf9, 0x19, 0x9c, 0xe2, 0xe4, 0xa7, 0x0f, 0x25, 0x88, 0xc6, 0x86, 0xd6, 0x8c, 0x74, 0x4e, 0x6e, 0xfc, 0xa8, 0x48, 0x9e, 0xa7, 0x9d, 0x1a, 0x4b, 0x37, 0x09, 0xc8, 0xb0, 0x10, 0xbe, 0x6f, 0xfe, 0xa3, 0xc4, 0x7a, 0xb5, 0x3d, 0xe8, 0x30, 0xf1, 0x0d, 0xa0, 0xb2, 0x44, 0xfc, 0x9b, 0x8c, 0xf8, 0x61, 0xed, 0x81, 0xd1, 0x62, 0x11, 0xb4, 0xe1, 0xd5, 0x39, 0x52, 0x89, 0xd3, 0xa8, 0x49, 0x31, 0xdf, 0xb6, 0xf9, 0x91, 0xf4, 0x1c, 0x9d, 0x09, 0x95, 0x40, 0x56, 0xe7, 0xe3, 0xcd, 0x5c, 0x92, 0xc1, 0x1d, 0x6b, 0xe9, 0x78, 0x6f, 0x8e, 0x94, 0x42, 0x66, 0xa2, 0xaa, 0xd3, 0xc8, 0x2e, 0xe3, 0xf6, 0x07, 0x72, 0x0b, 0x6b, 0x1e, 0x7b, 0xb9, 0x7c, 0xe0, 0xa0, 0xbc, 0xd9, 0x25, 0xdf, 0x87, 0xa8, 0x5f, 0x9c, 0xcc, 0xf0, 0xdb, 0x42, 0x8e, 0x07, 0x31, 0x13, 0x01, 0x66, 0x32, 0xd1, 0xb8, 0xd6, 0xe3, 0x5e, 0x12, 0x76, 0x61, 0xd3, 0x38, 0x89, 0xe6, 0x17, 0x6f, 0xa5, 0xf2, 0x71, 0x0e, 0xa5, 0xe2, 0x88, 0x30, 0xbb, 0xbe, 0x8a, 0xea, 0xc7, 0x62, 0xc4, 0xcf, 0xb8, 0xcd, 0x33, 0x8d, 0x3d, 0x3e, 0xb5, 0x60, 0x3a, 0x03, 0x92, 0xe4, 0x6d, 0x1b, 0xe0, 0xb4, 0x84, 0x08, 0x55, 0x88, 0xa7, 0x3a, 0xb9, 0x3d, 0x43, 0xc3, 0xc0, 0xfa, 0x07, 0x6a, 0xca, 0x94, 0xad, 0x99, 0x55, 0xf1, 0xf1, 0xc0, 0x23, 0x87, 0x1d, 0x3d, 0x1c, 0xd1, 0x66, 0xa0, 0x57, 0x10, 0x52, 0xa2, 0x7f, 0xbe, 0xf9, 0x88, 0xb6, 0x02, 0xbf, 0x08, 0x23, 0xa9, 0x0c, 0x63, 0x17, 0x2a, 0xae, 0xf5, 0xf7, 0xb7, 0x21, 0x83, 0x92, 0x31, 0x23, 0x0d, 0x20, 0xc3, 0xc2, 0x05, 0x21, 0x62, 0x8e, 0x45, 0xe8, 0x14, 0xc1, 0xda, 0x75, 0xb8, 0xf8, 0x92, 0x01, 0xd0, 0x5d, 0x18, 0x9f, 0x99, 0x11, 0x19, 0xf5, 0x35, 0xe8, 0x7f, 0x20, 0x88, 0x8c, 0x05, 0x75, 0xf5, 0xd7, 0x40, 0x17, 0xbb, 0x1e, 0x36, 0x52, 0xd9, 0xa4, 0x9c, 0xc2, 0x9d, 0x42, 0x81, 0xd8, 0xc7, 0x8a, 0xe7, 0x4c, 0x81, 0xe0, 0xb7, 0x57, 0xed, 0x48, 0x8b, 0xf0, 0x97, 0x15, 0x61, 0xd9, 0x2c, 0x7c, 0x45, 0xaf, 0xc2, 0xcd, 0xfc, 0xaa, 0x13, 0xad, 0x59, 0xcc, 0xb2, 0xb2, 0x6e, 0xdd, 0x63, 0x9c, 0x32, 0x0f, 0xec, 0x83, 0xbe, 0x78, 0xac, 0x91, 0x44, 0x1a, 0x1f, 0xea, 0xfd, 0x5d, 0x8e, 0xb4, 0xc0, 0x84, 0xd4, 0xac, 0xb4, 0x87, 0x5f, 0xac, 0xef, 0xdf, 0xcd, 0x12, 0x56, 0xc8, 0xcd, 0xfe, 0xc5, 0xda, 0xd3, 0xc1, 0x69, 0xf3, 0x61, 0x05, 0xea, 0x25, 0xe2, 0x12, 0x05, 0x8f, 0x39, 0x08, 0x08, 0x7c, 0x37, 0xb6, 0x7e, 0x5b, 0xd8, 0xb1, 0x0e, 0xf2, 0xdb, 0x4b, 0xf1, 0xad, 0x90, 0x01, 0x57, 0xcd, 0xa0, 0xb4, 0x52, 0xe8, 0xf3, 0xd7, 0x8a, 0xbd, 0x4f, 0x9f, 0x21, 0x40, 0x72, 0xa4, 0xfc, 0x0b, 0x01, 0x2b, 0x2f, 0xb6, 0x4c, 0x95, 0x2d, 0x35, 0x33, 0x41, 0x6b, 0xa0, 0x93, 0xe7, 0x2c, 0xf2, 0xd3, 0x72, 0x8b, 0xf4, 0x4f, 0x15, 0x3c, 0xaf, 0xd6, 0x12, 0xde, 0x3f, 0x83, 0x3f, 0xff, 0xf8, 0x7f, 0xf6, 0xcc, 0xa6, 0x7f, 0xc9, 0x9a, 0x6e, 0x1f, 0xc1, 0x0c, 0xfb, 0xee, 0x9c, 0xe7, 0xaf, 0xc9, 0x26, 0x54, 0xef, 0xb0, 0x39, 0xef, 0xb2, 0xe9, 0x23, 0xc4, 0xef, 0xd1, 0xa1, 0xa4, 0x25, 0x24, 0x6f, 0x8d, 0x6a, 0xe5, 0x8a, 0x32, 0x3a, 0xaf, 0xfc, 0xda, 0xce, 0x18, 0x25, 0x42, 0x07, 0x4d, 0x45, 0x8b, 0xdf, 0x85, 0xcf, 0x55, 0xb2, 0x24, 0xfe, 0x9c, 0x69, 0x74, 0xa7, 0x6e, 0xa0, 0xce, 0xc0, 0x39, 0xf4, 0x86, 0xc6, 0x8d, 0xae, 0xb9, 0x48, 0x64, 0x13, 0x0b, 0x40, 0x81, 0xa2, 0xc9, 0xa8, 0x85, 0x51, 0xee, 0x9f, 0xcf, 0xa2, 0x8c, 0x19, 0x52, 0x48, 0xe2, 0xc1, 0xa8, 0x58, 0xb4, 0x10, 0x24, 0x06, 0x58, 0x51, 0xfc, 0xb9, 0x12, 0xec, 0xfd, 0x73, 0xb4, 0x6d, 0x84, 0xfa, 0x06, 0x8b, 0x05, 0x0b, 0x2d, 0xd6, 0xd6, 0x1f, 0x29, 0x82, 0x9f, 0x19, 0x12, 0x1e, 0xb2, 0x04, 0x8f, 0x7f, 0x4d, 0xbd, 0x30, 0x2e, 0xe3, 0xe0, 0x88, 0x29, 0xc5, 0x93, 0xd6, 0x6c, 0x1f, 0x29, 0x45, 0x91, 0xa7, 0x58, 0xcd, 0x05, 0x17, 0xd6, 0x6d, 0xb3, 0xca, 0x66, 0xcc, 0x3c, 0x4a, 0x74, 0xfd, 0x08, 0x10, 0xa6, 0x99, 0x92, 0x10, 0xd2, 0x85, 0xab, 0x6e, 0x1d, 0x0e, 0x8b, 0x26, 0x46, 0xd1, 0x6c, 0x84, 0xc0, 0x26, 0x43, 0x59, 0x68, 0xf0, 0x13, 0x1d, 0xfb, 0xe3, 0xd1, 0xd2, 0xb4, 0x71, 0x9e, 0xf2, 0x59, 0x6a, 0x33, 0x29, 0x79, 0xd2, 0xd7, 0x26, 0xf1, 0xae, 0x78, 0x9e, 0x1f, 0x0f, 0x3f, 0xe3, 0xe8, 0xd0, 0x27, 0x78, 0x77, 0xf6, 0xac, 0x9c, 0x56, 0x39, 0x73, 0x8a, 0x6b, 0x2f, 0x34, 0x78, 0xb1, 0x11, 0xdb, 0xa4, 0x5c, 0x80, 0x01, 0x71, 0x6a, 0xc2, 0xd1, 0x2e, 0x5e, 0x76, 0x28, 0x70, 0x93, 0xae, 0x3e, 0x78, 0xb0, 0x1f, 0x0f, 0xda, 0xbf, 0xfb, 0x8a, 0x67, 0x65, 0x4f, 0x91, 0xed, 0x49, 0x75, 0x78, 0x62, 0xa2, 0x93, 0xb5, 0x70, 0x7f, 0x4d, 0x08, 0x4e, 0x79, 0x61, 0xa8, 0x5f, 0x7f, 0xb4, 0x65, 0x9f, 0x91, 0x54, 0x3a, 0xe8, 0x50, 0x33, 0xd3, 0xd5, 0x8a, 0x7c, 0xf3, 0x9e, 0x8b, 0x77, 0x7b, 0xc6, 0xc6, 0x0c, 0x45, 0x95, 0x1f, 0xb0, 0xd0, 0x0b, 0x27, 0x4a, 0xfd, 0xc7, 0xf7, 0x0d, 0x5a, 0x43, 0xc9, 0x7d, 0x35, 0xb0, 0x7d, 0xc4, 0x9c, 0x57, 0x1e, 0x76, 0x0d, 0xf1, 0x95, 0x30, 0x71, 0xcc, 0xb3, 0x66, 0x3b, 0x63, 0xa8, 0x6c, 0xa3, 0x43, 0xa0, 0x24, 0xcc, 0xb7, 0x53, 0xfe, 0xfe, 0xbc, 0x6e, 0x60, 0x89, 0xaf, 0x16, 0x21, 0xc8, 0x91, 0x6a, 0x89, 0xce, 0x80, 0x2c, 0xf1, 0x59, 0xce, 0xc3, 0x60, 0x61, 0x3b, 0x0b, 0x19, 0xfe, 0x99, 0xac, 0x65, 0x90, 0x15, 0x12, 0x05, 0xac, 0x7e, 0xff, 0x98, 0x7b, 0x66, 0x64, 0x0e, 0x4b, 0x5b, 0xaa, 0x8d, 0x3b, 0xd2, 0x56, 0xcf, 0x99, 0x39, 0xee, 0x22, 0x81, 0xd0, 0x60, 0x06, 0x66, 0x20, 0x81, 0x48, 0x3c, 0x6f, 0x3a, 0x77, 0xba, 0xcb, 0x52, 0xac, 0x79, 0x56, 0xaf, 0xe9, 0x16, 0x17, 0x0a, 0xa3, 0x82, 0x08, 0xd5, 0x3c, 0x97, 0xcb, 0x09, 0xff, 0x7f, 0xf9, 0x4f, 0x60, 0x05, 0xb9, 0x53, 0x26, 0xaa, 0xb8, 0x50, 0xaa, 0x19, 0x25, 0xae, 0x5f, 0xea, 0x8a, 0xd0, 0x89, 0x12, 0x80, 0x43, 0x50, 0x24, 0x12, 0x21, 0x14, 0xcd, 0x77, 0xeb, 0x21, 0xcc, 0x5c, 0x09, 0x64, 0xf3, 0xc7, 0xcb, 0xc5, 0x4b, 0xc3, 0xe7, 0xed, 0xe7, 0x86, 0x2c, 0x1d, 0x8e, 0x19, 0x52, 0x9b, 0x2a, 0x0c, 0x18, 0x72, 0x0b, 0x1e, 0x1b, 0xb0, 0x0f, 0x42, 0x99, 0x04, 0xae, 0xd5, 0xb7, 0x89, 0x1a, 0xb9, 0x4f, 0xd6, 0xaf, 0xf3, 0xc9, 0x93, 0x6f, 0xb0, 0x60, 0x83, 0x6e, 0x6b, 0xd1, 0x5f, 0x3f, 0x1a, 0x83, 0x1e, 0x24, 0x00, 0x87, 0xb5, 0x3e, 0xdb, 0xf9, 0x4d, 0xa7, 0x16, 0x2e, 0x19, 0x5b, 0x8f, 0x1b, 0x0d, 0x47, 0x72, 0x42, 0xe9, 0x0a, 0x11, 0x08, 0x2d, 0x88, 0x1c, 0xbc, 0xc7, 0xb4, 0xbe, 0x29, 0x4d, 0x03, 0x5e, 0xec, 0xdf, 0xf3, 0x3d, 0x2f, 0xe8, 0x1d, 0x9a, 0xd2, 0xd1, 0xab, 0x41, 0x3d, 0x87, 0x11, 0x45, 0xb0, 0x0d, 0x46, 0xf5, 0xe8, 0x95, 0x62, 0x1c, 0x68, 0xf7, 0xa6, 0x5b, 0x39, 0x4e, 0xbf, 0x47, 0xba, 0x5d, 0x7f, 0xb7, 0x6a, 0xf4, 0xba, 0x1d, 0x69, 0xf6, 0xa4, 0xe7, 0xe4, 0x6b, 0x3b, 0x0d, 0x23, 0x16, 0x4a, 0xb2, 0x68, 0xf0, 0xb2, 0x0d, 0x09, 0x17, 0x6a, 0x63, 0x8c, 0x83, 0xd3, 0xbd, 0x05, 0xc9, 0xf6, 0xf0, 0xa1, 0x31, 0x0b, 0x2c, 0xac, 0x83, 0xac, 0x80, 0x34, 0x32, 0xb4, 0xec, 0xd0, 0xbc, 0x54, 0x82, 0x9a, 0xc8, 0xf6, 0xa0, 0x7d, 0xc6, 0x79, 0x73, 0xf4, 0x20, 0x99, 0xf3, 0xb4, 0x01, 0xde, 0x91, 0x27, 0xf2, 0xc0, 0xdc, 0x81, 0x00, 0x4e, 0x7e, 0x07, 0x99, 0xc8, 0x3a, 0x51, 0xbc, 0x38, 0xd6, 0x8a, 0xa2, 0xde, 0x3b, 0x6a, 0x8c, 0x1a, 0x7c, 0x81, 0x0f, 0x3a, 0x1f, 0xe4, 0x05, 0x7b, 0x20, 0x35, 0x6b, 0xa5, 0x6a, 0xa7, 0xe7, 0xbc, 0x9c, 0x20, 0xec, 0x00, 0x15, 0xe2, 0x51, 0xaf, 0x77, 0xeb, 0x29, 0x3c, 0x7d, 0x2e, 0x00, 0x5c, 0x81, 0x21, 0xfa, 0x35, 0x6f, 0x40, 0xef, 0xfb, 0xd1, 0x3f, 0xcc, 0x9d, 0x55, 0x53, 0xfb, 0x5a, 0xa5, 0x56, 0x89, 0x0b, 0x52, 0xeb, 0x57, 0x73, 0x4f, 0x1b, 0x67, 0x24, 0xcb, 0xb8, 0x6a, 0x10, 0x69, 0xd6, 0xfb, 0x52, 0x40, 0xff, 0x20, 0xa5, 0xf3, 0x72, 0xe1, 0x3d, 0xa4, 0x8c, 0x81, 0x66, 0x16, 0x0d, 0x5d, 0xad, 0xa8, 0x50, 0x25, 0x78, 0x31, 0x77, 0x0c, 0x57, 0xe4, 0xe9, 0x15, 0x2d, 0xdb, 0x07, 0x87, 0xc8, 0xb0, 0x43, 0xde, 0xfc, 0xfe, 0xa9, 0xeb, 0xf5, 0xb0, 0xd3, 0x7b, 0xe9, 0x1f, 0x6e, 0xca, 0xe4, 0x03, 0x95, 0xc5, 0xd1, 0x59, 0x72, 0x63, 0xf0, 0x86, 0x54, 0xe8, 0x16, 0x62, 0x0b, 0x35, 0x29, 0xc2, 0x68, 0xd0, 0xd6, 0x3e, 0x90, 0x60, 0x57, 0x1d, 0xc9, 0xed, 0x3f, 0xed, 0xb0, 0x2f, 0x7e, 0x97, 0x02, 0x51, 0xec, 0xee, 0x6f, 0x82, 0x74, 0x76, 0x7f, 0xfb, 0xd6, 0xc4, 0xc3, 0xdd, 0xe8, 0xb1, 0x60, 0xfc, 0xc6, 0xb9, 0x0d, 0x6a, 0x33, 0x78, 0xc6, 0xc1, 0xbf, 0x86, 0x2c, 0x50, 0xcc, 0x9a, 0x70, 0x8e, 0x7b, 0xec, 0xab, 0x95, 0xac, 0x53, 0xa0, 0x4b, 0x07, 0x88, 0xaf, 0x42, 0xed, 0x19, 0x8d, 0xf6, 0x32, 0x17, 0x48, 0x47, 0x1d, 0x41, 0x6f, 0xfe, 0x2e, 0xa7, 0x8f, 0x4b, 0xa0, 0x51, 0xf3, 0xbf, 0x02, 0x0a, 0x48, 0x58, 0xf7, 0xa1, 0x6d, 0xea, 0xa5, 0x13, 0x5a, 0x5b, 0xea, 0x0c, 0x9e, 0x52, 0x4f, 0x9e, 0xb9, 0x71, 0x7f, 0x23, 0x83, 0xda, 0x1b, 0x86, 0x9a, 0x41, 0x29, 0xda, 0x70, 0xe7, 0x64, 0xa1, 0x7b, 0xd5, 0x0a, 0x22, 0x0d, 0x5c, 0x40, 0xc4, 0x81, 0x07, 0x25, 0x35, 0x4a, 0x1c, 0x10, 0xdb, 0x45, 0x0a, 0xff, 0x36, 0xd4, 0xe0, 0xeb, 0x5f, 0x68, 0xd6, 0x67, 0xc6, 0xd0, 0x8b, 0x76, 0x1a, 0x7d, 0x59, 0x42, 0xa1, 0xcb, 0x96, 0x4d, 0x84, 0x09, 0x9a, 0x3d, 0xe0, 0x52, 0x85, 0x6e, 0x48, 0x90, 0x85, 0x2a, 0x63, 0xb2, 0x69, 0xd2, 0x00, 0x43, 0x31, 0x37, 0xb3, 0x52, 0xaf, 0x62, 0xfa, 0xc1, 0xe0, 0x03, 0xfb, 0x62, 0xaa, 0x88, 0xc9, 0xb2, 0x2c, 0xd5, 0xa8, 0xf5, 0xa5, 0x4c, 0x12, 0x59, 0x4e, 0x06, 0x5e, 0x9b, 0x15, 0x66, 0x11, 0xb2, 0x27, 0x92, 0xdc, 0x98, 0x59, 0xde, 0xdf, 0xfa, 0x9a, 0x32, 0x2e, 0xc0, 0x5d, 0x3c, 0x33, 0x41, 0x6d, 0xaf, 0xb2, 0x25, 0x23, 0x14, 0xa5, 0x7b, 0xc7, 0x9b, 0x68, 0xf3, 0xda, 0xeb, 0xe3, 0xa9, 0xe2, 0x6f, 0x0e, 0x1d, 0x1c, 0xba, 0x55, 0xb6, 0x34, 0x6a, 0x93, 0x1f, 0x1f, 0xb8, 0x34, 0xc8, 0x84, 0x08, 0xb1, 0x6b, 0x6a, 0x28, 0x74, 0x74, 0xe5, 0xeb, 0x75, 0xe9, 0x7c, 0xd8, 0xba, 0xd8, 0x42, 0xa5, 0xee, 0x1f, 0x80, 0xd9, 0x96, 0xb2, 0x2e, 0xe7, 0xbf, 0xba, 0xeb, 0xd1, 0x69, 0xbb, 0x8f, 0xfd, 0x5a, 0x63, 0x8f, 0x39, 0x7f, 0xdf, 0x1d, 0x37, 0xd2, 0x18, 0x35, 0x9d, 0xb6, 0xcc, 0xe4, 0x27, 0x81, 0x89, 0x38, 0x38, 0x68, 0x33, 0xe7, 0x78, 0xd8, 0x76, 0xf5, 0xee, 0xd0, 0x4a, 0x07, 0x69, 0x19, 0x7a, 0xad, 0x18, 0xb1, 0x94, 0x61, 0x45, 0x53, 0xa2, 0x48, 0xda, 0x96, 0x4a, 0xf9, 0xee, 0x94, 0x2a, 0x1f, 0x6e, 0x18, 0x3c, 0x92, 0x46, 0xd1, 0x1a, 0x28, 0x18, 0x32, 0x1f, 0x3a, 0x45, 0xbe, 0x04, 0x35, 0x92, 0xe5, 0xa3, 0xcb, 0xb5, 0x2e, 0x32, 0x43, 0xac, 0x65, 0x17, 0x89, 0x99, 0x15, 0x03, 0x9e, 0xb1, 0x23, 0x2f, 0xed, 0x76, 0x4d, 0xd8, 0xac, 0x21, 0x40, 0xc4, 0x99, 0x4e, 0x65, 0x71, 0x2c, 0xb3, 0x45, 0xab, 0xfb, 0xe7, 0x72, 0x39, 0x56, 0x30, 0x6d, 0xfb, 0x74, 0xeb, 0x99, 0xf3, 0xcd, 0x57, 0x5c, 0x78, 0x75, 0xe9, 0x8d, 0xc3, 0xa2, 0xfb, 0x5d, 0xe0, 0x90, 0xc5, 0x55, 0xad, 0x91, 0x53, 0x4e, 0x9e, 0xbd, 0x8c, 0x49, 0xa4, 0xa4, 0x69, 0x10, 0x0c, 0xc5, 0x76, 0xe9, 0x25, 0x86, 0x8d, 0x66, 0x23, 0xa8, 0xdb, 0x5c, 0xe8, 0xd9, 0x30, 0xe1, 0x15, 0x7b, 0xc0, 0x99, 0x0f, 0x03, 0xec, 0xaa, 0x12, 0xef, 0xce, 0xd4, 0xea, 0x55, 0x5c, 0x08, 0x86, 0xf4, 0xf4, 0xb0, 0x83, 0x42, 0x95, 0x37, 0xb6, 0x38, 0xe0, 0x2b, 0x54, 0x89, 0xbd, 0x4e, 0x20, 0x9d, 0x3f, 0xc3, 0x4b, 0xb7, 0xec, 0xfa, 0x5a, 0x14, 0x03, 0xcb, 0x64, 0xc8, 0x34, 0x4a, 0x4b, 0x6e, 0xf8, 0x6e, 0x56, 0xf6, 0xdd, 0x5f, 0xa1, 0x24, 0xe2, 0xd4, 0xd0, 0x82, 0x64, 0x1f, 0x8e, 0x9b, 0xfa, 0xb4, 0xcb, 0xdb, 0x0a, 0xe8, 0x15, 0xfc, 0x15, 0xab, 0x4b, 0x18, 0xbf, 0xd4, 0x42, 0x14, 0x48, 0x82, 0x85, 0xdd, 0xeb, 0x49, 0x1b, 0x0b, 0x0b, 0x05, 0xe9, 0xb4, 0xa1, 0x33, 0x0a, 0x5d, 0x0e, 0x6c, 0x4b, 0xc0, 0xd6, 0x6c, 0x7c, 0xfb, 0x69, 0x0b, 0x53, 0x19, 0xe4, 0xf3, 0x35, 0xfc, 0xbe, 0xa1, 0x34, 0x02, 0x09, 0x4f, 0x74, 0x86, 0x92, 0xcd, 0x5d, 0x1a, 0xc1, 0x27, 0x0c, 0xf2, 0xc5, 0xcf, 0xdd, 0x23, 0x93, 0x02, 0xbd, 0x41, 0x5e, 0x42, 0xf0, 0xa0, 0x9d, 0x0c, 0x72, 0xc8, 0xec, 0x32, 0x0a, 0x8a, 0xfd, 0x3d, 0x5a, 0x41, 0x27, 0x0c, 0x88, 0x59, 0xad, 0x94, 0x2e, 0xef, 0x5d, 0x8f, 0xc7, 0xdf, 0x66, 0xe4, 0xdd, 0x56, 0x6c, 0x7b, 0xca, 0x55, 0x81, 0xae, 0xae, 0x5c, 0x1b, 0x1a, 0xab, 0xae, 0x99, 0x8d, 0xcc, 0x42, 0x97, 0x59, 0xf4, 0x14, 0x3f, 0x75, 0xc6, 0xd1, 0x88, 0xba, 0xaa, 0x84, 0x4a, 0xd0, 0x34, 0x08, 0x3b, 0x7d, 0xdb, 0x15, 0x06, 0xb0, 0x5c, 0xbd, 0x40, 0xf5, 0xa8, 0xec, 0xae, 0x36, 0x40, 0xdd, 0x90, 0x1c, 0x3e, 0x0d, 0x7e, 0x73, 0xc7, 0xc2, 0xc5, 0x6a, 0xff, 0x52, 0x05, 0x7f, 0xbe, 0xd0, 0x92, 0xfd, 0xb3, 0x6f, 0xff, 0x5d, 0xb7, 0x97, 0x64, 0x73, 0x7b, 0xca, 0xd1, 0x98, 0x24, 0x6b, 0x0b, 0x01, 0x68, 0xdd, 0x27, 0x85, 0x85, 0xb5, 0x83, 0xc1, 0xe0, 0x50, 0x64, 0xc7, 0xaf, 0xf1, 0xc6, 0x4d, 0xb1, 0xef, 0xc9, 0xb4, 0x0a, 0x6d, 0x65, 0xf3, 0x47, 0xcc, 0xa3, 0x02, 0x21, 0x0c, 0xbe, 0x22, 0x29, 0x05, 0xcf, 0x5f, 0xe8, 0x94, 0x6c, 0xe5, 0xdc, 0xc4, 0xdf, 0xbe, 0x3e, 0xa8, 0xb4, 0x18, 0xb0, 0x99, 0xb8, 0x6f, 0xff, 0x5d, 0xb9, 0xfd, 0x3b, 0x5d, 0x16, 0xbf, 0x3e, 0xd8, 0xb3, 0xd8, 0x08, 0x34, 0xf6, 0x47, 0x35, 0x5b, 0x72, 0x1a, 0x33, 0xad, 0x52, 0x5d, 0xb8, 0xd0, 0x77, 0xc6, 0xab, 0xba, 0x55, 0x09, 0x5f, 0x02, 0xf8, 0xd4, 0x5f, 0x53, 0x06, 0x91, 0xcd, 0x74, 0x42, 0xae, 0x54, 0x91, 0x81, 0x62, 0x13, 0x6f, 0xd8, 0xa9, 0x77, 0xc3, 0x6c, 0xcb, 0xf1, 0x29, 0x5a, 0xcc, 0xda, 0x35, 0xbd, 0x52, 0x23, 0xbe, 0x59, 0xeb, 0x12, 0x6d, 0xb7, 0x53, 0xee, 0xfc, 0xb4, 0x1b, 0x13, 0x5e, 0xba, 0x16, 0x7c, 0xc5, 0xf3, 0xe3, 0x6d, 0x07, 0x78, 0xf5, 0x2b, 0x21, 0x05, 0x88, 0x4c, 0xc0, 0xa1, 0xe3, 0x36, 0x10, 0xf8, 0x1b, 0xd8, 0x17, 0xfb, 0x6a, 0x4e, 0xd8, 0xb3, 0x47, 0x2d, 0x99, 0xbd, 0xbb, 0x5d, 0x37, 0x7d, 0xba, 0xf1, 0xe1, 0x7c, 0xc0, 0xc5, 0x54, 0x62, 0x7f, 0xcf, 0x5a, 0x4a, 0x93, 0xcc, 0xf1, 0x1b, 0x34, 0xc8, 0xa6, 0x05, 0x4c, 0x55, 0x8b, 0x54, 0x84, 0xd5, 0x77, 0xeb, 0xc0, 0x6d, 0x3a, 0x29, 0xbd, 0x75, 0x61, 0x09, 0x9a, 0x2c, 0xbb, 0xf7, 0x18, 0x79, 0x34, 0x90, 0x24, 0xa5, 0x81, 0x70, 0x87, 0xc5, 0x02, 0x7c, 0xba, 0xd4, 0x5e, 0x14, 0x8e, 0xe4, 0xed, 0xa2, 0x61, 0x6a, 0xb9, 0x6e, 0xb5, 0x4a, 0xb9, 0x01, 0x46, 0xf4, 0xcf, 0xbc, 0x09, 0x2f, 0x27, 0x4b, 0xbd, 0x86, 0x7a, 0x10, 0xe1, 0xd4, 0xc8, 0xd9, 0x20, 0x8d, 0x8a, 0x63, 0x00, 0x63, 0x44, 0xeb, 0x54, 0x0b, 0x75, 0x49, 0x10, 0xa2, 0xa7, 0xad, 0xb9, 0xd1, 0x01, 0x80, 0x63, 0x25, 0xc8, 0x12, 0xa6, 0xce, 0x1e, 0xbe, 0xfe, 0x7e, 0x5f, 0x3c, 0xdb, 0x34, 0xea, 0x37, 0xec, 0x3b, 0xd5, 0x28, 0xd2, 0x07, 0x8c, 0x9a, 0xb6, 0xee, 0x5e, 0x3e, 0xdf, 0x1d, 0x99, 0xb0, 0xe2, 0x46, 0xef, 0x5c, 0x1b, 0xb4, 0xea, 0x56, 0x2e, 0xde, 0x1f, 0x9d, 0xb8, 0xd3, 0x24, 0xab, 0xd4, 0x2a, 0xd6, 0x2e, 0xde, 0x1f, 0x9d, 0xb8, 0xf2, 0x66, 0x2f, 0xbd, 0xf8, 0x72, 0x66, 0x4e, 0x1e, 0x9f, 0x9d, 0xb8, 0xf2, 0x47, 0x0c, 0x9a, 0xb6, 0xee, 0x3f, 0xfc, 0x7a, 0x57, 0x0d, 0x79, 0x70, 0x62, 0x27, 0xad, 0xb9, 0xd1, 0x01, 0x61, 0x40, 0x02, 0x67, 0x2d, 0xd8, 0x32, 0xe6, 0x2f, 0xdc, 0x3a, 0xd7, 0x2c, 0xbb, 0xf4, 0x4b, 0xf5, 0x49, 0xf1, 0x60, 0x23, 0xc4, 0x0a, 0x77, 0x4d, 0xf9, 0x51, 0x01, 0x80, 0x63, 0x25, 0xa9, 0xb1, 0xe0, 0x42, 0xe7, 0x4c, 0x1a, 0x97, 0xac, 0xbb, 0xf4, 0x6a, 0x37, 0xcd, 0x18, 0xb2, 0xe6, 0x2f, 0xdc, 0x1b, 0x95, 0xa8, 0xd2, 0x07, 0x6d, 0x58, 0x32, 0xe6, 0x4e, 0x1e, 0x9f, 0xbc, 0xfa, 0x57, 0x0d, 0x79, 0x51, 0x20, 0xc2, 0x06, 0x6f, 0x5c, 0x1b, 0x95, 0xa8, 0xb3, 0xc5, 0xe9, 0x31, 0xe0, 0x23, 0xc4, 0x0a, 0x77, 0x4d, 0x18, 0x93, 0x85, 0x69, 0x31, 0xc1, 0xe1, 0x21, 0xc0, 0xe3, 0x44, 0x0a, 0x77, 0x6c, 0x5a, 0x17, 0x8d, 0x98, 0x93, 0xa4, 0xab, 0xd4, 0x2a, 0xb7, 0xec, 0x5a, 0x17, 0xac, 0xbb, 0xf4, 0x4b, 0x14, 0xaa, 0xb7, 0xec, 0x3b, 0xd5, 0x28, 0xb3, 0xc5, 0xe9, 0x31, 0xc1, 0x00, 0x82, 0x67, 0x4c, 0xfb, 0x55, 0x28, 0xd2, 0x26, 0xaf, 0xbd, 0xd9, 0x11, 0x81, 0x61, 0x21, 0xa1, 0xa1, 0xc0, 0x02, 0x86, 0x6f, 0x5c, 0x1b, 0xb4, 0xcb, 0x14, 0x8b, 0x94, 0xaa, 0xd6, 0x2e, 0xbf, 0xdd, 0x19, 0xb0, 0xe2, 0x46, 0x0e, 0x7f, 0x7c, 0x5b, 0x15, 0x89, 0x90, 0x83, 0x84, 0x6b, 0x54, 0x0b, 0x75, 0x68, 0x52, 0x07, 0x6d, 0x58, 0x32, 0xc7, 0xed, 0x58, 0x32, 0xc7, 0xed, 0x58, 0x32, 0xe6, 0x4e, 0xff, 0x7c, 0x7a, 0x76, 0x6e, 0x3f, 0xdd, 0x38, 0xd3, 0x05, 0x88, 0x92, 0xa6, 0xaf, 0xdc, 0x1b, 0xb4, 0xcb, 0xf5, 0x68, 0x52, 0x07, 0x8c, 0x7b, 0x55, 0x09, 0x90, 0x83, 0x84, 0x6b, 0x54, 0x2a, 0xb7, 0xec, 0x3b, 0xd5, 0x09, 0x90, 0xa2, 0xc6, 0x0e, 0x7f, 0x7c, 0x7a, 0x57, 0x0d, 0x98, 0xb2, 0xc7, 0xed, 0x58, 0x32, 0xc7, 0x0c, 0x7b, 0x74, 0x4b, 0x14, 0x8b, 0x94, 0xaa, 0xb7, 0xcd, 0x18, 0x93, 0xa4, 0xca, 0x16, 0xae, 0xbf, 0xdd, 0x19, 0xb0, 0xe2, 0x46, 0x0e, 0x7f, 0x5d, 0x19, 0x91, 0x81, 0x80, 0x63, 0x44, 0xeb, 0x35, 0xc9, 0x10, 0x83, 0x65, 0x48, 0x12, 0xa6, 0xce, 0x1e, 0x9f, 0xbc, 0xdb, 0x15, 0x89, 0x71, 0x60, 0x23, 0xc4, 0xeb, 0x54, 0x2a, 0xb7, 0xec, 0x5a, 0x36, 0xcf, 0x81, 0x10, 0xac, 0x74 };<file_sep>/print.ino void printIntln(int msg) { if (LOG == true) { Serial.println(msg); } } void printInt(int msg) { if (LOG == true) { Serial.print(msg); } } void print(String msg) { if (LOG == true) { Serial.print(msg); } } void println(String msg) { if (LOG == true) { Serial.println(msg); } } void printBytes( byte* bytes, int length) { for (int i = 0; i < length; i++) { print(bytes[i]); } println(""); } void printBits(byte data) { byte mask = 1; //our bitmask for (mask = 128; mask > 0; mask >>= 1) { //iterate through bit mask if (data & mask) { // if bitwise AND resolves to true print("1"); } else { //if bitwise and resolves to false print("0"); } } println(""); }<file_sep>/Keys.ino //################### keyboard ######################### byte rows[] = { 23, 22, 21, 20, 15, 14, 9 }; const int rowCount = sizeof(rows) / sizeof(rows[0]); byte cols[] = { 5, 4, 3, 2, 1, 0 }; const int colCount = sizeof(cols) / sizeof(cols[0]); byte keyStates[colCount][rowCount]; void setupKeys() { initKeyStates(); Keyboard.begin(); for (int x = 0; x < rowCount; x++) { pinMode(rows[x], INPUT_PULLUP); } for (int x = 0; x < colCount; x++) { pinMode(cols[x], INPUT); } } bool readKeys(int keyBufSize, byte* keysBuffer) { int keyIdx = 0; bool keyRead = false; for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) { byte row = rows[rowIdx]; pinMode(row, OUTPUT); digitalWrite(row, LOW); for (int colIdx = 0; colIdx < colCount; colIdx++) { byte col = cols[colIdx]; pinMode(col, INPUT_PULLUP); delayMicroseconds(15); byte btnState = !digitalRead(col); if (keyStates[colIdx][rowIdx] != btnState) { // check if button state changed keyRead = true; if (keyIdx >= keyBufSize) { // Only so many button presses can be tracked and sent at one time via i2c println("Key buffer full"); return true; // buffer full } // col row nonce state // 111 111 1 1 byte state = colIdx; state = state << 3; state += rowIdx; state = state << 2; state += 2; // flip the empty bit as a nonce so we can distinguish between no value and 0,0 released state += btnState; keysBuffer[keyIdx++] = state; } keyStates[colIdx][rowIdx] = btnState; pinMode(col, INPUT); } pinMode(row, INPUT); } return keyRead; } void initKeyStates() { for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) { for (int colIdx = 0; colIdx < colCount; colIdx++) { keyStates[colIdx][rowIdx] = 0; } } }<file_sep>/mouse.ino #ifdef ADVANCE_MODE #include <AdvMouse.h> #define MOUSE_BEGIN AdvMouse.begin() #define MOUSE_PRESS(x) AdvMouse.press_(x) #define MOUSE_RELEASE(x) AdvMouse.release_(x) #else #include <Mouse.h> #define MOUSE_BEGIN Mouse.begin() #define MOUSE_PRESS(x) Mouse.press(x) #define MOUSE_RELEASE(x) Mouse.release(x) #endif unsigned long lastWheelTime = 0; void processBallMotionData(int8_t x, int8_t y, int8_t wheel, int8_t horiz, bool invertXY) { unsigned long elapsed = curTime - lastWheelTime; if (elapsed < 50000) { wheel = 0; horiz = 0; } else { lastWheelTime = curTime; } if (wheel <= 1 && wheel >= -1) { wheel = 0; } else { wheel = wheel / 2; print("wheel: "); println(wheel); } if (horiz <= 1 && horiz >= -1) { horiz = 0; } else { horiz = horiz / 2; print("horiz: "); println(horiz); } if (invertXY) { x = x * -1; y = y * -1; wheel = wheel * -1; horiz = horiz * -1; } Mouse.move(x * -1, y, wheel, horiz); } <file_sep>/dactylmanu-ball.ino const int isRightPin = 7; const int isRightPinOut = 8; bool isPrimary = false; bool LOG = false; bool isRightHalf = false; unsigned long lastTS = 0; unsigned long curTime = micros(); const int keyBufSize = 6; uint8_t keyBuffer[keyBufSize]; const int ballBufSize = 2; int8_t ballMotionBuffer[ballBufSize]; bool keysSent = true; void setup() { Serial.begin(57600); Serial.println("Dactyl Manuball 2.0 starting..."); isRightHalf = isRight(); if (isRightHalf) { println("Right Side"); } else { println("Left Side"); } if (!bitRead(USB1_PORTSC1, 7)) { //usb connected isPrimary = true; println("Is Primary"); } else { //usb disconnected isPrimary = false; println("Is Secondary"); } initKeyBuf(); setupBall(!isRightHalf); setupKeys(); setupI2c(isPrimary); Serial.println("Keyboad ready"); } void loop() { curTime = micros(); unsigned long elapsed = curTime - lastTS; if (elapsed >= 5000) // polling interval : more than > 0.5 ms. { if (isPrimary) { if (readBall(ballMotionBuffer)) { processBallMotionData(ballMotionBuffer[0], ballMotionBuffer[1], 0, 0, !isRightHalf); initBallBuf(); } if (readKeys(keyBufSize, keyBuffer)) { processKeyStates(isRightHalf, keyBufSize, keyBuffer); initKeyBuf(); } if (readSecondary()) { processKeyStates(!isRightHalf, keyBufSize, keyBuffer); processBallMotionData(0, 0, ballMotionBuffer[1], ballMotionBuffer[0], !isRightHalf); initKeyBuf(); initBallBuf(); } } else { readBall(ballMotionBuffer); readKeys(keyBufSize, keyBuffer); } lastTS = curTime; } } void initKeyBuf() { for (int i = 0; i < keyBufSize; i++) { keyBuffer[i] = 0; } } void initBallBuf() { for (int i = 0; i < ballBufSize; i++) { ballMotionBuffer[i] = 0; } } bool isRight() { pinMode(isRightPin, INPUT_PULLDOWN); pinMode(isRightPinOut, OUTPUT); digitalWrite(isRightPinOut, HIGH); delayMicroseconds(100); byte isRight = digitalRead(isRightPin); pinMode(isRightPin, INPUT_DISABLE); pinMode(isRightPinOut, INPUT_DISABLE); return isRight == 1; }<file_sep>/trackBall.ino // Uncomment this line to activate an advanced mouse mode // Need to install AdvMouse library (copy /library/AdvMouse to the Arduino libraries) //#define ADVANCE_MODE #include <SPI.h> #include <avr/pgmspace.h> // Configurations // The default CPI value should be in between 100 -- 12000 #define CPI 2000 #define DEBOUNCE 10 //unit = ms. #define NUMCPI 4 //Set this to a pin your buttons are attached #define NUMBTN 4 #define Btn1_Pin 3 // left button #define Btn2_Pin 0 // right button #define Btn4_Pin 2 // middle button #define Btn8_Pin 1 // back button // Registers #define Product_ID 0x00 #define Revision_ID 0x01 #define Motion 0x02 #define Delta_X_L 0x03 #define Delta_X_H 0x04 #define Delta_Y_L 0x05 #define Delta_Y_H 0x06 #define SQUAL 0x07 #define Raw_Data_Sum 0x08 #define Maximum_Raw_data 0x09 #define Minimum_Raw_data 0x0A #define Shutter_Lower 0x0B #define Shutter_Upper 0x0C #define Ripple_Control 0x0D #define Resolution_L 0x0E #define Resolution_H 0x0F #define Config2 0x10 #define Angle_Tune 0x11 #define Frame_Capture 0x12 #define SROM_Enable 0x13 #define Run_Downshift 0x14 #define Rest1_Rate_Lower 0x15 #define Rest1_Rate_Upper 0x16 #define Rest1_Downshift 0x17 #define Rest2_Rate_Lower 0x18 #define Rest2_Rate_Upper 0x19 #define Rest2_Downshift 0x1A #define Rest3_Rate_Lower 0x1B #define Rest3_Rate_Upper 0x1C #define Observation 0x24 #define Data_Out_Lower 0x25 #define Data_Out_Upper 0x26 #define SROM_ID 0x2A #define Min_SQ_Run 0x2B #define Raw_Data_Threshold 0x2C #define Control2 0x2D #define Config5_L 0x2E #define Config5_H 0x2F #define Power_Up_Reset 0x3A #define Shutdown 0x3B #define Inverse_Product_ID 0x3F #define LiftCutoff_Cal3 0x41 #define Angle_Snap 0x42 #define LiftCutoff_Cal1 0x4A #define Motion_Burst 0x50 #define SROM_Load_Burst 0x62 #define Lift_Config 0x63 #define Raw_Data_Burst 0x64 #define LiftCutoff_Cal2 0x65 #define LiftCutoff_Cal_Timeout 0x71 #define LiftCutoff_Cal_Min_Length 0x72 #define PWM_Period_Cnt 0x73 #define PWM_Width_Cnt 0x74 const int ncs = 10; // This is the SPI "slave select" pin that the sensor is hooked up to const int reset = 8; // Optional unsigned long Cpis[NUMCPI] = { 400, 800, 1200, 2000 }; struct CpiUpdater { bool target_set; bool updated; uint8_t target_cpi_index; }; CpiUpdater CpiUpdate = { false, false, 3 }; // Default Cpis[3] = 2000 byte initComplete = 0; bool inBurst = false; // in busrt mode bool reportSQ = false; // report surface quality int16_t dx, dy; unsigned long lastButtonCheck = 0; //Be sure to add the SROM file into this sketch via "Sketch->Add File" extern const unsigned short firmware_length; extern const unsigned char firmware_data[]; bool invertXY = false; void setupBall(bool invert) { invertXY = invert; pinMode(ncs, OUTPUT); pinMode(reset, INPUT_PULLUP); pinMode(Btn1_Pin, INPUT_PULLUP); pinMode(Btn2_Pin, INPUT_PULLUP); pinMode(Btn4_Pin, INPUT_PULLUP); pinMode(Btn8_Pin, INPUT_PULLUP); SPI.begin(); SPI.setDataMode(SPI_MODE3); SPI.setBitOrder(MSBFIRST); //SPI.setClockDivider(4); Serial.println("ON"); performStartup(); dx = dy = 0; delay(500); //dispRegisters(); initComplete = 9; lastTS = micros(); MOUSE_BEGIN; } void adns_com_begin() { digitalWrite(ncs, LOW); } void adns_com_end() { digitalWrite(ncs, HIGH); } byte adns_read_reg(byte reg_addr) { adns_com_begin(); // send adress of the register, with MSBit = 0 to indicate it's a read SPI.transfer(reg_addr & 0x7f); delayMicroseconds(35); // tSRAD // read data byte data = SPI.transfer(0); delayMicroseconds(1); // tSCLK-NCS for read operation is 120ns adns_com_end(); delayMicroseconds(19); // tSRW/tSRR (=20us) minus tSCLK-NCS return data; } void adns_write_reg(byte reg_addr, byte data) { adns_com_begin(); //send adress of the register, with MSBit = 1 to indicate it's a write SPI.transfer(reg_addr | 0x80); //sent data SPI.transfer(data); delayMicroseconds(20); // tSCLK-NCS for write operation adns_com_end(); delayMicroseconds(100); // tSWW/tSWR (=120us) minus tSCLK-NCS. Could be shortened, but is looks like a safe lower bound } void adns_upload_firmware() { // send the firmware to the chip, cf p.18 of the datasheet Serial.println("Uploading firmware..."); //Write 0 to Rest_En bit of Config2 register to disable Rest mode. adns_write_reg(Config2, 0x00); // write 0x1d in SROM_enable reg for initializing adns_write_reg(SROM_Enable, 0x1d); // wait for more than one frame period delay(10); // assume that the frame rate is as low as 100fps... even if it should never be that low // write 0x18 to SROM_enable to start SROM download adns_write_reg(SROM_Enable, 0x18); // write the SROM file (=firmware data) adns_com_begin(); SPI.transfer(SROM_Load_Burst | 0x80); // write burst destination adress delayMicroseconds(15); // send all bytes of the firmware unsigned char c; for (int i = 0; i < firmware_length; i++) { c = (unsigned char)pgm_read_byte(firmware_data + i); SPI.transfer(c); delayMicroseconds(15); } //Read the SROM_ID register to verify the ID before any other register reads or writes. adns_read_reg(SROM_ID); //Write 0x00 (rest disable) to Config2 register for wired mouse or 0x20 for wireless mouse design. adns_write_reg(Config2, 0x00); adns_com_end(); } void setCPI(int cpi) { unsigned cpival = cpi / 50; adns_com_begin(); adns_write_reg(Resolution_L, (cpival & 0xFF)); adns_write_reg(Resolution_H, ((cpival >> 8) & 0xFF)); adns_com_end(); Serial.print("Got "); Serial.println(cpi); Serial.print("Set cpi to "); Serial.println(cpival * 50); } void performStartup(void) { // hard reset adns_com_end(); // ensure that the serial port is reset adns_com_begin(); // ensure that the serial port is reset adns_com_end(); // ensure that the serial port is reset adns_write_reg(Shutdown, 0xb6); // Shutdown first delay(300); adns_com_begin(); // drop and raise ncs to reset spi port delayMicroseconds(40); adns_com_end(); delayMicroseconds(40); adns_write_reg(Power_Up_Reset, 0x5a); // force reset delay(50); // wait for it to reboot // read registers 0x02 to 0x06 (and discard the data) adns_read_reg(Motion); adns_read_reg(Delta_X_L); adns_read_reg(Delta_X_H); adns_read_reg(Delta_Y_L); adns_read_reg(Delta_Y_H); // upload the firmware adns_upload_firmware(); delay(10); setCPI(Cpis[CpiUpdate.target_cpi_index]); Serial.println("Optical Chip Initialized"); } // device signature void dispRegisters(void) { int oreg[7] = { 0x00, 0x3F, 0x2A, 0x02 }; char* oregname[] = { "Product_ID", "Inverse_Product_ID", "SROM_Version", "Motion" }; byte regres; digitalWrite(ncs, LOW); int rctr = 0; for (rctr = 0; rctr < 4; rctr++) { SPI.transfer(oreg[rctr]); delay(1); Serial.println("---"); Serial.println(oregname[rctr]); Serial.println(oreg[rctr], HEX); regres = SPI.transfer(0); Serial.println(regres, BIN); Serial.println(regres, HEX); delay(1); } digitalWrite(ncs, HIGH); } bool readBall(int8_t* motionData) { byte burstBuffer[12]; curTime = micros(); if (!inBurst) { adns_write_reg(Motion_Burst, 0x00); // start burst mode lastTS = curTime; inBurst = true; } adns_com_begin(); SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE3)); SPI.transfer(Motion_Burst); delayMicroseconds(35); // waits for tSRAD SPI.transfer(burstBuffer, 12); // read burst buffer delayMicroseconds(1); // tSCLK-NCS for read operation is 120ns SPI.endTransaction(); /* BYTE[00] = Motion = if the 7th bit is 1, a motion is detected. ==> 7 bit: MOT (1 when motion is detected) ==> 3 bit: 0 when chip is on surface / 1 when off surface ] = Observation BYTE[02] = Delta_X_L = dx (LSB) BYTE[03] = Delta_X_H = dx (MSB) BYTE[04] = Delta_Y_L = dy (LSB) BYTE[05] = Delta_Y_H = dy (MSB) BYTE[06] = SQUAL = Surface Quality register, max 0x80 - Number of features on the surface = SQUAL * 8 BYTE[07] = Raw_Data_Sum = It reports the upper byte of an 18‐bit counter which sums all 1296 raw data in the current frame; * Avg value = Raw_Data_Sum * 1024 / 1296 BYTE[08] = Maximum_Raw_Data = Max raw data value in current frame, max=127 BYTE[09] = Minimum_Raw_Data = Min raw data value in current frame, max=127 BYTE[10] = Shutter_Upper = Shutter LSB BYTE[11] = Shutter_Lower = Shutter MSB, Shutter = shutter is adjusted to keep the average raw data values within normal operating ranges */ int motion = (burstBuffer[0] & 0x80) > 0; int surface = (burstBuffer[0] & 0x08) > 0; // 0 if on surface / 1 if off surface int yl = burstBuffer[2]; int yh = burstBuffer[3]; int xl = burstBuffer[4]; int xh = burstBuffer[5]; int squal = burstBuffer[6]; int x = xh << 8 | xl; int y = yh << 8 | yl; int16_t dx = 0; int16_t dy = 0; dx -= y; dy -= x; adns_com_end(); // update only if a movement is detected. int8_t mdx = constrain(dx, -127, 127); int8_t mdy = constrain(dy, -127, 127); if (motion) { motionData[0] = mdx; motionData[1] = mdy; } if (reportSQ && !surface) // print surface quality { println(squal); } lastTS = curTime; // update CPI cycled from button combo if (CpiUpdate.target_set == true && CpiUpdate.updated == false) { setCPI(Cpis[CpiUpdate.target_cpi_index]); CpiUpdate.updated = true; } // command process routine if (Serial.available() > 0) { char c = Serial.read(); switch (c) { case 'Q': // Toggle reporting surface quality reportSQ = !reportSQ; break; case 'I': // sensor info (signature) inBurst = false; dispRegisters(); break; case 'C': // set CPI int newCPI = readNumber(); setCPI(newCPI); break; } } return motion; } unsigned long readNumber() { String inString = ""; for (int i = 0; i < 10; i++) { while (Serial.available() == 0) ; int inChar = Serial.read(); if (isDigit(inChar)) { inString += (char)inChar; } if (inChar == '\n') { int val = inString.toInt(); return (unsigned long)val; } } // flush remain strings in serial buffer while (Serial.available() > 0) { Serial.read(); } return 0UL; }
f3a4203aaab8dff3086da53d89f2afd9504d7ad0
[ "C++" ]
8
C++
drGarbinsky/dactylmanu-ball
8fabea97620cbd3f61014730b842abe8e43f2103
5b74f80862d3f5bf92f510b33c4ef586ae83264a
refs/heads/lru_cache
<file_sep>Step by Step Guide Create a repo, with the README.md initialized on GitHub. Name the repo as toy-problems. Add your mentor to this repo as a collaborator. Any practice problems that you practice can be part of this repo. Now create a branch lru-cache in the toy-problems repo. Start developing python code for the LRU cache problem. Begin by creating a python class. The class should be a constructor to initialize the properties of the LRU object. Think about what properties are required. Then complete the constructor. This is a good time to commit and the commit message could be to “add constructor for LRU”. Next, think about what public methods should be provided to anyone who is using your LRU object. I can think of 3 methods, put, get and get_cache (not really required but this is useful for testing as you will see below). Think about the method signatures and then create blank methods. Don’t complete the method logic yet. To keep the program from failing with syntax errors, you could write a pass python statement after the method signature. Another good time to commit and I’ll let you decide the commit message. Next step is to write a class for testing the LRU object. So, a general convention is to write LRUTest. In this test class you will import LRU, set up test cases for all the public methods to ensure that they work as expected. Writing the test cases before completing the logic for the put, get and get_cache methods. This is part of the test first development strategy. In the main method, create an object of LRU, and design test cases to verify the correctness of put, get and get_cache methods. Verify for all the test cases if the return values match with the expected results using assert. If your test program returns with no errors then your tests have passed otherwise you will see the error messages. At this stage, as there is no logic in LRU, your test cases will fail. Your strategy now is to write the logic so that the test cases pass. You may have guessed this step, commit! Now write code for your put, get and get_cache methods. Verify if the LRU is working as expected by running the LRUTest. Commit every bug fix and it will create a nice trace of what went wrong. This is not required in general on real projects but as it is your toy-problems repo it is useful to review the common mistakes that you make while programming. Now that you have completed your task, create a pull request and ask your mentor to review your work.<file_sep>class LRUCache(): def _init_(self,k): self.k = k list = [] def put(self,k): if len(self.list) == 6: if k not in self.list: self.list.pop(0) self.list.append(k) else: self.list.remove(k) self.list.append(k) else: if k not in self.list: self.list.append(k) else: self.list.remove(k) self.list.append(k) def get(self): return self.list[0] def get_cache(self): return self.list<file_sep>from LRUcache import LRUCache class LRUtest: def __init__(self): self.lru_cache=LRUCache() def put(self, k): return self.lru_cache.put(k) def get(self): return self.lru_cache.get() def get_cache(self): return self.lru_cache.get_cache() def main(): LRUtest_obj=LRUtest() LRUtest_obj.put(1) LRUtest_obj.put(2) LRUtest_obj.put(3) LRUtest_obj.put(2) assert LRUtest_obj.get() == 1 assert [1,3,2] == LRUtest_obj.get_cache() LRUtest_obj.put(4) LRUtest_obj.put(5) LRUtest_obj.put(4) LRUtest_obj.put(6) assert [1,3,2,5,4,6] == LRUtest_obj.get_cache() print("All the Test cases are passed") if __name__ == '__main__': main()
deb6f6fed403956294b098522238859a32b44c3a
[ "Markdown", "Python" ]
3
Markdown
vamsikrishnanunna-1998/Toy_problem
9682a6e2036dc7723f3fc545109e9394aab44675
2ecee88723a5c1a364693fef78296c31964be12b
refs/heads/master
<repo_name>qt314cumslut/discord-gif-bot<file_sep>/README.md # discord-gif-bot A simple discord bot template which posts gifs you have saved to a directory. ## NodeJs & Discord.js Literally just a bare bones template for posting a gif via a discord bot. <file_sep>/config.js module.exports = { discordAPI: 'Ur Bot API Token', prefix: '!', } ; <file_sep>/index.js // Imports const Discord = require('discord.js'); const conf = require('./config.js'); const bot = new Discord.Client(); // Vars const token = conf.discordAPI; var prefix = conf.prefix; // Main bot.on('message', message => { if (message.author.bot) return; let messageArray = message.content.split(' '); let args = messageArray.slice(1); let cmd = messageArray[0]; let // Porn if (cmd === `${prefix}porn`) { message.channel.send({files: ["gifs/1.gif"]}) } }); bot.login(token);
8228c9282d5848814a69378c7e2b46f3cec366ff
[ "Markdown", "JavaScript" ]
3
Markdown
qt314cumslut/discord-gif-bot
1d2f09521e1e3fc42f161227f0f5483c8ecf0f1d
5ae9379c99625fecfa67f9d9a4382ab8baba1f75
refs/heads/master
<file_sep>from django.contrib import admin from django.urls import path from lists import views from django.conf.urls import url urlpatterns = [ url(r'^$', views.home_page, name='home') ] <file_sep>from selenium import webdriver from selenium.webdriver.common.keys import Keys import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self): # Edyta dowiedziała sie o nowej, wspaniałej aplikacji w postaci listy rzeczy do zrobienia # Postanowiła więc przejść na stronę główną tej aplikacji self.browser.get('http://localhost:8000') #Zwróciła uwagę, że tytuł strony i nagłówek zawierają słowo Listy. self.assertIn('Listy', self.browser.title) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn('lista', header_text) # Od razu zostaje zachęcona, aby wpisać rzecz do zrobienia. inputbox = self.browser.find_element_by_id('id_new_item') self.assertEqual( inputbox.get_attribute('placeholder'), 'Wpisz rzeczy do zrobienia' ) # W polu tekstowym wpisała "Kupić pawie pióra" (<NAME> # polega na tworzeniu ozdobnych przynęt). inputbox.send_keys('Kupić pawie pióra') # Po naciśnięciu klawisza Enter strona została uaktulaniona i wyświetla # "1: Kupić pawie pióra" jako element listy do zrobienia. inputbox.send_keys(Keys.ENTER) table = self.browser.find_element_by_id('id_list_table') rows = table.find_elements_by_tag_name('tr') self.assertTrue( any(row.text == '1: Kupić pawie pióra' for row in rows), "Nowy element nie znajduje się w tabeli." ) # Na stronie nadal znajduje się pole tekstowe zachęcające do podania kolejnego zadaniai. # Edyta wpisała "Użyć pawich piór do zrobienia przynęty" (Edyta jest niezwykle skrupulatna). self.fail('Zakończenie testu') if __name__ == '__main__': unittest.main(warnings='ignore') # Strona została ponownie uaktulaniona i teraz wyświetla dwa elementy na liście rzeczy do zrobienia. #Edyta była ciekawa, czy witryna zapamięta jej listę. Zwróciła uwagę na wygenerowany dla niej #unikatowy adres URL,obok którego znajduje się pewien tekst z wyjaśnieniem #Przechodzi pod podany adres URL i widzi wyświetloną swoją listę rzeczy do zrobienia. #Usatysfakcjonowana kładzie się spać. browser.quit()
3706577e4b4e81c72d53959156e5ab5ffe54f15a
[ "Python" ]
2
Python
swiderrr/tdd_python
389a4e4c1a7087a406d4e6475ca2acd2c9fef3ca
b25af95e6aeb7f49499554a2d9a6c8dff67029ea
refs/heads/master
<repo_name>brooks/narabe<file_sep>/app/controllers/index.rb get '/' do puts session.inspect if signed_in? @games = Game.all_active @player = current_player erb :lobby else erb :login end end<file_sep>/TODO.md TODO ---- * Handle session messages, displaying and clearing * Add multi-player support * list only active games in lobby * ensure resign game destroys record in db<file_sep>/app/controllers/players.rb # create new user post '/signup' do player = Player.create :email => params[:email], :password => params[:password], :password_confirmation => params[:password_confirmation] if player session[:message] = "Sign up successful" session[:remember_token] = player.remember_token else session[:message] = "Error with signup" end redirect "/" end # retrieve user profile page get '/players/:id' do @player = Player.find(params[:id]) if @player.remember_token == session[:remember_token] erb :profile else session[:message] = "Unauthorized access" redirect '/' end end <file_sep>/app/models/game.rb class Game < ActiveRecord::Base has_many :players, :through => :player_games has_many :player_games def self.all_active # TODO: Game.where("full = false") Game.all end def is_available?(player) !self.full && has_waiting_player? && new_player_is_unique?(player) end private def has_waiting_player? self.players.length == 1 end def new_player_is_unique?(player) !self.players.include?(player) end end <file_sep>/app/controllers/games.rb # before do # authorize # end # create new game post "/games" do game = Game.create() game.players << current_player redirect "/games/#{game.id}" end # retrieve active game get "/games/:id" do @game = Game.find(params[:id]) @player = current_player if @game.players.include? @player # render game board erb :game else # redirect to player page redirect "/players/#{player.id}" end end put "/games/:id" do game = Game.find(params[:id]) player = current_player if game.is_available?(player) game.players << player game.update_attributes :full => true {:status => "success"}.to_json else {:status => "error"}.to_json end end put "/games/:id/status" do # return game status end <file_sep>/app/controllers/sessions.rb # login post '/login' do player = Player.find_by_email(params[:email]) if player && player.authenticate(params[:password]) session[:remember_token] = player.remember_token session[:message] = "Login successful." else session[:message] = "Login failed." end redirect "/" end # logout delete "/logout" do if session.delete :remember_token session[:message] = "Logout successful" {:status => "success"}.to_json else {:status => "failure"}.to_json end end <file_sep>/app/helpers/authentication.rb helpers do def signed_in? session[:remember_token] end def authorize unless current_user session[:message] = "Unauthorized" redirect '/' end end def current_player Player.find_by_remember_token(session[:remember_token]) end def render_message session[:message] end def clear_message session.delete(:message) end end <file_sep>/public/js/application.js $(function(){ GameWorker.init(); GameModule.init(); $("#resign").on("click", function(e){ e.preventDefault(); var result = confirm("Are you sure you want to resign?"); if (result) { // handle resign game here. $(location).attr("href", "/"); } }); $("#signup-btn").on("click", function(e){ e.preventDefault(); $("#login").hide(); $("#signup").fadeIn(); }); $("#login-btn").on("click", function(e){ e.preventDefault(); $("#signup").hide(); $("#login").fadeIn(); }); $("#logout-btn").on("click", function(e){ e.preventDefault(); $.ajax({ type: "DELETE", url: "/logout", dataType: "json" }) .done(function(data){ if(data.status === "success") { console.log("sucess signing out"); window.location.reload(true); } else console.log("server error. please try again."); }) .error(function(){ alert("Error logging out. Please try again."); }); }); });<file_sep>/app/models/player.rb class Player < ActiveRecord::Base VALID_EMAIL = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i attr_accessible :email, :password, :password_confirmation has_many :games, :through => :player_games has_many :player_games has_secure_password before_validation { self.email.downcase! } before_save :create_remember_token validates :email, :presence => true, :format => { :with => VALID_EMAIL } validates :password, :presence => true validates :password_confirmation, :presence => true private def create_remember_token self.remember_token = SecureRandom.urlsafe_base64 end end <file_sep>/README.md About ===== Narabe is a simple multi-player tic-tac-toe game built in Sinatra with lots of front-end javascript.
57e22fc00d4924bf595f1b23c1918c47844b400c
[ "Markdown", "JavaScript", "Ruby" ]
10
Ruby
brooks/narabe
b3870eeae5d89b87c721201f0cc37fd5f7ab8332
f93fcbc5257a142c50d9c918111094b3b743c6e1
refs/heads/main
<file_sep>// Asignar nombre y version de la caché const CACHE_NAME = 'v1_cache_ruben_terre_pwa'; // Ficheros a cachear en la aplicación var urlsToCache = [ './', './css/styles.css', './images/Favicom/favicon.png', './images/Favicom/favicon_512x512.png', './images/Favicom/favicon_152x152.png', './images/Favicom/favicon_120x120.png', './images/Favicom/favicon_76x76.png', './images/Favicom/favicon_60x60.png', ]; // Evento install //Que la web funcione sin conexiÓN //instalación del service worker y guardar en caché los recursosestáticos self.addEventListener('install', e => { e.waitUntil( caches.open(CACHE_NAME) .then(cache => { return cache.addAll(urlsToCache) .then(() => { self.skipWaiting(); }) }) .catch(err => { console.log( 'No se ha registrado el caché', err) }) ) }) // Evento activate self.addEventListener('activate', e => { const cacheWhitelist = [CACHE_NAME]; e.waitUntil( caches.keys() .then(cacheNames => { return Promise.all( cacheNames.map(cacheName => { if(cacheWhitelist.indexOf(cacheName) === 1){ // Borrar elementos que no necesita return caches.delete(cacheName); } }) ) }) .then( ()=>{ //Activar cache self.clientInformation.claim(); } ) ) }); // Evento fetch self.addEventListener('fetch', e => { e.respondWith( caches.match(e.request) .then(res => { if(res){ // devuelvo datos desde caché return res; } return fetch(e.request); }) ) });<file_sep># Convierte tu web en una PWA Con estos archivos he convertido mi sitio web en una PWA. Esta tecnología tiene muchas ventajas: - Así como existen aplicaciones para Windows, Mac, Android o iOS, también existen otro tipo de aplicaciones que no dependen de ningún sistema operativo, sino que tienen lugar en una página web en un navegador. - Son aplicaciones más fluidas y con mayor capacidad de respuesta - Son aplicaciones rápidas de crear - Pueden contener notificaciones push Puedes probarlo en [RubenTerre](https://www.rubenterre.com/) # Convert to PWA With these files I have converted my website into a PWA. This technology has many advantages: - Just as there are applications for Windows, Mac, Android or iOS, there are also other types of applications that do not depend on any operating system, but take place on a web page in a browser. - Smoother and more responsive apps - Quick apps to create - Push notifications You can try it on [RubenTerre](https://www.rubenterre.com/)
6eeff82cb60935651882be990ad77ea5c3ac6643
[ "JavaScript", "Markdown" ]
2
JavaScript
rubenterre/Convierte-tu-Web-en-una-PWA
8c2435637db9b11d015b7625d36468c6fc75e0b4
4c13dc31d3b8ef435f1ab9d3b763949986a2c752
refs/heads/master
<repo_name>lzlzlz911/AKKA4NET<file_sep>/Akka4Net/Program.cs namespace Akka4Net{ using System; using Akka.Actor; internal class Program{ private static void Main(string[] args){ ActorSystem actorsystem = ActorSystem.Create("MySystem"); IActorRef actorref = actorsystem.ActorOf<GreetingActor>("greeter"); actorref.Tell(new GreetingMessage()); Console.Read(); } } }<file_sep>/Akka4Net/GreetingMessage.cs namespace Akka4Net{ public class GreetingMessage{ } }<file_sep>/Akka4Net.Server/GreetingActor.cs namespace Akka4Net.Server { #region Using using System; using Akka.Actor; using Akka4NET.Common; #endregion public class GreetingActor : ReceiveActor { public GreetingActor() { this.Receive<GreetingMessage>( greet => { Console.WriteLine("Receive"); this.Sender.Tell( new GreetingResponseMessage() { UserName = "lizhen" }); }); } } }<file_sep>/Akka4NET.Common/GreetingMessage.cs namespace Akka4NET.Common{ public class GreetingMessage{ } }<file_sep>/Akka4Net.Client/Program.cs namespace Akka4Net.Client { #region Using using System; using Akka.Actor; using Akka.Configuration; using Akka4NET.Common; #endregion internal class Program { private static void Main(string[] args) { var config = ConfigurationFactory.ParseString( @" akka { actor { provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote"" } remote { helios.tcp { transport-class = ""Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"" applied-adapters = [] transport-protocol = tcp port = 0 hostname = localhost } } } " ); using (var system = ActorSystem.Create("MyClient", config)) { var greeting = system.ActorSelection("akka.tcp://MyServer@localhost:8081/user/Greeting"); Console.WriteLine("Client Run......"); while (true) { var input = Console.ReadLine(); if (input.Equals("sayHello")) // greeting.Tell(new GreetingMessage()); { var result = greeting.Ask(new GreetingMessage()).Result as GreetingResponseMessage; Console.WriteLine(result.UserName); } } } } } }<file_sep>/Akka4Net.Server/BasicActor.cs namespace Akka4Net.Server { using Akka.Actor; public class BasicActor : UntypedActor { protected override void OnReceive(object message) { } } }<file_sep>/Akka4Net.Server/GreetingActorTwo.cs namespace Akka4Net.Server { #region Using using System; using Akka.Actor; using Akka4NET.Common; #endregion public class GreetingActorTwo : ReceiveActor { public GreetingActorTwo() { this.Receive<GreetingMessage>(greet => Console.WriteLine("ReceiveTwo")); } } }<file_sep>/Akka4Net/GreetingActor.cs namespace Akka4Net{ #region Using using System; using Akka.Actor; #endregion public class GreetingActor : ReceiveActor{ public GreetingActor() { Receive<GreetingMessage>(greet => Console.WriteLine("Receive")); } } }
f37fed551f3d2eafe2e2bb4163383707d76570dd
[ "C#" ]
8
C#
lzlzlz911/AKKA4NET
cbcc4bbfbd28b1dc26bbca0099513d61cdf53665
c8999dfd1965cb3a605792d7f0f76e5d5ce51559
refs/heads/master
<file_sep>#-*- coding: utf-8 -*- import Crypto.Cipher.AES as AES import os import random import string import shutil import time # 是的,这里99.99%代码都是Ctrl+c和Ctrl+v # msfvenom -p windows/meterpreter/reverse_tcp_rc4 RC4PASSWORD=<PASSWORD> LHOST=172.16.31.10 LPORT=82 -f c -i 4 -e x86/shikata_ga_nai shellcode=("\xbb\x14\x4a\x84\x4f\xdd\xc7\xd9\x74\x24\xf4\x58\x2b\xc9\xb1" "\x85\x31\x58\x15\x83\xe8\xfc\x03\x58\x11\xe2\xe1\xf4\x88\x3e" "\xd3\x22\x4a\x1d\x3a\x40\x48\x6a\xe6\x80\x59\x23\x69\x50\x9b" "\x40\xa4\x24\x12\x4a\xb8\xb7\x12\x92\x80\x75\x7e\x30\x70\x9f" "\x00\xc0\x8c\x26\xcf\xa5\x4b\x50\x4e\xde\x75\xb9\x9c\x29\x62" "\xf4\x16\xe7\x49\xb4\x60\xb8\x10\xb1\x69\x61\x0a\xff\xe9\xbb" "\x55\x7a\x51\x6a\x7a\xf5\x26\x90\x87\x89\x91\x2c\xb9\x59\x85" "\xb1\x5e\xa1\x70\x70\x64\x4b\xdb\xf0\xd1\x22\xe9\x05\x6f\x6e" "\x95\xbb\x98\x88\xad\xbb\x95\x1b\x41\x8e\xf1\x09\x0a\x50\x5b" "\x99\x2b\x1f\xcc\x45\xf8\x16\x6e\xd9\xb1\x63\x52\x28\x7f\x34" "\x1c\xd8\x8a\xa3\x59\xd4\xc9\x96\xf3\x28\x86\x20\x3d\x6d\x7f" "\x54\xee\x73") #shellcode add \ def bsadd(shellcode): bscode = '' for byte in shellcode: bscode += '\\x%s' % byte.encode('hex') return bscode def randomVar(): return ''.join(random.sample(string.ascii_lowercase, 8)) def randomJunk(): newString = '' for i in xrange(random.randint(150, 200)): newString += ''.join(random.sample(string.ascii_lowercase, 3)) return newString def do_Encryption(payload): counter = os.urandom(16) key = os.urandom(32) randkey = randomVar() randcounter = randomVar() randcipher = randomVar() randdecrypt = randomJunk() randshellcode = randomJunk() randctypes = randomJunk() randaes = randomJunk() randsub = randomJunk() encrypto = AES.new(key, AES.MODE_CTR, counter=lambda: counter) encrypted = encrypto.encrypt(payload.replace('ctypes',randctypes).replace('shellcode',randshellcode)) newpayload = "# -*- coding: utf-8 -*- \n" newpayload += "%s = '%s'\n"% (randomVar(), randomJunk()) newpayload += "import Crypto.Cipher.AES as %s \nimport ctypes as %s \n" %(randaes, randctypes) newpayload += "import subprocess as %s \n" % (randsub) newpayload += "%s.call('c:\\windows\\system32\\calc.exe') \n" % (randsub) newpayload += "%s = '%s'.decode('hex') \n" % (randkey, key.encode('hex')) newpayload += "%s = '%s'.decode('hex') \n" % (randcounter, counter.encode('hex')) newpayload += "%s = '%s'\n"% (randomVar(), randomJunk()) newpayload += "%s = %s.new(%s , %s.MODE_CTR, counter=lambda: %s )\n" % (randdecrypt, randaes, randkey, randaes, randcounter) newpayload += "%s = %s.decrypt('%s'.decode('hex')) \n" % (randcipher, randdecrypt, encrypted.encode('hex')) newpayload += "exec(%s)" % randcipher return newpayload def gen_Payload(): pre="""shellcode = bytearray('%s') ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(shellcode)),ctypes.c_int(0x3000),ctypes.c_int(0x40)) buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode) ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr),buf,ctypes.c_int(len(shellcode))) ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(ptr),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0))) ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1)) """ return pre with open('./calc0.py', 'w+') as f: f.write(do_Encryption(gen_Payload() % bsadd(shellcode))) f.close() time.sleep(1) execkey = ''.join(random.sample(string.ascii_lowercase, 16)) os.popen('pyinstaller --specpath Payload --workpath Payload --distpath Payload calc0.py -w -F -i calc.ico --key ' + execkey) time.sleep(1) shutil.move('.\Payload\calc0.exe','calc0.exe') shutil.rmtree('Payload') os.remove('calc0.py') <file_sep># calc0 Undetectable Windows Payload Generation 所有代码来自https://github.com/nccgroup/Winpayloads Thx NCC Group
3e29b6102590d241b0d55bc99f19cc7e65b5633c
[ "Markdown", "Python" ]
2
Python
c0ll3cti0n/calc0
f302b8771c362cbe22f085a03a40577283bc1ee7
204cd821ca2cb9d31ae9df6fd8ce0f343eb7fb08
refs/heads/dev
<file_sep>#!/bin/bash user="" host="" # user="root" # host="localhost" dbname="SyncServer_SharedImages" sqlScript="7.sql" echo "Migrating $dbname on $host" result=$(mysql -P 3306 -p --user="$user" --host="$host" --database="$dbname" < "$sqlScript" 2>&1 ) # I've embedded "ERROR999" to be output from the sql script -- when an error and subsequent rollback occurs. ERROR=`echo $result | grep ERROR999` if [ "empty$ERROR" = "empty" ]; then SUCCESS=`echo $result | grep SUCCESS123` # Didn't have ERROR string-- presumably no error. if [ "empty$SUCCESS" = "empty" ]; then # Didn't find SUCCESS string-- must have error. echo "**** Failure running migration, despite no error marker *******" echo $result else echo "Success running migration" fi else echo "**** Failure running migration (with error marker) *******" echo $result fi <file_sep>#!/bin/bash # Parameter: The URL of the server. # E.g., http://localhost:8080 (for local testing) # https://staging.syncserver.cprince.com (for staging) # Trying to deal with an error I get during load testing: # [2019-07-16T01:50:29.406Z] [ERROR] [Database.swift:46 init(showStartupInfo:)] Failure connecting to mySQL server docker.for.mac.localhost: Failure: 2003 ' (110) # It looks like this may be due to number of files that can be opened # See https://www.percona.com/blog/2014/12/08/what-happens-when-your-application-cannot-open-yet-another-connection-to-mysql/ # https://superuser.com/questions/433746/is-there-a-fix-for-the-too-many-open-files-in-system-error-on-os-x-10-7-1 ulimit -n 4096 locust --host="$1"<file_sep>// // SharingAccountsController_GetSharingInvitationInfo.swift // ServerTests // // Created by <NAME> on 4/9/19. // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared import KituraNet class SharingAccountsController_GetSharingInvitationInfo: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func getSharingInfo(existing: Bool) { var httpStatusCodeExpected: HTTPStatusCode = .OK if !existing { httpStatusCodeExpected = .gone } let owningUser:TestAccount = .primaryOwningAccount let sharingGroupUUID = Foundation.UUID().uuidString let deviceUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(testAccount: owningUser, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! let permission: Permission = .read let allowSharingAcceptance = false if existing { createSharingInvitation(testAccount: owningUser, permission: permission, numberAcceptors: 1, allowSharingAcceptance: allowSharingAcceptance, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } } else { // Fake one! sharingInvitationUUID = Foundation.UUID().uuidString } var errorExpected = false if !existing { errorExpected = true } let response = getSharingInvitationInfo(sharingInvitationUUID: sharingInvitationUUID, errorExpected: errorExpected, httpStatusCodeExpected: httpStatusCodeExpected) if errorExpected { XCTAssert(response == nil) } else { guard let response = response else { XCTFail() return } XCTAssert(response.allowSocialAcceptance == allowSharingAcceptance) XCTAssert(response.permission == permission) } } func testNonExistentSharingInvitationUUID() { getSharingInfo(existing: false) } func testExistingSharingInvitationUUID() { getSharingInfo(existing: true) } func getSharingInfo(hasBeenRedeemed: Bool, httpStatusCodeExpected: HTTPStatusCode = .OK) { let sharingUser:TestAccount = .primarySharingAccount let owningUser:TestAccount = .primaryOwningAccount let sharingGroupUUID = Foundation.UUID().uuidString let deviceUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(testAccount: owningUser, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! let permission: Permission = .admin let allowSharingAcceptance = true createSharingInvitation(testAccount: owningUser, permission: permission, numberAcceptors: 1, allowSharingAcceptance: allowSharingAcceptance, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } if hasBeenRedeemed { redeemSharingInvitation(sharingUser:sharingUser, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in expectation.fulfill() } } let response = getSharingInvitationInfo(sharingInvitationUUID: sharingInvitationUUID, errorExpected: hasBeenRedeemed, httpStatusCodeExpected: httpStatusCodeExpected) if hasBeenRedeemed { XCTAssert(response == nil) } else { guard let response = response else { XCTFail() return } XCTAssert(response.allowSocialAcceptance == allowSharingAcceptance) XCTAssert(response.permission == permission) } } func testGetSharingInvitationInfoThatHasNotBeenRedeemedWorks() { getSharingInfo(hasBeenRedeemed: false) } func testGetSharingInvitationInfoThatHasAlreadyBeenRedeemedFails() { getSharingInfo(hasBeenRedeemed: true, httpStatusCodeExpected: .gone) } func testGetSharingInvitationInfoWithSecondaryAuthWorks() { let owningUser:TestAccount = .primaryOwningAccount let sharingGroupUUID = Foundation.UUID().uuidString let deviceUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(testAccount: owningUser, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! let permission: Permission = .admin let allowSharingAcceptance = true createSharingInvitation(testAccount: owningUser, permission: permission, numberAcceptors: 1, allowSharingAcceptance: allowSharingAcceptance, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } guard sharingInvitationUUID != nil else { XCTFail() return } var response: GetSharingInvitationInfoResponse! getSharingInvitationInfoWithSecondaryAuth(testAccount: owningUser, sharingInvitationUUID: sharingInvitationUUID) { r, exp in response = r exp.fulfill() } guard response != nil else { XCTFail() return } XCTAssert(response.allowSocialAcceptance == allowSharingAcceptance) XCTAssert(response.permission == permission) } } extension SharingAccountsController_GetSharingInvitationInfo { static var allTests : [(String, (SharingAccountsController_GetSharingInvitationInfo) -> () throws -> Void)] { return [ ("testNonExistentSharingInvitationUUID", testNonExistentSharingInvitationUUID), ("testExistingSharingInvitationUUID", testExistingSharingInvitationUUID), ("testGetSharingInvitationInfoThatHasNotBeenRedeemedWorks", testGetSharingInvitationInfoThatHasNotBeenRedeemedWorks), ("testGetSharingInvitationInfoThatHasAlreadyBeenRedeemedFails", testGetSharingInvitationInfoThatHasAlreadyBeenRedeemedFails), ("testGetSharingInvitationInfoWithSecondaryAuthWorks", testGetSharingInvitationInfoWithSecondaryAuthWorks) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SharingAccountsController_GetSharingInvitationInfo.self) } } <file_sep>// // Account.swift // Server // // Created by <NAME> on 7/9/17. // import Foundation import SyncServerShared import Credentials import KituraNet import LoggerAPI import Kitura import HeliumLogger enum AccountCreationUser { case user(User) // use this if we have it. case userId(UserId) // and this if we don't. } protocol AccountDelegate : class { // This is delegated because (a) it enables me to only sometimes allow an Account to save to the database, and (b) because knowledge of how to save to a database seems outside of the responsibilities of `Account`s. Returns false iff an error occurred on database save. func saveToDatabase(account:Account) -> Bool } /// E.g., tokens stored in the database representing the Account. protocol DatabaseCredentials { } protocol Account { static var accountScheme:AccountScheme {get} var accountScheme:AccountScheme {get} // Sharing always need to return false. // Owning accounts return true iff they need a cloud folder name (e.g., Google Drive). var owningAccountsNeedCloudFolderName: Bool {get} var delegate:AccountDelegate? {get set} var accountCreationUser:AccountCreationUser? {get set} // Currently assuming all Account's use access tokens. var accessToken: String! {get set} func toJSON() -> String? /// Given existing Account info stored in the database, decide if we need to generate tokens. Token generation can be used for various purposes by the particular Account. E.g., For owning users to allow access to cloud storage data in offline manner. E.g., to allow access to that data by sharing users. /// You must call this before `generateTokens`-- the Account scheme may save some state as a result of this call that changes how the `generateTokens` call works. func needToGenerateTokens(dbCreds:Account?) -> Bool /// Some Account's (e.g., Google) need to generate internal tokens (e.g., a refresh token) in some circumstances (e.g., when having a serverAuthCode). May use delegate, if one is defined, to save creds to database. Some accounts may use HTTP header in RouterResponse to send back token(s). func generateTokens(response: RouterResponse?, completion:@escaping (Swift.Error?)->()) func merge(withNewer account:Account) // Gets account specific properties, if any, from the request. static func getProperties(fromRequest request:RouterRequest) -> [String: Any] static func fromProperties(_ properties: AccountManager.AccountProperties, user:AccountCreationUser?, delegate:AccountDelegate?) -> Account? static func fromJSON(_ json:String, user:AccountCreationUser, delegate:AccountDelegate?) throws -> Account? } enum FromJSONError : Swift.Error { case noRequiredKeyValue } extension Account { // Only use this for owning accounts. var cloudFolderName: String? { guard let accountCreationUser = accountCreationUser, case .user(let user) = accountCreationUser, let cloudFolderName = user.cloudFolderName else { if owningAccountsNeedCloudFolderName { Log.error("Account needs cloud folder name, but has none.") assert(false) } return nil } assert(owningAccountsNeedCloudFolderName) return cloudFolderName } func generateTokensIfNeeded(dbCreds:Account?, routerResponse:RouterResponse, success:@escaping ()->(), failure: @escaping ()->()) { if needToGenerateTokens(dbCreds: dbCreds) { generateTokens(response: routerResponse) { error in if error == nil { success() } else { Log.error("Failed attempting to generate tokens: \(error!))") failure() } } } else { success() } } static func setProperty(jsonDict: [String:Any], key:String, required:Bool=true, setWithValue:(String)->()) throws { guard let keyValue = jsonDict[key] as? String else { if required { Log.error("No \(key) value present.") throw FromJSONError.noRequiredKeyValue } else { Log.warning("No \(key) value present.") } return } setWithValue(keyValue) } static var accessTokenKey: String { return "accessToken" } static var refreshTokenKey: String { return "refreshToken" } } extension Account { var cloudStorage:CloudStorage? { #if DEBUG if let loadTesting = Configuration.server.loadTestingCloudStorage, loadTesting { return MockStorage() } else { return self as? CloudStorage } #else return self as? CloudStorage #endif } } enum APICallBody { case string(String) case data(Data) } enum APICallResult { case dictionary([String: Any]) case array([Any]) case data(Data) } enum GenerateTokensError : Swift.Error { case badStatusCode(HTTPStatusCode?) case couldNotObtainParameterFromJSON case nilAPIResult case noDataInAPIResult case couldNotDecodeResult case errorSavingCredsToDatabase case couldNotGetSelf } // I didn't just use a protocol extension for this because I want to be able to override `apiCall` and call "super" to get the base definition. class AccountAPICall { // Used by `apiCall` function to make a REST call to an Account service. var baseURL:String? init?() {} private func parseResponse(_ response: ClientResponse, expectedBody: ExpectedResponse?, errorIfParsingFailure: Bool = false) -> APICallResult? { var result:APICallResult? do { var body = Data() try response.readAllData(into: &body) if let expectedBody = expectedBody, expectedBody == .data { result = .data(body) } else { let jsonResult:Any = try JSONSerialization.jsonObject(with: body, options: []) if let dictionary = jsonResult as? [String : Any] { result = .dictionary(dictionary) } else if let array = jsonResult as? [Any] { result = .array(array) } else { result = .data(body) } } } catch (let error) { if errorIfParsingFailure { Log.error("Failed to read response: \(error)") } } return result } enum ExpectedResponse { case data case json } // Does an HTTP call to the endpoint constructed by baseURL with path, the HTTP method, and the given body parameters (if any). BaseURL is given without any http:// or https:// (https:// is used). If baseURL is nil, then self.baseURL is used-- which must not be nil in that case. // expectingData == true means return Data. false or nil just look for Data or JSON result. func apiCall(method:String, baseURL:String? = nil, path:String, additionalHeaders: [String:String]? = nil, additionalOptions: [ClientRequest.Options] = [], urlParameters:String? = nil, body:APICallBody? = nil, returnResultWhenNon200Code:Bool = true, expectedSuccessBody:ExpectedResponse? = nil, expectedFailureBody:ExpectedResponse? = nil, completion:@escaping (_ result: APICallResult?, HTTPStatusCode?, _ responseHeaders: HeadersContainer?)->()) { var hostname = baseURL if hostname == nil { hostname = self.baseURL } var requestOptions: [ClientRequest.Options] = additionalOptions requestOptions.append(.schema("https://")) requestOptions.append(.hostname(hostname!)) requestOptions.append(.method(method)) if urlParameters == nil { requestOptions.append(.path(path)) } else { var charSet = CharacterSet.urlQueryAllowed // At least for the Google REST API, it seems single quotes need to be encoded. See https://developers.google.com/drive/v3/web/search-parameters // urlQueryAllowed doesn't exclude single quotes, so I'm doing that myself. charSet.remove("'") let escapedURLParams = urlParameters!.addingPercentEncoding(withAllowedCharacters: charSet) requestOptions.append(.path(path + "?" + escapedURLParams!)) } var headers = [String:String]() //headers["Accept"] = "application/json; charset=UTF-8" headers["Accept"] = "*/*" if additionalHeaders != nil { for (key, value) in additionalHeaders! { headers[key] = value } } requestOptions.append(.headers(headers)) let req = HTTP.request(requestOptions) {[unowned self] response in if let response:KituraNet.ClientResponse = response { let statusCode = response.statusCode if statusCode == HTTPStatusCode.OK { if let result = self.parseResponse(response, expectedBody: expectedSuccessBody, errorIfParsingFailure: true) { completion(result, statusCode, response.headers) return } } else { if returnResultWhenNon200Code { if let result = self.parseResponse(response, expectedBody: expectedFailureBody) { completion(result, statusCode, response.headers) } else { completion(nil, statusCode, nil) } return } } } completion(nil, nil, nil) } switch body { case .none: req.end() case .some(.string(let str)): req.end(str) case .some(.data(let data)): req.end(data) } // Log.debug("Request URL: \(req.url)") } } <file_sep>// // FileIndexRepository.swift // Server // // Created by <NAME> on 1/21/17. // // // Meta data for files currently in cloud storage. import Foundation import LoggerAPI import SyncServerShared typealias FileIndexId = Int64 class FileIndex : NSObject, Model, Filenaming { static let fileIndexIdKey = "fileIndexId" var fileIndexId: FileIndexId! static let fileUUIDKey = "fileUUID" var fileUUID: String! static let deviceUUIDKey = "deviceUUID" // We don't give the deviceUUID when updating the fileIndex for an upload deletion. var deviceUUID:String? static let fileGroupUUIDKey = "fileGroupUUID" // Not all files have to be associated with a file group. var fileGroupUUID:String? // Currently allowing files to be in exactly one sharing group. static let sharingGroupUUIDKey = "sharingGroupUUID" var sharingGroupUUID: String! static let creationDateKey = "creationDate" // We don't give the `creationDate` when updating the fileIndex for versions > 0. var creationDate:Date? static let updateDateKey = "updateDate" var updateDate:Date! // OWNER /// The userId of the (effective) owning user of v0 of the file. The userId doesn't change beyond that point-- the v0 owner is always the owner. static let userIdKey = "userId" var userId: UserId! static let mimeTypeKey = "mimeType" var mimeType: String! static let appMetaDataKey = "appMetaData" var appMetaData: String? static let appMetaDataVersionKey = "appMetaDataVersion" var appMetaDataVersion: AppMetaDataVersionInt? static let deletedKey = "deleted" var deleted:Bool! static let fileVersionKey = "fileVersion" var fileVersion: FileVersionInt! static let lastUploadedCheckSumKey = "lastUploadedCheckSum" var lastUploadedCheckSum: String? // For queries; not in this table. static let accountTypeKey = "accountType" var accountType: String! subscript(key:String) -> Any? { set { switch key { case FileIndex.fileIndexIdKey: fileIndexId = newValue as! FileIndexId? case FileIndex.fileUUIDKey: fileUUID = newValue as! String? case FileIndex.fileGroupUUIDKey: fileGroupUUID = newValue as! String? case FileIndex.sharingGroupUUIDKey: sharingGroupUUID = newValue as! String? case FileIndex.deviceUUIDKey: deviceUUID = newValue as! String? case FileIndex.creationDateKey: creationDate = newValue as! Date? case FileIndex.updateDateKey: updateDate = newValue as! Date? case FileIndex.userIdKey: userId = newValue as! UserId? case FileIndex.mimeTypeKey: mimeType = newValue as! String? case FileIndex.appMetaDataKey: appMetaData = newValue as! String? case FileIndex.appMetaDataVersionKey: appMetaDataVersion = newValue as! AppMetaDataVersionInt? case FileIndex.deletedKey: deleted = newValue as! Bool? case FileIndex.fileVersionKey: fileVersion = newValue as! FileVersionInt? case FileIndex.lastUploadedCheckSumKey: lastUploadedCheckSum = newValue as! String? case User.accountTypeKey: accountType = newValue as! String? default: Log.debug("key: \(key)") assert(false) } } get { return getValue(forKey: key) } } override init() { super.init() } func typeConvertersToModel(propertyName:String) -> ((_ propertyValue:Any) -> Any?)? { switch propertyName { case FileIndex.deletedKey: return {(x:Any) -> Any? in return (x as! Int8) == 1 } case FileIndex.creationDateKey: return {(x:Any) -> Any? in return DateExtras.date(x as! String, fromFormat: .DATETIME) } case FileIndex.updateDateKey: return {(x:Any) -> Any? in return DateExtras.date(x as! String, fromFormat: .DATETIME) } default: return nil } } override var description : String { return "fileIndexId: \(String(describing: fileIndexId)); fileUUID: \(String(describing: fileUUID)); deviceUUID: \(deviceUUID ?? ""); creationDate: \(String(describing: creationDate)); updateDate: \(String(describing: updateDate)); userId: \(String(describing: userId)); mimeTypeKey: \(String(describing: mimeType)); appMetaData: \(String(describing: appMetaData)); appMetaDataVersion: \(String(describing: appMetaDataVersion)); deleted: \(String(describing: deleted)); fileVersion: \(String(describing: fileVersion)); lastUploadedCheckSum: \(String(describing: lastUploadedCheckSum))" } } class FileIndexRepository : Repository, RepositoryLookup { private(set) var db:Database! required init(_ db:Database) { self.db = db } var tableName:String { return FileIndexRepository.tableName } static var tableName:String { return "FileIndex" } func upcreate() -> Database.TableUpcreateResult { let createColumns = "(fileIndexId BIGINT NOT NULL AUTO_INCREMENT, " + // permanent reference to file (assigned by app) "fileUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + // reference into User table // TODO: *2* Make this a foreign reference. "userId BIGINT NOT NULL, " + // identifies a specific mobile device (assigned by app) // This plays a different role than it did in the Upload table. Here, it forms part of the filename in cloud storage, and thus must be retained. We will ignore this field otherwise, i.e., we will not have two entries in this table for the same userId, fileUUID pair. "deviceUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + // identifies a group of files (assigned by app) "fileGroupUUID VARCHAR(\(Database.uuidLength)), " + "sharingGroupUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + // Not saying "NOT NULL" here only because in the first deployed version of the database, I didn't have these dates. "creationDate DATETIME," + "updateDate DATETIME," + // MIME type of the file "mimeType VARCHAR(\(Database.maxMimeTypeLength)) NOT NULL, " + // App-specific meta data "appMetaData TEXT, " + // true if file has been deleted, false if not. "deleted BOOL NOT NULL, " + "fileVersion INT NOT NULL, " + // Making this optional because appMetaData is optional. If there is app meta data, this must not be null. "appMetaDataVersion INT, " + // I've left this as NULL-able for now to deal with migration-- systems in production prior to 10/27/18. In general, this should not be null. "lastUploadedCheckSum TEXT, " + "FOREIGN KEY (sharingGroupUUID) REFERENCES \(SharingGroupRepository.tableName)(\(SharingGroup.sharingGroupUUIDKey)), " + "UNIQUE (fileUUID, sharingGroupUUID), " + "UNIQUE (fileIndexId))" let result = db.createTableIfNeeded(tableName: "\(tableName)", columnCreateQuery: createColumns) switch result { case .success(.alreadyPresent): // Table was already there. Do we need to update it? // Evolution 1: Are creationDate and updateDate present? If not, add them. if db.columnExists(Upload.creationDateKey, in: tableName) == false { if !db.addColumn("\(Upload.creationDateKey) DATETIME", to: tableName) { return .failure(.columnCreation) } } if db.columnExists(Upload.updateDateKey, in: tableName) == false { if !db.addColumn("\(Upload.updateDateKey) DATETIME", to: tableName) { return .failure(.columnCreation) } } // 2/25/18; Evolution 2: Remove the cloudFolderName column let cloudFolderNameKey = "cloudFolderName" if db.columnExists(cloudFolderNameKey, in: tableName) == true { if !db.removeColumn(cloudFolderNameKey, from: tableName) { return .failure(.columnRemoval) } } // 3/23/18; Evolution 3: Add the appMetaDataVersion column. if db.columnExists(FileIndex.appMetaDataVersionKey, in: tableName) == false { if !db.addColumn("\(FileIndex.appMetaDataVersionKey) INT", to: tableName) { return .failure(.columnCreation) } } // 4/19/18; Evolution 4: Add in fileGroupUUID if db.columnExists(FileIndex.fileGroupUUIDKey, in: tableName) == false { if !db.addColumn("\(FileIndex.fileGroupUUIDKey) VARCHAR(\(Database.uuidLength))", to: tableName) { return .failure(.columnCreation) } } default: break } return result } private func haveNilFieldForAdd(fileIndex:FileIndex) -> Bool { return fileIndex.fileUUID == nil || fileIndex.userId == nil || fileIndex.mimeType == nil || fileIndex.deviceUUID == nil || fileIndex.deleted == nil || fileIndex.fileVersion == nil || fileIndex.lastUploadedCheckSum == nil || fileIndex.creationDate == nil || fileIndex.updateDate == nil } enum AddFileIndexResponse: RetryRequest { case success(uploadId: Int64) case error case deadlock var shouldRetry: Bool { if case .deadlock = self { return true } else { return false } } } // uploadId in the model is ignored and the automatically generated uploadId is returned if the add is successful. func add(fileIndex:FileIndex) -> AddFileIndexResponse { if haveNilFieldForAdd(fileIndex: fileIndex) { Log.error("One of the model values was nil: \(fileIndex)") return .error } let deletedValue = fileIndex.deleted == true ? 1 : 0 let creationDateValue = DateExtras.date(fileIndex.creationDate!, toFormat: .DATETIME) let updateDateValue = DateExtras.date(fileIndex.updateDate, toFormat: .DATETIME) // TODO: *2* Seems like we could use an encoding here to deal with sql injection issues. let (appMetaDataFieldValue, appMetaDataFieldName) = getInsertFieldValueAndName(fieldValue: fileIndex.appMetaData, fieldName: Upload.appMetaDataKey) let (appMetaDataVersionFieldValue, appMetaDataVersionFieldName) = getInsertFieldValueAndName(fieldValue: fileIndex.appMetaDataVersion, fieldName: Upload.appMetaDataVersionKey, fieldIsString:false) let (fileGroupUUIDFieldValue, fileGroupUUIDFieldName) = getInsertFieldValueAndName(fieldValue: fileIndex.fileGroupUUID, fieldName: FileIndex.fileGroupUUIDKey) let query = "INSERT INTO \(tableName) (\(FileIndex.fileUUIDKey), \(FileIndex.userIdKey), \(FileIndex.deviceUUIDKey), \(FileIndex.creationDateKey), \(FileIndex.updateDateKey), \(FileIndex.mimeTypeKey), \(FileIndex.deletedKey), \(FileIndex.fileVersionKey), \(FileIndex.lastUploadedCheckSumKey), \(FileIndex.sharingGroupUUIDKey) \(appMetaDataFieldName) \(appMetaDataVersionFieldName) \(fileGroupUUIDFieldName) ) VALUES('\(fileIndex.fileUUID!)', \(fileIndex.userId!), '\(fileIndex.deviceUUID!)', '\(creationDateValue)', '\(updateDateValue)', '\(fileIndex.mimeType!)', \(deletedValue), \(fileIndex.fileVersion!), '\(fileIndex.lastUploadedCheckSum!)', '\(fileIndex.sharingGroupUUID!)' \(appMetaDataFieldValue) \(appMetaDataVersionFieldValue) \(fileGroupUUIDFieldValue) );" if db.query(statement: query) { return .success(uploadId: db.lastInsertId()) } else if db.errorCode() == Database.deadlockError { return .deadlock } else { let error = db.error Log.error("Could not insert row into \(tableName): \(error)") return .error } } private func haveNilFieldForUpdate(fileIndex:FileIndex, updateType: UpdateType) -> Bool { // OWNER // Allowing a nil userId for update because the v0 owner of a file is always the owner of the file. i.e., for v1, v2 etc. of a file, we don't update the userId. let result = fileIndex.fileUUID == nil || fileIndex.deleted == nil switch updateType { case .uploadDeletion: return result || fileIndex.fileVersion == nil case .uploadAppMetaData: return result case .uploadFile: return result || fileIndex.fileVersion == nil || fileIndex.deviceUUID == nil } } enum UpdateType { case uploadFile case uploadDeletion case uploadAppMetaData } // The FileIndex model *must* have a fileIndexId // OWNER: userId is ignored in the fileIndex-- the v0 owner is the permanent owner. func update(fileIndex:FileIndex, updateType: UpdateType = .uploadFile) -> Bool { if fileIndex.fileIndexId == nil || haveNilFieldForUpdate(fileIndex: fileIndex, updateType:updateType) { Log.error("One of the model values was nil: \(fileIndex)") return false } // TODO: *2* Seems like we could use an encoding here to deal with sql injection issues. let appMetaDataField = getUpdateFieldSetter(fieldValue: fileIndex.appMetaData, fieldName: FileIndex.appMetaDataKey) let appMetaDataVersionField = getUpdateFieldSetter(fieldValue: fileIndex.appMetaDataVersion, fieldName: FileIndex.appMetaDataVersionKey, fieldIsString: false) let lastUploadedCheckSumField = getUpdateFieldSetter(fieldValue: fileIndex.lastUploadedCheckSum, fieldName: FileIndex.lastUploadedCheckSumKey) let mimeTypeField = getUpdateFieldSetter(fieldValue: fileIndex.mimeType, fieldName: FileIndex.mimeTypeKey) let deviceUUIDField = getUpdateFieldSetter(fieldValue: fileIndex.deviceUUID, fieldName: FileIndex.deviceUUIDKey) let fileVersionField = getUpdateFieldSetter(fieldValue: fileIndex.fileVersion, fieldName: FileIndex.fileVersionKey, fieldIsString: false) let fileGroupUUIDField = getUpdateFieldSetter(fieldValue: fileIndex.fileGroupUUID, fieldName: FileIndex.fileGroupUUIDKey) var updateDateValue:String? if fileIndex.updateDate != nil { updateDateValue = DateExtras.date(fileIndex.updateDate, toFormat: .DATETIME) } let updateDateField = getUpdateFieldSetter(fieldValue: updateDateValue, fieldName: FileIndex.updateDateKey) let deletedValue = fileIndex.deleted == true ? 1 : 0 let query = "UPDATE \(tableName) SET \(FileIndex.fileUUIDKey)='\(fileIndex.fileUUID!)', \(FileIndex.deletedKey)=\(deletedValue) \(appMetaDataField) \(lastUploadedCheckSumField) \(mimeTypeField) \(deviceUUIDField) \(updateDateField) \(appMetaDataVersionField) \(fileVersionField) \(fileGroupUUIDField) WHERE \(FileIndex.fileIndexIdKey)=\(fileIndex.fileIndexId!)" if db.query(statement: query) { // "When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows may not actually equal the number of rows matched, only the number of rows that were literally affected by the query." From: https://dev.mysql.com/doc/apis-php/en/apis-php-function.mysql-affected-rows.html if db.numberAffectedRows() <= 1 { return true } else { Log.error("Did not have <= 1 row updated: \(db.numberAffectedRows())") return false } } else { let error = db.error Log.error("Could not update \(tableName): \(error)") return false } } enum LookupKey : CustomStringConvertible { case fileIndexId(Int64) case userId(UserId) case primaryKeys(sharingGroupUUID: String, fileUUID:String) case sharingGroupUUID(sharingGroupUUID: String) case userAndSharingGroup(UserId, sharingGroupUUID: String) var description : String { switch self { case .fileIndexId(let fileIndexId): return "fileIndexId(\(fileIndexId))" case .userId(let userId): return "userId(\(userId))" case .primaryKeys(let sharingGroupUUID, let fileUUID): return "sharingGroupUUID(\(sharingGroupUUID)); fileUUID(\(fileUUID))" case .sharingGroupUUID(let sharingGroupUUID): return "sharingGroupUUID(\(sharingGroupUUID)))" case .userAndSharingGroup(let userId, let sharingGroupUUID): return "userId(\(userId)); sharingGroupUUID(\(sharingGroupUUID)))" } } } func lookupConstraint(key:LookupKey) -> String { switch key { case .fileIndexId(let fileIndexId): return "fileIndexId = \(fileIndexId)" case .userId(let userId): return "userId = \(userId)" case .primaryKeys(let sharingGroupUUID, let fileUUID): return "sharingGroupUUID = '\(sharingGroupUUID)' and fileUUID = '\(fileUUID)'" case .sharingGroupUUID(let sharingGroupUUID): return "sharingGroupUUID = '\(sharingGroupUUID)'" case .userAndSharingGroup(let userId, let sharingGroupUUID): return "userId = \(userId) AND sharingGroupUUID = '\(sharingGroupUUID)'" } } /* For each entry in Upload for the userId/deviceUUID that is in the uploaded state, we need to do the following: 1) If there is no file in the FileIndex for the userId/fileUUID, then a new entry needs to be inserted into the FileIndex. This should be version 0 of the file. The deviceUUID is taken from the device uploading the file. 2) If there is already a file in the FileIndex for the userId/fileUUID, then the version number we have in Uploads should be the version number in the FileIndex + 1 (if not, it is an error). Update the FileIndex with the new info from Upload, if no error. More specifically, the deviceUUID of the uploading device will replace that currently in the FileIndex-- because the new file in cloud storage is named: <fileUUID>.<Uploading-deviceUUID>.<fileVersion> where <fileVersion> is the new file version, and <Uploading-deviceUUID> is the device UUID of the uploading device. */ enum TransferUploadsResult { case success(numberUploadsTransferred: Int32) case failure(RequestHandler.FailureResult?) } func transferUploads(uploadUserId: UserId, owningUserId: @escaping ()->(FileController.EffectiveOwningUser), sharingGroupUUID: String, uploadingDeviceUUID:String, uploadRepo:UploadRepository) -> TransferUploadsResult { var error = false var failureResult:RequestHandler.FailureResult? var numberTransferred:Int32 = 0 // [1] Fetch the uploaded files for the user, device, and sharing group. guard let uploadSelect = uploadRepo.select(forUserId: uploadUserId, sharingGroupUUID: sharingGroupUUID, deviceUUID: uploadingDeviceUUID) else { return .failure(nil) } uploadSelect.forEachRow { rowModel in if error { return } let upload = rowModel as! Upload // This will a) mark the FileIndex entry as deleted for toDeleteFromFileIndex, and b) mark it as not deleted for *both* uploadingUndelete and uploading files. So, effectively, it does part of our upload undelete for us. let uploadDeletion = upload.state == .toDeleteFromFileIndex let fileIndex = FileIndex() fileIndex.lastUploadedCheckSum = upload.lastUploadedCheckSum fileIndex.deleted = uploadDeletion fileIndex.fileUUID = upload.fileUUID // If this an uploadDeletion or updating app meta data, it seems inappropriate to update the deviceUUID in the file index-- all we're doing is marking it as deleted. if !uploadDeletion && upload.state != .uploadingAppMetaData { // Using `uploadingDeviceUUID` here, but equivalently use upload.deviceUUID-- they are the same. See [1] above. assert(uploadingDeviceUUID == upload.deviceUUID) fileIndex.deviceUUID = uploadingDeviceUUID } fileIndex.mimeType = upload.mimeType fileIndex.appMetaData = upload.appMetaData fileIndex.appMetaDataVersion = upload.appMetaDataVersion fileIndex.fileGroupUUID = upload.fileGroupUUID if let uploadFileVersion = upload.fileVersion { fileIndex.fileVersion = uploadFileVersion if uploadFileVersion == 0 { fileIndex.creationDate = upload.creationDate // OWNER // version 0 of a file establishes the owning user. The owning user doesn't change if new versions are uploaded. switch owningUserId() { case .success(let userId): fileIndex.userId = userId case .failure(let failure): failureResult = failure error = true return } // Similarly, the sharing group id doesn't change over time. fileIndex.sharingGroupUUID = upload.sharingGroupUUID } fileIndex.updateDate = upload.updateDate } else if upload.state != .uploadingAppMetaData { Log.error("No file version, and not uploading app meta data.") error = true return } let key = LookupKey.primaryKeys(sharingGroupUUID: upload.sharingGroupUUID, fileUUID: upload.fileUUID) let result = self.lookup(key: key, modelInit: FileIndex.init) switch result { case .error(_): error = true return case .found(let object): let existingFileIndex = object as! FileIndex if uploadDeletion { guard upload.fileVersion == existingFileIndex.fileVersion else { Log.error("Did not specify current version of file in upload deletion!") error = true return } } else if upload.state != .uploadingAppMetaData { guard upload.fileVersion == (existingFileIndex.fileVersion + 1) else { Log.error("Did not have next version of file!") error = true return } } fileIndex.fileIndexId = existingFileIndex.fileIndexId var updateType:UpdateType = .uploadFile if uploadDeletion { updateType = .uploadDeletion } else if upload.state == .uploadingAppMetaData { updateType = .uploadAppMetaData } guard self.update(fileIndex: fileIndex, updateType: updateType) else { Log.error("Could not update FileIndex!") error = true return } case .noObjectFound: if upload.state == .uploadingAppMetaData { Log.error("Attempting to upload app meta data for a file not present in the file index: \(key)!") error = true return } else if uploadDeletion { Log.error("Attempting to delete a file not present in the file index: \(key)!") error = true return } else { guard upload.fileVersion == 0 else { Log.error("Did not have version 0 of file!") error = true return } let result = self.retry(request: { self.add(fileIndex: fileIndex) }) switch result { case .success: break case .deadlock, .error: Log.error("Could not add new FileIndex!") error = true return } } } numberTransferred += 1 } if error { return .failure(failureResult) } if uploadSelect.forEachRowStatus == nil { return .success(numberUploadsTransferred: numberTransferred) } else { return .failure(nil) } } enum MarkDeletionCriteria { case userId(String) case sharingGroupUUID(String) func toString() -> String { switch self { case .userId(let userId): return "\(FileIndex.userIdKey)=\(userId)" case .sharingGroupUUID(let sharingGroupUUID): return "\(FileIndex.sharingGroupUUIDKey)='\(sharingGroupUUID)'" } } } func markFilesAsDeleted(key:LookupKey) -> Int64? { let query = "UPDATE \(tableName) SET \(FileIndex.deletedKey)=1 WHERE " + lookupConstraint(key: key) if db.query(statement: query) { let numberRows = db.numberAffectedRows() Log.debug("Number rows: \(numberRows) for query: \(query)") return numberRows } else { let error = db.error Log.error("Could not mark files as deleted in \(tableName): \(error)") return nil } } enum FileIndexResult { case fileIndex([FileInfo]) case error(String) } // Does not return FileIndex rows where the user has been deleted and those rows have been marked as deleted. func fileIndex(forSharingGroupUUID sharingGroupUUID: String) -> FileIndexResult { let query = "select \(tableName).*, \(UserRepository.tableName).accountType from \(tableName), \(UserRepository.tableName) where sharingGroupUUID = '\(sharingGroupUUID)' and \(tableName).userId = \(UserRepository.tableName).userId" return fileIndex(forSelectQuery: query) } private func fileIndex(forSelectQuery selectQuery: String) -> FileIndexResult { guard let select = Select(db:db, query: selectQuery, modelInit: FileIndex.init, ignoreErrors:false) else { return .error("Failed on Select!") } var result:[FileInfo] = [] var error:FileIndexResult! select.forEachRow { rowModel in if let _ = error { return } let rowModel = rowModel as! FileIndex let fileInfo = FileInfo() fileInfo.fileUUID = rowModel.fileUUID fileInfo.deviceUUID = rowModel.deviceUUID fileInfo.fileVersion = rowModel.fileVersion fileInfo.deleted = rowModel.deleted fileInfo.mimeType = rowModel.mimeType fileInfo.creationDate = rowModel.creationDate fileInfo.updateDate = rowModel.updateDate fileInfo.appMetaDataVersion = rowModel.appMetaDataVersion fileInfo.fileGroupUUID = rowModel.fileGroupUUID fileInfo.owningUserId = rowModel.userId fileInfo.sharingGroupUUID = rowModel.sharingGroupUUID guard let accountType = rowModel.accountType, let accountScheme = AccountScheme(.accountName(accountType)), let cloudStorageType = accountScheme.cloudStorageType else { error = .error("Failed getting cloud storage type for fileUUID: \(String(describing: rowModel.fileUUID))") return } fileInfo.cloudStorageType = cloudStorageType result.append(fileInfo) } if let error = error { return error } if select.forEachRowStatus == nil { return .fileIndex(result) } else { return .error("\(select.forEachRowStatus!)") } } func fileIndex(forKeys keys: [LookupKey]) -> FileIndexResult { if keys.count == 0 { return .error("Can't give 0 keys!") } var query = "select \(tableName).*, \(UserRepository.tableName).accountType from \(tableName), \(UserRepository.tableName) where \(tableName).userId = \(UserRepository.tableName).userId and ( " var numberValues = 0 for key in keys { if numberValues > 0 { query += " or " } query += " (\(lookupConstraint(key: key))) " numberValues += 1 } query += " )" return fileIndex(forSelectQuery: query) } } <file_sep>#!/bin/bash # Usage: numberUsers.sh <Server.json> # e.g., ./numberUsers.sh ~/Desktop/Apps/SyncServerII/Private/Server.json.aws.app.bundles/Neebla-production.json MY_SQL_JSON=$1 DATABASE=`jq -r '.["mySQL.database"]' < ${MY_SQL_JSON}` USER=`jq -r '.["mySQL.user"]' < ${MY_SQL_JSON}` PASSWORD=`jq -r '.["mySQL.password"]' < ${MY_SQL_JSON}` HOST=`jq -r '.["mySQL.host"]' < ${MY_SQL_JSON}` SCRIPT="select count(*) from User;" echo -n "Number of users: " mysql -P 3306 --password="$<PASSWORD>" --user="$USER" --host="$HOST" --database="$DATABASE" -Bse "$SCRIPT" 2>&1 | grep -v "Using a password" <file_sep>// // UserRepository.swift // Server // // Created by <NAME> on 11/26/16. // // import Foundation import Credentials import CredentialsGoogle import SyncServerShared import LoggerAPI class User : NSObject, Model { static let userIdKey = "userId" var userId: UserId! static let usernameKey = "username" var username: String! static let accountTypeKey = "accountType" var accountType: AccountScheme.AccountName! // Account type specific id. E.g., for Google, this is the "sub". static let credsIdKey = "credsId" var credsId:String! static let credsKey = "creds" var creds:String! // Stored as JSON // Only used by some owning user accounts (e.g., Google Drive). static let cloudFolderNameKey = "cloudFolderName" var cloudFolderName: String? static let pushNotificationTopicKey = "pushNotificationTopic" var pushNotificationTopic: String? subscript(key:String) -> Any? { set { switch key { case User.userIdKey: userId = newValue as! UserId? case User.usernameKey: username = newValue as! String? case User.accountTypeKey: accountType = newValue as! AccountScheme.AccountName? case User.credsIdKey: credsId = newValue as! String? case User.credsKey: creds = newValue as! String? case User.cloudFolderNameKey: cloudFolderName = newValue as! String? case User.pushNotificationTopicKey: pushNotificationTopic = newValue as! String? default: assert(false) } } get { return getValue(forKey: key) } } // Converts from the current creds JSON and accountType. Returns a new `Creds` object with each call. var credsObject:Account? { do { let credsObj = try AccountManager.session.accountFromJSON(creds, accountName: accountType, user: .user(self), delegate: nil) return credsObj } catch (let error) { Log.error("\(error)") return nil } } } class UserRepository : Repository, RepositoryLookup { private(set) var db:Database! required init(_ db:Database) { self.db = db } var tableName:String { return UserRepository.tableName } static var tableName:String { return "User" } let usernameMaxLength = 255 let credsIdMaxLength = 255 let accountTypeMaxLength = 20 func upcreate() -> Database.TableUpcreateResult { let createColumns = "(userId BIGINT NOT NULL AUTO_INCREMENT, " + // Just a displayable/UI textual name for the user. Not a login name or email address. "username VARCHAR(\(usernameMaxLength)) NOT NULL, " + "accountType VARCHAR(\(accountTypeMaxLength)) NOT NULL, " + // An id specific to the particular type of credentials, e.g., Google. "credsId VARCHAR(\(credsIdMaxLength)) NOT NULL, " + // Stored as JSON. Credential specifics for the particular accountType. "creds TEXT NOT NULL, " + // Can be null because only some cloud storage accounts use this and only owning user accounts use this. "cloudFolderName VARCHAR(\(AddUserRequest.maxCloudFolderNameLength)), " + // A push notification topic for AWS SNS is a group containing endpoint ARN's for all the users registered devices. This will be NULL if a user has no registered devices. "pushNotificationTopic TEXT, " + // I'm not going to require that the username be unique. The userId is unique. "UNIQUE (accountType, credsId), " + "UNIQUE (userId))" let result = db.createTableIfNeeded(tableName: "\(tableName)", columnCreateQuery: createColumns) switch result { case .success(.alreadyPresent): // Table was already there. Do we need to update it? // 2/25/18; Evolution 2: Add cloudFolderName column if db.columnExists(User.cloudFolderNameKey, in: tableName) == false { if !db.addColumn("\(User.cloudFolderNameKey) VARCHAR(\(AddUserRequest.maxCloudFolderNameLength))", to: tableName) { return .failure(.columnCreation) } } default: break } return result } enum LookupKey : CustomStringConvertible { case userId(UserId) case accountTypeInfo(accountType:AccountScheme.AccountName, credsId:String) var description : String { switch self { case .userId(let userId): return "userId(\(userId))" case .accountTypeInfo(accountType: let accountType, credsId: let credsId): return "accountTypeInfo(\(accountType), \(credsId))" } } } func lookupConstraint(key:LookupKey) -> String { switch key { case .userId(let userId): return "userId = '\(userId)'" case .accountTypeInfo(accountType: let accountType, credsId: let credsId): return "accountType = '\(accountType)' AND credsId = '\(credsId)'" } } // userId in the user model is ignored and the automatically generated userId is returned if the add is successful. // 6/12/19; Added `validateJSON`-- this is only for testing and normally should be left with the true default value. func add(user:User, validateJSON: Bool = true) -> Int64? { if user.username == nil || user.accountType == nil || user.credsId == nil { Log.error("One of the model values was nil!") return nil } if validateJSON { // Validate the JSON before we insert it. guard let _ = try? AccountManager.session.accountFromJSON(user.creds, accountName: user.accountType, user: .user(user), delegate: nil) else { Log.error("Invalid creds JSON: \(String(describing: user.creds)) for accountType: \(String(describing: user.accountType))") return nil } } let (cloudFolderNameFieldValue, cloudFolderNameFieldName) = getInsertFieldValueAndName(fieldValue: user.cloudFolderName, fieldName: User.cloudFolderNameKey) let query = "INSERT INTO \(tableName) (username, accountType, credsId, creds \(cloudFolderNameFieldName)) VALUES('\(user.username!)', '\(user.accountType!)', '\(user.credsId!)', '\(user.creds!)' \(cloudFolderNameFieldValue));" if db.query(statement: query) { return db.lastInsertId() } else { let error = db.error Log.error("Could not insert into \(tableName): \(error)") Log.error("query: \(query)") return nil } } func updateCreds(creds newCreds:Account, forUser updateCredsUser:AccountCreationUser) -> Bool { var credsJSONString:String var userId:UserId switch updateCredsUser { case .user(let user): // First need to merge creds-- otherwise, we might override part of the creds with our update. // This looks like it is leaving the `user` object with changed values, but it's actually not (.credsObject generates a new `Creds` object each time it's called). let oldCreds = user.credsObject! oldCreds.merge(withNewer: newCreds) credsJSONString = oldCreds.toJSON()! userId = user.userId case .userId(let id): credsJSONString = newCreds.toJSON()! userId = id } let query = "UPDATE \(tableName) SET creds = '\(credsJSONString)' WHERE " + lookupConstraint(key: .userId(userId)) if db.query(statement: query) { let numberUpdates = db.numberAffectedRows() // 7/6/18; I'm allowing 0 updates because in some cases, e.g., Dropbox, there will be no change in the row. guard numberUpdates <= 1 else { Log.error("Expected <= 1 updated, but had \(numberUpdates)") return false } return true } else { let error = db.error Log.error("Could not update row for \(tableName): \(error)") return false } } // For a sharing user, will have one element per sharing group the user is a member of. These are the "owners" or "parents" of the sharing groups the sharing user is in. Returns an empty list if the user isn't a sharing user. func getOwningSharingGroupUsers(forSharingUserId userId: UserId) -> [User]? { let sharingGroupUserTableName = SharingGroupUserRepository.tableName let selectQuery = "select DISTINCT \(tableName).* FROM \(sharingGroupUserTableName), \(tableName) WHERE \(sharingGroupUserTableName).userId = \(userId) and \(sharingGroupUserTableName).owningUserId = \(tableName).userId" guard let select = Select(db:db, query: selectQuery, modelInit: User.init, ignoreErrors:false) else { return nil } var result:[User] = [] select.forEachRow { rowModel in let rowModel = rowModel as! User result.append(rowModel) } if select.forEachRowStatus == nil { return result } else { return nil } } func updatePushNotificationTopic(forUserId userId: UserId, topic: String?) -> Bool { let topicText = topic ?? "NULL" let query = "UPDATE \(tableName) SET pushNotificationTopic = '\(topicText)' WHERE " + lookupConstraint(key: .userId(userId)) if db.query(statement: query) { let numberUpdates = db.numberAffectedRows() // 7/6/18; I'm allowing 0 updates -- in case the update doesn't change the roow. guard numberUpdates <= 1 else { Log.error("Expected <= 1 updated, but had \(numberUpdates)") return false } return true } else { let error = db.error Log.error("Could not update row for \(tableName): \(error)") return false } } } <file_sep>// // UserController.swift // Server // // Created by <NAME> on 11/26/16. // // import LoggerAPI import Credentials import CredentialsGoogle import SyncServerShared class UserController : ControllerProtocol { // Don't do this setup in init so that database initalizations don't have to be done per endpoint call. class func setup() -> Bool { return true } init() { } enum UserStatus { case error case doesNotExist case exists(User) } // Looks up user in mySQL database. credsId is typically from userProfile.id static func userExists(accountType: AccountScheme.AccountName, credsId: String, userRepository:UserRepository) -> UserStatus { let result = userRepository.lookup(key: .accountTypeInfo(accountType:accountType, credsId:credsId), modelInit: User.init) switch result { case .found(let object): let user = object as! User return .exists(user) case .noObjectFound: return .doesNotExist case .error(_): return .error } } func addUser(params:RequestProcessingParameters) { guard let addUserRequest = params.request as? AddUserRequest else { let message = "Did not receive AddUserRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard let accountScheme = params.accountProperties?.accountScheme else { let message = "Could not get account scheme." Log.error(message) params.completion(.failure(.message(message))) return } guard let credsId = params.userProfile?.id else { let message = "Could not get credsId." Log.error(message) params.completion(.failure(.message(message))) return } let userExists = UserController.userExists(accountType: accountScheme.accountName, credsId: credsId, userRepository: params.repos.user) switch userExists { case .doesNotExist: break case .error, .exists(_): let message = "Could not add user: Already exists!" Log.error(message) params.completion(.failure(.message(message))) return } // No database creds because this is a new user-- so use params.profileCreds let user = User() user.username = params.userProfile!.displayName user.accountType = accountScheme.accountName user.credsId = params.userProfile!.id user.creds = params.profileCreds!.toJSON() if params.profileCreds!.owningAccountsNeedCloudFolderName { guard addUserRequest.cloudFolderName != nil else { let message = "owningAccountsNeedCloudFolderName but no cloudFolderName" Log.error(message) params.completion(.failure(.message(message))) return } user.cloudFolderName = addUserRequest.cloudFolderName } guard params.profileCreds?.accountScheme.userType == .owning else { let message = "Attempting to add a user with an Account that only allows sharing users!" Log.error(message) params.completion(.failure(.message(message))) return } guard let userId = params.repos.user.add(user: user) else { let message = "Failed on adding user to User!" Log.error(message) params.completion(.failure(.message(message))) return } user.userId = userId guard SharingGroupsController.addSharingGroup(sharingGroupUUID: addUserRequest.sharingGroupUUID, sharingGroupName: addUserRequest.sharingGroupName, params: params) else { let message = "Failed on adding new sharing group." Log.error(message) params.completion(.failure(.message(message))) return } // This is creating the "root" owning user for a sharing group; they have max permissions. guard case .success = params.repos.sharingGroupUser.add(sharingGroupUUID: addUserRequest.sharingGroupUUID, userId: userId, permission: .admin, owningUserId: nil) else { let message = "Failed on adding sharing group user." Log.error(message) params.completion(.failure(.message(message))) return } if !params.repos.masterVersion.initialize(sharingGroupUUID: addUserRequest.sharingGroupUUID) { let message = "Failed on creating MasterVersion record for sharing group!" Log.error(message) params.completion(.failure(.message(message))) return } let response = AddUserResponse() response.userId = userId // Previously, we won't have established an `accountCreationUser` for these Creds-- because this is a new user. var profileCreds = params.profileCreds! profileCreds.accountCreationUser = .userId(userId) // We're creating an account for an owning user. `profileCreds` will be an owning user account and this will implement the CloudStorage protocol. guard let cloudStorageCreds = profileCreds.cloudStorage else { let message = "Could not obtain CloudStorage Creds" Log.error(message) params.completion(.failure(.message(message))) return } Log.info("About to check if we need to generate tokens...") // I am not doing token generation earlier (e.g., in the RequestHandler) because in most cases, we don't have a user database record created earlier, so if needed cannot save the tokens generated. profileCreds.generateTokensIfNeeded(dbCreds: nil, routerResponse: params.routerResponse, success: { UserController.createInitialFileForOwningUser(cloudFolderName: addUserRequest.cloudFolderName, cloudStorage: cloudStorageCreds) { creationResponse in switch creationResponse { case .success: params.completion(.success(response)) case .accessTokenRevokedOrExpired: // This is a fatal error. Trying to create an account for which an access token has expired or been revoked. Yikes. Bail out. let message = "Yikes: Access token expired or revoked!" Log.error(message) params.completion(.failure(.message(message))) case .failure: params.completion(.failure(nil)) } } }, failure: { params.completion(.failure(nil)) }) } func checkCreds(params:RequestProcessingParameters) { assert(params.ep.authenticationLevel == .secondary) let response = CheckCredsResponse() response.userId = params.currentSignedInUser!.userId // If we got this far, that means we passed primary and secondary authentication, but we also have to generate tokens, if needed. params.profileCreds!.generateTokensIfNeeded(dbCreds: params.creds!, routerResponse: params.routerResponse, success: { params.completion(.success(response)) }, failure: { params.completion(.failure(nil)) }) } // A user can only remove themselves, not another user-- this policy is enforced because the currently signed in user (with the UserProfile) is the one removed. // Not currently holding a lock to remove a user-- because currently our locks work on sharing groups-- and in general the scope of removing a user is wider than a single sharing group. In the worst case it seems that some other user(s), invited to join by the user being removed, could be uploading at the same time. Seems like limited consequences. func removeUser(params:RequestProcessingParameters) { assert(params.ep.authenticationLevel == .secondary) // I'm not going to remove the users files in their cloud storage. They own those. I think SyncServer doesn't have any business removing their files in this context. guard let accountScheme = params.accountProperties?.accountScheme else { let message = "Could not get accountScheme!" Log.error(message) params.completion(.failure(.message(message))) return } let deviceUUIDRepoKey = DeviceUUIDRepository.LookupKey.userId(params.currentSignedInUser!.userId) let removeResult = params.repos.deviceUUID.retry { return params.repos.deviceUUID.remove(key: deviceUUIDRepoKey) } guard case .removed = removeResult else { let message = "Could not remove deviceUUID's for user!" Log.error(message) params.completion(.failure(.message(message))) return } // When deleting a user, should set to NULL any sharing users that have that userId (being deleted) as their owningUserId. let uploadRepoKey = UploadRepository.LookupKey.userId(params.currentSignedInUser!.userId) let removeResult2 = params.repos.upload.retry { return params.repos.upload.remove(key: uploadRepoKey) } guard case .removed = removeResult2 else { let message = "Could not remove upload files for user!" Log.error(message) params.completion(.failure(.message(message))) return } // 6/25/18; Up until today, user removal had included actual removal of all of the user's files from the FileIndex. BUT-- this goes against how deletion occurs on the SyncServer-- we mark files as deleted, but don't actually remove them from the FileIndex. let markKey = FileIndexRepository.LookupKey.userId(params.currentSignedInUser!.userId) guard let _ = params.repos.fileIndex.markFilesAsDeleted(key: markKey) else { let message = "Could not mark files as deleted for user!" Log.error(message) params.completion(.failure(.message(message))) return } // The user will no longer be part of any sharing groups let sharingGroupUserKey = SharingGroupUserRepository.LookupKey.userId(params.currentSignedInUser!.userId) let removeResult3 = params.repos.sharingGroupUser.retry { return params.repos.sharingGroupUser.remove(key: sharingGroupUserKey) } guard case .removed = removeResult3 else { let message = "Could not remove sharing group references for user: \(removeResult3)" Log.error(message) params.completion(.failure(.message(message))) return } // And, any sharing users making use of this user as an owningUserId can no longer use its userId. let resetKey = SharingGroupUserRepository.LookupKey.owningUserId(params.currentSignedInUser!.userId) guard params.repos.sharingGroupUser.resetOwningUserIds(key: resetKey) else { let message = "Could not remove sharing group references for owning user" Log.error(message) params.completion(.failure(.message(message))) return } // A sharing user that was invited by this user that is deleting themselves will no longer be able to upload files. Because those files have nowhere to go. However, they should still be able to read files in the sharing group uploaded by others. See https://github.com/crspybits/SyncServerII/issues/78 // When removing an owning user: Also remove any sharing invitations that have that owning user in them-- this is just in case there are non-expired invitations from that sharing user. They will be invalid now. let sharingInvitationsKey = SharingInvitationRepository.LookupKey .owningUserId(params.currentSignedInUser!.userId) let removeResult4 = params.repos.sharing.retry { return params.repos.sharing.remove(key: sharingInvitationsKey) } guard case .removed = removeResult4 else { let message = "Could not remove sharing invitations for user: \(removeResult4)" Log.error(message) params.completion(.failure(.message(message))) return } // This has to be last-- we have to remove all references to the user first-- due to foreign key constraints. let userRepoKey = UserRepository.LookupKey.accountTypeInfo(accountType: accountScheme.accountName, credsId: params.userProfile!.id) let removeResult5 = params.repos.user.retry { return params.repos.user.remove(key: userRepoKey) } guard case .removed(let numberRows) = removeResult5, numberRows == 1 else { let message = "Could not remove user!" Log.error(message) params.completion(.failure(.message(message))) return } let response = RemoveUserResponse() params.completion(.success(response)) } } <file_sep>// // AsyncTailRecursion.swift // Server // // Created by <NAME> on 6/10/17. // // import Foundation import Dispatch // This might be a better solution: https://stackoverflow.com/questions/35906568/wait-until-swift-for-loop-with-asynchronous-network-requests-finishes-executing // Except that the above technique allows multiple async requests to operate in parallel, which is not what I want. class AsyncTailRecursion { // TODO: *1* Make sure we're getting deallocation deinit { print("AsyncTailRecursion.deinit") } private let lock = DispatchSemaphore(value: 0) // Blocks the calling thread and another thread starts the recursion. func start(_ firstRecursiveCall:@escaping ()->()) { DispatchQueue.global().async() { firstRecursiveCall() } lock.wait() } func next(_ subsequentRecursiveCall:@escaping ()->()) { DispatchQueue.global().async() { subsequentRecursiveCall() } } // Call this to terminate your recursion. The thread blocked by calling `start` will restart. func done() { lock.signal() } } <file_sep>For documentation see: https://crspybits.github.io/SyncServerII/ SyncServerII supports multiple groups of sharing users synchronizing their data across owers' cloud storage: ![Logical Structure of SyncServer](Docs/MultipleGroupsOfSharingUsers.png) When building, during development, with Xcode, make sure you select "Server > My Mac" otherwise you may get errors like: unable to resolve product type 'com.apple.product-type.tool' for platform 'iphoneos' (in target 'Main') <file_sep>#!/bin/bash eb create syncserver-testing --cname syncserver-testing <file_sep>// // ServerMain.swift // Server // // Created by <NAME> on 12/3/16. // // import Foundation import HeliumLogger import LoggerAPI import Kitura // 7/2/17; SwiftMetrics, perhaps because it was mis-installed, was causing several of my higher-performing test cases to fail. E.g., 10 consecutive uploads and downloads of a 1MB file. Thus, I've commented it out for now. // import SwiftMetrics // import SwiftMetricsDash // If given, the single command line argument to the server is expected to be a full path to the server config file. public class ServerMain { // If server fails to start, try looking for a process using the server's port: // sudo lsof -i -n -P | grep TCP | grep 8080 // static var smd:SwiftMetricsDash? public enum ServerStartup { case blocking // doesn't return from startup (normal case) case nonBlocking // returns from startup (for XCTests) } public class func startup(type:ServerStartup = .blocking) { // Set the logging level HeliumLogger.use(.debug) Log.info("Launching server in \(type) mode with \(CommandLine.arguments.count) command line arguments.") // http://www.kitura.io/en/resources/tutorials/swiftmetrics.html // https://developer.ibm.com/swift/2017/03/21/using-swiftmetrics-secure-kitura-server/ // Enable SwiftMetrics Monitoring //let sm = try! SwiftMetrics() // Pass SwiftMetrics to the dashboard for visualising //smd = try? SwiftMetricsDash(swiftMetricsInstance : sm) if type == .blocking { do { // When we launch the server from within Xcode (or just with no explicit arguments), we have 1 "argument" (CommandLine.arguments[0]). if CommandLine.arguments.count == 1 { try Configuration.setup(configFileFullPath: ServerConfiguration.serverConfigFile) } else { let configFile = CommandLine.arguments[1] Log.info("Loading server config file from: \(configFile)") try Configuration.setup(configFileFullPath: configFile) } } catch (let error) { Log.error("Failed during startup: Could not load config file: \(error)") exit(1) } } if !Controllers.setup() { Log.error("Failed during startup: Could not setup controller(s).") exit(1) } if !Database.setup() { Log.error("Failed during startup: Could not setup database tables(s).") exit(1) } let serverRoutes = CreateRoutes() Kitura.addHTTPServer(onPort: Configuration.server.port, with: serverRoutes.getRoutes()) switch type { case .blocking: Kitura.run() case .nonBlocking: Kitura.start() } } public class func shutdown() { Kitura.stop() } } <file_sep>#!/usr/local/bin/ruby # 12/3/17-- not sure why, but the path `/usr/bin/ruby` isn't working any more. More specifically, require 'xcodeproj' fails. Perhaps because of a High Sierra install? # Tweak the .xcodeproj after creating with the swift package manager. # Resources: # http://stackoverflow.com/questions/41527782/swift-package-manager-and-xcode-retaining-xcode-settings/41612477#41612477 # http://stackoverflow.com/questions/20072937/add-run-script-build-phase-to-xcode-project-from-podspec # https://github.com/IBM-Swift/Kitura-Build/blob/master/build/fix_xcode_project.rb # http://www.rubydoc.info/github/CocoaPods/Xcodeproj/Xcodeproj%2FProject%2FObject%2FAbstractTarget%3Anew_shell_script_build_phase # http://www.rubydoc.info/github/CocoaPods/Xcodeproj/Xcodeproj/Project/Object/AbstractTarget # https://gist.github.com/niklasberglund/129065e2612d00c811d0 # https://github.com/CocoaPods/Xcodeproj # http://stackoverflow.com/questions/34367048/how-do-you-automate-do-copy-files-in-build-phases-using-a-cocoapods-post-insta?rq=1 require 'xcodeproj' path_to_project = "Server.xcodeproj" project = Xcodeproj::Project.open(path_to_project) # 1) Add Copy Files Phase for Server.json to the Products directory for Server target target = project.targets.select { |target| target.name == 'Server' }.first puts "Add Copy Files Phase to #{target}" phase = target.new_copy_files_build_phase() # Contrary to the docs (see http://www.rubydoc.info/github/CocoaPods/Xcodeproj/Xcodeproj/Project/Object/PBXCopyFilesBuildPhase) I believe this is not a path, but rather a code, e.g., 16 indicates to copy the file to the Products Directory. phase.dst_subfolder_spec = "16" fileRef1 = project.new(Xcodeproj::Project::Object::PBXFileReference) fileRef1.path = 'Server.json' phase.add_file_reference(fileRef1) fileRef2 = project.new(Xcodeproj::Project::Object::PBXFileReference) fileRef2.path = 'ServerTests.json' phase.add_file_reference(fileRef2) # 2) Add in script phase for testing target-- because I haven't figured out to get access to the Products directory at test-run time. target = project.targets.select { |target| target.name == 'ServerTests' }.first puts "Add Script Phase to #{target}" phase = target.new_shell_script_build_phase() phase.shell_script = "cp Server.json /tmp; cp ServerTests.json /tmp; cp Resources/Cat.jpg /tmp; cp VERSION /tmp; cp Resources/example.url /tmp" # 3) Add in DEBUG and SERVER flags # A little overkill, but hopefully appending these flags in the Debug configuration for each target doesn't hurt it. project.targets.each do |target| puts "Appending flags to #{target}" if target.build_settings('Debug')['OTHER_SWIFT_FLAGS'].nil? target.build_settings('Debug')['OTHER_SWIFT_FLAGS'] = "" end target.build_settings('Debug')['OTHER_SWIFT_FLAGS'] << '-DDEBUG -DSERVER' # target.build_settings('Debug')['SWIFT_VERSION'] = '4.0' end project.save() <file_sep>// // SharingAccountsController_RedeemSharingInvitation.swift // Server // // Created by <NAME> on 4/12/17. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class SharingAccountsController_RedeemSharingInvitation: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testThatRedeemingWithASharingAccountWorks() { let sharingUser:TestAccount = .primarySharingAccount let owningUser:TestAccount = .primaryOwningAccount var sharingGroupUUID: String! var newSharingUserId: UserId! createSharingUser(sharingUser: sharingUser, owningUserWhenCreating: owningUser) { userId, sid, _ in sharingGroupUUID = sid newSharingUserId = userId } guard sharingGroupUUID != nil else { XCTFail() return } checkOwingUserForSharingGroupUser(sharingGroupUUID: sharingGroupUUID, sharingUserId: newSharingUserId, sharingUser: sharingUser, owningUser: owningUser) } // Requires that Facebook creds be up to date. func testThatRedeemingWithANonOwningSharingAccountWorks() { let sharingUser:TestAccount = .nonOwningSharingAccount let owningUser:TestAccount = .primaryOwningAccount var sharingGroupUUID: String! var newSharingUserId: UserId! createSharingUser(sharingUser: sharingUser, owningUserWhenCreating: owningUser) { userId, sid, _ in sharingGroupUUID = sid newSharingUserId = userId } guard sharingGroupUUID != nil else { XCTFail() return } guard checkOwingUserForSharingGroupUser(sharingGroupUUID: sharingGroupUUID, sharingUserId: newSharingUserId, sharingUser: sharingUser, owningUser: owningUser) else { XCTFail() return } guard let (_, sharingGroups) = getIndex(testAccount: sharingUser), sharingGroups.count > 0 else { XCTFail() return } var found = false for sharingGroup in sharingGroups { if sharingGroup.sharingGroupUUID == sharingGroupUUID { guard let cloudStorageType = sharingGroup.cloudStorageType else { XCTFail() return } XCTAssert(owningUser.scheme.cloudStorageType == cloudStorageType) found = true } } XCTAssert(found) } func testThatRedeemingUsingGoogleAccountWithoutCloudFolderNameFails() { let permission:Permission = .write let sharingUser:TestAccount = .google2 let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: permission, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } redeemSharingInvitation(sharingUser:sharingUser, canGiveCloudFolderName: false, sharingInvitationUUID: sharingInvitationUUID, errorExpected: true) { result, expectation in expectation.fulfill() } } func redeemingASharingInvitationWithoutGivingTheInvitationUUIDFails(sharingUser: TestAccount) { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } redeemSharingInvitation(sharingUser: sharingUser, errorExpected:true) { _, expectation in expectation.fulfill() } } func testThatRedeemingASharingInvitationByAUserWithoutGivingTheInvitationUUIDFails() { redeemingASharingInvitationWithoutGivingTheInvitationUUIDFails(sharingUser: .primarySharingAccount) } func testThatRedeemingWithTheSameAccountAsTheOwningAccountFails() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID: sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } redeemSharingInvitation(sharingUser: .primaryOwningAccount, sharingInvitationUUID: sharingInvitationUUID, errorExpected:true) { _, expectation in expectation.fulfill() } } // 8/12/18; This now works-- i.e., you can redeem with other owning accounts-- because each user can now be in multiple sharing groups. (Prior to this, it was a failure test!). func testThatRedeemingWithAnExistingOtherOwningAccountWorks() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID1 = Foundation.UUID().uuidString let owningAccount:TestAccount = .primaryOwningAccount guard let _ = self.addNewUser(testAccount: owningAccount, sharingGroupUUID: sharingGroupUUID1, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(testAccount: owningAccount, permission: .read, sharingGroupUUID:sharingGroupUUID1) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let secondOwningAccount:TestAccount = .secondaryOwningAccount let deviceUUID2 = Foundation.UUID().uuidString let sharingGroupUUID2 = Foundation.UUID().uuidString addNewUser(testAccount: secondOwningAccount, sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID2) var result: RedeemSharingInvitationResponse! redeemSharingInvitation(sharingUser: secondOwningAccount, sharingInvitationUUID: sharingInvitationUUID) { response, expectation in result = response expectation.fulfill() } guard result != nil else { XCTFail() return } checkOwingUserForSharingGroupUser(sharingGroupUUID: sharingGroupUUID2, sharingUserId: result.userId, sharingUser: secondOwningAccount, owningUser: owningAccount) } // Redeem sharing invitation for existing user: Works if user isn't already in sharing group func testThatRedeemingWithAnExistingOtherSharingAccountWorks() { redeemWithAnExistingOtherSharingAccount() } func redeemingForSameSharingGroupFails(sharingUser: TestAccount) { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID: sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } redeemSharingInvitation(sharingUser: sharingUser, sharingInvitationUUID: sharingInvitationUUID) { _, expectation in expectation.fulfill() } // Check to make sure we have a new user: let userKey = UserRepository.LookupKey.accountTypeInfo(accountType: sharingUser.scheme.accountName, credsId: sharingUser.id()) let userResults = UserRepository(self.db).lookup(key: userKey, modelInit: User.init) guard case .found(_) = userResults else { XCTFail() return } let key = SharingInvitationRepository.LookupKey.sharingInvitationUUID(uuid: sharingInvitationUUID) let results = SharingInvitationRepository(self.db).lookup(key: key, modelInit: SharingInvitation.init) guard case .noObjectFound = results else { XCTFail() return } createSharingInvitation(permission: .write, sharingGroupUUID: sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } // Since the user account represented by sharingUser is already a member of the sharing group referenced by the specific sharingGroupUUID, this redeem attempt will fail. redeemSharingInvitation(sharingUser: sharingUser, sharingInvitationUUID: sharingInvitationUUID, errorExpected: true) { _, expectation in expectation.fulfill() } } func testThatRedeemingForSameSharingGroupFails() { redeemingForSameSharingGroupFails(sharingUser: .primarySharingAccount) } func checkingCredsOnASharingUserGivesSharingPermission(sharingUser: TestAccount) { let perm:Permission = .write var actualSharingGroupUUID: String? var newSharingUserId:UserId! let owningUser:TestAccount = .primaryOwningAccount createSharingUser(withSharingPermission: perm, sharingUser: sharingUser, owningUserWhenCreating: owningUser) { userId, sharingGroupUUID, _ in actualSharingGroupUUID = sharingGroupUUID newSharingUserId = userId } guard newSharingUserId != nil, actualSharingGroupUUID != nil, let (_, groups) = getIndex(testAccount: sharingUser) else { XCTFail() return } let filtered = groups.filter {$0.sharingGroupUUID == actualSharingGroupUUID} guard filtered.count == 1 else { XCTFail() return } checkOwingUserForSharingGroupUser(sharingGroupUUID: actualSharingGroupUUID!, sharingUserId: newSharingUserId, sharingUser: sharingUser, owningUser: owningUser) XCTAssert(filtered[0].permission == perm, "Actual: \(String(describing: filtered[0].permission)); expected: \(perm)") } func testThatCheckingCredsOnASharingUserGivesSharingPermission() { checkingCredsOnASharingUserGivesSharingPermission(sharingUser: .primarySharingAccount) } func testThatCheckingCredsOnARootOwningUserGivesAdminSharingPermission() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let (_, groups) = getIndex() else { XCTFail() return } let filtered = groups.filter {$0.sharingGroupUUID == sharingGroupUUID} guard filtered.count == 1 else { XCTFail() return } XCTAssert(filtered[0].permission == .admin) } func testThatDeletingSharingUserWorks() { createSharingUser(sharingUser: .primarySharingAccount) let deviceUUID = Foundation.UUID().uuidString // remove performServerTest(testAccount: .primarySharingAccount) { expectation, creds in let headers = self.setupHeaders(testUser: .primarySharingAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.removeUser, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "removeUser failed") expectation.fulfill() } } } func testThatRedeemingWithAnExistingOwningAccountWorks() { // Create an owning user, A -- this also creates sharing group 1 // Create another owning user, B (also creates a sharing group) // A creates sharing invitation to sharing group 1. // B redeems sharing invitation. let deviceUUID = Foundation.UUID().uuidString let permission:Permission = .read let sharingGroupUUID1 = Foundation.UUID().uuidString guard let _ = self.addNewUser(testAccount: .primaryOwningAccount, sharingGroupUUID: sharingGroupUUID1, deviceUUID:deviceUUID) else { XCTFail() return } let sharingGroupUUID2 = Foundation.UUID().uuidString guard let _ = self.addNewUser(testAccount: .secondaryOwningAccount, sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(testAccount: .primaryOwningAccount, permission: permission, sharingGroupUUID:sharingGroupUUID1) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } var redeemResult: RedeemSharingInvitationResponse? redeemSharingInvitation(sharingUser: .secondaryOwningAccount, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in XCTAssert(result?.userId != nil && result?.sharingGroupUUID != nil) redeemResult = result expectation.fulfill() } guard redeemResult != nil else { XCTFail() return } checkOwingUserForSharingGroupUser(sharingGroupUUID: sharingGroupUUID1, sharingUserId: redeemResult!.userId, sharingUser: .secondaryOwningAccount, owningUser: .primaryOwningAccount) } func testRedeemingSharingInvitationThatHasAlreadyBeenRedeemedFails() { let sharingUser1:TestAccount = .primarySharingAccount let sharingUser2:TestAccount = .secondarySharingAccount let owningUser:TestAccount = .primaryOwningAccount var sharingGroupUUID: String! var newSharingUserId: UserId! var sharingInvitationUUID: String! createSharingUser(sharingUser: sharingUser1, owningUserWhenCreating: owningUser) { userId, sid, sharingInviteUUID in sharingGroupUUID = sid newSharingUserId = userId sharingInvitationUUID = sharingInviteUUID } guard sharingGroupUUID != nil, newSharingUserId != nil else { XCTFail() return } redeemSharingInvitation(sharingUser:sharingUser2, sharingInvitationUUID: sharingInvitationUUID, errorExpected: true) { result, expectation in expectation.fulfill() } } func testTwoAcceptorsSharingInvitationCanBeRedeemedTwice() { let sharingUser1:TestAccount = .primarySharingAccount let sharingUser2:TestAccount = .secondarySharingAccount let owningUser:TestAccount = .primaryOwningAccount var sharingGroupUUID: String! var newSharingUserId: UserId! var sharingInvitationUUID: String! createSharingUser(sharingUser: sharingUser1, owningUserWhenCreating: owningUser, numberAcceptors: 2) { userId, sid, sharingInviteUUID in sharingGroupUUID = sid newSharingUserId = userId sharingInvitationUUID = sharingInviteUUID } guard sharingGroupUUID != nil, newSharingUserId != nil else { XCTFail() return } redeemSharingInvitation(sharingUser:sharingUser2, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in expectation.fulfill() } // Make sure the sharing invitation has now been removed. let key = SharingInvitationRepository.LookupKey.sharingInvitationUUID(uuid: sharingInvitationUUID) let results = SharingInvitationRepository(self.db).lookup(key: key, modelInit: SharingInvitation.init) guard case .noObjectFound = results else { XCTFail() return } } func testNonSocialSharingInvitationRedeemedSociallyFails() { let sharingUser:TestAccount = .nonOwningSharingAccount let owningUser:TestAccount = .primaryOwningAccount createSharingUser(sharingUser: sharingUser, owningUserWhenCreating: owningUser, allowSharingAcceptance: false, failureExpected: true) { userId, sid, sharingInviteUUID in } } func testNonSocialSharingInvitationRedeemedNonSociallyWorks() { let sharingUser:TestAccount = .secondaryOwningAccount let owningUser:TestAccount = .primaryOwningAccount createSharingUser(sharingUser: sharingUser, owningUserWhenCreating: owningUser, allowSharingAcceptance: false) { userId, sid, sharingInviteUUID in } } } extension SharingAccountsController_RedeemSharingInvitation { static var allTests : [(String, (SharingAccountsController_RedeemSharingInvitation) -> () throws -> Void)] { return [ ("testThatRedeemingWithASharingAccountWorks", testThatRedeemingWithASharingAccountWorks), ("testThatRedeemingWithANonOwningSharingAccountWorks", testThatRedeemingWithANonOwningSharingAccountWorks), ("testThatRedeemingUsingGoogleAccountWithoutCloudFolderNameFails", testThatRedeemingUsingGoogleAccountWithoutCloudFolderNameFails), ("testThatRedeemingASharingInvitationByAUserWithoutGivingTheInvitationUUIDFails", testThatRedeemingASharingInvitationByAUserWithoutGivingTheInvitationUUIDFails), ("testThatRedeemingWithTheSameAccountAsTheOwningAccountFails", testThatRedeemingWithTheSameAccountAsTheOwningAccountFails), ("testThatRedeemingWithAnExistingOtherOwningAccountWorks", testThatRedeemingWithAnExistingOtherOwningAccountWorks), ("testThatRedeemingWithAnExistingOtherSharingAccountWorks", testThatRedeemingWithAnExistingOtherSharingAccountWorks), ("testThatRedeemingForSameSharingGroupFails", testThatRedeemingForSameSharingGroupFails), ("testThatCheckingCredsOnASharingUserGivesSharingPermission", testThatCheckingCredsOnASharingUserGivesSharingPermission), ("testThatCheckingCredsOnARootOwningUserGivesAdminSharingPermission", testThatCheckingCredsOnARootOwningUserGivesAdminSharingPermission), ("testThatDeletingSharingUserWorks", testThatDeletingSharingUserWorks), ("testThatRedeemingWithAnExistingOwningAccountWorks", testThatRedeemingWithAnExistingOwningAccountWorks), ("testRedeemingSharingInvitationThatHasAlreadyBeenRedeemedFails", testRedeemingSharingInvitationThatHasAlreadyBeenRedeemedFails), ("testTwoAcceptorsSharingInvitationCanBeRedeemedTwice", testTwoAcceptorsSharingInvitationCanBeRedeemedTwice), ("testNonSocialSharingInvitationRedeemedSociallyFails", testNonSocialSharingInvitationRedeemedSociallyFails), ("testNonSocialSharingInvitationRedeemedNonSociallyWorks", testNonSocialSharingInvitationRedeemedNonSociallyWorks) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SharingAccountsController_RedeemSharingInvitation.self) } } <file_sep>// // VersionTests.swift // Server // // Created by <NAME> on 2/3/18. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class VersionTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() } func testThatVersionGetsReturnedInHeaders() { performServerTest { expectation, creds in // Use healthCheck just because it's a simple endpoint. self.performRequest(route: ServerEndpoints.healthCheck) { response, dict in XCTAssert(response!.statusCode == .OK, "Failed on healthcheck request") // It's a bit odd, but Kitura gives a [String] for each http header key. guard let versionHeaderArray = response?.headers[ServerConstants.httpResponseCurrentServerVersion], versionHeaderArray.count == 1 else { XCTFail() expectation.fulfill() return } let versionString = versionHeaderArray[0] let components = versionString.components(separatedBy: ".") guard components.count == 3 else { XCTFail("Didn't get three components in version: \(versionString)") expectation.fulfill() return } guard let _ = Int(components[0]), let _ = Int(components[1]), let _ = Int(components[2]) else { XCTFail("All components were not integers: \(versionString)") expectation.fulfill() return } expectation.fulfill() } } } } extension VersionTests { static var allTests : [(String, (VersionTests) -> () throws -> Void)] { return [ ("testThatVersionGetsReturnedInHeaders", testThatVersionGetsReturnedInHeaders), ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: VersionTests.self) } } <file_sep>// // FileController_DownloadAppMetaDataTests.swift // ServerTests // // Created by <NAME> on 3/24/18. // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared import HeliumLogger class FileController_DownloadAppMetaDataTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testDownloadAppMetaDataForBadUUIDFails() { let masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData = AppMetaData(version: 0, contents: "Test1") guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) let badFileUUID = Foundation.UUID().uuidString downloadAppMetaDataVersion(deviceUUID:deviceUUID, fileUUID: badFileUUID, masterVersionExpectedWithDownload:1, appMetaDataVersion: 0, sharingGroupUUID: sharingGroupUUID, expectedError: true) } func testDownloadAppMetaDataForReallyBadUUIDFails() { let masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData = AppMetaData(version: 0, contents: "Test1") guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) let badFileUUID = "Blig" downloadAppMetaDataVersion(deviceUUID:deviceUUID, fileUUID: badFileUUID, masterVersionExpectedWithDownload:1, appMetaDataVersion: 0, sharingGroupUUID: sharingGroupUUID, expectedError: true) } func testDownloadAppMetaDataVersionNotOnServerFails() { let masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData = AppMetaData(version: 0, contents: "Test1") guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) let badAppMetaDataVersion = appMetaData.version + 1 downloadAppMetaDataVersion(deviceUUID:deviceUUID, fileUUID: uploadResult1.request.fileUUID, masterVersionExpectedWithDownload:1, appMetaDataVersion: badAppMetaDataVersion, sharingGroupUUID: sharingGroupUUID, expectedError: true) } func testDownloadNilAppMetaDataVersionAs0Fails() { var masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 downloadAppMetaDataVersion(deviceUUID:deviceUUID, fileUUID: uploadResult1.request.fileUUID, masterVersionExpectedWithDownload:masterVersion, appMetaDataVersion: 0, sharingGroupUUID: sharingGroupUUID, expectedError: true) } func testDownloadAppMetaDataForFileThatIsNotOwnedFails() { var masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData = AppMetaData(version: 0, contents: "Test1") Log.debug("About to uploadTextFile") guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } Log.debug("About to sendDoneUploads") sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 let deviceUUID2 = Foundation.UUID().uuidString Log.debug("About to addNewUser") let nonOwningAccount:TestAccount = .secondaryOwningAccount let sharingGroupUUID2 = UUID().uuidString guard let _ = addNewUser(testAccount: nonOwningAccount, sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID2) else { XCTFail() return } Log.debug("About to downloadAppMetaDataVersion") // Using masterVersion 0 here because that's what the nonOwningAccount will have at this point. downloadAppMetaDataVersion(testAccount: nonOwningAccount, deviceUUID:deviceUUID2, fileUUID: uploadResult1.request.fileUUID, masterVersionExpectedWithDownload:0, appMetaDataVersion: 0, sharingGroupUUID: sharingGroupUUID2, expectedError: true) } func testDownloadValidAppMetaDataVersion0() { let masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData = AppMetaData(version: 0, contents: "Test1") guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) guard let downloadAppMetaDataResponse = downloadAppMetaDataVersion(deviceUUID:deviceUUID, fileUUID: uploadResult1.request.fileUUID, masterVersionExpectedWithDownload:1, appMetaDataVersion: 0, sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } XCTAssert(downloadAppMetaDataResponse.appMetaData == appMetaData.contents) } func testDownloadValidAppMetaDataVersion1() { var masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString var appMetaData = AppMetaData(version: 0, contents: "Test1") guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 guard let downloadAppMetaDataResponse1 = downloadAppMetaDataVersion(deviceUUID:deviceUUID, fileUUID: uploadResult1.request.fileUUID, masterVersionExpectedWithDownload:masterVersion, appMetaDataVersion: appMetaData.version, sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } XCTAssert(downloadAppMetaDataResponse1.appMetaData == appMetaData.contents) // Second upload and download appMetaData = AppMetaData(version: 1, contents: "Test2") uploadTextFile(deviceUUID:deviceUUID, fileUUID: uploadResult1.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion: 1, masterVersion:masterVersion, appMetaData:appMetaData) sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 guard let downloadAppMetaDataResponse2 = downloadAppMetaDataVersion(deviceUUID:deviceUUID, fileUUID: uploadResult1.request.fileUUID, masterVersionExpectedWithDownload:masterVersion, appMetaDataVersion: appMetaData.version, sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } XCTAssert(downloadAppMetaDataResponse2.appMetaData == appMetaData.contents) } // Upload app meta data version 0, then upload app meta version nil, and then make sure when you download you still have app meta version 0. i.e., nil doesn't overwrite a non-nil version. func testUploadingNilAppMetaDataDoesNotOverwriteCurrent() { var masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData = AppMetaData(version: 0, contents: "Test1") guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 guard let _ = uploadTextFile(deviceUUID:deviceUUID, fileUUID: uploadResult1.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion: 1, masterVersion:masterVersion) else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 guard let downloadAppMetaDataResponse1 = downloadAppMetaDataVersion(deviceUUID:deviceUUID, fileUUID: uploadResult1.request.fileUUID, masterVersionExpectedWithDownload:masterVersion, appMetaDataVersion: appMetaData.version, sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } XCTAssert(downloadAppMetaDataResponse1.appMetaData == appMetaData.contents) } func testDownloadAppMetaDataWithFakeSharingGroupUUIDFails() { let masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData = AppMetaData(version: 0, contents: "Test1") guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) let invalidSharingGroupUUID = UUID().uuidString downloadAppMetaDataVersion(deviceUUID:deviceUUID, fileUUID: uploadResult1.request.fileUUID, masterVersionExpectedWithDownload:1, appMetaDataVersion: 0, sharingGroupUUID: invalidSharingGroupUUID, expectedError: true) } func testDownloadAppMetaDataWithBadSharingGroupUUIDFails() { let masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData = AppMetaData(version: 0, contents: "Test1") guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) let workingButBadSharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: workingButBadSharingGroupUUID) else { XCTFail() return } downloadAppMetaDataVersion(deviceUUID:deviceUUID, fileUUID: uploadResult1.request.fileUUID, masterVersionExpectedWithDownload:1, appMetaDataVersion: 0, sharingGroupUUID: workingButBadSharingGroupUUID, expectedError: true) } } extension FileController_DownloadAppMetaDataTests { static var allTests : [(String, (FileController_DownloadAppMetaDataTests) -> () throws -> Void)] { return [ ("testDownloadAppMetaDataForBadUUIDFails", testDownloadAppMetaDataForBadUUIDFails), ("testDownloadAppMetaDataForReallyBadUUIDFails", testDownloadAppMetaDataForReallyBadUUIDFails), ("testDownloadAppMetaDataVersionNotOnServerFails", testDownloadAppMetaDataVersionNotOnServerFails), ("testDownloadNilAppMetaDataVersionAs0Fails", testDownloadNilAppMetaDataVersionAs0Fails), ("testDownloadAppMetaDataForFileThatIsNotOwnedFails", testDownloadAppMetaDataForFileThatIsNotOwnedFails), ("testDownloadValidAppMetaDataVersion0", testDownloadValidAppMetaDataVersion0), ("testDownloadValidAppMetaDataVersion1", testDownloadValidAppMetaDataVersion1), ("testUploadingNilAppMetaDataDoesNotOverwriteCurrent", testUploadingNilAppMetaDataDoesNotOverwriteCurrent), ("testDownloadAppMetaDataWithBadSharingGroupUUIDFails", testDownloadAppMetaDataWithBadSharingGroupUUIDFails), ("testDownloadAppMetaDataWithFakeSharingGroupUUIDFails", testDownloadAppMetaDataWithFakeSharingGroupUUIDFails) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:FileController_DownloadAppMetaDataTests.self) } } <file_sep>// // FileController+UploadDeletion.swift // Server // // Created by <NAME> on 3/22/17. // // import Foundation import LoggerAPI import SyncServerShared import Kitura extension FileController { func uploadDeletion(params:RequestProcessingParameters) { guard let uploadDeletionRequest = params.request as? UploadDeletionRequest else { let message = "Did not receive UploadDeletionRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard sharingGroupSecurityCheck(sharingGroupUUID: uploadDeletionRequest.sharingGroupUUID, params: params) else { let message = "Failed in sharing group security check." Log.error(message) params.completion(.failure(.message(message))) return } guard uploadDeletionRequest.fileVersion != nil else { let message = "File version not given in upload request." Log.error(message) params.completion(.failure(.message(message))) return } Controllers.getMasterVersion(sharingGroupUUID: uploadDeletionRequest.sharingGroupUUID, params: params) { (error, masterVersion) in if error != nil { let message = "Error: \(String(describing: error))" Log.error(message) params.completion(.failure(.message(message))) return } if masterVersion != uploadDeletionRequest.masterVersion { let response = UploadDeletionResponse() Log.warning("Master version update: \(String(describing: masterVersion))") response.masterVersionUpdate = masterVersion params.completion(.success(response)) return } // Check whether this fileUUID exists in the FileIndex. let key = FileIndexRepository.LookupKey.primaryKeys(sharingGroupUUID: uploadDeletionRequest.sharingGroupUUID, fileUUID: uploadDeletionRequest.fileUUID) let lookupResult = params.repos.fileIndex.lookup(key: key, modelInit: FileIndex.init) var fileIndexObj:FileIndex! switch lookupResult { case .found(let modelObj): fileIndexObj = modelObj as? FileIndex if fileIndexObj == nil { let message = "Could not convert model object to FileIndex" Log.error(message) params.completion(.failure(.message(message))) return } case .noObjectFound: let message = "Could not find file to delete in FileIndex" Log.error(message) params.completion(.failure(.message(message))) return case .error(let error): let message = "Error looking up file in FileIndex: \(error)" Log.error(message) params.completion(.failure(.message(message))) return } if fileIndexObj.fileVersion != uploadDeletionRequest.fileVersion { let message = "File index version is: \(String(describing: fileIndexObj.fileVersion)), but you asked to delete version: \(String(describing: uploadDeletionRequest.fileVersion))" Log.error(message) params.completion(.failure(.message(message))) return } Log.debug("uploadDeletionRequest.actualDeletion: \(String(describing: uploadDeletionRequest.actualDeletion))") #if DEBUG if let actualDeletion = uploadDeletionRequest.actualDeletion, actualDeletion { actuallyDeleteFileFromServer(key:key, uploadDeletionRequest:uploadDeletionRequest, fileIndexObj:fileIndexObj, params:params) return } #endif var errorString:String? // Create entry in Upload table. let upload = Upload() upload.fileUUID = uploadDeletionRequest.fileUUID upload.deviceUUID = params.deviceUUID upload.fileVersion = uploadDeletionRequest.fileVersion upload.state = .toDeleteFromFileIndex upload.userId = params.currentSignedInUser!.userId upload.sharingGroupUUID = uploadDeletionRequest.sharingGroupUUID let uploadAddResult = params.repos.upload.add(upload: upload) switch uploadAddResult { case .success(_): let response = UploadDeletionResponse() params.completion(.success(response)) return case .duplicateEntry: Log.info("File was already marked for deletion: Not adding again.") let response = UploadDeletionResponse() params.completion(.success(response)) return case .aModelValueWasNil: errorString = "A model value was nil!" case .deadlock: errorString = "Deadlock" case .waitTimeout: errorString = "waitTimeout" case .otherError(let error): errorString = error } Log.error(errorString!) params.completion(.failure(.message(errorString!))) return } } #if DEBUG func actuallyDeleteFileFromServer(key:FileIndexRepository.LookupKey, uploadDeletionRequest: Filenaming, fileIndexObj:FileIndex, params:RequestProcessingParameters) { let result = params.repos.fileIndex.retry { return params.repos.fileIndex.remove(key: key) } switch result { case .removed(numberRows: let numberRows): if numberRows != 1 { let message = "Number of rows deleted \(numberRows) != 1" Log.error(message) params.completion(.failure(.message(message))) return } case .deadlock: let message = "Error deleting from FileIndex: deadlock" Log.error(message) params.completion(.failure(.message(message))) return case .waitTimeout: let message = "Error deleting from FileIndex: waitTimeout" Log.error(message) params.completion(.failure(.message(message))) return case .error(let error): let message = "Error deleting from FileIndex: \(error)" Log.error(message) params.completion(.failure(.message(message))) return } // OWNER // Need to get creds for the user that uploaded the v0 file. guard let cloudStorageCreds = FileController.getCreds(forUserId: fileIndexObj.userId, from: params.db, delegate: params.accountDelegate)?.cloudStorage else { let message = "Could not obtain CloudStorage creds for original v0 owner of file." Log.error(message) params.completion(.failure( .goneWithReason(message: message, .userRemoved))) return } let cloudFileName = uploadDeletionRequest.cloudFileName(deviceUUID: fileIndexObj.deviceUUID!, mimeType: fileIndexObj.mimeType!) // Because we need this to get the cloudFolderName guard let effectiveOwningUserCreds = params.effectiveOwningUserCreds else { let message = "No effectiveOwningUserCreds" Log.debug(message) params.completion(.failure( .goneWithReason(message: message, .userRemoved))) return } let options = CloudStorageFileNameOptions(cloudFolderName: effectiveOwningUserCreds.cloudFolderName, mimeType: fileIndexObj.mimeType!) cloudStorageCreds.deleteFile(cloudFileName: cloudFileName, options: options) { result in switch result { case .success: break case .accessTokenRevokedOrExpired: // As in [1]. Log.warning("Error deleting file from cloud storage: Access token revoked or expired") case .failure(let error): // [1] Log.warning("Error deleting file from cloud storage: \(error)!") // I'm not going to fail if this fails-- this is for debugging and it's not a big deal. Drop through and report success. } let response = UploadDeletionResponse() params.completion(.success(response)) return } } #endif } <file_sep>#!/bin/bash /bin/rm -rf .build # 9/14/18; Get a problem with `swift package update` now if we leave this in. An apparent dependency "cycle" or other such that issue that never gets resolved, never returns from swift package update. # rm Package.resolved >& /dev/null /bin/rm -rf .testing <file_sep>../Tools/suspend.sh<file_sep>// // SpecificDatabaseTests_SharingGroups.swift // ServerTests // // Created by <NAME> on 7/4/18. // import XCTest @testable import Server import LoggerAPI import HeliumLogger import Foundation import SyncServerShared class SpecificDatabaseTests_SharingGroups: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testAddSharingGroupWithoutName() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } } func testAddSharingGroupWithName() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID, sharingGroupName: "Foobar") else { XCTFail() return } } func testLookupFromSharingGroupExisting() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let key = SharingGroupRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let result = SharingGroupRepository(db).lookup(key: key, modelInit: SharingGroup.init) switch result { case .found(let model): guard let obj = model as? Server.SharingGroup else { XCTFail() return } XCTAssert(obj.sharingGroupUUID != nil) case .noObjectFound: XCTFail("No object found") case .error(let error): XCTFail("Error: \(error)") } } func testLookupFromSharingGroupNonExisting() { let key = SharingGroupRepository.LookupKey.sharingGroupUUID(UUID().uuidString) let result = SharingGroupRepository(db).lookup(key: key, modelInit: SharingGroup.init) switch result { case .found: XCTFail() case .noObjectFound: break case .error(let error): XCTFail("Error: \(error)") } } } extension SpecificDatabaseTests_SharingGroups { static var allTests : [(String, (SpecificDatabaseTests_SharingGroups) -> () throws -> Void)] { return [ ("testAddSharingGroupWithoutName", testAddSharingGroupWithoutName), ("testAddSharingGroupWithName", testAddSharingGroupWithName), ("testLookupFromSharingGroupExisting", testLookupFromSharingGroupExisting), ("testLookupFromSharingGroupNonExisting", testLookupFromSharingGroupNonExisting) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SpecificDatabaseTests_SharingGroups.self) } } <file_sep>// // FileControllerTests_GetUploads.swift // Server // // Created by <NAME> on 2/18/17. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class FileControllerTests_GetUploads: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testForZeroUploads() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } self.getUploads(expectedFiles: [], deviceUUID:deviceUUID, expectedCheckSums: [:], sharingGroupUUID: sharingGroupUUID) } func testForOneUpload() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } let expectedCheckSums = [ uploadResult.request.fileUUID!: uploadResult.checkSum ] self.getUploads(expectedFiles: [uploadResult.request], deviceUUID:deviceUUID, expectedCheckSums: expectedCheckSums, sharingGroupUUID: sharingGroupUUID) } func testForOneUploadButDoneTwice() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // Second upload-- shouldn't result in second entries in Upload table. guard let _ = uploadTextFile(deviceUUID: deviceUUID, fileUUID: uploadResult.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion: uploadResult.request.fileVersion, masterVersion: uploadResult.request.masterVersion, appMetaData: uploadResult.request.appMetaData) else { XCTFail() return } let expectedCheckSums = [ uploadResult.request.fileUUID!: uploadResult.checkSum, ] self.getUploads(expectedFiles: [uploadResult.request], deviceUUID:deviceUUID, expectedCheckSums: expectedCheckSums, sharingGroupUUID: sharingGroupUUID) } func testForOneUploadButFromWrongDeviceUUID() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // This will do the GetUploads, but with a different deviceUUID, which will give empty result. self.getUploads(expectedFiles: [], expectedCheckSums: [:], sharingGroupUUID:sharingGroupUUID) } func testForTwoUploads() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } guard let uploadResult2 = uploadJPEGFile(deviceUUID:deviceUUID, addUser:.no(sharingGroupUUID: sharingGroupUUID)) else { XCTFail() return } let expectedCheckSums = [ uploadResult1.request.fileUUID!: uploadResult1.checkSum, uploadResult2.request.fileUUID!: uploadResult2.checkSum ] self.getUploads(expectedFiles: [uploadResult1.request, uploadResult2.request], deviceUUID:deviceUUID, expectedCheckSums: expectedCheckSums, sharingGroupUUID: sharingGroupUUID) } func testForNoUploadsAfterDoneUploads() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) self.getUploads(expectedFiles: [], deviceUUID:deviceUUID, expectedCheckSums: [:], sharingGroupUUID: sharingGroupUUID) } func testFakeSharingGroupWithGetUploadsFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } let invalidSharingGroupUUID = UUID().uuidString self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) self.getUploads(expectedFiles: [], deviceUUID:deviceUUID, expectedCheckSums: [:], sharingGroupUUID: invalidSharingGroupUUID, errorExpected: true) } func testBadSharingGroupWithGetUploadsFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } let workingButBadSharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: workingButBadSharingGroupUUID) else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) self.getUploads(expectedFiles: [], deviceUUID:deviceUUID, expectedCheckSums: [:], sharingGroupUUID: workingButBadSharingGroupUUID, errorExpected: true) } } extension FileControllerTests_GetUploads { static var allTests : [(String, (FileControllerTests_GetUploads) -> () throws -> Void)] { return [ ("testForZeroUploads", testForZeroUploads), ("testForOneUpload", testForOneUpload), ("testForOneUploadButDoneTwice", testForOneUploadButDoneTwice), ("testForOneUploadButFromWrongDeviceUUID", testForOneUploadButFromWrongDeviceUUID), ("testForTwoUploads", testForTwoUploads), ("testForNoUploadsAfterDoneUploads", testForNoUploadsAfterDoneUploads), ("testBadSharingGroupWithGetUploadsFails", testBadSharingGroupWithGetUploadsFails), ("testFakeSharingGroupWithGetUploadsFails", testFakeSharingGroupWithGetUploadsFails) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:FileControllerTests_GetUploads.self) } } <file_sep>// // Configuration.swift // Server // // Created by <NAME> on 9/10/19. // // Server startup configuration info. import LoggerAPI import Foundation import PerfectLib class Configuration { let deployedGitTag:String // The following file is assumed to be at the root of the running, deployed server-- e.g., I'm putting it there when I build the Docker image. File is assumed to contain one line of text. private let deployedGitTagFilename = "VERSION" static private(set) var server: ServerConfiguration! static private(set) var misc:Configuration! #if DEBUG static private(set) var test:TestConfiguration? #endif /// testConfigFileFullPath is only for testing, with the DEBUG compilation flag on. static func setup(configFileFullPath:String, testConfigFileFullPath:String? = nil) throws { misc = try Configuration(configFileFullPath:configFileFullPath, testConfigFileFullPath: testConfigFileFullPath) } private init(configFileFullPath:String, testConfigFileFullPath:String? = nil) throws { Log.info("Loading config file: \(configFileFullPath)") let decoder = JSONDecoder() let url = URL(fileURLWithPath: configFileFullPath) let data = try Data(contentsOf: url) Configuration.server = try decoder.decode(ServerConfiguration.self, from: data) #if DEBUG if let testConfigFileFullPath = testConfigFileFullPath { let testConfigUrl = URL(fileURLWithPath: testConfigFileFullPath) let testConfigData = try Data(contentsOf: testConfigUrl) Configuration.test = try decoder.decode(TestConfiguration.self, from: testConfigData) } #endif let file = File(deployedGitTagFilename) try file.open(.read, permissions: .readUser) defer { file.close() } let tag = try file.readString() // In case the line in the file had trailing white space (e.g., a new line) self.deployedGitTag = tag.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) } #if DEBUG static func setupLoadTestingCloudStorage() { server.setupLoadTestingCloudStorage() } #endif } <file_sep>// // SpecificDatabaseTests_SharingInvitationRepository.swift // Server // // Created by <NAME> on 4/10/17. // // import XCTest @testable import Server import Foundation import Dispatch import SyncServerShared class SpecificDatabaseTests_SharingInvitationRepository: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testAddingSharingInvitation() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let userId:UserId = 100 let result = SharingInvitationRepository(db).add(owningUserId: userId, sharingGroupUUID: sharingGroupUUID, permission: .read, allowSocialAcceptance: true, numberAcceptors: 2) guard case .success(let uuid) = result else { XCTFail() return } let key = SharingInvitationRepository.LookupKey.sharingInvitationUUID(uuid: uuid) let results = SharingInvitationRepository(db).lookup(key: key, modelInit: SharingInvitation.init) guard case .found(let model) = results else { XCTFail() return } guard let invitation = model as? SharingInvitation else { XCTFail() return } XCTAssert(invitation.owningUserId == userId) XCTAssert(invitation.permission == .read) XCTAssert(invitation.sharingInvitationUUID == uuid) XCTAssert(invitation.numberAcceptors == 2) XCTAssert(invitation.allowSocialAcceptance == true) } func testAttemptToRemoveStaleInvitationsThatAreNotStale() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let userId:UserId = 100 let result = SharingInvitationRepository(db).add(owningUserId: userId, sharingGroupUUID: sharingGroupUUID, permission: .write, allowSocialAcceptance: false, numberAcceptors: 1) guard case .success(let uuid) = result else { XCTFail() return } let exp = expectation(description: "attemptedToRemoveStateInvitation") let timer = DispatchSource.makeTimerSource() timer.setEventHandler() { let key1 = SharingInvitationRepository.LookupKey.staleExpiryDates let removalResult = SharingInvitationRepository(self.db).remove(key: key1) guard case .removed(numberRows:let number) = removalResult else{ XCTFail() exp.fulfill() return } // We didn't remove any rows. XCTAssert(number == 0) let key2 = SharingInvitationRepository.LookupKey.sharingInvitationUUID(uuid: uuid) let results = SharingInvitationRepository(self.db).lookup(key: key2, modelInit: SharingInvitation.init) guard case .found(let model) = results else { XCTFail() return } guard let invitation = model as? SharingInvitation else { XCTFail() return } XCTAssert(invitation.owningUserId == userId) XCTAssert(invitation.permission == .write) XCTAssert(invitation.sharingInvitationUUID == uuid) XCTAssert(invitation.sharingGroupUUID == sharingGroupUUID) XCTAssert(invitation.numberAcceptors == 1) XCTAssert(invitation.allowSocialAcceptance == false) exp.fulfill() } let now = DispatchTime.now() let delayInSeconds:UInt64 = 5 let deadline = DispatchTime(uptimeNanoseconds: now.uptimeNanoseconds + delayInSeconds*UInt64(1e9)) timer.schedule(deadline: deadline) if #available(OSX 10.12, *) { timer.activate() } else { XCTFail() } waitForExpectations(timeout: 20, handler: nil) } func testRemoveStaleSharingInvitations() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let userId:UserId = 100 let result = SharingInvitationRepository(db).add(owningUserId: userId, sharingGroupUUID: sharingGroupUUID, permission: .read, allowSocialAcceptance: false, numberAcceptors: 1, expiryDuration: 2) guard case .success(let uuid) = result else { XCTFail() return } let exp = expectation(description: "removedStateInvitation") let timer = DispatchSource.makeTimerSource() timer.setEventHandler() { let key1 = SharingInvitationRepository.LookupKey.staleExpiryDates let removalResult = SharingInvitationRepository(self.db).remove(key: key1) guard case .removed(numberRows:let number) = removalResult else{ XCTFail() exp.fulfill() return } XCTAssert(number == 1) let key2 = SharingInvitationRepository.LookupKey.sharingInvitationUUID(uuid: uuid) let results = SharingInvitationRepository(self.db).lookup(key: key2, modelInit: SharingInvitation.init) guard case .noObjectFound = results else { XCTFail() return } exp.fulfill() } let now = DispatchTime.now() let delayInSeconds:UInt64 = 5 let deadline = DispatchTime(uptimeNanoseconds: now.uptimeNanoseconds + delayInSeconds*UInt64(1e9)) timer.schedule(deadline: deadline) if #available(OSX 10.12, *) { timer.activate() } else { XCTFail() } waitForExpectations(timeout: 20, handler: nil) } func testDecrementSharingInvitationWithNumberAcceptorsGreaterThan1() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let userId:UserId = 100 let result = SharingInvitationRepository(db).add(owningUserId: userId, sharingGroupUUID: sharingGroupUUID, permission: .read, allowSocialAcceptance: true, numberAcceptors: 2) guard case .success(let uuid) = result else { XCTFail() return } guard SharingInvitationRepository(db).decrementNumberAcceptors(sharingInvitationUUID: uuid) else { XCTFail() return } let key = SharingInvitationRepository.LookupKey.sharingInvitationUUID(uuid: uuid) let results = SharingInvitationRepository(db).lookup(key: key, modelInit: SharingInvitation.init) guard case .found(let model) = results, let invitation = model as? SharingInvitation else { XCTFail() return } XCTAssert(invitation.owningUserId == userId) XCTAssert(invitation.permission == .read) XCTAssert(invitation.sharingInvitationUUID == uuid) XCTAssert(invitation.numberAcceptors == 1) XCTAssert(invitation.allowSocialAcceptance == true) } func testDecrementSharingInvitationWithNumberAcceptorsEqualTo1() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let userId:UserId = 100 let result = SharingInvitationRepository(db).add(owningUserId: userId, sharingGroupUUID: sharingGroupUUID, permission: .read, allowSocialAcceptance: true, numberAcceptors: 1) guard case .success(let uuid) = result else { XCTFail() return } guard !SharingInvitationRepository(db).decrementNumberAcceptors(sharingInvitationUUID: uuid) else { XCTFail() return } let key = SharingInvitationRepository.LookupKey.sharingInvitationUUID(uuid: uuid) let results = SharingInvitationRepository(db).lookup(key: key, modelInit: SharingInvitation.init) guard case .found(let model) = results, let invitation = model as? SharingInvitation else { XCTFail() return } XCTAssert(invitation.owningUserId == userId) XCTAssert(invitation.permission == .read) XCTAssert(invitation.sharingInvitationUUID == uuid) XCTAssert(invitation.numberAcceptors == 1) XCTAssert(invitation.allowSocialAcceptance == true) } } extension SpecificDatabaseTests_SharingInvitationRepository { static var allTests : [(String, (SpecificDatabaseTests_SharingInvitationRepository) -> () throws -> Void)] { return [ ("testAddingSharingInvitation", testAddingSharingInvitation), ("testAttemptToRemoveStaleInvitationsThatAreNotStale", testAttemptToRemoveStaleInvitationsThatAreNotStale), ("testRemoveStaleSharingInvitations", testRemoveStaleSharingInvitations), ("testDecrementSharingInvitationWithNumberAcceptorsGreaterThan1", testDecrementSharingInvitationWithNumberAcceptorsGreaterThan1), ("testDecrementSharingInvitationWithNumberAcceptorsEqualTo1", testDecrementSharingInvitationWithNumberAcceptorsEqualTo1) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SpecificDatabaseTests_SharingInvitationRepository.self) } } <file_sep>#!/bin/bash # Usage: build [verbose] VERBOSE="" if [ "$1empty" == "verboseempty" ]; then VERBOSE="-v" fi swift build $VERBOSE -Xswiftc -DDEBUG -Xswiftc -DSERVER<file_sep>// // AccountDelegateHandler.swift // Server // // Created by <NAME> on 12/7/18. // import Foundation import LoggerAPI class AccountDelegateHandler: AccountDelegate { private let userRepository: UserRepository init(userRepository: UserRepository) { self.userRepository = userRepository } func saveToDatabase(account creds:Account) -> Bool { let result = userRepository.updateCreds(creds: creds, forUser: creds.accountCreationUser!) Log.debug("saveToDatabase: result: \(result)") return result } } <file_sep>import XCTest import Kitura import KituraNet @testable import Server import LoggerAPI import CredentialsMicrosoft import Foundation import SyncServerShared class AccountAuthenticationTests_Microsoft: ServerTestCase, LinuxTestable { let serverResponseTime:TimeInterval = 10 // Need to use this test to get an initial refresh token for the TestCredentials. Put an id token in the TestCredentials for .microsoft1 before this. func testBootstrapRefreshToken() { guard let microsoftCreds = MicrosoftCreds() else { XCTFail() return } guard let test = Configuration.test else { XCTFail() return } let accessToken1 = test.microsoft1.idToken microsoftCreds.accessToken = accessToken1 let exp = expectation(description: "generate") microsoftCreds.generateTokens(response: nil) { error in XCTAssert(error == nil, "\(String(describing: error))") Log.info("Refresh token: \(String(describing: microsoftCreds.refreshToken))") exp.fulfill() } waitExpectation(timeout: 10, handler: nil) } func testRefreshToken() { guard let test = Configuration.test else { XCTFail() return } guard let microsoftCreds = MicrosoftCreds() else { XCTFail() return } microsoftCreds.refreshToken = test.microsoft1.refreshToken let exp = expectation(description: "refresh") microsoftCreds.refresh() { error in XCTAssert(error == nil, "\(String(describing: error))") exp.fulfill() } waitExpectation(timeout: 10, handler: nil) } func testGoodEndpointWithBadCredsFails() { let deviceUUID = Foundation.UUID().uuidString performServerTest(testAccount: .microsoft1) { expectation, creds in let headers = self.setupHeaders(testUser: .microsoft1, accessToken: "foobar", deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkPrimaryCreds, headers: headers) { response, dict in Log.info("Status Code: \(response!.statusCode.rawValue)") XCTAssert(response!.statusCode == .unauthorized, "Did not fail on check creds request: \(response!.statusCode)") expectation.fulfill() } } } // Good Microsoft creds, not creds that are necessarily on the server. func testGoodEndpointWithGoodCredsWorks() { let deviceUUID = Foundation.UUID().uuidString self.performServerTest(testAccount: .microsoft1) { expectation, creds in let headers = self.setupHeaders(testUser: .microsoft1, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkPrimaryCreds, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "Did not work on check creds request") expectation.fulfill() } } } func testBadPathWithGoodCredsFails() { let badRoute = ServerEndpoint("foobar", method: .post, requestMessageType: AddUserRequest.self) let deviceUUID = Foundation.UUID().uuidString performServerTest(testAccount: .microsoft1) { expectation, dbCreds in let headers = self.setupHeaders(testUser: .microsoft1, accessToken: dbCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: badRoute, headers: headers) { response, dict in XCTAssert(response!.statusCode != .OK, "Did not fail on check creds request") expectation.fulfill() } } } func testGoodPathWithBadMethodWithGoodCredsFails() { let badRoute = ServerEndpoint(ServerEndpoints.checkCreds.pathName, method: .post, requestMessageType: CheckCredsRequest.self) XCTAssert(ServerEndpoints.checkCreds.method != .post) let deviceUUID = Foundation.UUID().uuidString self.performServerTest(testAccount: .microsoft1) { expectation, dbCreds in let headers = self.setupHeaders(testUser: .microsoft1, accessToken: dbCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: badRoute, headers: headers) { response, dict in XCTAssert(response!.statusCode != .OK, "Did not fail on check creds request") expectation.fulfill() } } } func testThatMicrosoftUserHasValidCreds() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString addNewUser(testAccount: .microsoft1, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID, cloudFolderName: nil) self.performServerTest(testAccount: .microsoft1) { expectation, dbCreds in let headers = self.setupHeaders(testUser: .microsoft1, accessToken: dbCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkCreds, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "Did not work on check creds request") expectation.fulfill() } } } } extension AccountAuthenticationTests_Microsoft { static var allTests : [(String, (AccountAuthenticationTests_Microsoft) -> () throws -> Void)] { let result:[(String, (AccountAuthenticationTests_Microsoft) -> () throws -> Void)] = [ ("testBootstrapRefreshToken", testBootstrapRefreshToken), ("testRefreshToken", testRefreshToken), ("testGoodEndpointWithBadCredsFails", testGoodEndpointWithBadCredsFails), ("testGoodEndpointWithGoodCredsWorks", testGoodEndpointWithGoodCredsWorks), ("testBadPathWithGoodCredsFails", testBadPathWithGoodCredsFails), ("testGoodPathWithBadMethodWithGoodCredsFails", testGoodPathWithBadMethodWithGoodCredsFails), ("testThatMicrosoftUserHasValidCreds", testThatMicrosoftUserHasValidCreds), ] return result } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:AccountAuthenticationTests_Microsoft.self) } } <file_sep>#!/bin/bash user= host= dbname="SyncServer_SharedImages" result=$(mysql -P 3306 -p --user="$user" --host="$host" --database="$dbname" < 5.sql 2>&1 ) if [ $? = 0 ]; then echo "Success running migration" else echo "**** Failure running migration *******" echo $result fi <file_sep>// // FileController+DoneUploads.swift // Server // // Created by <NAME> on 3/22/17. // // import Foundation import PerfectThread import Dispatch import LoggerAPI import SyncServerShared extension FileController { enum EffectiveOwningUser { case success(UserId) case failure(RequestHandler.FailureResult) } // Returns nil on an error. private func getIndexEntries(forUploadFiles uploadFiles:[Upload], params:RequestProcessingParameters) -> [FileInfo]? { var primaryFileIndexKeys = [FileIndexRepository.LookupKey]() for uploadFile in uploadFiles { // 12/1/17; Up until today, I was using the params.currentSignedInUser!.userId in here and not the effective user id. Thus, when sharing users did an upload deletion, the files got deleted from the file index, but didn't get deleted from cloud storage. // 6/24/18; Now things have changed again: With the change to having multiple owning users in a sharing group, a sharingGroup id is the key instead of the userId. primaryFileIndexKeys += [.primaryKeys(sharingGroupUUID: uploadFile.sharingGroupUUID, fileUUID: uploadFile.fileUUID)] } var fileIndexObjs = [FileInfo]() if primaryFileIndexKeys.count > 0 { let fileIndexResult = params.repos.fileIndex.fileIndex(forKeys: primaryFileIndexKeys) switch fileIndexResult { case .fileIndex(let fileIndex): fileIndexObjs = fileIndex case .error(let error): Log.error("Failed to get fileIndex: \(error)") return nil } } return fileIndexObjs } enum DoInitialDoneUploadResponse { case success(numberTransferred:Int32, uploadDeletions:[FileInfo]?, staleVersionsToDelete:[FileInfo]?) case doCompletion(RequestProcessingParameters.Response) } // staleVersionsToDelete gives info, if any, on files that we're uploading new versions of. private func doInitialDoneUploads(params:RequestProcessingParameters, doneUploadsRequest: DoneUploadsRequest) -> DoInitialDoneUploadResponse { #if DEBUG if doneUploadsRequest.testLockSync != nil { Log.info("Starting sleep (testLockSync= \(String(describing: doneUploadsRequest.testLockSync))).") Thread.sleep(forTimeInterval: TimeInterval(doneUploadsRequest.testLockSync!)) Log.info("Finished sleep (testLockSync= \(String(describing: doneUploadsRequest.testLockSync))).") } #endif if let response = Controllers.updateMasterVersion(sharingGroupUUID: doneUploadsRequest.sharingGroupUUID, masterVersion: doneUploadsRequest.masterVersion, params: params, responseType: DoneUploadsResponse.self) { return .doCompletion(response) } // Now, start the heavy lifting. This has to accomodate both file uploads, and upload deletions-- because these both need to alter the masterVersion (i.e., they change the file index). // 1) See if any of the file uploads are for file versions > 0. Later, we'll have to delete stale versions of the file(s) in cloud storage if so. // 2) Get the upload deletions, if any. var staleVersionsFromUploads:[Upload] var uploadDeletions:[Upload] // Get uploads for the current signed in user -- uploads are identified by userId, not effectiveOwningUserId, because we want to organize uploads by specific user. let fileUploadsResult = params.repos.upload.uploadedFiles(forUserId: params.currentSignedInUser!.userId, sharingGroupUUID: doneUploadsRequest.sharingGroupUUID, deviceUUID: params.deviceUUID!) switch fileUploadsResult { case .uploads(let uploads): Log.debug("Number of file uploads and upload deletions: \(uploads.count)") // 1) Filter out uploaded files with versions > 0 -- for the stale file versions. Note that we're not including files with status `uploadedUndelete`-- we don't need to delete any stale versions for these. staleVersionsFromUploads = uploads.filter({ // The left to right order of these checks is important-- check the state first. If the state is uploadingAppMetaData, there will be a nil fileVersion and don't want to check that. $0.state == .uploadedFile && $0.fileVersion > 0 }) // 2) Filter out upload deletions uploadDeletions = uploads.filter({$0.state == .toDeleteFromFileIndex}) case .error(let error): let message = "Failed to get file uploads: \(String(describing: error))" Log.error(message) return .doCompletion(.failure(.message(message))) } // Now, map the upload objects found to the file index. What we need here are not just the entries from the `Upload` table-- we need the corresponding entries from FileIndex since those have the deviceUUID's that we need in order to correctly name the files in cloud storage. guard let staleVersionsToDelete = getIndexEntries(forUploadFiles: staleVersionsFromUploads, params:params) else { let message = "Failed to getIndexEntries for staleVersionsFromUploads: \(String(describing: staleVersionsFromUploads))" Log.error(message) return .doCompletion(.failure(.message(message))) } guard let fileIndexDeletions = getIndexEntries(forUploadFiles: uploadDeletions, params:params) else { let message = "Failed to getIndexEntries for uploadDeletions: \(String(describing: uploadDeletions))" Log.error(message) return .doCompletion(.failure(.message(message))) } // Deferring computation of `effectiveOwningUserId` because: (a) don't always need it in the `transferUploads` below, and (b) it will cause unecessary failures in some cases where a sharing owner user has been removed. effectiveOwningUserId is only needed when v0 of a file is being uploaded. var effectiveOwningUserId: UserId? func getEffectiveOwningUserId() -> EffectiveOwningUser { if let effectiveOwningUserId = effectiveOwningUserId { return .success(effectiveOwningUserId) } let geouiResult = Controllers.getEffectiveOwningUserId(user: params.currentSignedInUser!, sharingGroupUUID: doneUploadsRequest.sharingGroupUUID, sharingGroupUserRepo: params.repos.sharingGroupUser) switch geouiResult { case .found(let userId): effectiveOwningUserId = userId return .success(userId) case .noObjectFound, .gone: let message = "No effectiveOwningUserId: \(geouiResult)" Log.debug(message) return .failure(.goneWithReason(message: message, .userRemoved)) case .error: let message = "Failed to getEffectiveOwningUserId" Log.error(message) return .failure(.message(message)) } } // 3) Transfer info to the FileIndex repository from Upload. let numberTransferredResult = params.repos.fileIndex.transferUploads(uploadUserId: params.currentSignedInUser!.userId, owningUserId: getEffectiveOwningUserId, sharingGroupUUID: doneUploadsRequest.sharingGroupUUID, uploadingDeviceUUID: params.deviceUUID!, uploadRepo: params.repos.upload) var numberTransferred: Int32! switch numberTransferredResult { case .success(numberUploadsTransferred: let num): numberTransferred = num case .failure(let failureResult): let message = "Failed on transfer to FileIndex!" Log.error(message) return .doCompletion(.failure(failureResult)) } // 4) Remove the corresponding records from the Upload repo-- this is specific to the userId and the deviceUUID. let filesForUserDevice = UploadRepository.LookupKey.filesForUserDevice(userId: params.currentSignedInUser!.userId, deviceUUID: params.deviceUUID!, sharingGroupUUID: doneUploadsRequest.sharingGroupUUID) // 5/28/17; I just got an error on this: // [ERR] Number rows removed from Upload was 10 but should have been Optional(9)! // How could this happen? // 9/23/18; It could have been a race condition across test cases with the same device UUID and user. I'm now adding in a sharing group UUID qualifier, so I wonder if this will solve that problem too? let removalResult = params.repos.upload.retry { return params.repos.upload.remove(key: filesForUserDevice) } switch removalResult { case .removed(let numberRows): if numberRows != numberTransferred { let message = "Number rows removed from Upload was \(numberRows) but should have been \(String(describing: numberTransferred))!" Log.error(message) return .doCompletion(.failure(.message(message))) } case .deadlock: let message = "Failed removing rows from Upload: deadlock!" Log.error(message) return .doCompletion(.failure(.message(message))) case .waitTimeout: let message = "Failed removing rows from Upload: wait timeout!" Log.error(message) return .doCompletion(.failure(.message(message))) case .error(_): let message = "Failed removing rows from Upload!" Log.error(message) return .doCompletion(.failure(.message(message))) } // See if we have to do a sharing group update operation. if let sharingGroupName = doneUploadsRequest.sharingGroupName { let serverSharingGroup = Server.SharingGroup() serverSharingGroup.sharingGroupUUID = doneUploadsRequest.sharingGroupUUID serverSharingGroup.sharingGroupName = sharingGroupName if !params.repos.sharingGroup.update(sharingGroup: serverSharingGroup) { let message = "Failed in updating sharing group." Log.error(message) return .doCompletion(.failure(.message(message))) } } return .success(numberTransferred:numberTransferred!, uploadDeletions:fileIndexDeletions, staleVersionsToDelete:staleVersionsToDelete) } func doneUploads(params:RequestProcessingParameters) { guard let doneUploadsRequest = params.request as? DoneUploadsRequest else { let message = "Did not receive DoneUploadsRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard sharingGroupSecurityCheck(sharingGroupUUID: doneUploadsRequest.sharingGroupUUID, params: params) else { let message = "Failed in sharing group security check." Log.error(message) params.completion(.failure(.message(message))) return } let result = doInitialDoneUploads(params: params, doneUploadsRequest: doneUploadsRequest) guard case .success(let numberTransferred, let uploadDeletions, let staleVersionsToDelete) = result else { Log.debug("Success on doInitialDoneUploads: \(result)") switch result { case .doCompletion(let response): params.completion(response) case .success: assert(false) } return } // Next: If there are any upload deletions, we need to actually do the file deletions. We are doing this *without* the lock held. I'm assuming it takes far longer to contact the cloud storage service than the other operations we are doing (e.g., mySQL operations). var cloudDeletions = [FileInfo]() if let uploadDeletions = uploadDeletions { cloudDeletions += uploadDeletions } if let staleVersionsToDelete = staleVersionsToDelete { cloudDeletions += staleVersionsToDelete } if cloudDeletions.count == 0 { func successResponse() { let response = DoneUploadsResponse() response.numberUploadsTransferred = numberTransferred Log.debug("no upload deletions or stale file versions: doneUploads.numberUploadsTransferred: \(numberTransferred)") params.completion(.success(response)) } if let pushNotificationMessage = doneUploadsRequest.pushNotificationMessage { sendNotifications(fromUser: params.currentSignedInUser!, forSharingGroupUUID: doneUploadsRequest.sharingGroupUUID, message: pushNotificationMessage, params: params) { success in if success { successResponse() } else { let message = "Failed on sendNotifications with no cloud deletions." Log.debug(message) params.completion(.failure(.message(message))) } } } else { successResponse() } return } // Do deletions let async = AsyncTailRecursion() async.start { self.finishDoneUploads(cloudDeletions: cloudDeletions, params: params, numberTransferred: Int(numberTransferred), pushNotificationMessage: doneUploadsRequest.pushNotificationMessage, sharingGroupUUID: doneUploadsRequest.sharingGroupUUID, async:async) } } private func finishDoneUploads(cloudDeletions:[FileInfo], params:RequestProcessingParameters, numberTransferred: Int, pushNotificationMessage: String?, sharingGroupUUID: String, async:AsyncTailRecursion, numberErrorsDeletingFiles:Int32 = 0) { // Base case. if cloudDeletions.count == 0 { func successResponse() { let response = DoneUploadsResponse() if numberErrorsDeletingFiles > 0 { response.numberDeletionErrors = numberErrorsDeletingFiles Log.debug("doneUploads.numberDeletionErrors: \(numberErrorsDeletingFiles)") } response.numberUploadsTransferred = Int32(numberTransferred) Log.debug("base case: doneUploads.numberUploadsTransferred: \(numberTransferred)") params.completion(.success(response)) } if pushNotificationMessage == nil { successResponse() async.done() } else { sendNotifications(fromUser: params.currentSignedInUser!, forSharingGroupUUID: sharingGroupUUID, message: pushNotificationMessage!, params: params) { success in if success { successResponse() } else { let message = "Failed on sendNotifications in finishDoneUploads" Log.error(message) params.completion(.failure(.message(message))) } async.done() } } return } // Recursive case. let cloudDeletion = cloudDeletions[0] let cloudFileName = cloudDeletion.cloudFileName(deviceUUID: cloudDeletion.deviceUUID!, mimeType: cloudDeletion.mimeType!) Log.info("Deleting file: \(cloudFileName)") // OWNER guard let owningUserCreds = FileController.getCreds(forUserId: cloudDeletion.owningUserId, from: params.db, delegate: params.accountDelegate) else { let message = "Could not obtain owning users creds" Log.error(message) params.completion(.failure(.message(message))) return } guard let cloudStorageCreds = owningUserCreds.cloudStorage else { let message = "Could not obtain cloud storage creds." Log.error(message) params.completion(.failure(.message(message))) return } let options = CloudStorageFileNameOptions(cloudFolderName: owningUserCreds.cloudFolderName, mimeType: cloudDeletion.mimeType!) cloudStorageCreds.deleteFile(cloudFileName: cloudFileName, options: options) { result in let tail = (cloudDeletions.count > 0) ? Array(cloudDeletions[1..<cloudDeletions.count]) : [] var numberAdditionalErrors:Int32 = 0 switch result { case .success: break case .accessTokenRevokedOrExpired: // Handling this the same way as [1] below. Log.warning("Error occurred while deleting file: Access token revoked or expired") numberAdditionalErrors = 1 case .failure(let error): // [1]. We could get into some odd situations here if we actually report an error by failing. Failing will cause a db transaction rollback. Which could mean we had some files deleted, but *all* of the entries would still be present in the FileIndex/Uploads directory. So, I'm not going to fail, but forge on. I'll report the errors in the DoneUploadsResponse message though. // TODO: *1* A better way to deal with this situation could be to use transactions at a finer grained level. Each deletion we do from Upload and FileIndex for an UploadDeletion could be in a transaction that we don't commit until the deletion succeeds with cloud storage. Log.warning("Error occurred while deleting file: \(error)") numberAdditionalErrors = 1 } async.next() { self.finishDoneUploads(cloudDeletions: tail, params: params, numberTransferred: numberTransferred, pushNotificationMessage: pushNotificationMessage, sharingGroupUUID: sharingGroupUUID, async:async, numberErrorsDeletingFiles: numberErrorsDeletingFiles + numberAdditionalErrors) } } } // Returns true iff success. private func sendNotifications(fromUser: User, forSharingGroupUUID sharingGroupUUID: String, message: String, params:RequestProcessingParameters, completion: @escaping (_ success: Bool)->()) { guard var users:[User] = params.repos.sharingGroupUser.sharingGroupUsers(forSharingGroupUUID: sharingGroupUUID) else { Log.error(("sendNotifications: Failed to get sharing group users!")) completion(false) return } // Remove sending user from users. They already know they uploaded/deleted-- no point in sending them a notification. // Also remove any users that don't have topics-- i.e., they don't have any devices registered for push notifications. users = users.filter { user in user.userId != fromUser.userId && user.pushNotificationTopic != nil } let key = SharingGroupRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let sharingGroupResult = params.repos.sharingGroup.lookup(key: key, modelInit: SharingGroup.init) var sharingGroup: SharingGroup! switch sharingGroupResult { case .found(let model): sharingGroup = (model as! SharingGroup) case .error(let error): Log.error("sendNotifications: \(error)") completion(false) return case .noObjectFound: Log.error("sendNotifications: No object found!") completion(false) return } var modifiedMessage = "\(fromUser.username!)" if let name = sharingGroup.sharingGroupName { modifiedMessage += ", \(name)" } modifiedMessage += ": " + message guard let formattedMessage = PushNotifications.format(message: modifiedMessage) else { Log.error("sendNotifications: Failed on formatting message.") completion(false) return } guard let pn = PushNotifications() else { Log.error("sendNotifications: Failed on PushNotifications constructor.") completion(false) return } pn.send(formattedMessage: formattedMessage, toUsers: users, completion: completion) } } <file_sep>// // AccountManager.swift // Server // // Created by <NAME> on 7/9/17. // import Foundation import Credentials import Kitura import SyncServerShared import LoggerAPI class AccountManager { static let session = AccountManager() private var accountTypes = [Account.Type]() var numberAccountTypes: Int { return accountTypes.count } // Number of account types that can own. var numberOfOwningAccountTypes:Int { var number = 0 for accountType in accountTypes { if accountType.accountScheme.userType == .owning { number += 1 } } return number } private init() { } func reset() { accountTypes.removeAll() } // I'm allowing these to be added dynamically to enable the user of the server to disallow certain types of account credentials. func addAccountType(_ newAccountType:Account.Type) { for accountType in accountTypes { // Don't add the same account type twice! if newAccountType == accountType { assert(false) } } Log.info("Added account type to system: \(newAccountType)") accountTypes.append(newAccountType) } enum UpdateUserProfileError : Error { case noAccountWithThisToken case noTokenFoundInHeaders } // Account specific properties obtained from a request. struct AccountProperties { let accountScheme: AccountScheme let properties: [String: Any] } // Allow the specific Account's to process headers in their own special way, and get values from the request. // 7/14/19; Previously, I was using the UserProfile (from Kitura Credentials) to bridge these properties. However, that ran into crashes during load testing. See https://forums.swift.org/t/kitura-perfect-mysql-server-crash-double-free-or-corruption-prev/26740/10 // So, I changed to using a thread-safe mechanism (AccountProperties). func getProperties(fromRequest request:RouterRequest) throws -> AccountProperties { guard let tokenTypeString = request.headers[ServerConstants.XTokenTypeKey] else { throw UpdateUserProfileError.noTokenFoundInHeaders } for accountType in accountTypes { if tokenTypeString == accountType.accountScheme.authTokenType { return AccountProperties(accountScheme: accountType.accountScheme, properties: accountType.getProperties(fromRequest: request)) } } throw UpdateUserProfileError.noAccountWithThisToken } func accountFromProperties(properties: AccountProperties, user:AccountCreationUser?, delegate:AccountDelegate?) -> Account? { let currentAccountScheme = properties.accountScheme for accountType in accountTypes { if accountType.accountScheme == currentAccountScheme { return accountType.fromProperties(properties, user: user, delegate: delegate) } } return nil } func accountFromJSON(_ json:String, accountName name: AccountScheme.AccountName, user:AccountCreationUser, delegate:AccountDelegate?) throws -> Account? { for accountType in accountTypes { if accountType.accountScheme.accountName == name { return try accountType.fromJSON(json, user: user, delegate: delegate) } } Log.error("Could not find accountName: \(name)") return nil } } <file_sep>#!/bin/bash # Usage: buildlatest.sh # For local server testing. Assumes that you have built a binary. Builds the docker image for that binary. Doesn't push to docker hub. # docker hub username USERNAME=crspybits # image name IMAGE=syncserver-runner # build the runtime image docker build -t $USERNAME/$IMAGE:latest . <file_sep>// // FileController_DoneUploadsTests.swift // Server // // Created by <NAME> on 3/23/17. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class FileController_DoneUploadsTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testDoneUploadsWithNoUploads() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 0, sharingGroupUUID: sharingGroupUUID) } func testDoneUploadsWithSingleUpload() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) } func testDoneUploadsWithTwoUploads() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } Log.info("Done uploadTextFile") guard let _ = uploadJPEGFile(deviceUUID:deviceUUID, addUser:.no(sharingGroupUUID: sharingGroupUUID)) else { XCTFail() return } Log.info("Done uploadJPEGFile") self.sendDoneUploads(expectedNumberOfUploads: 2, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) Log.info("Done sendDoneUploads") } func testDoneUploadsThatUpdatesFileVersion() { let deviceUUID = Foundation.UUID().uuidString let fileUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, fileUUID: fileUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) guard let _ = uploadTextFile(deviceUUID:deviceUUID, fileUUID:fileUUID, addUser:.no(sharingGroupUUID: sharingGroupUUID), fileVersion:1, masterVersion: 1) else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: 1, sharingGroupUUID: sharingGroupUUID) } func testDoneUploadsTwiceDoesNothingSecondTime() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) self.sendDoneUploads(expectedNumberOfUploads: 0, masterVersion: 1, sharingGroupUUID: sharingGroupUUID) } // If you first upload a file (followed by a DoneUploads), then delete it, and then upload again the last upload fails. func testThatUploadAfterUploadDeletionFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) var masterVersion:MasterVersionInt = uploadResult1.request.masterVersion + MasterVersionInt(1) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult1.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult1.request.fileVersion uploadDeletionRequest.masterVersion = masterVersion uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false) self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 // Try upload again. This should fail. uploadTextFile(deviceUUID:deviceUUID, fileUUID: uploadResult1.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion: 1, masterVersion: masterVersion, errorExpected: true) } func testDoneUploadsWithFakeSharingGroupUUIDFails() { let deviceUUID = Foundation.UUID().uuidString guard let _ = uploadTextFile(deviceUUID:deviceUUID) else { XCTFail() return } let invalidSharingGroupUUID = UUID().uuidString self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: invalidSharingGroupUUID, failureExpected: true) } func testDoneUploadsWithBadSharingGroupUUIDFails() { let deviceUUID = Foundation.UUID().uuidString guard let _ = uploadTextFile(deviceUUID:deviceUUID) else { XCTFail() return } let workingButBadSharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: workingButBadSharingGroupUUID) else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: workingButBadSharingGroupUUID, failureExpected: true) } func testDoneUploadsWithChangeOfSharingGroupNameWorks() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } guard let (_, sharingGroups1) = getIndex() else { XCTFail() return } let filter1 = sharingGroups1.filter {$0.sharingGroupUUID == sharingGroupUUID} guard filter1.count == 1 else { XCTFail() return } let sharingGroupName = UUID().uuidString self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, sharingGroupName: sharingGroupName) guard let (_, sharingGroups2) = getIndex() else { XCTFail() return } let filter2 = sharingGroups2.filter {$0.sharingGroupUUID == sharingGroupUUID} guard filter2.count == 1 else { XCTFail() return } XCTAssert(filter2[0].sharingGroupName == sharingGroupName) } } extension FileController_DoneUploadsTests { static var allTests : [(String, (FileController_DoneUploadsTests) -> () throws -> Void)] { return [ ("testDoneUploadsWithNoUploads", testDoneUploadsWithNoUploads), ("testDoneUploadsWithSingleUpload", testDoneUploadsWithSingleUpload), ("testDoneUploadsWithTwoUploads", testDoneUploadsWithTwoUploads), ("testDoneUploadsThatUpdatesFileVersion", testDoneUploadsThatUpdatesFileVersion), ("testDoneUploadsTwiceDoesNothingSecondTime", testDoneUploadsTwiceDoesNothingSecondTime), ("testThatUploadAfterUploadDeletionFails", testThatUploadAfterUploadDeletionFails), ("testDoneUploadsWithBadSharingGroupUUIDFails", testDoneUploadsWithBadSharingGroupUUIDFails), ("testDoneUploadsWithFakeSharingGroupUUIDFails", testDoneUploadsWithFakeSharingGroupUUIDFails), ("testDoneUploadsWithChangeOfSharingGroupNameWorks", testDoneUploadsWithChangeOfSharingGroupNameWorks) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:FileController_DoneUploadsTests.self) } } <file_sep>// // Database+Setup.swift // Server // // Created by <NAME> on 6/26/18. // import Foundation extension Database { typealias Repo = Repository & RepositoryBasics static let repoTypes:[Repo.Type] = [ SharingGroupRepository.self, UserRepository.self, DeviceUUIDRepository.self, UploadRepository.self, FileIndexRepository.self, SharingInvitationRepository.self, SharingGroupUserRepository.self, MasterVersionRepository.self ] static func setup() -> Bool { let db = Database(showStartupInfo: true) // The ordering of these table creations is important because of foreign key constraints. for repoType in repoTypes { let repo = repoType.init(db) if case .failure(_) = repo.upcreate() { return false } } return true } #if DEBUG static func remove() { // Reversing the order on removal to deal with foreign key constraints. let reversedRepoTypes = repoTypes.reversed() let db = Database(showStartupInfo: false) for repoType in reversedRepoTypes { let repo = repoType.init(db) _ = repo.remove() } } #endif } <file_sep>// // main.swift // import Server ServerMain.startup() <file_sep>// // AppleSignInCreds+Refresh.swift // Server // // Created by <NAME> on 10/4/19. // import Foundation import HeliumLogger import LoggerAPI import KituraNet extension AppleSignInCreds { struct GenerateRefreshTokenResult: Decodable { // The purpose of this, for Apple, is undefined. let access_token: String let refresh_token: String let expires_in: Date let id_token: String let token_type: String } struct RefreshIdTokenResult: Decodable { let access_token: String let token_type: String let expires_in: Date } // https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens /// This can only be called once for a serverAuthCode. func generateRefreshToken(serverAuthCode: String, completion: @escaping (Swift.Error?) -> ()) { // https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data // For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be: // MyVariableOne=ValueOne&MyVariableTwo=ValueTwo /* client_id string (Required) (Authorization and Validation) The application identifier for your app. Content-Type: text/plain client_secret string (Required) (Authorization and Validation) A secret generated as a JSON Web Token that uses the secret key generated by the WWDR portal. Content-Type: text/plain code string (Authorization) The authorization code received from your application’s user agent. The code is single use only and valid for five minutes. Content-Type: text/plain grant_type string (Required) (Authorization and Validation) The grant type that determines how the client interacts with the server. For authorization code validation, use authorization_code. For refresh token validation requests, use refresh_token. Content-Type: text/plain refresh_token string (Validation) The refresh token received during the authorization request. Content-Type: text/plain redirect_uri string (Authorization) The destination URI the code was originally sent to. Content-Type: text/plain */ guard let clientSecret = createClientSecret() else { completion(AppleSignInCredsError.failedCreatingClientSecret) return } // What to use for the redirect_uri? // Looks like I have to create a Service ID, which I've been avoiding until now. // "You will have to use the value you passed to the "Return URL" field ... on the same Service ID." // See https://auth0.com/blog/what-is-sign-in-with-apple-a-new-identity-provider/ // And https://developer.apple.com/account/resources/identifiers/list/serviceId // When I was creatting the Service Id, I got the message "An App ID with Identifier '' is not available. Please enter a different string" // The problem was that I was making a test app, and used "test" as part of the bundle Id (see also https://stackoverflow.com/questions/20565565/an-app-id-with-identifier-is-not-available-please-enter-a-different-string) // Hmmm. It seems that this can not be the same as the app id for the iOS app that is using the server. let redirectURI = config.redirectURI let bodyParameters = "client_id=\(config.clientId)" + "&" + "client_secret=\(clientSecret)" + "&" + "code=\(serverAuthCode)" + "&" + "grant_type=authorization_code" + "&" + "redirect_uri=\(redirectURI)" Log.debug("bodyParameters: \(bodyParameters)") let additionalHeaders = ["Content-Type": "application/x-www-form-urlencoded"] apiCall(method: "POST", path: "/auth/token", additionalHeaders:additionalHeaders, body: .string(bodyParameters), expectedSuccessBody: .data) {[weak self] apiResult, statusCode, responseHeaders in guard let self = self else { completion(GenerateTokensError.couldNotGetSelf) return } guard statusCode == HTTPStatusCode.OK else { completion(GenerateTokensError.badStatusCode(statusCode)) return } guard apiResult != nil else { completion(GenerateTokensError.nilAPIResult) return } guard case .data(let data) = apiResult else { completion(GenerateTokensError.noDataInAPIResult) return } let decoder = JSONDecoder() let tokenResult: GenerateRefreshTokenResult do { tokenResult = try decoder.decode(GenerateRefreshTokenResult.self, from: data) } catch let error { Log.error("\(error)") completion(GenerateTokensError.couldNotDecodeResult) return } self.accessToken = tokenResult.id_token self.refreshToken = tokenResult.refresh_token Log.debug("Obtained tokens: idToken: \(String(describing: self.accessToken))\n refreshToken: \(String(describing: self.refreshToken))") guard let delegate = self.delegate else { Log.warning("No delegate!") completion(nil) return } guard delegate.saveToDatabase(account: self) else { completion(GenerateTokensError.errorSavingCredsToDatabase) return } completion(nil) } } /// Validate the given refresh token. This does *not* generate a new id token-- the API returns an updated *access token*, which Apple doesn't define a use for (and we don't save). /// On success, updates the lastRefreshTokenValidation. func validateRefreshToken(refreshToken: String, completion: @escaping (Swift.Error?) -> ()) { self.refreshToken = refreshToken guard let clientSecret = createClientSecret() else { completion(AppleSignInCredsError.failedCreatingClientSecret) return } let bodyParameters = "client_id=\(config.clientId)" + "&" + "client_secret=\(clientSecret)" + "&" + "refresh_token=\(refreshToken)" + "&" + "grant_type=refresh_token" Log.debug("bodyParameters: \(bodyParameters)") let additionalHeaders = ["Content-Type": "application/x-www-form-urlencoded"] apiCall(method: "POST", path: "/auth/token", additionalHeaders:additionalHeaders, body: .string(bodyParameters), expectedSuccessBody: .data) {[weak self] apiResult, statusCode, responseHeaders in guard let self = self else { completion(GenerateTokensError.couldNotGetSelf) return } guard statusCode == HTTPStatusCode.OK else { completion(GenerateTokensError.badStatusCode(statusCode)) return } guard apiResult != nil else { completion(GenerateTokensError.nilAPIResult) return } guard case .data(let data) = apiResult else { completion(GenerateTokensError.noDataInAPIResult) return } let decoder = JSONDecoder() do { _ = try decoder.decode(RefreshIdTokenResult.self, from: data) } catch let error { Log.error("\(error)") completion(GenerateTokensError.couldNotDecodeResult) return } self.lastRefreshTokenValidation = Date() guard let delegate = self.delegate else { Log.warning("No delegate!") completion(nil) return } guard delegate.saveToDatabase(account: self) else { completion(GenerateTokensError.errorSavingCredsToDatabase) return } completion(nil) } } } <file_sep>// // Database.swift // Authentication // // Created by <NAME> on 11/26/16. // // import LoggerAPI import Foundation import PerfectMySQL // See https://github.com/PerfectlySoft/Perfect-MySQL for assumptions about mySQL installation. // For mySQL interface docs, see: http://perfect.org/docs/MySQL.html class Database { // See http://stackoverflow.com/questions/13397038/uuid-max-character-length static let uuidLength = 36 static let maxSharingGroupNameLength = 255 static let maxMimeTypeLength = 100 // E.g.,[ERR] Could not insert into ShortLocks: Failure: 1062 Duplicate entry '1' for key 'userId' static let duplicateEntryForKey = UInt32(1062) // Failure: 1213 Deadlock found when trying to get lock; try restarting transaction static let deadlockError = UInt32(1213) // Failure: 1205 Lock wait timeout exceeded; try restarting transaction static let lockWaitTimeout = UInt32(1205) private var closed = false fileprivate var connection: MySQL! var error: String { return "Failure: \(self.connection.errorCode()) \(self.connection.errorMessage())" } init(showStartupInfo:Bool = false) { self.connection = MySQL() if showStartupInfo { Log.info("Connecting to database with host: \(Configuration.server.db.host)...") } guard self.connection.connect(host: Configuration.server.db.host, user: Configuration.server.db.user, password: Configuration.server.db.password ) else { Log.error("Failure connecting to mySQL server \(Configuration.server.db.host): \(self.error)") return } ServerStatsKeeper.session.increment(stat: .dbConnectionsOpened) if showStartupInfo { Log.info("Connecting to database named: \(Configuration.server.db.database)...") } Log.info("DB CONNECTION STATS: opened: \(ServerStatsKeeper.session.currentValue(stat: .dbConnectionsOpened)); closed: \(ServerStatsKeeper.session.currentValue(stat: .dbConnectionsClosed))") guard self.connection.selectDatabase(named: Configuration.server.db.database) else { Log.error("Failure: \(self.error)") return } } func query(statement: String) -> Bool { DBLog.query(statement) return connection.query(statement: statement) } func numberAffectedRows() -> Int64 { return connection.numberAffectedRows() } func lastInsertId() -> Int64 { return connection.lastInsertId() } func errorCode() -> UInt32 { return connection.errorCode() } func errorMessage() -> String { return connection.errorMessage() } deinit { close() } // Do not close the database connection until rollback or commit have been called. func close() { if !closed { ServerStatsKeeper.session.increment(stat: .dbConnectionsClosed) Log.info("CLOSING DB CONNECTION: opened: \(ServerStatsKeeper.session.currentValue(stat: .dbConnectionsOpened)); closed: \(ServerStatsKeeper.session.currentValue(stat: .dbConnectionsClosed))") connection = nil closed = true } } enum TableUpcreateSuccess { case created case updated case alreadyPresent } enum TableUpcreateError : Error { case query case tableCreation case columnCreation case columnRemoval } enum TableUpcreateResult { case success(TableUpcreateSuccess) case failure(TableUpcreateError) } // columnCreateQuery is the table creation query without the prefix "CREATE TABLE <TableName>" func createTableIfNeeded(tableName:String, columnCreateQuery:String) -> TableUpcreateResult { let checkForTable = "SELECT * " + "FROM information_schema.tables " + "WHERE table_schema = '\(Configuration.server.db.database)' " + "AND table_name = '\(tableName)' " + "LIMIT 1;" guard query(statement: checkForTable) else { Log.error("Failure: \(self.error)") return .failure(.query) } if let results = connection.storeResults(), results.numRows() == 1 { Log.info("Table \(tableName) was already in database") return .success(.alreadyPresent) } Log.info("**** Table \(tableName) was not already in database") let createTable = "CREATE TABLE \(tableName) \(columnCreateQuery) ENGINE=InnoDB;" guard query(statement: createTable) else { Log.error("Failure: \(self.error)") return .failure(.tableCreation) } return .success(.created) } // Returns nil on error. func columnExists(_ column:String, in tableName:String) -> Bool? { let checkForColumn = "SELECT * " + "FROM information_schema.columns " + "WHERE table_schema = '\(Configuration.server.db.database)' " + "AND table_name = '\(tableName)' " + "AND column_name = '\(column)' " + "LIMIT 1;" guard query(statement: checkForColumn) else { Log.error("Failure: \(self.error)") return nil } if let results = connection.storeResults(), results.numRows() == 1 { Log.info("Column \(column) was already in database table \(tableName)") return true } Log.info("Column \(column) was not in database table \(tableName)") return false } // column should be something like "newStrCol VARCHAR(255)" func addColumn(_ column:String, to tableName:String) -> Bool { let alterTable = "ALTER TABLE \(tableName) ADD \(column)" guard query(statement: alterTable) else { Log.error("Failure: \(self.error)") return false } return true } func removeColumn(_ columnName:String, from tableName:String) -> Bool { let alterTable = "ALTER TABLE \(tableName) DROP \(columnName)" guard query(statement: alterTable) else { Log.error("Failure: \(self.error)") return false } return true } /* References on mySQL transactions, locks, and blocking http://www.informit.com/articles/article.aspx?p=2036581&seqNum=12 https://dev.mysql.com/doc/refman/5.5/en/innodb-information-schema-understanding-innodb-locking.html The default isolation level for InnoDB is REPEATABLE READ See https://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html#isolevel_repeatable-read */ func startTransaction() -> Bool { let start = "START TRANSACTION;" if query(statement: start) { return true } else { Log.error("Could not start transaction: \(self.error)") return false } } func commit() -> Bool { let commit = "COMMIT;" if query(statement: commit) { return true } else { Log.error("Could not commit transaction: \(self.error)") return false } } func rollback() -> Bool { let rollback = "ROLLBACK;" if query(statement: rollback) { return true } else { Log.error("Could not rollback transaction: \(self.error)") return false } } } private struct DBLog { static func query(_ query: String) { // Log.debug("DB QUERY: \(query)") } } class Select { private var stmt:MySQLStmt! private var fieldNames:[Int: String]! private var fieldTypes:[Int: String]! private var modelInit:(() -> Model)? private var ignoreErrors:Bool! // Pass a mySQL select statement; the modelInit will be used to create the object type that will be returned in forEachRow // ignoreErrors, if true, will ignore type conversion errors and missing fields in your model. ignoreErrors is only used with `forEachRow`. init?(db:Database, query:String, modelInit:(() -> Model)? = nil, ignoreErrors:Bool = true) { self.modelInit = modelInit self.stmt = MySQLStmt(db.connection) self.ignoreErrors = ignoreErrors DBLog.query(query) if !self.stmt.prepare(statement: query) { Log.error("Failed on preparing statement: \(query)") return nil } if !self.stmt.execute() { Log.error("Failed on executing statement: \(query)") return nil } self.fieldTypes = [Int: String]() for index in 0 ..< Int(stmt.fieldCount()) { let currField:MySQLStmt.FieldInfo = stmt.fieldInfo(index: index)! self.fieldTypes[index] = String(describing: currField.type) } self.fieldNames = self.stmt.fieldNames() if self.fieldNames == nil { Log.error("Failed on stmt.fieldNames: \(query)") return nil } } enum ProcessResultRowsError : Error { case failedRowIterator case unknownFieldType case failedSettingFieldValueInModel(String) case problemConvertingFieldValueToModel(String) } private(set) var forEachRowStatus: ProcessResultRowsError? typealias FieldName = String func numberResultRows() -> Int { return self.stmt.results().numRows } // Check forEachRowStatus after you have finished this -- it will indicate the error, if any. // TODO: *3* The callback could return a boolean, which indicates whether to continue iterating. This would be useful to enable the iteration to stop, e.g., on an error condition. func forEachRow(callback:@escaping (_ row: Model?) ->()) { let results = self.stmt.results() var failure = false let returnCode = results.forEachRow { row in if failure { return } guard let rowModel = self.modelInit?() else { failure = true return } for fieldNumber in 0 ..< results.numFields { guard let fieldName = self.fieldNames[fieldNumber] else { Log.error("Failed on getting field name for field number: \(fieldNumber)") failure = true return } guard fieldNumber < row.count else { Log.error("Field number exceeds row.count: \(fieldNumber)") failure = true return } // If this particular field is nil (not given), then skip it. Won't return it in the row. guard var rowFieldValue: Any = row[fieldNumber] else { continue } guard let fieldType = self.fieldTypes[fieldNumber] else { failure = true return } switch fieldType { case "integer", "double", "string", "date": break case "bytes": if let bytes = rowFieldValue as? Array<UInt8> { // Assume this is actually a String. Some Text fields come back this way. if let str = String(bytes: bytes, encoding: String.Encoding.utf8) { rowFieldValue = str } } default: Log.error("Unknown field type: \(String(describing: self.fieldTypes[fieldNumber])); fieldNumber: \(fieldNumber)") if !ignoreErrors { self.forEachRowStatus = .unknownFieldType failure = true return } } if let converter = rowModel.typeConvertersToModel(propertyName: fieldName) { let value = converter(rowFieldValue) if value == nil { if ignoreErrors! { continue } else { let message = "Problem with converting: \(String(describing: self.fieldTypes[fieldNumber])); fieldNumber: \(fieldNumber)" Log.error(message) self.forEachRowStatus = .problemConvertingFieldValueToModel(message) failure = true return } } else { rowFieldValue = value! } } rowModel[fieldName] = rowFieldValue } // end for callback(rowModel) } if !returnCode { self.forEachRowStatus = .failedRowIterator } } enum SingleValueResult { case success(Any?) case error } // Returns a single value from a single row result. E.g., for SELECT GET_LOCK. func getSingleRowValue() -> SingleValueResult { let stmtResults = self.stmt.results() guard stmtResults.numRows == 1, stmtResults.numFields == 1 else { return .error } var result: Any? let returnCode = stmtResults.forEachRow { row in result = row[0] } if !returnCode { return .error } return .success(result) } } extension Database { // This intended for a one-off insert of a row, or row updates. class PreparedStatement { enum ValueType { case null case int(Int) case int64(Int64) case string(String) case bool(Bool) } enum Errors : Error { case failedOnPreparingStatement case executionError } private var stmt:MySQLStmt! private var repo: RepositoryBasics! private var statementType: StatementType! private var valueTypes = [ValueType]() private var fieldNames = [String]() private var whereValueTypes = [ValueType]() private var whereFieldNames = [String]() enum StatementType { case insert case update } init(repo: RepositoryBasics, type: StatementType) { self.repo = repo self.stmt = MySQLStmt(repo.db.connection) self.statementType = type } // For an insert, these are the fields and values for the row you are inserting. For an update, these are the fields and values for the updated row. func add(fieldName: String, value: ValueType) { fieldNames += [fieldName] valueTypes += [value] } // For an update only, provide the (conjoined) parts of the where clause. func `where`(fieldName: String, value: ValueType) { assert(statementType == .update) whereFieldNames += [fieldName] whereValueTypes += [value] } // Returns the id of the inserted row for an insert. For an update, returns the number of rows updated. @discardableResult func run() throws -> Int64 { // The insert query has `?` where values would be. See also https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection var query:String switch statementType! { case .insert: var formattedFieldNames = "" var bindParams = "" fieldNames.forEach { fieldName in if formattedFieldNames.count > 0 { formattedFieldNames += "," bindParams += "," } formattedFieldNames += fieldName bindParams += "?" } query = "INSERT INTO \(repo.tableName) (\(formattedFieldNames)) VALUES (\(bindParams))" case .update: var setValues = "" fieldNames.forEach { fieldName in if setValues.count > 0 { setValues += "," } setValues += "\(fieldName)=?" } var whereClause = "" if whereFieldNames.count > 0 { whereClause = "WHERE " var count = 0 whereFieldNames.forEach { whereFieldName in if count > 0 { whereClause += " and " } count += 1 whereClause += "\(whereFieldName)=?" } } query = "UPDATE \(repo.tableName) SET \(setValues) \(whereClause)" } Log.debug("Preparing query: \(query)") DBLog.query(query) guard self.stmt.prepare(statement: query) else { Log.error("Failed on preparing statement: \(query)") throw Errors.failedOnPreparingStatement } for valueType in valueTypes + whereValueTypes { switch valueType { case .null: self.stmt.bindParam() case .int(let intValue): self.stmt.bindParam(intValue) case .int64(let int64Value): self.stmt.bindParam(int64Value) case .string(let stringValue): self.stmt.bindParam(stringValue) case .bool(let boolValue): // Bool is TINYINT(1), which is Int8; https://dev.mysql.com/doc/refman/8.0/en/numeric-type-overview.html self.stmt.bindParam(Int8(boolValue ? 1 : 0)) } } guard self.stmt.execute() else { throw Errors.executionError } switch statementType! { case .insert: return repo.db.connection.lastInsertId() case .update: return repo.db.connection.numberAffectedRows() } } } } <file_sep>// // AccountAuthenticationTests_Facebook.swift // ServerTests // // Created by <NAME> on 7/19/17. // import XCTest import SyncServerShared import LoggerAPI @testable import Server class AccountAuthenticationTests_Facebook: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testGoodEndpointWithBadCredsFails() { let deviceUUID = Foundation.UUID().uuidString performServerTest(testAccount: .facebook1) { expectation, facebookCreds in let headers = self.setupHeaders(testUser: .facebook1, accessToken: "foobar", deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkPrimaryCreds, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode.rawValue)") XCTAssert(response!.statusCode == .unauthorized, "Did not fail on check creds request: \(response!.statusCode)") expectation.fulfill() } } } // Good Facebook creds, not creds that are necessarily on the server. func testGoodEndpointWithGoodCredsWorks() { let deviceUUID = Foundation.UUID().uuidString self.performServerTest(testAccount: .facebook1) { expectation, facebookCreds in let headers = self.setupHeaders(testUser: .facebook1, accessToken: facebookCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkPrimaryCreds, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "Did not work on check creds request") expectation.fulfill() } } } func testBadPathWithGoodCredsFails() { let badRoute = ServerEndpoint("foobar", method: .post, requestMessageType: AddUserRequest.self) let deviceUUID = Foundation.UUID().uuidString performServerTest(testAccount: .facebook1) { expectation, fbCreds in let headers = self.setupHeaders(testUser: .facebook1, accessToken: fbCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: badRoute, headers: headers) { response, dict in XCTAssert(response!.statusCode != .OK, "Did not fail on check creds request") expectation.fulfill() } } } func testGoodPathWithBadMethodWithGoodCredsFails() { let badRoute = ServerEndpoint(ServerEndpoints.checkCreds.pathName, method: .post, requestMessageType: CheckCredsRequest.self) XCTAssert(ServerEndpoints.checkCreds.method != .post) let deviceUUID = Foundation.UUID().uuidString self.performServerTest(testAccount: .facebook1) { expectation, fbCreds in let headers = self.setupHeaders(testUser: .facebook1, accessToken: fbCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: badRoute, headers: headers) { response, dict in XCTAssert(response!.statusCode != .OK, "Did not fail on check creds request") expectation.fulfill() } } } func testThatFacebookUserHasValidCreds() { createSharingUser(withSharingPermission: .read, sharingUser: .facebook1) let deviceUUID = Foundation.UUID().uuidString self.performServerTest(testAccount: .facebook1) { expectation, facebookCreds in let headers = self.setupHeaders(testUser: .facebook1, accessToken: facebookCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkCreds, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "Did not work on check creds request") expectation.fulfill() } } } } extension AccountAuthenticationTests_Facebook { static var allTests : [(String, (AccountAuthenticationTests_Facebook) -> () throws -> Void)] { let result:[(String, (AccountAuthenticationTests_Facebook) -> () throws -> Void)] = [ ("testGoodEndpointWithBadCredsFails", testGoodEndpointWithBadCredsFails), ("testGoodEndpointWithGoodCredsWorks", testGoodEndpointWithGoodCredsWorks), ("testBadPathWithGoodCredsFails", testBadPathWithGoodCredsFails), ("testGoodPathWithBadMethodWithGoodCredsFails", testGoodPathWithBadMethodWithGoodCredsFails), ("testThatFacebookUserHasValidCreds", testThatFacebookUserHasValidCreds), ] return result } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:AccountAuthenticationTests_Facebook.self) } } <file_sep>// // ServerStats.swift // Server // // Created by <NAME> on 12/28/17. // import Foundation enum ServerStat : String { case dbConnectionsOpened case dbConnectionsClosed case apiRequestsCreated case apiRequestsDeleted } class ServerStatsKeeper { private var statsRecord = [ServerStat: Int]() private var block = Synchronized() static let session = ServerStatsKeeper() var stats:[ServerStat: Int] { get { var result: [ServerStat: Int]! block.sync { result = statsRecord } return result } } private init() { } func increment(stat:ServerStat) { block.sync { if let current = statsRecord[stat] { statsRecord[stat] = current + 1 } else { statsRecord[stat] = 1 } } } func currentValue(stat:ServerStat) -> Int { var result = 0 block.sync { if let current = statsRecord[stat] { result = current } } return result } } <file_sep>// // MasterVersionRepository.swift // Server // // Created by <NAME> on 11/26/16. // // // This tracks an overall version of the fileIndex per sharingGroupUUID. import Foundation import SyncServerShared import LoggerAPI class MasterVersion : NSObject, Model { static let sharingGroupUUIDKey = "sharingGroupUUID" var sharingGroupUUID: String! static let masterVersionKey = "masterVersion" var masterVersion: MasterVersionInt! subscript(key:String) -> Any? { set { switch key { case MasterVersion.sharingGroupUUIDKey: sharingGroupUUID = newValue as? String case MasterVersion.masterVersionKey: masterVersion = newValue as? MasterVersionInt default: assert(false) } } get { return getValue(forKey: key) } } } class MasterVersionRepository : Repository, RepositoryLookup { private(set) var db:Database! required init(_ db:Database) { self.db = db } var tableName:String { return MasterVersionRepository.tableName } static var tableName:String { return "MasterVersion" } let initialMasterVersion = 0 func upcreate() -> Database.TableUpcreateResult { let createColumns = "(sharingGroupUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + "masterVersion BIGINT NOT NULL, " + "FOREIGN KEY (sharingGroupUUID) REFERENCES \(SharingGroupRepository.tableName)(\(SharingGroup.sharingGroupUUIDKey)), " + "UNIQUE (sharingGroupUUID))" return db.createTableIfNeeded(tableName: "\(tableName)", columnCreateQuery: createColumns) } enum LookupKey : CustomStringConvertible { case sharingGroupUUID(String) var description : String { switch self { case .sharingGroupUUID(let sharingGroupUUID): return "sharingGroupUUID(\(sharingGroupUUID))" } } } // The masterVersion is with respect to the userId func lookupConstraint(key:LookupKey) -> String { switch key { case .sharingGroupUUID(let sharingGroupUUID): return "sharingGroupUUID = '\(sharingGroupUUID)'" } } func initialize(sharingGroupUUID:String) -> Bool { let query = "INSERT INTO \(tableName) (sharingGroupUUID, masterVersion) " + "VALUES('\(sharingGroupUUID)', \(initialMasterVersion)) " if db.query(statement: query) { return true } else { let error = db.error Log.error("Could not initialize MasterVersion: \(error)") return false } } enum UpdateToNextResult { case error(String) case didNotMatchCurrentMasterVersion case success case deadlock case waitTimeout } // Increments master version for specific sharingGroupUUID func updateToNext(current:MasterVersion) -> UpdateToNextResult { let query = "UPDATE \(tableName) SET masterVersion = masterVersion + 1 " + "WHERE sharingGroupUUID = '\(current.sharingGroupUUID!)' and " + "masterVersion = \(current.masterVersion!)" if db.query(statement: query) { if db.numberAffectedRows() == 1 { return UpdateToNextResult.success } else { return UpdateToNextResult.didNotMatchCurrentMasterVersion } } else if db.errorCode() == Database.deadlockError { return .deadlock } else if db.errorCode() == Database.lockWaitTimeout { return .waitTimeout } else { let message = "Could not updateToNext MasterVersion: \(db.error)" Log.error(message) return UpdateToNextResult.error(message) } } } <file_sep>../Tools/deploy.sh<file_sep>// // FileControllerTests.swift // Server // // Created by <NAME> on 1/15/17. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class FileControllerTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // A test that causes a conflict with the master version on the server. Presumably this needs to take the form of (a) device1 uploading a file to the server, (b) device2 uploading a file, and finishing that upload (`DoneUploads` endpoint), and (c) device1 uploading a second file using its original master version. func testMasterVersionConflict1() { let deviceUUID1 = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } let deviceUUID2 = Foundation.UUID().uuidString guard let _ = uploadTextFile(deviceUUID:deviceUUID2, addUser:.no(sharingGroupUUID: sharingGroupUUID)) else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID2, sharingGroupUUID: sharingGroupUUID) guard let _ = uploadTextFile(deviceUUID:deviceUUID2, addUser:.no(sharingGroupUUID: sharingGroupUUID), updatedMasterVersionExpected:1) else { XCTFail() return } } func testMasterVersionConflict2() { let deviceUUID1 = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } let deviceUUID2 = Foundation.UUID().uuidString guard let _ = uploadTextFile(deviceUUID:deviceUUID2, addUser:.no(sharingGroupUUID: sharingGroupUUID)) else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, sharingGroupUUID: sharingGroupUUID) // No uploads should have been successfully finished, i.e., expectedNumberOfUploads = nil, and the updatedMasterVersion should have been updated to 1. self.sendDoneUploads(expectedNumberOfUploads: nil, deviceUUID:deviceUUID2, updatedMasterVersionExpected:1, sharingGroupUUID: sharingGroupUUID) } func testIndexWithNoFiles() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } self.getIndex(expectedFiles: [], masterVersionExpected: 0, sharingGroupUUID: sharingGroupUUID) } func testGetIndexForOnlySharingGroupsWorks() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let (files, sharingGroups) = getIndex() else { XCTFail() return } XCTAssert(files == nil) guard sharingGroups.count == 1 else { XCTFail() return } XCTAssert(sharingGroups[0].sharingGroupUUID == sharingGroupUUID) XCTAssert(sharingGroups[0].sharingGroupName == nil) XCTAssert(sharingGroups[0].deleted == false) guard sharingGroups[0].sharingGroupUsers != nil, sharingGroups[0].sharingGroupUsers.count == 1 else { XCTFail() return } sharingGroups[0].sharingGroupUsers.forEach { sgu in XCTAssert(sgu.name != nil) XCTAssert(sgu.userId != nil) } } func testIndexWithOneFile() { let deviceUUID = Foundation.UUID().uuidString let testAccount:TestAccount = .primaryOwningAccount guard let uploadResult = uploadTextFile(testAccount: testAccount, deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // Have to do a DoneUploads to transfer the files into the FileIndex self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let key = FileIndexRepository.LookupKey.primaryKeys(sharingGroupUUID: sharingGroupUUID, fileUUID: uploadResult.request.fileUUID) let fileIndexResult = FileIndexRepository(db).lookup(key: key, modelInit: FileIndex.init) guard case .found(let obj) = fileIndexResult, let fileIndexObj = obj as? FileIndex else { XCTFail() return } guard fileIndexObj.lastUploadedCheckSum != nil else { XCTFail() return } self.getIndex(expectedFiles: [uploadResult.request], masterVersionExpected: 1, sharingGroupUUID: sharingGroupUUID) guard let (files, sharingGroups) = getIndex(sharingGroupUUID: sharingGroupUUID), let theFiles = files else { XCTFail() return } XCTAssert(files != nil) guard sharingGroups.count == 1, sharingGroups[0].sharingGroupUUID == sharingGroupUUID, sharingGroups[0].sharingGroupName == nil, sharingGroups[0].deleted == false else { XCTFail() return } for file in theFiles { guard let cloudStorageType = file.cloudStorageType else { XCTFail() return } if file.fileUUID == uploadResult.request.fileUUID { XCTAssert(testAccount.scheme.cloudStorageType == cloudStorageType) } } } func testIndexWithTwoFiles() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } guard let uploadResult2 = uploadJPEGFile(deviceUUID:deviceUUID, addUser:.no(sharingGroupUUID: sharingGroupUUID)) else { XCTFail() return } // Have to do a DoneUploads to transfer the files into the FileIndex self.sendDoneUploads(expectedNumberOfUploads: 2, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) self.getIndex(expectedFiles: [uploadResult1.request, uploadResult2.request],masterVersionExpected: 1, sharingGroupUUID: sharingGroupUUID) } func testDownloadFileTextSucceeds() { downloadTextFile(masterVersionExpectedWithDownload: 1) } func testDownloadURLFileSucceeds() { downloadServerFile(mimeType: .url, file: .testUrlFile, masterVersionExpectedWithDownload: 1) } func testDownloadFileTextWithASimulatedUserChangeSucceeds() { let testAccount:TestAccount = .primaryOwningAccount let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(testAccount: testAccount, deviceUUID: deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(testAccount: testAccount, expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) var cloudStorageCreds: CloudStorage! let exp = expectation(description: "\(#function)\(#line)") testAccount.scheme.doHandler(for: .getCredentials, testAccount: testAccount) { creds in // For social accounts, e.g., Facebook, this will result in nil and fail below. That's what we want. Just trying to get cloud storage creds. cloudStorageCreds = creds as? CloudStorage exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) guard cloudStorageCreds != nil else { XCTFail() return } let file = TestFile.test2 let checkSum = file.checkSum(type: testAccount.scheme.accountName) let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = uploadResult.request.fileUUID uploadRequest.mimeType = "text/plain" uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = sharingGroupUUID uploadRequest.checkSum = checkSum let options = CloudStorageFileNameOptions(cloudFolderName: ServerTestCase.cloudFolderName, mimeType: "text/plain") let cloudFileName = uploadRequest.cloudFileName(deviceUUID:deviceUUID, mimeType: uploadRequest.mimeType) deleteFile(testAccount: testAccount, cloudFileName: cloudFileName, options: options) uploadFile(accountType: testAccount.scheme.accountName, creds: cloudStorageCreds, deviceUUID: deviceUUID, testFile: file, uploadRequest: uploadRequest, options: options) // Don't want the download to fail just due to a checksum mismatch. uploadResult.request.checkSum = checkSum downloadTextFile(testAccount: testAccount, masterVersionExpectedWithDownload: 1, uploadFileRequest: uploadResult.request, contentsChangedExpected: true) } func testDownloadTextFileWhereFileDeletedGivesGoneResponse() { let testAccount:TestAccount = .primaryOwningAccount let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(testAccount: testAccount, deviceUUID: deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(testAccount: testAccount, expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) var checkSum:String! let file = TestFile.test2 checkSum = file.checkSum(type: testAccount.scheme.accountName) let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = uploadResult.request.fileUUID uploadRequest.mimeType = "text/plain" uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = sharingGroupUUID uploadRequest.checkSum = checkSum let options = CloudStorageFileNameOptions(cloudFolderName: ServerTestCase.cloudFolderName, mimeType: "text/plain") let cloudFileName = uploadRequest.cloudFileName(deviceUUID:deviceUUID, mimeType: uploadRequest.mimeType) deleteFile(testAccount: testAccount, cloudFileName: cloudFileName, options: options) self.performServerTest(testAccount:testAccount) { expectation, testCreds in let headers = self.setupHeaders(testUser:testAccount, accessToken: testCreds.accessToken, deviceUUID:deviceUUID) let downloadFileRequest = DownloadFileRequest() downloadFileRequest.fileUUID = uploadRequest.fileUUID downloadFileRequest.masterVersion = 1 downloadFileRequest.fileVersion = 0 downloadFileRequest.sharingGroupUUID = sharingGroupUUID self.performRequest(route: ServerEndpoints.downloadFile, responseDictFrom:.header, headers: headers, urlParameters: "?" + downloadFileRequest.urlParameters()!, body:nil) { response, dict in Log.info("Status code: \(response!.statusCode)") if let dict = dict, let downloadFileResponse = try? DownloadFileResponse.decode(dict) { XCTAssert(downloadFileResponse.gone == GoneReason.fileRemovedOrRenamed.rawValue) } else { XCTFail() } expectation.fulfill() } } } func testDownloadFileTextWhereMasterVersionDiffersFails() { downloadTextFile(masterVersionExpectedWithDownload: 0, expectUpdatedMasterUpdate:true) } func testDownloadFileTextWithAppMetaDataSucceeds() { downloadTextFile(masterVersionExpectedWithDownload: 1, appMetaData:AppMetaData(version: 0, contents: "{ \"foo\": \"bar\" }")) } func testDownloadFileTextWithDifferentDownloadVersion() { downloadTextFile(masterVersionExpectedWithDownload: 1, downloadFileVersion:1, expectedError: true) } func testIndexWithFakeSharingGroupUUIDFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // Have to do a DoneUploads to transfer the files into the FileIndex self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let invalidSharingGroupUUID = UUID().uuidString self.getIndex(expectedFiles: [uploadResult.request], masterVersionExpected: 1, sharingGroupUUID: invalidSharingGroupUUID, errorExpected: true) } func testIndexWithBadSharingGroupUUIDFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // Have to do a DoneUploads to transfer the files into the FileIndex self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let workingButBadSharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: workingButBadSharingGroupUUID) else { XCTFail() return } self.getIndex(expectedFiles: [uploadResult.request], masterVersionExpected: 1, sharingGroupUUID: workingButBadSharingGroupUUID, errorExpected: true) } // TODO: *0*: Make sure we're not trying to download a file that has already been deleted. // TODO: *1* Make sure its an error for a different user to download our file even if they have the fileUUID and fileVersion. // TODO: *1* Test that two concurrent downloads work. } extension FileControllerTests { static var allTests : [(String, (FileControllerTests) -> () throws -> Void)] { return [ ("testMasterVersionConflict1", testMasterVersionConflict1), ("testMasterVersionConflict2", testMasterVersionConflict2), ("testIndexWithNoFiles", testIndexWithNoFiles), ("testGetIndexForOnlySharingGroupsWorks", testGetIndexForOnlySharingGroupsWorks), ("testIndexWithOneFile", testIndexWithOneFile), ("testIndexWithTwoFiles", testIndexWithTwoFiles), ("testDownloadFileTextSucceeds", testDownloadFileTextSucceeds), ("testDownloadURLFileSucceeds", testDownloadURLFileSucceeds), ("testDownloadFileTextWithASimulatedUserChangeSucceeds", testDownloadFileTextWithASimulatedUserChangeSucceeds), ("testDownloadTextFileWhereFileDeletedGivesGoneResponse", testDownloadTextFileWhereFileDeletedGivesGoneResponse), ("testDownloadFileTextWhereMasterVersionDiffersFails", testDownloadFileTextWhereMasterVersionDiffersFails), ("testDownloadFileTextWithAppMetaDataSucceeds", testDownloadFileTextWithAppMetaDataSucceeds), ("testDownloadFileTextWithDifferentDownloadVersion", testDownloadFileTextWithDifferentDownloadVersion), ("testIndexWithFakeSharingGroupUUIDFails", testIndexWithFakeSharingGroupUUIDFails), ("testIndexWithBadSharingGroupUUIDFails", testIndexWithBadSharingGroupUUIDFails) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:FileControllerTests.self) } } <file_sep>// // MockStorageLiveTests.swift // ServerTests // // Created by <NAME> on 6/27/19. // import XCTest @testable import Server import LoggerAPI import HeliumLogger import SyncServerShared class MockStorageLiveTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() Configuration.setupLoadTestingCloudStorage() } func testUploadFile() { let deviceUUID = Foundation.UUID().uuidString guard let result = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = result.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID) let fileIndexResult = FileIndexRepository(db).fileIndex(forSharingGroupUUID: sharingGroupUUID) switch fileIndexResult { case .fileIndex(let fileIndex): guard fileIndex.count == 1 else { XCTFail("fileIndex.count: \(fileIndex.count)") return } XCTAssert(fileIndex[0].fileUUID == result.request.fileUUID) case .error(_): XCTFail() } } func testDeleteFile() { let deviceUUID = Foundation.UUID().uuidString // This file is going to be deleted. guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult1.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult1.request.fileVersion uploadDeletionRequest.masterVersion = uploadResult1.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false) self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: uploadResult1.request.masterVersion + MasterVersionInt(1), sharingGroupUUID: sharingGroupUUID) } func testDownloadFile() { downloadTextFile(masterVersionExpectedWithDownload: 1) } } extension MockStorageLiveTests { static var allTests : [(String, (MockStorageLiveTests) -> () throws -> Void)] { return [ ("testUploadFile", testUploadFile), ("testDeleteFile", testDeleteFile), ("testDownloadFile", testDownloadFile) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: MockStorageLiveTests.self) } } <file_sep>#!/bin/bash # 11/18/17: This is the script I was using to run/test the server prior to starting to use the AWS Elastic Beanstalk. # Build and run the server from the command line # Usage: # 1) ./run.sh test [Optional-Specific-Test] -- run server tests # Optional-Specific-Test Format: # <test-module>.<test-case> or <test-module>.<test-case>/<test> # ./run.sh test ServerTests.SharingAccountsController_CreateSharingInvitation # # 2) ./run.sh [local | aws] <PathToJsonConfigFile> -- start up the server # In this case, the server is built before running. # e.g., # ./run.sh local ../Private/Server/Server.json # ./run.sh aws ../Private/Server/SharedImagesServer.json # When running on AWS, you first need to kill the prior running instance: # ps -A | grep Main # and get the pid # kill -9 <PID> # If the repo has been changed (check with: git status), do: # git reset --hard # If you need to get the new repo version: # git pull origin master # Then: # cd ~/SyncServerII # Then, run the server. # If you get a crash during building, you may need to do: # trash ~/builds/ # And try again. buildLocation=~/builds/.build-server ARG1=$1 ARG2=$2 if [ "empty${ARG1}" == "empty" ] ; then echo "See usage instructions!" exit 1 elif [ "${ARG1}" == "test" ] ; then # Some test cases expect `Cat.jpg` in /tmp cp Resources/Cat.jpg /tmp CMD="test" if [ "empty${ARG2}" != "empty" ] ; then # --filter command line option to `swift` indicates a specific test SPECIFIC_TEST="--filter ${ARG2}" fi elif [ "${ARG1}" == "local" ] || [ "${ARG1}" == "aws" ] ; then if [ "empty${ARG2}" == "empty" ] ; then echo "See usage instructions!" exit 1 fi if [ "${ARG1}" == "aws" ] ; then RUNCHECK=`ps -A | grep Main` if [ "empty${RUNCHECK}" != "empty" ] ; then echo "The server is already running: " ps -A | grep Main exit 1 fi fi CMD="build" JSONCONFIG="${ARG2}" else echo "See usage instructions!" exit 1 fi # use --verbose flag on `swift` to show more output if [ "${ARG1}" == "test" ] ; then echo "Building server and then running tests ..." swift "${CMD}" ${SPECIFIC_TEST} -Xswiftc -DDEBUG -Xswiftc -DSERVER --build-path "${buildLocation}" else echo "Building server ..." swift "${CMD}" -Xswiftc -DDEBUG -Xswiftc -DSERVER --build-path "${buildLocation}" fi if [ $? == 0 ] && [ "${CMD}" == "build" ] ; then if [ "${ARG1}" == "local" ] ; then echo "Starting server locally..." ${buildLocation}/debug/Main "${JSONCONFIG}" else echo "Starting server on AWS ..." # `stdbuf` gets rid of buffering; see also https://serverfault.com/questions/294218/is-there-a-way-to-redirect-output-to-a-file-without-buffering-on-unix-linux ( stdbuf -o0 ${buildLocation}/debug/Main "${JSONCONFIG}" > ~/output.log 2>&1 & ) fi fi <file_sep>// // GeneralAuthTests.swift // Server // // Created by <NAME> on 12/4/16. // // import LoggerAPI @testable import Server import KituraNet import XCTest import Foundation import SyncServerShared class GeneralAuthTests: ServerTestCase, LinuxTestable { func testBadEndpointFails() { performServerTest { expectation, creds in let badRoute = ServerEndpoint("foobar", method: .post, requestMessageType: AddUserRequest.self) self.performRequest(route:badRoute) { response, dict in XCTAssert(response!.statusCode != .OK, "Did not fail on request") Log.info("response.statusCode: \(String(describing: response?.statusCode))") expectation.fulfill() } } } func testGoodEndpointWithNoCredsRequiredWorks() { performServerTest { expectation, creds in self.performRequest(route: ServerEndpoints.healthCheck) { response, dict in XCTAssert(response!.statusCode == .OK, "Failed on healthcheck request") expectation.fulfill() } } } } extension GeneralAuthTests { static var allTests : [(String, (GeneralAuthTests) -> () throws -> Void)] { return [ ("testBadEndpointFails", testBadEndpointFails), ("testGoodEndpointWithNoCredsRequiredWorks", testGoodEndpointWithNoCredsRequiredWorks) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:GeneralAuthTests.self) } } <file_sep>#!/bin/bash # Usage: # <script> [update] # update -- will update dependencies. # Odd things seem to happen if you have xcode running when you run tweakXcodeproj.rb RESULT=`killall Xcode 2>&1` KILLED=0 if [ "empty$RESULT" == "empty" ]; then KILLED=1 elif [ "$RESULT" == "No matching processes belonging to you were found" ]; then # killall outputs "No matching processes belonging to you were found" if Xcode is not running, but that's OK. KILLED=1 fi if [[ KILLED -eq 1 ]]; then if [ "empty$1" == "emptyupdate" ]; then swift package update elif [ "$#" -eq 1 ]; then echo "Unknown argument!" exit fi swift package generate-xcodeproj ./tweakXcodeproj.rb echo "Success!" else echo "Youch: Could not kill xcode-- shut it down manually and try this again." fi <file_sep>The files `Server.json` and `ServerTests.json` contain private info, and so are not contained in the public repo. For now, search the code for this file name to find out the keys/values it contains. Hopefully later, I document this better! :). The file `VERSION` contains the git tag of version pushed to Docker, is put there and updated by the devops/release.sh script, and is read by the server when it starts. It is reported by the healthcheck endpoint.<file_sep>// // FileController+DownloadFile.swift // Server // // Created by <NAME> on 3/22/17. // // import Foundation import LoggerAPI import SyncServerShared import Kitura extension FileController { func downloadFile(params:RequestProcessingParameters) { guard let downloadRequest = params.request as? DownloadFileRequest else { let message = "Did not receive DownloadFileRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard sharingGroupSecurityCheck(sharingGroupUUID: downloadRequest.sharingGroupUUID, params: params) else { let message = "Failed in sharing group security check." Log.error(message) params.completion(.failure(.message(message))) return } // TODO: *0* What would happen if someone else deletes the file as we we're downloading it? It seems a shame to hold a lock for the entire duration of the download, however. // TODO: *0* Related question: With transactions, if we just select from a particular row (i.e., for the master version for this user, as immediately below) does this result in a lock for the duration of the transaction? We could test for this by sleeping in the middle of the download below, and seeing if another request could delete the file at the same time. This should make a good test case for any mechanism that I come up with. Controllers.getMasterVersion(sharingGroupUUID: downloadRequest.sharingGroupUUID, params: params) { (error, masterVersion) in if error != nil { params.completion(.failure(.message("\(error!)"))) return } if masterVersion != downloadRequest.masterVersion { let response = DownloadFileResponse() Log.warning("Master version update: \(String(describing: masterVersion))") response.masterVersionUpdate = masterVersion params.completion(.success(response)) return } // Need to get the file from the cloud storage service: // First, lookup the file in the FileIndex. This does an important security check too-- make sure the fileUUID is in the sharing group. let key = FileIndexRepository.LookupKey.primaryKeys(sharingGroupUUID: downloadRequest.sharingGroupUUID, fileUUID: downloadRequest.fileUUID) let lookupResult = params.repos.fileIndex.lookup(key: key, modelInit: FileIndex.init) var fileIndexObj:FileIndex? switch lookupResult { case .found(let modelObj): fileIndexObj = modelObj as? FileIndex if fileIndexObj == nil { let message = "Could not convert model object to FileIndex" Log.error(message) params.completion(.failure(.message(message))) return } case .noObjectFound: let message = "Could not find file in FileIndex" Log.error(message) params.completion(.failure(.message(message))) return case .error(let error): let message = "Error looking up file in FileIndex: \(error)" Log.error(message) params.completion(.failure(.message(message))) return } guard downloadRequest.fileVersion == fileIndexObj!.fileVersion else { let message = "Expected file version \(String(describing: downloadRequest.fileVersion)) was not the same as the actual version \(String(describing: fileIndexObj!.fileVersion))" Log.error(message) params.completion(.failure(.message(message))) return } guard downloadRequest.appMetaDataVersion == fileIndexObj!.appMetaDataVersion else { let message = "Expected app meta data version \(String(describing: downloadRequest.appMetaDataVersion)) was not the same as the actual version \(String(describing: fileIndexObj!.appMetaDataVersion))" Log.error(message) params.completion(.failure(.message(message))) return } if fileIndexObj!.deleted! { let message = "The file you are trying to download has been deleted!" Log.error(message) params.completion(.failure(.message(message))) return } // TODO: *5*: Eventually, this should bypass the middle man and stream from the cloud storage service directly to the client. // Both the deviceUUID and the fileUUID must come from the file index-- They give the specific name of the file in cloud storage. The deviceUUID of the requesting device is not the right one. guard let deviceUUID = fileIndexObj!.deviceUUID else { let message = "No deviceUUID!" Log.error(message) params.completion(.failure(.message(message))) return } let cloudFileName = fileIndexObj!.cloudFileName(deviceUUID:deviceUUID, mimeType: fileIndexObj!.mimeType) // OWNER // The cloud storage for the file is the original owning user's storage. guard let owningUserCreds = FileController.getCreds(forUserId: fileIndexObj!.userId, from: params.db, delegate: params.accountDelegate) else { let message = "Could not obtain owning users creds" Log.error(message) params.completion(.failure(.message(message))) return } guard let cloudStorageCreds = owningUserCreds.cloudStorage, let cloudStorageType = owningUserCreds.accountScheme.cloudStorageType else { let message = "Could not obtain cloud storage creds or cloud storage type." Log.error(message) params.completion(.failure(.message(message))) return } let options = CloudStorageFileNameOptions(cloudFolderName: owningUserCreds.cloudFolderName, mimeType: fileIndexObj!.mimeType) cloudStorageCreds.downloadFile(cloudFileName: cloudFileName, options:options) { result in switch result { case .success(let downloadResult): // I used to check the file size as downloaded against the file size in the file index (last uploaded). And call it an error if they didn't match. But we're being fancier now. Going to let the client see if this is an error. https://github.com/crspybits/SyncServerII/issues/93 Log.debug("CheckSum: \(downloadResult.checkSum)") var contentsChanged = false // 11/4/18; This is conditional because for migration purposes, the FileIndex may not contain a lastUploadedCheckSum. i.e., it comes from a FileIndex record before we added the lastUploadedCheckSum field. if let lastUploadedCheckSum = fileIndexObj!.lastUploadedCheckSum { contentsChanged = downloadResult.checkSum != lastUploadedCheckSum } let response = DownloadFileResponse() response.appMetaData = fileIndexObj!.appMetaData response.data = downloadResult.data response.checkSum = downloadResult.checkSum response.cloudStorageType = cloudStorageType response.contentsChanged = contentsChanged params.completion(.success(response)) // Don't consider the following two cases as HTTP status errors, so we can return appMetaData back to client. appMetaData, for v0 files, can be necessary for clients to deal more completely with these error conditions. case .accessTokenRevokedOrExpired: let message = "Access token revoked or expired." Log.error(message) let response = DownloadFileResponse() response.appMetaData = fileIndexObj!.appMetaData response.cloudStorageType = cloudStorageType response.gone = GoneReason.authTokenExpiredOrRevoked.rawValue params.completion(.success(response)) case .fileNotFound: let message = "File not found." Log.error(message) let response = DownloadFileResponse() response.appMetaData = fileIndexObj!.appMetaData response.cloudStorageType = cloudStorageType response.gone = GoneReason.fileRemovedOrRenamed.rawValue params.completion(.success(response)) case .failure(let error): let message = "Failed downloading file: \(error)" Log.error(message) params.completion(.failure(.message(message))) } } } } } <file_sep>// // Google.swift // Server // // Created by <NAME> on 12/22/16. // // import Foundation import Credentials import CredentialsGoogle import KituraNet import SyncServerShared import Kitura import LoggerAPI // Credentials basis for making Google endpoint calls. /* Analysis of credential usage for Google SignIn: a) Upon first usage by a specific client app instance, the client will do a `checkCreds`, which will find that the user is not present on the system. It will then do an `addUser` to create the user, which will give us (the server) a serverAuthCode, which we use to generate a refreshToken and access token. Both of these are stored in the SyncServer on the database. (Note that this access token, generated from the serverAuthCode, is distinct from the access token sent from the client to the SyncServer). Only the `addUser` and `checkCreds` SyncServer endpoints make use of the serverAuthCode (though it is sent to all endpoints). b) Subsequent operations pass in an access token from the client app. That client-generated access token is sent to the server for a single purpose: It enables primary authentication-- it is sent to Google to verify that we have an actual Google user. The lifetime of the access token when used purely in this way is uncertain. Definitely longer than 60 minutes. It might not expire. See also my comment at http://stackoverflow.com/questions/13851157/oauth2-and-google-api-access-token-expiration-time/42878810#42878810 If primary authentication with Google fails using this access token, then a 401 HTTP status code is returned to the client app, which is its signal to, on the client-side, refresh that access token. c) If the SyncServer endpoint needs to use Google Drive endpoints, the SyncServer utilizes the refresh-token based access token. (Note that not all SyncServer endpoints, e.g., /Index, connect to Google Drive). These refresh-token based access token's expire every 60 minutes, and we observe such expiration purely on the basis of specific failures of Google Drive endpoints-- in which case, we initiate a refresh of the access token using the refresh token, and store the refreshed access token in our SyncServer database. d) The rationale for the two kinds of access tokens (client-side, and server-side refresh-token based) are as follows: i) I don't want a situation where I have to always use the client to refresh access tokens. I think this would be awkward. Operations using Google Drive would have to fail part-way through their operation when an access token expires, send an HTTP code back to the client, and then restart. This seems awkward and could make for more complicated than needed algorithms on the server. ii) The pattern of client-based primary authentication and server-side tokens that access cloud services is the general pattern by which the server needs to be structured. For example, for shared account authorization where Google Drive user X wants to allow a Facebook user Y to make use of their files, primary authentication will take place using Facebook credentials for Y, and server-side use of Google Drive will make use of X's stored refresh token/access token's. */ class GoogleCreds : AccountAPICall, Account { // The following keys are for conversion <-> JSON (e.g., to store this into a database). var accessToken: String! // This is obtained via the serverAuthCode var refreshToken: String! // Storing the serverAuthCode in the database so that I don't try to generate a refresh token from the same serverAuthCode twice. static let serverAuthCodeKey = "serverAuthCode" // Only present transiently. var serverAuthCode:String? let expiredAccessTokenHTTPCode = HTTPStatusCode.unauthorized var owningAccountsNeedCloudFolderName: Bool { return true } static var accountScheme:AccountScheme { return .google } var accountScheme:AccountScheme { return GoogleCreds.accountScheme } weak var delegate:AccountDelegate? var accountCreationUser:AccountCreationUser? // This is to ensure that some error doesn't cause us to attempt to refresh the access token multiple times in a row. I'm assuming that for any one endpoint invocation, we'll at most need to refresh the access token a single time. private var alreadyRefreshed = false override init?() { super.init() baseURL = "www.googleapis.com" } static func getProperties(fromRequest request:RouterRequest) -> [String: Any] { var result = [String: Any]() if let authCode = request.headers[ServerConstants.HTTPOAuth2AuthorizationCodeKey] { result[ServerConstants.HTTPOAuth2AuthorizationCodeKey] = authCode } if let accessToken = request.headers[ServerConstants.HTTPOAuth2AccessTokenKey] { result[ServerConstants.HTTPOAuth2AccessTokenKey] = accessToken } return result } static func fromProperties(_ properties: AccountManager.AccountProperties, user:AccountCreationUser?, delegate:AccountDelegate?) -> Account? { guard let creds = GoogleCreds() else { return nil } creds.accountCreationUser = user creds.delegate = delegate creds.accessToken = properties.properties[ServerConstants.HTTPOAuth2AccessTokenKey] as? String creds.serverAuthCode = properties.properties[ServerConstants.HTTPOAuth2AuthorizationCodeKey] as? String return creds } static func fromJSON(_ json:String, user:AccountCreationUser, delegate:AccountDelegate?) throws -> Account? { guard let jsonDict = json.toJSONDictionary() as? [String:String] else { Log.error("Could not convert string to JSON [String:String]: \(json)") return nil } guard let result = GoogleCreds() else { return nil } result.delegate = delegate result.accountCreationUser = user // Only owning users have access token's in creds. Sharing users have empty creds stored in the database. switch user { case .user(let user) where AccountScheme(.accountName(user.accountType))?.userType == .owning: fallthrough case .userId: try setProperty(jsonDict:jsonDict, key: accessTokenKey) { value in result.accessToken = value } default: // Sharing users not allowed. assert(false) } // Considering the refresh token and serverAuthCode as optional because (a) I think I don't always get these from the client, and (b) during testing, I don't always have these. try setProperty(jsonDict:jsonDict, key: refreshTokenKey, required:false) { value in result.refreshToken = value } try setProperty(jsonDict:jsonDict, key: serverAuthCodeKey, required:false) { value in result.serverAuthCode = value } return result } func toJSON() -> String? { var jsonDict = [String:String]() // 8/8/17; Only if a Google user is an owning user should we be storing creds info into the database. https://github.com/crspybits/SyncServerII/issues/13 // 6/23/18; Now-- we've changed the concept of owning versus sharing. Google accounts are always owning. See also https://github.com/crspybits/SyncServerII/issues/27 jsonDict[GoogleCreds.accessTokenKey] = self.accessToken jsonDict[GoogleCreds.refreshTokenKey] = self.refreshToken jsonDict[GoogleCreds.serverAuthCodeKey] = self.serverAuthCode return JSONExtras.toJSONString(dict: jsonDict) } static let googleAPIAccessTokenKey = "access_token" static let googleAPIRefreshTokenKey = "refresh_token" func needToGenerateTokens(dbCreds:Account? = nil) -> Bool { var result = serverAuthCode != nil // If no dbCreds, then we generate tokens. if let dbCreds = dbCreds { if let dbGoogleCreds = dbCreds as? GoogleCreds { result = result && serverAuthCode != dbGoogleCreds.serverAuthCode } else { Log.error("Did not get GoogleCreds as dbCreds!") } } Log.debug("needToGenerateTokens: \(result); serverAuthCode: \(String(describing: serverAuthCode))") return result } // Use the serverAuthCode to generate a refresh and access token if there is one. func generateTokens(response: RouterResponse?, completion:@escaping (Swift.Error?)->()) { if self.serverAuthCode == nil { Log.info("No serverAuthCode from client.") completion(nil) return } guard let clientId = Configuration.server.GoogleServerClientId, let clientSecret = Configuration.server.GoogleServerClientSecret else { Log.info("No client or secret from in configuration.") completion(CredentialsError.noClientIdOrSecret) return } let bodyParameters = "code=\(self.serverAuthCode!)&client_id=\(clientId)&client_secret=\(clientSecret)&redirect_uri=&grant_type=authorization_code" Log.debug("bodyParameters: \(bodyParameters)") let additionalHeaders = ["Content-Type": "application/x-www-form-urlencoded"] self.apiCall(method: "POST", path: "/oauth2/v4/token", additionalHeaders:additionalHeaders, body: .string(bodyParameters)) { apiResult, statusCode, responseHeaders in guard statusCode == HTTPStatusCode.OK else { completion(GenerateTokensError.badStatusCode(statusCode)) return } guard apiResult != nil else { completion(GenerateTokensError.nilAPIResult) return } if case .dictionary(let dictionary) = apiResult!, let accessToken = dictionary[GoogleCreds.googleAPIAccessTokenKey] as? String, let refreshToken = dictionary[GoogleCreds.googleAPIRefreshTokenKey] as? String { self.accessToken = accessToken self.refreshToken = refreshToken Log.debug("Obtained tokens: accessToken: \(accessToken)\n refreshToken: \(refreshToken)") if self.delegate == nil { Log.warning("No Google Creds delegate!") completion(nil) return } if self.delegate!.saveToDatabase(account: self) { completion(nil) return } completion(GenerateTokensError.errorSavingCredsToDatabase) return } completion(GenerateTokensError.couldNotObtainParameterFromJSON) } } func merge(withNewer newerAccount:Account) { assert(newerAccount is GoogleCreds, "Wrong other type of creds!") let newerGoogleCreds = newerAccount as! GoogleCreds if newerGoogleCreds.refreshToken != nil { self.refreshToken = newerGoogleCreds.refreshToken } if newerGoogleCreds.serverAuthCode != nil { self.serverAuthCode = newerGoogleCreds.serverAuthCode } self.accessToken = newerGoogleCreds.accessToken } enum CredentialsError : Swift.Error { case badStatusCode(HTTPStatusCode?) case couldNotObtainParameterFromJSON case nilAPIResult case badJSONResult case errorSavingCredsToDatabase case noRefreshToken case expiredOrRevokedAccessToken case noClientIdOrSecret } // Use the refresh token to generate a new access token. // If error is nil when the completion handler is called, then the accessToken of this object has been refreshed. It hasn't yet been persistently stored on this server. Uses delegate, if one is defined, to save refreshed creds to database. func refresh(completion:@escaping (Swift.Error?)->()) { // See "Using a refresh token" at https://developers.google.com/identity/protocols/OAuth2WebServer // TODO: *0* Sometimes we've been ending up in a situation where we don't have a refresh token. The database somehow doesn't get the refresh token saved in certain situations. What are those situations? guard self.refreshToken != nil else { completion(CredentialsError.noRefreshToken) return } guard let clientId = Configuration.server.GoogleServerClientId, let clientSecret = Configuration.server.GoogleServerClientSecret else { Log.info("No client or secret from in configuration.") completion(CredentialsError.noClientIdOrSecret) return } let bodyParameters = "client_id=\(clientId)&client_secret=\(clientSecret)&refresh_token=\(self.refreshToken!)&grant_type=refresh_token" Log.debug("bodyParameters: \(bodyParameters)") let additionalHeaders = ["Content-Type": "application/x-www-form-urlencoded"] self.apiCall(method: "POST", path: "/oauth2/v4/token", additionalHeaders:additionalHeaders, body: .string(bodyParameters), expectedFailureBody: .json) { apiResult, statusCode, responseHeaders in // When the refresh token has been revoked // ["error": "invalid_grant", "error_description": "Token has been expired or revoked."] // [1] if statusCode == HTTPStatusCode.badRequest, case .dictionary(let dict)? = apiResult, let error = dict["error"] as? String, error == "invalid_grant" { completion(CredentialsError.expiredOrRevokedAccessToken) return } guard statusCode == HTTPStatusCode.OK else { Log.error("Bad status code: \(String(describing: statusCode))") completion(CredentialsError.badStatusCode(statusCode)) return } guard apiResult != nil else { Log.error("API result was nil!") completion(CredentialsError.nilAPIResult) return } guard case .dictionary(let dictionary) = apiResult! else { Log.error("Bad JSON result: \(String(describing: apiResult))") completion(CredentialsError.badJSONResult) return } if let accessToken = dictionary[GoogleCreds.googleAPIAccessTokenKey] as? String { self.accessToken = accessToken Log.debug("Refreshed access token: \(accessToken)") if self.delegate == nil { Log.warning("Delegate was nil-- could not save creds to database!") completion(nil) return } if self.delegate!.saveToDatabase(account: self) { completion(nil) return } completion(CredentialsError.errorSavingCredsToDatabase) return } Log.error("Could not obtain parameter from JSON!") completion(CredentialsError.couldNotObtainParameterFromJSON) } } let tokenRevokedOrExpired = "accessTokenRevokedOrExpired" override func apiCall(method:String, baseURL:String? = nil, path:String, additionalHeaders: [String:String]? = nil, additionalOptions: [ClientRequest.Options] = [], urlParameters:String? = nil, body:APICallBody? = nil, returnResultWhenNon200Code:Bool = true, expectedSuccessBody:ExpectedResponse? = nil, expectedFailureBody:ExpectedResponse? = nil, completion:@escaping (_ result: APICallResult?, HTTPStatusCode?, _ responseHeaders: HeadersContainer?)->()) { var headers:[String:String] = additionalHeaders ?? [:] // We use this for some cases where we don't have an accessToken if self.accessToken != nil { headers["Authorization"] = "Bearer \(self.accessToken!)" } super.apiCall(method: method, baseURL: baseURL, path: path, additionalHeaders: headers, additionalOptions: additionalOptions, urlParameters: urlParameters, body: body, returnResultWhenNon200Code: returnResultWhenNon200Code, expectedSuccessBody: expectedSuccessBody, expectedFailureBody: expectedFailureBody) { (apiCallResult, statusCode, responseHeaders) in /* So far, I've seen two results from a Google expired or revoked refresh token: 1) an unauthorized http status here followed by [1] in refresh. 2) The following response here: ["error": ["code": 403, "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.", "errors": [ ["message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.", "reason": "dailyLimitExceededUnreg", "extendedHelp": "https://code.google.com/apis/console", "domain": "usageLimits"] ] ] ] */ if statusCode == HTTPStatusCode.forbidden, case .dictionary(let dict)? = apiCallResult, let error = dict["error"] as? [String: Any], let errors = error["errors"] as? [[String: Any]], errors.count > 0, let reason = errors[0]["reason"] as? String, reason == "dailyLimitExceededUnreg" { Log.info("Google API Call: Daily limit exceeded.") completion(APICallResult.dictionary( ["error":self.tokenRevokedOrExpired]), .forbidden, nil) return } if statusCode == self.expiredAccessTokenHTTPCode && !self.alreadyRefreshed { self.alreadyRefreshed = true Log.info("Attempting to refresh Google access token...") self.refresh() { error in if let error = error { switch error { case CredentialsError.expiredOrRevokedAccessToken: Log.info("Refresh token expired or revoked") completion( APICallResult.dictionary( ["error":self.tokenRevokedOrExpired]), .unauthorized, nil) default: Log.error("Failed to refresh access token: \(String(describing: error))") } } else { Log.info("Successfully refreshed access token!") // Refresh was successful, update the authorization header and try the operation again. headers["Authorization"] = "Bearer \(self.accessToken!)" super.apiCall(method: method, baseURL: baseURL, path: path, additionalHeaders: headers, additionalOptions: additionalOptions, urlParameters: urlParameters, body: body, returnResultWhenNon200Code: returnResultWhenNon200Code, expectedSuccessBody: expectedSuccessBody, expectedFailureBody: expectedFailureBody, completion: completion) } } } else { completion(apiCallResult, statusCode, responseHeaders) } } } } <file_sep>// // TestConfiguration.swift // Server // // Created by <NAME> on 9/11/19. // import Foundation // I've put this in the Server files because I've added it into the Configuration as well, for easier access. #if DEBUG struct TestConfiguration: Decodable { // This is from <EMAIL>; I created this and the two other Google refresh tokens below on 8/26/18 using method: 1) boot up testing SyncServer on AWS or locally, 2) sign in using SyncServer Example client, 3) connect into the RDS mySQL or the mySQL db locally, 4) Look at the User table for the refresh token let GoogleRefreshToken: String let GoogleSub: String // Another testing only token, for account: <EMAIL>. This is used for redeeming sharing invitations. let GoogleRefreshToken2: String let GoogleSub2: String // Another testing only token, for account: <EMAIL>. For testing sharing invitations. let GoogleRefreshToken3: String let GoogleSub3: String // I think this is from <EMAIL>; revoked using https://myaccount.google.com/permissions?pli=1 let GoogleRefreshTokenRevoked: String let GoogleSub4: String // Facebook token for Facebook test user <EMAIL>; api v3.0", let FacebookLongLivedToken1: String let FacebookId1: String // Facebook token for Facebook test user <EMAIL> This is *not* long-lived. let FacebookLongLivedToken2: String let FacebookId2: String // Dropbox access tokens live forever-- until revoked-- <EMAIL> let DropboxAccessToken1: String let DropboxId1: String // Dropbox access token -- <EMAIL> let DropboxAccessToken2: String let DropboxId2: String // Dropbox access token -- <EMAIL>-- that was revoked; see https://www.dropbox.com/account/security let DropboxAccessTokenRevoked: String let DropboxId3: String struct MicrosoftTokens: Decodable { let refreshToken: String // For bootstrapping the refresh token-- must be the "idToken" from iOS MSAL (and not the accessToken from that). // See https://docs.microsoft.com/en-us/azure/active-directory/develop/id-tokens // https://docs.microsoft.com/en-us/azure/active-directory/develop/authentication-scenarios // https://medium.com/@nilasini/id-token-vs-access-token-17e7dd622084 let idToken: String // The "accessToken" from iOS MSAL let accessToken: String let id: String } // for <EMAIL> let microsoft1: MicrosoftTokens // for <EMAIL> let microsoft2: MicrosoftTokens // for <EMAIL>, but an expired access token let microsoft1ExpiredAccessToken: MicrosoftTokens /* This is somewhat tricky to generate. 1) Make a new account, 1) Generate an accessToken (in iOS MSAL's terminology). 2) Revoke the rights of Neebla from this account The access token, at least until it is expired, should be purely a revoked access token. */ let microsoft2RevokedAccessToken: MicrosoftTokens struct AppleSignInTokens: Decodable { let authorizationCode: String let refreshToken: String let idToken: String } let apple1: AppleSignInTokens } #endif <file_sep>#!/bin/bash # Usage: # arg1: the name of the .json configuration file for the server # Using https://stackoverflow.com/questions/10467272/get-long-live-access-token-from-facebook to extend the life of a Facebook access token CONFIG_FILE=$1 getToken () { # Parameters: local tokenKey=$1 local FB_CLIENT_ID=`jq -r .FacebookClientId < "$CONFIG_FILE"` local FB_CLIENT_SECRET=`jq -r .FacebookClientSecret < "$CONFIG_FILE"` local ACCESS_TOKEN=`jq -r .${tokenKey} < "$CONFIG_FILE"` local RESULT=`curl --silent "https://graph.facebook.com/oauth/access_token?client_id=${FB_CLIENT_ID}&client_secret=${FB_CLIENT_SECRET}&grant_type=fb_exchange_token&fb_exchange_token=${ACCESS_TOKEN}"` echo "Long lived token for: ${tokenKey}:" echo $RESULT | jq -r .access_token } getToken "FacebookLongLivedToken1" getToken "FacebookLongLivedToken2" <file_sep>import XCTest import Kitura import KituraNet @testable import Server import LoggerAPI import HeliumLogger import CredentialsDropbox import Foundation import SyncServerShared class AccountAuthenticationTests_Dropbox: ServerTestCase, LinuxTestable { let serverResponseTime:TimeInterval = 10 func testGoodEndpointWithBadCredsFails() { let deviceUUID = Foundation.UUID().uuidString performServerTest(testAccount: .dropbox1) { expectation, dropboxCreds in let headers = self.setupHeaders(testUser: .dropbox1, accessToken: "foobar", deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkPrimaryCreds, headers: headers) { response, dict in Log.info("Status Code: \(response!.statusCode.rawValue)") XCTAssert(response!.statusCode == .unauthorized, "Did not fail on check creds request: \(response!.statusCode)") expectation.fulfill() } } } // Good Dropbox creds, not creds that are necessarily on the server. func testGoodEndpointWithGoodCredsWorks() { let deviceUUID = Foundation.UUID().uuidString self.performServerTest(testAccount: .dropbox1) { expectation, dropboxCreds in let headers = self.setupHeaders(testUser: .dropbox1, accessToken: dropboxCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkPrimaryCreds, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "Did not work on check creds request") expectation.fulfill() } } } func testBadPathWithGoodCredsFails() { let badRoute = ServerEndpoint("foobar", method: .post, requestMessageType: AddUserRequest.self) let deviceUUID = Foundation.UUID().uuidString performServerTest(testAccount: .dropbox1) { expectation, dbCreds in let headers = self.setupHeaders(testUser: .dropbox1, accessToken: dbCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: badRoute, headers: headers) { response, dict in XCTAssert(response!.statusCode != .OK, "Did not fail on check creds request") expectation.fulfill() } } } func testGoodPathWithBadMethodWithGoodCredsFails() { let badRoute = ServerEndpoint(ServerEndpoints.checkCreds.pathName, method: .post, requestMessageType: CheckCredsRequest.self) XCTAssert(ServerEndpoints.checkCreds.method != .post) let deviceUUID = Foundation.UUID().uuidString self.performServerTest(testAccount: .dropbox1) { expectation, dbCreds in let headers = self.setupHeaders(testUser: .dropbox1, accessToken: dbCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: badRoute, headers: headers) { response, dict in XCTAssert(response!.statusCode != .OK, "Did not fail on check creds request") expectation.fulfill() } } } func testThatDropboxUserHasValidCreds() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString addNewUser(testAccount: .dropbox1, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID, cloudFolderName: nil) self.performServerTest(testAccount: .dropbox1) { expectation, dbCreds in let headers = self.setupHeaders(testUser: .dropbox1, accessToken: dbCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkCreds, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "Did not work on check creds request") expectation.fulfill() } } } } extension AccountAuthenticationTests_Dropbox { static var allTests : [(String, (AccountAuthenticationTests_Dropbox) -> () throws -> Void)] { let result:[(String, (AccountAuthenticationTests_Dropbox) -> () throws -> Void)] = [ ("testGoodEndpointWithBadCredsFails", testGoodEndpointWithBadCredsFails), ("testGoodEndpointWithGoodCredsWorks", testGoodEndpointWithGoodCredsWorks), ("testBadPathWithGoodCredsFails", testBadPathWithGoodCredsFails), ("testGoodPathWithBadMethodWithGoodCredsFails", testGoodPathWithBadMethodWithGoodCredsFails), ("testThatDropboxUserHasValidCreds", testThatDropboxUserHasValidCreds), ] return result } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:AccountAuthenticationTests_Dropbox.self) } } <file_sep>// // SharingGroupUserRepository.swift // Server // // Created by <NAME> on 6/24/18. // // What users are in specific sharing groups? import Foundation import LoggerAPI import SyncServerShared typealias SharingGroupUserId = Int64 class SharingGroupUser : NSObject, Model { static let sharingGroupUserIdKey = "sharingGroupUserId" var sharingGroupUserId: SharingGroupUserId! // Each record in this table relates a sharing group... static let sharingGroupUUIDKey = "sharingGroupUUID" var sharingGroupUUID: String! // ... to a user. static let userIdKey = "userId" var userId: UserId! // Only when the current user (identified by the userId) is a sharing user, this gives the userId that is the owner of the data for this sharing group. static let owningUserIdKey = "owningUserId" var owningUserId:UserId? // The permissions that the user has in regards to the sharing group. The user can read (anyone's data), can upload (to their own or others storage), and invite others to join the group. static let permissionKey = "permission" var permission:Permission? subscript(key:String) -> Any? { set { switch key { case SharingGroupUser.sharingGroupUserIdKey: sharingGroupUserId = newValue as! SharingGroupUserId? case SharingGroupUser.userIdKey: userId = newValue as! UserId? case SharingGroupUser.sharingGroupUUIDKey: sharingGroupUUID = newValue as! String? case SharingGroupUser.permissionKey: permission = newValue as! Permission? case SharingGroupUser.owningUserIdKey: owningUserId = newValue as! UserId? default: Log.error("Did not find key: \(key)") assert(false) } } get { return getValue(forKey: key) } } func typeConvertersToModel(propertyName:String) -> ((_ propertyValue:Any) -> Any?)? { switch propertyName { case SharingGroupUser.permissionKey: return {(x:Any) -> Any? in return Permission(rawValue: x as! String) } default: return nil } } override init() { super.init() } } class SharingGroupUserRepository : Repository, RepositoryLookup { private(set) var db:Database! required init(_ db:Database) { self.db = db } var tableName:String { return SharingGroupUserRepository.tableName } static var tableName:String { return "SharingGroupUser" } func upcreate() -> Database.TableUpcreateResult { let createColumns = "(sharingGroupUserId BIGINT NOT NULL AUTO_INCREMENT, " + "sharingGroupUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + "userId BIGINT NOT NULL, " + // NULL for only owning users; sharing users must have non-NULL value. "owningUserId BIGINT, " + "permission VARCHAR(\(Permission.maxStringLength())), " + "FOREIGN KEY (owningUserId) REFERENCES \(UserRepository.tableName)(\(User.userIdKey)), " + "FOREIGN KEY (userId) REFERENCES \(UserRepository.tableName)(\(User.userIdKey)), " + "FOREIGN KEY (sharingGroupUUID) REFERENCES \(SharingGroupRepository.tableName)(\(SharingGroup.sharingGroupUUIDKey)), " + "UNIQUE (sharingGroupUUID, userId), " + "UNIQUE (sharingGroupUserId))" let result = db.createTableIfNeeded(tableName: "\(tableName)", columnCreateQuery: createColumns) return result } enum LookupKey : CustomStringConvertible { case sharingGroupUserId(SharingGroupUserId) case primaryKeys(sharingGroupUUID: String, userId: UserId) case userId(UserId) case sharingGroupUUID(String) case owningUserId(UserId) case owningUserAndSharingGroup(owningUserId: UserId, uuid: String) var description : String { switch self { case .sharingGroupUserId(let sharingGroupUserId): return "sharingGroupUserId(\(sharingGroupUserId))" case .primaryKeys(sharingGroupUUID: let sharingGroupUUID, userId: let userId): return "primaryKeys(\(sharingGroupUUID), \(userId))" case .userId(let userId): return "userId(\(userId))" case .sharingGroupUUID(let sharingGroupUUID): return "sharingGroupUUID(\(sharingGroupUUID))" case .owningUserId(let owningUserId): return "owningUserId(\(owningUserId))" case .owningUserAndSharingGroup(owningUserId: let owningUserId, let sharingGroupUUID): return "owningUserId(\(owningUserId), \(sharingGroupUUID)" } } } func lookupConstraint(key:LookupKey) -> String { switch key { case .sharingGroupUserId(let sharingGroupUserId): return "sharingGroupUserId = \(sharingGroupUserId)" case .primaryKeys(sharingGroupUUID: let sharingGroupUUID, userId: let userId): return "sharingGroupUUID = '\(sharingGroupUUID)' AND userId = \(userId)" case .userId(let userId): return "userId = \(userId)" case .sharingGroupUUID(let sharingGroupUUID): return "sharingGroupUUID = '\(sharingGroupUUID)'" case .owningUserId(let owningUserId): return "owningUserId = \(owningUserId)" case .owningUserAndSharingGroup(owningUserId: let owningUserId, let sharingGroupUUID): return "owningUserId = \(owningUserId) AND sharingGroupUUID = '\(sharingGroupUUID)'" } } enum AddResult { case success(SharingGroupUserId) case error(String) } func add(sharingGroupUUID: String, userId: UserId, permission: Permission, owningUserId: UserId?) -> AddResult { let owningUserIdValue = owningUserId == nil ? "NULL" : "\(owningUserId!)" let query = "INSERT INTO \(tableName) (sharingGroupUUID, userId, permission, owningUserId) VALUES('\(sharingGroupUUID)', \(userId), '\(permission.rawValue)', \(owningUserIdValue));" if db.query(statement: query) { Log.info("Sucessfully created sharing user group") return .success(db.lastInsertId()) } else { let error = db.error Log.error("Could not insert into \(tableName): \(error)") return .error(error) } } func sharingGroupUsers(forSharingGroupUUID sharingGroupUUID: String) -> [SyncServerShared.SharingGroupUser]? { guard let users: [User] = sharingGroupUsers(forSharingGroupUUID: sharingGroupUUID) else { return nil } let result = users.map { user -> SyncServerShared.SharingGroupUser in let sharingGroupUser = SyncServerShared.SharingGroupUser() sharingGroupUser.name = user.username sharingGroupUser.userId = user.userId return sharingGroupUser } return result } func sharingGroupUsers(forSharingGroupUUID sharingGroupUUID: String) -> [User]? { let query = "select \(UserRepository.tableName).\(User.usernameKey), \(UserRepository.tableName).\(User.userIdKey), \(UserRepository.tableName).\(User.pushNotificationTopicKey) from \(tableName), \(UserRepository.tableName) where \(tableName).userId = \(UserRepository.tableName).userId and \(tableName).sharingGroupUUID = '\(sharingGroupUUID)'" return sharingGroupUsers(forSelectQuery: query) } // Number of rows in table or nil if there was an error. Only used in testing. #if DEBUG func count() -> Int? { let query = "SELECT * FROM \(tableName)" let users: [User]? = sharingGroupUsers(forSelectQuery: query) return users?.count } #endif private func sharingGroupUsers(forSelectQuery selectQuery: String) -> [User]? { guard let select = Select(db:db, query: selectQuery, modelInit: User.init, ignoreErrors:false) else { Log.error("Failed on Select: query: \(selectQuery)") return nil } var result:[User] = [] select.forEachRow { rowModel in let rowModel = rowModel as! User result.append(rowModel) } if select.forEachRowStatus == nil { return result } else { Log.error("Failed on forEachRowStatus: \(select.forEachRowStatus!)") return nil } } // To deal with deleting a user account-- any other users that have its user id as their owningUserId must have that owningUserId set to NULL. Don't just remove the invited/sharing user from SharingGroupUsers-- why not let them still download from the sharing group? func resetOwningUserIds(key: LookupKey) -> Bool { let query = "UPDATE \(tableName) SET owningUserId = NULL WHERE " + lookupConstraint(key: key) if db.query(statement: query) { let numberUpdates = db.numberAffectedRows() Log.info("\(numberUpdates) users had their owningUserId set to NULL.") return true } else { let error = db.error Log.error("Could not update row(s) for \(tableName): \(error)") return false } } } <file_sep>// // TestFiles.swift // ServerTests // // Created by <NAME> on 10/23/18. // import Foundation @testable import Server import XCTest import SyncServerShared struct TestFile { enum FileContents { case string(String) case url(URL) } let dropboxCheckSum:String let md5CheckSum:String // Google let sha1Hash: String // Microsoft let contents: FileContents let mimeType: MimeType func checkSum(type: AccountScheme.AccountName) -> String! { switch type { case AccountScheme.google.accountName: return md5CheckSum case AccountScheme.dropbox.accountName: return dropboxCheckSum case AccountScheme.facebook.accountName: return nil case AccountScheme.microsoft.accountName: return sha1Hash default: XCTFail() return nil } } static let test1 = TestFile( dropboxCheckSum: "42a873ac3abd02122d27e80486c6fa1ef78694e8505fcec9cbcc8a7728ba8949", md5CheckSum: "b10a8db164e0754105b7a99be72e3fe5", sha1Hash: "0A4D55A8D778E5022FAB701977C5D840BBC486D0", contents: .string("Hello World"), mimeType: .text) static let test2 = TestFile( dropboxCheckSum: "3e1c5665be7f2f5552efb9fd93df8fe9d58c54619fefe1a5b474e38464391011", md5CheckSum: "a9d2b23e3001e558213c4ee056f31ba1", sha1Hash: "3480185FC5811EC5F242E13B23E2D9274B080EF1", contents: .string("This is some longer text that I'm typing here and hopefullly I don't get too bored"), mimeType: .text) #if os(macOS) private static let catFileURL = URL(fileURLWithPath: "/tmp/Cat.jpg") #else private static let catFileURL = URL(fileURLWithPath: "./Resources/Cat.jpg") #endif static let catJpg = TestFile( dropboxCheckSum: "d342f6ab222c322e5fccf148435ef32bd676d7ce0baa72ea88593ef93bef8ac2", md5CheckSum: "5edb34be3781c079935b9314b4d3340d", sha1Hash: "41CA4AF2CE9C85D4F9969EA5D5C551D1FABD4857", contents: .url(catFileURL), mimeType: .jpeg) #if os(macOS) private static let urlFile = URL(fileURLWithPath: "/tmp/example.url") #else private static let urlFile = URL(fileURLWithPath: "./Resources/example.url") #endif // The specific hash values are obtained from bootstraps in the iOS client test cases. static let testUrlFile = TestFile( dropboxCheckSum: "842520e78cc66fad4ea3c5f24ad11734075d97d686ca10b799e726950ad065e7", md5CheckSum: "958c458be74acfcf327619387a8a82c4", sha1Hash: "92D74581DBCBC143ED68079A476CD770BE7E4BD9", contents: .url(urlFile), mimeType: .url) } <file_sep>Need to modify build image because of: 1) /root/SyncServerII/.build/checkouts/Perfect-LinuxBridge.git--87219909877364581/LinuxBridge/include/LinuxBridge.h:6:10: fatal error: 'uuid/uuid.h' file not found I added: `uuid-dev` 2) /root/SyncServerII/.build/checkouts/Perfect-mysqlclient-Linux.git--5648820300544252669/module.modulemap:2:12: error: header '/usr/include/mysql/mysql.h' not found header "/usr/include/mysql/mysql.h" I added: `libmysqlclient-dev` 3) TimeZone returns nil in my tests. See https://bugs.swift.org/browse/SR-4921 I added: `tzdata` (NOTE-- as of 6/17/18-- this is now in the Swift Docker image 4) I'm also adding `jq` because my test case runner (see runTests.sh) uses it. Note that this does *not* need to be in the run time image. Create the image based on the Dockerfile using: docker build -t swift-ubuntu:latest . docker tag swift-ubuntu:latest crspybits/swift-ubuntu:latest docker tag swift-ubuntu:latest crspybits/swift-ubuntu:5.0.1 docker push crspybits/swift-ubuntu:latest docker push crspybits/swift-ubuntu:5.0.1 Also relying on https://github.com/hopsoft/relay/wiki/How-to-Deploy-Docker-apps-to-Elastic-Beanstalk Run this with: docker run --rm -i -t -v /Users/chris/Desktop/Apps/:/root/Apps crspybits/swift-ubuntu:5.0.1 To figure out the IP address of the docker host: ip addr show eth0 See also https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach # To access mysql running on Docker host on MacOS for testing, use docker.for.mac.localhost for the mysql host. See https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach?noredirect=1&lq=1 6/10/19 I tried to get Ubuntu 18.04 working with Swift 5 and my server, but ran into a problem. I was getting the error "Parsed fewer bytes than were passed to the HTTP parser" during request parsing. See also https://github.com/IBM-Swift/Kitura/issues/1146 I have gone back to 16.04 and the server is working again. I wonder if this is at least part of the reason why IBM doesn't overtly support 18.04 in their released Docker images. <file_sep>// // FileController.swift // Server // // Created by <NAME> on 1/15/17. // // import Foundation import LoggerAPI import Credentials import CredentialsGoogle import SyncServerShared class FileController : ControllerProtocol { enum CheckError : Error { case couldNotConvertModelObject case errorLookingUpInFileIndex } // Result is nil if there is no existing file in the FileIndex. Throws an error if there is an error. static func checkForExistingFile(params:RequestProcessingParameters, sharingGroupUUID: String, fileUUID: String) throws -> FileIndex? { let key = FileIndexRepository.LookupKey.primaryKeys(sharingGroupUUID: sharingGroupUUID, fileUUID: fileUUID) let lookupResult = params.repos.fileIndex.lookup(key: key, modelInit: FileIndex.init) switch lookupResult { case .found(let modelObj): guard let fileIndexObj = modelObj as? FileIndex else { Log.error("Could not convert model object to FileIndex") throw CheckError.couldNotConvertModelObject } return fileIndexObj case .noObjectFound: return nil case .error(let error): Log.error("Error looking up file in FileIndex: \(error)") throw CheckError.errorLookingUpInFileIndex } } class func setup() -> Bool { return true } init() { } // OWNER static func getCreds(forUserId userId: UserId, from db: Database, delegate: AccountDelegate) -> Account? { let userKey = UserRepository.LookupKey.userId(userId) let userResults = UserRepository(db).lookup(key: userKey, modelInit: User.init) guard case .found(let model) = userResults, let user = model as? User else { Log.error("Could not get user from database.") return nil } guard var creds = user.credsObject else { Log.error("Could not get user creds.") return nil } creds.delegate = delegate return creds } func index(params:RequestProcessingParameters) { guard let indexRequest = params.request as? IndexRequest else { let message = "Did not receive IndexRequest" Log.error(message) params.completion(.failure(.message(message))) return } #if DEBUG if indexRequest.testServerSleep != nil { Log.info("Starting sleep (testServerSleep= \(indexRequest.testServerSleep!)).") Thread.sleep(forTimeInterval: TimeInterval(indexRequest.testServerSleep!)) Log.info("Finished sleep (testServerSleep= \(indexRequest.testServerSleep!)).") } #endif guard let groups = params.repos.sharingGroup.sharingGroups(forUserId: params.currentSignedInUser!.userId, sharingGroupUserRepo: params.repos.sharingGroupUser, userRepo: params.repos.user) else { let message = "Could not get sharing groups for user." Log.error(message) params.completion(.failure(.message(message))) return } let clientSharingGroups:[SyncServerShared.SharingGroup] = groups.map { serverGroup in return serverGroup.toClient() } guard let sharingGroupUUID = indexRequest.sharingGroupUUID else { // Not an error-- caller just didn't give a sharing group uuid-- only returning sharing group info. let response = IndexResponse() response.sharingGroups = clientSharingGroups params.completion(.success(response)) return } Log.info("Index: Getting file index for sharing group uuid: \(sharingGroupUUID)") // Not worrying about whether the sharing group is deleted-- where's the harm in getting a file index for a deleted sharing group? guard sharingGroupSecurityCheck(sharingGroupUUID: sharingGroupUUID, params: params, checkNotDeleted: false) else { let message = "Failed in sharing group security check." Log.error(message) params.completion(.failure(.message(message))) return } Controllers.getMasterVersion(sharingGroupUUID: sharingGroupUUID, params: params) { (error, masterVersion) in let fileIndexResult = params.repos.fileIndex.fileIndex(forSharingGroupUUID: sharingGroupUUID) switch fileIndexResult { case .fileIndex(let fileIndex): Log.info("Number of entries in FileIndex: \(fileIndex.count)") let response = IndexResponse() response.fileIndex = fileIndex response.masterVersion = masterVersion response.sharingGroups = clientSharingGroups params.completion(.success(response)) case .error(let error): let message = "Error: \(error)" Log.error(message) params.completion(.failure(.message(message))) return } } } func getUploads(params:RequestProcessingParameters) { guard let getUploadsRequest = params.request as? GetUploadsRequest else { let message = "Did not receive GetUploadsRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard sharingGroupSecurityCheck(sharingGroupUUID: getUploadsRequest.sharingGroupUUID, params: params) else { let message = "Failed in sharing group security check." Log.error(message) params.completion(.failure(.message(message))) return } let uploadsResult = params.repos.upload.uploadedFiles(forUserId: params.currentSignedInUser!.userId, sharingGroupUUID: getUploadsRequest.sharingGroupUUID, deviceUUID: params.deviceUUID!) switch uploadsResult { case .uploads(let uploads): let fileInfo = UploadRepository.uploadsToFileInfo(uploads: uploads) let response = GetUploadsResponse() response.uploads = fileInfo params.completion(.success(response)) case .error(let error): let message = "Error: \(String(describing: error))" Log.error(message) params.completion(.failure(.message(message))) return } } } <file_sep>// // MessageTests.swift // Server // // Created by <NAME> on 1/15/17. // // import XCTest @testable import Server import Foundation import SyncServerShared class MessageTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testIntConversions() { let uuidString1 = Foundation.UUID().uuidString let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = uuidString1 uploadRequest.mimeType = "text/plain" uploadRequest.fileVersion = FileVersionInt(1) uploadRequest.masterVersion = MasterVersionInt(42) uploadRequest.sharingGroupUUID = UUID().uuidString uploadRequest.checkSum = TestFile.test1.dropboxCheckSum guard uploadRequest.valid() else { XCTFail() return } XCTAssert(uploadRequest.fileVersion == 1) XCTAssert(uploadRequest.masterVersion == 42) } func testURLParameters() { let uuidString1 = Foundation.UUID().uuidString let sharingGroupUUID = UUID().uuidString let uploadRequest = UploadFileRequest() uploadRequest.checkSum = TestFile.test1.dropboxCheckSum uploadRequest.fileUUID = uuidString1 uploadRequest.fileVersion = FileVersionInt(1) uploadRequest.masterVersion = MasterVersionInt(42) uploadRequest.mimeType = "text/plain" uploadRequest.sharingGroupUUID = sharingGroupUUID guard let result = uploadRequest.urlParameters() else { XCTFail() return } let resultArray = result.components(separatedBy: "&") let expectedCheckSum = "checkSum=\(TestFile.test1.dropboxCheckSum)" let expectedFileUUID = "fileUUID=\(uuidString1)" let expectedFileVersion = "fileVersion=1" let expectedMasterVersion = "masterVersion=42" let expectedMimeType = "mimeType=text%2Fplain" let expectedSharingGroupUUID = "sharingGroupUUID=\(sharingGroupUUID)" XCTAssert(resultArray[0] == expectedCheckSum) XCTAssert(resultArray[1] == expectedFileUUID) XCTAssert(resultArray[2] == expectedFileVersion) XCTAssert(resultArray[3] == expectedMasterVersion) XCTAssert(resultArray[4] == expectedMimeType) XCTAssert(resultArray[5] == expectedSharingGroupUUID) let expected = expectedCheckSum + "&" + expectedFileUUID + "&" + expectedFileVersion + "&" + expectedMasterVersion + "&" + expectedMimeType + "&" + expectedSharingGroupUUID XCTAssert(result == expected, "Result was: \(String(describing: result))") } func testURLParametersForUploadDeletion() { let uuidString = Foundation.UUID().uuidString let sharingGroupUUID = UUID().uuidString let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uuidString uploadDeletionRequest.fileVersion = FileVersionInt(99) uploadDeletionRequest.masterVersion = MasterVersionInt(23) uploadDeletionRequest.actualDeletion = true uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID let result = uploadDeletionRequest.urlParameters() let expectedURLParams = "actualDeletion=1&" + "fileUUID=\(uuidString)&" + "fileVersion=99&" + "masterVersion=23&" + "sharingGroupUUID=\(sharingGroupUUID)" XCTAssert(result == expectedURLParams, "Expected: \(String(describing: expectedURLParams)); actual: \(String(describing: result))") } func testBadUUIDForFileName() { let sharingGroupUUID = UUID().uuidString let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = "foobar" uploadRequest.mimeType = "text/plain" uploadRequest.fileVersion = FileVersionInt(1) uploadRequest.masterVersion = MasterVersionInt(42) uploadRequest.sharingGroupUUID = sharingGroupUUID uploadRequest.checkSum = TestFile.test1.dropboxCheckSum XCTAssert(!uploadRequest.valid()) } func testPropertyHasValue() { let uuidString1 = Foundation.UUID().uuidString let sharingGroupUUID = UUID().uuidString let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = uuidString1 uploadRequest.mimeType = "text/plain" uploadRequest.fileVersion = FileVersionInt(1) uploadRequest.masterVersion = MasterVersionInt(42) uploadRequest.sharingGroupUUID = sharingGroupUUID uploadRequest.checkSum = TestFile.test1.dropboxCheckSum guard uploadRequest.valid() else { XCTFail() return } XCTAssert(uploadRequest.fileUUID == uuidString1) XCTAssert(uploadRequest.mimeType == "text/plain") XCTAssert(uploadRequest.fileVersion == FileVersionInt(1)) XCTAssert(uploadRequest.masterVersion == MasterVersionInt(42)) XCTAssert(uploadRequest.sharingGroupUUID == sharingGroupUUID) XCTAssert(uploadRequest.checkSum == TestFile.test1.dropboxCheckSum) } func testNonNilRequestMessageParams() { let upload = RedeemSharingInvitationRequest() upload.sharingInvitationUUID = "foobar" XCTAssert(upload.valid()) XCTAssert(upload.sharingInvitationUUID == "foobar") } // Because of some Linux problems I was having. func testDoneUploadsResponse() { let numberUploads = Int32(23) let response = DoneUploadsResponse() response.numberUploadsTransferred = numberUploads XCTAssert(response.numberUploadsTransferred == numberUploads) guard let jsonDict = response.toDictionary else { XCTFail() return } // Could not cast value of type 'Foundation.NSNumber' (0x7fd77dcf8188) to 'Swift.Int32' (0x7fd77e0c9b18). guard let response2 = try? DoneUploadsResponse.decode(jsonDict) else { XCTFail() return } XCTAssert(response2.numberUploadsTransferred == numberUploads) } func testValidGetSharingInvitationInfoRequest() { let request = GetSharingInvitationInfoRequest() request.sharingInvitationUUID = Foundation.UUID().uuidString XCTAssert(request.valid()) } func testInvalidGetSharingInvitationInfoRequest() { let request = GetSharingInvitationInfoRequest() request.sharingInvitationUUID = "foobar" XCTAssert(!request.valid()) } } extension MessageTests { static var allTests : [(String, (MessageTests) -> () throws -> Void)] { return [ ("testIntConversions", testIntConversions), ("testURLParameters", testURLParameters), ("testURLParametersForUploadDeletion", testURLParametersForUploadDeletion), ("testBadUUIDForFileName", testBadUUIDForFileName), ("testPropertyHasValue", testPropertyHasValue), ("testNonNilRequestMessageParams", testNonNilRequestMessageParams), ("testDoneUploadsResponse", testDoneUploadsResponse), ("testValidGetSharingInvitationInfoRequest", testValidGetSharingInvitationInfoRequest), ("testInvalidGetSharingInvitationInfoRequest", testInvalidGetSharingInvitationInfoRequest) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:MessageTests.self) } } <file_sep># Builds a Docker image for running SyncServer. FROM crspybits/swift-ubuntu-runtime:latest MAINTAINER <NAME>, LLC LABEL Description="Docker image for running SyncServer." USER root # This depends on the Server.json file using port 8080 for SyncServer. EXPOSE 8080 # The git tag of the deployed SyncServer -- this is for documentation, *and* is read when the server launches-- the server reports this back in healthchecks. ADD VERSION . # Binaries should have been compiled against the correct platform (i.e. Ubuntu 16.04). COPY .build/debug/Main /root/SyncServerII/.build/debug/Main # This depends on the Server.json file being copied into a directory that's mounted at /root/extras # For now, I'm also writing the server log to /root/extras. Later it would be nice to make it available over the web instead of having to sign-in to the server. # `stdbuf` gets rid of buffering to make it easier to tail the log; see also https://serverfault.com/questions/294218/is-there-a-way-to-redirect-output-to-a-file-without-buffering-on-unix-linux # CMD [ "sh", "-c", "cd /root/SyncServerII && ( stdbuf -o0 .build/debug/Main /root/extras/Server.json > /root/extras/output.log 2>&1 & )" ] CMD stdbuf -o0 /root/SyncServerII/.build/debug/Main /root/extras/Server.json > /root/extras/output.log 2>&1 <file_sep>// // UploadRepository.swift // Server // // Created by <NAME> on 1/16/17. // // // Persistent Storage for temporarily storing meta data for file uploads and file deletions before finally storing that info in the FileIndex. This also represents files that need to be purged from cloud storage-- this will be for losers of FileIndex update races and for upload deletions. import Foundation import SyncServerShared import LoggerAPI enum UploadState : String { case uploadingFile case uploadedFile case uploadingUndelete case uploadedUndelete case uploadingAppMetaData case toDeleteFromFileIndex static func maxCharacterLength() -> Int { return 22 } } class Upload : NSObject, Model, Filenaming { static let uploadIdKey = "uploadId" var uploadId: Int64! static let fileUUIDKey = "fileUUID" var fileUUID: String! static let userIdKey = "userId" // The userId of the uploading user. i.e., this is not necessarily the owning user id. var userId: UserId! // 3/15/18-- Can now be nil-- when we do an upload app meta data. Keeping it as `!` so it abides by the FileNaming protocol. static let fileVersionKey = "fileVersion" var fileVersion: FileVersionInt! static let deviceUUIDKey = "deviceUUID" var deviceUUID: String! static let fileGroupUUIDKey = "fileGroupUUID" // Not all files have to be associated with a file group. var fileGroupUUID:String? // Currently allowing files to be in exactly one sharing group. static let sharingGroupUUIDKey = "sharingGroupUUID" var sharingGroupUUID: String! // The following two dates are required for file uploads. static let creationDateKey = "creationDate" var creationDate:Date? // Mostly for future use since we're not yet allowing multiple file versions. static let updateDateKey = "updateDate" var updateDate:Date? static let stateKey = "state" var state:UploadState! static let appMetaDataKey = "appMetaData" var appMetaData: String? static let appMetaDataVersionKey = "appMetaDataVersion" var appMetaDataVersion: AppMetaDataVersionInt? // This is not present in upload deletions. static let mimeTypeKey = "mimeType" var mimeType: String? // Required only when the state is .uploaded static let lastUploadedCheckSumKey = "lastUploadedCheckSum" var lastUploadedCheckSum: String? subscript(key:String) -> Any? { set { switch key { case Upload.uploadIdKey: uploadId = newValue as! Int64? case Upload.fileUUIDKey: fileUUID = newValue as! String? case Upload.fileGroupUUIDKey: fileGroupUUID = newValue as! String? case Upload.sharingGroupUUIDKey: sharingGroupUUID = newValue as! String? case Upload.userIdKey: userId = newValue as! UserId? case Upload.fileVersionKey: fileVersion = newValue as! FileVersionInt? case Upload.deviceUUIDKey: deviceUUID = newValue as! String? case Upload.creationDateKey: creationDate = newValue as! Date? case Upload.updateDateKey: updateDate = newValue as! Date? case Upload.stateKey: state = newValue as! UploadState? case Upload.appMetaDataKey: appMetaData = newValue as! String? case Upload.appMetaDataVersionKey: appMetaDataVersion = newValue as! AppMetaDataVersionInt? case Upload.mimeTypeKey: mimeType = newValue as! String? case Upload.lastUploadedCheckSumKey: lastUploadedCheckSum = newValue as! String? default: Log.error("key: \(key)") assert(false) } } get { return getValue(forKey: key) } } func typeConvertersToModel(propertyName:String) -> ((_ propertyValue:Any) -> Any?)? { switch propertyName { case Upload.stateKey: return {(x:Any) -> Any? in return UploadState(rawValue: x as! String) } case Upload.creationDateKey: return {(x:Any) -> Any? in return DateExtras.date(x as! String, fromFormat: .DATETIME) } case Upload.updateDateKey: return {(x:Any) -> Any? in return DateExtras.date(x as! String, fromFormat: .DATETIME) } default: return nil } } } class UploadRepository : Repository, RepositoryLookup { private(set) var db:Database! required init(_ db:Database) { self.db = db } var tableName:String { return UploadRepository.tableName } static var tableName:String { return "Upload" } func upcreate() -> Database.TableUpcreateResult { let createColumns = "(uploadId BIGINT NOT NULL AUTO_INCREMENT, " + // Together, the next three fields form a unique key. The deviceUUID is needed because two devices using the same userId (i.e., the same owning user credentials) could be uploading the same file at the same time. // permanent reference to file (assigned by app) "fileUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + // reference into User table // TODO: *2* Make this a foreign reference. "userId BIGINT NOT NULL, " + // identifies a specific mobile device (assigned by app) "deviceUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + // identifies a group of files (assigned by app) "fileGroupUUID VARCHAR(\(Database.uuidLength)), " + "sharingGroupUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + // Not saying "NOT NULL" here only because in the first deployed version of the database, I didn't have these dates. Plus, upload deletions need not have dates. And when uploading a new version of a file we won't give the creationDate. "creationDate DATETIME," + "updateDate DATETIME," + // MIME type of the file; will be nil for UploadDeletion's. "mimeType VARCHAR(\(Database.maxMimeTypeLength)), " + // Optional app-specific meta data "appMetaData TEXT, " + // 3/25/18; This used to be `NOT NULL` but now allowing it to be NULL because when we upload an app meta data change, it will be null. "fileVersion INT, " + // Making this optional because appMetaData is optional. If there is app meta data, this must not be null. "appMetaDataVersion INT, " + "state VARCHAR(\(UploadState.maxCharacterLength())) NOT NULL, " + // Can be null if we create the Upload entry before actually uploading the file. "lastUploadedCheckSum TEXT, " + "FOREIGN KEY (sharingGroupUUID) REFERENCES \(SharingGroupRepository.tableName)(\(SharingGroup.sharingGroupUUIDKey)), " + // Not including fileVersion in the key because I don't want to allow the possiblity of uploading vN of a file and vM of a file at the same time. // This allows for the possibility of a client interleaving uploads to different sharing group UUID's (without interveneing DoneUploads) -- because the same fileUUID cannot appear in different sharing groups. "UNIQUE (fileUUID, userId, deviceUUID), " + "UNIQUE (uploadId))" let result = db.createTableIfNeeded(tableName: "\(tableName)", columnCreateQuery: createColumns) switch result { case .success(.alreadyPresent): // Table was already there. Do we need to update it? // Evolution 1: Are creationDate and updateDate present? If not, add them. if db.columnExists(Upload.creationDateKey, in: tableName) == false { if !db.addColumn("\(Upload.creationDateKey) DATETIME", to: tableName) { return .failure(.columnCreation) } } if db.columnExists(Upload.updateDateKey, in: tableName) == false { if !db.addColumn("\(Upload.updateDateKey) DATETIME", to: tableName) { return .failure(.columnCreation) } } // 2/25/18; Evolution 2: Remove the cloudFolderName column let cloudFolderNameKey = "cloudFolderName" if db.columnExists(cloudFolderNameKey, in: tableName) == true { if !db.removeColumn(cloudFolderNameKey, from: tableName) { return .failure(.columnRemoval) } } // 3/23/18; Evolution 3: Add the appMetaDataVersion column. if db.columnExists(Upload.appMetaDataVersionKey, in: tableName) == false { if !db.addColumn("\(Upload.appMetaDataVersionKey) INT", to: tableName) { return .failure(.columnCreation) } } if db.columnExists(Upload.fileGroupUUIDKey, in: tableName) == false { if !db.addColumn("\(Upload.fileGroupUUIDKey) VARCHAR(\(Database.uuidLength))", to: tableName) { return .failure(.columnCreation) } } default: break } return result } private func haveNilField(upload:Upload, fileInFileIndex: Bool) -> Bool { // Basic criteria-- applies across uploads and upload deletion. if upload.deviceUUID == nil || upload.fileUUID == nil || upload.userId == nil || upload.state == nil || upload.sharingGroupUUID == nil { return true } if upload.fileVersion == nil && upload.state != .uploadingAppMetaData { return true } if upload.state == .toDeleteFromFileIndex { return false } if upload.state == .uploadingAppMetaData { return upload.appMetaData == nil || upload.appMetaDataVersion == nil } // We're uploading a file if we get to here. Criteria only for file uploads: if upload.mimeType == nil || upload.updateDate == nil { return true } // The meta data and version must be nil or non-nil *together*. let metaDataNil = upload.appMetaData == nil let metaDataVersionNil = upload.appMetaDataVersion == nil if metaDataNil != metaDataVersionNil { return true } if !fileInFileIndex && upload.creationDate == nil { return true } if upload.state == .uploadingFile || upload.state == .uploadingUndelete { return false } // Have to have lastUploadedCheckSum when we're in the uploaded state. return upload.lastUploadedCheckSum == nil } enum AddResult: RetryRequest { case success(uploadId:Int64) case duplicateEntry case aModelValueWasNil case otherError(String) case deadlock case waitTimeout var shouldRetry: Bool { if case .deadlock = self { return true } if case .waitTimeout = self { return true } else { return false } } } // uploadId in the model is ignored and the automatically generated uploadId is returned if the add is successful. func add(upload:Upload, fileInFileIndex:Bool=false) -> AddResult { if haveNilField(upload: upload, fileInFileIndex:fileInFileIndex) { Log.error("One of the model values was nil!") return .aModelValueWasNil } // TODO: *2* Seems like we could use an encoding here to deal with sql injection issues. let (appMetaDataFieldValue, appMetaDataFieldName) = getInsertFieldValueAndName(fieldValue: upload.appMetaData, fieldName: Upload.appMetaDataKey) let (appMetaDataVersionFieldValue, appMetaDataVersionFieldName) = getInsertFieldValueAndName(fieldValue: upload.appMetaDataVersion, fieldName: Upload.appMetaDataVersionKey, fieldIsString:false) let (fileGroupUUIDFieldValue, fileGroupUUIDFieldName) = getInsertFieldValueAndName(fieldValue: upload.fileGroupUUID, fieldName: Upload.fileGroupUUIDKey) let (lastUploadedCheckSumFieldValue, lastUploadedCheckSumFieldName) = getInsertFieldValueAndName(fieldValue: upload.lastUploadedCheckSum, fieldName: Upload.lastUploadedCheckSumKey) let (mimeTypeFieldValue, mimeTypeFieldName) = getInsertFieldValueAndName(fieldValue: upload.mimeType, fieldName: Upload.mimeTypeKey) var creationDateValue:String? var updateDateValue:String? if upload.creationDate != nil { creationDateValue = DateExtras.date(upload.creationDate!, toFormat: .DATETIME) } if upload.updateDate != nil { updateDateValue = DateExtras.date(upload.updateDate!, toFormat: .DATETIME) } let (creationDateFieldValue, creationDateFieldName) = getInsertFieldValueAndName(fieldValue: creationDateValue, fieldName: Upload.creationDateKey) let (updateDateFieldValue, updateDateFieldName) = getInsertFieldValueAndName(fieldValue: updateDateValue, fieldName: Upload.updateDateKey) let (fileVersionFieldValue, fileVersionFieldName) = getInsertFieldValueAndName(fieldValue: upload.fileVersion, fieldName: Upload.fileVersionKey, fieldIsString:false) let query = "INSERT INTO \(tableName) (\(Upload.fileUUIDKey), \(Upload.userIdKey), \(Upload.deviceUUIDKey), \(Upload.stateKey), \(Upload.sharingGroupUUIDKey) \(creationDateFieldName) \(updateDateFieldName) \(lastUploadedCheckSumFieldName) \(mimeTypeFieldName) \(appMetaDataFieldName) \(appMetaDataVersionFieldName) \(fileVersionFieldName) \(fileGroupUUIDFieldName)) VALUES('\(upload.fileUUID!)', \(upload.userId!), '\(upload.deviceUUID!)', '\(upload.state!.rawValue)', '\(upload.sharingGroupUUID!)' \(creationDateFieldValue) \(updateDateFieldValue) \(lastUploadedCheckSumFieldValue) \(mimeTypeFieldValue) \(appMetaDataFieldValue) \(appMetaDataVersionFieldValue) \(fileVersionFieldValue) \(fileGroupUUIDFieldValue));" if db.query(statement: query) { return .success(uploadId: db.lastInsertId()) } else if db.errorCode() == Database.deadlockError { return .deadlock } else if db.errorCode() == Database.lockWaitTimeout { return .waitTimeout } else if db.errorCode() == Database.duplicateEntryForKey { return .duplicateEntry } else { let error = db.error let message = "Could not insert into \(tableName): \(error)" Log.error(message) return .otherError(message) } } // The Upload model *must* have an uploadId func update(upload:Upload, fileInFileIndex:Bool=false) -> Bool { if upload.uploadId == nil || haveNilField(upload: upload, fileInFileIndex:fileInFileIndex) { Log.error("One of the model values was nil!") return false } // TODO: *2* Seems like we could use an encoding here to deal with sql injection issues. let appMetaDataField = getUpdateFieldSetter(fieldValue: upload.appMetaData, fieldName: Upload.appMetaDataKey) let lastUploadedCheckSumField = getUpdateFieldSetter(fieldValue: upload.lastUploadedCheckSum, fieldName: Upload.lastUploadedCheckSumKey) let mimeTypeField = getUpdateFieldSetter(fieldValue: upload.mimeType, fieldName: Upload.mimeTypeKey) let fileGroupUUIDField = getUpdateFieldSetter(fieldValue: upload.fileGroupUUID, fieldName: Upload.fileGroupUUIDKey) let query = "UPDATE \(tableName) SET fileUUID='\(upload.fileUUID!)', userId=\(upload.userId!), fileVersion=\(upload.fileVersion!), state='\(upload.state!.rawValue)', deviceUUID='\(upload.deviceUUID!)' \(lastUploadedCheckSumField) \(appMetaDataField) \(mimeTypeField) \(fileGroupUUIDField) WHERE uploadId=\(upload.uploadId!)" if db.query(statement: query) { // "When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows may not actually equal the number of rows matched, only the number of rows that were literally affected by the query." From: https://dev.mysql.com/doc/apis-php/en/apis-php-function.mysql-affected-rows.html if db.numberAffectedRows() <= 1 { return true } else { Log.error("Did not have <= 1 row updated: \(db.numberAffectedRows())") return false } } else { let error = db.error Log.error("Could not update \(tableName): \(error)") return false } } enum LookupKey : CustomStringConvertible { case uploadId(Int64) case fileUUID(String) case userId(UserId) case filesForUserDevice(userId:UserId, deviceUUID:String, sharingGroupUUID: String) case primaryKey(fileUUID:String, userId:UserId, deviceUUID:String) var description : String { switch self { case .uploadId(let uploadId): return "uploadId(\(uploadId))" case .fileUUID(let fileUUID): return "fileUUID(\(fileUUID))" case .userId(let userId): return "userId(\(userId))" case .filesForUserDevice(let userId, let deviceUUID, let sharingGroupUUID): return "userId(\(userId)); deviceUUID(\(deviceUUID)); sharingGroupUUID(\(sharingGroupUUID))" case .primaryKey(let fileUUID, let userId, let deviceUUID): return "fileUUID(\(fileUUID)); userId(\(userId)); deviceUUID(\(deviceUUID))" } } } func lookupConstraint(key:LookupKey) -> String { switch key { case .uploadId(let uploadId): return "uploadId = '\(uploadId)'" case .fileUUID(let fileUUID): return "fileUUID = '\(fileUUID)'" case .userId(let userId): return "userId = '\(userId)'" case .filesForUserDevice(let userId, let deviceUUID, let sharingGroupUUID): return "userId = \(userId) and deviceUUID = '\(deviceUUID)' and sharingGroupUUID = '\(sharingGroupUUID)'" case .primaryKey(let fileUUID, let userId, let deviceUUID): return "fileUUID = '\(fileUUID)' and userId = \(userId) and deviceUUID = '\(deviceUUID)'" } } func select(forUserId userId: UserId, sharingGroupUUID: String, deviceUUID:String, andState state:UploadState? = nil) -> Select? { var query = "select * from \(tableName) where userId=\(userId) and sharingGroupUUID = '\(sharingGroupUUID)' and deviceUUID='\(deviceUUID)'" if state != nil { query += " and state='\(state!.rawValue)'" } return Select(db:db, query: query, modelInit: Upload.init, ignoreErrors:false) } enum UploadedFilesResult { case uploads([Upload]) case error(Swift.Error?) } // With nil `andState` parameter value, returns both file uploads and upload deletions. func uploadedFiles(forUserId userId: UserId, sharingGroupUUID: String, deviceUUID: String, andState state:UploadState? = nil) -> UploadedFilesResult { guard let selectUploadedFiles = select(forUserId: userId, sharingGroupUUID: sharingGroupUUID, deviceUUID: deviceUUID, andState: state) else { return .error(nil) } var result:[Upload] = [] selectUploadedFiles.forEachRow { rowModel in let rowModel = rowModel as! Upload result.append(rowModel) } if selectUploadedFiles.forEachRowStatus == nil { return .uploads(result) } else { return .error(selectUploadedFiles.forEachRowStatus!) } } static func uploadsToFileInfo(uploads: [Upload]) -> [FileInfo] { var result = [FileInfo]() for upload in uploads { let fileInfo = FileInfo() fileInfo.fileUUID = upload.fileUUID fileInfo.fileVersion = upload.fileVersion fileInfo.deleted = upload.state == .toDeleteFromFileIndex fileInfo.mimeType = upload.mimeType fileInfo.creationDate = upload.creationDate fileInfo.updateDate = upload.updateDate fileInfo.fileGroupUUID = upload.fileGroupUUID fileInfo.sharingGroupUUID = upload.sharingGroupUUID result += [fileInfo] } return result } static func isValidAppMetaDataUpload(currServerAppMetaDataVersion: AppMetaDataVersionInt?, currServerAppMetaData: String?, optionalUpload appMetaData:AppMetaData?) -> Bool { if appMetaData == nil { // Doesn't matter what the current app meta data is-- we're not changing it. return true } else { return isValidAppMetaDataUpload(currServerAppMetaDataVersion: currServerAppMetaDataVersion, currServerAppMetaData: currServerAppMetaData, upload: appMetaData!) } } static func isValidAppMetaDataUpload(currServerAppMetaDataVersion: AppMetaDataVersionInt?, currServerAppMetaData: String?, upload appMetaData:AppMetaData) -> Bool { if currServerAppMetaDataVersion == nil { // No app meta data yet on server for this file. Need 0 first version. return appMetaData.version == 0 } else { // Already have app meta data on server-- must have next version. return appMetaData.version == currServerAppMetaDataVersion! + 1 } } } <file_sep>-- Modified from https://stackoverflow.com/questions/6121917/automatic-rollback-if-commit-transaction-is-not-reached -- Exporting from AWS RDS -- mysqldump -h url.for.db -P 3306 -u username --databases dbname > dump.sql -- importing to local db -- mysql -u root -p < ~/Desktop/dump.sql -- drop table DeviceUUID; drop table ShortLocks; drop table FileIndex; drop table MasterVersion; drop table SharingGroupUser; drop table Upload; drop table User; drop table SharingInvitation; drop table SharingGroup; -- delete from DeviceUUID; delete from ShortLocks; delete from FileIndex; delete from MasterVersion; delete from SharingGroupUser; delete from Upload; delete from User; delete from SharingInvitation; delete from SharingGroup; delimiter // create procedure migration() begin DECLARE exit handler for sqlexception BEGIN GET DIAGNOSTICS CONDITION 1 @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT; SELECT @p1, @p2, "ERROR999"; ROLLBACK; END; DECLARE exit handler for sqlwarning BEGIN GET DIAGNOSTICS CONDITION 1 @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT; SELECT @p1, @p2, "ERROR999"; ROLLBACK; END; START TRANSACTION; -- Add sharing group name column to SharingGroup table. ALTER TABLE SharingGroup ADD COLUMN sharingGroupName VARCHAR(255); -- **************************************** -- Give the existing sharing groups names. -- **************************************** -- 1) Need to check these numbers, -- and 2) make sure there are only three of these. SET @RodDanyNatashaMeSharingGroupId := 1; SET @AppleReviewSharingGroupId := 2; SET @ChrisDropboxSharingGroupId := 3; SET @RodDanyNatashaMeSharingGroupName := "Louisiana Guys"; SET @AppleReviewSharingGroupName := "Apple Review"; SET @ChrisDropboxSharingGroupName := "Chris Dropbox"; UPDATE SharingGroup SET sharingGroupName = @RodDanyNatashaMeSharingGroupName WHERE sharingGroupId = @RodDanyNatashaMeSharingGroupId; UPDATE SharingGroup SET sharingGroupName = @AppleReviewSharingGroupName WHERE sharingGroupId = @AppleReviewSharingGroupId; UPDATE SharingGroup SET sharingGroupName = @ChrisDropboxSharingGroupName WHERE sharingGroupId = @ChrisDropboxSharingGroupId; -- **************************************** -- Add deleted column to SharingGroup table -- Set the current sharing groups to have this set to 0. -- **************************************** ALTER TABLE SharingGroup ADD COLUMN deleted BOOL NOT NULL DEFAULT FALSE; -- Now we're back to the IMPLICIT DEFAULT ALTER TABLE SharingGroup ALTER deleted DROP DEFAULT; -- **************************************** -- Need to change permissions from being in User table to being in SharingGroupUser table. -- **************************************** -- 1) Add permissions column in SharingGroupUser ALTER TABLE SharingGroupUser ADD COLUMN permission VARCHAR(5); -- 2) Copy over data to new column. -- See https://stackoverflow.com/questions/11709043/mysql-update-column-with-value-from-another-table UPDATE SharingGroupUser INNER JOIN User ON SharingGroupUser.userId = User.userId SET SharingGroupUser.permission = User.permission; -- 3) Remove old column from User table. ALTER TABLE User DROP COLUMN permission; -- **************************************** -- Move owningUserId from User table to SharingGroupUser table. -- **************************************** -- Without the FK name, I get: -- ERROR 1050 (42S01): Table './syncserver_sharedimages/sharinggroupuser' already exists ALTER TABLE SharingGroupUser ADD COLUMN owningUserId BIGINT, ADD CONSTRAINT `SharingGroupUser_ibfk_5` FOREIGN KEY (owningUserId) REFERENCES User(userId); UPDATE SharingGroupUser INNER JOIN User ON SharingGroupUser.userId = User.userId SET SharingGroupUser.owningUserId = User.owningUserId; ALTER TABLE User DROP COLUMN owningUserId; -- **************************************** -- All tables that use sharingGroupId, change to sharingGroupUUID -- SharingGroup -- MasterVersion -- SharingGroupUser -- FileIndex -- SharingInvitation -- ShortLocks -- Upload -- May have to do this by first adding a new sharingGroupUUID column, populating values, and then later dropping the SharingGroupId columns. -- **************************************** -- 1) SharingGroup ALTER TABLE SharingGroup ADD COLUMN sharingGroupUUID VARCHAR(36); SET @RodDanyNatashaMeSharingGroupUUID := "DB1DECB5-F2D6-441E-8D6A-4A6AF93216DB"; SET @AppleReviewSharingGroupUUID := "61944E02-E76E-4937-8FE6-8BDF6F2D983E"; SET @ChrisDropboxSharingGroupUUID := "1D12B154-A9EB-4B63-AC85-E4BB83DD680D"; UPDATE SharingGroup SET sharingGroupUUID = @RodDanyNatashaMeSharingGroupUUID WHERE sharingGroupId = @RodDanyNatashaMeSharingGroupId; UPDATE SharingGroup SET sharingGroupUUID = @AppleReviewSharingGroupUUID WHERE sharingGroupId = @AppleReviewSharingGroupId; UPDATE SharingGroup SET sharingGroupUUID = @ChrisDropboxSharingGroupUUID WHERE sharingGroupId = @ChrisDropboxSharingGroupId; -- Add NOT NULL not back to SharingGroup. ALTER TABLE SharingGroup MODIFY sharingGroupUUID VARCHAR(36) NOT NULL; -- Add unique key on sharingGroupUUID ALTER TABLE SharingGroup ADD CONSTRAINT UNIQUE (sharingGroupUUID); -- 2) MasterVersion ALTER TABLE MasterVersion ADD COLUMN sharingGroupUUID VARCHAR(36); UPDATE MasterVersion INNER JOIN SharingGroup ON MasterVersion.sharingGroupId = SharingGroup.sharingGroupId SET MasterVersion.sharingGroupUUID = SharingGroup.sharingGroupUUID; ALTER TABLE MasterVersion MODIFY sharingGroupUUID VARCHAR(36) NOT NULL; ALTER TABLE MasterVersion ADD CONSTRAINT UNIQUE (sharingGroupUUID), ADD CONSTRAINT `MasterVersion_ibfk_2` FOREIGN KEY (sharingGroupUUID) REFERENCES SharingGroup(sharingGroupUUID); ALTER TABLE MasterVersion DROP FOREIGN KEY `MasterVersion_ibfk_1`; ALTER TABLE MasterVersion DROP COLUMN sharingGroupId; -- 3) SharingGroupUser ALTER TABLE SharingGroupUser ADD COLUMN sharingGroupUUID VARCHAR(36); UPDATE SharingGroupUser INNER JOIN SharingGroup ON SharingGroupUser.sharingGroupId = SharingGroup.sharingGroupId SET SharingGroupUser.sharingGroupUUID = SharingGroup.sharingGroupUUID; ALTER TABLE SharingGroupUser MODIFY sharingGroupUUID VARCHAR(36) NOT NULL; ALTER TABLE SharingGroupUser ADD CONSTRAINT `SharingGroupUser_ibfk_4` FOREIGN KEY (sharingGroupUUID) REFERENCES SharingGroup(sharingGroupUUID); ALTER TABLE SharingGroupUser ADD CONSTRAINT UNIQUE (sharingGroupUUID, userId); ALTER TABLE SharingGroupUser DROP FOREIGN KEY `SharingGroupUser_ibfk_2`; ALTER TABLE SharingGroupUser DROP INDEX sharingGroupId; ALTER TABLE SharingGroupUser DROP COLUMN sharingGroupId; -- 4) FileIndex ALTER TABLE FileIndex ADD COLUMN sharingGroupUUID VARCHAR(36); UPDATE FileIndex INNER JOIN SharingGroup ON FileIndex.sharingGroupId = SharingGroup.sharingGroupId SET FileIndex.sharingGroupUUID = SharingGroup.sharingGroupUUID; ALTER TABLE FileIndex MODIFY sharingGroupUUID VARCHAR(36) NOT NULL; ALTER TABLE FileIndex ADD CONSTRAINT `FileIndex_ibfk_2` FOREIGN KEY (sharingGroupUUID) REFERENCES SharingGroup(sharingGroupUUID); ALTER TABLE FileIndex ADD CONSTRAINT UNIQUE (fileUUID, sharingGroupUUID); ALTER TABLE FileIndex DROP FOREIGN KEY `FileIndex_ibfk_1`; ALTER TABLE FileIndex DROP COLUMN sharingGroupId; -- Get left with a unique key on fileUUID; remove it after removing sharingGroupId. ALTER TABLE FileIndex DROP INDEX fileUUID; -- 5) SharingInvitation -- Need to delete rows from SharingInvitation first DELETE FROM SharingInvitation; ALTER TABLE SharingInvitation ADD COLUMN sharingGroupUUID VARCHAR(36) NOT NULL, ADD CONSTRAINT `SharingInvitation_ibfk_2` FOREIGN KEY (sharingGroupUUID) REFERENCES SharingGroup(sharingGroupUUID); ALTER TABLE SharingInvitation DROP FOREIGN KEY `SharingInvitation_ibfk_1`; ALTER TABLE SharingInvitation DROP COLUMN sharingGroupId; -- 6) ShortLocks DELETE FROM ShortLocks; ALTER TABLE ShortLocks ADD COLUMN sharingGroupUUID VARCHAR(36) NOT NULL, ADD CONSTRAINT UNIQUE (sharingGroupUUID), ADD CONSTRAINT `ShortLocks_ibfk_2` FOREIGN KEY (sharingGroupUUID) REFERENCES SharingGroup(sharingGroupUUID); ALTER TABLE ShortLocks DROP FOREIGN KEY `ShortLocks_ibfk_1`; ALTER TABLE ShortLocks DROP COLUMN sharingGroupId; -- 7) Upload DELETE FROM Upload; ALTER TABLE Upload ADD COLUMN sharingGroupUUID VARCHAR(36) NOT NULL, ADD CONSTRAINT `Upload_ibfk_2` FOREIGN KEY (sharingGroupUUID) REFERENCES SharingGroup(sharingGroupUUID); ALTER TABLE Upload DROP FOREIGN KEY `Upload_ibfk_1`; ALTER TABLE Upload DROP COLUMN sharingGroupId; -- **************************************** -- Remove sharingGroupId column on SharingGroup -- **************************************** ALTER TABLE SharingGroup DROP COLUMN sharingGroupId; COMMIT; end// delimiter ; Use SyncServer_SharedImages; call migration(); drop procedure migration; <file_sep>#!/bin/bash # Usage: # arg1: the name of the .json configuration file for the server # arg2: The name of the sql script. # arg3: (optional) host-- replaces the host from the configuration file. # e.g., ./Migrations/migrate.sh ~/Desktop/Apps/SyncServerII/Private/Server/SharedImages-local.json Migrations/9.sql localhost # e.g., ./Migrations/migrate.sh ~/Desktop/Apps/SyncServerII/Private/Server.json.aws.app.bundles/Neebla-production.json Migrations/9.sql CONFIG_FILE=$1 SQL_SCRIPT=$2 CMD_LINE_HOST=$3 DBNAME=`jq -r '.["mySQL.database"]' < ${CONFIG_FILE}` USER=`jq -r '.["mySQL.user"]' < ${CONFIG_FILE}` PASSWORD=`jq -r '.["mySQL.password"]' < ${CONFIG_FILE}` HOST=`jq -r '.["mySQL.host"]' < ${CONFIG_FILE}` if [ "empty$CMD_LINE_HOST" != "empty" ]; then HOST=$CMD_LINE_HOST fi echo "Migrating $DBNAME on $HOST" result=$(mysql -P 3306 -p --user="$USER" --password="$<PASSWORD>" --host="$HOST" --database="$DBNAME" < "$SQL_SCRIPT" 2>&1 ) # I've embedded "ERROR999" to be output from the sql script -- when an error and subsequent rollback occurs. ERROR=`echo $result | grep ERROR999` if [ "empty$ERROR" = "empty" ]; then SUCCESS=`echo $result | grep SUCCESS123` # Didn't have ERROR string-- presumably no error. if [ "empty$SUCCESS" = "empty" ]; then # Didn't find SUCCESS string-- must have error. echo "**** Failure running migration, despite no error marker *******" echo $result else echo "Success running migration" fi else echo "**** Failure running migration (with error marker) *******" echo $result fi <file_sep>SETTING UP A VPC =============== Be aware that this technique is somewhat arduous (if you find one simpler, *please* let me know!). It is something you could do just once though, and not each time you startup your server. I am not sure, but I *think* the ony expense of keeping this VPC around is the cost of the Elastic IP (see below; but see https://aws.amazon.com/vpc/pricing/). Also, I am not sure, but I suspect you need one of these VPC's and associated subnets etc. for each of your servers. 1. I started with the directions at http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/vpc-rds.html to create a "VPC with a Public and Private Subnet". * In the part where it talks about "Elastic IP Allocation ID" I had to first use the AWS console GUI to allocate an Elastic IP. You can find this under the EC2 Dashboard. * In order to create the DBSubnet, I had to create another private subnet for the VPC. In a different availability zone because of an error I got when creating the DBSubnet. 2. Creating your database. While it does seem possible to apply these VPC changes to an existing database (see https://aws.amazon.com/premiumsupport/knowledge-center/change-vpc-rds-db-instance/), I haven't yet had success with that. What has worked for me is to create a new database. * When creating the database, use your new VPC and DB subnet group. * Create a new security group, for the database, for the new VPC. * Change this new database security group by adding a custom rule that allows ingress from your databases security group. Seems odd, but you're going to also use that security group in your configure.yml. Note down the name of that security group. E.g., sg-d8e99ea3 3. Changes to `configure.yml`. You'll need to make specific changes to this file for your VPC. These changes are given in http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/vpc-rds.html in the section "Deploying with the AWS Toolkits, Eb, CLI, or API" see EBSEnvironments/sharedimages-staging/configure-vpc.yml, which is a full example of yml parameters for setting up a VPC. You'll need to make these changes before zipping up your application bundle. 4. After thoughts. This has worked for me. The only issue I can see is that the EC2 instance doesn't have public DNS access. Perhaps this is because of the way I set up the VPC? The drawback of this for now is that I can't access the server logs, which are just stored locally on the EC2 instance. Which will make debugging more difficult. Either I'll need to make the EC2 instance have a public DNS access, or I'll have to make the logs publicly accessible some other way.<file_sep>// // GeneralDatabaseTests.swift // Server // // Created by <NAME> on 12/6/16. // // import XCTest @testable import Server import LoggerAPI import HeliumLogger import Foundation import SyncServerShared class model : Model { var c1: String! var c2: String! var c3: String! var c4: String! var c5: String! var c6: String! // Insert a mySQL TINYINT as a Model Int8 var c7: Int8! // Insert a mySQL SMALLINT as a Model Int16 var c8: Int16! // Insert a mySQL MEDIUMINT as a Model Int32 var c9: Int32! // Insert a mySQL INT as a Model Int32 var c10: Int32! // // Insert a mySQL BIGINT as a Model Int64 var c11: Int64! var c12: Float! // Insert a mySQL FLOAT as a Model Float var c13: Double! // Insert a mySQL DOUBLE as a Model Double // Perfect MySQL interface doesn't play well with Decimals. It returns Strings. Odd. // var c14: Decimal! // Dates must be inserted as Strings, and they are returned by mySQL as Strings. // The Database class will have helper methods to convert Dates <-> Strings in the needed formats. var c15: String! // Insert mySQL DATE in format: '2013-12-31' var c16: String! // Insert mySQL DATETIME in format: '2013-12-31 11:30:45' var c17: String! // Insert mySQL TIMESTAMP in format: '2013-12-31 11:30:45' var c18: String! // Insert mySQL TIME in format: '11:30:45' subscript(key:String) -> Any? { set { switch key { case "c1": c1 = newValue as! String? case "c2": c2 = newValue as! String? case "c3": c3 = newValue as! String? case "c4": c4 = newValue as! String? case "c5": c5 = newValue as! String? case "c6": c6 = newValue as! String? case "c7": c7 = newValue as! Int8? case "c8": c8 = newValue as! Int16? case "c9": c9 = newValue as! Int32? case "c10": c10 = newValue as! Int32? case "c11": c11 = newValue as! Int64? case "c12": c12 = newValue as! Float? case "c13": c13 = newValue as! Double? //case "c14": // break case "c15": c15 = newValue as! String? case "c16": c16 = newValue as! String? case "c17": c17 = newValue as! String? case "c18": c18 = newValue as! String? default: assert(false) } } get { return getValue(forKey:key) } } } enum TestEnum : String { case TestEnum1 case TestEnum2 } class model2 : Model { var c1: TestEnum! var c2: Date! subscript(key:String) -> Any? { set { switch key { case "c1": c1 = newValue as! TestEnum? case "c2": c2 = newValue as! Date? default: assert(false) } } get { return getValue(forKey:key) } } func typeConvertersToModel(propertyName:String) -> ((_ propertyValue:Any) -> Any?)? { switch propertyName { case "c1": return {(x:Any) -> Any? in return TestEnum(rawValue: x as! String) } case "c2": return {(x:Any) -> Any? in return DateExtras.date(x as! String, fromFormat: .DATE) } default: return nil } } } class GeneralDatabaseTests: ServerTestCase, LinuxTestable { let c1Value = "a" let c2Value = "bc" let c3Value = "def" let c4Value = "ghik" let c5Value = "1" let c6Value = "12" let c7Value:Int8 = 1 let c8Value:Int16 = 5 let c9Value:Int32 = 42 let c10Value:Int32 = 78 let c11Value:Int64 = 100 let c12Value = Float(43.1) let c13Value = Double(12.2) //let c14Value = Decimal(12.112) let c15Value = Date() let c16Value = Date() let c17Value = Date() let c18Value = Date() var c15String:String! var c16String:String! var c17String:String! var c18String:String! let testTableName = "TestTable12345" let testTableName2 = "TestTable6789" static let testTableName3 = "TestTableABC" let c2Table2Value = Date() override func setUp() { super.setUp() Log.info("Starting setUp") c15String = DateExtras.date(c15Value, toFormat: .DATE) c16String = DateExtras.date(c16Value, toFormat: .DATETIME) c17String = DateExtras.date(c17Value, toFormat: .TIMESTAMP) c18String = DateExtras.date(c18Value, toFormat: .TIME) // Ignore any failure in dropping: E.g., a failure resulting from the table not existing the first time around. let _ = db.query(statement: "DROP TABLE \(testTableName)") let _ = db.query(statement: "DROP TABLE \(testTableName2)") let _ = db.query(statement: "DROP TABLE \(GeneralDatabaseTests.testTableName3)") XCTAssert(createTable()) XCTAssert(createTable2()) XCTAssert(createTable3()) insertRows() insertRows2() Log.info("Completed setUp") } func createTable() -> Bool { let createColumns = "(c1 CHAR(5), " + "c2 VARCHAR(100)," + "c3 TINYTEXT," + "c4 TEXT," + "c5 MEDIUMTEXT," + "c6 LONGTEXT," + "c7 TINYINT(1)," + "c8 SMALLINT(2)," + "c9 MEDIUMINT(3)," + "c10 INT(3)," + "c11 BIGINT," + "c12 FLOAT," + "c13 DOUBLE," + //"c14 DECIMAL(5, 3)," + "c15 DATE," + "c16 DATETIME," + "c17 TIMESTAMP," + "c18 TIME)" if case .success(.created) = db.createTableIfNeeded(tableName: testTableName, columnCreateQuery: createColumns) { return true } else { return false } } func createTable2() -> Bool { let createColumns = "(c1 VARCHAR(100), " + "c2 DATE)" if case .success(.created) = db.createTableIfNeeded(tableName: testTableName2, columnCreateQuery: createColumns) { return true } else { return false } } class Table3 : RepositoryBasics { var db: Database! let tableName = GeneralDatabaseTests.testTableName3 static var tableName = GeneralDatabaseTests.testTableName3 } func createTable3() -> Bool { let createColumns = "(c1 VARCHAR(100), " + "c2 INT(3), " + "c3 INT(2), " + "c4 BOOL)" if case .success(.created) = db.createTableIfNeeded(tableName: GeneralDatabaseTests.testTableName3, columnCreateQuery: createColumns) { return true } else { return false } } func insertRows() { // Make sure NULL values can be handled. let insertRow1 = "INSERT INTO \(testTableName) (c1, c2, c3, c4) VALUES('\(c1Value)', '\(c2Value)', '\(c3Value)', '\(c4Value)');" guard db.query(statement: insertRow1) else { XCTFail(db.errorMessage()) return } let insertRow2 = "INSERT INTO \(testTableName) (c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c15, c16, c17, c18) VALUES('\(c1Value)', '\(c2Value)', '\(c3Value)', '\(c4Value)','\(c5Value)', '\(c6Value)', '\(c7Value)', '\(c8Value)','\(c9Value)', '\(c10Value)', '\(c11Value)', '\(c12Value)', '\(c13Value)', '\(c15String!)', '\(c16String!)', '\(c17String!)', '\(c18String!)');" Log.debug(insertRow2) guard db.query(statement: insertRow2) else { XCTFail(db.errorMessage()) return } } func insertRows2() { let c1Value:TestEnum = .TestEnum1 let c2Value = DateExtras.date(c2Table2Value, toFormat: .DATE) let insertRow1 = "INSERT INTO \(testTableName2) (c1, c2) VALUES('\(c1Value.rawValue)', '\(c2Value)');" guard db.query(statement: insertRow1) else { XCTFail(db.errorMessage()) return } } func runSelectTestForEachRow(ignoreErrors:Bool) { let query = "select * from \(testTableName)" guard let select = Select(db:db, query: query, modelInit: model.init, ignoreErrors:ignoreErrors) else { XCTFail() return } var row = 1 select.forEachRow { rowModel in let rowModel = rowModel as! model XCTAssert(rowModel.c1 == self.c1Value, "Value was not \(self.c1Value)") XCTAssert(rowModel.c2 == self.c2Value, "Value was not \(self.c2Value)") XCTAssert(rowModel.c3 == self.c3Value, "Value was not \(self.c3Value)") XCTAssert(rowModel.c4 == self.c4Value, "Value was not \(self.c4Value)") if row == 2 { XCTAssert(rowModel.c5 == self.c5Value, "Value was not \(self.c5Value)") XCTAssert(rowModel.c6 == self.c6Value, "Value was not \(self.c6Value)") XCTAssert(rowModel.c7 == self.c7Value, "Value was not \(self.c7Value)") XCTAssert(rowModel.c8 == self.c8Value, "Value was not \(self.c8Value)") XCTAssert(rowModel.c9 == self.c9Value, "Value was not \(self.c9Value)") XCTAssert(rowModel.c10 == self.c10Value, "Value was not \(self.c10Value)") XCTAssert(rowModel.c11 == self.c11Value, "Value was not \(self.c11Value)") XCTAssert(rowModel.c12 == self.c12Value, "Value was not \(self.c12Value)") XCTAssert(rowModel.c13 == self.c13Value, "Value was not \(self.c13Value)") //XCTAssert(rowModel.c14 == self.c14Value, "Value was not \(self.c14Value)") XCTAssert(rowModel.c15 == self.c15String, "Value was not \(String(describing: self.c15String))") XCTAssert(rowModel.c16 == self.c16String, "Value was not \(String(describing: self.c16String))") XCTAssert(rowModel.c17 == self.c17String, "Value was not \(String(describing: self.c17String))") XCTAssert(rowModel.c18 == self.c18String, "Value was not \(String(describing: self.c18String))") } row += 1 } XCTAssert(select.numberResultRows() == row-1, "Got an unexpected number of result rows") Log.info("forEachRowStatus: \(String(describing: select.forEachRowStatus)); rows: \(row-1)") XCTAssert(select.forEachRowStatus == nil, "forEachRowStatus \(String(describing: select.forEachRowStatus))") } func testSelectForEachRowIgnoringErrors() { runSelectTestForEachRow(ignoreErrors: true) } func testSelectForEachRowNotIgnoringErrors() { runSelectTestForEachRow(ignoreErrors: false) } func equalDMY(date1:Date, date2:Date) -> Bool { Log.info("In equalDMY") guard let utc = TimeZone(abbreviation: "UTC") else { Log.error("Could not convert to UTC timezone!") return false } Log.info("After TimeZone: \(utc)") Log.info("date1: \(date1); date2: \(date2)") // 6/12/19; Due to Swift 5.0.1 issue; See https://stackoverflow.com/questions/56555005/swift-5-ubuntu-16-04-crash-with-datecomponents // not using Calendar.current let calendar = Calendar(identifier: .gregorian) let componentsDate1 = calendar.dateComponents(in: utc, from: date1) let componentsDate2 = calendar.dateComponents(in: utc, from: date2) Log.info("componentsDate1.year: \(String(describing: componentsDate1.year)) componentsDate2.year: \(String(describing: componentsDate2.year))") Log.info("componentsDate1.month: \(String(describing: componentsDate1.month)) componentsDate2.month: \(String(describing: componentsDate2.month))") Log.info("componentsDate1.day: \(String(describing: componentsDate1.day)) componentsDate2.day: \(String(describing: componentsDate2.day))") return componentsDate1.year == componentsDate2.year && componentsDate1.month == componentsDate2.month && componentsDate1.day == componentsDate2.day } func testTypeConverters() { let query = "select * from \(testTableName2)" Log.info("Before select") guard let select = Select(db:db, query: query, modelInit: model2.init, ignoreErrors:false) else { XCTFail() return } var rows = 0 Log.info("Before each row") select.forEachRow { rowModel in Log.info("In forEachRow callback") rows += 1 guard let rowModel = rowModel as? model2 else { XCTFail() return } XCTAssert(rowModel.c1 == .TestEnum1, "TestEnum value was wrong") guard let date = rowModel.c2 else { XCTFail() return } Log.info("Before equalDMY") XCTAssert(self.equalDMY(date1: date, date2: self.c2Table2Value), "c2 date value was wrong: rowModel.c2=\(String(describing: date)); self.c2Table2Value=\(self.c2Table2Value)") Log.info("End of a row") } Log.info("After forEachRow") XCTAssert(select.forEachRowStatus == nil, "forEachRowStatus \(String(describing: select.forEachRowStatus))") XCTAssert(rows == 1, "Didn't find expected number of rows") } /* func testColumnExists() { XCTAssert(db.columnExists("c1", in: testTableName) == true) XCTAssert(db.columnExists("c3", in: testTableName2) == false) XCTAssert(db.columnExists("xxx", in: "yyy") == false) } func testAddColumn() { XCTAssert(db.addColumn("newTextColumn TEXT", to: testTableName)) XCTAssert(!db.addColumn("newTextColumn TEXT", to: testTableName)) } func testRemoveColumn() { XCTAssert(db.addColumn("newTextColumn TEXT", to: testTableName)) XCTAssert(db.removeColumn("newTextColumn", from: testTableName)) } // MARK: Database.PreparedStatement func testDatabaseInsertStringValueIntoStringColumnWorks() { let repo = Table3() repo.db = db let insert = Database.PreparedStatement(repo: repo, type: .insert) insert.add(fieldName: "c1", value: .string("Example")) do { try insert.run() } catch (let error) { XCTFail("\(error)") } } func testDatabaseInsertIntValueIntoIntColumnWorks() { let repo = Table3() repo.db = db let insert = Database.PreparedStatement(repo: repo, type: .insert) insert.add(fieldName: "c2", value: .int(56)) do { try insert.run() } catch (let error) { XCTFail("\(error)") } } func testDatabaseInsertBoolValueIntoBoolColumnWorks() { let repo = Table3() repo.db = db let insert = Database.PreparedStatement(repo: repo, type: .insert) insert.add(fieldName: "c4", value: .bool(true)) do { try insert.run() } catch (let error) { XCTFail("\(error)") } } func testDatabaseInsertNullValueIntoIntColumnWorks() { let repo = Table3() repo.db = db let insert = Database.PreparedStatement(repo: repo, type: .insert) insert.add(fieldName: "c2", value: .null) do { try insert.run() } catch (let error) { XCTFail("\(error)") } } func testDatabaseInsertStringValueIntoIntColumnFails() { let repo = Table3() repo.db = db let insert = Database.PreparedStatement(repo: repo, type: .insert) // Note that the opposite doesn't fail-- you can successfully bind an integer value to a string column. insert.add(fieldName: "c2", value: .string("Foobar")) do { try insert.run() XCTFail() } catch { } } func testDatabaseInsertValuesIntoColumnsWorks() { let repo = Table3() repo.db = db let insert = Database.PreparedStatement(repo: repo, type: .insert) insert.add(fieldName: "c1", value: .string("Foobar")) insert.add(fieldName: "c2", value: .int(56)) do { try insert.run() } catch (let error) { XCTFail("\(error)") } } func testDatabaseUpdateWorks() { let repo = Table3() repo.db = db let insert = Database.PreparedStatement(repo: repo, type: .insert) insert.add(fieldName: "c1", value: .string("Foobar")) insert.add(fieldName: "c2", value: .int(56)) do { try insert.run() } catch (let error) { XCTFail("\(error)") } let update = Database.PreparedStatement(repo: repo, type: .update) update.add(fieldName: "c1", value: .string("Snigly")) update.where(fieldName: "c2", value: .int(56)) do { try update.run() } catch (let error) { XCTFail("\(error)") } } func testDatabaseUpdateWithTwoFieldsInWhereClauseWorks() { let repo = Table3() repo.db = db let insert = Database.PreparedStatement(repo: repo, type: .insert) insert.add(fieldName: "c1", value: .string("Foobar")) insert.add(fieldName: "c2", value: .int(56)) insert.add(fieldName: "c3", value: .int(100)) do { try insert.run() } catch (let error) { XCTFail("\(error)") } let update = Database.PreparedStatement(repo: repo, type: .update) update.add(fieldName: "c1", value: .string("Snigly")) update.where(fieldName: "c2", value: .int(56)) update.where(fieldName: "c3", value: .int(100)) do { let num = try update.run() XCTAssert(num == 1) } catch (let error) { XCTFail("\(error)") } } */ } extension GeneralDatabaseTests { static var allTests : [(String, (GeneralDatabaseTests) -> () throws -> Void)] { return [ ("testSelectForEachRowIgnoringErrors", testSelectForEachRowIgnoringErrors), ("testSelectForEachRowNotIgnoringErrors", testSelectForEachRowNotIgnoringErrors), ("testTypeConverters", testTypeConverters), /* ("testColumnExists", testColumnExists), ("testAddColumn", testAddColumn), ("testRemoveColumn", testRemoveColumn), ("testDatabaseInsertStringValueIntoStringColumnWorks", testDatabaseInsertStringValueIntoStringColumnWorks), ("testDatabaseInsertIntValueIntoIntColumnWorks", testDatabaseInsertIntValueIntoIntColumnWorks), ("testDatabaseInsertBoolValueIntoBoolColumnWorks", testDatabaseInsertBoolValueIntoBoolColumnWorks), ("testDatabaseInsertNullValueIntoIntColumnWorks", testDatabaseInsertNullValueIntoIntColumnWorks), ("testDatabaseInsertStringValueIntoIntColumnFails", testDatabaseInsertStringValueIntoIntColumnFails), ("testDatabaseInsertValuesIntoColumnsWorks", testDatabaseInsertValuesIntoColumnsWorks), ("testDatabaseUpdateWorks", testDatabaseUpdateWorks), ("testDatabaseUpdateWithTwoFieldsInWhereClauseWorks", testDatabaseUpdateWithTwoFieldsInWhereClauseWorks) */ ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:GeneralDatabaseTests.self) } } <file_sep>// // HealthCheckTests.swift // Server // // Created by <NAME> on 12/28/17. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class HealthCheckTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() } func testThatHealthCheckReturnsExpectedInfo() { healthCheck() } } extension HealthCheckTests { static var allTests : [(String, (HealthCheckTests) -> () throws -> Void)] { return [ ("testThatHealthCheckReturnsExpectedInfo", testThatHealthCheckReturnsExpectedInfo), ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: HealthCheckTests.self) } } <file_sep>eb create sharedimages-production --cname sharedimages-production <file_sep>#!/bin/bash # Add a blank discussion thread file to all images that don't (yet) have a discussion thread. This also requires a change to appMetaData for each image file that doesn't yet have discussion thread. # First, I need to figure out which images don't have a discussion thread. Could do this by: # a) Get a list of all image files # b) Get a list of all discussion thread files. # c) For each discussion thread file: # i) read its JSON and get the associated imageUUID. # ii) remove that file from the list of image files. # d) The remaining image files do not have discussion threads. # e) For each remaining image file: # i) Generate an empty discussion thread file for that image file. Use as a device UUID, for the discussion thread file, the same as for the image file. Put the imageUUID into that file. # ii) Generate mySQL statements to insert this file reference into the FileIndex, along with app meta data for this file. # Usage: pass in the directory to process; doesn't need a trailing "/", and the directory to place the output files. INPUT_DIRECTORY=$1 OUTPUT_DIRECTORY=$2 # a file in the output directory SQL_STMTS="4.sql" # names without paths in directory. DISCUSSIONS=() IMAGES=() if [ ! -d $OUTPUT_DIRECTORY ]; then mkdir -p $OUTPUT_DIRECTORY; fi for fileNameWithPath in "$INPUT_DIRECTORY"/*; do mimeType=`file --mime-type "$fileNameWithPath" | awk '{print $NF}'` # echo \"$mimeType\" fileName=$(basename "$fileNameWithPath") if [ "$mimeType" == "text/plain" ]; then DISCUSSIONS+=("$fileName") else IMAGES+=("$fileName") fi done # echo ${DISCUSSIONS[*]} # echo ${IMAGES[*]} removeImageFromList () { local imageUUID=$1 for imageFileIndex in ${!IMAGES[*]}; do local imageFile=${IMAGES[$imageFileIndex]} if [[ $imageFile == *"$imageUUID"* ]]; then unset IMAGES[$imageFileIndex] # So we don't get gaps in the array IMAGES=( "${IMAGES[@]}" ) return fi done echo "ERROR: Not contained: $imageUUID" } echo "Number of images before:" ${#IMAGES[@]} echo "Number of discussions before:" ${#DISCUSSIONS[@]} for discussionFile in ${DISCUSSIONS[*]}; do imageUUID=`jq -r .imageUUID < "$INPUT_DIRECTORY/$discussionFile"` # This image has a discussion, remove it from list of images removeImageFromList $imageUUID done echo "Number of images after:" ${#IMAGES[@]} # Generate discussion threads for the images that don't have them. # Put them in $OUTPUT_DIRECTORY for imageFile in ${IMAGES[*]}; do # Files are named like this: 0A97AC41-0E4C-40F7-92FB-5601863521BA.FAF13FCE-EA89-4BCA-84C2-D6F594E3A429.0.jpg # The first UUID is the UUID of the image. The second is the UUID of the device. # Split a string at period delimiters: From https://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash splitAtPeriods=(${imageFile//./ }) imageUUID=${splitAtPeriods[0]} deviceUUID=${splitAtPeriods[1]} # Discussion thread files have initial contents like: {"elements":[],"imageUUID":"6FD07995-66E0-4E51-96E5-E5C0E1A197C0"} contents="{\"elements\":[],\"imageUUID\":\"$imageUUID\"}" # The number of bytes in the initial discussion thread file fileSizeBytes=${#contents} # Generate UUID for new discussion thread file. Uses MacOS function. discussionUUID=`uuidgen` # Need to fake a deviceUUID to make the file name. discussionFileName=$discussionUUID.$deviceUUID.0.txt echo -n $contents > $OUTPUT_DIRECTORY/$discussionFileName # Generate mySQL to insert into the FileIndex table to add this discussion. This will be in two parts fileGroupUUID=`uuidgen` userId=1 discussionAppMetaData='{"fileType":"discussion"}' # 1) For the new discussion thread file insert="INSERT INTO FileIndex (fileUUID, userId, deviceUUID, fileGroupUUID, creationDate, updateDate, mimeType, appMetaData, deleted, fileVersion, appMetaDataVersion, fileSizeBytes) VALUES (\"$discussionUUID\", $userId, \"$deviceUUID\", \"$fileGroupUUID\", Now(), Now(), \"text/plain\", '$discussionAppMetaData', FALSE, 0, 0, $fileSizeBytes);" # 2) An update to the existing image file to give it the new fileGroupUUID update="UPDATE FileIndex SET fileGroupUUID = \"$fileGroupUUID\" WHERE fileUUID = \"$imageUUID\";" echo "$insert" >> "$OUTPUT_DIRECTORY"/$SQL_STMTS echo "$update" >> "$OUTPUT_DIRECTORY"/$SQL_STMTS echo >> "$OUTPUT_DIRECTORY"/$SQL_STMTS done <file_sep>#!/bin/bash # Usage: # logTail.sh <EnvironmentName> # E.g., # logTail.sh neebla-production # logTail.sh sharedimages-production # logTail.sh sharedimages-staging ENVIRONMENT=$1 if [ "empty${ENVIRONMENT}" == "empty" ]; then echo "**** Please give an environment name." exit fi script -q /dev/null awslogs --query=message get /aws/elasticbeanstalk/${ENVIRONMENT}/home/ec2-user/output.log ALL --watch | cut -d " " -f 3- <file_sep>// // SharingGroupsControllerTests.swift // ServerTests // // Created by <NAME> on 7/15/18. // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class SharingGroupsControllerTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testCreateSharingGroupWorks() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } let sharingGroup = SyncServerShared.SharingGroup() sharingGroup.sharingGroupName = "Louisiana Guys" let sharingGroupUUID2 = UUID().uuidString guard createSharingGroup(sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID, sharingGroup: sharingGroup) else { XCTFail() return } guard let (_, sharingGroups) = getIndex() else { XCTFail() return } let filtered = sharingGroups.filter {$0.sharingGroupUUID == sharingGroupUUID2} guard filtered.count == 1 else { XCTFail() return } XCTAssert(filtered[0].sharingGroupName == sharingGroup.sharingGroupName) } func testThatNonOwningUserCannotCreateASharingGroup() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let testAccount:TestAccount = .nonOwningSharingAccount redeemSharingInvitation(sharingUser: testAccount, sharingInvitationUUID: sharingInvitationUUID) { _, expectation in expectation.fulfill() } let deviceUUID2 = Foundation.UUID().uuidString let sharingGroupUUID2 = Foundation.UUID().uuidString createSharingGroup(testAccount: testAccount, sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID2, errorExpected: true) } func testNewlyCreatedSharingGroupHasNoFiles() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } let sharingGroup = SyncServerShared.SharingGroup() sharingGroup.sharingGroupName = "Louisiana Guys" let sharingGroupUUID2 = Foundation.UUID().uuidString guard createSharingGroup(sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID, sharingGroup: sharingGroup) else { XCTFail() return } guard let (files, sharingGroups) = getIndex(sharingGroupUUID: sharingGroupUUID2) else { XCTFail() return } guard files != nil && files?.count == 0 else { XCTFail() return } guard sharingGroups.count == 2 else { XCTFail() return } sharingGroups.forEach { sharingGroup in guard let deleted = sharingGroup.deleted else { XCTFail() return } XCTAssert(!deleted) XCTAssert(sharingGroup.permission == .admin) XCTAssert(sharingGroup.masterVersion == 0) } let filtered = sharingGroups.filter {$0.sharingGroupUUID == sharingGroupUUID2} guard filtered.count == 1 else { XCTFail() return } XCTAssert(filtered[0].sharingGroupName == sharingGroup.sharingGroupName) guard let users = filtered[0].sharingGroupUsers, users.count == 1, users[0].name != nil, users[0].name.count > 0 else { XCTFail() return } } func testUpdateSharingGroupWorks() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let sharingGroup = SyncServerShared.SharingGroup() sharingGroup.sharingGroupUUID = sharingGroupUUID sharingGroup.sharingGroupName = "<NAME>" guard updateSharingGroup(deviceUUID:deviceUUID, sharingGroup: sharingGroup, masterVersion: masterVersion) else { XCTFail() return } } func testUpdateSharingGroupWithBadMasterVersionFails() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let sharingGroup = SyncServerShared.SharingGroup() sharingGroup.sharingGroupUUID = sharingGroupUUID sharingGroup.sharingGroupName = "<NAME>" updateSharingGroup(deviceUUID:deviceUUID, sharingGroup: sharingGroup, masterVersion: masterVersion+1, expectMasterVersionUpdate: true) } // MARK: Remove sharing groups func testRemoveSharingGroupWorks() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } let key1 = SharingGroupRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let result1 = SharingGroupRepository(db).lookup(key: key1, modelInit: SharingGroup.init) guard case .found(let model) = result1, let sharingGroup = model as? Server.SharingGroup else { XCTFail() return } guard sharingGroup.deleted else { XCTFail() return } guard let count = SharingGroupUserRepository(db).count(), count == 0 else { XCTFail() return } } func testRemoveSharingGroupWorks_filesMarkedAsDeleted() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } // Can't do a file index because no one is left in the sharing group. So, just look up in the db directly. let key = FileIndexRepository.LookupKey.sharingGroupUUID(sharingGroupUUID: sharingGroupUUID) let result = FileIndexRepository(db).lookup(key: key, modelInit: FileIndex.init) switch result { case .noObjectFound: XCTFail() case .error: XCTFail() case .found(let model): let file = model as! FileIndex XCTAssert(file.deleted) } } func testRemoveSharingGroupWorks_multipleUsersRemovedFromSharingGroup() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let sharingUser: TestAccount = .secondaryOwningAccount redeemSharingInvitation(sharingUser:sharingUser, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in expectation.fulfill() } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } guard let count = SharingGroupUserRepository(db).count(), count == 0 else { XCTFail() return } } func testRemoveSharingGroupWorks_cannotThenInviteSomeoneToThatGroup() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } createSharingInvitation(permission: .read, sharingGroupUUID:sharingGroupUUID, errorExpected: true) { expectation, _ in expectation.fulfill() } } func testRemoveSharingGroupWorks_cannotThenUploadFileToThatSharingGroup() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } uploadTextFile(deviceUUID:deviceUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), masterVersion:masterVersion+1, errorExpected:true) } func testRemoveSharingGroupWorks_cannotThenDoDoneUploads() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 0, deviceUUID:deviceUUID, masterVersion: masterVersion+1, sharingGroupUUID: sharingGroupUUID, failureExpected: true) } func testRemoveSharingGroupWorks_cannotDeleteFile() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult.request.fileVersion uploadDeletionRequest.masterVersion = masterVersion + 1 uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false, expectError: true) } func testRemoveSharingGroupWorks_uploadAppMetaDataFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } let appMetaData = AppMetaData(version: 0, contents: "Foo") uploadAppMetaDataVersion(deviceUUID: deviceUUID, fileUUID: uploadResult.request.fileUUID, masterVersion:masterVersion+1, appMetaData: appMetaData, sharingGroupUUID:sharingGroupUUID, expectedError: true) } func testRemoveSharingGroupWorks_downloadAppMetaDataFails() { let deviceUUID = Foundation.UUID().uuidString let appMetaData = AppMetaData(version: 0, contents: "Foo") guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID, appMetaData: appMetaData), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } downloadAppMetaDataVersion(deviceUUID: deviceUUID, fileUUID: uploadResult.request.fileUUID, masterVersionExpectedWithDownload:masterVersion + 1, appMetaDataVersion: 0, sharingGroupUUID: sharingGroupUUID, expectedError: true) } func testRemoveSharingGroupWorks_downloadFileFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } downloadTextFile(masterVersionExpectedWithDownload:Int(masterVersion+1), downloadFileVersion:0, uploadFileRequest:uploadResult.request, expectedError: true) } func testRemoveSharingGroup_failsWithBadMasterVersion() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard !removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion+1) else { XCTFail() return } } func testUpdateSharingGroupForDeletedSharingGroupFails() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard var masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeSharingGroup(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } masterVersion += 1 let sharingGroup = SyncServerShared.SharingGroup() sharingGroup.sharingGroupUUID = sharingGroupUUID sharingGroup.sharingGroupName = "<NAME>" let result = updateSharingGroup(deviceUUID:deviceUUID, sharingGroup: sharingGroup, masterVersion: masterVersion, expectFailure: true) XCTAssert(result == false) } // MARK: Remove user from sharing group func testRemoveUserFromSharingGroup_lastUserInSharingGroup() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let addUserResponse = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeUserFromSharingGroup(deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } let key1 = SharingGroupRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let result1 = SharingGroupRepository(db).lookup(key: key1, modelInit: SharingGroup.init) guard case .found(let model) = result1, let sharingGroup = model as? Server.SharingGroup else { XCTFail() return } guard sharingGroup.deleted else { XCTFail() return } let key2 = SharingGroupUserRepository.LookupKey.userId(addUserResponse.userId) let result2 = SharingGroupUserRepository(db).lookup(key: key2 , modelInit: SharingGroupUser.init) guard case .noObjectFound = result2 else { XCTFail() return } } func testRemoveUserFromSharingGroup_notLastUserInSharingGroup() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let addUserResponse = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let sharingUser: TestAccount = .secondaryOwningAccount redeemSharingInvitation(sharingUser:sharingUser, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in expectation.fulfill() } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeUserFromSharingGroup(deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } guard let masterVersion2 = getMasterVersion(testAccount: sharingUser, sharingGroupUUID: sharingGroupUUID), masterVersion + 1 == masterVersion2 else { XCTFail() return } let key1 = SharingGroupRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let result1 = SharingGroupRepository(db).lookup(key: key1, modelInit: SharingGroup.init) guard case .found(let model) = result1, let sharingGroup = model as? Server.SharingGroup else { XCTFail() return } // Still one user in sharing group-- should not be deleted. guard !sharingGroup.deleted else { XCTFail() return } let key2 = SharingGroupUserRepository.LookupKey.userId(addUserResponse.userId) let result2 = SharingGroupUserRepository(db).lookup(key: key2 , modelInit: SharingGroupUser.init) guard case .noObjectFound = result2 else { XCTFail() return } } func testRemoveUserFromSharingGroup_failsWithBadMasterVersion() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } removeUserFromSharingGroup(deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion + 1, expectMasterVersionUpdate: true) } // When user has files in the sharing group-- those should be marked as deleted. func testRemoveUserFromSharingGroup_userHasFiles() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) // Need a second user as a member of the sharing group so we can do a file index on the sharing group after the first user is removed. var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let sharingUser: TestAccount = .secondaryOwningAccount redeemSharingInvitation(sharingUser:sharingUser, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in expectation.fulfill() } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeUserFromSharingGroup(deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } guard let (files, _) = getIndex(testAccount: sharingUser, sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let filtered = files!.filter {$0.fileUUID == uploadResult.request.fileUUID} guard filtered.count == 1 else { XCTFail() return } XCTAssert(filtered[0].deleted == true) } // When owning user has sharing users in sharing group: Those should no longer be able to upload to the sharing group. func testRemoveUserFromSharingGroup_owningUserHasSharingUsers() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString let owningUser:TestAccount = .primaryOwningAccount guard let _ = self.addNewUser(testAccount: owningUser, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(testAccount: owningUser, permission: .write, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let sharingUser: TestAccount = .nonOwningSharingAccount redeemSharingInvitation(sharingUser:sharingUser, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in expectation.fulfill() } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard removeUserFromSharingGroup(testAccount: owningUser, deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } let result = uploadTextFile(testAccount: sharingUser, owningAccountType: owningUser.scheme.accountName, deviceUUID:deviceUUID, addUser: .no(sharingGroupUUID:sharingGroupUUID), masterVersion: masterVersion + 1, errorExpected: true) XCTAssert(result == nil) } func testInterleavedUploadsToDifferentSharingGroupsWorks() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID1 = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID1, deviceUUID:deviceUUID) else { XCTFail() return } let sharingGroup = SyncServerShared.SharingGroup() let sharingGroupUUID2 = UUID().uuidString guard createSharingGroup(sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID, sharingGroup: sharingGroup) else { XCTFail() return } // Upload (only; no DoneUploads) to sharing group 1 guard let masterVersion1 = getMasterVersion(sharingGroupUUID: sharingGroupUUID1) else { XCTFail() return } uploadTextFile(deviceUUID:deviceUUID, addUser: .no(sharingGroupUUID:sharingGroupUUID1), masterVersion: masterVersion1) // Upload (only; no DoneUploads) to sharing group 2 guard let masterVersion2 = getMasterVersion(sharingGroupUUID: sharingGroupUUID2) else { XCTFail() return } uploadTextFile(deviceUUID:deviceUUID, addUser: .no(sharingGroupUUID:sharingGroupUUID2), masterVersion: masterVersion2) self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID1) self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID2) } } extension SharingGroupsControllerTests { static var allTests : [(String, (SharingGroupsControllerTests) -> () throws -> Void)] { return [ ("testCreateSharingGroupWorks", testCreateSharingGroupWorks), ("testThatNonOwningUserCannotCreateASharingGroup", testThatNonOwningUserCannotCreateASharingGroup), ("testNewlyCreatedSharingGroupHasNoFiles", testNewlyCreatedSharingGroupHasNoFiles), ("testUpdateSharingGroupWorks", testUpdateSharingGroupWorks), ("testUpdateSharingGroupWithBadMasterVersionFails", testUpdateSharingGroupWithBadMasterVersionFails), ("testRemoveSharingGroupWorks", testRemoveSharingGroupWorks), ("testRemoveSharingGroupWorks_filesMarkedAsDeleted", testRemoveSharingGroupWorks_filesMarkedAsDeleted), ("testRemoveSharingGroupWorks_multipleUsersRemovedFromSharingGroup", testRemoveSharingGroupWorks_multipleUsersRemovedFromSharingGroup), ("testRemoveSharingGroupWorks_cannotThenInviteSomeoneToThatGroup", testRemoveSharingGroupWorks_cannotThenInviteSomeoneToThatGroup), ("testRemoveSharingGroupWorks_cannotThenUploadFileToThatSharingGroup", testRemoveSharingGroupWorks_cannotThenUploadFileToThatSharingGroup), ("testRemoveSharingGroupWorks_cannotThenDoDoneUploads", testRemoveSharingGroupWorks_cannotThenDoDoneUploads), ("testRemoveSharingGroupWorks_cannotDeleteFile", testRemoveSharingGroupWorks_cannotDeleteFile), ("testRemoveSharingGroupWorks_uploadAppMetaDataFails", testRemoveSharingGroupWorks_uploadAppMetaDataFails), ("testRemoveSharingGroupWorks_downloadAppMetaDataFails", testRemoveSharingGroupWorks_downloadAppMetaDataFails), ("testRemoveSharingGroupWorks_downloadFileFails", testRemoveSharingGroupWorks_downloadFileFails), ("testRemoveSharingGroup_failsWithBadMasterVersion", testRemoveSharingGroup_failsWithBadMasterVersion), ("testUpdateSharingGroupForDeletedSharingGroupFails", testUpdateSharingGroupForDeletedSharingGroupFails), ("testRemoveUserFromSharingGroup_lastUserInSharingGroup", testRemoveUserFromSharingGroup_lastUserInSharingGroup), ("testRemoveUserFromSharingGroup_notLastUserInSharingGroup", testRemoveUserFromSharingGroup_notLastUserInSharingGroup), ("testRemoveUserFromSharingGroup_failsWithBadMasterVersion", testRemoveUserFromSharingGroup_failsWithBadMasterVersion), ("testRemoveUserFromSharingGroup_userHasFiles", testRemoveUserFromSharingGroup_userHasFiles), ("testRemoveUserFromSharingGroup_owningUserHasSharingUsers", testRemoveUserFromSharingGroup_owningUserHasSharingUsers), ("testInterleavedUploadsToDifferentSharingGroupsWorks", testInterleavedUploadsToDifferentSharingGroupsWorks) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SharingGroupsControllerTests.self) } } <file_sep>1) Dockerrun.aws.json "AWSEBDockerrunVersion": "1", The value `1` indicates single container Docker environment. This is the right value since my server is using just a single container. 2) Elastic Beanstalk and NGINX: https://medium.com/trisfera/getting-to-know-and-love-aws-elastic-beanstalk-configuration-files-ebextensions-9a4502a26e3c 3) I haven't been able to get this to work. Seems specific to Java apps. http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/java-se-nginx.html 4) For the pgrep command I have in the 2nd .config file, see https://stackoverflow.com/questions/18908426/increasing-client-max-body-size-in-nginx-conf-on-aws-elastic-beanstalk?rq=1 5) At first I thought that the environment manifest file they talk about here http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-cfg-manifest.html could be used to specify all of the environment options. After much struggling, that doesn't seem so. Instead, I've moved on to specifying these options in a .config file in the .ebextensions folder. http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-configuration-methods-during.html http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions-optionsettings.html http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-configuration-methods-before.html See also: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-applicationloadbalancer.html I did use the Elastic Beanstalk configuration files, saved from particular environments, as a starting point for these. 5) I struggled quite a bit trying to figure out how to put most of the parameters needed to launch an environment from the EB web UI into a .config file. However, that doesn't seem fully possible. See https://devops.stackexchange.com/questions/2598/elastic-beanstalk-setting-parameters-from-a-config-file-in-the-application-bun 6) I've finally boiled down the .config file (I'm calling it configure.yml) contents to two parts that work when using the eb cli. One part is a `Resources` section and the other part is a `option_settings` section. It seems the Resources section is needed with the eb cli, otherwise, the load balancer doesn't get configured properly. https://aws.amazon.com/blogs/devops/three-easy-steps-to-enable-cross-zone-load-balancing-in-elastic-beanstalk/ http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-format-resources-eb.html http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-resources.html http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html 7) Setting up CloudWatch logs See https://stackoverflow.com/questions/34018931/how-to-view-aws-log-real-time-like-tail-f https://github.com/jorgebastida/awslogs Seems like the final secret sauce in all this was: "Before you can configure integration with CloudWatch Logs using configuration files, you must set up IAM permissions to use with the CloudWatch Logs agent. You can attach the following custom policy to the instance profile that you assign to your environment." (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.cloudwatchlogs.html#AWSHowTo.cloudwatchlogs.streaming). I attached that custom policy to the IAM aws-elasticbeanstalk-ec2-role. You attach that custom policy to aws-elasticbeanstalk-ec2-role by going to: https://console.aws.amazon.com/iam/home#roles and https://console.aws.amazon.com/iam/home?#/roles/aws-elasticbeanstalk-ec2-role This policy will be applied to *all* of your Elastic Beanstalk Applications/Environments. "When you launch an environment in the AWS Elastic Beanstalk environment management console, the console creates a default instance profile, called aws-elasticbeanstalk-ec2-role, and assigns managed policies with default permissions to it." (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-instanceprofile.html) It also looks like the prefix "/etc/awslogs/config/" in the .config file is necessary. I restarted the staging environment with the above custom policy change in place, and that didn't do the job. But with that policy change *and* the prefix "/etc/awslogs/config/" in the .config file, I *am* now seeing the log in CloudWatch. awslogs groups # The following does a "tail" on the CloudWatch log for staging. # script -q /dev/null # This unbuffers the output # cut -d " " -f 3- # This removes the first two fields of the output. Just fluff. script -q /dev/null awslogs --query=message get /aws/elasticbeanstalk/sharedimages-staging/home/ec2-user/output.log ALL --watch | cut -d " " -f 3- # The following does a "tail" on the CloudWatch log for production. script -q /dev/null awslogs --query=message get /aws/elasticbeanstalk/sharedimages-production/home/ec2-user/output.log ALL --watch | cut -d " " -f 3- <file_sep>// // DropboxCreds+CloudStorage.swift // Server // // Created by <NAME> on 12/10/17. // import Foundation import SyncServerShared import LoggerAPI import KituraNet extension DropboxCreds { // Dropbox is using this https://blogs.dropbox.com/developers/2015/04/a-preview-of-the-new-dropbox-api-v2/ "But if a request fails for some call-specific reason, v1 might have returned any of 403, 404, 406, 411, etc. API v2 will always return a 409 status code with a stable and documented error identifier in the body. We chose 409 because, unlike many other error codes, it doesn’t have any specific meaning in the HTTP spec. This ensures that HTTP intermediaries, such as proxies or client libraries, will relay it along untouched." static let requestFailureCode = 409 private func basicHeaders(withContentTypeHeader contentType:String = "application/json") -> [String: String] { var headers = [String:String]() headers["Authorization"] = "Bearer \(accessToken!)" headers["Content-Type"] = contentType return headers } enum DropboxError : Swift.Error { case badStatusCode(HTTPStatusCode?) case nilAPIResult case nilCheckSum case badJSONResult case couldNotGetCheckSum case unknownError case noDataInAPIResult case couldNotGetId } // On success, Bool in result indicates whether or not the file exists. func checkForFile(fileName: String, completion:@escaping (Result<Bool>)->()) { // See https://www.dropbox.com/developers/documentation/http/documentation#files-get_metadata /* curl -X POST https://api.dropboxapi.com/2/files/get_metadata \ --header "Authorization: Bearer " \ --header "Content-Type: application/json" \ --data "{\"path\": \"/Homework/math\",\"include_media_info\": false,\"include_deleted\": false,\"include_has_explicit_shared_members\": false}" */ // It's hard to see in here, but I've put an explicit "/" before the file name. Dropbox needs this to precede file names. let body = "{\"path\": \"/\(fileName)\",\"include_media_info\": false,\"include_deleted\": false,\"include_has_explicit_shared_members\": false}" self.apiCall(method: "POST", path: "/2/files/get_metadata", additionalHeaders: basicHeaders(), body: .string(body), expectedFailureBody: .json) { (apiResult, statusCode, responseHeaders) in if self.revokedAccessToken(result: apiResult, statusCode: statusCode) { completion(.accessTokenRevokedOrExpired) return } Log.debug("apiResult: \(String(describing: apiResult)); statusCode: \(String(describing: statusCode))") guard statusCode == HTTPStatusCode.OK || statusCode?.rawValue == DropboxCreds.requestFailureCode else { completion(.failure(DropboxError.badStatusCode(statusCode))) return } guard let apiResult = apiResult else { completion(.failure(DropboxError.nilAPIResult)) return } guard case .dictionary(let dictionary) = apiResult else { completion(.failure(DropboxError.badJSONResult)) return } // For file not found error, gives: // "error": [".tag": "path", "path": [".tag": "not_found"]] if let _ = dictionary["id"] { completion(.success(true)) } else if let error = dictionary["error"] as? [String: Any], let path = error["path"] as? [String: Any], let tag = path[".tag"] as? String, tag == "not_found" { completion(.success(false)) } else { completion(.failure(DropboxError.unknownError)) } } } // String in successful result is checksum. func uploadFile(withName fileName: String, data:Data, completion:@escaping (Result<String>)->()) { // https://www.dropbox.com/developers/documentation/http/documentation#files-upload /* curl -X POST https://content.dropboxapi.com/2/files/upload \ --header "Authorization: Bearer " \ --header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Matrices.txt\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}" \ --header "Content-Type: application/octet-stream" \ --data-binary @local_file.txt */ var headers = basicHeaders() headers["Dropbox-API-Arg"] = "{\"path\": \"/\(fileName)\",\"mode\": \"add\",\"autorename\": false,\"mute\": false}" headers["Content-Type"] = "application/octet-stream" self.apiCall(method: "POST", baseURL: "content.dropboxapi.com", path: "/2/files/upload", additionalHeaders: headers, body: .data(data), expectedFailureBody: .json) {[unowned self] (apiResult, statusCode, responseHeaders) in if self.revokedAccessToken(result: apiResult, statusCode: statusCode) { completion(.accessTokenRevokedOrExpired) return } guard statusCode == HTTPStatusCode.OK else { completion(.failure(DropboxError.badStatusCode(statusCode))) return } guard let apiResult = apiResult else { completion(.failure(DropboxError.nilAPIResult)) return } guard case .dictionary(let dictionary) = apiResult else { completion(.failure(DropboxError.badJSONResult)) return } if let idJson = dictionary["id"] as? String, idJson != "", let checkSum = dictionary["content_hash"] as? String { completion(.success(checkSum)) } else { completion(.failure(DropboxError.couldNotGetCheckSum)) } } } // See https://github.com/dropbox/dropbox-sdk-obj-c/issues/83 func revokedAccessToken(result: APICallResult?, statusCode: HTTPStatusCode?) -> Bool { /* ["error_summary": "invalid_access_token/...", "error": [".tag": "invalid_access_token"] ] */ if statusCode == HTTPStatusCode.unauthorized, case .dictionary(let dict)? = result, let tag = dict["error"] as? [String: Any], let message = tag[".tag"] as? String, message == "invalid_access_token" { return true } else { return false } } } extension DropboxCreds : CloudStorage { enum UploadFileError : Swift.Error { case fileCheckFailed(Swift.Error) case alreadyUploaded } func uploadFile(cloudFileName:String, data:Data, options:CloudStorageFileNameOptions? = nil, completion:@escaping (Result<String>)->()) { // First, look to see if the file exists on Dropbox. Don't want to upload it more than once. checkForFile(fileName: cloudFileName) {[unowned self] result in switch result { case .failure(let error): completion(.failure(UploadFileError.fileCheckFailed(error))) case .accessTokenRevokedOrExpired: completion(.accessTokenRevokedOrExpired) case .success(let found): if found { // Don't need to upload it again. completion(.failure(CloudStorageError.alreadyUploaded)) } else { self.uploadFile(withName: cloudFileName, data: data) { result in completion(result) } } } } } func downloadFile(cloudFileName:String, options:CloudStorageFileNameOptions? = nil, completion:@escaping (DownloadResult)->()) { // https://www.dropbox.com/developers/documentation/http/documentation#files-download /* curl -X POST https://content.dropboxapi.com/2/files/download \ --header "Authorization: Bearer " \ --header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Prime_Numbers.txt\"}" */ // Content-Type needs to explicitly be an empty string or the request fails. Odd. // See https://stackoverflow.com/questions/42755495/dropbox-download-file-api-stopped-working-with-400-error var headers = basicHeaders(withContentTypeHeader: "") headers["Dropbox-API-Arg"] = "{\"path\": \"/\(cloudFileName)\"}" // "The response body contains file content, so the result will appear as JSON in the Dropbox-API-Result response header" // See https://www.dropbox.com/developers/documentation/http/documentation#formats self.apiCall(method: "POST", baseURL: "content.dropboxapi.com", path: "/2/files/download", additionalHeaders: headers, expectedSuccessBody: .data, expectedFailureBody: .json) { (apiResult, statusCode, responseHeaders) in /* Example of what is returned when a file is not found: HTTPStatusCode.conflict (["error": ["path": [".tag": "not_found"], ".tag": "path"], "error_summary": "path/not_found/"])) See also https://www.dropbox.com/developers/documentation/http/documentation#error-handling and https://www.dropboxforum.com/t5/API-Support-Feedback/Did-404-change-to-409-in-v2/td-p/208370 */ if statusCode == HTTPStatusCode.conflict, case .dictionary(let dict)? = apiResult, let path = dict["error"] as? [String: Any], let tag = path["path"] as? [String: Any], let message = tag[".tag"] as? String, message == "not_found" { Log.warning("Dropbox: File \(cloudFileName) not found.") completion(.fileNotFound) return } if self.revokedAccessToken(result: apiResult, statusCode: statusCode) { completion(.accessTokenRevokedOrExpired) return } guard statusCode == HTTPStatusCode.OK else { completion(.failure(DropboxError.badStatusCode(statusCode))) return } guard let apiResult = apiResult else { completion(.failure(DropboxError.nilAPIResult)) return } guard let headerAPIResult = responseHeaders?["Dropbox-API-Result"], headerAPIResult.count > 0 else { Log.error("Could not get headerAPIResult") completion(.failure(DropboxError.nilCheckSum)) return } guard let headerAPIResultDict = headerAPIResult[0].toJSONDictionary() else { Log.error("Could not convert string to JSON dict: headerAPIResultDict") completion(.failure(DropboxError.nilCheckSum)) return } guard let checkSum = headerAPIResultDict["content_hash"] as? String else { Log.error("Could not get check sum from headerAPIResultDict") completion(.failure(DropboxError.nilCheckSum)) return } guard case .data(let data) = apiResult else { completion(.failure(DropboxError.noDataInAPIResult)) return } let downloadResult:DownloadResult = .success(data: data, checkSum: checkSum) completion(downloadResult) } } func deleteFile(cloudFileName:String, options:CloudStorageFileNameOptions? = nil, completion:@escaping (Result<()>)->()) { // https://www.dropbox.com/developers/documentation/http/documentation#files-delete_v2 /* curl -X POST https://api.dropboxapi.com/2/files/delete_v2 \ --header "Authorization: Bearer " \ --header "Content-Type: application/json" \ --data "{\"path\": \"/Homework/math/Prime_Numbers.txt\"}" */ var headers = basicHeaders() headers["Content-Type"] = "application/json" let body = "{\"path\": \"/\(cloudFileName)\"}" self.apiCall(method: "POST", path: "/2/files/delete_v2", additionalHeaders: headers, body: .string(body), expectedFailureBody: .json) { (apiResult, statusCode, responseHeaders) in if self.revokedAccessToken(result: apiResult, statusCode: statusCode) { completion(.accessTokenRevokedOrExpired) return } guard statusCode == HTTPStatusCode.OK else { completion(.failure(DropboxError.badStatusCode(statusCode))) return } guard let apiResult = apiResult else { completion(.failure(DropboxError.nilAPIResult)) return } guard case .dictionary(let dictionary) = apiResult else { completion(.failure(DropboxError.badJSONResult)) return } if let metaData = dictionary["metadata"] as? [String: Any], let idJson = metaData["id"] as? String, idJson != "" { completion(.success(())) } else { completion(.failure(DropboxError.couldNotGetId)) } } } func lookupFile(cloudFileName:String, options:CloudStorageFileNameOptions? = nil, completion:@escaping (Result<Bool>)->()) { checkForFile(fileName: cloudFileName) { result in completion(result) } } } <file_sep>These folders are where you run the eb cli. To initialize the folder, with the basic environment setup, do: eb init (also see Docs/LaunchingEnvironment.md) Later, e.g., in the sharedimages-staging folder, you create (start) an environment with: eb create sharedimages-staging --cname sharedimages-staging --------------------------------------------------------- For the most recent version of the AWS Platform Version of AWS Linux to put in the .elasticbeanstalk/config.yml file, see: https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html <file_sep>#!/bin/bash # Usage: release.sh <ReleaseTag> # <ReleaseTag> is the tag to apply to git, and to use as a tag for Docker Hub. # Run this from the root of the repo. i.e., ./devops/release.sh # after you have built the SyncServer server binary. # Example: # ./devops/release.sh 0.7.7 # Note that you can also use this to "release" testing versions. For example, if you do: # ./devops/release.sh release-candidate-0.8.0 # This script adapted from https://medium.com/travis-on-docker/how-to-version-your-docker-images-1d5c577ebf54 RELEASE_TAG=$1 if [ "empty${RELEASE_TAG}" == "empty" ]; then echo "**** Please give a release tag." exit fi # docker hub username USERNAME=crspybits # image name IMAGE=syncserver-runner # ensure we're up to date git pull # bump version echo $RELEASE_TAG > VERSION echo "version: $RELEASE_TAG" # build the runtime image docker build -t $USERNAME/$IMAGE:latest . # tag it git add -A git commit -m "version $RELEASE_TAG" git tag -a "$RELEASE_TAG" -m "version $RELEASE_TAG" git push git push --tags docker tag $USERNAME/$IMAGE:latest $USERNAME/$IMAGE:$RELEASE_TAG # push it docker push $USERNAME/$IMAGE:latest docker push $USERNAME/$IMAGE:$RELEASE_TAG<file_sep>// // ServerRoutes.swift // Authentication // // Created by <NAME> on 11/26/16. // // import Kitura import SyncServerShared // When adding a new controller, you must also add it to the list in Controllers.swift public class ServerRoutes { class func add(proxyRouter:CreateRoutes) { let utilController = UtilController() proxyRouter.addRoute(ep: ServerEndpoints.healthCheck, processRequest: utilController.healthCheck) #if DEBUG proxyRouter.addRoute(ep: ServerEndpoints.checkPrimaryCreds, processRequest: utilController.checkPrimaryCreds) #endif let userController = UserController() proxyRouter.addRoute(ep: ServerEndpoints.addUser, processRequest: userController.addUser) proxyRouter.addRoute(ep: ServerEndpoints.checkCreds, processRequest: userController.checkCreds) proxyRouter.addRoute(ep: ServerEndpoints.removeUser, processRequest: userController.removeUser) let fileController = FileController() proxyRouter.addRoute(ep: ServerEndpoints.index, processRequest: fileController.index) proxyRouter.addRoute(ep: ServerEndpoints.uploadFile, processRequest: fileController.uploadFile) proxyRouter.addRoute(ep: ServerEndpoints.uploadAppMetaData, processRequest: fileController.uploadAppMetaData) proxyRouter.addRoute(ep: ServerEndpoints.doneUploads, processRequest: fileController.doneUploads) proxyRouter.addRoute(ep: ServerEndpoints.downloadFile, processRequest: fileController.downloadFile) proxyRouter.addRoute(ep: ServerEndpoints.downloadAppMetaData, processRequest: fileController.downloadAppMetaData) proxyRouter.addRoute(ep: ServerEndpoints.getUploads, processRequest: fileController.getUploads) proxyRouter.addRoute(ep: ServerEndpoints.uploadDeletion, processRequest: fileController.uploadDeletion) let sharingAccountsController = SharingAccountsController() proxyRouter.addRoute(ep: ServerEndpoints.createSharingInvitation, processRequest: sharingAccountsController.createSharingInvitation) proxyRouter.addRoute(ep: ServerEndpoints.getSharingInvitationInfo, processRequest: sharingAccountsController.getSharingInvitationInfo) proxyRouter.addRoute(ep: ServerEndpoints.redeemSharingInvitation, processRequest: sharingAccountsController.redeemSharingInvitation) let sharingGroupsController = SharingGroupsController() proxyRouter.addRoute(ep: ServerEndpoints.createSharingGroup, processRequest: sharingGroupsController.createSharingGroup) proxyRouter.addRoute(ep: ServerEndpoints.updateSharingGroup, processRequest: sharingGroupsController.updateSharingGroup) proxyRouter.addRoute(ep: ServerEndpoints.removeSharingGroup, processRequest: sharingGroupsController.removeSharingGroup) proxyRouter.addRoute(ep: ServerEndpoints.removeUserFromSharingGroup, processRequest: sharingGroupsController.removeUserFromSharingGroup) let pushNotificationsController = PushNotificationsController() proxyRouter.addRoute(ep: ServerEndpoints.registerPushNotificationToken, processRequest: pushNotificationsController.registerPushNotificationToken) } } <file_sep>// // DropboxCreds.swift // Server // // Created by <NAME> on 12/3/17. // import Foundation import SyncServerShared import Kitura import Credentials import LoggerAPI import KituraNet class DropboxCreds : AccountAPICall, Account { static var accountScheme:AccountScheme { return .dropbox } var accountScheme:AccountScheme { return DropboxCreds.accountScheme } var owningAccountsNeedCloudFolderName: Bool { return false } weak var delegate:AccountDelegate? var accountCreationUser:AccountCreationUser? static let accessTokenKey = "accessToken" var accessToken: String! static let accountIdKey = "accountId" var accountId: String! override init?() { super.init() baseURL = "api.dropboxapi.com" } func toJSON() -> String? { var jsonDict = [String:String]() jsonDict[DropboxCreds.accessTokenKey] = self.accessToken // Don't need the accountId in the json because its saved as the credsId in the database. return JSONExtras.toJSONString(dict: jsonDict) } // Given existing Account info stored in the database, decide if we need to generate tokens. Token generation can be used for various purposes by the particular Account. E.g., For owning users to allow access to cloud storage data in offline manner. E.g., to allow access that data by sharing users. func needToGenerateTokens(dbCreds:Account?) -> Bool { // 7/6/18; Previously, for Dropbox, I was returning false. But I want to deal with the case where a user a) deauthorizes the client app from using Dropbox, and then b) authorizes it again. This will make the access token we have in the database invalid. This will refresh it. return true } private static let apiAccessTokenKey = "access_token" private static let apiTokenTypeKey = "token_type" func generateTokens(response: RouterResponse?, completion:@escaping (Swift.Error?)->()) { // Not generating tokens, just saving. guard let delegate = delegate else { Log.warning("No Dropbox Creds delegate!") completion(nil) return } if delegate.saveToDatabase(account: self) { completion(nil) return } completion(GenerateTokensError.errorSavingCredsToDatabase) } func merge(withNewer newerAccount:Account) { guard let newerDropboxCreds = newerAccount as? DropboxCreds else { Log.error("Wrong other type of creds!") assert(false) return } // Both of these will be present-- both are necessary to authenticate with Dropbox. accountId = newerDropboxCreds.accountId accessToken = newerDropboxCreds.accessToken } static func getProperties(fromRequest request:RouterRequest) -> [String: Any] { var result = [String: Any]() if let accountId = request.headers[ServerConstants.HTTPAccountIdKey] { result[ServerConstants.HTTPAccountIdKey] = accountId } if let accessToken = request.headers[ServerConstants.HTTPOAuth2AccessTokenKey] { result[ServerConstants.HTTPOAuth2AccessTokenKey] = accessToken } return result } static func fromProperties(_ properties: AccountManager.AccountProperties, user:AccountCreationUser?, delegate:AccountDelegate?) -> Account? { guard let creds = DropboxCreds() else { return nil } creds.accountCreationUser = user creds.delegate = delegate creds.accessToken = properties.properties[ServerConstants.HTTPOAuth2AccessTokenKey] as? String creds.accountId = properties.properties[ServerConstants.HTTPAccountIdKey] as? String return creds } static func fromJSON(_ json:String, user:AccountCreationUser, delegate:AccountDelegate?) throws -> Account? { guard let jsonDict = json.toJSONDictionary() as? [String:String] else { Log.error("Could not convert string to JSON [String:String]: \(json)") return nil } guard let result = DropboxCreds() else { return nil } result.delegate = delegate result.accountCreationUser = user // Owning users have access token's in creds. switch user { case .user(let user) where AccountScheme(.accountName(user.accountType))?.userType == .owning: fallthrough case .userId(_): try setProperty(jsonDict:jsonDict, key: accessTokenKey) { value in result.accessToken = value } default: // Sharing users not allowed. assert(false) } return result } } <file_sep>// // FailureTests.swift // Server // // Created by <NAME> on 4/2/17. // // import LoggerAPI @testable import Server import KituraNet import XCTest import Foundation import SyncServerShared class FailureTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testThatHealthCheckFailsWhenRequested() { performServerTest { expectation, creds in let headers = [ ServerConstants.httpRequestEndpointFailureTestKey: "true" ] self.performRequest(route: ServerEndpoints.healthCheck, headers:headers) { response, dict in XCTAssert(response!.statusCode == .internalServerError, "Did not fail on healthcheck request: \(response!.statusCode)") expectation.fulfill() } } } } extension FailureTests { static var allTests : [(String, (FailureTests) -> () throws -> Void)] { return [("testThatHealthCheckFailsWhenRequested", testThatHealthCheckFailsWhenRequested)] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:FailureTests.self) } } <file_sep>// // PushNotificationsController.swift // Server // // Created by <NAME> on 2/6/19. // import LoggerAPI import SyncServerShared import Foundation import SwiftyAWSSNS class PushNotificationsController : ControllerProtocol { class func setup() -> Bool { return true } func registerPushNotificationToken(params:RequestProcessingParameters) { guard let request = params.request as? RegisterPushNotificationTokenRequest else { let message = "Did not receive RegisterPushNotificationTokenRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard let pn = PushNotifications() else { params.completion(.failure(nil)) return } let userId = params.currentSignedInUser!.userId! let topicName = PushNotifications.topicName(userId: userId) pn.sns.createPlatformEndpoint(apnsToken: request.pushNotificationToken) { response in switch response { case .success(let endpointArn): pn.sns.createTopic(topicName: topicName) { response in switch response { case .success(let topicArn): pn.sns.subscribe(endpointArn: endpointArn, topicArn: topicArn) { response in switch response { case .success: guard params.repos.user.updatePushNotificationTopic( forUserId: userId, topic: topicArn) else { let message = "Failed updating user topic." Log.error(message) params.completion(.failure(.message(message))) return } let response = RegisterPushNotificationTokenResponse() params.completion(.success(response)) return case .error(let error): let message = "Failed on subscribe: \(error)" Log.error(message) params.completion(.failure(.message(message))) return } } case .error(let error): let message = "Failed on createTopic: \(error)" Log.error(message) params.completion(.failure(.message(message))) return } } case .error(let error): let message = "Failed on createPlatformEndpoint: \(error)" Log.error(message) params.completion(.failure(.message(message))) return } } } } <file_sep>// // FileController_UploadAppMetaDataTests.swift // ServerTests // // Created by <NAME> on 3/25/18. // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class FileController_UploadAppMetaDataTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func checkFileIndex(before: FileInfo, after: FileInfo, uploadRequest: UploadFileRequest, deviceUUID: String, fileVersion: FileVersionInt, appMetaDataVersion: AppMetaDataVersionInt) { XCTAssert(after.fileUUID == uploadRequest.fileUUID) XCTAssert(after.deviceUUID == deviceUUID) // Updating app meta data doesn't change dates. XCTAssert(after.creationDate == before.creationDate) XCTAssert(after.updateDate == before.updateDate) XCTAssert(after.mimeType == uploadRequest.mimeType) XCTAssert(after.deleted == false) XCTAssert(after.appMetaDataVersion == appMetaDataVersion) XCTAssert(after.fileVersion == fileVersion) } func successDownloadAppMetaData(usingFileDownload: Bool) { var masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData1 = AppMetaData(version: 0, contents: "Test1") let testAccount:TestAccount = .primaryOwningAccount guard let uploadResult = uploadTextFile(testAccount: testAccount, deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID:sharingGroupUUID) masterVersion += 1 guard let (files, _) = getIndex(deviceUUID: deviceUUID, sharingGroupUUID:sharingGroupUUID), let fileInfoObjs1 = files, fileInfoObjs1.count == 1 else { XCTFail() return } let fileInfo1 = fileInfoObjs1[0] let appMetaData2 = AppMetaData(version: 1, contents: "Test2") let deviceUUID2 = Foundation.UUID().uuidString // Use a different deviceUUID so we can check that the app meta data update doesn't change it in the FileIndex. uploadAppMetaDataVersion(deviceUUID: deviceUUID2, fileUUID: uploadResult.request.fileUUID, masterVersion:masterVersion, appMetaData: appMetaData2, sharingGroupUUID:sharingGroupUUID) sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID2, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 if usingFileDownload { guard let downloadResponse = downloadTextFile(masterVersionExpectedWithDownload:Int(masterVersion), appMetaData:appMetaData2, uploadFileRequest:uploadResult.request) else { XCTFail() return } XCTAssert(downloadResponse.appMetaData == appMetaData2.contents) } else { guard let downloadAppMetaDataResponse = downloadAppMetaDataVersion(deviceUUID:deviceUUID, fileUUID: uploadResult.request.fileUUID, masterVersionExpectedWithDownload:masterVersion, appMetaDataVersion: appMetaData2.version, sharingGroupUUID: sharingGroupUUID, expectedError: false) else { XCTFail() return } XCTAssert(downloadAppMetaDataResponse.appMetaData == appMetaData2.contents) } guard let (files2, _) = getIndex(deviceUUID: deviceUUID, sharingGroupUUID:sharingGroupUUID), let fileInfoObjs2 = files2, fileInfoObjs2.count == 1 else { XCTFail() return } let fileInfo2 = fileInfoObjs2[0] checkFileIndex(before: fileInfo1, after: fileInfo2, uploadRequest: uploadResult.request, deviceUUID: deviceUUID, fileVersion: 0, appMetaDataVersion: appMetaData2.version) } func uploadAppMetaDataOfInitiallyNilAppMetaDataWorks(toAppMetaDataVersion appMetaDataVersion: AppMetaDataVersionInt, expectedError: Bool = false) { var masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:nil), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 guard let (files, _) = getIndex(deviceUUID: deviceUUID, sharingGroupUUID:sharingGroupUUID), let fileInfoObjs1 = files, fileInfoObjs1.count == 1 else { XCTFail() return } let fileInfo1 = fileInfoObjs1[0] let appMetaData = AppMetaData(version: appMetaDataVersion, contents: "Test2") let deviceUUID2 = Foundation.UUID().uuidString // Use a different deviceUUID so we can check that the app meta data update doesn't change it in the FileIndex. uploadAppMetaDataVersion(deviceUUID: deviceUUID2, fileUUID: uploadResult.request.fileUUID, masterVersion:masterVersion, appMetaData: appMetaData, sharingGroupUUID:sharingGroupUUID, expectedError: expectedError) if !expectedError { sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID2, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 guard let downloadAppMetaDataResponse = downloadAppMetaDataVersion(deviceUUID:deviceUUID, fileUUID: uploadResult.request.fileUUID, masterVersionExpectedWithDownload:masterVersion, appMetaDataVersion: appMetaData.version, sharingGroupUUID: sharingGroupUUID, expectedError: false) else { XCTFail() return } XCTAssert(downloadAppMetaDataResponse.appMetaData == appMetaData.contents) guard let (files2, _) = getIndex(deviceUUID: deviceUUID, sharingGroupUUID:sharingGroupUUID), let fileInfoObjs2 = files2, fileInfoObjs2.count == 1 else { XCTFail() return } let fileInfo2 = fileInfoObjs2[0] checkFileIndex(before: fileInfo1, after: fileInfo2, uploadRequest: uploadResult.request, deviceUUID: deviceUUID, fileVersion: 0, appMetaDataVersion: appMetaData.version) } } // Try to update from nil app data to version 1 (or other than 0). func testUploadAppMetaDataOfInitiallyNilAppMetaDataToVersion1Fails() { uploadAppMetaDataOfInitiallyNilAppMetaDataWorks(toAppMetaDataVersion: 1, expectedError: true) } // Try to update from version N meta data to version N (or other, non N+1). func testUpdateFromVersion0ToVersion0Fails() { var masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData1 = AppMetaData(version: 0, contents: "Test1") guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 let appMetaData2 = AppMetaData(version: 0, contents: "Test2") uploadAppMetaDataVersion(deviceUUID: deviceUUID, fileUUID: uploadResult.request.fileUUID, masterVersion:masterVersion, appMetaData: appMetaData2, sharingGroupUUID: sharingGroupUUID, expectedError: true) } // Attempt to upload app meta data for a deleted file. func testUploadAppMetaDataForDeletedFileFails() { let deviceUUID = Foundation.UUID().uuidString var masterVersion: MasterVersionInt = 0 guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID, masterVersion: masterVersion), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult.request.fileVersion uploadDeletionRequest.masterVersion = uploadResult.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false) sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 let appMetaData = AppMetaData(version: 0, contents: "Test2") uploadAppMetaDataVersion(deviceUUID: deviceUUID, fileUUID: uploadResult.request.fileUUID, masterVersion:masterVersion, appMetaData: appMetaData, sharingGroupUUID:sharingGroupUUID, expectedError: true) } // UploadAppMetaData for a file that doesn't exist. func testUploadAppMetaDataForANonExistentFileFails() { let deviceUUID = Foundation.UUID().uuidString let masterVersion: MasterVersionInt = 0 let appMetaData = AppMetaData(version: 0, contents: "Test1") let badFileUUID = Foundation.UUID().uuidString let cloudFolderName = ServerTestCase.cloudFolderName let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID, cloudFolderName: cloudFolderName) else { XCTFail() return } uploadAppMetaDataVersion(deviceUUID: deviceUUID, fileUUID: badFileUUID, masterVersion:masterVersion, appMetaData: appMetaData, sharingGroupUUID:sharingGroupUUID, expectedError: true) } // Use download file to try to download an incorrect meta data version. func testFileDownloadOfBadMetaDataVersionFails() { var masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData1 = AppMetaData(version: 0, contents: "Test1") guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 let appMetaData2 = AppMetaData(version: 1, contents: "Test2") let deviceUUID2 = Foundation.UUID().uuidString // Use a different deviceUUID so we can check that the app meta data update doesn't change it in the FileIndex. uploadAppMetaDataVersion(deviceUUID: deviceUUID2, fileUUID: uploadResult.request.fileUUID, masterVersion:masterVersion, appMetaData: appMetaData2, sharingGroupUUID: sharingGroupUUID) sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID2, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 let appMetaData3 = AppMetaData(version: appMetaData2.version + 1, contents: appMetaData2.contents) downloadTextFile(masterVersionExpectedWithDownload:Int(masterVersion), appMetaData:appMetaData3, uploadFileRequest:uploadResult.request, expectedError: true) } // UploadAppMetaData, then use regular download to retrieve. func testSuccessUsingFileDownloadToCheck() { successDownloadAppMetaData(usingFileDownload: true) } // UploadAppMetaData, then use DownloadAppMetaData to retrieve. func testSuccessUsingDownloadAppMetaDataToCheck() { successDownloadAppMetaData(usingFileDownload: false) } func testUploadAppMetaDataOfInitiallyNilAppMetaDataToVersion0Works() { uploadAppMetaDataOfInitiallyNilAppMetaDataWorks(toAppMetaDataVersion: 0) } func testUploadAppMetaDataWithFakeSharingGroupUUIDFails() { var masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData1 = AppMetaData(version: 0, contents: "Test1") guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID:sharingGroupUUID) masterVersion += 1 guard let (files, _) = getIndex(deviceUUID: deviceUUID, sharingGroupUUID:sharingGroupUUID), let fileInfoObjs1 = files, fileInfoObjs1.count == 1 else { XCTFail() return } let appMetaData2 = AppMetaData(version: 1, contents: "Test2") let deviceUUID2 = Foundation.UUID().uuidString let invalidSharingGroupUUID = UUID().uuidString uploadAppMetaDataVersion(deviceUUID: deviceUUID2, fileUUID: uploadResult.request.fileUUID, masterVersion:masterVersion, appMetaData: appMetaData2, sharingGroupUUID:invalidSharingGroupUUID, expectedError: true) } func testUploadAppMetaDataWithInvalidSharingGroupUUIDFails() { var masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString let appMetaData1 = AppMetaData(version: 0, contents: "Test1") guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID, masterVersion:masterVersion, appMetaData:appMetaData1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID:sharingGroupUUID) masterVersion += 1 guard let (files, _) = getIndex(deviceUUID: deviceUUID, sharingGroupUUID:sharingGroupUUID), let fileInfoObjs1 = files, fileInfoObjs1.count == 1 else { XCTFail() return } let appMetaData2 = AppMetaData(version: 1, contents: "Test2") let deviceUUID2 = Foundation.UUID().uuidString let workingButBadSharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: workingButBadSharingGroupUUID) else { XCTFail() return } uploadAppMetaDataVersion(deviceUUID: deviceUUID2, fileUUID: uploadResult.request.fileUUID, masterVersion:masterVersion, appMetaData: appMetaData2, sharingGroupUUID:workingButBadSharingGroupUUID, expectedError: true) } } extension FileController_UploadAppMetaDataTests { static var allTests : [(String, (FileController_UploadAppMetaDataTests) -> () throws -> Void)] { return [ ("testUploadAppMetaDataOfInitiallyNilAppMetaDataToVersion1Fails", testUploadAppMetaDataOfInitiallyNilAppMetaDataToVersion1Fails), ("testUpdateFromVersion0ToVersion0Fails", testUpdateFromVersion0ToVersion0Fails), ("testUploadAppMetaDataForDeletedFileFails", testUploadAppMetaDataForDeletedFileFails), ("testUploadAppMetaDataForANonExistentFileFails", testUploadAppMetaDataForANonExistentFileFails), ("testFileDownloadOfBadMetaDataVersionFails", testFileDownloadOfBadMetaDataVersionFails), ("testSuccessUsingFileDownloadToCheck", testSuccessUsingFileDownloadToCheck), ("testSuccessUsingDownloadAppMetaDataToCheck", testSuccessUsingDownloadAppMetaDataToCheck), ("testUploadAppMetaDataOfInitiallyNilAppMetaDataToVersion0Works", testUploadAppMetaDataOfInitiallyNilAppMetaDataToVersion0Works), ("testUploadAppMetaDataWithInvalidSharingGroupUUIDFails", testUploadAppMetaDataWithInvalidSharingGroupUUIDFails), ("testUploadAppMetaDataWithFakeSharingGroupUUIDFails", testUploadAppMetaDataWithFakeSharingGroupUUIDFails) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:FileController_UploadAppMetaDataTests.self) } } <file_sep>// // MockStorageTests.swift // ServerTests // // Created by <NAME> on 6/27/19. // import XCTest @testable import Server class MockStorageTests: XCTestCase, LinuxTestable { func testUploadFile() { let storage = MockStorage() let exp = expectation(description: "upload") storage.uploadFile(cloudFileName: "foo", data: Data(), options: nil) { result in switch result { case .success: break default: XCTFail() break } exp.fulfill() } waitExpectation(timeout: 20, handler: nil) } func testDownloadFile() { let storage = MockStorage() let exp = expectation(description: "download") storage.downloadFile(cloudFileName: "foo", options: nil) { result in switch result { case .success: break default: XCTFail() break } exp.fulfill() } waitExpectation(timeout: 20, handler: nil) } func testDeleteFile() { let storage = MockStorage() let exp = expectation(description: "delete") storage.deleteFile(cloudFileName: "foo", options: nil) { result in switch result { case .success: break default: XCTFail() break } exp.fulfill() } waitExpectation(timeout: 20, handler: nil) } func testLookupFile() { let storage = MockStorage() let exp = expectation(description: "lookup") storage.lookupFile(cloudFileName: "foo", options: nil) { result in switch result { case .success: break default: XCTFail() break } exp.fulfill() } waitExpectation(timeout: 20, handler: nil) } } extension MockStorageTests { static var allTests : [(String, (MockStorageTests) -> () throws -> Void)] { return [ ("testUploadFile", testUploadFile), ("testDownloadFile", testDownloadFile), ("testDeleteFile", testDeleteFile), ("testLookupFile", testLookupFile) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: MockStorageTests.self) } } <file_sep>// // SpecificDatabaseTests_Uploads.swift // Server // // Created by <NAME> on 2/18/17. // // import XCTest @testable import Server import LoggerAPI import HeliumLogger import Credentials import CredentialsGoogle import Foundation import SyncServerShared class SpecificDatabaseTests_Uploads: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func doAddUpload(sharingGroupUUID: String, checkSum: String? = "", mimeType:String? = "text/plain", appMetaData:AppMetaData? = AppMetaData(version: 0, contents: "{ \"foo\": \"bar\" }"), userId:UserId = 1, deviceUUID:String = Foundation.UUID().uuidString, missingField:Bool = false) -> Upload { let upload = Upload() if !missingField { upload.deviceUUID = deviceUUID } upload.lastUploadedCheckSum = checkSum upload.fileUUID = Foundation.UUID().uuidString upload.fileVersion = 1 upload.mimeType = mimeType upload.state = .uploadingFile upload.userId = userId upload.appMetaData = appMetaData?.contents upload.appMetaDataVersion = appMetaData?.version upload.creationDate = Date() upload.updateDate = Date() upload.sharingGroupUUID = sharingGroupUUID let result = UploadRepository(db).add(upload: upload) var uploadId:Int64? switch result { case .success(uploadId: let id): if missingField { XCTFail() } uploadId = id default: if !missingField { XCTFail() } } upload.uploadId = uploadId return upload } func testAddUpload() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } _ = doAddUpload(sharingGroupUUID:sharingGroupUUID) } func testAddUploadWithMissingField() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } _ = doAddUpload(sharingGroupUUID:sharingGroupUUID, missingField: true) } func doAddUploadDeletion(sharingGroupUUID: String, userId:UserId = 1, deviceUUID:String = Foundation.UUID().uuidString, missingField:Bool = false) -> Upload { let upload = Upload() upload.deviceUUID = deviceUUID upload.fileUUID = Foundation.UUID().uuidString upload.fileVersion = 1 upload.state = .toDeleteFromFileIndex upload.sharingGroupUUID = sharingGroupUUID if !missingField { upload.userId = userId } let result = UploadRepository(db).add(upload: upload) var uploadId:Int64? switch result { case .success(uploadId: let id): if missingField { XCTFail() } uploadId = id default: if !missingField { XCTFail() } } if missingField { XCTAssert(uploadId == nil, "Good uploadId!") } else { XCTAssert(uploadId == 1, "Bad uploadId!") upload.uploadId = uploadId } return upload } func testAddUploadDeletion() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } _ = doAddUploadDeletion(sharingGroupUUID:sharingGroupUUID) } func testAddUploadDeletionWithMissingField() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } _ = doAddUploadDeletion(sharingGroupUUID:sharingGroupUUID, missingField:true) } func testAddUploadSucceedsWithNilAppMetaData() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } _ = doAddUpload(sharingGroupUUID:sharingGroupUUID, appMetaData:nil) } func testAddUploadSucceedsWithNilCheckSum() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } _ = doAddUpload(sharingGroupUUID:sharingGroupUUID, checkSum:nil) } func testUpdateUpload() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let upload = doAddUpload(sharingGroupUUID:sharingGroupUUID) XCTAssert(UploadRepository(db).update(upload: upload)) } func testUpdateUploadFailsWithoutUploadId() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let upload = doAddUpload(sharingGroupUUID:sharingGroupUUID) upload.uploadId = nil XCTAssert(!UploadRepository(db).update(upload: upload)) } func testUpdateUploadToUploadedFailsWithoutCheckSum() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let upload = doAddUpload(sharingGroupUUID:sharingGroupUUID) upload.lastUploadedCheckSum = nil upload.state = .uploadedFile XCTAssert(!UploadRepository(db).update(upload: upload)) } func testUpdateUploadSucceedsWithNilAppMetaData() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let upload = doAddUpload(sharingGroupUUID:sharingGroupUUID) upload.appMetaData = nil upload.appMetaDataVersion = nil XCTAssert(UploadRepository(db).update(upload: upload)) } func testLookupFromUpload() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let upload1 = doAddUpload(sharingGroupUUID:sharingGroupUUID) let result = UploadRepository(db).lookup(key: .uploadId(1), modelInit: Upload.init) switch result { case .error(let error): XCTFail("\(error)") case .found(let object): let upload2 = object as! Upload XCTAssert(upload1.deviceUUID != nil && upload1.deviceUUID == upload2.deviceUUID) XCTAssert(upload1.lastUploadedCheckSum != nil && upload1.lastUploadedCheckSum == upload2.lastUploadedCheckSum) XCTAssert(upload1.fileUUID != nil && upload1.fileUUID == upload2.fileUUID) XCTAssert(upload1.fileVersion != nil && upload1.fileVersion == upload2.fileVersion) XCTAssert(upload1.mimeType != nil && upload1.mimeType == upload2.mimeType) XCTAssert(upload1.state != nil && upload1.state == upload2.state) XCTAssert(upload1.userId != nil && upload1.userId == upload2.userId) XCTAssert(upload1.appMetaData != nil && upload1.appMetaData == upload2.appMetaData) case .noObjectFound: XCTFail("No Upload Found") } } func testGetUploadsWithNoFiles() { let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" let result1 = UserRepository(db).add(user: user1, validateJSON: false) XCTAssert(result1 == 1, "Bad credentialsId!") let uploadedFilesResult = UploadRepository(db).uploadedFiles(forUserId: result1!, sharingGroupUUID: UUID().uuidString, deviceUUID: Foundation.UUID().uuidString) switch uploadedFilesResult { case .uploads(let uploads): XCTAssert(uploads.count == 0) case .error(_): XCTFail() } } func testUploadedIndexWithOneFile() { let sharingGroupUUID = UUID().uuidString let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" let userId = UserRepository(db).add(user: user1, validateJSON: false) XCTAssert(userId == 1, "Bad credentialsId!") guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let deviceUUID = Foundation.UUID().uuidString let upload1 = doAddUpload(sharingGroupUUID:sharingGroupUUID, userId:userId!, deviceUUID:deviceUUID) let uploadedFilesResult = UploadRepository(db).uploadedFiles(forUserId: userId!, sharingGroupUUID: sharingGroupUUID, deviceUUID: deviceUUID) switch uploadedFilesResult { case .uploads(let uploads): XCTAssert(uploads.count == 1) XCTAssert(upload1.appMetaData == uploads[0].appMetaData) XCTAssert(upload1.fileUUID == uploads[0].fileUUID) XCTAssert(upload1.fileVersion == uploads[0].fileVersion) XCTAssert(upload1.mimeType == uploads[0].mimeType) XCTAssert(upload1.lastUploadedCheckSum == uploads[0].lastUploadedCheckSum) case .error(_): XCTFail() } } func testUploadedIndexWithInterleavedSharingGroupFiles() { let sharingGroupUUID1 = UUID().uuidString let sharingGroupUUID2 = UUID().uuidString let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" let userId = UserRepository(db).add(user: user1, validateJSON: false) XCTAssert(userId == 1, "Bad credentialsId!") guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID1) else { XCTFail() return } guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID2) else { XCTFail() return } let deviceUUID = Foundation.UUID().uuidString let upload1 = doAddUpload(sharingGroupUUID:sharingGroupUUID1, userId:userId!, deviceUUID:deviceUUID) // This is illustrating an "interleaved" upload-- where a client could have uploaded a file to a different sharing group UUID before doing a DoneUploads. let _ = doAddUpload(sharingGroupUUID:sharingGroupUUID2, userId:userId!, deviceUUID:deviceUUID) let uploadedFilesResult = UploadRepository(db).uploadedFiles(forUserId: userId!, sharingGroupUUID: sharingGroupUUID1, deviceUUID: deviceUUID) switch uploadedFilesResult { case .uploads(let uploads): XCTAssert(uploads.count == 1) XCTAssert(upload1.appMetaData == uploads[0].appMetaData) XCTAssert(upload1.fileUUID == uploads[0].fileUUID) XCTAssert(upload1.fileVersion == uploads[0].fileVersion) XCTAssert(upload1.mimeType == uploads[0].mimeType) XCTAssert(upload1.lastUploadedCheckSum == uploads[0].lastUploadedCheckSum) XCTAssert(upload1.sharingGroupUUID == uploads[0].sharingGroupUUID) case .error(_): XCTFail() } } } extension SpecificDatabaseTests_Uploads { static var allTests : [(String, (SpecificDatabaseTests_Uploads) -> () throws -> Void)] { return [ ("testAddUpload", testAddUpload), ("testAddUploadWithMissingField", testAddUploadWithMissingField), ("testAddUploadDeletion", testAddUploadDeletion), ("testAddUploadDeletionWithMissingField", testAddUploadDeletionWithMissingField), ("testAddUploadSucceedsWithNilAppMetaData", testAddUploadSucceedsWithNilAppMetaData), ("testAddUploadSucceedsWithNilCheckSum", testAddUploadSucceedsWithNilCheckSum), ("testUpdateUpload", testUpdateUpload), ("testUpdateUploadFailsWithoutUploadId", testUpdateUploadFailsWithoutUploadId), ("testUpdateUploadToUploadedFailsWithoutCheckSum", testUpdateUploadToUploadedFailsWithoutCheckSum), ("testUpdateUploadSucceedsWithNilAppMetaData", testUpdateUploadSucceedsWithNilAppMetaData), ("testLookupFromUpload", testLookupFromUpload), ("testGetUploadsWithNoFiles", testGetUploadsWithNoFiles), ("testUploadedIndexWithOneFile", testUploadedIndexWithOneFile), ("testUploadedIndexWithInterleavedSharingGroupFiles", testUploadedIndexWithInterleavedSharingGroupFiles) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SpecificDatabaseTests_Uploads.self) } } <file_sep>USE SyncServer_SharedImages; # USE syncserver; UPDATE FileIndex SET creationDate = Now() - INTERVAL 10 DAY + INTERVAL fileIndexId HOUR; UPDATE FileIndex SET updateDate = creationDate; <file_sep>// // DropboxTests.swift // Server // // Created by <NAME> on 12/10/17. // // import XCTest @testable import Server import Foundation import LoggerAPI import HeliumLogger import SyncServerShared class FileDropboxTests: ServerTestCase, LinuxTestable { // In my Dropbox: let knownPresentFile = "DO-NOT-REMOVE.txt" let knownPresentFile2 = "DO-NOT-REMOVE2.txt" let knownAbsentFile = "Markwa.Farkwa.Blarkwa" override func setUp() { super.setUp() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testCheckForFileFailsWithFileThatDoesNotExist() { let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1.token() creds.accountId = TestAccount.dropbox1.id() let exp = expectation(description: "\(#function)\(#line)") creds.checkForFile(fileName: "foobar") { result in switch result { case .success(let found): XCTAssert(!found) case .failure: XCTFail() case .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testCheckForFileWorksWithExistingFile() { let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1.token() creds.accountId = TestAccount.dropbox1.id() let exp = expectation(description: "\(#function)\(#line)") creds.checkForFile(fileName: knownPresentFile) { result in switch result { case .success(let found): XCTAssert(found) case .failure, .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func uploadFile(file: TestFile, mimeType: MimeType) { let fileName = Foundation.UUID().uuidString let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1.token() creds.accountId = TestAccount.dropbox1.id() let exp = expectation(description: "\(#function)\(#line)") let fileContentsData: Data! switch file.contents { case .string(let fileContents): fileContentsData = fileContents.data(using: .ascii)! case .url(let url): fileContentsData = try? Data(contentsOf: url) } guard fileContentsData != nil else { XCTFail() return } creds.uploadFile(withName: fileName, data: fileContentsData) { result in switch result { case .success(let hash): XCTAssert(hash == file.dropboxCheckSum) case .failure(let error): Log.error("uploadFile: \(error)") XCTFail() case .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testUploadFileWorks() { uploadFile(file: .test1, mimeType: .text) } func testUploadURLFileWorks() { uploadFile(file: .testUrlFile, mimeType: .url) } func testUploadWithRevokedToken() { let fileName = Foundation.UUID().uuidString let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1Revoked.token() creds.accountId = TestAccount.dropbox1Revoked.id() let exp = expectation(description: "\(#function)\(#line)") let stringFile = TestFile.test1 guard case .string(let stringContents) = stringFile.contents else { XCTFail() return } let fileContentsData = stringContents.data(using: .ascii)! creds.uploadFile(withName: fileName, data: fileContentsData) { result in switch result { case .success: XCTFail() case .failure(let error): Log.error("uploadFile: \(error)") XCTFail() case .accessTokenRevokedOrExpired: break } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func fullUpload(file: TestFile, mimeType: MimeType) { let deviceUUID = Foundation.UUID().uuidString let fileUUID = Foundation.UUID().uuidString let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1.token() creds.accountId = TestAccount.dropbox1.id() let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUID uploadRequest.mimeType = mimeType.rawValue uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = UUID().uuidString uploadRequest.checkSum = file.dropboxCheckSum uploadFile(accountType: AccountScheme.dropbox.accountName, creds: creds, deviceUUID:deviceUUID, testFile: file, uploadRequest:uploadRequest) // The second time we try it, it should fail with CloudStorageError.alreadyUploaded -- same file. uploadFile(accountType: AccountScheme.dropbox.accountName, creds: creds, deviceUUID:deviceUUID, testFile: file, uploadRequest:uploadRequest, failureExpected: true, errorExpected: CloudStorageError.alreadyUploaded) } func testFullUploadWorks() { fullUpload(file: .test1, mimeType: .text) } func testFullUploadURLWorks() { fullUpload(file: .testUrlFile, mimeType: .url) } func downloadFile(creds: DropboxCreds, cloudFileName: String, expectedStringFile:TestFile? = nil, expectedFailure: Bool = false, expectedFileNotFound: Bool = false, expectedRevokedToken: Bool = false) { let exp = expectation(description: "\(#function)\(#line)") creds.downloadFile(cloudFileName: cloudFileName) { result in switch result { case .success(let downloadResult): if let expectedStringFile = expectedStringFile { guard case .string(let expectedContents) = expectedStringFile.contents else { XCTFail() return } guard let str = String(data: downloadResult.data, encoding: String.Encoding.ascii) else { XCTFail() Log.error("Failed on string decoding") return } XCTAssert(downloadResult.checkSum == expectedStringFile.dropboxCheckSum) XCTAssert(str == expectedContents) } if expectedFailure || expectedRevokedToken || expectedFileNotFound { XCTFail() } case .failure(let error): if !expectedFailure || expectedRevokedToken || expectedFileNotFound { XCTFail() Log.error("Failed download: \(error)") } case .accessTokenRevokedOrExpired: if !expectedRevokedToken || expectedFileNotFound || expectedFailure { XCTFail() } case .fileNotFound: if !expectedFileNotFound || expectedRevokedToken || expectedFailure{ XCTFail() } } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testDownloadOfNonExistingFileFails() { let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1.token() creds.accountId = TestAccount.dropbox1.id() downloadFile(creds: creds, cloudFileName: knownAbsentFile, expectedFileNotFound: true) } func testSimpleDownloadWorks() { let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1.token() creds.accountId = TestAccount.dropbox1.id() downloadFile(creds: creds, cloudFileName: knownPresentFile) } func testDownloadWithRevokedToken() { let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1Revoked.token() creds.accountId = TestAccount.dropbox1Revoked.id() downloadFile(creds: creds, cloudFileName: knownPresentFile, expectedRevokedToken: true) } func testSimpleDownloadWorks2() { let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1.token() creds.accountId = TestAccount.dropbox1.id() downloadFile(creds: creds, cloudFileName: knownPresentFile2) } func testUploadAndDownloadWorks() { let deviceUUID = Foundation.UUID().uuidString let fileUUID = Foundation.UUID().uuidString let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1.token() creds.accountId = TestAccount.dropbox1.id() let file = TestFile.test1 guard case .string = file.contents else { XCTFail() return } let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUID uploadRequest.mimeType = "text/plain" uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = UUID().uuidString uploadRequest.checkSum = file.dropboxCheckSum uploadFile(accountType: AccountScheme.dropbox.accountName, creds: creds, deviceUUID:deviceUUID, testFile: file, uploadRequest:uploadRequest) let cloudFileName = uploadRequest.cloudFileName(deviceUUID:deviceUUID, mimeType: uploadRequest.mimeType) Log.debug("cloudFileName: \(cloudFileName)") downloadFile(creds: creds, cloudFileName: cloudFileName, expectedStringFile: file) } func deleteFile(creds: DropboxCreds, cloudFileName: String, expectedFailure: Bool = false) { let exp = expectation(description: "\(#function)\(#line)") creds.deleteFile(cloudFileName: cloudFileName) { result in switch result { case .success: if expectedFailure { XCTFail() } case .accessTokenRevokedOrExpired: XCTFail() case .failure(let error): if !expectedFailure { XCTFail() Log.error("Failed download: \(error)") } } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testDeletionWithRevokedAccessToken() { let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1Revoked.token() creds.accountId = TestAccount.dropbox1Revoked.id() let existingFile = knownPresentFile let exp = expectation(description: "\(#function)\(#line)") creds.deleteFile(cloudFileName: existingFile) { result in switch result { case .success: XCTFail() case .accessTokenRevokedOrExpired: break case .failure: XCTFail() } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) let result = lookupFile(cloudFileName: existingFile) XCTAssert(result == true) } func testDeletionOfNonExistingFileFails() { let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1.token() creds.accountId = TestAccount.dropbox1.id() deleteFile(creds: creds, cloudFileName: knownAbsentFile, expectedFailure: true) } func deletionOfExistingFile(file: TestFile, mimeType: MimeType) { let deviceUUID = Foundation.UUID().uuidString let fileUUID = Foundation.UUID().uuidString let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1.token() creds.accountId = TestAccount.dropbox1.id() let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUID uploadRequest.mimeType = mimeType.rawValue uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = UUID().uuidString uploadRequest.checkSum = file.dropboxCheckSum guard let fileName = uploadFile(accountType: AccountScheme.dropbox.accountName, creds: creds, deviceUUID:deviceUUID, testFile:file, uploadRequest:uploadRequest) else { XCTFail() return } deleteFile(creds: creds, cloudFileName: fileName) } func testDeletionOfExistingFileWorks() { deletionOfExistingFile(file: .test1, mimeType: .text) } func testDeletionOfExistingURLFileWorks() { deletionOfExistingFile(file: .testUrlFile, mimeType: .url) } func lookupFile(cloudFileName: String, expectError:Bool = false) -> Bool? { var foundResult: Bool? let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1.token() creds.accountId = TestAccount.dropbox1.id() let exp = expectation(description: "\(#function)\(#line)") creds.lookupFile(cloudFileName:cloudFileName) { result in switch result { case .success(let found): if expectError { XCTFail() } else { foundResult = found } case .failure, .accessTokenRevokedOrExpired: if !expectError { XCTFail() } } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) return foundResult } func testLookupFileThatExists() { let result = lookupFile(cloudFileName: knownPresentFile) XCTAssert(result == true) } func testLookupFileThatDoesNotExist() { let result = lookupFile(cloudFileName: knownAbsentFile) XCTAssert(result == false) } func testLookupWithRevokedAccessToken() { let creds = DropboxCreds()! creds.accessToken = TestAccount.dropbox1Revoked.token() creds.accountId = TestAccount.dropbox1Revoked.id() let exp = expectation(description: "\(#function)\(#line)") creds.lookupFile(cloudFileName:knownPresentFile) { result in switch result { case .success, .failure: XCTFail() case .accessTokenRevokedOrExpired: break } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } } extension FileDropboxTests { static var allTests : [(String, (FileDropboxTests) -> () throws -> Void)] { return [ ("testCheckForFileFailsWithFileThatDoesNotExist", testCheckForFileFailsWithFileThatDoesNotExist), ("testCheckForFileWorksWithExistingFile", testCheckForFileWorksWithExistingFile), ("testUploadFileWorks", testUploadFileWorks), ("testUploadURLFileWorks", testUploadURLFileWorks), ("testUploadWithRevokedToken", testUploadWithRevokedToken), ("testFullUploadWorks", testFullUploadWorks), ("testFullUploadURLWorks", testFullUploadURLWorks), ("testDownloadOfNonExistingFileFails", testDownloadOfNonExistingFileFails), ("testSimpleDownloadWorks", testSimpleDownloadWorks), ("testDownloadWithRevokedToken", testDownloadWithRevokedToken), ("testSimpleDownloadWorks2", testSimpleDownloadWorks2), ("testUploadAndDownloadWorks", testUploadAndDownloadWorks), ("testDeletionWithRevokedAccessToken", testDeletionWithRevokedAccessToken), ("testDeletionOfNonExistingFileFails", testDeletionOfNonExistingFileFails), ("testDeletionOfExistingFileWorks", testDeletionOfExistingFileWorks), ("testDeletionOfExistingURLFileWorks", testDeletionOfExistingURLFileWorks), ("testLookupFileThatDoesNotExist", testLookupFileThatDoesNotExist), ("testLookupFileThatExists", testLookupFileThatExists), ("testLookupWithRevokedAccessToken", testLookupWithRevokedAccessToken) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:FileDropboxTests.self) } } <file_sep>// // CloudStorage.swift // Server // // Created by <NAME> on 12/3/17. // import Foundation import SyncServerShared enum Result<T> { case success(T) // If a user revokes their access token, or it expires, I want to make sure we provide gracefully degraded service. case accessTokenRevokedOrExpired case failure(Swift.Error) } // Some cloud services (e.g., Google Drive) need additional file naming options; other's don't (e.g., Dropbox). If you give these options and the method doesn't need it, they are ignored. struct CloudStorageFileNameOptions { // `String?` because only some cloud storage services need it. let cloudFolderName:String? let mimeType:String } public enum CloudStorageError : Int, Swift.Error { case alreadyUploaded } public enum DownloadResult { // Checksum: value defined by the cloud storage system. This is the checksum value *before* the download. case success (data: Data, checkSum: String) // This is distinguished from the more general failure case because (a) it definitively relects the file not being present in cloud storage, and (b) because it could be due to the user either renaming the file in cloud storage or the file being deleted by the user. case fileNotFound // Similarly, if a user revokes their access token, I want to make sure we provide gracefully degraded service. case accessTokenRevokedOrExpired case failure(Swift.Error) } protocol CloudStorage { // On success, String in result gives checksum of file on server. // Returns .failure(CloudStorageError.alreadyUploaded) in completion if the named file already exists. func uploadFile(cloudFileName:String, data:Data, options:CloudStorageFileNameOptions?, completion:@escaping (Result<String>)->()) func downloadFile(cloudFileName:String, options:CloudStorageFileNameOptions?, completion:@escaping (DownloadResult)->()) func deleteFile(cloudFileName:String, options:CloudStorageFileNameOptions?, completion:@escaping (Result<()>)->()) // On success, returns true iff the file was found. // Used primarily for testing. func lookupFile(cloudFileName:String, options:CloudStorageFileNameOptions?, completion:@escaping (Result<Bool>)->()) } <file_sep>// // UserController+Extras.swift // Server // // Created by <NAME> on 2/21/18. // import Foundation import LoggerAPI extension UserController { enum CreateInitialFileResponse { case success case accessTokenRevokedOrExpired case failure } static func createInitialFileForOwningUser(cloudFolderName: String?, cloudStorage: CloudStorage, completion: @escaping (CreateInitialFileResponse)->()) { guard let fileName = Configuration.server.owningUserAccountCreation.initialFileName, let fileContents = Configuration.server.owningUserAccountCreation.initialFileContents, let data = fileContents.data(using: .utf8) else { // Note: This is not an error-- the server just isn't configured to create these files for owning user accounts. Log.info("No file name and/or contents for initial user file.") completion(.success) return } Log.info("Initial user file being sent to cloud storage: \(fileName)") let options = CloudStorageFileNameOptions(cloudFolderName: cloudFolderName, mimeType: "text/plain") cloudStorage.uploadFile(cloudFileName:fileName, data: data, options:options) { result in switch result { case .success: completion(.success) case .accessTokenRevokedOrExpired: completion(.accessTokenRevokedOrExpired) case .failure(CloudStorageError.alreadyUploaded): // Not considering it an error when the initial file is already there-- user might be recreating an account. Log.info("Could not upload initial file: It already exists.") completion(.success) case .failure(let error): // It's possible the file was successfully uploaded, but we got an error anyways. Delete it. cloudStorage.deleteFile(cloudFileName: fileName, options: options) { _ in // Ignore any error from deletion. We've alread got an error. Log.error("Could not upload initial file: error: \(error)") completion(.failure) } } } } } <file_sep>// Modified from: /** * Copyright IBM Corporation 2016 * * 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. **/ import XCTest import Kitura import HeliumLogger import KituraNet import LoggerAPI import Dispatch import Foundation @testable import Server import CredentialsGoogle import SyncServerShared protocol KituraTest { func expectation(_ index: Int) -> XCTestExpectation func waitExpectation(timeout t: TimeInterval, handler: XCWaitCompletionHandler?) } enum ResponseDictFrom { case body case header } extension KituraTest { func performServerTest(testAccount:TestAccount = .primaryOwningAccount, asyncTask: @escaping (XCTestExpectation, Account) -> Void) { func runTest(usingCreds creds:Account) { Log.info("performServerTest: Starts") ServerMain.startup(type: .nonBlocking) let requestQueue = DispatchQueue(label: "Request queue") let expectation = self.expectation(0) requestQueue.async() { asyncTask(expectation, creds) } // blocks test until request completes self.waitExpectation(timeout: 60) { error in ServerMain.shutdown() XCTAssertNil(error) } // At least with Google accounts, I'm having problems with periodic `unauthorized` responses. Could be due to some form of throttling? if testAccount.scheme.accountName == AccountScheme.google.accountName { sleep(5) } Log.info("performServerTest: Ends") } testAccount.scheme.doHandler(for: .getCredentials, testAccount: testAccount) { creds in runTest(usingCreds: creds) } } // Perform server test, with no creds. e.g., health check. func performServerTest(asyncTask: @escaping (XCTestExpectation) -> Void) { Log.info("performServerTest: Starts") ServerMain.startup(type: .nonBlocking) let requestQueue = DispatchQueue(label: "Request queue") let expectation = self.expectation(0) requestQueue.async() { asyncTask(expectation) } // blocks test until request completes self.waitExpectation(timeout: 60) { error in ServerMain.shutdown() XCTAssertNil(error) } Log.info("performServerTest: Ends") } func performRequest(route:ServerEndpoint, responseDictFrom:ResponseDictFrom = .body, headers: [String: String]? = nil, urlParameters:String? = nil, body:Data? = nil, callback: @escaping (ClientResponse?, [String:Any]?) -> Void) { var allHeaders = [String: String]() if let headers = headers { for (headerName, headerValue) in headers { allHeaders[headerName] = headerValue } } var path = route.pathWithSuffixSlash if urlParameters != nil { path += urlParameters! } allHeaders["Content-Type"] = "text/plain" let options: [ClientRequest.Options] = [.method(route.method.rawValue), .hostname("localhost"), .port(Int16(Configuration.server.port)), .path(path), .headers(allHeaders), .schema("http://")] let req:ClientRequest = HTTP.request(options) { (response:ClientResponse?) in var dict:[String:Any]? if response != nil { dict = self.getResponseDict(response: response!, responseDictFrom:responseDictFrom) } Log.info("Result: \(String(describing: dict)); \(String(describing: response))") callback(response, dict) } if body == nil { req.end() } else { req.end(body!) } } func getResponseDict(response:ClientResponse, responseDictFrom:ResponseDictFrom) -> [String: Any]? { var jsonString:String? switch responseDictFrom { case .body: do { jsonString = try response.readString() } catch (let error) { Log.error("Failed with error \(error)") return nil } case .header: guard let params = response.headers[ServerConstants.httpResponseMessageParams.lowercased()], params.count > 0 else { Log.error("Could not obtain response parameters from header") return nil } Log.info("Result params: \(params)") jsonString = params[0] } Log.info("Result string: \(String(describing: jsonString))") guard jsonString != nil else { Log.error("Empty string obtained") return nil } guard let jsonDict = jsonString!.toJSONDictionary() else { Log.error("Could not convert string to JSON dict") return nil } Log.info("Contents of dictionary:") for (key, value) in jsonDict { Log.info("key: \(key): value: \(value); type of value: \(type(of: value))") } return jsonDict } func setupHeaders(testUser: TestAccount, accessToken:String, deviceUUID:String) -> [String: String] { var headers = [String: String]() headers[ServerConstants.XTokenTypeKey] = testUser.scheme.authTokenType headers[ServerConstants.HTTPOAuth2AccessTokenKey] = accessToken headers[ServerConstants.httpRequestDeviceUUID] = deviceUUID testUser.scheme.specificHeaderSetup(headers: &headers, testUser: testUser) return headers } } extension XCTestCase: KituraTest { func expectation(_ index: Int) -> XCTestExpectation { let expectationDescription = "\(type(of: self))-\(index)" return self.expectation(description: expectationDescription) } func waitExpectation(timeout t: TimeInterval, handler: XCWaitCompletionHandler?) { self.waitForExpectations(timeout: t, handler: handler) } } <file_sep>#!/bin/bash # Usage: runLocally.sh <Server.json> [latest | <ServerRelease>] # This runs a docker image. # Once started, you can test with: # http://localhost:8080/HealthCheck/ # E.g., runLocally.sh ~/Desktop/Apps/SyncServerII/Private/Server/SharedImages-local.json 0.19.1 # E.g., runLocally.sh ~/Desktop/Apps/SyncServerII/Private/Server/ClientTesting-local.json latest SERVER_JSON=$1 SERVER_RELEASE=$2 if [ "empty$SERVER_RELEASE" != "empty" ]; then SERVER_RELEASE=":${SERVER_RELEASE}" fi RUN_DIR=/Users/chris/Desktop/Apps/SyncServer.Run IMAGE=syncserver-runner # Copy Server.json file into the directory where the server's going to look for it cp "${SERVER_JSON}" "${RUN_DIR}"/Server.json docker run -p 8080:8080 --rm -i -t -v "${RUN_DIR}"/:/root/extras crspybits/"${IMAGE}${SERVER_RELEASE}" <file_sep>// // MockStorage.swift // ServerPackageDescription // // Created by <NAME> on 6/27/19. // import Foundation // Stubs of the CloudStorage protocol for load testing so that I don't run into limits with particular cloud storage systems under higher loads. class MockStorage: CloudStorage { let lowDuration: Int = 1 let highDuration: Int = 20 private var duration: Int { return Int.random(in: lowDuration...highDuration) } private func runAfterDuration(completion: @escaping ()->()) { DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(duration)) { completion() } } func uploadFile(cloudFileName: String, data: Data, options: CloudStorageFileNameOptions?, completion: @escaping (Result<String>) -> ()) { runAfterDuration { completion(.success("not-really-a-hash")) } } func downloadFile(cloudFileName: String, options: CloudStorageFileNameOptions?, completion: @escaping (DownloadResult) -> ()) { runAfterDuration { let data = "foobar".data(using: .utf8)! completion(.success(data: data, checkSum: "not-really-a-hash")) } } func deleteFile(cloudFileName: String, options: CloudStorageFileNameOptions?, completion: @escaping (Result<()>) -> ()) { runAfterDuration { completion(.success(())) } } func lookupFile(cloudFileName: String, options: CloudStorageFileNameOptions?, completion: @escaping (Result<Bool>) -> ()) { runAfterDuration { completion(.success(true)) } } } <file_sep>// // Sharing_FileManipulationTests.swift // Server // // Created by <NAME> on 4/15/17. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared import Kitura class Sharing_FileManipulationTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { super.tearDown() } struct SharingUploadResult { let request: UploadFileRequest let checkSum:String let sharingTestAccount:TestAccount let uploadedDeviceUUID: String let redeemResponse: RedeemSharingInvitationResponse } // If not adding a user, you must pass a sharingGroupUUID. @discardableResult func uploadFileBySharingUser(withPermission sharingPermission:Permission, owningAccount: TestAccount, sharingUser: TestAccount = .primarySharingAccount, addUser: Bool = true, sharingGroupUUID: String, failureExpected:Bool = false, fileUUID:String? = nil, fileVersion:FileVersionInt = 0, masterVersion: MasterVersionInt = 0) -> SharingUploadResult? { let deviceUUID1 = Foundation.UUID().uuidString if addUser { guard let _ = addNewUser(testAccount: owningAccount, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID1) else { XCTFail() return nil } } var sharingInvitationUUID:String! // Have that newly created user create a sharing invitation. createSharingInvitation(testAccount: owningAccount, permission: sharingPermission, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID! expectation.fulfill() } var redeemResponse: RedeemSharingInvitationResponse! // Redeem that sharing invitation with a new user redeemSharingInvitation(sharingUser: sharingUser, sharingInvitationUUID:sharingInvitationUUID) { result, expectation in redeemResponse = result expectation.fulfill() } guard redeemResponse != nil else { XCTFail() return nil } let deviceUUID2 = Foundation.UUID().uuidString var owningAccountType: AccountScheme.AccountName if fileVersion == 0 { switch sharingUser.scheme.userType { case .owning: owningAccountType = sharingUser.scheme.accountName case .sharing: owningAccountType = owningAccount.scheme.accountName } } else { owningAccountType = owningAccount.scheme.accountName } // Attempting to upload a file by our sharing user guard let uploadResult = uploadTextFile(testAccount: sharingUser, owningAccountType: owningAccountType, deviceUUID:deviceUUID2, fileUUID: fileUUID, addUser: .no(sharingGroupUUID:sharingGroupUUID), fileVersion: fileVersion, masterVersion: masterVersion + 1, errorExpected: failureExpected) else { if !failureExpected { XCTFail() } return nil } sendDoneUploads(testAccount: sharingUser, expectedNumberOfUploads: 1, deviceUUID:deviceUUID2, masterVersion: masterVersion + 1, sharingGroupUUID: sharingGroupUUID, failureExpected: failureExpected) return SharingUploadResult(request: uploadResult.request, checkSum: uploadResult.checkSum, sharingTestAccount: sharingUser, uploadedDeviceUUID:deviceUUID2, redeemResponse: redeemResponse) } func uploadDeleteFileBySharingUser(withPermission sharingPermission:Permission, sharingUser: TestAccount = .primarySharingAccount, failureExpected:Bool = false) { let deviceUUID1 = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = addNewUser(testAccount: .primaryOwningAccount, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID1) else { XCTFail() return } // And upload a file by that user. guard let uploadResult = uploadTextFile(testAccount: .primaryOwningAccount, deviceUUID:deviceUUID1, addUser:.no(sharingGroupUUID: sharingGroupUUID)) else { XCTFail() return } sendDoneUploads(testAccount: .primaryOwningAccount, expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, sharingGroupUUID:sharingGroupUUID) var sharingInvitationUUID:String! // Have that newly created user create a sharing invitation. createSharingInvitation(permission: sharingPermission, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID! expectation.fulfill() } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } // Redeem that sharing invitation with a new user redeemSharingInvitation(sharingUser: sharingUser, sharingInvitationUUID:sharingInvitationUUID) { _, expectation in expectation.fulfill() } let deviceUUID2 = Foundation.UUID().uuidString let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult.request.fileVersion uploadDeletionRequest.masterVersion = masterVersion + 1 uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(testAccount: sharingUser, uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID2, addUser: false, expectError: failureExpected) sendDoneUploads(testAccount: sharingUser, expectedNumberOfUploads: 1, deviceUUID:deviceUUID2, masterVersion: masterVersion + 1, sharingGroupUUID: sharingGroupUUID, failureExpected:failureExpected) } func downloadFileBySharingUser(withPermission sharingPermission:Permission, sharingUser: TestAccount = .primarySharingAccount, failureExpected:Bool = false) { let deviceUUID1 = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = addNewUser(testAccount: .primaryOwningAccount, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID1) else { XCTFail() return } // And upload a file by that user. guard let uploadResult = uploadTextFile(testAccount: .primaryOwningAccount, deviceUUID:deviceUUID1, addUser:.no(sharingGroupUUID: sharingGroupUUID)) else { XCTFail() return } sendDoneUploads(testAccount: .primaryOwningAccount, expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, sharingGroupUUID: sharingGroupUUID) var sharingInvitationUUID:String! // Have that newly created user create a sharing invitation. createSharingInvitation(permission: sharingPermission, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID! expectation.fulfill() } redeemSharingInvitation(sharingUser: sharingUser, sharingInvitationUUID:sharingInvitationUUID) { _, expectation in expectation.fulfill() } // Now see if we can download the file with the sharing user creds. downloadTextFile(testAccount: sharingUser, masterVersionExpectedWithDownload: 2, uploadFileRequest: uploadResult.request, expectedError:failureExpected) } func downloadDeleteFileBySharingUser(withPermission sharingPermission:Permission, sharingUser: TestAccount = .primarySharingAccount, failureExpected:Bool = false) { let deviceUUID1 = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = addNewUser(testAccount: .primaryOwningAccount, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID1) else { XCTFail() return } // And upload a file by that user. guard let uploadResult = uploadTextFile(testAccount: .primaryOwningAccount, deviceUUID:deviceUUID1, addUser:.no(sharingGroupUUID: sharingGroupUUID)) else { XCTFail() return } sendDoneUploads(testAccount: .primaryOwningAccount, expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, sharingGroupUUID: sharingGroupUUID) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult.request.fileVersion uploadDeletionRequest.masterVersion = uploadResult.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID1, addUser: false, expectError: failureExpected) sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, masterVersion: uploadResult.request.masterVersion + MasterVersionInt(1), sharingGroupUUID: sharingGroupUUID, failureExpected:failureExpected) var sharingInvitationUUID:String! // Have that newly created user create a sharing invitation. createSharingInvitation(permission: sharingPermission, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID! expectation.fulfill() } // Redeem that sharing invitation with a new user redeemSharingInvitation(sharingUser: sharingUser, sharingInvitationUUID:sharingInvitationUUID) { _, expectation in expectation.fulfill() } // The final step of a download deletion is to check the file index-- and make sure it's marked as deleted for us. let deviceUUID2 = Foundation.UUID().uuidString guard let (files, _) = getIndex(testAccount: sharingUser, deviceUUID:deviceUUID2, sharingGroupUUID: sharingGroupUUID), let fileIndex = files, fileIndex.count == 1 else { XCTFail() return } XCTAssert(fileIndex[0].deleted == true) } // MARK: Read sharing user func testThatReadSharingUserCannotUploadAFile() { let sharingGroupUUID = UUID().uuidString let result = uploadFileBySharingUser(withPermission: .read, owningAccount: .primaryOwningAccount, sharingGroupUUID: sharingGroupUUID, failureExpected:true) XCTAssert(result == nil) } func testThatReadSharingUserCannotUploadDeleteAFile() { uploadDeleteFileBySharingUser(withPermission: .read, failureExpected:true) } func testThatReadSharingUserCanDownloadAFile() { downloadFileBySharingUser(withPermission: .read) } func testThatReadSharingUserCanDownloadDeleteAFile() { downloadDeleteFileBySharingUser(withPermission: .read) } func checkFileOwner(uploadedDeviceUUID: String, owningAccount: TestAccount, ownerUserId: UserId, request: UploadFileRequest) { let options = CloudStorageFileNameOptions(cloudFolderName: ServerTestCase.cloudFolderName, mimeType: request.mimeType) let fileName = request.cloudFileName(deviceUUID:uploadedDeviceUUID, mimeType: request.mimeType) Log.debug("Looking for file: \(fileName)") guard let found = lookupFile(forOwningTestAccount: owningAccount, cloudFileName: fileName, options: options), found else { XCTFail() return } var fileIndexObj: FileInfo! let fileIndexResult = FileIndexRepository(db).fileIndex(forSharingGroupUUID: request.sharingGroupUUID) switch fileIndexResult { case .fileIndex(let fileIndex): guard fileIndex.count > 0 else { XCTFail("fileIndex.count: \(fileIndex.count)") return } let filtered = fileIndex.filter {$0.fileUUID == request.fileUUID} guard filtered.count == 1 else { XCTFail() return } fileIndexObj = filtered[0] case .error(_): XCTFail() } XCTAssert(fileIndexObj.cloudStorageType != nil) // Need to make sure that the cloud storage type of the file, in the file index, corresponds to the cloud storage type of the owningAccount. XCTAssert(owningAccount.scheme.cloudStorageType == fileIndexObj.cloudStorageType) } // Check to make sure that if the invited user owns cloud storage that the file was uploaded to their cloud storage. func makeSureSharingOwnerOwnsUploadedFile(result: SharingUploadResult) { if result.sharingTestAccount.scheme.userType == .owning { checkFileOwner(uploadedDeviceUUID: result.uploadedDeviceUUID, owningAccount: result.sharingTestAccount, ownerUserId: result.redeemResponse.userId, request: result.request) } } // MARK: Write sharing user func testThatWriteSharingUserCanUploadAFile() { let sharingGroupUUID = UUID().uuidString guard let result = uploadFileBySharingUser(withPermission: .write, owningAccount: .primaryOwningAccount, sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } makeSureSharingOwnerOwnsUploadedFile(result: result) } // When an owning user uploads a modified file (v1) which was initially uploaded (v0) by another owning user, that original owning user must remain the owner of the modified file. func testThatV0FileOwnerRemainsFileOwner() { // Upload v0 of file. let owningAccount:TestAccount = .primaryOwningAccount let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(testAccount: owningAccount, deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID, let v0UserId = uploadResult.uploadingUserId else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) // Upload v1 of file by another user guard let uploadResult2 = uploadFileBySharingUser(withPermission: .write, owningAccount: owningAccount, addUser: false, sharingGroupUUID: sharingGroupUUID, fileUUID: uploadResult.request.fileUUID, fileVersion: 1, masterVersion: 1) else { XCTFail() return } // Check that the v0 owner still owns the file. checkFileOwner(uploadedDeviceUUID: uploadResult2.uploadedDeviceUUID, owningAccount: owningAccount, ownerUserId: v0UserId, request: uploadResult2.request) } func testThatWriteSharingUserCanUploadDeleteAFile() { uploadDeleteFileBySharingUser(withPermission: .write) } // Upload deletion, including DoneUploads, with files with v0 owners that are different. func testUploadDeletionWithDifferentV0OwnersWorks() { // Upload v0 of file by .primaryOwningAccount user var masterVersion: MasterVersionInt = 0 let deviceUUID = Foundation.UUID().uuidString guard let upload1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = upload1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 guard let upload2 = uploadFileBySharingUser(withPermission: .write, owningAccount: .primaryOwningAccount, addUser: false, sharingGroupUUID: sharingGroupUUID, masterVersion: masterVersion) else { XCTFail() return } masterVersion += 1 let uploadDeletionRequest1 = UploadDeletionRequest() uploadDeletionRequest1.fileUUID = upload1.request.fileUUID uploadDeletionRequest1.fileVersion = upload1.request.fileVersion uploadDeletionRequest1.masterVersion = masterVersion + 1 uploadDeletionRequest1.sharingGroupUUID = sharingGroupUUID uploadDeletion(testAccount: upload2.sharingTestAccount, uploadDeletionRequest: uploadDeletionRequest1, deviceUUID: deviceUUID, addUser: false) let uploadDeletionRequest2 = UploadDeletionRequest() uploadDeletionRequest2.fileUUID = upload2.request.fileUUID uploadDeletionRequest2.fileVersion = upload2.request.fileVersion uploadDeletionRequest2.masterVersion = masterVersion + 1 uploadDeletionRequest2.sharingGroupUUID = sharingGroupUUID uploadDeletion(testAccount: upload2.sharingTestAccount, uploadDeletionRequest: uploadDeletionRequest2, deviceUUID: deviceUUID, addUser: false) sendDoneUploads(testAccount: upload2.sharingTestAccount, expectedNumberOfUploads: 2, deviceUUID:deviceUUID, masterVersion: masterVersion + 1, sharingGroupUUID: sharingGroupUUID) } // Upload deletions must go to the account of the original (v0) owning user. To test this: a) upload v0 of a file, b) have a different user upload v1 of the file. Now upload delete. Make sure the deletion works. func testThatUploadDeletionOfFileAfterV1UploadBySharingUserWorks() { // Upload v0 of file. let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // Upload v1 of file by another user self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) var masterVersion: MasterVersionInt = 1 guard let _ = uploadFileBySharingUser(withPermission: .write, owningAccount: .primaryOwningAccount, addUser: false, sharingGroupUUID: sharingGroupUUID, fileUUID: uploadResult.request.fileUUID, fileVersion: 1, masterVersion: masterVersion) else { XCTFail() return } masterVersion += 2 let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult.request.fileUUID uploadDeletionRequest.fileVersion = 1 uploadDeletionRequest.masterVersion = masterVersion uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID // Original v0 uploader deletes file. uploadDeletion(testAccount: .primaryOwningAccount, uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false) sendDoneUploads(testAccount: .primaryOwningAccount, expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) } // Make sure file actually gets deleted in cloud storage for non-root owning users. func testUploadDeletionForNonRootOwningUserWorks() { let sharingGroupUUID = UUID().uuidString guard let result = uploadFileBySharingUser(withPermission: .write, owningAccount: .primaryOwningAccount, sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let masterVersion: MasterVersionInt = 2 let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = result.request.fileUUID uploadDeletionRequest.fileVersion = 0 uploadDeletionRequest.masterVersion = masterVersion uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID // Original v0 uploader deletes file. uploadDeletion(testAccount: result.sharingTestAccount, uploadDeletionRequest: uploadDeletionRequest, deviceUUID: result.uploadedDeviceUUID, addUser: false) sendDoneUploads(testAccount: result.sharingTestAccount, expectedNumberOfUploads: 1, deviceUUID:result.uploadedDeviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) let options = CloudStorageFileNameOptions(cloudFolderName: ServerTestCase.cloudFolderName, mimeType: result.request.mimeType) // The owner of the file will be either (a) the sharing user if that user is an owning user, or (b) the inviting user otherwise. var owningUser: TestAccount! if result.sharingTestAccount.scheme.userType == .owning { owningUser = result.sharingTestAccount } else { owningUser = .primaryOwningAccount } let fileName = result.request.cloudFileName(deviceUUID:result.uploadedDeviceUUID, mimeType: result.request.mimeType) Log.debug("Looking for file: \(fileName)") guard let found = lookupFile(forOwningTestAccount: owningUser, cloudFileName: fileName, options: options), !found else { XCTFail() return } } func testThatWriteSharingUserCanDownloadAFile() { downloadFileBySharingUser(withPermission: .write) } func testThatWriteSharingUserCanDownloadDeleteAFile() { downloadDeleteFileBySharingUser(withPermission: .write) } // MARK: Admin sharing user func testThatAdminSharingUserCanUploadAFile() { let sharingGroupUUID = UUID().uuidString guard let result = uploadFileBySharingUser(withPermission: .admin, owningAccount: .primaryOwningAccount, sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } makeSureSharingOwnerOwnsUploadedFile(result: result) } func testThatAdminSharingUserCanUploadDeleteAFile() { uploadDeleteFileBySharingUser(withPermission: .admin) } func testThatAdminSharingUserCanDownloadAFile() { downloadFileBySharingUser(withPermission: .admin) } func testThatAdminSharingUserCanDownloadDeleteAFile() { downloadDeleteFileBySharingUser(withPermission: .admin) } // MARK: Across sharing and owning users. func owningUserCanDownloadSharingUserFile(sharingUser: TestAccount = .primarySharingAccount) { let sharingGroupUUID = UUID().uuidString guard let result = uploadFileBySharingUser(withPermission: .write, owningAccount: .primaryOwningAccount, sharingUser: sharingUser, sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } downloadTextFile(testAccount: .primaryOwningAccount, masterVersionExpectedWithDownload: 2, uploadFileRequest: result.request, expectedError:false) } func testThatOwningUserCanDownloadSharingUserFile() { owningUserCanDownloadSharingUserFile() } func sharingUserCanDownloadSharingUserFile(sharingUser: TestAccount = .secondarySharingAccount) { // uploaded by primarySharingAccount let sharingGroupUUID = UUID().uuidString guard let result = uploadFileBySharingUser(withPermission: .write, owningAccount: .primaryOwningAccount, sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID: sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID! expectation.fulfill() } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } // Redeem that sharing invitation with a new user redeemSharingInvitation(sharingUser: sharingUser, sharingInvitationUUID:sharingInvitationUUID) { _, expectation in expectation.fulfill() } downloadTextFile(testAccount: sharingUser, masterVersionExpectedWithDownload: Int(masterVersion + 1), uploadFileRequest: result.request, expectedError:false) } func testThatSharingUserCanDownloadSharingUserFile() { sharingUserCanDownloadSharingUserFile() } // After accepting a sharing invitation as an owning user (e.g., Google or Dropbox user), make sure auth tokens are stored, for that redeeming user, so that we can access cloud storage of that user. func testCanAccessCloudStorageOfRedeemingUser() { var sharingUserId: UserId! let sharingUser:TestAccount = .primarySharingAccount if sharingUser.scheme.userType == .owning { createSharingUser(sharingUser: sharingUser) { newUserId, _, _ in sharingUserId = newUserId } guard sharingUserId != nil else { XCTFail() return } let accountDelegate = AccountDelegateHandler(userRepository: UserRepository(db)) // Reconstruct the creds of the sharing user and attempt to access their cloud storage. guard let cloudStorageCreds = FileController.getCreds(forUserId: sharingUserId, from: db, delegate: accountDelegate) as? CloudStorage else { XCTFail() return } let exp = expectation(description: "test1") // It doesn't matter if the file here is found or not found; what matters is that the operation doesn't fail. let options = CloudStorageFileNameOptions(cloudFolderName: ServerTestCase.cloudFolderName, mimeType: "text/plain") cloudStorageCreds.lookupFile(cloudFileName: "foobar", options: options) { result in switch result { case .success(let result): Log.debug("cloudStorageCreds.lookupFile: success: found: \(result)") break case .failure(let error): XCTFail("\(error)") case .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } } // User A invites B. B has cloud storage. B uploads. It goes to B's storage. Both A and B can download the file. func testUploadByOwningSharingUserThenDownloadByBothWorks() { let sharingAccount: TestAccount = .secondaryOwningAccount let sharingGroupUUID = UUID().uuidString guard let result = uploadFileBySharingUser(withPermission: .write, owningAccount: .primaryOwningAccount, sharingUser: sharingAccount, sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } makeSureSharingOwnerOwnsUploadedFile(result: result) guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard let _ = downloadTextFile(testAccount: sharingAccount, masterVersionExpectedWithDownload: Int(masterVersion), uploadFileRequest: result.request) else { XCTFail() return } guard let _ = downloadTextFile(testAccount: .primaryOwningAccount, masterVersionExpectedWithDownload: Int(masterVersion), uploadFileRequest: result.request) else { XCTFail() return } } // Add a regular user. Invite a sharing user. Delete that regular user. See what happens if the sharing user tries to upload a file. func testUploadByOwningSharingUserAfterInvitingUserDeletedWorks() { var actualSharingGroupUUID:String! // Using an owning account here as sharing user because we always want the upload to work after deleting the inviting user. let sharingAccount: TestAccount = .secondaryOwningAccount createSharingUser(withSharingPermission: .write, sharingUser: sharingAccount) { userId, sharingGroupUUID, _ in actualSharingGroupUUID = sharingGroupUUID } guard actualSharingGroupUUID != nil else { XCTFail() return } let deviceUUID = Foundation.UUID().uuidString // remove the regular/inviting user performServerTest(testAccount: .primaryOwningAccount) { expectation, creds in let headers = self.setupHeaders(testUser: .primaryOwningAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.removeUser, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "removeUser failed") expectation.fulfill() } } // Attempting to upload a file by our sharing user-- this should work because the sharing user owns cloud storage. guard let _ = uploadTextFile(testAccount: sharingAccount, deviceUUID:deviceUUID, addUser: .no(sharingGroupUUID:actualSharingGroupUUID), masterVersion: 1) else { XCTFail() return } } func testUploadByNonOwningSharingUserAfterInvitingUserDeletedRespondsWithGone() { var actualSharingGroupUUID:String! let sharingAccount: TestAccount = .nonOwningSharingAccount let owningUserWhenCreating:TestAccount = .primaryOwningAccount createSharingUser(withSharingPermission: .write, sharingUser: sharingAccount, owningUserWhenCreating: owningUserWhenCreating) { userId, sharingGroupUUID, _ in actualSharingGroupUUID = sharingGroupUUID } guard actualSharingGroupUUID != nil else { XCTFail() return } let deviceUUID = Foundation.UUID().uuidString // remove the regular/inviting user performServerTest(testAccount: .primaryOwningAccount) { expectation, creds in let headers = self.setupHeaders(testUser: .primaryOwningAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.removeUser, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "removeUser failed") expectation.fulfill() } } // Attempting to upload a file by our sharing user-- this should fail with HTTP 410 (Gone) because the sharing user does not own cloud storage. let result = uploadTextFile(testAccount: sharingAccount, owningAccountType: owningUserWhenCreating.scheme.accountName, deviceUUID:deviceUUID, addUser: .no(sharingGroupUUID:actualSharingGroupUUID), masterVersion: 1, errorExpected: true, statusCodeExpected: HTTPStatusCode.gone) XCTAssert(result == nil) } // Similar to that above, but the non-owning, sharing user downloads a file-- that was owned by a third user, that is still on the system, and was in the same sharing group. func testDownloadFileOwnedByThirdUserAfterInvitingUserDeletedWorks() { var actualSharingGroupUUID:String! let sharingAccount1: TestAccount = .nonOwningSharingAccount // This account must be an owning account. let sharingAccount2: TestAccount = .secondaryOwningAccount createSharingUser(withSharingPermission: .write, sharingUser: sharingAccount1) { userId, sharingGroupUUID, _ in actualSharingGroupUUID = sharingGroupUUID } guard var masterVersion = getMasterVersion(sharingGroupUUID: actualSharingGroupUUID) else { XCTFail() return } createSharingUser(withSharingPermission: .write, sharingUser: sharingAccount2, addUser: .no(sharingGroupUUID: actualSharingGroupUUID)) masterVersion += 1 let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(testAccount: sharingAccount2, deviceUUID:deviceUUID, addUser: .no(sharingGroupUUID:actualSharingGroupUUID), masterVersion: masterVersion) else { XCTFail() return } self.sendDoneUploads(testAccount: sharingAccount2, expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: actualSharingGroupUUID) masterVersion += 1 let deviceUUID2 = Foundation.UUID().uuidString // remove the regular/inviting user performServerTest(testAccount: .primaryOwningAccount) { expectation, creds in let headers = self.setupHeaders(testUser: .primaryOwningAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID2) self.performRequest(route: ServerEndpoints.removeUser, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "removeUser failed") expectation.fulfill() } } guard let _ = downloadTextFile(testAccount: sharingAccount1, masterVersionExpectedWithDownload: Int(masterVersion), uploadFileRequest: uploadResult.request) else { XCTFail() return } } // File operations work for a second sharing group you are a member of: Upload func testThatUploadForSecondSharingGroupWorks() { let owningAccount: TestAccount = .primaryOwningAccount guard let (sharingAccount, sharingGroupUUID) = redeemWithAnExistingOtherSharingAccount() else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } var owningAccountType: AccountScheme.AccountName? if sharingAccount.scheme.userType == .owning { owningAccountType = sharingAccount.scheme.accountName } else { owningAccountType = owningAccount.scheme.accountName } guard let _ = uploadTextFile(testAccount: sharingAccount, owningAccountType: owningAccountType, addUser: .no(sharingGroupUUID:sharingGroupUUID), masterVersion: masterVersion) else { XCTFail() return } } func testThatDoneUploadsForSecondSharingGroupWorks() { let owningAccount: TestAccount = .primaryOwningAccount guard let (sharingAccount, sharingGroupUUID) = redeemWithAnExistingOtherSharingAccount() else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } var owningAccountType: AccountScheme.AccountName? if sharingAccount.scheme.userType == .owning { owningAccountType = sharingAccount.scheme.accountName } else { owningAccountType = owningAccount.scheme.accountName } let deviceUUID = Foundation.UUID().uuidString guard let _ = uploadTextFile(testAccount: sharingAccount, owningAccountType: owningAccountType, deviceUUID: deviceUUID, addUser: .no(sharingGroupUUID:sharingGroupUUID), masterVersion: masterVersion) else { XCTFail() return } sendDoneUploads(testAccount: sharingAccount, expectedNumberOfUploads: 1, deviceUUID: deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) } func testThatDownloadForSecondSharingGroupWorks() { let owningAccount: TestAccount = .primaryOwningAccount guard let (sharingAccount, sharingGroupUUID) = redeemWithAnExistingOtherSharingAccount() else { XCTFail() return } guard let masterVersion = getMasterVersion(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } var owningAccountType: AccountScheme.AccountName? if sharingAccount.scheme.userType == .owning { owningAccountType = sharingAccount.scheme.accountName } else { owningAccountType = owningAccount.scheme.accountName } let deviceUUID = Foundation.UUID().uuidString guard let result = uploadTextFile(testAccount: sharingAccount, owningAccountType: owningAccountType, deviceUUID: deviceUUID, addUser: .no(sharingGroupUUID:sharingGroupUUID), masterVersion: masterVersion) else { XCTFail() return } sendDoneUploads(testAccount: sharingAccount, expectedNumberOfUploads: 1, deviceUUID: deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) downloadTextFile(testAccount: sharingAccount, masterVersionExpectedWithDownload: Int(masterVersion+1), uploadFileRequest: result.request) } } extension Sharing_FileManipulationTests { static var allTests : [(String, (Sharing_FileManipulationTests) -> () throws -> Void)] { return [ ("testThatReadSharingUserCannotUploadAFile", testThatReadSharingUserCannotUploadAFile), ("testThatReadSharingUserCannotUploadDeleteAFile", testThatReadSharingUserCannotUploadDeleteAFile), ("testThatReadSharingUserCanDownloadAFile", testThatReadSharingUserCanDownloadAFile), ("testThatReadSharingUserCanDownloadDeleteAFile", testThatReadSharingUserCanDownloadDeleteAFile), ("testThatWriteSharingUserCanUploadAFile", testThatWriteSharingUserCanUploadAFile), ("testThatV0FileOwnerRemainsFileOwner", testThatV0FileOwnerRemainsFileOwner), ("testUploadDeletionWithDifferentV0OwnersWorks", testUploadDeletionWithDifferentV0OwnersWorks), ("testThatUploadDeletionOfFileAfterV1UploadBySharingUserWorks", testThatUploadDeletionOfFileAfterV1UploadBySharingUserWorks), ("testUploadDeletionForNonRootOwningUserWorks", testUploadDeletionForNonRootOwningUserWorks), ("testThatWriteSharingUserCanUploadDeleteAFile", testThatWriteSharingUserCanUploadDeleteAFile), ("testThatWriteSharingUserCanDownloadAFile", testThatWriteSharingUserCanDownloadAFile), ("testThatWriteSharingUserCanDownloadDeleteAFile", testThatWriteSharingUserCanDownloadDeleteAFile), ("testThatAdminSharingUserCanUploadAFile", testThatAdminSharingUserCanUploadAFile), ("testThatAdminSharingUserCanUploadDeleteAFile", testThatAdminSharingUserCanUploadDeleteAFile), ("testThatAdminSharingUserCanDownloadAFile", testThatAdminSharingUserCanDownloadAFile), ("testThatAdminSharingUserCanDownloadDeleteAFile", testThatAdminSharingUserCanDownloadDeleteAFile), ("testThatOwningUserCanDownloadSharingUserFile", testThatOwningUserCanDownloadSharingUserFile), ("testThatSharingUserCanDownloadSharingUserFile", testThatSharingUserCanDownloadSharingUserFile), ("testUploadByOwningSharingUserThenDownloadByBothWorks", testUploadByOwningSharingUserThenDownloadByBothWorks), ("testCanAccessCloudStorageOfRedeemingUser", testCanAccessCloudStorageOfRedeemingUser), ("testUploadByOwningSharingUserAfterInvitingUserDeletedWorks", testUploadByOwningSharingUserAfterInvitingUserDeletedWorks), ("testUploadByNonOwningSharingUserAfterInvitingUserDeletedRespondsWithGone", testUploadByNonOwningSharingUserAfterInvitingUserDeletedRespondsWithGone), ("testDownloadFileOwnedByThirdUserAfterInvitingUserDeletedWorks", testDownloadFileOwnedByThirdUserAfterInvitingUserDeletedWorks), ("testThatUploadForSecondSharingGroupWorks", testThatUploadForSecondSharingGroupWorks), ("testThatDoneUploadsForSecondSharingGroupWorks", testThatDoneUploadsForSecondSharingGroupWorks), ("testThatDownloadForSecondSharingGroupWorks", testThatDownloadForSecondSharingGroupWorks) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:Sharing_FileManipulationTests.self) } } <file_sep>// // MicrosofttCreds+CloudStorage.swift // Server // // Created by <NAME> on 9/7/19. // import Foundation import LoggerAPI import HeliumLogger import KituraNet import SyncServerShared extension MicrosoftCreds : CloudStorage { enum OneDriveFailure: Swift.Error { case urlEncoding case mimeTypeEncoding case noAPIResult case noDataInAPIResult case couldNotDecodeError case otherError(ErrorResult) case badStatusCode(HTTPStatusCode?, ErrorResult?) case couldNotDecodeResult case couldNotGetOptions case couldNotGetSelf case fileNotFound case couldNotEncodeBody case couldNotCreateUploadState case expiredOrRevokedAccessToken } func basicHeaders(withContentTypeHeader contentType:String = "application/json") -> [String: String] { var headers = [String:String]() headers["Authorization"] = "Bearer \(accessToken!)" headers["Content-Type"] = contentType return headers } func uploadFile(cloudFileName: String, data: Data, options: CloudStorageFileNameOptions?, completion: @escaping (Result<String>) -> ()) { guard let options = options, let mimeType = MimeType(rawValue: options.mimeType) else { completion(.failure(OneDriveFailure.couldNotGetOptions)) return } checkForFile(fileName: cloudFileName) {[weak self] result in guard let self = self else { completion(.failure(OneDriveFailure.couldNotGetSelf)) return } switch result { case .success(.fileFound): completion(.failure(CloudStorageError.alreadyUploaded)) case .success(.fileNotFound): //self.uploadFile(withName: cloudFileName, mimeType: mimeType, data: data, completion: completion) self.uploadFileUsingSession(withName: cloudFileName, mimeType: mimeType, data: data, completion: completion) case .failure(let error): completion(.failure(error)) case .accessTokenRevokedOrExpired: completion(.accessTokenRevokedOrExpired) } } } func downloadFile(cloudFileName: String, options: CloudStorageFileNameOptions?, completion: @escaping (DownloadResult) -> ()) { // First do a `checkForFile` to get the file's checksum. checkForFile(fileName: cloudFileName) {[weak self] result in guard let self = self else { completion(.failure(OneDriveFailure.couldNotGetSelf)) return } switch result { case .success(.fileFound(let fileResult)): self.downloadFile(cloudFileName: cloudFileName) { result in switch result { case .success(let data): completion(.success( data: data, checkSum: fileResult.file.hashes.sha1Hash)) case .failure(let error): completion(.failure(error)) case .accessTokenRevokedOrExpired: completion(.accessTokenRevokedOrExpired) } } case .success(.fileNotFound): completion(.fileNotFound) case .accessTokenRevokedOrExpired: completion(.accessTokenRevokedOrExpired) case .failure(let error): completion(.failure(error)) } } } func deleteFile(cloudFileName: String, options: CloudStorageFileNameOptions?, completion: @escaping (Result<()>) -> ()) { deleteFile(cloudFileName: cloudFileName, completion: completion) } func lookupFile(cloudFileName: String, options: CloudStorageFileNameOptions?, completion: @escaping (Result<Bool>) -> ()) { checkForFile(fileName: cloudFileName) { result in switch result { case .success(.fileFound): completion(.success(true)) case .success(.fileNotFound): completion(.success(false)) case .accessTokenRevokedOrExpired: completion(.accessTokenRevokedOrExpired) case .failure(let error): completion(.failure(error)) } } } } // MARK: Helpers extension MicrosoftCreds { func accessTokenIsRevokedOrExpired(errorResult: ErrorResult, statusCode: HTTPStatusCode?) -> Bool { // From my testing, this error catches only an expired token. So far in my testing it seems there is no such thing as a revoked access token. See testSimpleDownloadWithRevokedAccessTokenFails. if errorResult.error.code == MicrosoftCreds.ErrorResult.invalidAuthToken { return true } return false } struct ErrorResult: Codable { // Assuming this response means an expired auth code static let invalidAuthToken = "<PASSWORD>" struct TheError: Codable { let code: String let message: String } let error: TheError } var graphBaseURL: String { return "graph.microsoft.com/v1.0" } struct FileResult: Decodable { let id: String // Lots of other fields in this too. struct File: Decodable { let mimeType: String struct Hashes: Decodable { let quickXorHash: String let sha1Hash: String } let hashes: Hashes } let file: File } struct FileCheck: Decodable { let value: [FileResult] } enum CheckForFileResult { case fileNotFound case fileFound(FileResult) } func checkForFile(fileName: String, completion:@escaping (Result<CheckForFileResult>)->()) { // /me/drive/root:/{item-path} // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_get?view=odsp-graph-online let path = "/me/drive/special/approot:/\(fileName)" guard let encodedPath = encoded(string: path, additionalExcludedCharacters: "()''") else { Log.error("Failed encoding path.") completion(.failure(OneDriveFailure.urlEncoding)) return } self.apiCall(method: "GET", baseURL: graphBaseURL, path: encodedPath, additionalHeaders: basicHeaders(), expectedSuccessBody: .data, expectedFailureBody: .data) {[weak self] apiResult, statusCode, responseHeaders in guard let self = self else { completion(.failure(OneDriveFailure.couldNotGetSelf)) return } Log.debug("apiResult: \(String(describing: apiResult)); statusCode: \(String(describing: statusCode))") guard let apiResult = apiResult else { completion(.failure(OneDriveFailure.noAPIResult)) return } guard case .data(let data) = apiResult else { completion(.failure(OneDriveFailure.noDataInAPIResult)) return } let decoder = JSONDecoder() guard statusCode == HTTPStatusCode.OK else { guard let errorResult = try? decoder.decode(ErrorResult.self, from: data) else { completion(.failure(OneDriveFailure.couldNotDecodeError)) return } guard !self.accessTokenIsRevokedOrExpired(errorResult: errorResult, statusCode: statusCode) else { completion(.accessTokenRevokedOrExpired) return } if errorResult.error.code == "itemNotFound" { completion(.success(.fileNotFound)) return } completion(.failure(OneDriveFailure.badStatusCode(statusCode, errorResult))) return } guard let fileResult = try? decoder.decode(FileResult.self, from: data) else { completion(.failure(OneDriveFailure.couldNotDecodeResult)) return } completion(.success(.fileFound(fileResult))) } } // I initially tried using the search-based method below for checkForFile. However, there seems to be a latency between uploading a file and being able to search for that file and find it. #if false // Not using a mimeType to check for a file existing. Can OneDrive have two different files with the same file name but different mimeTypes? func checkForFile2(fileName: String, completion:@escaping (Result<Bool>)->()) { // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/concepts/special-folders-appfolder?view=odsp-graph-online // Shows: GET /drive/special/approot:/{path}:/search // And that links to: // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_search?view=odsp-graph-online let path = "/me/drive/special/approot/search(q='\(fileName)')" guard let encodedPath = encoded(string: path, additionalExcludedCharacters: "()''") else { Log.error("Failed encoding path.") completion(.failure(OneDriveFailure.urlEncoding)) return } self.apiCall(method: "GET", baseURL: graphBaseURL, path: encodedPath, additionalHeaders: basicHeaders(), expectedSuccessBody: .data, expectedFailureBody: .data) { apiResult, statusCode, responseHeaders in Log.debug("apiResult: \(String(describing: apiResult)); statusCode: \(String(describing: statusCode))") guard let apiResult = apiResult else { completion(.failure(OneDriveFailure.noAPIResult)) return } guard case .data(let data) = apiResult else { completion(.failure(OneDriveFailure.noDataInAPIResult)) return } guard statusCode == HTTPStatusCode.OK else { completion(.failure(OneDriveFailure.badStatusCode(statusCode))) return } let decoder = JSONDecoder() guard let fileCheckResult = try? decoder.decode(FileCheckResult.self, from: data) else { completion(.failure(OneDriveFailure.couldNotDecodeError)) return } completion(.success(!fileCheckResult.value.isEmpty)) } } #endif // String in successful result is checksum. // This is for uploading files up to 4MB in size. func uploadFile(withName fileName: String, mimeType: MimeType, data:Data, completion:@escaping (Result<String>)->()) { // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/concepts/special-folders-appfolder?view=odsp-graph-online // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_put_content?view=odsp-graph-online let path = "/me/drive/special/approot:/\(fileName):/content" guard let encodedPath = encoded(string: path) else { Log.error("Failed encoding path.") completion(.failure(OneDriveFailure.urlEncoding)) return } guard let encodedMimeType = encoded(string: mimeType.rawValue, additionalExcludedCharacters: "/") else { Log.error("Failed encoding mimeType.") completion(.failure(OneDriveFailure.mimeTypeEncoding)) return } self.apiCall(method: "PUT", baseURL: graphBaseURL, path: encodedPath, additionalHeaders: basicHeaders(withContentTypeHeader: encodedMimeType), body: .data(data), expectedSuccessBody: .data, expectedFailureBody: .data) { apiResult, statusCode, responseHeaders in Log.debug("apiResult: \(String(describing: apiResult)); statusCode: \(String(describing: statusCode))") guard let apiResult = apiResult else { completion(.failure(OneDriveFailure.noAPIResult)) return } guard case .data(let data) = apiResult else { completion(.failure(OneDriveFailure.noDataInAPIResult)) return } let decoder = JSONDecoder() guard statusCode == HTTPStatusCode.created || statusCode == HTTPStatusCode.OK else { guard let errorResult = try? decoder.decode(ErrorResult.self, from: data) else { completion(.failure(OneDriveFailure.couldNotDecodeError)) return } guard !self.accessTokenIsRevokedOrExpired(errorResult: errorResult, statusCode: statusCode) else { completion(.accessTokenRevokedOrExpired) return } completion(.failure(OneDriveFailure.badStatusCode(statusCode, errorResult))) return } guard let uploadResult = try? decoder.decode(FileResult.self, from: data) else { completion(.failure(OneDriveFailure.couldNotDecodeResult)) return } completion(.success(uploadResult.file.hashes.sha1Hash)) } } /// Download the file, but don't get the checksum. func downloadFile(cloudFileName: String, completion: @escaping (Result<Data>) -> ()) { // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_get_content?view=odsp-graph-online // Note that this endpoint initially generates a "302 Found" response-- and I think the HTTP library I'm using must follow it because I get the downloaded file-- and not the preauthenticated link. let path = "/me/drive/special/approot:/\(cloudFileName):/content" guard let encodedPath = encoded(string: path) else { Log.error("Failed encoding path.") completion(.failure(OneDriveFailure.urlEncoding)) return } // To not traverse the "302 Found" response redirect // let additionalOptions: [ClientRequest.Options] = [.maxRedirects(0)] let additionalOptions: [ClientRequest.Options] = [] self.apiCall(method: "GET", baseURL: graphBaseURL, path: encodedPath, additionalHeaders: basicHeaders(), additionalOptions: additionalOptions, expectedSuccessBody: .data, expectedFailureBody: .data) { apiResult, statusCode, responseHeaders in Log.debug("apiResult: \(String(describing: apiResult)); statusCode: \(String(describing: statusCode))") guard let apiResult = apiResult else { completion(.failure(OneDriveFailure.noAPIResult)) return } guard case .data(let data) = apiResult else { completion(.failure(OneDriveFailure.noDataInAPIResult)) return } // When handling a 302, need to do: /* guard statusCode == HTTPStatusCode.movedTemporarily else { completion(.failure(OneDriveFailure.badStatusCode(statusCode))) return } // And then the preauthenticated download link is in here: let location = responseHeaders?["Location"] ?? [] Log.debug("Location: \(location)") */ guard statusCode == HTTPStatusCode.OK else { let decoder = JSONDecoder() guard let errorResult = try? decoder.decode(ErrorResult.self, from: data) else { completion(.failure(OneDriveFailure.couldNotDecodeError)) return } guard !self.accessTokenIsRevokedOrExpired(errorResult: errorResult, statusCode: statusCode) else { completion(.accessTokenRevokedOrExpired) return } completion(.failure(OneDriveFailure.badStatusCode(statusCode, errorResult))) return } completion(.success(data)) } } func deleteFile(itemId: String, completion: @escaping (Result<()>) -> ()) { // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_delete?view=odsp-graph-online // DELETE /me/drive/items/{item-id} // This deletes the entire app folder! Yike! // let path = "/me/drive/special/approot/items/\(itemId)" // I wonder if this is related to https://answers.microsoft.com/en-us/windows/forum/all/onedrive-automatically-deleting-files-from/f9582c7f-ae84-474c-b470-4e941b6682a1?page=7 let path = "/me/drive/items/\(itemId)" guard let encodedPath = encoded(string: path) else { Log.error("Failed encoding path.") completion(.failure(OneDriveFailure.urlEncoding)) return } self.apiCall(method: "DELETE", baseURL: graphBaseURL, path: encodedPath, additionalHeaders: basicHeaders(), expectedFailureBody: .data) { apiResult, statusCode, responseHeaders in guard statusCode == HTTPStatusCode.noContent else { guard let apiResult = apiResult else { completion(.failure(OneDriveFailure.noAPIResult)) return } guard case .data(let data) = apiResult else { completion(.failure(OneDriveFailure.noDataInAPIResult)) return } let decoder = JSONDecoder() guard let errorResult = try? decoder.decode(ErrorResult.self, from: data) else { completion(.failure(OneDriveFailure.couldNotDecodeError)) return } guard !self.accessTokenIsRevokedOrExpired(errorResult: errorResult, statusCode: statusCode) else { completion(.accessTokenRevokedOrExpired) return } completion(.failure(OneDriveFailure.badStatusCode(statusCode, nil))) return } completion(.success(())) } } func deleteFile(cloudFileName: String, completion: @escaping (Result<()>) -> ()) { // Before we can delete the file, we need it's item id checkForFile(fileName: cloudFileName) {[weak self] result in guard let self = self else { completion(.failure(OneDriveFailure.couldNotGetSelf)) return } switch result { case .success(.fileFound(let fileResult)): self.deleteFile(itemId: fileResult.id, completion: completion) case .success(.fileNotFound): completion(.failure(OneDriveFailure.fileNotFound)) case .accessTokenRevokedOrExpired: completion(.accessTokenRevokedOrExpired) case .failure(let error): completion(.failure(error)) } } } } <file_sep>#!/bin/bash # Purpose: Update an environment using a new bundle.zip file eb deploy <file_sep>// // SpecificDatabaseTests_SharingGroupUsers.swift // ServerTests // // Created by <NAME> on 7/4/18. // import XCTest @testable import Server import LoggerAPI import HeliumLogger import Foundation import SyncServerShared class SpecificDatabaseTests_SharingGroupUsers: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } @discardableResult func addSharingGroupUser(sharingGroupUUID: String, userId: UserId, owningUserId: UserId?, failureExpected: Bool = false) -> SharingGroupUserId? { let result = SharingGroupUserRepository(db).add(sharingGroupUUID: sharingGroupUUID, userId: userId, permission: .read, owningUserId: owningUserId) var sharingGroupUserId:SharingGroupUserId? switch result { case .success(sharingGroupUserId: let id): if failureExpected { XCTFail() } else { sharingGroupUserId = id } case .error: if !failureExpected { XCTFail() } } return sharingGroupUserId } func testAddSharingGroupUser() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" guard let userId: UserId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail() return } guard let _ = addSharingGroupUser(sharingGroupUUID:sharingGroupUUID, userId: userId, owningUserId: nil) else { XCTFail() return } } func testAddMultipleSharingGroupUsers() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" guard let userId1: UserId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail() return } guard let id1 = addSharingGroupUser(sharingGroupUUID:sharingGroupUUID, userId: userId1, owningUserId: nil) else { XCTFail() return } let user2 = User() user2.username = "Chris" user2.accountType = AccountScheme.google.accountName user2.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user2.credsId = "101" guard let userId2: UserId = UserRepository(db).add(user: user2, validateJSON: false) else { XCTFail() return } guard let id2 = addSharingGroupUser(sharingGroupUUID:sharingGroupUUID, userId: userId2, owningUserId: nil) else { XCTFail() return } XCTAssert(id1 != id2) } func testAddSharingGroupUserFailsIfYouAddTheSameUserToSameGroupTwice() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" guard let userId1: UserId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail() return } guard let _ = addSharingGroupUser(sharingGroupUUID:sharingGroupUUID, userId: userId1, owningUserId: nil) else { XCTFail() return } addSharingGroupUser(sharingGroupUUID:sharingGroupUUID, userId: userId1, owningUserId: nil, failureExpected: true) } func testLookupFromSharingGroupUser() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard MasterVersionRepository(db).initialize(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessToken<PASSWORD>\"}" user1.credsId = "100" guard let userId: UserId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail() return } guard let _ = addSharingGroupUser(sharingGroupUUID:sharingGroupUUID, userId: userId, owningUserId: nil) else { XCTFail() return } let key = SharingGroupUserRepository.LookupKey.primaryKeys(sharingGroupUUID: sharingGroupUUID, userId: userId) let result = SharingGroupUserRepository(db).lookup(key: key, modelInit: SharingGroupUser.init) switch result { case .found(let model): guard let obj = model as? Server.SharingGroupUser else { XCTFail() return } XCTAssert(obj.sharingGroupUUID == sharingGroupUUID) XCTAssert(obj.userId == userId) XCTAssert(obj.sharingGroupUserId != nil) case .noObjectFound: XCTFail("No object found") case .error(let error): XCTFail("Error: \(error)") } guard let groups = SharingGroupRepository(db).sharingGroups(forUserId: userId, sharingGroupUserRepo: SharingGroupUserRepository(db), userRepo: UserRepository(db)), groups.count == 1 else { XCTFail() return } XCTAssert(groups[0].sharingGroupUUID == sharingGroupUUID) } func testGetUserSharingGroupsForMultipleGroups() { let sharingGroupUUID1 = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID1) else { XCTFail() return } guard MasterVersionRepository(db).initialize(sharingGroupUUID: sharingGroupUUID1) else { XCTFail() return } let sharingGroupUUID2 = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID2, sharingGroupName: "Foobar") else { XCTFail() return } guard MasterVersionRepository(db).initialize(sharingGroupUUID: sharingGroupUUID2) else { XCTFail() return } let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" guard let userId: UserId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail() return } guard let _ = addSharingGroupUser(sharingGroupUUID:sharingGroupUUID1, userId: userId, owningUserId: nil) else { XCTFail() return } guard let _ = addSharingGroupUser(sharingGroupUUID:sharingGroupUUID2, userId: userId, owningUserId: nil) else { XCTFail() return } guard let groups = SharingGroupRepository(db).sharingGroups(forUserId: userId, sharingGroupUserRepo: SharingGroupUserRepository(db), userRepo: UserRepository(db)), groups.count == 2 else { XCTFail() return } let filter1 = groups.filter {$0.sharingGroupUUID == sharingGroupUUID1} guard filter1.count == 1 else { XCTFail() return } XCTAssert(filter1[0].sharingGroupName == nil) let filter2 = groups.filter {$0.sharingGroupUUID == sharingGroupUUID2} guard filter2.count == 1 else { XCTFail() return } XCTAssert(filter2[0].sharingGroupName == "Foobar") } } extension SpecificDatabaseTests_SharingGroupUsers { static var allTests : [(String, (SpecificDatabaseTests_SharingGroupUsers) -> () throws -> Void)] { return [ ("testAddSharingGroupUser", testAddSharingGroupUser), ("testAddMultipleSharingGroupUsers", testAddMultipleSharingGroupUsers), ("testAddSharingGroupUserFailsIfYouAddTheSameUserToSameGroupTwice", testAddSharingGroupUserFailsIfYouAddTheSameUserToSameGroupTwice), ("testLookupFromSharingGroupUser", testLookupFromSharingGroupUser), ("testGetUserSharingGroupsForMultipleGroups", testGetUserSharingGroupsForMultipleGroups) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SpecificDatabaseTests_SharingGroupUsers.self) } } <file_sep>// // MicrosoftCreds+Uploads.swift // Server // // Created by <NAME> on 9/15/19. // import Foundation import LoggerAPI import HeliumLogger import KituraNet import SyncServerShared extension MicrosoftCreds { struct UploadSession: Decodable { let uploadUrl: String } // Doesn't fail if the folder already exists. If it doesn't exist, it creates the app folder. func createAppFolder(completion:@escaping (Result<()>)->()) { // A call to list the children of the folder implictly creates the app folder. // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/concepts/special-folders-appfolder?view=odsp-graph-online let path = "/me/drive/special/approot/children" self.apiCall(method: "GET", baseURL: graphBaseURL, path: path, additionalHeaders: basicHeaders(), expectedSuccessBody: .data, expectedFailureBody: .data) { apiResult, statusCode, responseHeaders in Log.debug("apiResult: \(String(describing: apiResult)); statusCode: \(String(describing: statusCode))") guard let apiResult = apiResult else { completion(.failure(OneDriveFailure.noAPIResult)) return } guard case .data(let data) = apiResult else { completion(.failure(OneDriveFailure.noDataInAPIResult)) return } let decoder = JSONDecoder() guard statusCode == HTTPStatusCode.OK else { guard let errorResult = try? decoder.decode(ErrorResult.self, from: data) else { completion(.failure(OneDriveFailure.couldNotDecodeError)) return } guard !self.accessTokenIsRevokedOrExpired(errorResult: errorResult, statusCode: statusCode) else { completion(.accessTokenRevokedOrExpired) return } completion(.failure(OneDriveFailure.badStatusCode(statusCode, errorResult))) return } completion(.success(())) } } func createUploadSession(cloudFileName: String, createFolderFirst: Bool, completion:@escaping (Result<UploadSession>)->()) { if createFolderFirst { createAppFolder() { [weak self] result in guard let self = self else { completion(.failure(OneDriveFailure.couldNotGetSelf)) return } switch result { case .success: self.createUploadSession(cloudFileName: cloudFileName, completion: completion) case .failure(let error): completion(.failure(error)) case .accessTokenRevokedOrExpired: completion(.accessTokenRevokedOrExpired) } } } else { createUploadSession(cloudFileName: cloudFileName, completion: completion) } } // At least as of 6/22/19-- this is not creating the App folder if it doesn't already exist. It is returning HTTP status code forbidden. // See https://github.com/OneDrive/onedrive-api-docs/issues/1150 func createUploadSession(cloudFileName: String, completion:@escaping (Result<UploadSession>)->()) { // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_createuploadsession?view=odsp-graph-online#create-an-upload-session // POST /drive/root:/{item-path}:/createUploadSession // Content-Type: application/json let path = "/me/drive/special/approot:/\(cloudFileName):/createUploadSession" guard let encodedPath = encoded(string: path) else { Log.error("Failed encoding path.") completion(.failure(OneDriveFailure.urlEncoding)) return } let bodyDict = [ "item": [ "@microsoft.graph.conflictBehavior": "fail" ] ] guard let jsonString = JSONExtras.toJSONString(dict: bodyDict) else { completion(.failure(OneDriveFailure.couldNotEncodeBody)) return } self.apiCall(method: "POST", baseURL: graphBaseURL, path: encodedPath, additionalHeaders: basicHeaders(), body: .string(jsonString), expectedSuccessBody: .data, expectedFailureBody: .data) { apiResult, statusCode, responseHeaders in Log.debug("apiResult: \(String(describing: apiResult)); statusCode: \(String(describing: statusCode))") guard let apiResult = apiResult else { completion(.failure(OneDriveFailure.noAPIResult)) return } guard case .data(let data) = apiResult else { completion(.failure(OneDriveFailure.noDataInAPIResult)) return } let decoder = JSONDecoder() guard statusCode == HTTPStatusCode.OK else { guard let errorResult = try? decoder.decode(ErrorResult.self, from: data) else { completion(.failure(OneDriveFailure.couldNotDecodeError)) return } guard !self.accessTokenIsRevokedOrExpired(errorResult: errorResult, statusCode: statusCode) else { completion(.accessTokenRevokedOrExpired) return } print("responseHeaders: \(String(describing: responseHeaders))") completion(.failure(OneDriveFailure.badStatusCode(statusCode, errorResult))) return } guard let uploadSession = try? decoder.decode(UploadSession.self, from: data) else { completion(.failure(OneDriveFailure.couldNotDecodeResult)) return } completion(.success(uploadSession)) } } class UploadState { let numberBytesInFile: UInt let blockSize: UInt let data: Data let numberFullBlocks: UInt let partialLastBlock: Bool let partialLastBlockLength: UInt private(set) var currentStartOffset: Data.Index private(set) var currentEndOffset: Data.Index private(set) var currentBlock: Int = 0 var contentRange: String { let startByte = currentStartOffset let endByte = currentEndOffset - 1 let numberBytes = numberBytesInFile return "bytes \(startByte)-\(endByte)/\(numberBytes)" } static let blockMultipleInBytes = 327680 // The size of each byte range MUST be a multiple of 320 KiB (327,680 bytes). // checkBlockSize set to false is for testing. init?(blockSize: UInt, data: Data, checkBlockSize: Bool = true) { if data.count == 0 || blockSize == 0 { return nil } if checkBlockSize { guard Int(blockSize) % MicrosoftCreds.UploadState.blockMultipleInBytes == 0 else { return nil } } numberBytesInFile = UInt(data.count) self.blockSize = blockSize self.data = data numberFullBlocks = numberBytesInFile / blockSize partialLastBlockLength = numberBytesInFile % blockSize partialLastBlock = partialLastBlockLength != 0 currentStartOffset = data.startIndex if numberFullBlocks > 0 { currentEndOffset = data.index(data.startIndex, offsetBy: Int(blockSize)) } else { currentEndOffset = data.index(data.startIndex, offsetBy: Int(partialLastBlockLength)) } } func getCurrentBlock() -> Data { let range = currentStartOffset..<currentEndOffset return data.subdata(in: range) } // Returns true iff could advance. Returning false indicate we're out data. func advanceToNextBlock() -> Bool { currentBlock += 1 if currentBlock < numberFullBlocks { currentStartOffset = currentEndOffset currentEndOffset = data.index(currentStartOffset, offsetBy: Int(blockSize)) return true } else if currentBlock == numberFullBlocks && partialLastBlock { currentStartOffset = currentEndOffset currentEndOffset = data.index(currentStartOffset, offsetBy: Int(partialLastBlockLength)) return true } return false } } // The completion handler is called, with the file checksum, when the entire upload is complete. func uploadBytes(toUploadSession uploadSession: UploadSession, withUploadState uploadState: UploadState, completion:@escaping (Result<String>)->()) { // Content-Length: 26 // Content-Range: bytes 0-25/128 let urlString = uploadSession.uploadUrl guard let components = URLComponents(string: urlString), let host = components.host else { completion(.failure(OneDriveFailure.urlEncoding)) return } let dataSubrange = uploadState.getCurrentBlock() var headers = basicHeaders() headers["Content-Length"] = "\(dataSubrange.count)" headers["Content-Range"] = uploadState.contentRange Log.debug("Upload content range: \(uploadState.contentRange)") self.apiCall(method: "PUT", baseURL: host, path: components.path, additionalHeaders: headers, body: .data(dataSubrange), expectedSuccessBody: .data, expectedFailureBody: .data) { apiResult, statusCode, responseHeaders in Log.debug("apiResult: \(String(describing: apiResult)); statusCode: \(String(describing: statusCode))") guard let apiResult = apiResult else { completion(.failure(OneDriveFailure.noAPIResult)) return } guard case .data(let data) = apiResult else { completion(.failure(OneDriveFailure.noDataInAPIResult)) return } let decoder = JSONDecoder() guard statusCode == HTTPStatusCode.OK || statusCode == HTTPStatusCode.created || statusCode == HTTPStatusCode.accepted else { guard let errorResult = try? decoder.decode(ErrorResult.self, from: data) else { completion(.failure(OneDriveFailure.couldNotDecodeError)) return } guard !self.accessTokenIsRevokedOrExpired(errorResult: errorResult, statusCode: statusCode) else { completion(.accessTokenRevokedOrExpired) return } completion(.failure(OneDriveFailure.badStatusCode(statusCode, errorResult))) return } if uploadState.advanceToNextBlock() { self.uploadBytes(toUploadSession: uploadSession, withUploadState: uploadState, completion: completion) } else { guard let fileResult = try? decoder.decode(FileResult.self, from: data) else { completion(.failure(OneDriveFailure.couldNotDecodeResult)) return } completion(.success(fileResult.file.hashes.sha1Hash)) } } } enum CreateFolderFirst { case defaultNo case failedFirstTryYes case failedSecondTryNo var toBool:Bool { switch self { case .defaultNo: return false case .failedFirstTryYes: return true case .failedSecondTryNo: return false } } var nextState: CreateFolderFirst { switch self { case .defaultNo: return .failedFirstTryYes case .failedFirstTryYes: return .failedSecondTryNo case .failedSecondTryNo: return .failedSecondTryNo } } } // String in successful result is checksum. // Large file upload. // createFolderFirst is a workaround for a OneDrive issue. See comments in createUploadSession. func uploadFileUsingSession(withName fileName: String, mimeType: MimeType, data:Data, createFolderFirst: CreateFolderFirst = .defaultNo, completion:@escaping (Result<String>)->()) { let blockSize = MicrosoftCreds.UploadState.blockMultipleInBytes * 4 createUploadSession(cloudFileName: fileName, createFolderFirst: createFolderFirst.toBool) {[weak self] result in guard let self = self else { completion(.failure(OneDriveFailure.couldNotGetSelf)) return } switch result { case .failure(let error): if case OneDriveFailure.badStatusCode(let statusCode, _) = error, statusCode == .forbidden, createFolderFirst.nextState.toBool { self.uploadFileUsingSession(withName: fileName, mimeType: mimeType, data: data,createFolderFirst: createFolderFirst.nextState, completion: completion) } else { completion(.failure(error)) } case .accessTokenRevokedOrExpired: completion(.accessTokenRevokedOrExpired) case .success(let session): guard let state = MicrosoftCreds.UploadState(blockSize: UInt(blockSize), data: data) else { completion(.failure(OneDriveFailure.couldNotCreateUploadState)) return } self.uploadBytes(toUploadSession: session, withUploadState: state) { result in switch result { case .success(let checkSum): completion(.success(checkSum)) case .failure(let error): completion(.failure(error)) case .accessTokenRevokedOrExpired: completion(.accessTokenRevokedOrExpired) } } } } } } <file_sep>// // Repository.swift // Server // // Created by <NAME> on 11/26/16. // // import Foundation import LoggerAPI protocol RepositoryBasics { var db:Database! {get} var tableName:String {get} static var tableName:String {get} } protocol RepositoryLookup : RepositoryBasics { associatedtype LOOKUPKEY // Returns a constraint for a WHERE clause in mySQL based on the key func lookupConstraint(key:LOOKUPKEY) -> String } protocol Repository { init(_ db: Database) // If the table is present, and it's structure needs updating, update it. // If it's absent, create it. func upcreate() -> Database.TableUpcreateResult } enum RepositoryRemoveResult: RetryRequest { case removed(numberRows:Int32) case error(String) case deadlock case waitTimeout var shouldRetry: Bool { if case .deadlock = self { return true } else if case .waitTimeout = self { return true } else { return false } } } enum RepositoryLookupResult { case found(Model) case noObjectFound case error(String) } extension RepositoryBasics { // Remove entire table. func remove() -> Bool { return db.query(statement: "DROP TABLE \(tableName)") } } extension RepositoryLookup { // Remove row(s) from the table. func remove(key:LOOKUPKEY) -> RepositoryRemoveResult { let query = "delete from \(tableName) where " + lookupConstraint(key: key) if db.query(statement: query) { let numberRows = db.numberAffectedRows() var initialMessage:String if numberRows == 0 { initialMessage = "Did not remove any rows" } else { initialMessage = "Successfully removed \(numberRows) row(s)" } Log.info("\(initialMessage) from \(tableName): \(key)") return .removed(numberRows:Int32(numberRows)) } else if db.errorCode() == Database.deadlockError { return .deadlock } else if db.errorCode() == Database.lockWaitTimeout { return .waitTimeout } else { let error = db.error Log.error("Could not remove rows from \(tableName): \(error); \(key)") return .error("\(error)") } } // The lookup should find: a) exactly one object, or b) no objects. func lookup<MODEL: Model>(key: LOOKUPKEY, modelInit:@escaping () -> MODEL) -> RepositoryLookupResult { let query = "select * from \(tableName) where " + lookupConstraint(key: key) guard let select = Select(db:db, query: query, modelInit: modelInit, ignoreErrors:false) else { return .error("Failed on Select!") } switch select.numberResultRows() { case 0: Log.debug("No object found!") return .noObjectFound case 1: var result:MODEL! select.forEachRow { rowModel in result = (rowModel as! MODEL) } if select.forEachRowStatus != nil { let error = "Error: \(select.forEachRowStatus!) in Select forEachRow" Log.error(error) return .error(error) } Log.debug("Found result!") return .found(result) default: let error = "Error: \(select.numberResultRows()) in Select result: More than one object found!" Log.error(error) return .error(error) } } } extension Repository { func getUpdateFieldSetter(fieldValue: Any?, fieldName:String, fieldIsString:Bool = true) -> String { var fieldSetter = "" if fieldValue != nil { fieldSetter = ", \(fieldName) = " if fieldIsString { fieldSetter += "'\(fieldValue!)' " } else { fieldSetter += "\(fieldValue!) " } } return fieldSetter } func getInsertFieldValueAndName(fieldValue: Any?, fieldName:String, fieldIsString:Bool = true) -> (queryFieldValue:String, queryFieldName:String) { var queryFieldName = "" var queryFieldValue = "" if fieldValue != nil { queryFieldName = ", \(fieldName) " if fieldIsString { queryFieldValue = ", '\(fieldValue!)' " } else { queryFieldValue = ", \(fieldValue!) " } } return (queryFieldValue, queryFieldName) } } protocol RetryRequest { var shouldRetry: Bool { get } } extension Repository { func retry<T: RetryRequest>(request: @escaping ()->(T)) -> T { let maxNumberRetries = 3 var result = request() var count = 1 while result.shouldRetry && count < maxNumberRetries { let sleepDuration = TimeInterval(count) * TimeInterval(0.1) Log.info("Deadlock found: Retrying after \(sleepDuration)s") Thread.sleep(forTimeInterval: sleepDuration) result = request() count += 1 } return result } } <file_sep>// // GoogleDriveTests.swift // Server // // Created by <NAME> on 1/7/17. // // import XCTest @testable import Server import Foundation import HeliumLogger import LoggerAPI import SyncServerShared class GoogleDriveTests: ServerTestCase, LinuxTestable { // In my Google Drive, at the top-level: let knownPresentFolder = "Programming" let knownPresentFile = "DO-NOT-REMOVE.txt" let knownPresentImageFile = "DO-NOT-REMOVE.png" let knownPresentURLFile = "DO-NOT-REMOVE.url" // This is special in that (a) it contains only two characters, and (b) it was causing me problems for downloading on 2/4/18. let knownPresentFile2 = "DO-NOT-REMOVE2.txt" let knownAbsentFolder = "Markwa.Farkwa.Blarkwa" let knownAbsentFile = "Markwa.Farkwa.Blarkwa" let knownAbsentURLFile = "Markwa.Farkwa.Blarkwa.url" // Folder that will be created and removed. let folderCreatedAndDeleted = "abcdefg12345temporary" override func setUp() { super.setUp() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testListFiles() { let creds = GoogleCreds()! creds.refreshToken = TestAccount.google1.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) creds.listFiles { json, error in XCTAssert(error == nil) XCTAssert((json?.count)! > 0) exp.fulfill() } } waitForExpectations(timeout: 10, handler: nil) } func searchForFolder(name:String, presentExpected:Bool) { let creds = GoogleCreds()! creds.refreshToken = TestAccount.google1.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) creds.searchFor(.folder, itemName: name) { result, error in if presentExpected { XCTAssert(result != nil) } else { XCTAssert(result == nil) } XCTAssert(error == nil) exp.fulfill() } } waitForExpectations(timeout: 10, handler: nil) } func searchForFile(name:String, withMimeType mimeType:String, inFolder folderName:String?, presentExpected:Bool) { let creds = GoogleCreds()! creds.refreshToken = <EMAIL>Account.google1.token() let exp = expectation(description: "\(#function)\(#line)") Log.debug("Folder name: \(String(describing: folderName))") func searchForFile(parentFolderId:String?) { creds.searchFor(.file(mimeType:mimeType, parentFolderId:parentFolderId), itemName: name) { result, error in if presentExpected { XCTAssert(result != nil, "\(String(describing: error))") } else { XCTAssert(result == nil) } XCTAssert(error == nil) exp.fulfill() } } creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) if folderName == nil { searchForFile(parentFolderId: nil) } else { creds.searchFor(.folder, itemName: folderName!) { result, error in XCTAssert(result != nil) XCTAssert(error == nil) searchForFile(parentFolderId: result!.itemId) } } } waitForExpectations(timeout: 20, handler: nil) } func testSearchForPresentFolder() { searchForFolder(name: self.knownPresentFolder, presentExpected: true) } func testSearchForAbsentFolder() { searchForFolder(name: self.knownAbsentFolder, presentExpected: false) } func testSearchForPresentFile() { searchForFile(name: knownPresentFile, withMimeType: "text/plain", inFolder: nil, presentExpected: true) } func testSearchForPresentImageFile() { searchForFile(name: knownPresentImageFile, withMimeType: "image/png", inFolder: nil, presentExpected: true) } func testBootStrapTestSearchForPresentURLFile() { let file = knownPresentURLFile if let found = lookupFile(cloudFileName: file, mimeType: .url) { // Uploads to knownPresentFolder if !found { fullUpload(file: TestFile.testUrlFile, mimeType: MimeType.url.rawValue, nonStandardFileName: file) } } else { XCTFail() } } func testSearchForPresentURLFile() { searchForFile(name: knownPresentURLFile, withMimeType: MimeType.url.rawValue, inFolder: knownPresentFolder, presentExpected: true) } func testSearchForAbsentFile() { searchForFile(name: knownAbsentFile, withMimeType: "text/plain", inFolder: nil, presentExpected: false) } func testSearchForAbsentURLFile() { searchForFile(name: knownAbsentURLFile, withMimeType: MimeType.url.rawValue, inFolder: nil, presentExpected: false) } func testSearchForPresentFileInFolder() { searchForFile(name: knownPresentFile, withMimeType: "text/plain", inFolder: knownPresentFolder, presentExpected: true) } func testSearchForPresentURLFileInFolder() { searchForFile(name: knownPresentURLFile, withMimeType: MimeType.url.rawValue, inFolder: knownPresentFolder, presentExpected: true) } func testSearchForAbsentFileInFolder() { searchForFile(name: knownAbsentFile, withMimeType: "text/plain", inFolder: knownPresentFolder, presentExpected: false) } func testSearchForAbsentURLFileInFolder() { searchForFile(name: knownAbsentURLFile, withMimeType: MimeType.url.rawValue, inFolder: knownPresentFolder, presentExpected: false) } // Haven't been able to get trashFile to work yet. /* func testTrashFolder() { let creds = GoogleCreds() creds.refreshToken = self.credentialsToken() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) // creds.createFolder(folderName: "TestMe") { folderId, error in // XCTAssert(folderId != nil) // XCTAssert(error == nil) let folderId = "0B3xI3Shw5ptRdWtPR3ZLdXpqbHc" creds.trashFile(fileId: folderId) { error in XCTAssert(error == nil) exp.fulfill() } // } } waitForExpectations(timeout: 10, handler: nil) } */ func testCreateAndDeleteFolder() { let creds = GoogleCreds()! creds.refreshToken = TestAccount.google1.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) creds.createFolder(rootFolderName: "TestMe") { folderId, error in XCTAssert(folderId != nil) XCTAssert(error == nil) creds.deleteFile(fileId: folderId!) { error in XCTAssert(error == nil) exp.fulfill() } } } waitForExpectations(timeout: 10, handler: nil) } func testDeleteFolderThatDoesNotExistFailure() { let creds = GoogleCreds()! creds.refreshToken = TestAccount.google1.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) creds.deleteFile(fileId: "foobar") { error in XCTAssert(error != nil) exp.fulfill() } } waitForExpectations(timeout: 10, handler: nil) } func cloudStorageFileDelete(file: TestFile, mimeType: MimeType) { let creds = GoogleCreds()! creds.refreshToken = TestAccount.google1.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) // Do the upload let deviceUUID = Foundation.UUID().uuidString let fileUUID = Foundation.UUID().uuidString let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUID uploadRequest.mimeType = mimeType.rawValue uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = UUID().uuidString uploadRequest.checkSum = file.md5CheckSum let options = CloudStorageFileNameOptions(cloudFolderName: self.knownPresentFolder, mimeType: mimeType.rawValue) uploadFile(accountType: AccountScheme.google.accountName, creds: creds, deviceUUID: deviceUUID, testFile: file, uploadRequest: uploadRequest, options: options) let cloudFileName = uploadRequest.cloudFileName(deviceUUID:deviceUUID, mimeType: uploadRequest.mimeType) deleteFile(testAccount: TestAccount.google1, cloudFileName: cloudFileName, options: options) } func testCloudStorageFileDeleteWorks() { cloudStorageFileDelete(file: .test1, mimeType: .text) } func testCloudStorageURLFileDeleteWorks() { cloudStorageFileDelete(file: .testUrlFile, mimeType: .url) } func testCloudStorageFileDeleteWithRevokedRefreshToken() { let creds = GoogleCreds()! creds.refreshToken = TestAccount.googleRevoked.token() let options = CloudStorageFileNameOptions(cloudFolderName: self.knownPresentFolder, mimeType: "text/plain") let file = TestFile.test1 let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = Foundation.UUID().uuidString uploadRequest.mimeType = "text/plain" uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = UUID().uuidString uploadRequest.checkSum = file.md5CheckSum let deviceUUID = Foundation.UUID().uuidString let cloudFileName = uploadRequest.cloudFileName(deviceUUID:deviceUUID, mimeType: uploadRequest.mimeType) let exp = expectation(description: "\(#function)\(#line)") creds.deleteFile(cloudFileName:cloudFileName, options:options) { result in switch result { case .success: XCTFail() case .accessTokenRevokedOrExpired: break case .failure: XCTFail() } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testCreateFolderIfDoesNotExist() { let creds = GoogleCreds()! creds.refreshToken = TestAccount.google1.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) creds.createFolderIfDoesNotExist(rootFolderName: self.folderCreatedAndDeleted) { (folderIdA, error) in XCTAssert(folderIdA != nil) XCTAssert(error == nil) // It should be there after being created. creds.searchFor(.folder, itemName: self.folderCreatedAndDeleted) { (result, error) in XCTAssert(result != nil) XCTAssert(error == nil) // And attempting to create it again shouldn't fail. creds.createFolderIfDoesNotExist(rootFolderName: self.folderCreatedAndDeleted) { (folderIdB, error) in XCTAssert(folderIdB != nil) XCTAssert(error == nil) XCTAssert(folderIdA == folderIdB) creds.deleteFile(fileId: folderIdA!) { error in XCTAssert(error == nil) exp.fulfill() } } } } } waitForExpectations(timeout: 10, handler: nil) } func fullUpload(file: TestFile, mimeType: String, nonStandardFileName: String? = nil) { let creds = GoogleCreds()! creds.refreshToken = TestAccount.google1.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) // Do the upload let deviceUUID = Foundation.UUID().uuidString let fileUUID = Foundation.UUID().uuidString let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUID uploadRequest.mimeType = mimeType uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = UUID().uuidString uploadRequest.checkSum = file.md5CheckSum let options = CloudStorageFileNameOptions(cloudFolderName: self.knownPresentFolder, mimeType: mimeType) uploadFile(accountType: AccountScheme.google.accountName, creds: creds, deviceUUID: deviceUUID, testFile: file, uploadRequest: uploadRequest, options: options, nonStandardFileName: nonStandardFileName) // The second time we try it, it should fail with CloudStorageError.alreadyUploaded -- same file. uploadFile(accountType: AccountScheme.google.accountName, creds: creds, deviceUUID: deviceUUID, testFile: file, uploadRequest: uploadRequest, options: options, nonStandardFileName: nonStandardFileName, failureExpected: true, errorExpected: CloudStorageError.alreadyUploaded) } func testFullUploadWorks() { fullUpload(file: TestFile.test1, mimeType: MimeType.text.rawValue) } func testFullUploadWorksForURLFile() { fullUpload(file: TestFile.testUrlFile, mimeType: MimeType.url.rawValue) } func testUploadWithRevokedRefreshToken() { let creds = GoogleCreds()! creds.refreshToken = TestAccount.googleRevoked.token() // Do the upload let deviceUUID = Foundation.UUID().uuidString let fileUUID = Foundation.UUID().uuidString let file = TestFile.test1 let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUID uploadRequest.mimeType = "text/plain" uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = UUID().uuidString uploadRequest.checkSum = file.md5CheckSum let options = CloudStorageFileNameOptions(cloudFolderName: self.knownPresentFolder, mimeType: "text/plain") uploadFile(accountType: AccountScheme.google.accountName, creds: creds, deviceUUID: deviceUUID, testFile: file, uploadRequest: uploadRequest, options: options, expectAccessTokenRevokedOrExpired: true) } func downloadFile(cloudFileName:String, mimeType: MimeType, expectError:Bool = false, expectedFileNotFound: Bool = false) { let creds = GoogleCreds()! creds.refreshToken = TestAccount.google1.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) let options = CloudStorageFileNameOptions(cloudFolderName: self.knownPresentFolder, mimeType: mimeType.rawValue) creds.downloadFile(cloudFileName: cloudFileName, options:options) { result in switch result { case .success: if expectError { XCTFail() } case .failure, .accessTokenRevokedOrExpired: XCTFail() case .fileNotFound: if !expectedFileNotFound { XCTFail() } } // A different unit test will check to see if the contents of the file are correct. exp.fulfill() } } waitForExpectations(timeout: 10, handler: nil) } func testBasicFileDownloadWorks() { downloadFile(cloudFileName: self.knownPresentFile, mimeType: .text) } func testBasicURLFileDownloadWorks() { downloadFile(cloudFileName: self.knownPresentURLFile, mimeType: .url) } func testSearchForPresentFile2() { searchForFile(name: knownPresentFile2, withMimeType: "text/plain", inFolder: nil, presentExpected: true) } func testBasicFileDownloadWorks2() { downloadFile(cloudFileName: self.knownPresentFile2, mimeType: .text) } func testFileDownloadOfNonExistentFileFails() { downloadFile(cloudFileName: self.knownAbsentFile, mimeType: .text, expectedFileNotFound: true) } func testDownloadWithRevokedRefreshToken() { let cloudFileName = self.knownPresentFile let creds = GoogleCreds()! creds.refreshToken = TestAccount.googleRevoked.token() let exp = expectation(description: "\(#function)\(#line)") let options = CloudStorageFileNameOptions(cloudFolderName: self.knownPresentFolder, mimeType: "text/plain") creds.downloadFile(cloudFileName: cloudFileName, options:options) { result in switch result { case .success: XCTFail() case .failure(let error): XCTFail("error: \(error)") case .accessTokenRevokedOrExpired: break case .fileNotFound: XCTFail() } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testFileDirectDownloadOfNonExistentFileFails() { let creds = GoogleCreds()! creds.refreshToken = TestAccount.google1.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) creds.completeSmallFileDownload(fileId: "foobar") { data, error in if let error = error { switch error { case GoogleCreds.DownloadSmallFileError.fileNotFound: break default: XCTFail() } } else { XCTFail() } exp.fulfill() } } waitForExpectations(timeout: 10, handler: nil) } func testThatAccessTokenRefreshOccursWithBadToken() { let creds = GoogleCreds()! creds.refreshToken = TestAccount.google1.token() let exp = expectation(description: "\(#function)\(#line)") // Use a known incorrect access token. We expect this to generate a 401 unauthorized, and thus cause an access token refresh. But, the refresh will work. creds.accessToken = "foobar" let options = CloudStorageFileNameOptions(cloudFolderName: self.knownPresentFolder, mimeType: "text/plain") creds.downloadFile(cloudFileName: self.knownPresentFile, options:options) { result in switch result { case .success: break case .failure, .accessTokenRevokedOrExpired: XCTFail() case .fileNotFound: XCTFail() } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testThatAccessTokenRefreshFailsWithBadRefreshToken() { let creds = GoogleCreds()! creds.refreshToken = "<PASSWORD>" let exp = expectation(description: "\(#function)\(#line)") let options = CloudStorageFileNameOptions(cloudFolderName: self.knownPresentFolder, mimeType: "text/plain") creds.downloadFile(cloudFileName: self.knownPresentFile, options:options) { result in switch result { case .success: XCTFail() case .failure: XCTFail() case .accessTokenRevokedOrExpired: break case .fileNotFound: XCTFail() } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testLookupFileWithRevokedRefreshToken() { let creds = GoogleCreds()! creds.refreshToken = TestAccount.googleRevoked.token() let exp = expectation(description: "\(#function)\(#line)") let options = CloudStorageFileNameOptions(cloudFolderName: self.knownPresentFolder, mimeType: "text/plain") creds.lookupFile(cloudFileName:knownPresentFile, options:options) { result in switch result { case .success: XCTFail() case .failure: XCTFail() case .accessTokenRevokedOrExpired: break } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } // Searches in knownPresentFolder func lookupFile(cloudFileName: String, mimeType: MimeType = .text, expectError:Bool = false) -> Bool? { var foundResult: Bool? let creds = GoogleCreds()! creds.refreshToken = TestAccount.google1.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) let options = CloudStorageFileNameOptions(cloudFolderName: self.knownPresentFolder, mimeType: mimeType.rawValue) creds.lookupFile(cloudFileName:cloudFileName, options:options) { result in switch result { case .success(let found): if expectError { XCTFail() } else { foundResult = found } case .failure, .accessTokenRevokedOrExpired: if !expectError { XCTFail() } } exp.fulfill() } } waitForExpectations(timeout: 10, handler: nil) return foundResult } func testLookupFileThatExists() { let result = lookupFile(cloudFileName: knownPresentFile) XCTAssert(result == true) } func testLookupURLFileThatExists() { let result = lookupFile(cloudFileName: knownPresentURLFile, mimeType: .url) XCTAssert(result == true) } func testLookupFileThatDoesNotExist() { let result = lookupFile(cloudFileName: knownAbsentFile) XCTAssert(result == false) } func testRevokedGoogleRefreshToken() { let creds = GoogleCreds()! creds.refreshToken = TestAccount.googleRevoked.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in if let error = error { switch error { case GoogleCreds.CredentialsError.expiredOrRevokedAccessToken: break default: XCTFail() } } else { XCTFail() } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } } extension GoogleDriveTests { static var allTests : [(String, (GoogleDriveTests) -> () throws -> Void)] { return [ ("testListFiles", testListFiles), ("testSearchForPresentFolder", testSearchForPresentFolder), ("testSearchForAbsentFolder", testSearchForAbsentFolder), ("testSearchForPresentFile", testSearchForPresentFile), ("testSearchForPresentImageFile", testSearchForPresentImageFile), ("testBootStrapTestSearchForPresentURLFile", testBootStrapTestSearchForPresentURLFile), ("testSearchForPresentURLFile", testSearchForPresentURLFile), ("testSearchForAbsentFile", testSearchForAbsentFile), ("testSearchForAbsentURLFile", testSearchForAbsentURLFile), ("testSearchForPresentFileInFolder", testSearchForPresentFileInFolder), ("testSearchForPresentURLFileInFolder", testSearchForPresentURLFileInFolder), ("testSearchForAbsentFileInFolder", testSearchForAbsentFileInFolder), ("testSearchForAbsentURLFileInFolder", testSearchForAbsentURLFileInFolder), ("testCreateAndDeleteFolder", testCreateAndDeleteFolder), ("testDeleteFolderThatDoesNotExistFailure", testDeleteFolderThatDoesNotExistFailure), ("testCloudStorageFileDeleteWorks", testCloudStorageFileDeleteWorks), ("testCloudStorageURLFileDeleteWorks", testCloudStorageURLFileDeleteWorks), ("testCloudStorageFileDeleteWithRevokedRefreshToken", testCloudStorageFileDeleteWithRevokedRefreshToken), ("testCreateFolderIfDoesNotExist", testCreateFolderIfDoesNotExist), ("testUploadWithRevokedRefreshToken", testUploadWithRevokedRefreshToken), ("testFullUploadWorks", testFullUploadWorks), ("testFullUploadWorksForURLFile", testFullUploadWorksForURLFile), ("testBasicFileDownloadWorks", testBasicFileDownloadWorks), ("testBasicURLFileDownloadWorks", testBasicURLFileDownloadWorks), ("testSearchForPresentFile2", testSearchForPresentFile2), ("testBasicFileDownloadWorks2", testBasicFileDownloadWorks2), ("testFileDownloadOfNonExistentFileFails", testFileDownloadOfNonExistentFileFails), ("testDownloadWithRevokedRefreshToken", testDownloadWithRevokedRefreshToken), ("testFileDirectDownloadOfNonExistentFileFails", testFileDirectDownloadOfNonExistentFileFails), ("testThatAccessTokenRefreshOccursWithBadToken", testThatAccessTokenRefreshOccursWithBadToken), ("testThatAccessTokenRefreshFailsWithBadRefreshToken", testThatAccessTokenRefreshFailsWithBadRefreshToken), ("testLookupFileWithRevokedRefreshToken", testLookupFileWithRevokedRefreshToken), ("testLookupFileThatDoesNotExist", testLookupFileThatDoesNotExist), ("testLookupFileThatExists", testLookupFileThatExists), ("testLookupURLFileThatExists", testLookupURLFileThatExists), ("testRevokedGoogleRefreshToken", testRevokedGoogleRefreshToken) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:GoogleDriveTests.self) } } <file_sep>// // SharingGroupsController.swift // Server // // Created by <NAME> on 7/15/18. // import LoggerAPI import Credentials import SyncServerShared import Foundation class SharingGroupsController : ControllerProtocol { static func setup() -> Bool { return true } func createSharingGroup(params:RequestProcessingParameters) { guard let request = params.request as? CreateSharingGroupRequest else { let message = "Did not receive CreateSharingGroupRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard let accountScheme = params.accountProperties?.accountScheme else { let message = "Could not get account scheme from properties!" Log.error(message) params.completion(.failure(.message(message))) return } // My logic here is that a sharing user should only be able to create files in the same sharing group(s) to which they were originally invited. The only way they'll get access to another sharing group is through invitation, not by creating new sharing groups. guard accountScheme.userType == .owning else { let message = "Current signed in user is not an owning user." Log.error(message) params.completion(.failure(.message(message))) return } guard SharingGroupsController.addSharingGroup(sharingGroupUUID: request.sharingGroupUUID, sharingGroupName: request.sharingGroupName, params: params) else { let message = "Failed on adding new sharing group." Log.error(message) params.completion(.failure(.message(message))) return } guard case .success = params.repos.sharingGroupUser.add(sharingGroupUUID: request.sharingGroupUUID, userId: params.currentSignedInUser!.userId, permission: .admin, owningUserId: nil) else { let message = "Failed on adding sharing group user." Log.error(message) params.completion(.failure(.message(message))) return } if !params.repos.masterVersion.initialize(sharingGroupUUID: request.sharingGroupUUID) { let message = "Failed on creating MasterVersion record for sharing group!" Log.error(message) params.completion(.failure(.message(message))) return } let response = CreateSharingGroupResponse() params.completion(.success(response)) } // Updates master version: Because this changes the sharing group. func updateSharingGroup(params:RequestProcessingParameters) { guard let request = params.request as? UpdateSharingGroupRequest else { let message = "Did not receive UpdateSharingGroupRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard let sharingGroupUUID = request.sharingGroupUUID, let sharingGroupName = request.sharingGroupName else { Log.info("No name given in sharing group update request-- no change made.") let response = UpdateSharingGroupResponse() params.completion(.success(response)) return } guard sharingGroupSecurityCheck(sharingGroupUUID: sharingGroupUUID, params: params) else { let message = "Failed in sharing group security check." Log.error(message) params.completion(.failure(.message(message))) return } if let errorResponse = Controllers.updateMasterVersion(sharingGroupUUID: sharingGroupUUID, masterVersion: request.masterVersion, params: params, responseType: UpdateSharingGroupResponse.self) { params.completion(errorResponse) return } let serverSharingGroup = Server.SharingGroup() serverSharingGroup.sharingGroupUUID = sharingGroupUUID serverSharingGroup.sharingGroupName = sharingGroupName guard params.repos.sharingGroup.update(sharingGroup: serverSharingGroup) else { let message = "Failed in updating sharing group." Log.error(message) params.completion(.failure(.message(message))) return } let response = UpdateSharingGroupResponse() params.completion(.success(response)) } func removeSharingGroup(params:RequestProcessingParameters) { guard let request = params.request as? RemoveSharingGroupRequest else { let message = "Did not receive RemoveSharingGroupRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard sharingGroupSecurityCheck(sharingGroupUUID: request.sharingGroupUUID, params: params) else { let message = "Failed in sharing group security check." Log.error(message) params.completion(.failure(.message(message))) return } if let errorResponse = Controllers.updateMasterVersion(sharingGroupUUID: request.sharingGroupUUID, masterVersion: request.masterVersion, params: params, responseType: RemoveSharingGroupResponse.self) { params.completion(errorResponse) return } guard remove(params:params, sharingGroupUUID: request.sharingGroupUUID) else { return } let response = RemoveSharingGroupResponse() params.completion(.success(response)) } private func remove(params:RequestProcessingParameters, sharingGroupUUID: String) -> Bool { let markKey = FileIndexRepository.LookupKey.sharingGroupUUID(sharingGroupUUID: sharingGroupUUID) guard let _ = params.repos.fileIndex.markFilesAsDeleted(key: markKey) else { let message = "Could not mark files as deleted for sharing group!" Log.error(message) params.completion(.failure(.message(message))) return false } // Any users who were members of the sharing group should no longer be members. let sharingGroupUserKey = SharingGroupUserRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let removeResult = params.repos.sharingGroupUser.retry { return params.repos.sharingGroupUser.remove(key: sharingGroupUserKey) } switch removeResult { case .removed: break case .deadlock: let message = "Could not remove sharing group user references: deadlock" Log.error(message) params.completion(.failure(.message(message))) return false case .waitTimeout: let message = "Could not remove sharing group user references: waitTimeout" Log.error(message) params.completion(.failure(.message(message))) return false case .error(let error): let message = "Could not remove sharing group user references: \(error)" Log.error(message) params.completion(.failure(.message(message))) return false } // Mark the sharing group as deleted. guard let _ = params.repos.sharingGroup.markAsDeleted(forCriteria: .sharingGroupUUID(sharingGroupUUID)) else { let message = "Could not mark sharing group as deleted." Log.error(message) params.completion(.failure(.message(message))) return false } // Not going to remove row from master version. People will still be able to get the file index for this sharing group-- to see that all the files are (marked as) deleted. That requires a master version. return true } func removeUserFromSharingGroup(params:RequestProcessingParameters) { guard let request = params.request as? RemoveUserFromSharingGroupRequest else { let message = "Did not receive RemoveUserFromSharingGroupRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard sharingGroupSecurityCheck(sharingGroupUUID: request.sharingGroupUUID, params: params) else { let message = "Failed in sharing group security check." Log.error(message) params.completion(.failure(.message(message))) return } if let errorResponse = Controllers.updateMasterVersion(sharingGroupUUID: request.sharingGroupUUID, masterVersion: request.masterVersion, params: params, responseType: RemoveSharingGroupResponse.self) { params.completion(errorResponse) return } // Need to count number of users in sharing group-- if this will be the last user need to "remove" the sharing group because no other people will be able to enter it. ("remove" == mark the sharing group as deleted). var numberSharingUsers:Int! if let result:[SyncServerShared.SharingGroupUser] = params.repos.sharingGroupUser.sharingGroupUsers(forSharingGroupUUID: request.sharingGroupUUID) { numberSharingUsers = result.count } else { params.completion(.failure(nil)) } guard let accountScheme = params.accountProperties?.accountScheme else { let message = "Could not get account scheme from properties!" Log.error(message) params.completion(.failure(.message(message))) return } // If we're going to remove the user from the sharing group, and this user is an owning user, we should mark any of their sharing users in that sharing group as removed. let resetKey = SharingGroupUserRepository.LookupKey.owningUserAndSharingGroup(owningUserId: params.currentSignedInUser!.userId, uuid: request.sharingGroupUUID) if accountScheme.userType == .owning { guard params.repos.sharingGroupUser.resetOwningUserIds(key: resetKey) else { let message = "Could not reset owning users ids." Log.error(message) params.completion(.failure(.message(message))) return } } let removalKey = SharingGroupUserRepository.LookupKey.primaryKeys(sharingGroupUUID: request.sharingGroupUUID, userId: params.currentSignedInUser!.userId) let removalResult = params.repos.sharingGroupUser.retry { return params.repos.sharingGroupUser.remove(key: removalKey) } guard case .removed(let numberRows) = removalResult, numberRows == 1 else { let message = "Could not remove user from SharingGroup." Log.error(message) params.completion(.failure(.message(message))) return } // Any files that this user has in the FileIndex for this sharing group should be marked as deleted. let markKey = FileIndexRepository.LookupKey.userAndSharingGroup(params.currentSignedInUser!.userId, sharingGroupUUID: request.sharingGroupUUID) guard let _ = params.repos.fileIndex.markFilesAsDeleted(key: markKey) else { let message = "Could not mark files as deleted for user and sharing group!" Log.error(message) params.completion(.failure(.message(message))) return } if numberSharingUsers == 1 { guard remove(params:params, sharingGroupUUID: request.sharingGroupUUID) else { return } } let response = RemoveUserFromSharingGroupResponse() params.completion(.success(response)) } } extension SharingGroupsController { // Adds a sharing group, and also adds a sharing group lock. // Return true iff success. static func addSharingGroup(sharingGroupUUID: String, sharingGroupName: String?, params:RequestProcessingParameters) -> Bool { guard case .success = params.repos.sharingGroup.add(sharingGroupUUID: sharingGroupUUID, sharingGroupName: sharingGroupName) else { let message = "Failed on adding new sharing group." Log.error(message) return false } return true } } <file_sep>// // SpecificDatabaseTests.swift // Server // // Created by <NAME> on 12/18/16. // // import XCTest @testable import Server import LoggerAPI import HeliumLogger import Credentials import CredentialsGoogle import Foundation import SyncServerShared class SpecificDatabaseTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func checkMasterVersion(sharingGroupUUID:String, version:Int64) { let result = MasterVersionRepository(db).lookup(key: .sharingGroupUUID(sharingGroupUUID), modelInit: MasterVersion.init) switch result { case .error(let error): XCTFail("\(error)") case .found(let object): let masterVersion = object as! MasterVersion XCTAssert(masterVersion.masterVersion == version && masterVersion.sharingGroupUUID == sharingGroupUUID) case .noObjectFound: XCTFail("No MasterVersion Found") } } func doUpdateToNextMasterVersion(currentMasterVersion:MasterVersionInt, sharingGroupUUID: String, expectedError: Bool = false) { let current = MasterVersion() current.sharingGroupUUID = sharingGroupUUID current.masterVersion = currentMasterVersion let result = MasterVersionRepository(db).updateToNext(current: current) if case .success = result { if expectedError { XCTFail() } else { XCTAssert(true) } } else { if expectedError { XCTAssert(true) } else { XCTFail() } } } func testUpdateToNextMasterVersion() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } XCTAssert(MasterVersionRepository(db).initialize(sharingGroupUUID: sharingGroupUUID)) doUpdateToNextMasterVersion(currentMasterVersion: 0, sharingGroupUUID: sharingGroupUUID) checkMasterVersion(sharingGroupUUID: sharingGroupUUID, version: 1) } func testUpdateToNextTwiceMasterVersion() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } XCTAssert(MasterVersionRepository(db).initialize(sharingGroupUUID: sharingGroupUUID)) doUpdateToNextMasterVersion(currentMasterVersion: 0, sharingGroupUUID: sharingGroupUUID) doUpdateToNextMasterVersion(currentMasterVersion: 1, sharingGroupUUID: sharingGroupUUID) checkMasterVersion(sharingGroupUUID: sharingGroupUUID, version: 2) } func testUpdateToNextFailsWithWrongExpectedMasterVersion() { let sharingGroupUUID = UUID().uuidString guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } XCTAssert(MasterVersionRepository(db).initialize(sharingGroupUUID: sharingGroupUUID)) doUpdateToNextMasterVersion(currentMasterVersion: 1, sharingGroupUUID: sharingGroupUUID, expectedError: true) } func doAddFileIndex(userId:UserId = 1, sharingGroupUUID:String, createSharingGroup: Bool) -> FileIndex? { if createSharingGroup { guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return nil } guard case .success = SharingGroupUserRepository(db).add(sharingGroupUUID: sharingGroupUUID, userId: userId, permission: .write, owningUserId: nil) else { XCTFail() return nil } } let fileIndex = FileIndex() fileIndex.lastUploadedCheckSum = "abcde" fileIndex.deleted = false fileIndex.fileUUID = Foundation.UUID().uuidString fileIndex.deviceUUID = Foundation.UUID().uuidString fileIndex.fileVersion = 1 fileIndex.mimeType = "text/plain" fileIndex.userId = userId fileIndex.appMetaData = "{ \"foo\": \"bar\" }" fileIndex.creationDate = Date() fileIndex.updateDate = Date() fileIndex.sharingGroupUUID = sharingGroupUUID let result1 = FileIndexRepository(db).add(fileIndex: fileIndex) guard case .success(let uploadId) = result1 else { XCTFail() return nil } fileIndex.fileIndexId = uploadId return fileIndex } func testAddFileIndex() { let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" guard let userId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail("Bad credentialsId!") return } let sharingGroupUUID = UUID().uuidString guard let _ = doAddFileIndex(userId:userId, sharingGroupUUID: sharingGroupUUID, createSharingGroup: true) else { XCTFail() return } } func testUpdateFileIndexWithNoChanges() { let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" guard let userId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail("Bad credentialsId!") return } let sharingGroupUUID = UUID().uuidString guard let fileIndex = doAddFileIndex(userId:userId, sharingGroupUUID: sharingGroupUUID, createSharingGroup: true) else { XCTFail() return } XCTAssert(FileIndexRepository(db).update(fileIndex: fileIndex)) } func testUpdateFileIndexWithAChange() { let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" let sharingGroupUUID = UUID().uuidString // 6/12/19; Just added the JSON validation paramter. I have *no* idea how this was working before this. It ought to have required the server to be running for it to work. guard let userId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail("Bad credentialsId!") return } guard let fileIndex = doAddFileIndex(userId:userId, sharingGroupUUID: sharingGroupUUID, createSharingGroup: true) else { XCTFail() return } fileIndex.fileVersion = 2 XCTAssert(FileIndexRepository(db).update(fileIndex: fileIndex)) } func testUpdateFileIndexFailsWithoutFileIndexId() { let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" let sharingGroupUUID = UUID().uuidString guard let userId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail("Bad credentialsId!") return } guard let fileIndex = doAddFileIndex(userId:userId, sharingGroupUUID: sharingGroupUUID, createSharingGroup: true) else { XCTFail() return } fileIndex.fileIndexId = nil XCTAssert(!FileIndexRepository(db).update(fileIndex: fileIndex)) } func testUpdateUploadSucceedsWithNilAppMetaData() { let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" let sharingGroupUUID = UUID().uuidString guard let userId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail("Bad credentialsId!") return } guard let fileIndex = doAddFileIndex(userId:userId, sharingGroupUUID: sharingGroupUUID, createSharingGroup: true) else { XCTFail() return } fileIndex.appMetaData = nil XCTAssert(FileIndexRepository(db).update(fileIndex: fileIndex)) } func testLookupFromFileIndex() { let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"Some<PASSWORD>\"}" user1.credsId = "100" let sharingGroupUUID = UUID().uuidString guard let userId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail("Bad credentialsId!") return } guard let fileIndex1 = doAddFileIndex(userId:userId, sharingGroupUUID: sharingGroupUUID, createSharingGroup: true) else { XCTFail() return } let result = FileIndexRepository(db).lookup(key: .fileIndexId(fileIndex1.fileIndexId), modelInit: FileIndex.init) switch result { case .error(let error): XCTFail("\(error)") case .found(let object): let fileIndex2 = object as! FileIndex XCTAssert(fileIndex1.lastUploadedCheckSum != nil && fileIndex1.lastUploadedCheckSum == fileIndex2.lastUploadedCheckSum) XCTAssert(fileIndex1.deleted != nil && fileIndex1.deleted == fileIndex2.deleted) XCTAssert(fileIndex1.fileUUID != nil && fileIndex1.fileUUID == fileIndex2.fileUUID) XCTAssert(fileIndex1.deviceUUID != nil && fileIndex1.deviceUUID == fileIndex2.deviceUUID) XCTAssert(fileIndex1.fileVersion != nil && fileIndex1.fileVersion == fileIndex2.fileVersion) XCTAssert(fileIndex1.mimeType != nil && fileIndex1.mimeType == fileIndex2.mimeType) XCTAssert(fileIndex1.userId != nil && fileIndex1.userId == fileIndex2.userId) XCTAssert(fileIndex1.appMetaData != nil && fileIndex1.appMetaData == fileIndex2.appMetaData) XCTAssert(fileIndex1.sharingGroupUUID != nil && fileIndex1.sharingGroupUUID == fileIndex2.sharingGroupUUID) case .noObjectFound: XCTFail("No Upload Found") } } func testFileIndexWithNoFiles() { let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" let sharingGroupUUID = UUID().uuidString guard let userId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail("Bad credentialsId!") return } guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard case .success = SharingGroupUserRepository(db).add(sharingGroupUUID: sharingGroupUUID, userId: userId, permission: .admin, owningUserId: nil) else { XCTFail() return } let fileIndexResult = FileIndexRepository(db).fileIndex(forSharingGroupUUID: sharingGroupUUID) switch fileIndexResult { case .fileIndex(let fileIndex): XCTAssert(fileIndex.count == 0) case .error(_): XCTFail() } } func testFileIndexWithOneFile() { let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" let sharingGroupUUID = UUID().uuidString guard let userId = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail() return } guard case .success = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } guard case .success = SharingGroupUserRepository(db).add(sharingGroupUUID: sharingGroupUUID, userId: userId, permission: .read, owningUserId: nil) else { XCTFail() return } guard let fileIndexInserted = doAddFileIndex(userId: userId, sharingGroupUUID: sharingGroupUUID, createSharingGroup: false) else { XCTFail() return } let fileIndexResult = FileIndexRepository(db).fileIndex(forSharingGroupUUID: sharingGroupUUID) switch fileIndexResult { case .fileIndex(let fileIndex): guard fileIndex.count == 1 else { XCTFail() return } XCTAssert(fileIndexInserted.fileUUID == fileIndex[0].fileUUID) XCTAssert(fileIndexInserted.fileVersion == fileIndex[0].fileVersion) XCTAssert(fileIndexInserted.mimeType == fileIndex[0].mimeType) XCTAssert(fileIndexInserted.deleted == fileIndex[0].deleted) XCTAssert(fileIndex[0].cloudStorageType == AccountScheme.google.cloudStorageType) case .error(_): XCTFail() } } func doAddDeviceUUID(userId:UserId = 1, repo:DeviceUUIDRepository) -> DeviceUUID? { let du = DeviceUUID(userId: userId, deviceUUID: Foundation.UUID().uuidString) let result = repo.add(deviceUUID: du) switch result { case .error(_), .exceededMaximumUUIDsPerUser: return nil case .success: return du } } func testAddDeviceUUID() { XCTAssert(doAddDeviceUUID(repo:DeviceUUIDRepository(db)) != nil) } func testAddDeviceUUIDFailsAfterMax() { let repo = DeviceUUIDRepository(db) if let maxNumber = repo.maximumNumberOfDeviceUUIDsPerUser { let number = maxNumber + 1 for curr in 1...number { if curr < number { XCTAssert(doAddDeviceUUID(repo: repo) != nil) } else { XCTAssert(doAddDeviceUUID(repo: repo) == nil) } } } } func testAddDeviceUUIDDoesNotFailFailsAfterMaxWithNilMax() { let repo = DeviceUUIDRepository(db) if let maxNumber = repo.maximumNumberOfDeviceUUIDsPerUser { let number = maxNumber + 1 repo.maximumNumberOfDeviceUUIDsPerUser = nil for _ in 1...number { XCTAssert(doAddDeviceUUID(repo: repo) != nil) } } } func testLookupFromDeviceUUID() { let repo = DeviceUUIDRepository(db) let result = doAddDeviceUUID(repo:repo) XCTAssert(result != nil) let key = DeviceUUIDRepository.LookupKey.deviceUUID(result!.deviceUUID) let lookupResult = repo.lookup(key: key, modelInit: DeviceUUID.init) if case .found(let model) = lookupResult, let du = model as? DeviceUUID { XCTAssert(du.deviceUUID == result!.deviceUUID) XCTAssert(du.userId == result!.userId) } else { XCTFail() } } } extension SpecificDatabaseTests { static var allTests : [(String, (SpecificDatabaseTests) -> () throws -> Void)] { return [ ("testUpdateToNextMasterVersion", testUpdateToNextMasterVersion), ("testUpdateToNextTwiceMasterVersion", testUpdateToNextTwiceMasterVersion), ("testUpdateToNextFailsWithWrongExpectedMasterVersion", testUpdateToNextFailsWithWrongExpectedMasterVersion), ("testAddFileIndex", testAddFileIndex), ("testUpdateFileIndexWithNoChanges", testUpdateFileIndexWithNoChanges), ("testUpdateFileIndexWithAChange", testUpdateFileIndexWithAChange), ("testUpdateFileIndexFailsWithoutFileIndexId", testUpdateFileIndexFailsWithoutFileIndexId), ("testUpdateUploadSucceedsWithNilAppMetaData", testUpdateUploadSucceedsWithNilAppMetaData), ("testLookupFromFileIndex", testLookupFromFileIndex), ("testFileIndexWithNoFiles", testFileIndexWithNoFiles), ("testFileIndexWithOneFile", testFileIndexWithOneFile), ("testAddDeviceUUID", testAddDeviceUUID), ("testAddDeviceUUIDFailsAfterMax", testAddDeviceUUIDFailsAfterMax), ("testAddDeviceUUIDDoesNotFailFailsAfterMaxWithNilMax", testAddDeviceUUIDDoesNotFailFailsAfterMaxWithNilMax), ("testLookupFromDeviceUUID", testLookupFromDeviceUUID) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SpecificDatabaseTests.self) } } <file_sep>#!/bin/bash # Usage: pass in the directory to process DIRECTORY=$1 for fileNameWithPath in "$DIRECTORY"/*; do mimeType=`file --mime-type "$fileNameWithPath" | awk '{print $NF}'` # echo \"$mimeType\" if [ "$mimeType" == "text/plain" ]; then extension="txt" else extension="jpg" fi # fileName=$(basename "$fileNameWithPath") mv "$fileNameWithPath" "$fileNameWithPath.$extension" done<file_sep>// // UtilController.swift // Server // // Created by <NAME> on 11/26/16. // // import LoggerAPI import Credentials import SyncServerShared import Foundation class UtilController : ControllerProtocol { static var serverStart:Date! class func setup() -> Bool { serverStart = Date() return true } func healthCheck(params:RequestProcessingParameters) { let response = HealthCheckResponse() response.currentServerDateTime = Date() response.serverUptime = -UtilController.serverStart.timeIntervalSinceNow response.deployedGitTag = Configuration.misc.deployedGitTag let stats = ServerStatsKeeper.session.stats var diagnostics = "" for (key, value) in stats { diagnostics += "\(key.rawValue): \(value); " } if diagnostics.count > 0 { response.diagnostics = diagnostics } params.completion(.success(response)) } func checkPrimaryCreds(params:RequestProcessingParameters) { let response = CheckPrimaryCredsResponse() params.completion(.success(response)) } } <file_sep>// // ServerConfiguration.swift // Server // // Created by <NAME> on 12/26/16. // // import Foundation import PerfectLib import LoggerAPI // Server startup configuration info, pulled from the Server.json file. struct ServerConfiguration: Decodable { /* When adding this .json into your Xcode project make sure to a) add it into Copy Files in Build Phases, and b) select Products Directory as a destination. For testing, I've had to put a build script in that does: cp Server.json /tmp */ static let serverConfigFile = "Server.json" struct mySQL: Decodable { let host:String let user:String let password:<PASSWORD> let database:String } let db:mySQL let port:Int // For Kitura Credentials plugins let signInTokenTimeToLive: TimeInterval? // If you are using Google Accounts let GoogleServerClientId:String? let GoogleServerClientSecret:String? // If you are using Facebook Accounts let FacebookClientId:String? // This is the AppId from Facebook let FacebookClientSecret:String? // App Secret from Facebook // If you are using Microsoft Accounts let MicrosoftClientId:String? let MicrosoftClientSecret:String? struct AppleSignIn: Decodable { // From creating a Service Id for your app. let redirectURI: String // The reverse DNS style app identifier for your iOS app. let clientId: String // MARK: For generating the client secret; See notes in AppleSignInCreds+ClientSecret.swift let keyId: String let teamId: String // Once generated from the Apple developer's website, the key is converted // to a single line for the JSON using: // awk 'NF {sub(/\r/, ""); printf "%s\\\\n",$0;}' *.p8 // Script from https://docs.vmware.com/en/Unified-Access-Gateway/3.0/com.vmware.access-point-30-deploy-config.doc/GUID-870AF51F-AB37-4D6C-B9F5-4BFEB18F11E9.html let privateKey: String } let appleSignIn: AppleSignIn? let maxNumberDeviceUUIDPerUser:Int? struct AllowedSignInTypes: Decodable { let Google:Bool? let Facebook:Bool? let Dropbox:Bool? let Microsoft:Bool? let AppleSignIn: Bool? } let allowedSignInTypes:AllowedSignInTypes struct OwningUserAccountCreation: Decodable { let initialFileName:String? let initialFileContents:String? } let owningUserAccountCreation:OwningUserAccountCreation let iOSMinimumClientVersion: String? // For AWS SNS (Push Notifications) struct AWSSNS: Decodable { let accessKeyId: String? let secretKey: String? let region: String? let platformApplicationArn: String? } let awssns:AWSSNS? // If set to true, uses MockStorage. // This is a `var` only for testing-- so I can change this to true during test cases. var loadTestingCloudStorage: Bool? #if DEBUG mutating func setupLoadTestingCloudStorage() { loadTestingCloudStorage = true } #endif } <file_sep>// // FileController_FileGroupUUID.swift // ServerTests // // Created by <NAME> on 4/20/18. // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class FileController_FileGroupUUIDTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testUploadWithFileGroupUUIDWorks() { let deviceUUID = Foundation.UUID().uuidString let fileGroupUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, fileGroupUUID: fileGroupUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } // Have to do a DoneUploads to transfer the files into the FileIndex self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) guard let (files, _) = getIndex(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID), let fileIndex = files, fileIndex.count == 1 else { XCTFail() return } XCTAssert(uploadResult1.request.fileGroupUUID != nil) let fileInfo = fileIndex[0] XCTAssert(uploadResult1.request.fileGroupUUID == fileInfo.fileGroupUUID) } // Make sure when uploading version 1 of a file, given with nil fileGroupUUID, the fileGroupUUID doesn't reset to nil-- when you gave a fileGroupUUID when uploading v0 func testUploadVersion1WithNilFileGroupUUIDWorks() { let deviceUUID = Foundation.UUID().uuidString let fileGroupUUID = Foundation.UUID().uuidString // Upload v0, with fileGroupUUID guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID, fileGroupUUID: fileGroupUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) // Upload v1 with nil fileGroupUUID guard let _ = uploadTextFile(deviceUUID:deviceUUID, fileUUID:uploadResult1.request.fileUUID, addUser:.no(sharingGroupUUID: sharingGroupUUID), fileVersion:1, masterVersion: 1) else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: 1, sharingGroupUUID: sharingGroupUUID) guard let (files, _) = getIndex(deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID), let fileIndex = files, fileIndex.count == 1 else { XCTFail() return } // Make sure we have v0 fileGroupUUID let fileInfo = fileIndex[0] XCTAssert(fileGroupUUID == fileInfo.fileGroupUUID) } // Give fileGroupUUID with version 1 of file (but not with v0)-- make sure this fails. func testFileGroupUUIDOnlyWithVersion1Fails() { let deviceUUID = Foundation.UUID().uuidString let fileGroupUUID = Foundation.UUID().uuidString // Upload v0, *without* fileGroupUUID guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) // Upload v1 *with* fileGroupUUID uploadTextFile(deviceUUID:deviceUUID, fileUUID:uploadResult1.request.fileUUID, addUser:.no(sharingGroupUUID: sharingGroupUUID), fileVersion:1, masterVersion: 1, errorExpected: true, fileGroupUUID: fileGroupUUID) } } extension FileController_FileGroupUUIDTests { static var allTests : [(String, (FileController_FileGroupUUIDTests) -> () throws -> Void)] { return [ ("testUploadWithFileGroupUUIDWorks", testUploadWithFileGroupUUIDWorks), ("testUploadVersion1WithNilFileGroupUUIDWorks", testUploadVersion1WithNilFileGroupUUIDWorks), ("testFileGroupUUIDOnlyWithVersion1Fails", testFileGroupUUIDOnlyWithVersion1Fails) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:FileController_MultiVersionFiles.self) } } <file_sep>#!/bin/bash # Usage: showUsers.sh <Server.json> # e.g., ./devops/showUsers.sh ~/Desktop/Apps/SyncServerII/Private/Server.json.aws.app.bundles/Neebla-production.json MY_SQL_JSON=$1 DATABASE=`jq -r '.["mySQL.database"]' < ${MY_SQL_JSON}` USER=`jq -r '.["mySQL.user"]' < ${MY_SQL_JSON}` PASSWORD=`jq -r '.["mySQL.password"]' < ${MY_SQL_JSON}` HOST=`jq -r '.["mySQL.host"]' < ${MY_SQL_JSON}` SCRIPT="select username, accountType from User;" # --json option on mysql not working on version of mysql I have installed with macOS: # mysql Ver 14.14 Distrib 5.7.23, for osx10.14 (x86_64) using EditLine wrapper # and the mySQL version I'm using on AWS RDS doesn't support it either: # https://stackoverflow.com/questions/41758870/how-to-convert-result-table-to-json-array-in-mysql # I get: # ERROR 1305 (42000) at line 1: FUNCTION SyncServer_SharedImages.JSON_OBJECT does not exist echo "Users: " mysql -P 3306 --password="$<PASSWORD>" --user="$USER" --host="$HOST" --database="$DATABASE" -Bse "$SCRIPT" 2>&1 | grep -v "Using a password" <file_sep>The SyncServerII iOS client library has a mechanism to enable taking the server down for maintenance, and reporting that downtime to the iOS client app. See also https://github.com/crspybits/SyncServerII/issues/84 The following assumes the server is running on AWS/Elastic Beanstalk. 1) Edit the failover file message (e.g., production.motd.txt). The iOS client app already displays the title "The server is down for maintenance." 2) Copy the failover file to the relevant location on AWS/S3. The usage of S3 is incidental; these message files just need to be placed where the iOS app is expecting them. The URL paths for these files are specified in the Server.plist file in the iOS app. 3) Make sure the message file on S3 has public-read permissions set. (AWS S3 will probably complain loudly at this permissions setting, but that's OK). 4) Take the server down using the "suspend.sh on" script of the relevant environment. This will take the server down to 0 EC2 instances and cause the load balancer to respond with a 503 HTTP status code, which the iOS client app uses to detect this maintenance condition. See the example message image file in this folder. At this point, the server will not accept new requests. (I'm not sure what happens when you reduce to 0 instances, for requests that are currently running.) And you can perform database maintenance as needed. To bring the server back up, do the following: A) If there is a server version update, deploy that update using the "deploy.sh" script for the relevant environment. Note that while there are 0 EC2 instances currently running, this *does* update the AWS application source bundle for the environment so that the next step will work. Though just now (4/2/19), I had to run deploy.sh a second time (with the same environment info) after the "suspend.sh off" because the environment was in a "Warning" state. B) Use the "suspend.sh off" script to resume the server. (As noted above, if you deployed a new server version, this will run that version). C) Remove the failover file on S3. The intent is that this file is only in place when we are doing server maintenance.<file_sep># For Ubuntu 16.04, Swift 5.0.1 (IBM only has a `latest` at least as of 6/12/19) FROM ibmcom/swift-ubuntu-xenial-runtime:latest LABEL maintainer="<NAME> <<EMAIL>>" LABEL Description="Runtime Docker Container for the Apple's Swift programming language" # 6/15/19; I got a failure in running SyncServerII due to not finding libbsd; apparently this is present in the development build of Kitura/Ubuntu, but not in the runtime. Though I can't find it in the development build with `dpkg -l libbsd` or `dpkg -l libbsd-dev`. `apt-get install libbsd` doesn't find a package. # Install additional packages RUN apt-get -q update && \ apt-get -q install -y \ uuid-dev \ libmysqlclient-dev \ openssl \ libssl-dev \ pkg-config \ tzdata \ libbsd-dev \ && rm -r /var/lib/apt/lists/* CMD /bin/bash<file_sep>-- Modified from https://stackoverflow.com/questions/6121917/automatic-rollback-if-commit-transaction-is-not-reached delimiter // create procedure migration() begin DECLARE exit handler for sqlexception BEGIN GET DIAGNOSTICS CONDITION 1 @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT; SELECT @p1, @p2; ROLLBACK; END; DECLARE exit handler for sqlwarning BEGIN GET DIAGNOSTICS CONDITION 1 @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT; SELECT @p1, @p2; ROLLBACK; END; START TRANSACTION; ALTER TABLE User DROP COLUMN userType; ALTER TABLE User CHANGE COLUMN sharingPermission permission VARCHAR(5); ALTER TABLE SharingInvitation CHANGE COLUMN sharingPermission permission VARCHAR(5); -- Create SharingGroup table; edited this from show create table SharingGroup; CREATE TABLE `SharingGroup` (`sharingGroupId` bigint(20) NOT NULL AUTO_INCREMENT, UNIQUE KEY `sharingGroupId` (`sharingGroupId`)) ENGINE=InnoDB; -- Create SharingGroupUser table. CREATE TABLE `SharingGroupUser` (`sharingGroupUserId` bigint(20) NOT NULL AUTO_INCREMENT, `sharingGroupId` bigint(20) NOT NULL, `userId` bigint(20) NOT NULL, UNIQUE (`sharingGroupId`,`userId`), UNIQUE (`sharingGroupUserId`), FOREIGN KEY (`userId`) REFERENCES `User` (`userId`), FOREIGN KEY (`sharingGroupId`) REFERENCES `SharingGroup` (`sharingGroupId`)) ENGINE=InnoDB; -- Need to insert into the SharingGroup table a row for our group-- Rod, Dany, Me, Natasha. INSERT INTO SharingGroup (sharingGroupId) values (null); SELECT @firstSharingGroupId := MAX(sharingGroupId) FROM SharingGroup; -- Got these by inspection SET @ChrisUserId := 1; SET @NatashaUserId := 2; SET @RodUserId := 3; SET @DanyUserId := 4; -- Add these users into the SharingGroupUser table with this sharing group. INSERT INTO SharingGroupUser (sharingGroupId, userId) VALUES (@firstSharingGroupId, @ChrisUserId); INSERT INTO SharingGroupUser (sharingGroupId, userId) VALUES (@firstSharingGroupId, @NatashaUserId); INSERT INTO SharingGroupUser (sharingGroupId, userId) VALUES (@firstSharingGroupId, @RodUserId); INSERT INTO SharingGroupUser (sharingGroupId, userId) VALUES (@firstSharingGroupId, @DanyUserId); -- Create SharingGroup row for Apple review user. INSERT INTO SharingGroup (sharingGroupId) values (null); SELECT @secondSharingGroupId := MAX(sharingGroupId) FROM SharingGroup; SET @AppleReviewUserId := 12; -- Add this user into the SharingGroupUser table with this sharing group. INSERT INTO SharingGroupUser (sharingGroupId, userId) VALUES (@secondSharingGroupId, @AppleReviewUserId); -- Adding sharingGroupId column to SharingInvitation table. -- Need to delete rows from SharingInvitation first DELETE FROM SharingInvitation; ALTER TABLE SharingInvitation ADD COLUMN sharingGroupId bigint(20) NOT NULL, ADD FOREIGN KEY (sharingGroupId) REFERENCES SharingGroup (sharingGroupId); -- Need to convert Dany, Rod, and Natasha into owning users. UPDATE User SET owningUserId = NULL, cloudFolderName = 'SharedImages.Folder' WHERE userId = @NatashaUserId; UPDATE User SET owningUserId = NULL, cloudFolderName = 'SharedImages.Folder' WHERE userId = @RodUserId; UPDATE User SET owningUserId = NULL, cloudFolderName = 'SharedImages.Folder' WHERE userId = @DanyUserId; -- Update Chris/Facebook SET @ChrisFacebookUserId := 11; INSERT INTO SharingGroupUser (sharingGroupId, userId) VALUES (@firstSharingGroupId, @ChrisFacebookUserId); -- Make changes to owning users: Chris/Google, Chris/Dropbox, AppleDev UPDATE User SET permission = 'admin' WHERE userId = @ChrisUserId; SET @ChrisDropboxUserId := 13; UPDATE User SET permission = 'admin' WHERE userId = @ChrisDropboxUserId; INSERT INTO SharingGroup (sharingGroupId) values (null); SELECT @thirdSharingGroupId := MAX(sharingGroupId) FROM SharingGroup; INSERT INTO SharingGroupUser (sharingGroupId, userId) VALUES (@thirdSharingGroupId, @ChrisDropboxUserId); UPDATE User SET permission = 'admin' WHERE userId = @AppleReviewUserId; -- Adding sharingGroupId column to FileIndex table -- Right now, all except one file is owned by me. One file was uploaded by the apple dev account. ALTER TABLE FileIndex ADD COLUMN sharingGroupId bigint(20); UPDATE FileIndex SET sharingGroupId = @firstSharingGroupId WHERE userId = @ChrisUserId; UPDATE FileIndex SET sharingGroupId = @secondSharingGroupId WHERE userId = @AppleReviewUserId; ALTER TABLE FileIndex MODIFY sharingGroupId bigint(20) NOT NULL; ALTER TABLE FileIndex ADD CONSTRAINT FOREIGN KEY (sharingGroupId) REFERENCES SharingGroup (sharingGroupId); -- Adding sharingGroupId column to Upload table. DELETE FROM Upload; ALTER TABLE Upload ADD COLUMN sharingGroupId bigint(20) NOT NULL, ADD FOREIGN KEY (sharingGroupId) REFERENCES SharingGroup (sharingGroupId); -- Change from UNIQUE (fileUUID, userId) for FileIndex to UNIQUE (fileUUID, sharingGroupId). ALTER TABLE FileIndex DROP INDEX FileUUID; ALTER TABLE FileIndex ADD UNIQUE (fileUUID, sharingGroupId); -- Master version table: -- Replace userId with sharingGroupId -- * Should just be a few userId's in the production table-- and predominantly, mine. -- -- mysql> select * from MasterVersion; -- +--------+---------------+ -- | userId | masterVersion | -- +--------+---------------+ -- | 1 | 484 | -- | 12 | 1 | -- | 13 | 0 | -- +--------+---------------+ -- 3 rows in set (0.05 sec) -- SET @AppleReviewUserId := 12; -- SET @ChrisUserId := 1; -- SET @ChrisDropboxUserId := 13; -- CREATE TABLE `MasterVersion` ( -- `userId` bigint(20) NOT NULL, -- `masterVersion` bigint(20) NOT NULL, -- UNIQUE KEY `userId` (`userId`) -- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 -- SET @firstSharingGroupId := 1; -- -- For Apple Review -- SET @secondSharingGroupId := 2; -- -- For Dropbox -- SET @thirdSharingGroupId := 3; ALTER TABLE MasterVersion DROP INDEX userId; ALTER TABLE MasterVersion ADD COLUMN sharingGroupId bigint(20); UPDATE MasterVersion SET sharingGroupId = @secondSharingGroupId WHERE userId = @AppleReviewUserId; UPDATE MasterVersion SET sharingGroupId = @thirdSharingGroupId WHERE userId = @ChrisDropboxUserId; UPDATE MasterVersion SET sharingGroupId = @firstSharingGroupId WHERE userId = @ChrisUserId; ALTER TABLE MasterVersion DROP COLUMN userId; ALTER TABLE MasterVersion MODIFY sharingGroupId bigint(20) NOT NULL; ALTER TABLE MasterVersion ADD CONSTRAINT FOREIGN KEY (sharingGroupId) REFERENCES SharingGroup (sharingGroupId); ALTER TABLE MasterVersion ADD UNIQUE (sharingGroupId); -- Changing the Lock table to have a sharingGroupId as index. -- userId column removed; replaced with sharingGroupId column. -- No longer have UNIQUE (userId) but have UNIQUE (sharingGroupId) ALTER TABLE ShortLocks DROP INDEX userId; ALTER TABLE ShortLocks DROP COLUMN userId; ALTER TABLE ShortLocks ADD COLUMN sharingGroupId bigint(20) NOT NULL, ADD FOREIGN KEY (sharingGroupId) REFERENCES SharingGroup (sharingGroupId); ALTER TABLE ShortLocks ADD UNIQUE (sharingGroupId); COMMIT; end// delimiter ; Use SyncServer_SharedImages; call migration(); drop procedure migration; DROP DATABASE syncserver; <file_sep>// // DatabaseModelTests.swift // Server // // Created by <NAME> on 5/2/17. // // import XCTest @testable import Server import LoggerAPI import HeliumLogger import Foundation import SyncServerShared class DatabaseModelTests: XCTestCase, LinuxTestable { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testDeviceUUID() { let deviceUUID = DeviceUUID(userId: 0, deviceUUID: Foundation.UUID().uuidString) let newDeviceUUID = Foundation.UUID().uuidString let newUserId = Int64(10) deviceUUID[DeviceUUID.deviceUUIDKey] = newDeviceUUID deviceUUID[DeviceUUID.userIdKey] = newUserId XCTAssert(deviceUUID.deviceUUID == newDeviceUUID) XCTAssert(deviceUUID.userId == newUserId) deviceUUID[DeviceUUID.deviceUUIDKey] = nil deviceUUID[DeviceUUID.userIdKey] = nil XCTAssert(deviceUUID.deviceUUID == nil) XCTAssert(deviceUUID.userId == nil) } func testMasterVersion() { let masterVersion = MasterVersion() let newSharingGroupUUID = UUID().uuidString let newMasterVersion = MasterVersionInt(100) masterVersion[MasterVersion.sharingGroupUUIDKey] = newSharingGroupUUID masterVersion[MasterVersion.masterVersionKey] = newMasterVersion XCTAssert(masterVersion.sharingGroupUUID == newSharingGroupUUID) XCTAssert(masterVersion.masterVersion == newMasterVersion) masterVersion[MasterVersion.sharingGroupUUIDKey] = nil masterVersion[MasterVersion.masterVersionKey] = nil XCTAssert(masterVersion.sharingGroupUUID == nil) XCTAssert(masterVersion.masterVersion == nil) } func testSharingInvitation() { let sharingInvitation = SharingInvitation() let newSharingInvitationUUID = Foundation.UUID().uuidString let newExpiry = Date() let newOwningUserId = UserId(342) let newSharingPermission:Permission = .read sharingInvitation[SharingInvitation.sharingInvitationUUIDKey] = newSharingInvitationUUID sharingInvitation[SharingInvitation.expiryKey] = newExpiry sharingInvitation[SharingInvitation.owningUserIdKey] = newOwningUserId sharingInvitation[SharingInvitation.permissionKey] = newSharingPermission XCTAssert(sharingInvitation.sharingInvitationUUID == newSharingInvitationUUID) XCTAssert(sharingInvitation.expiry == newExpiry) XCTAssert(sharingInvitation.owningUserId == newOwningUserId) XCTAssert(sharingInvitation.permission == newSharingPermission) sharingInvitation[SharingInvitation.sharingInvitationUUIDKey] = nil sharingInvitation[SharingInvitation.expiryKey] = nil sharingInvitation[SharingInvitation.owningUserIdKey] = nil sharingInvitation[SharingInvitation.permissionKey] = nil XCTAssert(sharingInvitation.sharingInvitationUUID == nil) XCTAssert(sharingInvitation.expiry == nil) XCTAssert(sharingInvitation.owningUserId == nil) XCTAssert(sharingInvitation.permission == nil) } func testUser() { let user = User() let newUserId = UserId(43287) let newUsername = "foobar" let newAccountType: AccountScheme.AccountName = AccountScheme.google.accountName let newCredsId = "<PASSWORD>" let newCreds = "<PASSWORD>" user[User.userIdKey] = newUserId user[User.usernameKey] = newUsername user[User.accountTypeKey] = newAccountType user[User.credsIdKey] = newCredsId user[User.credsKey] = newCreds XCTAssert(user.userId == newUserId) XCTAssert(user.username == newUsername) // Swift Compiler issues. // XCTAssert(user.accountType == newAccountType) if user.accountType != newAccountType { XCTFail() } XCTAssert(user.credsId == newCredsId) XCTAssert(user.creds == newCreds) user[User.userIdKey] = nil user[User.usernameKey] = nil user[User.accountTypeKey] = nil user[User.credsIdKey] = nil user[User.credsKey] = nil XCTAssert(user.userId == nil) XCTAssert(user.username == nil) XCTAssert(user.accountType == nil) XCTAssert(user.credsId == nil) XCTAssert(user.creds == nil) } func testFileIndex() { let fileIndex = FileIndex() let newFileIndexId = FileIndexId(334) let newFileUUID = Foundation.UUID().uuidString let newDeviceUUID = Foundation.UUID().uuidString let newUserId = UserId(3226453) let newMimeType = "text/plain" let newAppMetaData = "whatever" let newDeleted = false let newFileVersion = FileVersionInt(100) let newCheckSum = "abcdef" let creationDate = Date() let updateDate = Date() fileIndex[FileIndex.fileIndexIdKey] = newFileIndexId fileIndex[FileIndex.fileUUIDKey] = newFileUUID fileIndex[FileIndex.deviceUUIDKey] = newDeviceUUID fileIndex[FileIndex.userIdKey] = newUserId fileIndex[FileIndex.mimeTypeKey] = newMimeType fileIndex[FileIndex.appMetaDataKey] = newAppMetaData fileIndex[FileIndex.deletedKey] = newDeleted fileIndex[FileIndex.fileVersionKey] = newFileVersion fileIndex[FileIndex.lastUploadedCheckSumKey] = newCheckSum fileIndex[FileIndex.creationDateKey] = creationDate fileIndex[FileIndex.updateDateKey] = updateDate XCTAssert(fileIndex.fileIndexId == newFileIndexId) XCTAssert(fileIndex.fileUUID == newFileUUID) XCTAssert(fileIndex.deviceUUID == newDeviceUUID) XCTAssert(fileIndex.userId == newUserId) XCTAssert(fileIndex.mimeType == newMimeType) XCTAssert(fileIndex.appMetaData == newAppMetaData) XCTAssert(fileIndex.deleted == newDeleted) XCTAssert(fileIndex.fileVersion == newFileVersion) XCTAssert(fileIndex.lastUploadedCheckSum == newCheckSum) XCTAssert(fileIndex.creationDate == creationDate) XCTAssert(fileIndex.updateDate == updateDate) fileIndex[FileIndex.fileIndexIdKey] = nil fileIndex[FileIndex.fileUUIDKey] = nil fileIndex[FileIndex.deviceUUIDKey] = nil fileIndex[FileIndex.userIdKey] = nil fileIndex[FileIndex.mimeTypeKey] = nil fileIndex[FileIndex.appMetaDataKey] = nil fileIndex[FileIndex.deletedKey] = nil fileIndex[FileIndex.fileVersionKey] = nil fileIndex[FileIndex.lastUploadedCheckSumKey] = nil fileIndex[FileIndex.creationDateKey] = nil fileIndex[FileIndex.updateDateKey] = nil XCTAssert(fileIndex.fileIndexId == nil) XCTAssert(fileIndex.fileUUID == nil) XCTAssert(fileIndex.deviceUUID == nil) XCTAssert(fileIndex.userId == nil) XCTAssert(fileIndex.mimeType == nil) XCTAssert(fileIndex.appMetaData == nil) XCTAssert(fileIndex.deleted == nil) XCTAssert(fileIndex.fileVersion == nil) XCTAssert(fileIndex.lastUploadedCheckSum == nil) XCTAssert(fileIndex.creationDate == nil) XCTAssert(fileIndex.updateDate == nil) } func testUpload() { let upload = Upload() let uploadId = Int64(3300) let fileUUID = Foundation.UUID().uuidString let userId = UserId(43) let fileVersion = FileVersionInt(322) let deviceUUID = Foundation.UUID().uuidString let state:UploadState = .toDeleteFromFileIndex let appMetaData = "arba" let fileCheckSum = TestFile.test1.dropboxCheckSum let mimeType = "text/plain" let creationDate = Date() let updateDate = Date() upload[Upload.uploadIdKey] = uploadId upload[Upload.fileUUIDKey] = fileUUID upload[Upload.userIdKey] = userId upload[Upload.fileVersionKey] = fileVersion upload[Upload.deviceUUIDKey] = deviceUUID upload[Upload.stateKey] = state upload[Upload.appMetaDataKey] = appMetaData upload[Upload.lastUploadedCheckSumKey] = fileCheckSum upload[Upload.mimeTypeKey] = mimeType upload[Upload.creationDateKey] = creationDate upload[Upload.updateDateKey] = updateDate XCTAssert(upload.uploadId == uploadId) XCTAssert(upload.fileUUID == fileUUID) XCTAssert(upload.userId == userId) XCTAssert(upload.fileVersion == fileVersion) XCTAssert(upload.deviceUUID == deviceUUID) XCTAssert(upload.state == state) XCTAssert(upload.appMetaData == appMetaData) XCTAssert(upload.lastUploadedCheckSum == fileCheckSum) XCTAssert(upload.mimeType == mimeType) XCTAssert(upload.creationDate == creationDate) XCTAssert(upload.updateDate == updateDate) upload[Upload.uploadIdKey] = nil upload[Upload.fileUUIDKey] = nil upload[Upload.userIdKey] = nil upload[Upload.fileVersionKey] = nil upload[Upload.deviceUUIDKey] = nil upload[Upload.stateKey] = nil upload[Upload.appMetaDataKey] = nil upload[Upload.lastUploadedCheckSumKey] = nil upload[Upload.mimeTypeKey] = nil upload[Upload.creationDateKey] = nil upload[Upload.updateDateKey] = nil XCTAssert(upload.uploadId == nil) XCTAssert(upload.fileUUID == nil) XCTAssert(upload.userId == nil) XCTAssert(upload.fileVersion == nil) XCTAssert(upload.deviceUUID == nil) XCTAssert(upload.state == nil) XCTAssert(upload.appMetaData == nil) XCTAssert(upload.lastUploadedCheckSum == nil) XCTAssert(upload.mimeType == nil) XCTAssert(upload.creationDate == nil) XCTAssert(upload.updateDate == nil) } // SharingGroup // SharingGroupUser } extension DatabaseModelTests { static var allTests : [(String, (DatabaseModelTests) -> () throws -> Void)] { return [ ("testDeviceUUID", testDeviceUUID), ("testMasterVersion", testMasterVersion), ("testSharingInvitation", testSharingInvitation), ("testUser", testUser), ("testFileIndex", testFileIndex), ("testUpload", testUpload), ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:DatabaseModelTests.self) } } <file_sep>-- Some of this script modified from https://stackoverflow.com/questions/6121917/automatic-rollback-if-commit-transaction-is-not-reached -- Local testing procedure-- to test migration -- 1) Export production db structure/contents from AWS RDS -- 2) Drop local db tables -- 3) Apply production AWS RDS dump to local db -- 4) Run migration SQL script on local db -- 5) Check tables and make sure structure looks right. -- Exporting from AWS RDS -- mysqldump -h url.for.db -P 3306 -u username -p --databases SyncServer_SharedImages > dump.sql -- use SyncServer_SharedImages; -- drop table DeviceUUID; drop table SharingGroupLock; drop table FileIndex; drop table MasterVersion; drop table SharingGroupUser; drop table Upload; drop table User; drop table SharingInvitation; drop table SharingGroup; -- importing to local db -- mysql -u root -p < ~/Desktop/dump.sql -- delete from DeviceUUID; delete from ShortLocks; delete from FileIndex; delete from MasterVersion; delete from SharingGroupUser; delete from Upload; delete from User; delete from SharingInvitation; delete from SharingGroup; -- show structure of a table -- describe Upload; -- or other table name delimiter // create procedure migration() begin DECLARE exit handler for sqlexception BEGIN GET DIAGNOSTICS CONDITION 1 @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT; SELECT @p1, @p2, "ERROR999"; ROLLBACK; END; DECLARE exit handler for sqlwarning BEGIN GET DIAGNOSTICS CONDITION 1 @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT; SELECT @p1, @p2, "ERROR999"; ROLLBACK; END; START TRANSACTION; ALTER TABLE SharingInvitation ADD COLUMN allowSocialAcceptance BOOL NOT NULL DEFAULT TRUE; ALTER TABLE SharingInvitation ADD COLUMN numberAcceptors INT UNSIGNED NOT NULL DEFAULT 1; SELECT "SUCCESS123"; COMMIT; end// delimiter ; -- Not needed because the command line invocation of mysql specifies the database. -- Use SyncServer_SharedImages; call migration(); drop procedure migration; <file_sep>// // Model.swift // Server // // Created by <NAME> on 12/7/16. // // import Foundation // Your object that abides by this protocol must provide member properties that match the databases column names and types. protocol Model : class { // Optionally provide converters that will enable converting from MySQL field values to their corresponding model values. // This ought to be an optional func, but Object isn't @objc so I don't seem to be able do that. func typeConvertersToModel(propertyName:String) -> ((_ propertyValue:Any) -> Any?)? // Reflection is pretty limited in Swift. I was using Zewo Reflection before to do a KVC-type set but that seems pretty broken on Ubuntu Linux as of 5/1/17 and Swift 3.1.1. See also https://github.com/Zewo/Zewo/issues/238 // Subscripts can't (yet?) throw in Swift, otherwise, I'd have made this throw. subscript(key:String) -> Any? {set get} } extension Model { // Default implementation so Model's don't have to provide it. func typeConvertersToModel(propertyName:String) -> ((_ propertyValue:Any) -> Any?)? { return nil } func getValue(forKey key:String) -> Any? { let selfMirror = Mirror(reflecting: self) if let child = selfMirror.descendant(key) { return child } else { return nil } } } <file_sep>eb create neebla-production --cname neebla-production <file_sep>// // FileControllerTests_UploadDeletion.swift // Server // // Created by <NAME> on 2/18/17. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class FileControllerTests_UploadDeletion: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // TODO: *1* To test these it would be best to have a debugging endpoint or other service where we can test to see if the file is present in cloud storage. // TODO: *1* Also useful would be a service that lets us directly delete a file from cloud storage-- to simulate errors in file deletion. func testThatUploadDeletionTransfersToUploads() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult1.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult1.request.fileVersion uploadDeletionRequest.masterVersion = uploadResult1.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false) let expectedDeletionState = [ uploadResult1.request.fileUUID!: true, ] self.getUploads(expectedFiles: [uploadResult1.request], deviceUUID:deviceUUID, matchOptionals: false, expectedDeletionState:expectedDeletionState, sharingGroupUUID:sharingGroupUUID) self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: uploadResult1.request.masterVersion + MasterVersionInt(1), sharingGroupUUID: sharingGroupUUID) self.getUploads(expectedFiles: [], deviceUUID:deviceUUID, matchOptionals: false, sharingGroupUUID:sharingGroupUUID) } func testThatCombinedUploadDeletionAndFileUploadWork() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult1.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult1.request.fileVersion uploadDeletionRequest.masterVersion = uploadResult1.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false) let expectedDeletionState = [ uploadResult1.request.fileUUID!: true, ] self.getUploads(expectedFiles: [uploadResult1.request], deviceUUID:deviceUUID, matchOptionals: false, expectedDeletionState:expectedDeletionState, sharingGroupUUID:sharingGroupUUID) self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: uploadResult1.request.masterVersion + MasterVersionInt(1), sharingGroupUUID: sharingGroupUUID) self.getUploads(expectedFiles: [], deviceUUID:deviceUUID, matchOptionals: false, sharingGroupUUID:sharingGroupUUID) self.getIndex(expectedFiles: [uploadResult1.request], masterVersionExpected: uploadResult1.request.masterVersion + MasterVersionInt(2), sharingGroupUUID: sharingGroupUUID, expectedDeletionState:expectedDeletionState) } func testThatUploadDeletionTwiceOfSameFileWorks() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult1.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult1.request.fileVersion uploadDeletionRequest.masterVersion = uploadResult1.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false) uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false) let expectedDeletionState = [ uploadResult1.request.fileUUID!: true, ] self.getUploads(expectedFiles: [uploadResult1.request], deviceUUID:deviceUUID, matchOptionals: false, expectedDeletionState:expectedDeletionState, sharingGroupUUID:sharingGroupUUID) } func testThatUploadDeletionFollowedByDoneUploadsActuallyDeletes() { let deviceUUID = Foundation.UUID().uuidString // This file is going to be deleted. guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult1.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult1.request.fileVersion uploadDeletionRequest.masterVersion = uploadResult1.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false) // This file will not be deleted. guard let uploadResult2 = uploadTextFile(deviceUUID:deviceUUID, addUser:.no(sharingGroupUUID: sharingGroupUUID), masterVersion: uploadResult1.request.masterVersion + MasterVersionInt(1)) else { XCTFail() return } let expectedDeletionState = [ uploadResult1.request.fileUUID!: true, uploadResult2.request.fileUUID!: false ] self.getUploads(expectedFiles: [uploadResult1.request, uploadResult2.request], deviceUUID:deviceUUID, matchOptionals: false, expectedDeletionState:expectedDeletionState, sharingGroupUUID:sharingGroupUUID) self.sendDoneUploads(expectedNumberOfUploads: 2, deviceUUID:deviceUUID, masterVersion: uploadResult1.request.masterVersion + MasterVersionInt(1), sharingGroupUUID: sharingGroupUUID) self.getUploads(expectedFiles: [], deviceUUID:deviceUUID, matchOptionals: false, expectedDeletionState:expectedDeletionState, sharingGroupUUID:sharingGroupUUID) self.getIndex(expectedFiles: [uploadResult1.request, uploadResult2.request], masterVersionExpected: uploadResult1.request.masterVersion + MasterVersionInt(2), sharingGroupUUID: sharingGroupUUID, expectedDeletionState:expectedDeletionState) } // TODO: *0* Test upload deletion with with 2 files func testThatDeletionOfDifferentVersionFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult1.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult1.request.fileVersion + FileVersionInt(1) uploadDeletionRequest.masterVersion = uploadResult1.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false, expectError: true) } func testThatDeletionOfUnknownFileUUIDFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = Foundation.UUID().uuidString uploadDeletionRequest.fileVersion = uploadResult.request.fileVersion uploadDeletionRequest.masterVersion = uploadResult.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false, expectError: true) } // TODO: *1* Make sure a deviceUUID from a different user cannot do an UploadDeletion for our file. func testThatDeletionFailsWhenMasterVersionDoesNotMatch() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult.request.fileVersion uploadDeletionRequest.masterVersion = MasterVersionInt(100) uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false, updatedMasterVersionExpected: 1) } func testThatDebugDeletionFromServerWorks() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult.request.fileVersion uploadDeletionRequest.masterVersion = uploadResult.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.actualDeletion = true uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false) // Make sure deletion actually occurred! self.getIndex(expectedFiles: [], masterVersionExpected: uploadResult.request.masterVersion + MasterVersionInt(1), sharingGroupUUID: sharingGroupUUID, expectedDeletionState:[:]) self.performServerTest { expectation, creds in let cloudFileName = uploadDeletionRequest.cloudFileName(deviceUUID: deviceUUID, mimeType: uploadResult.request.mimeType) let options = CloudStorageFileNameOptions(cloudFolderName: ServerTestCase.cloudFolderName, mimeType: uploadResult.request.mimeType) let cloudStorageCreds = creds as! CloudStorage cloudStorageCreds.lookupFile(cloudFileName:cloudFileName, options:options) { result in switch result { case .success(let found): XCTAssert(!found) case .failure, .accessTokenRevokedOrExpired: XCTFail() } expectation.fulfill() } } } // Until today, 3/31/17, I had a bug in the server where this didn't work. It would try to delete the file using a name given by the the deviceUUID of the deleting device, not the uploading device. func testThatUploadByOneDeviceAndDeletionByAnotherActuallyDeletes() { let deviceUUID1 = Foundation.UUID().uuidString // This file is going to be deleted. guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, sharingGroupUUID: sharingGroupUUID) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult.request.fileVersion uploadDeletionRequest.masterVersion = uploadResult.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID let deviceUUID2 = Foundation.UUID().uuidString uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID2, addUser: false) let expectedDeletionState = [ uploadResult.request.fileUUID!: true, ] self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID2, masterVersion: uploadResult.request.masterVersion + MasterVersionInt(1), sharingGroupUUID: sharingGroupUUID) self.getIndex(expectedFiles: [uploadResult.request], masterVersionExpected: uploadResult.request.masterVersion + MasterVersionInt(2), sharingGroupUUID: sharingGroupUUID, expectedDeletionState:expectedDeletionState) } // MARK: Undeletion tests func uploadUndelete(twice: Bool = false) { let deviceUUID = Foundation.UUID().uuidString // This file is going to be deleted. guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) var masterVersion:MasterVersionInt = uploadResult.request.masterVersion + MasterVersionInt(1) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult.request.fileVersion uploadDeletionRequest.masterVersion = masterVersion uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false) sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 // Upload undeletion guard let _ = uploadTextFile(deviceUUID:deviceUUID, fileUUID: uploadResult.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion: 1, masterVersion: masterVersion, undelete: 1) else { XCTFail() return } if twice { guard let uploadResult2 = uploadTextFile(deviceUUID:deviceUUID, fileUUID: uploadResult.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion: 1, masterVersion: masterVersion, undelete: 1) else { XCTFail() return } // Check uploads-- make sure there is only one. getUploads(expectedFiles: [uploadResult2.request], deviceUUID:deviceUUID, expectedCheckSums: [uploadResult.request.fileUUID: uploadResult.checkSum], sharingGroupUUID:sharingGroupUUID) } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) // Get the file index and make sure the file is not marked as deleted. guard let (files, _) = getIndex(deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID), let fileIndex = files else { XCTFail() return } guard fileIndex.count == 1 else { XCTFail() return } XCTAssert(fileIndex[0].fileUUID == uploadResult.request.fileUUID) XCTAssert(fileIndex[0].deleted == false) } func testUploadUndeleteWorks() { uploadUndelete() } // Test that upload undelete 2x (without done uploads) doesn't fail. func textThatUploadUndeleteUploadTwiceWorks() { uploadUndelete(twice: true) } func testThatUploadDeletionWithFakeSharingGroupUUIDFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let invalidSharingGroupUUID = UUID().uuidString let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult1.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult1.request.fileVersion uploadDeletionRequest.masterVersion = uploadResult1.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = invalidSharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false, expectError: true) } func testThatUploadDeletionWithBadSharingGroupUUIDFails() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) let workingButBadSharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: workingButBadSharingGroupUUID) else { XCTFail() return } let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult1.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult1.request.fileVersion uploadDeletionRequest.masterVersion = uploadResult1.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = workingButBadSharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false, expectError: true) } } extension FileControllerTests_UploadDeletion { static var allTests : [(String, (FileControllerTests_UploadDeletion) -> () throws -> Void)] { return [ ("testThatUploadDeletionTransfersToUploads", testThatUploadDeletionTransfersToUploads), ("testThatCombinedUploadDeletionAndFileUploadWork", testThatCombinedUploadDeletionAndFileUploadWork), ("testThatUploadDeletionTwiceOfSameFileWorks", testThatUploadDeletionTwiceOfSameFileWorks), ("testThatUploadDeletionFollowedByDoneUploadsActuallyDeletes", testThatUploadDeletionFollowedByDoneUploadsActuallyDeletes), ("testThatDeletionOfDifferentVersionFails", testThatDeletionOfDifferentVersionFails), ("testThatDeletionOfUnknownFileUUIDFails", testThatDeletionOfUnknownFileUUIDFails), ("testThatDeletionFailsWhenMasterVersionDoesNotMatch", testThatDeletionFailsWhenMasterVersionDoesNotMatch), ("testThatDebugDeletionFromServerWorks", testThatDebugDeletionFromServerWorks), ("testThatUploadByOneDeviceAndDeletionByAnotherActuallyDeletes", testThatUploadByOneDeviceAndDeletionByAnotherActuallyDeletes), ("testUploadUndeleteWorks", testUploadUndeleteWorks), ("textThatUploadUndeleteUploadTwiceWorks", textThatUploadUndeleteUploadTwiceWorks), ("testThatUploadDeletionWithBadSharingGroupUUIDFails", testThatUploadDeletionWithBadSharingGroupUUIDFails), ("testThatUploadDeletionWithFakeSharingGroupUUIDFails", testThatUploadDeletionWithFakeSharingGroupUUIDFails) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:FileControllerTests_UploadDeletion.self) } } <file_sep>import XCTest import Kitura import KituraNet @testable import Server import LoggerAPI import CredentialsGoogle import Foundation import SyncServerShared class AccountAuthenticationTests_Google: ServerTestCase, LinuxTestable { let serverResponseTime:TimeInterval = 10 func testGoodEndpointWithBadCredsFails() { let deviceUUID = Foundation.UUID().uuidString performServerTest(testAccount: .google1) { expectation, googleCreds in let headers = self.setupHeaders(testUser: .google1, accessToken: "foobar", deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkPrimaryCreds, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode.rawValue)") XCTAssert(response!.statusCode == .unauthorized, "Did not fail on check creds request: \(response!.statusCode)") expectation.fulfill() } } } // Good Google creds, not creds that are necessarily on the server. func testGoodEndpointWithGoodCredsWorks() { let deviceUUID = Foundation.UUID().uuidString self.performServerTest(testAccount: .google1) { expectation, googleCreds in let headers = self.setupHeaders(testUser: .google1, accessToken: googleCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkPrimaryCreds, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "Did not work on check creds request") expectation.fulfill() } } } func testBadPathWithGoodCredsFails() { let badRoute = ServerEndpoint("foobar", method: .post, requestMessageType: AddUserRequest.self) let deviceUUID = Foundation.UUID().uuidString performServerTest(testAccount: .google1) { expectation, googleCreds in let headers = self.setupHeaders(testUser: .google1, accessToken: googleCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: badRoute, headers: headers) { response, dict in XCTAssert(response!.statusCode != .OK, "Did not fail on check creds request") expectation.fulfill() } } } func testGoodPathWithBadMethodWithGoodCredsFails() { let badRoute = ServerEndpoint(ServerEndpoints.checkCreds.pathName, method: .post, requestMessageType: CheckCredsRequest.self) XCTAssert(ServerEndpoints.checkCreds.method != .post) let deviceUUID = Foundation.UUID().uuidString self.performServerTest(testAccount: .google1) { expectation, googleCreds in let headers = self.setupHeaders(testUser: .google1, accessToken: googleCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: badRoute, headers: headers) { response, dict in XCTAssert(response!.statusCode != .OK, "Did not fail on check creds request") expectation.fulfill() } } } func testRefreshGoogleAccessTokenWorks() { guard let creds = GoogleCreds() else { XCTFail() return } creds.refreshToken = TestAccount.google1.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh { error in XCTAssert(error == nil) XCTAssert(creds.accessToken != nil) exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } } extension AccountAuthenticationTests_Google { static var allTests : [(String, (AccountAuthenticationTests_Google) -> () throws -> Void)] { var result:[(String, (AccountAuthenticationTests_Google) -> () throws -> Void)] = [ ("testGoodEndpointWithBadCredsFails", testGoodEndpointWithBadCredsFails), ("testBadPathWithGoodCredsFails", testBadPathWithGoodCredsFails), ("testGoodPathWithBadMethodWithGoodCredsFails", testGoodPathWithBadMethodWithGoodCredsFails), ("testRefreshGoogleAccessTokenWorks", testRefreshGoogleAccessTokenWorks) ] #if DEBUG result += [("testGoodEndpointWithGoodCredsWorks", testGoodEndpointWithGoodCredsWorks)] #endif return result } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:AccountAuthenticationTests_Google.self) } } <file_sep>// // DatabaseTransactionTests.swift // Server // // Created by <NAME> on 2/10/17. // // import XCTest @testable import Server // TODO: *0* Add "set global max_connections = 50;" into testing mySQL statements-- I just got an error on AWS with 66 max connections during testing. It appears I wasn't closing down connections. I have modified the code so it should now close connections, but it will be good to have this included in the testing. // To see the current connections, http://stackoverflow.com/questions/7432241/mysql-show-status-active-or-total-connections class DatabaseTransactionTests: ServerTestCase { override func setUp() { super.setUp() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // TODO: *2* I want a test where (a) an server endpoint starts with changes to the database, and (b) then fails in some way where the rollback is not explicitly done. Possibly this has to be done from a client and not at this unit testing level. Want to check to make sure this does effectively the same thing as a rollback. Might be able to do this by throwing an exception, and catching it at a higher level. } <file_sep>// // DeviceUUIDRepository.swift // Server // // Created by <NAME> on 2/14/17. // // // Tracks deviceUUID's and their userId's. This is important for security. Also can enable limitations about number of devices per userId. import Foundation import LoggerAPI import SyncServerShared class DeviceUUID : NSObject, Model { static let userIdKey = "userId" var userId: UserId! static let deviceUUIDKey = "deviceUUID" var deviceUUID: String! subscript(key:String) -> Any? { set { switch key { case DeviceUUID.userIdKey: userId = newValue as! UserId? case DeviceUUID.deviceUUIDKey: deviceUUID = newValue as! String? default: assert(false) } } get { return getValue(forKey: key) } } override init() { super.init() } init(userId: UserId, deviceUUID: String) { self.userId = userId // TODO: *2* Validate that this is a good UUID. self.deviceUUID = deviceUUID } } class DeviceUUIDRepository : Repository, RepositoryLookup { private(set) var db:Database! var maximumNumberOfDeviceUUIDsPerUser:Int? = Configuration.server.maxNumberDeviceUUIDPerUser required init(_ db:Database) { self.db = db } var tableName:String { return DeviceUUIDRepository.tableName } static var tableName:String { return "DeviceUUID" } // TODO: *3* We can possibly have the same device used by two different users. E.g., if a user signs in on the device with one set of credentials, then signs out and signs in with a different set of credentials. func upcreate() -> Database.TableUpcreateResult { let createColumns = // reference into User table "(userId BIGINT NOT NULL, " + // identifies a specific mobile device (assigned by app) "deviceUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + "UNIQUE (deviceUUID))" return db.createTableIfNeeded(tableName: "\(tableName)", columnCreateQuery: createColumns) } enum LookupKey : CustomStringConvertible { case userId(UserId) case deviceUUID(String) var description : String { switch self { case .userId(let userId): return "userId(\(userId))" case .deviceUUID(let deviceUUID): return "deviceUUID(\(deviceUUID))" } } } func lookupConstraint(key:LookupKey) -> String { switch key { case .userId(let userId): return "userId = '\(userId)'" case .deviceUUID(let deviceUUID): return "deviceUUID = '\(deviceUUID)'" } } enum DeviceUUIDAddResult { case error(String) case success case exceededMaximumUUIDsPerUser } // Adds a record // If maximumNumberOfDeviceUUIDsPerUser != nil, makes sure that the number of deviceUUID's per user doesn't exceed maximumNumberOfDeviceUUIDsPerUser func add(deviceUUID:DeviceUUID) -> DeviceUUIDAddResult { if deviceUUID.userId == nil || deviceUUID.deviceUUID == nil { let message = "One of the model values was nil!" Log.error(message) return .error(message) } var query = "INSERT INTO \(tableName) (userId, deviceUUID) " if maximumNumberOfDeviceUUIDsPerUser == nil { query += "VALUES (\(deviceUUID.userId!), '\(deviceUUID.deviceUUID!)')" } else { query += "select \(deviceUUID.userId!), '\(deviceUUID.deviceUUID!)' from Dual where " + "(select count(*) from \(tableName) where userId = \(deviceUUID.userId!)) < \(maximumNumberOfDeviceUUIDsPerUser!)" } if db.query(statement: query) { if db.numberAffectedRows() == 1 { return .success } else { return .exceededMaximumUUIDsPerUser } } else { let message = "Could not insert into \(tableName): \(db.error)" Log.error(message) return .error(message) } } } <file_sep>// // FileController_UploadTests.swift // Server // // Created by <NAME> on 3/22/17. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class FileController_UploadTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testUploadTextFile() { let deviceUUID = Foundation.UUID().uuidString guard let result = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = result.sharingGroupUUID else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID) let fileIndexResult = FileIndexRepository(db).fileIndex(forSharingGroupUUID: sharingGroupUUID) switch fileIndexResult { case .fileIndex(let fileIndex): guard fileIndex.count == 1 else { XCTFail("fileIndex.count: \(fileIndex.count)") return } XCTAssert(fileIndex[0].fileUUID == result.request.fileUUID) case .error(_): XCTFail() } } func testUploadJPEGFile() { guard let _ = uploadJPEGFile() else { XCTFail() return } } func testUploadURLFile() { _ = uploadFileUsingServer(mimeType: .url, file: .testUrlFile) } func testUploadTextAndJPEGFile() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } guard let _ = uploadJPEGFile(deviceUUID:deviceUUID, addUser:.no(sharingGroupUUID: sharingGroupUUID)) else { XCTFail() return } } func testUploadingSameFileTwiceWorks() { let deviceUUID = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // Second upload. guard let _ = uploadTextFile(deviceUUID: deviceUUID, fileUUID: uploadResult.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion: uploadResult.request.fileVersion, masterVersion: uploadResult.request.masterVersion, appMetaData: uploadResult.request.appMetaData) else { XCTFail() return } } func testUploadTextFileWithStringWithSpacesAppMetaData() { guard let _ = uploadTextFile(appMetaData:AppMetaData(version: 0, contents: "A Simple String")) else { XCTFail() return } } func testUploadTextFileWithJSONAppMetaData() { guard let _ = uploadTextFile(appMetaData:AppMetaData(version: 0, contents: "{ \"foo\": \"bar\" }")) else { XCTFail() return } } func testUploadWithInvalidMimeTypeFails() { let testAccount:TestAccount = .primaryOwningAccount let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID, cloudFolderName: ServerTestCase.cloudFolderName) else { XCTFail() return } let fileUUIDToSend = Foundation.UUID().uuidString let file = TestFile.test1 guard case .string(let fileContents) = file.contents, let data = fileContents.data(using: .utf8) else { XCTFail() return } let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUIDToSend uploadRequest.mimeType = "foobar" uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 0 uploadRequest.sharingGroupUUID = sharingGroupUUID uploadRequest.checkSum = file.checkSum(type: testAccount.scheme.accountName) runUploadTest(testAccount:testAccount, data:data, uploadRequest:uploadRequest, deviceUUID:deviceUUID, errorExpected: true) } func testUploadWithNoCheckSumFails() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID, cloudFolderName: ServerTestCase.cloudFolderName) else { XCTFail() return } let fileUUIDToSend = Foundation.UUID().uuidString let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUIDToSend uploadRequest.mimeType = "text/plain" uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 0 uploadRequest.sharingGroupUUID = sharingGroupUUID XCTAssert(uploadRequest.valid()) } func testUploadWithBadCheckSumFails() { let testAccount:TestAccount = .primaryOwningAccount let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID, cloudFolderName: ServerTestCase.cloudFolderName) else { XCTFail() return } let fileUUIDToSend = Foundation.UUID().uuidString let file = TestFile.test1 guard case .string(let fileContents) = file.contents, let data = fileContents.data(using: .utf8) else { XCTFail() return } let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUIDToSend uploadRequest.mimeType = "text/plain" uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 0 uploadRequest.sharingGroupUUID = sharingGroupUUID uploadRequest.checkSum = "foobar" runUploadTest(testAccount:testAccount, data:data, uploadRequest:uploadRequest, deviceUUID:deviceUUID, errorExpected: true) } func testUploadWithInvalidSharingGroupUUIDFails() { guard let _ = uploadTextFile() else { XCTFail() return } let invalidSharingGroupUUID = UUID().uuidString uploadTextFile(addUser: .no(sharingGroupUUID: invalidSharingGroupUUID), errorExpected: true) } func testUploadWithBadSharingGroupUUIDFails() { guard let _ = uploadTextFile() else { XCTFail() return } let workingButBadSharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: workingButBadSharingGroupUUID) else { XCTFail() return } uploadTextFile(addUser: .no(sharingGroupUUID: workingButBadSharingGroupUUID), errorExpected: true) } } extension FileController_UploadTests { static var allTests : [(String, (FileController_UploadTests) -> () throws -> Void)] { return [ ("testUploadTextFile", testUploadTextFile), ("testUploadJPEGFile", testUploadJPEGFile), ("testUploadURLFile", testUploadURLFile), ("testUploadTextAndJPEGFile", testUploadTextAndJPEGFile), ("testUploadingSameFileTwiceWorks", testUploadingSameFileTwiceWorks), ("testUploadTextFileWithStringWithSpacesAppMetaData", testUploadTextFileWithStringWithSpacesAppMetaData), ("testUploadTextFileWithJSONAppMetaData", testUploadTextFileWithJSONAppMetaData), ("testUploadWithInvalidMimeTypeFails", testUploadWithInvalidMimeTypeFails), ("testUploadWithInvalidSharingGroupUUIDFails", testUploadWithInvalidSharingGroupUUIDFails), ("testUploadWithBadSharingGroupUUIDFails", testUploadWithBadSharingGroupUUIDFails) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:FileController_UploadTests.self) } } <file_sep>// // GoogleCreds.swift // Server // // Created by <NAME> on 12/22/16. // // import LoggerAPI import KituraNet import Foundation import SyncServerShared // TODO: *0* Need automatic refreshing of the access token-- this should make client side testing easier: There should be no need to create a new access token every hour. // TODO: *5* It looks like if we give the user a reader-only role on a file, then they will not be able to modify it. Which will help in terms of users potentially modifying SyncServer files and messing things up. See https://developers.google.com/drive/v3/reference/permissions QUESTION: Will the user then be able to delete the file? private let folderMimeType = "application/vnd.google-apps.folder" extension GoogleCreds : CloudStorage { enum ListFilesError : Swift.Error { case badStatusCode(HTTPStatusCode?) case nilAPIResult case badJSONResult case expiredOrRevokedToken } private static let md5ChecksumKey = "md5Checksum" private func revokedOrExpiredToken(result: APICallResult?) -> Bool { if let result = result { switch result { case .dictionary(let dict): if dict["error"] as? String == self.tokenRevokedOrExpired { return true } default: break } } return false } /* If this isn't working for you, try: curl -H "Authorization: Bearer YourAccessToken" https://www.googleapis.com/drive/v3/files at the command line. */ /* For query parameter, see https://developers.google.com/drive/v3/web/search-parameters fieldsReturned parameter indicates the collection of fields to be returned in the, scoped over the entire response (not just the files resources). See https://developers.google.com/drive/v3/web/performance#partial E.g., "files/id,files/size" See also see http://stackoverflow.com/questions/35143283/google-drive-api-v3-migration */ // Not marked private for testing purposes. Don't call this directly outside of this class otherwise. func listFiles(query:String? = nil, fieldsReturned:String? = nil, completion:@escaping (_ fileListing:[String: Any]?, Swift.Error?)->()) { var urlParameters = "" if fieldsReturned != nil { urlParameters = "fields=" + fieldsReturned! } if query != nil { if urlParameters.count != 0 { urlParameters += "&" } urlParameters += "q=" + query! } var urlParams:String? = urlParameters if urlParameters.count == 0 { urlParams = nil } self.apiCall(method: "GET", path: "/drive/v3/files", urlParameters:urlParams) {[unowned self] (apiResult, statusCode, responseHeaders) in if self.revokedOrExpiredToken(result: apiResult) { completion(nil, ListFilesError.expiredOrRevokedToken) return } var error:ListFilesError? if statusCode != HTTPStatusCode.OK { error = .badStatusCode(statusCode) } guard apiResult != nil else { completion(nil, ListFilesError.nilAPIResult) return } guard case .dictionary(let dictionary) = apiResult! else { completion(nil, ListFilesError.badJSONResult) return } completion(dictionary, error) } } enum SearchError : Swift.Error { case noIdInResultingJSON case moreThanOneItemWithName case noJSONDictionaryResult case expiredOrRevokedToken } enum SearchType { case folder // If parentFolderId is nil, the root folder is assumed. case file(mimeType:String, parentFolderId:String?) case any // folders or files } struct SearchResult { let itemId:String // Google specific result-- a partial files resource for the file. // Contains fields: size, and id let dictionary:[String: Any] // Non-nil for files. let checkSum: String? } // Considers it an error for there to be more than one item with the given name. // Not marked private for testing purposes. Don't call this directly outside of this class otherwise. func searchFor(_ searchType: SearchType, itemName:String, completion:@escaping (_ result:SearchResult?, Swift.Error?)->()) { var query:String = "" switch searchType { case .folder: query = "mimeType='\(folderMimeType)' and " case .file(mimeType: let mimeType, parentFolderId: let parentFolderId): query += "mimeType='\(mimeType)' and " // See https://developers.google.com/drive/v3/web/folder var folderId = "root" if parentFolderId != nil { folderId = parentFolderId! } query += "'\(folderId)' in parents and " case .any: break } query += "name='\(itemName)' and trashed=false" // The structure of this wasn't obvious to me-- it's scoped over the entire response object, not just within the files resource. See also http://stackoverflow.com/questions/38853938/google-drive-api-v3-invalid-field-selection // And see https://developers.google.com/drive/api/v3/performance#partial let fieldsReturned = "files/id,files/\(GoogleCreds.md5ChecksumKey)" self.listFiles(query:query, fieldsReturned:fieldsReturned) { (dictionary, error) in // For the response structure, see https://developers.google.com/drive/v3/reference/files/list var result:SearchResult? var resultError:Swift.Error? = error if error != nil || dictionary == nil { if error == nil { resultError = SearchError.noJSONDictionaryResult } else { switch error! { case ListFilesError.expiredOrRevokedToken: resultError = SearchError.expiredOrRevokedToken default: break } } } else { if let filesArray = dictionary!["files"] as? [Any] { switch filesArray.count { case 0: // resultError will be nil as will result. break case 1: if let fileDict = filesArray[0] as? [String: Any], let id = fileDict["id"] as? String { // See https://developers.google.com/drive/api/v3/reference/files let checkSum = fileDict[GoogleCreds.md5ChecksumKey] as? String result = SearchResult(itemId: id, dictionary: fileDict, checkSum: checkSum) } else { resultError = SearchError.noIdInResultingJSON } default: resultError = SearchError.moreThanOneItemWithName } } } completion(result, resultError) } } enum CreateFolderError : Swift.Error { case badStatusCode(HTTPStatusCode?) case couldNotConvertJSONToString case badJSONResult case noJSONDictionaryResult case noIdInResultingJSON case nilAPIResult case expiredOrRevokedToken } // Create a folder-- assumes it doesn't yet exist. This won't fail if you use it more than once with the same folder name, you just get multiple instances of a folder with the same name. // Not marked private for testing purposes. Don't call this directly outside of this class otherwise. func createFolder(rootFolderName folderName:String, completion:@escaping (_ folderId:String?, Swift.Error?)->()) { // It's not obvious from the docs, but you use the /drive/v3/files endpoint (metadata only) for creating folders. Also not clear from the docs, you need to give the Content-Type in the headers. See https://developers.google.com/drive/v3/web/manage-uploads let additionalHeaders = [ "Content-Type": "application/json; charset=UTF-8" ] let bodyDict = [ "name" : folderName, "mimeType" : "\(folderMimeType)" ] guard let jsonString = JSONExtras.toJSONString(dict: bodyDict) else { completion(nil, CreateFolderError.couldNotConvertJSONToString) return } self.apiCall(method: "POST", path: "/drive/v3/files", additionalHeaders:additionalHeaders, body: .string(jsonString)) { (apiResult, statusCode, responseHeaders) in var resultId:String? var resultError:Swift.Error? if self.revokedOrExpiredToken(result: apiResult) { completion(nil, CreateFolderError.expiredOrRevokedToken) return } guard apiResult != nil else { completion(nil, CreateFolderError.nilAPIResult) return } guard case .dictionary(let dictionary) = apiResult! else { completion(nil, CreateFolderError.badJSONResult) return } if statusCode != HTTPStatusCode.OK { resultError = CreateFolderError.badStatusCode(statusCode) } else { if let id = dictionary["id"] as? String { resultId = id } else { resultError = CreateFolderError.noIdInResultingJSON } } completion(resultId, resultError) } } // Creates a root level folder if it doesn't exist. Returns the folderId in the completion if no error. // Not marked private for testing purposes. Don't call this directly outside of this class otherwise. // CreateFolderError.expiredOrRevokedToken or SearchError.expiredOrRevokedToken for expiry. func createFolderIfDoesNotExist(rootFolderName folderName:String, completion:@escaping (_ folderId:String?, Swift.Error?)->()) { self.searchFor(.folder, itemName: folderName) { (result, error) in if error == nil { if result == nil { // Folder doesn't exist. self.createFolder(rootFolderName: folderName) { (folderId, error) in completion(folderId, error) } } else { // Folder does exist. completion(result!.itemId, nil) } } else { completion(nil, error) } } } enum TrashFileError: Swift.Error { case couldNotConvertJSONToString } /* I've been unable to get this to work. The HTTP PATCH request is less than a year old in Kitura. Wonder if it could be having problems... It doesn't give an error, it gives the file's resource just like when in fact it does work, ie., with curl below. The following curl statement *did* do the job: curl -H "Content-Type: application/json; charset=UTF-8" -H "Authorization: Bearer <KEY>" -X PATCH -d '{"trashed":"true"}' https://www.googleapis.com/drive/v3/files/0B3xI3Shw5ptROTA2M1dfby1OVEk */ #if false // Move a file or folder to the trash on Google Drive. func trashFile(fileId:String, completion:@escaping (Swift.Error?)->()) { let bodyDict = [ "trashed": "true" ] guard let jsonString = dictionaryToJSONString(dict: bodyDict) else { completion(TrashFileError.couldNotConvertJSONToString) return } let additionalHeaders = [ "Content-Type": "application/json; charset=UTF-8", ] self.googleAPICall(method: "PATCH", path: "/drive/v3/files/\(fileId)", additionalHeaders:additionalHeaders, body: jsonString) { (json, error) in if error != nil { Log.error("\(error)") } completion(error) } } #endif enum DeleteFileError :Swift.Error { case badStatusCode(HTTPStatusCode?) case expiredOrRevokedToken } // Permanently delete a file or folder // Not marked private for testing purposes. Don't call this directly outside of this class otherwise. func deleteFile(fileId:String, completion:@escaping (Swift.Error?)->()) { // See https://developers.google.com/drive/v3/reference/files/delete let additionalHeaders = [ "Content-Type": "application/json; charset=UTF-8", ] self.apiCall(method: "DELETE", path: "/drive/v3/files/\(fileId)", additionalHeaders:additionalHeaders) { (apiResult, statusCode, responseHeaders) in if self.revokedOrExpiredToken(result: apiResult) { completion(DeleteFileError.expiredOrRevokedToken) return } // The "noContent" correct result was not apparent from the docs-- figured this out by experimentation. if statusCode == HTTPStatusCode.noContent { completion(nil) } else { completion(DeleteFileError.badStatusCode(statusCode)) } } } enum UploadError : Swift.Error { case badStatusCode(HTTPStatusCode?) case couldNotObtainCheckSum case noCloudFolderName case noOptions case missingCloudFolderNameOrMimeType case expiredOrRevokedToken } // TODO: *1* It would be good to put some retry logic in here. With a timed fallback as well. e.g., if an upload fails the first time around, retry after a period of time. OR, do this when I generalize this scheme to use other cloud storage services-- thus the retry logic could work across each scheme. // For relatively small files-- e.g., <= 5MB, where the entire upload can be retried if it fails. func uploadFile(cloudFileName:String, data:Data, options:CloudStorageFileNameOptions?, completion:@escaping (Result<String>)->()) { // See https://developers.google.com/drive/v3/web/manage-uploads guard let options = options else { completion(.failure(UploadError.noOptions)) return } let mimeType = options.mimeType guard let cloudFolderName = options.cloudFolderName else { completion(.failure(UploadError.missingCloudFolderNameOrMimeType)) return } self.createFolderIfDoesNotExist(rootFolderName: cloudFolderName) { (folderId, error) in if let error = error { switch error { case CreateFolderError.expiredOrRevokedToken, SearchError.expiredOrRevokedToken: completion(.accessTokenRevokedOrExpired) default: completion(.failure(error)) } return } let searchType = SearchType.file(mimeType: mimeType, parentFolderId: folderId) // I'm going to do this before I attempt the upload-- because I don't want to upload the same file twice. This results in google drive doing odd things with the file names. E.g., 5200B98F-8CD8-4248-B41E-4DA44087AC3C.950DBB91-B152-4D5C-B344-9BAFF49021B7 (1).0 self.searchFor(searchType, itemName: cloudFileName) { (result, error) in if error == nil { if result == nil { self.completeSmallFileUpload(folderId: folderId!, searchType:searchType, cloudFileName: cloudFileName, data: data, mimeType: mimeType, completion: completion) } else { completion(.failure(CloudStorageError.alreadyUploaded)) } } else { switch error! { case SearchError.expiredOrRevokedToken: completion(.accessTokenRevokedOrExpired) default: Log.error("Error in searchFor: \(String(describing: error))") completion(.failure(error!)) } } } } } // See https://developers.google.com/drive/api/v3/multipart-upload private func completeSmallFileUpload(folderId:String, searchType:SearchType, cloudFileName: String, data: Data, mimeType:String, completion:@escaping (Result<String>)->()) { let boundary = Foundation.UUID().uuidString let additionalHeaders = [ "Content-Type" : "multipart/related; boundary=\(boundary)" ] var urlParameters = "uploadType=multipart" urlParameters += "&fields=" + GoogleCreds.md5ChecksumKey let firstPart = "--\(boundary)\r\n" + "Content-Type: application/json; charset=UTF-8\r\n" + "\r\n" + "{\r\n" + "\"name\": \"\(cloudFileName)\",\r\n" + "\"parents\": [\r\n" + "\"\(folderId)\"\r\n" + "]\r\n" + "}\r\n" + "\r\n" + "--\(boundary)\r\n" + "Content-Type: \(mimeType)\r\n" + "\r\n" var multiPartData = firstPart.data(using: .utf8)! multiPartData.append(data) let endBoundary = "\r\n--\(boundary)--".data(using: .utf8)! multiPartData.append(endBoundary) self.apiCall(method: "POST", path: "/upload/drive/v3/files", additionalHeaders:additionalHeaders, urlParameters:urlParameters, body: .data(multiPartData)) { (json, statusCode, responseHeaders) in if self.revokedOrExpiredToken(result: json) { completion(.accessTokenRevokedOrExpired) return } if statusCode == HTTPStatusCode.OK { guard let json = json, case .dictionary(let dict) = json, let checkSum = dict[GoogleCreds.md5ChecksumKey] as? String else { completion(.failure(UploadError.couldNotObtainCheckSum)) return } completion(.success(checkSum)) } else { // Error case Log.error("Error in completeSmallFileUpload: statusCode=\(String(describing: statusCode))") completion(.failure(UploadError.badStatusCode(statusCode))) } } } enum SearchForFileError : Swift.Error { case cloudFolderDoesNotExist case cloudFileDoesNotExist(cloudFileName:String) case expiredOrRevokedToken } enum LookupFileError: Swift.Error { case noOptions case noCloudFolderName } func lookupFile(cloudFileName:String, options:CloudStorageFileNameOptions?, completion:@escaping (Result<Bool>)->()) { guard let options = options else { completion(.failure(LookupFileError.noOptions)) return } guard let cloudFolderName = options.cloudFolderName else { completion(.failure(LookupFileError.noCloudFolderName)) return } searchFor(cloudFileName: cloudFileName, inCloudFolder: cloudFolderName, fileMimeType: options.mimeType) { (cloudFileId, checkSum, error) in switch error { case .none: completion(.success(true)) case .some(SearchForFileError.cloudFileDoesNotExist): completion(.success(false)) case .some(SearchForFileError.expiredOrRevokedToken): completion(.accessTokenRevokedOrExpired) default: completion(.failure(error!)) } } } func searchFor(cloudFileName:String, inCloudFolder cloudFolderName:String, fileMimeType mimeType:String, completion:@escaping (_ cloudFileId: String?, _ checkSum: String?, Swift.Error?) -> ()) { self.searchFor(.folder, itemName: cloudFolderName) { (result, error) in if let error = error { switch error { case SearchError.expiredOrRevokedToken: completion(nil, nil, SearchForFileError.expiredOrRevokedToken) return default: break } } if result == nil { // Folder doesn't exist. Yikes! completion(nil, nil, SearchForFileError.cloudFolderDoesNotExist) } else { // Folder exists. Next need to find the id of our file within this folder. let searchType = SearchType.file(mimeType: mimeType, parentFolderId: result!.itemId) self.searchFor(searchType, itemName: cloudFileName) { (result, error) in if let error = error { switch error { case SearchError.expiredOrRevokedToken: completion(nil, nil, SearchForFileError.expiredOrRevokedToken) default: break } } if result == nil { completion(nil, nil, SearchForFileError.cloudFileDoesNotExist(cloudFileName: cloudFileName)) } else { completion(result!.itemId, result!.checkSum, nil) } } } } } enum DownloadSmallFileError : Swift.Error { case badStatusCode(HTTPStatusCode?) case nilAPIResult case noDataInAPIResult case noOptions case noCloudFolderName case fileNotFound case expiredOrRevokedToken } func downloadFile(cloudFileName:String, options:CloudStorageFileNameOptions?, completion:@escaping (DownloadResult)->()) { guard let options = options else { completion(.failure(DownloadSmallFileError.noOptions)) return } guard let cloudFolderName = options.cloudFolderName else { completion(.failure(DownloadSmallFileError.noCloudFolderName)) return } searchFor(cloudFileName: cloudFileName, inCloudFolder: cloudFolderName, fileMimeType: options.mimeType) { (cloudFileId, checkSum, error) in if error == nil { // File was found! Need to download it now. self.completeSmallFileDownload(fileId: cloudFileId!) { (data, error) in if error == nil { let downloadResult:DownloadResult = .success(data: data!, checkSum: checkSum!) completion(downloadResult) } else { switch error! { case DownloadSmallFileError.fileNotFound: completion(.fileNotFound) case DownloadSmallFileError.expiredOrRevokedToken: completion(.accessTokenRevokedOrExpired) default: completion(.failure(error!)) } } } } else { switch error! { case SearchForFileError.cloudFileDoesNotExist: completion(.fileNotFound) case SearchForFileError.expiredOrRevokedToken: completion(.accessTokenRevokedOrExpired) default: completion(.failure(error!)) } } } } // Not `private` because of some testing. func completeSmallFileDownload(fileId:String, completion:@escaping (_ data:Data?, Swift.Error?)->()) { // See https://developers.google.com/drive/v3/web/manage-downloads /* GET https://www.googleapis.com/drive/v3/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media Authorization: Bearer <ACCESS_TOKEN> */ let path = "/drive/v3/files/\(fileId)?alt=media" self.apiCall(method: "GET", path: path, expectedSuccessBody: .data, expectedFailureBody: .json) { (apiResult, statusCode, responseHeaders) in if self.revokedOrExpiredToken(result: apiResult) { completion(nil, DownloadSmallFileError.expiredOrRevokedToken) return } /* When the fileId doesn't exist, apiResult from body as JSON is: apiResult: Optional(Server.APICallResult.dictionary( ["error": ["code": 404, "errors": [ ["locationType": "parameter", "reason": "notFound", "location": "fileId", "message": "File not found: foobar.", "domain": "global" ] ], "message": "File not found: foobar."] ])) */ if statusCode == HTTPStatusCode.notFound, case .dictionary(let dict)? = apiResult, let error = dict["error"] as? [String: Any], let errors = error["errors"] as? [[String: Any]], errors.count == 1, let reason = errors[0]["reason"] as? String, reason == "notFound" { completion(nil, DownloadSmallFileError.fileNotFound) return } if statusCode != HTTPStatusCode.OK { completion(nil, DownloadSmallFileError.badStatusCode(statusCode)) return } guard apiResult != nil else { completion(nil, DownloadSmallFileError.nilAPIResult) return } guard case .data(let data) = apiResult! else { completion(nil, DownloadSmallFileError.noDataInAPIResult) return } completion(data, nil) } } enum DeletionError : Swift.Error { case noOptions case noCloudFolderName } func deleteFile(cloudFileName:String, options:CloudStorageFileNameOptions?, completion:@escaping (Result<()>)->()) { guard let options = options else { completion(.failure(DeletionError.noOptions)) return } guard let cloudFolderName = options.cloudFolderName else { completion(.failure(DeletionError.noCloudFolderName)) return } searchFor(cloudFileName: cloudFileName, inCloudFolder: cloudFolderName, fileMimeType: options.mimeType) { (cloudFileId, checkSum, error) in if error == nil { // File was found! Need to delete it now. self.deleteFile(fileId: cloudFileId!) { error in if error == nil { completion(.success(())) } else { switch error! { case DeleteFileError.expiredOrRevokedToken: completion(.accessTokenRevokedOrExpired) default: completion(.failure(error!)) } } } } else { switch error! { case SearchForFileError.expiredOrRevokedToken: completion(.accessTokenRevokedOrExpired) default: completion(.failure(error!)) } } } } } <file_sep># Make the server runtime-image Dockerfile, e.g., see https://developer.ibm.com/swift/2017/02/14/new-runtime-docker-image-for-swift-applications/#comment-2962 # Create a runtime image using the new Dockerfile by executing the following command in SyncServerII/devops/Docker/Runtime folder: docker build -t swift-ubuntu-runtime:latest . # Push that image to Docker hub-- Currently I'm using a public Docker hub repo-- so am *not* exposing anything private in that image. docker login # Tag the image # See also https://stackoverflow.com/questions/41984399/denied-requested-access-to-the-resource-is-denied-docker docker tag swift-ubuntu-runtime:latest crspybits/swift-ubuntu-runtime:latest docker tag swift-ubuntu-runtime:latest crspybits/swift-ubuntu-runtime:5.0.1 docker push crspybits/swift-ubuntu-runtime:latest docker push crspybits/swift-ubuntu-runtime:5.0.1 Run this with: docker run -p 8080:8080 --rm -i -t -v /Users/chris/Desktop/Apps/:/root/extras crspybits/swift-ubuntu-runtime:latest # Run a container # Assumes AWS Elastic Beanstalk configuration files (.ebextensions) have been used to copy Server.json into the directory: /home/ubuntu on the ec2 instance Get into the running container: docker exec -it <mycontainer> bash <mycontainer> is the container id. Show stopped containers: docker ps --filter "status=exited" docker ps -a (these don't show up with docker ps). <file_sep>// // FileMicrosoftTests.swift // ServerTests // // Created by <NAME> on 9/13/19. // import XCTest @testable import Server import Foundation import LoggerAPI import HeliumLogger import SyncServerShared class FileMicrosoftOneDriveTests: ServerTestCase, LinuxTestable { // In my OneDrive: let knownPresentFile = "DO-NOT-REMOVE.txt" let knownAbsentFile = "Markwa.Farkwa.Blarkwa" override func setUp() { super.setUp() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testCheckForFileFailsWithFileThatDoesNotExist() { let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft1.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh() { error in guard error == nil else { XCTFail() exp.fulfill() return } creds.checkForFile(fileName: self.knownAbsentFile) { result in switch result { case .success(.fileNotFound): break case .success(.fileFound): XCTFail() case .failure: XCTFail() case .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } } waitForExpectations(timeout: 10, handler: nil) } func testCheckForFileFailsWithExpiredAccessToken() { let creds = MicrosoftCreds()! creds.accessToken = TestAccount.microsoft1ExpiredAccessToken.secondToken() let existingFile = self.knownPresentFile let exp = expectation(description: "\(#function)\(#line)") creds.checkForFile(fileName: existingFile) { result in switch result { case .success(.fileFound): XCTFail() case .success((.fileNotFound)): XCTFail() case .failure: XCTFail() case .accessTokenRevokedOrExpired: break } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testCheckForFileWorksWithExistingFile() { let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft1.token() //let existingFile = "539C70F7-8144-49F1-81C7-003DD5D8833B.14B026F1-6E5F-43E6-A54B-0524BB8F3E9C.0.txt" let existingFile = self.knownPresentFile let exp = expectation(description: "\(#function)\(#line)") creds.refresh() { error in guard error == nil else { XCTFail() exp.fulfill() return } creds.checkForFile(fileName: existingFile) { result in switch result { case .success(.fileFound): break case .success((.fileNotFound)): XCTFail() case .failure, .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } } waitForExpectations(timeout: 10, handler: nil) } func uploadFile(file: TestFile) { let ext = Extension.forMimeType(mimeType: file.mimeType.rawValue) let fileName = Foundation.UUID().uuidString + ".\(ext)" let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft2.token() let exp = expectation(description: "\(#function)\(#line)") creds.refresh() { error in guard error == nil else { XCTFail() exp.fulfill() return } let fileContentsData: Data! switch file.contents { case .string(let fileContents): fileContentsData = fileContents.data(using: .ascii)! case .url(let url): fileContentsData = try? Data(contentsOf: url) } guard fileContentsData != nil else { XCTFail() return } creds.uploadFile(withName: fileName, mimeType: file.mimeType, data: fileContentsData) { result in switch result { case .success(let hash): XCTAssert(hash == file.sha1Hash) case .failure(let error): Log.error("uploadFile: \(error)") XCTFail() case .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } } waitForExpectations(timeout: 10, handler: nil) } func testSimpleUploadWithExpiredAccessToken() { let file = TestFile.test1 let ext = Extension.forMimeType(mimeType: file.mimeType.rawValue) let fileName = Foundation.UUID().uuidString + ".\(ext)" let creds = MicrosoftCreds()! creds.accessToken = TestAccount.microsoft1ExpiredAccessToken.secondToken() let exp = expectation(description: "\(#function)\(#line)") let fileContentsData: Data switch file.contents { case .string(let fileContents): fileContentsData = fileContents.data(using: .ascii)! case .url(let url): fileContentsData = try! Data(contentsOf: url) } creds.uploadFile(withName: fileName, mimeType: file.mimeType, data: fileContentsData) { result in switch result { case .success: XCTFail() case .failure: XCTFail() case .accessTokenRevokedOrExpired: break } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testUploadTextFileWorks() { uploadFile(file: .test1) } func testUploadImageFileWorks() { uploadFile(file: .catJpg) } func testUploadURLFileWorks() { uploadFile(file: .testUrlFile) } /* For Microsoft: What we need here is to-- 1) For a different account, say .microsoft2, 2) generate an access token from a refresh token 3) then revoke access from the account for the app 4) use the access token below However, will the test fail because of the revocation or just because of expiry of the access token? */ // func testUploadWithRevokedToken() { // } func testUploadWithExpiredToken() { let deviceUUID = Foundation.UUID().uuidString let fileUUID = Foundation.UUID().uuidString let creds = MicrosoftCreds()! creds.accessToken = TestAccount.microsoft1ExpiredAccessToken.secondToken() let file = TestFile.test1 let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUID uploadRequest.mimeType = file.mimeType.rawValue uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = UUID().uuidString uploadRequest.checkSum = file.sha1Hash let options = CloudStorageFileNameOptions(cloudFolderName: nil, mimeType: file.mimeType.rawValue) self.uploadFile(accountType: AccountScheme.microsoft.accountName, creds: creds, deviceUUID:deviceUUID, testFile: file, uploadRequest:uploadRequest, options: options, failureExpected: true, expectAccessTokenRevokedOrExpired: true) } func fullUpload(file: TestFile) { let deviceUUID = Foundation.UUID().uuidString let fileUUID = Foundation.UUID().uuidString let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft1.token() refresh(creds: creds) { success in guard success else { XCTFail() return } let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUID uploadRequest.mimeType = file.mimeType.rawValue uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = UUID().uuidString uploadRequest.checkSum = file.sha1Hash let options = CloudStorageFileNameOptions(cloudFolderName: nil, mimeType: file.mimeType.rawValue) self.uploadFile(accountType: AccountScheme.microsoft.accountName, creds: creds, deviceUUID:deviceUUID, testFile: file, uploadRequest:uploadRequest, options: options) // The second time we try it, it should fail with CloudStorageError.alreadyUploaded -- same file. self.uploadFile(accountType: AccountScheme.microsoft.accountName, creds: creds, deviceUUID:deviceUUID, testFile: file, uploadRequest:uploadRequest,options: options, failureExpected: true, errorExpected: CloudStorageError.alreadyUploaded) } } func refresh(creds: MicrosoftCreds, completion:@escaping (Bool)->()) { let exp = expectation(description: "full upload") creds.refresh() { error in guard error == nil else { XCTFail() exp.fulfill() completion(false) return } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) completion(true) } func testFullUploadWorks() { fullUpload(file: .test1) } func testFullImageUploadWorks() { fullUpload(file: .catJpg) } func testFullUploadURLWorks() { fullUpload(file: .testUrlFile) } func downloadFile(creds: MicrosoftCreds, cloudFileName: String, expectedStringFile:TestFile? = nil, expectedFailure: Bool = false, expectedFileNotFound: Bool = false, expectedRevokedToken: Bool = false) { let exp = expectation(description: "\(#function)\(#line)") creds.downloadFile(cloudFileName: cloudFileName, options: nil) { result in switch result { case .success(let downloadResult): if let expectedStringFile = expectedStringFile { guard case .string(let expectedContents) = expectedStringFile.contents else { XCTFail() return } guard let str = String(data: downloadResult.data, encoding: String.Encoding.ascii) else { XCTFail() Log.error("Failed on string decoding") return } XCTAssert(downloadResult.checkSum == expectedStringFile.sha1Hash) XCTAssert(str == expectedContents) } if expectedFailure || expectedRevokedToken || expectedFileNotFound { XCTFail() } case .failure(let error): if !expectedFailure || expectedRevokedToken || expectedFileNotFound { XCTFail() Log.error("Failed download: \(error)") } case .accessTokenRevokedOrExpired: if !expectedRevokedToken || expectedFileNotFound || expectedFailure { XCTFail() } case .fileNotFound: if !expectedFileNotFound || expectedRevokedToken || expectedFailure{ XCTFail() } } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testDownloadOfNonExistingFileFails() { let creds = MicrosoftCreds()! creds.refreshToken = <EMAIL>Account.microsoft1.token() refresh(creds: creds) { success in guard success else { XCTFail() return } self.downloadFile(creds: creds, cloudFileName: self.knownAbsentFile, expectedFileNotFound: true) } } // Download without checksum. func testSimpleDownloadWorks() { let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft1.token() refresh(creds: creds) { success in guard success else { XCTFail() return } let exp = self.expectation(description: "download") creds.downloadFile(cloudFileName: self.knownPresentFile) { result in switch result { case .success: break case .failure: XCTFail() case .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } self.waitExpectation(timeout: 10, handler: nil) } } // Reason code 80049228 func testSimpleDownloadWithExpiredAccessTokenFails() { let creds = MicrosoftCreds()! creds.accessToken = TestAccount.microsoft1ExpiredAccessToken.secondToken() let exp = self.expectation(description: "download") creds.downloadFile(cloudFileName: self.knownPresentFile) { result in switch result { case .success: XCTFail() case .failure: XCTFail() case .accessTokenRevokedOrExpired: break } exp.fulfill() } self.waitExpectation(timeout: 10, handler: nil) } // From my testing it looks like if you (a) generate an access token from a refresh token, and (b) then revoke access for the account, then the access token still works-- until it expires. The test below fails with .failure, not with .accessTokenRevokedOrExpired. #if false func testSimpleDownloadWithRevokedAccessTokenFails() { let creds = MicrosoftCreds() creds.accessToken = TestAccount.microsoft2RevokedAccessToken.secondToken() let exp = self.expectation(description: "download") creds.downloadFile(cloudFileName: self.knownPresentFile) { result in switch result { case .success: XCTFail() case .failure: XCTFail() case .accessTokenRevokedOrExpired: break } exp.fulfill() } self.waitExpectation(timeout: 10, handler: nil) } #endif // See above for revoked token test conditions // func testDownloadWithRevokedToken() { // } func testUploadAndDownloadWorks() { let deviceUUID = Foundation.UUID().uuidString let fileUUID = Foundation.UUID().uuidString let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft1.token() let file = TestFile.test1 guard case .string = file.contents else { XCTFail() return } let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUID uploadRequest.mimeType = file.mimeType.rawValue uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = UUID().uuidString uploadRequest.checkSum = file.sha1Hash let options = CloudStorageFileNameOptions(cloudFolderName: nil, mimeType: file.mimeType.rawValue) refresh(creds: creds) { success in guard success else { XCTFail() return } guard let _ = self.uploadFile(accountType: AccountScheme.microsoft.accountName, creds: creds, deviceUUID:deviceUUID, testFile: file, uploadRequest:uploadRequest, options: options) else { XCTFail() return } let cloudFileName = uploadRequest.cloudFileName(deviceUUID:deviceUUID, mimeType: uploadRequest.mimeType) Log.debug("cloudFileName: \(cloudFileName)") self.downloadFile(creds: creds, cloudFileName: cloudFileName, expectedStringFile: file) } } // Doesn't refresh the creds first. func deleteFile(creds: MicrosoftCreds, cloudFileName: String, expectedFailure: Bool = false) { let exp = expectation(description: "\(#function)\(#line)") creds.deleteFile(cloudFileName: cloudFileName) { result in switch result { case .success: if expectedFailure { XCTFail() } case .accessTokenRevokedOrExpired: XCTFail() case .failure(let error): if !expectedFailure { XCTFail() Log.error("Failed download: \(error)") } } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } // See above for comments on revoked token //func testDeletionWithRevokedAccessToken() { //} func testDeletionOfNonExistingFileFails() { let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft1.token() refresh(creds: creds) { success in guard success else { XCTFail() return } self.deleteFile(creds: creds, cloudFileName: self.knownAbsentFile, expectedFailure: true) } } func deletionOfExistingFile(file: TestFile) { let deviceUUID = Foundation.UUID().uuidString let fileUUID = Foundation.UUID().uuidString let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft1.token() let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUID uploadRequest.mimeType = file.mimeType.rawValue uploadRequest.fileVersion = 0 uploadRequest.masterVersion = 1 uploadRequest.sharingGroupUUID = UUID().uuidString uploadRequest.checkSum = file.sha1Hash let options = CloudStorageFileNameOptions(cloudFolderName: nil, mimeType: file.mimeType.rawValue) refresh(creds: creds) { success in guard success else { XCTFail() return } guard let fileName = self.uploadFile(accountType: AccountScheme.microsoft.accountName, creds: creds, deviceUUID:deviceUUID, testFile:file, uploadRequest:uploadRequest, options: options) else { XCTFail() return } self.deleteFile(creds: creds, cloudFileName: fileName) } } func testSimpleDeletionWithExpiredAccessTokenFails() { // First need to get item id of the file in the normal way so it doesn't fail. let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft1.token() refresh(creds: creds) { success in guard success else { XCTFail() return } let exp = self.expectation(description: "delete") creds.checkForFile(fileName: self.knownPresentFile) { result in switch result { case .success(.fileFound(let checkResult)): self.deleteExpectingExpiredAccessToken(itemId: checkResult.id, expectation: exp) case .success(.fileNotFound): XCTFail() exp.fulfill() case .accessTokenRevokedOrExpired, .failure: XCTFail() exp.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } } func deleteExpectingExpiredAccessToken(itemId: String, expectation: XCTestExpectation) { let creds = MicrosoftCreds()! creds.accessToken = TestAccount.microsoft1ExpiredAccessToken.secondToken() creds.deleteFile(itemId: itemId) { result in switch result { case .success: XCTFail() case .failure: XCTFail() case .accessTokenRevokedOrExpired: break } expectation.fulfill() } } func testDeletionOfExistingFileWorks() { deletionOfExistingFile(file: .test1) } func testDeletionOfExistingURLFileWorks() { deletionOfExistingFile(file: .testUrlFile) } func lookupFile(cloudFileName: String, expectError:Bool = false) { let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft1.token() refresh(creds: creds) { success in guard success else { XCTFail() return } let exp = self.expectation(description: "\(#function)\(#line)") creds.lookupFile(cloudFileName:cloudFileName, options: nil) { result in switch result { case .success: if expectError { XCTFail() } case .failure, .accessTokenRevokedOrExpired: if !expectError { XCTFail() } } exp.fulfill() } self.waitForExpectations(timeout: 10, handler: nil) } } func testLookupFileThatExists() { lookupFile(cloudFileName: knownPresentFile) } func testLookupFileThatDoesNotExist() { lookupFile(cloudFileName: knownAbsentFile) } // See comments for revoked access token // func testLookupWithRevokedAccessToken() { // } // MARK: Large file upload func testCreateUploadSession() { let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft1.token() let fileName = UUID().uuidString refresh(creds: creds) { success in guard success else { XCTFail() return } let exp = self.expectation(description: "uploadSession") creds.createUploadSession(cloudFileName: fileName) { result in switch result { case .success: break case .failure, .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } self.waitExpectation(timeout: 10, handler: nil) } } func testUploadStateComputedValues() { let inputData: [(numberBytes: UInt, blockSize: UInt, expectedNumberFullBlocks: UInt, expectedPartialLastBlock: Bool, expectedPartialLastBlockLength: Int)] = [ (numberBytes: 99, blockSize: 100, expectedNumberFullBlocks: 0, expectedPartialLastBlock: true, expectedPartialLastBlockLength: 99), (numberBytes: 100, blockSize: 100, expectedNumberFullBlocks: 1, expectedPartialLastBlock: false, expectedPartialLastBlockLength: 0), (numberBytes: 100, blockSize: 50, expectedNumberFullBlocks: 2, expectedPartialLastBlock: false, expectedPartialLastBlockLength: 0), (numberBytes: 101, blockSize: 50, expectedNumberFullBlocks: 2, expectedPartialLastBlock: true, expectedPartialLastBlockLength: 1), ] for (numberBytes, blockSize, expectedNumberFullBlocks, expectedPartialLastBlock, expectedPartialLastBlockLength) in inputData { let data = Data(count: Int(numberBytes)) guard let state = MicrosoftCreds.UploadState(blockSize: blockSize, data: data, checkBlockSize: false) else { XCTFail() return } XCTAssert(state.numberFullBlocks == expectedNumberFullBlocks) XCTAssert(state.partialLastBlock == expectedPartialLastBlock) XCTAssert(state.partialLastBlockLength == expectedPartialLastBlockLength) } } func testUploadStateOffsetsOnePartialBlock() { guard let state = MicrosoftCreds.UploadState(blockSize: 100, data: Data(count: Int(99)), checkBlockSize: false) else { XCTFail() return } XCTAssert(state.currentStartOffset == 0) XCTAssert(state.currentEndOffset == 99) XCTAssert(!state.advanceToNextBlock()) } func testUploadStateOffsetsOneFullOnePartialBlock() { guard let state = MicrosoftCreds.UploadState(blockSize: 100, data: Data(count: Int(199)), checkBlockSize: false) else { XCTFail() return } XCTAssert(state.currentStartOffset == 0) XCTAssert(state.currentEndOffset == 100) XCTAssert(state.advanceToNextBlock()) XCTAssert(state.currentStartOffset == 100) XCTAssert(state.currentEndOffset == 199) XCTAssert(!state.advanceToNextBlock()) } func testUploadStateOffsetsOneFullOnePartialBlock2() { guard let state = MicrosoftCreds.UploadState(blockSize: 100, data: Data(count: Int(101)), checkBlockSize: false) else { XCTFail() return } XCTAssert(state.currentStartOffset == 0) XCTAssert(state.currentEndOffset == 100) XCTAssert(state.advanceToNextBlock()) XCTAssert(state.currentStartOffset == 100) XCTAssert(state.currentEndOffset == 101) XCTAssert(!state.advanceToNextBlock()) } func testUploadStateOffsetsExactlyTwoBlocks() { guard let state = MicrosoftCreds.UploadState(blockSize: 100, data: Data(count: Int(200)), checkBlockSize: false) else { XCTFail() return } XCTAssert(state.currentStartOffset == 0) XCTAssert(state.currentEndOffset == 100) XCTAssert(state.advanceToNextBlock()) XCTAssert(state.currentStartOffset == 100) XCTAssert(state.currentEndOffset == 200) XCTAssert(!state.advanceToNextBlock()) } func testUploadStateOffsetsTwoBlocksAndOnePartial() { guard let state = MicrosoftCreds.UploadState(blockSize: 100, data: Data(count: Int(250)), checkBlockSize: false) else { XCTFail() return } XCTAssert(state.currentStartOffset == 0) XCTAssert(state.currentEndOffset == 100) XCTAssert(state.contentRange == "bytes 0-99/250") XCTAssert(state.advanceToNextBlock()) XCTAssert(state.currentStartOffset == 100) XCTAssert(state.currentEndOffset == 200) XCTAssert(state.advanceToNextBlock()) XCTAssert(state.currentStartOffset == 200) XCTAssert(state.currentEndOffset == 250) XCTAssert(!state.advanceToNextBlock()) } func testCreateUploadSessionWithExpiredToken() { let creds = MicrosoftCreds()! creds.accessToken = TestAccount.microsoft1ExpiredAccessToken.secondToken() let fileName = UUID().uuidString let exp = self.expectation(description: "uploadSession") creds.createUploadSession(cloudFileName: fileName) { result in switch result { case .success, .failure: XCTFail() case .accessTokenRevokedOrExpired: break } exp.fulfill() } self.waitExpectation(timeout: 10, handler: nil) } func testUploadWithAPartialBlock() { let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft2.token() let fileName = UUID().uuidString refresh(creds: creds) { success in guard success else { XCTFail() return } let exp = self.expectation(description: "uploadSession") creds.createUploadSession(cloudFileName: fileName) { result in switch result { case .success(let session): let blockSize = MicrosoftCreds.UploadState.blockMultipleInBytes guard let state = MicrosoftCreds.UploadState(blockSize: UInt(blockSize), data: Data(count: blockSize/2)) else { XCTFail() exp.fulfill() return } creds.uploadBytes(toUploadSession: session, withUploadState: state) { result in switch result { case .success: break case .failure, .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } case .failure, .accessTokenRevokedOrExpired: XCTFail() exp.fulfill() } } self.waitExpectation(timeout: 10, handler: nil) } } func testUploadWithSingleBlock() { let creds = MicrosoftCreds()! creds.refreshToken = Test<EMAIL>.microsoft2.token() let fileName = UUID().uuidString refresh(creds: creds) { success in guard success else { XCTFail() return } let exp = self.expectation(description: "uploadSession") creds.createUploadSession(cloudFileName: fileName) { result in switch result { case .success(let session): let blockSize = MicrosoftCreds.UploadState.blockMultipleInBytes guard let state = MicrosoftCreds.UploadState(blockSize: UInt(blockSize), data: Data(count: blockSize)) else { XCTFail() exp.fulfill() return } creds.uploadBytes(toUploadSession: session, withUploadState: state) { result in switch result { case .success: break case .failure, .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } case .failure, .accessTokenRevokedOrExpired: XCTFail() exp.fulfill() } } self.waitExpectation(timeout: 10, handler: nil) } } func testUploadWithTwoBlocks() { let creds = MicrosoftCreds()! creds.refreshToken = Test<EMAIL>.microsoft1.token() let fileName = UUID().uuidString refresh(creds: creds) { success in guard success else { XCTFail() return } let exp = self.expectation(description: "uploadSession") creds.createUploadSession(cloudFileName: fileName) { result in switch result { case .success(let session): let blockSize = MicrosoftCreds.UploadState.blockMultipleInBytes guard let state = MicrosoftCreds.UploadState(blockSize: UInt(blockSize), data: Data(count: blockSize*2)) else { XCTFail() exp.fulfill() return } creds.uploadBytes(toUploadSession: session, withUploadState: state) { result in switch result { case .success: break case .failure, .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } case .failure, .accessTokenRevokedOrExpired: XCTFail() exp.fulfill() } } self.waitExpectation(timeout: 10, handler: nil) } } func testUploadWithTwoBlocksAndAPartial() { let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft1.token() let fileName = UUID().uuidString refresh(creds: creds) { success in guard success else { XCTFail() return } let exp = self.expectation(description: "uploadSession") creds.createUploadSession(cloudFileName: fileName) { result in switch result { case .success(let session): let blockSize = MicrosoftCreds.UploadState.blockMultipleInBytes guard let state = MicrosoftCreds.UploadState(blockSize: UInt(blockSize), data: Data(count: blockSize*2 + 100)) else { XCTFail() exp.fulfill() return } creds.uploadBytes(toUploadSession: session, withUploadState: state) { result in switch result { case .success: break case .failure, .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } case .failure, .accessTokenRevokedOrExpired: exp.fulfill() } } self.waitExpectation(timeout: 10, handler: nil) } } func testUploadImageUsingSessionMethod() { let creds = MicrosoftCreds()! creds.refreshToken = Test<EMAIL>.microsoft2.token() let file = TestFile.catJpg let ext = Extension.forMimeType(mimeType: file.mimeType.rawValue) let fileName = Foundation.UUID().uuidString + ".\(ext)" guard case .url(let url) = file.contents, let fileContentsData = try? Data(contentsOf: url) else { XCTFail() return } refresh(creds: creds) { success in guard success else { XCTFail() return } let exp = self.expectation(description: "uploadSession") creds.uploadFileUsingSession(withName: fileName, mimeType: file.mimeType, data: fileContentsData) { result in switch result { case .success(let checkSum): XCTAssert(file.sha1Hash == checkSum) case .failure: XCTFail() case .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } self.waitExpectation(timeout: 10, handler: nil) } } func testCreateAppFolder() { let creds = MicrosoftCreds()! creds.refreshToken = TestAccount.microsoft2.token() refresh(creds: creds) { success in guard success else { XCTFail() return } let exp = self.expectation(description: "uploadSession") creds.createAppFolder() { result in switch result { case .success: break case .failure, .accessTokenRevokedOrExpired: XCTFail() } exp.fulfill() } self.waitExpectation(timeout: 10, handler: nil) } } } extension FileMicrosoftOneDriveTests { static var allTests : [(String, (FileMicrosoftOneDriveTests) -> () throws -> Void)] { return [ ("testCheckForFileFailsWithFileThatDoesNotExist", testCheckForFileFailsWithFileThatDoesNotExist), ("testCheckForFileWorksWithExistingFile", testCheckForFileWorksWithExistingFile), ("testUploadTextFileWorks", testUploadTextFileWorks), ("testUploadImageFileWorks", testUploadImageFileWorks), ("testUploadURLFileWorks", testUploadURLFileWorks), ("testFullUploadWorks", testFullUploadWorks), ("testFullImageUploadWorks", testFullImageUploadWorks), ("testFullUploadURLWorks", testFullUploadURLWorks), ("testDownloadOfNonExistingFileFails", testDownloadOfNonExistingFileFails), ("testSimpleDownloadWorks", testSimpleDownloadWorks), ("testUploadAndDownloadWorks", testUploadAndDownloadWorks), ("testDeletionOfNonExistingFileFails", testDeletionOfNonExistingFileFails), ("testDeletionOfExistingFileWorks", testDeletionOfExistingFileWorks), ("testDeletionOfExistingURLFileWorks", testDeletionOfExistingURLFileWorks), ("testLookupFileThatDoesNotExist", testLookupFileThatDoesNotExist), ("testLookupFileThatExists", testLookupFileThatExists), ("testUploadWithExpiredToken", testUploadWithExpiredToken), ("testCheckForFileFailsWithExpiredAccessToken", testCheckForFileFailsWithExpiredAccessToken), ("testSimpleDownloadWithExpiredAccessTokenFails", testSimpleDownloadWithExpiredAccessTokenFails), ("testSimpleDeletionWithExpiredAccessTokenFails", testSimpleDeletionWithExpiredAccessTokenFails), ("testSimpleUploadWithExpiredAccessToken", testSimpleUploadWithExpiredAccessToken), ("testCreateUploadSession", testCreateUploadSession), ("testUploadStateComputedValues", testUploadStateComputedValues), ("testUploadStateOffsetsOnePartialBlock", testUploadStateOffsetsOnePartialBlock), ("testUploadStateOffsetsOneFullOnePartialBlock", testUploadStateOffsetsOneFullOnePartialBlock), ("testUploadStateOffsetsOneFullOnePartialBlock2", testUploadStateOffsetsOneFullOnePartialBlock2), ("testUploadStateOffsetsExactlyTwoBlocks", testUploadStateOffsetsExactlyTwoBlocks), ("testUploadStateOffsetsTwoBlocksAndOnePartial", testUploadStateOffsetsTwoBlocksAndOnePartial), ("testCreateUploadSessionWithExpiredToken", testCreateUploadSessionWithExpiredToken), ("testUploadWithAPartialBlock", testUploadWithAPartialBlock), ("testUploadWithSingleBlock", testUploadWithSingleBlock), ("testUploadWithTwoBlocks", testUploadWithTwoBlocks), ("testUploadWithTwoBlocksAndAPartial", testUploadWithTwoBlocksAndAPartial), ("testUploadImageUsingSessionMethod", testUploadImageUsingSessionMethod), ("testCreateAppFolder", testCreateAppFolder) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:FileMicrosoftOneDriveTests.self) } } <file_sep>#!/bin/bash user="" host="" # user="root" # host="localhost" dbname="SyncServer_SharedImages" sqlScript="6.sql" echo "Migrating $dbname on $host" result=$(mysql -P 3306 -p --user="$user" --host="$host" --database="$dbname" < "$sqlScript" 2>&1 ) # I've embedded "ERROR999" to be output from the sql script -- when an error and subsequent rollback occurs. ERROR=`echo $result | grep ERROR999` if [ "empty$ERROR" = "empty" ]; then echo "Success running migration" else echo "**** Failure running migration *******" echo $result fi <file_sep>// // FacebookCreds.swift // Server // // Created by <NAME> on 7/16/17. // import Foundation import SyncServerShared import Credentials import Kitura import LoggerAPI import KituraNet class FacebookCreds : AccountAPICall, Account { var accessToken: String! static var accountScheme:AccountScheme { return .facebook } var accountScheme:AccountScheme { return FacebookCreds.accountScheme } var owningAccountsNeedCloudFolderName: Bool { return false } weak var delegate:AccountDelegate? var accountCreationUser:AccountCreationUser? override init?() { super.init() baseURL = "graph.facebook.com" } // There is no need to put any tokens into the database for Facebook. We don't need to access Facebook creds when the mobile user is offline, and this would just make an extra security issue. func toJSON() -> String? { let jsonDict = [String:String]() return JSONExtras.toJSONString(dict: jsonDict) } // We're using token generation with Facebook to exchange a short-lived access token for a long-lived one. See https://developers.facebook.com/docs/facebook-login/access-tokens/expiration-and-extension and https://stackoverflow.com/questions/37674620/do-facebook-has-a-refresh-token-of-oauth/37683233 func needToGenerateTokens(dbCreds:Account? = nil) -> Bool { // 11/5/17; See SharingAccountsController.swift comment with the same date for the reason for this conditional compilation. When running the server XCTest cases, make sure to turn on this flag. #if DEVTESTING return false #else return true #endif } enum GenerateTokensError : Swift.Error { case non200ErrorCode(Int?) case didNotReceiveJSON case noAccessTokenInResult case noAppIdOrSecret } func generateTokens(response: RouterResponse?, completion:@escaping (Swift.Error?)->()) { guard let fbAppId = Configuration.server.FacebookClientId, let fbAppSecret = Configuration.server.FacebookClientSecret else { completion(GenerateTokensError.noAppIdOrSecret) return } let urlParameters = "grant_type=fb_exchange_token&client_id=\(fbAppId)&client_secret=\(fbAppSecret)&fb_exchange_token=\(accessToken!)" Log.debug("urlParameters: \(urlParameters)") /* GET /oauth/access_token? grant_type=fb_exchange_token&amp; client_id={app-id}&amp; client_secret={app-secret}&amp; fb_exchange_token={short-lived-token} */ apiCall(method: "GET", path: "/oauth/access_token", urlParameters: urlParameters) { apiCallResult, httpStatus, responseHeaders in if httpStatus == HTTPStatusCode.OK { switch apiCallResult { case .some(.dictionary(let dictionary)): guard let accessToken = dictionary["access_token"] as? String else { completion(GenerateTokensError.noAccessTokenInResult) return } response?.headers[ServerConstants.httpResponseOAuth2AccessTokenKey] = accessToken completion(nil) default: completion(GenerateTokensError.didNotReceiveJSON) } } else { Log.debug("apiCallResult: \(String(describing: apiCallResult))") completion(GenerateTokensError.non200ErrorCode(httpStatus.map { $0.rawValue })) } } } func merge(withNewer account:Account) { } static func getProperties(fromRequest request:RouterRequest) -> [String: Any] { if let accessToken = request.headers[ServerConstants.HTTPOAuth2AccessTokenKey] { return [ServerConstants.HTTPOAuth2AccessTokenKey: accessToken] } else { return [:] } } static func fromProperties(_ properties: AccountManager.AccountProperties, user:AccountCreationUser?, delegate:AccountDelegate?) -> Account? { guard let creds = FacebookCreds() else { return nil } creds.accountCreationUser = user creds.delegate = delegate creds.accessToken = properties.properties[ServerConstants.HTTPOAuth2AccessTokenKey] as? String return creds } static func fromJSON(_ json:String, user:AccountCreationUser, delegate:AccountDelegate?) throws -> Account? { guard let creds = FacebookCreds() else { return nil } creds.accountCreationUser = user creds.delegate = delegate return creds } } <file_sep>// // FileController+UploadFile.swift // Server // // Created by <NAME> on 3/22/17. // // import Foundation import LoggerAPI import SyncServerShared import Kitura extension FileController { private struct Cleanup { let cloudFileName: String let options: CloudStorageFileNameOptions let ownerCloudStorage: CloudStorage } private enum Info { case success(response:UploadFileResponse) case errorMessage(String) case errorResponse(RequestProcessingParameters.Response) case errorCleanup(message: String, cleanup: Cleanup) } private func finish(_ info: Info, params:RequestProcessingParameters) { switch info { case .errorResponse(let response): params.completion(response) case .errorMessage(let message): Log.error(message) params.completion(.failure(.message(message))) case .errorCleanup(message: let message, cleanup: let cleanup): cleanup.ownerCloudStorage.deleteFile(cloudFileName: cleanup.cloudFileName, options: cleanup.options, completion: {_ in Log.error(message) params.completion(.failure(.message(message))) }) case .success(response: let response): params.completion(.success(response)) } } func uploadFile(params:RequestProcessingParameters) { guard let uploadRequest = params.request as? UploadFileRequest else { let message = "Did not receive UploadFileRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard sharingGroupSecurityCheck(sharingGroupUUID: uploadRequest.sharingGroupUUID, params: params) else { finish(.errorMessage("Failed in sharing group security check."), params: params) return } guard let _ = MimeType(rawValue: uploadRequest.mimeType) else { let message = "Unknown mime type passed: \(String(describing: uploadRequest.mimeType)) (see SyncServer-Shared)" finish(.errorMessage(message), params: params) return } guard uploadRequest.fileVersion != nil else { let message = "File version not given in upload request." finish(.errorMessage(message), params: params) return } Log.debug("uploadRequest.sharingGroupUUID: \(String(describing: uploadRequest.sharingGroupUUID))") Controllers.getMasterVersion(sharingGroupUUID: uploadRequest.sharingGroupUUID, params: params) { error, masterVersion in if error != nil { let message = "Error: \(String(describing: error))" finish(.errorMessage(message), params: params) return } if masterVersion != uploadRequest.masterVersion { let response = UploadFileResponse() Log.warning("Master version update: \(String(describing: masterVersion))") response.masterVersionUpdate = masterVersion finish(.success(response: response), params: params) return } // Check to see if (a) this file is already present in the FileIndex, and if so then (b) is the version being uploaded +1 from that in the FileIndex. var existingFileInFileIndex:FileIndex? do { existingFileInFileIndex = try FileController.checkForExistingFile(params:params, sharingGroupUUID: uploadRequest.sharingGroupUUID, fileUUID:uploadRequest.fileUUID) } catch (let error) { let message = "Could not lookup file in FileIndex: \(error)" finish(.errorMessage(message), params: params) return } guard UploadRepository.isValidAppMetaDataUpload( currServerAppMetaDataVersion: existingFileInFileIndex?.appMetaDataVersion, currServerAppMetaData: existingFileInFileIndex?.appMetaData, optionalUpload:uploadRequest.appMetaData) else { let message = "App meta data or version is not valid for upload." finish(.errorMessage(message), params: params) return } // To send back to client. var creationDate:Date! let todaysDate = Date() var newFile = true if let existingFileInFileIndex = existingFileInFileIndex { if existingFileInFileIndex.deleted && (uploadRequest.undeleteServerFile == nil || uploadRequest.undeleteServerFile == false) { let message = "Attempt to upload an existing file, but it has already been deleted." finish(.errorMessage(message), params: params) return } newFile = false guard existingFileInFileIndex.fileVersion + 1 == uploadRequest.fileVersion else { let message = "File version being uploaded (\(String(describing: uploadRequest.fileVersion))) is not +1 of current version: \(String(describing: existingFileInFileIndex.fileVersion))" finish(.errorMessage(message), params: params) return } guard existingFileInFileIndex.mimeType == uploadRequest.mimeType else { let message = "File being uploaded(\(String(describing: uploadRequest.mimeType))) doesn't have the same mime type as current version: \(String(describing: existingFileInFileIndex.mimeType))" finish(.errorMessage(message), params: params) return } creationDate = existingFileInFileIndex.creationDate } else { if uploadRequest.undeleteServerFile != nil && uploadRequest.undeleteServerFile == true { let message = "Attempt to undelete a file but it's a new file!" finish(.errorMessage(message), params: params) return } // File isn't yet in the FileIndex-- must be a new file. Thus, must be version 0. guard uploadRequest.fileVersion == 0 else { let message = "File is new, but file version being uploaded (\(String(describing: uploadRequest.fileVersion))) is not 0" finish(.errorMessage(message), params: params) return } // 8/9/17; I'm no longer going to use a date from the client for dates/times-- clients can lie. // https://github.com/crspybits/SyncServerII/issues/4 creationDate = todaysDate } var ownerCloudStorage:CloudStorage! var ownerAccount:Account! if newFile { // OWNER // establish the v0 owner of the file. ownerAccount = params.effectiveOwningUserCreds } else { // OWNER // Need to get creds for the user that uploaded the v0 file. ownerAccount = FileController.getCreds(forUserId: existingFileInFileIndex!.userId, from: params.db, delegate: params.accountDelegate) } ownerCloudStorage = ownerAccount?.cloudStorage guard ownerCloudStorage != nil && ownerAccount != nil else { let message = "Could not obtain creds for v0 file: Assuming this means owning user is no longer on system." Log.error(message) finish(.errorResponse(.failure( .goneWithReason(message: message, .userRemoved))), params: params) return } // There is an unlikely race condition here -- two processes (within the same app, with the same deviceUUID) could be uploading the same file at the same time, both could upload, but only one would be able to create the Upload entry. I'm going to assume that this will not happen: That a single app/cilent will only upload the same file once at one time. (I used to create the Upload table entry first to avoid this race condition, but it's unlikely and leads to some locking issues-- see [1]). // Check to see if the file is present already-- i.e., if has been uploaded already. let key = UploadRepository.LookupKey.primaryKey(fileUUID: uploadRequest.fileUUID, userId: params.currentSignedInUser!.userId, deviceUUID: params.deviceUUID!) let lookupResult = params.repos.upload.lookup(key: key, modelInit: Upload.init) switch lookupResult { case .found(let model): Log.info("File was already present: Not uploading again.") let upload = model as! Upload let response = UploadFileResponse() // 12/27/17; Send the dates back down to the client. https://github.com/crspybits/SharedImages/issues/44 response.creationDate = creationDate response.updateDate = upload.updateDate finish(.success(response: response), params: params) return case .noObjectFound: // Expected result break case .error(let message): finish(.errorMessage(message), params: params) return } let cloudFileName = uploadRequest.cloudFileName(deviceUUID:params.deviceUUID!, mimeType: uploadRequest.mimeType) guard let mimeType = uploadRequest.mimeType else { let message = "No mimeType given!" finish(.errorMessage(message), params: params) return } // Lock will be held for the duration of the upload. Not the best, but don't have a better mechanism yet. Log.info("File being sent to cloud storage: \(cloudFileName)") let options = CloudStorageFileNameOptions(cloudFolderName: ownerAccount.cloudFolderName, mimeType: mimeType) let cleanup = Cleanup(cloudFileName: cloudFileName, options: options, ownerCloudStorage: ownerCloudStorage) ownerCloudStorage.uploadFile(cloudFileName:cloudFileName, data: uploadRequest.data, options:options) {[unowned self] result in switch result { case .success(let checkSum): Log.debug("File with checkSum \(checkSum) successfully uploaded!") /* 6/29/19; Doesn't seem like we need to acquire the lock again. We just need to add an entry into the Upload table. And what will it help to have the lock for that? Plus, I'm running into locking problems if I have the lock here. My hypothesis is: The Upload somehow acquires a lock that is needed by the DoneUploads. While the Upload is "uploading" its file, the DoneUploads acquires the GET_LOCK but is blocked on the other lock that the Upload has. The Upload tries to get the GET_LOCK once it finishes its upload, but can't since the DoneUploads has it. The Upload times out on its GET_LOCK request and fails. The DoneUploads completes, having gotten the lock that the Upload had. */ self.addUploadEntry(newFile: newFile, creationDate: creationDate, todaysDate: todaysDate, uploadedCheckSum: checkSum, cleanup: cleanup, params: params, uploadRequest: uploadRequest) case .accessTokenRevokedOrExpired: // Not going to do any cleanup. The access token has expired/been revoked. Presumably, the file wasn't uploaded. let message = "Access token revoked or expired." Log.error(message) self.finish(.errorResponse(.failure( .goneWithReason(message: message, .authTokenExpiredOrRevoked))), params: params) case .failure(let error): let message = "Could not uploadFile: error: \(error)" self.finish(.errorCleanup(message: message, cleanup: cleanup), params: params) } } } } private func addUploadEntry(newFile: Bool, creationDate: Date, todaysDate: Date, uploadedCheckSum: String, cleanup: Cleanup, params:RequestProcessingParameters, uploadRequest: UploadFileRequest) { let upload = Upload() upload.deviceUUID = params.deviceUUID upload.fileUUID = uploadRequest.fileUUID upload.fileVersion = uploadRequest.fileVersion upload.mimeType = uploadRequest.mimeType upload.sharingGroupUUID = uploadRequest.sharingGroupUUID // Waiting until now to check UploadRequest checksum because what's finally important is that the checksum before the upload is the same as that computed by the cloud storage service. var expectedCheckSum: String? expectedCheckSum = uploadRequest.checkSum?.lowercased() #if DEBUG // Short-circuit check sum test in the case of load testing. 'cause it won't be right :). if let loadTesting = Configuration.server.loadTestingCloudStorage, loadTesting { expectedCheckSum = uploadedCheckSum } #endif guard uploadedCheckSum.lowercased() == expectedCheckSum else { let message = "Checksum after upload to cloud storage (\(uploadedCheckSum) is not the same as before upload \(String(describing: expectedCheckSum))." finish(.errorCleanup(message: message, cleanup: cleanup), params: params) return } upload.lastUploadedCheckSum = uploadedCheckSum if let fileGroupUUID = uploadRequest.fileGroupUUID { guard uploadRequest.fileVersion == 0 else { let message = "fileGroupUUID was given, but file version being uploaded (\(String(describing: uploadRequest.fileVersion))) is not 0" finish(.errorCleanup(message: message, cleanup: cleanup), params: params) return } upload.fileGroupUUID = fileGroupUUID } if uploadRequest.undeleteServerFile != nil && uploadRequest.undeleteServerFile == true { Log.info("Undeleted server file.") upload.state = .uploadedUndelete } else { upload.state = .uploadedFile } // We are using the current signed in user's id here (and not the effective user id) because we need a way of indexing or organizing the collection of files uploaded by a particular user. upload.userId = params.currentSignedInUser!.userId upload.appMetaData = uploadRequest.appMetaData?.contents upload.appMetaDataVersion = uploadRequest.appMetaData?.version if newFile { upload.creationDate = creationDate } upload.updateDate = todaysDate let addUploadResult = params.repos.upload.retry { return params.repos.upload.add(upload: upload, fileInFileIndex: !newFile) } switch addUploadResult { case .success: let response = UploadFileResponse() // 12/27/17; Send the dates back down to the client. https://github.com/crspybits/SharedImages/issues/44 response.creationDate = creationDate response.updateDate = upload.updateDate finish(.success(response: response), params: params) case .duplicateEntry: finish(.errorCleanup(message: "Violated assumption: Two uploads by same app at the same time?", cleanup: cleanup), params: params) case .aModelValueWasNil: finish(.errorCleanup(message: "A model value was nil!", cleanup: cleanup), params: params) case .deadlock: finish(.errorCleanup(message: "Deadlock", cleanup: cleanup), params: params) case .waitTimeout: finish(.errorCleanup(message: "WaitTimeout", cleanup: cleanup), params: params) case .otherError(let error): finish(.errorCleanup(message: error, cleanup: cleanup), params: params) } } } /* [1] I'm getting another deadlock situation. It's happening on a DoneUploads, and a deletion from the Upload table. I'm thinking it has to do with an interaction with an Upload. What happens if: a) An upload occurs for sharing group X. b) While the upload is uploading, a DoneUploads for sharing group X occurs. sharingGroupUUID's are a foreign key. I'm assuming that inserting into Upload for sharing group X causes some kind of lock based on that sharing group X value. When the DoneUploads tries to delete from Upload, for that same sharing group, it gets a conflict. Conclusion: To deal with this, I'm (1) not adding the record to the Upload table until *after* the upload, and (2) only doing that when I am holding the sharing group lock. */ <file_sep>#!/bin/bash # Usage: ./runTests.sh <Command> <Option> # <Command> is one of: # suites -- where <Option> is one of: # all -- run all of the following suites. # basic -- tests needing no account # google -- run tests for Google specific accounts # dropbox -- run tests for Dropbox specific accounts # facebook -- run tests for Facebook specific accounts # owning -- run tests that depend only on owning account parameter # sharing-create -- run sharing tests-- these depend on several parameters # sharing-redeem # sharing-file # filter -- pass along the <Option> argument to swift tests as the --filter # run -- the <Option> is the complete swift test run command # Output in each case is in two parts: # 1) A series of lines of the format # Passed | N Failures ([out of] K tests): <Test suite name>[, <Parameters if any>] # where N in Failures are the number of individual test case failures. # where K is the numbe rof individual tests conducted. # 2) After the above series of lines, a single line summary: # Suites passed: X; Suite failures: Y (Z test cases) # where # X is the number of lines above that were marked as Passed; # Y is the number of lines that had non-zero failures # Z is the cummulative sum of N in the failure cases. # Assumption: This assumes it's run from the root of the repo. # Examples # ./Tools/runTests.sh filter ServerTests.DatabaseModelTests # ./Tools/runTests.sh suites google # ./Tools/runTests.sh suites sharing # ./Tools/runTests.sh suites owning TEST_JSON="Tools/TestSuites.json" COMMAND=$1 OPTION=$2 ALL_COUNT=`jq -r '.all | length' < ${TEST_JSON}` BASIC_SWIFT_TEST_CMD="swift test -Xswiftc -DDEBUG -Xswiftc -DSERVER" SWIFT_DEFINE="-Xswiftc -D" SYNCSERVER_TEST_MODULE="ServerTests" TEST_OUT_DIR=".testing" # Final stats TOTAL_SUITES_PASSED=0 TOTAL_SUITES_FAILED=0 TOTAL_FAILED_TEST_CASES=0 # Create TEST_OUT_DIR if it's not there. mkdir -p "$TEST_OUT_DIR" # See https://stackoverflow.com/questions/5947742/how-to-change-the-output-color-of-echo-in-linux RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m' # No Color generateFinalOutput () { if [ $TOTAL_SUITES_FAILED == "0" ]; then printf "${GREEN}Every test suite passed.${NC} There were $TOTAL_SUITES_PASSED of them.\n" else printf "Suites passed: $TOTAL_SUITES_PASSED; ${RED}Suite failed: $TOTAL_SUITES_FAILED ($TOTAL_FAILED_TEST_CASES test cases)${NC}\n" fi } generateOutput () { # Parameters: local resultsFileName=$1 local outputPrefix=$2 local compilerResult=$3 # The following depends on the assumption: That when a Swift test passes, there is a line containing the text " 0 failure", and that each test, pass or fail has lines "failure" in them (e.g., 0 failures or N failures). And further, that there are two of these lines per test. Of course, changes in the Swift testing output could change this and break this assumption. # The number of lines of output, divided by 2, is the total number of tests. local totalLines=`cat "$resultsFileName" | grep ' failure' | grep -Ev ERROR | wc -l` local totalTests=`expr $totalLines / 2` # This gives failures-- the number of lines divided by 2 is N, the number of failures. local failures=`cat "$resultsFileName" | grep ' failure' | grep -Ev ' 0 failure' | grep -Ev ERROR | wc -l` failures=`expr $failures / 2` TOTAL_FAILED_TEST_CASES=`expr $TOTAL_FAILED_TEST_CASES + $failures` local passLines=`cat "$resultsFileName" | grep ' passed at ' | wc -l` local testsPassed=`expr $passLines / 2` local possibleCompileFailure="false" if [ "${compilerResult}empty" != "empty" ] && [ $compilerResult -ne 0 ]; then possibleCompileFailure="true" fi if [ $possibleCompileFailure == "false" ] && [ "$failures" == "0" ] && [ $testsPassed == $totalTests ]; then printf "${outputPrefix}${GREEN}Passed${NC} ($testsPassed/$totalTests tests): $resultsFileName\n" TOTAL_SUITES_PASSED=`expr $TOTAL_SUITES_PASSED + 1` else TOTAL_SUITES_FAILED=`expr $TOTAL_SUITES_FAILED + 1` if [ $possibleCompileFailure == "true" ] && [ "$failures" == "0" ]; then printf "${outputPrefix}${RED}Compile failure${NC}: $resultsFileName\n" else printf "${outputPrefix}${RED}$failures FAILURES${NC} (out of $totalTests tests): $resultsFileName\n" fi fi } runSpecificSuite () { # Parameters: local suiteName=$1 local runOrPrint=$2 # "run" or "print" local suiteTestCount=`jq .$suiteName' | length' < ${TEST_JSON}` if [ $runOrPrint == "run" ]; then echo Running $suiteName containing $suiteTestCount test suites fi # To ensure the output filename (in /tmp) is unique local fileNameCounter=0 for suiteIndex in $(seq 0 `expr $suiteTestCount - 1`); do local testCase=`jq -r .$suiteName[$suiteIndex] < ${TEST_JSON}` local testCaseName=`echo $testCase | jq -r .name` local hasParameters=`echo $testCase | jq 'has("parameters")'` local commandParams="" local outputPrefix="" if [ $hasParameters == "true" ]; then # Generate command line parameter "defines" local parameters=`echo $testCase | jq .parameters` local parametersLength=`echo $parameters | jq length` for paramIndex in $(seq 0 `expr $parametersLength - 1`); do local parameter=`echo $parameters | jq -r .[$paramIndex]` commandParams="$commandParams ${SWIFT_DEFINE}$parameter" done if [ $runOrPrint == "run" ]; then printf "\trunning $testCaseName with command:\n" outputPrefix="\t\t" # I'm having problems running successive builds with parameters, back-to-back. Getting build failures. This seems to fix it. The problem stems from having to rebuild on each test run-- since these are build-time parameters. Somehow the build system seems to get confused otherwise. swift package clean fi else outputPrefix="\t" fi local outputFileName="$TEST_OUT_DIR"/$testCaseName.$fileNameCounter local command="$BASIC_SWIFT_TEST_CMD $commandParams --filter $SYNCSERVER_TEST_MODULE.$testCaseName" printf "$outputPrefix$command\n" if [ $runOrPrint == "run" ]; then $command > $outputFileName fi # For testing to see if the compiler failed. local compilerResult=$? if [ $runOrPrint == "run" ]; then generateOutput $outputFileName $outputPrefix $compilerResult fi fileNameCounter=`expr $fileNameCounter + 1` done } if [ "${COMMAND}" != "suites" ] && [ "${COMMAND}" != "print-suites" ] && [ "${COMMAND}" != "filter" ] && [ "${COMMAND}" != "run" ]; then echo "Command was not 'suites', 'print-suites', 'filter', or 'run' -- see Usage at the top of this script file." exit 1 fi if [ "${COMMAND}" == "suites" ] || [ "${COMMAND}" == "print-suites" ] ; then # option must be 'all' or from the all list. if [ "${COMMAND}" == "suites" ] ; then runOrPrint="run" else runOrPrint="print" fi if [ "${OPTION}" != "all" ] ; then FOUND=0 for i in $(seq 0 `expr $ALL_COUNT - 1`); do SUITE=`jq -r .all[$i] < ${TEST_JSON}` if [ "$SUITE" == "${OPTION}" ]; then FOUND=1 break fi done if [ $FOUND == "0" ]; then echo "suites option not found! See usage." exit 1 fi fi if [ "${OPTION}" == "all" ] ; then # iterate over all suites for i in $(seq 0 `expr $ALL_COUNT - 1`); do SUITE=`jq -r .all[$i] < ${TEST_JSON}` runSpecificSuite $SUITE $runOrPrint done else runSpecificSuite ${OPTION} $runOrPrint fi elif [ "${COMMAND}" == "filter" ] ; then OUTPUT_FILE_NAME="$TEST_OUT_DIR"/filter.txt $BASIC_SWIFT_TEST_CMD --filter ${OPTION} > $OUTPUT_FILE_NAME # For testing to see if the compiler failed. compilerResult=$? generateOutput $OUTPUT_FILE_NAME "\t" $compilerResult else # run command # See https://stackoverflow.com/questions/9057387/process-all-arguments-except-the-first-one-in-a-bash-script COMMAND=${@:2} TMPFILE=`mktemp $TEST_OUT_DIR/tmp.XXXXXXXX` echo "Running: $COMMAND" $COMMAND > $TMPFILE # For testing to see if the compiler failed. compilerResult=$? generateOutput $TMPFILE "\t" $compilerResult fi generateFinalOutput<file_sep>// // SharingGroupRepository.swift // Server // // Created by <NAME> on 6/23/18. // // A sharing group is a group of users who are sharing a collection of files. import Foundation import LoggerAPI import SyncServerShared class SharingGroup : NSObject, Model { static let sharingGroupUUIDKey = "sharingGroupUUID" var sharingGroupUUID: String! static let sharingGroupNameKey = "sharingGroupName" var sharingGroupName: String! static let deletedKey = "deleted" var deleted:Bool! // Not a part of this table, but a convenience for doing joins with the MasterVersion table. static let masterVersionKey = "masterVersion" var masterVersion: MasterVersionInt! // Similarly, not part of this table. For doing joins. public static let permissionKey = "permission" public var permission:Permission? // Also not part of this table. For doing fetches of sharing group users for the sharing group. public var sharingGroupUsers:[SyncServerShared.SharingGroupUser]! static let accountTypeKey = "accountType" var accountType: String! static let owningUserIdKey = "owningUserId" var owningUserId:UserId? subscript(key:String) -> Any? { set { switch key { case SharingGroup.sharingGroupUUIDKey: sharingGroupUUID = newValue as! String? case SharingGroup.sharingGroupNameKey: sharingGroupName = newValue as! String? case SharingGroup.deletedKey: deleted = newValue as! Bool? case SharingGroup.masterVersionKey: masterVersion = newValue as! MasterVersionInt? case SharingGroup.permissionKey: permission = newValue as! Permission? case SharingGroup.accountTypeKey: accountType = newValue as! String? case SharingGroup.owningUserIdKey: owningUserId = newValue as! UserId? default: assert(false) } } get { return getValue(forKey: key) } } override init() { super.init() } func typeConvertersToModel(propertyName:String) -> ((_ propertyValue:Any) -> Any?)? { switch propertyName { case SharingGroup.deletedKey: return {(x:Any) -> Any? in return (x as! Int8) == 1 } case SharingGroupUser.permissionKey: return {(x:Any) -> Any? in return Permission(rawValue: x as! String) } default: return nil } } func toClient() -> SyncServerShared.SharingGroup { let clientGroup = SyncServerShared.SharingGroup() clientGroup.sharingGroupUUID = sharingGroupUUID clientGroup.sharingGroupName = sharingGroupName clientGroup.deleted = deleted clientGroup.masterVersion = masterVersion clientGroup.permission = permission clientGroup.sharingGroupUsers = sharingGroupUsers Log.debug("accountType: \(String(describing: accountType)) (expected to be nil for an owning user)") if let accountType = accountType { clientGroup.cloudStorageType = AccountScheme(.accountName(accountType))?.cloudStorageType } return clientGroup } } class SharingGroupRepository: Repository, RepositoryLookup { private(set) var db:Database! required init(_ db:Database) { self.db = db } var tableName:String { return SharingGroupRepository.tableName } static var tableName:String { return "SharingGroup" } func upcreate() -> Database.TableUpcreateResult { let createColumns = "(sharingGroupUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + // A name for the sharing group-- assigned by the client app. "sharingGroupName VARCHAR(\(Database.maxSharingGroupNameLength)), " + // true iff sharing group has been deleted. Like file references in the FileIndex, I'm never going to actually delete sharing groups. "deleted BOOL NOT NULL, " + "UNIQUE (sharingGroupUUID))" let result = db.createTableIfNeeded(tableName: "\(tableName)", columnCreateQuery: createColumns) return result } enum LookupKey : CustomStringConvertible { case sharingGroupUUID(String) var description : String { switch self { case .sharingGroupUUID(let sharingGroupUUID): return "sharingGroupUUID(\(sharingGroupUUID))" } } } func lookupConstraint(key:LookupKey) -> String { switch key { case .sharingGroupUUID(let sharingGroupUUID): return "sharingGroupUUID = '\(sharingGroupUUID)'" } } enum AddResult { case success case error(String) } func add(sharingGroupUUID:String, sharingGroupName: String? = nil) -> AddResult { let insert = Database.PreparedStatement(repo: self, type: .insert) insert.add(fieldName: SharingGroup.sharingGroupUUIDKey, value: .string(sharingGroupUUID)) insert.add(fieldName: SharingGroup.deletedKey, value: .bool(false)) if let sharingGroupName = sharingGroupName { insert.add(fieldName: SharingGroup.sharingGroupNameKey, value: .string(sharingGroupName)) } do { try insert.run() Log.info("Sucessfully created sharing group") return .success } catch (let error) { Log.error("Could not insert into \(tableName): \(error)") return .error("\(error)") } } func sharingGroups(forUserId userId: UserId, sharingGroupUserRepo: SharingGroupUserRepository, userRepo: UserRepository) -> [SharingGroup]? { let masterVersionTableName = MasterVersionRepository.tableName let sharingGroupUserTableName = SharingGroupUserRepository.tableName let query = "select \(tableName).sharingGroupUUID, \(tableName).sharingGroupName, \(tableName).deleted, \(masterVersionTableName).masterVersion, \(sharingGroupUserTableName).permission, \(sharingGroupUserTableName).owningUserId FROM \(tableName),\(sharingGroupUserTableName), \(masterVersionTableName) WHERE \(sharingGroupUserTableName).userId = \(userId) AND \(sharingGroupUserTableName).sharingGroupUUID = \(tableName).sharingGroupUUID AND \(tableName).sharingGroupUUID = \(masterVersionTableName).sharingGroupUUID" // The "owners" or "parents" of the sharing groups the sharing user is in guard let owningUsers = userRepo.getOwningSharingGroupUsers(forSharingUserId: userId) else { Log.error("Failed calling getOwningSharingGroupUsers") return nil } guard let sharingGroups = self.sharingGroups(forSelectQuery: query, sharingGroupUserRepo: sharingGroupUserRepo) else { Log.error("Failed calling sharingGroups") return nil } // Now, get the accountTypes of the "owning" or "parent" users for each sharing group, for sharing users. This will be used downstream to determine the cloud sharing type of each sharing group for the sharing user. for sharingGroup in sharingGroups { let owningUser = owningUsers.filter {sharingGroup.owningUserId != nil && $0.userId == sharingGroup.owningUserId} if owningUser.count == 1 { sharingGroup.accountType = owningUser[0].accountType } } return sharingGroups } private func sharingGroups(forSelectQuery selectQuery: String, sharingGroupUserRepo: SharingGroupUserRepository) -> [SharingGroup]? { guard let select = Select(db:db, query: selectQuery, modelInit: SharingGroup.init, ignoreErrors:false) else { return nil } var result = [SharingGroup]() var errorGettingSgus = false select.forEachRow { rowModel in let sharingGroup = rowModel as! SharingGroup if let sgus:[SyncServerShared.SharingGroupUser] = sharingGroupUserRepo.sharingGroupUsers(forSharingGroupUUID: sharingGroup.sharingGroupUUID) { sharingGroup.sharingGroupUsers = sgus } else { errorGettingSgus = true return } result.append(sharingGroup) } if !errorGettingSgus && select.forEachRowStatus == nil { return result } else { return nil } } enum MarkDeletionCriteria { case sharingGroupUUID(String) func toString() -> String { switch self { case .sharingGroupUUID(let sharingGroupUUID): return "\(SharingGroup.sharingGroupUUIDKey)='\(sharingGroupUUID)'" } } } func markAsDeleted(forCriteria criteria: MarkDeletionCriteria) -> Int64? { let query = "UPDATE \(tableName) SET \(SharingGroup.deletedKey)=1 WHERE " + criteria.toString() if db.query(statement: query) { return db.numberAffectedRows() } else { let error = db.error Log.error("Could not mark files as deleted in \(tableName): \(error)") return nil } } func update(sharingGroup: SharingGroup) -> Bool { let update = Database.PreparedStatement(repo: self, type: .update) guard let sharingGroupUUID = sharingGroup.sharingGroupUUID, let sharingGroupName = sharingGroup.sharingGroupName else { return false } update.add(fieldName: SharingGroup.sharingGroupNameKey, value: .string(sharingGroupName)) update.where(fieldName: SharingGroup.sharingGroupUUIDKey, value: .string(sharingGroupUUID)) do { try update.run() } catch (let error) { Log.error("Failed updating sharing group: \(error)") return false } return true } } <file_sep>// // SharingAccountsController // Server // // Created by <NAME> on 4/9/17. // // import Credentials import SyncServerShared import LoggerAPI import KituraNet import Foundation class SharingAccountsController : ControllerProtocol { class func setup() -> Bool { return true } init() { } func createSharingInvitation(params:RequestProcessingParameters) { assert(params.ep.authenticationLevel == .secondary) assert(params.ep.sharing?.minPermission == .admin) guard let createSharingInvitationRequest = params.request as? CreateSharingInvitationRequest else { let message = "Did not receive CreateSharingInvitationRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard sharingGroupSecurityCheck(sharingGroupUUID: createSharingInvitationRequest.sharingGroupUUID, params: params) else { let message = "Failed in sharing group security check." Log.error(message) params.completion(.failure(.message(message))) return } guard let currentSignedInUser = params.currentSignedInUser else { let message = "No currentSignedInUser" Log.error(message) params.completion(.failure(.message(message))) return } // 6/20/18; The current user can be a sharing or owning user, and whether or not these users can invite others depends on the permissions they have. See https://github.com/crspybits/SyncServerII/issues/76 And permissions have already been checked before this point in request handling. guard case .found(let effectiveOwningUserId) = Controllers.getEffectiveOwningUserId(user: currentSignedInUser, sharingGroupUUID: createSharingInvitationRequest.sharingGroupUUID, sharingGroupUserRepo: params.repos.sharingGroupUser) else { let message = "Could not get effectiveOwningUserId for inviting user." Log.error(message) params.completion(.failure(.message(message))) return } let allowSocialAcceptance = createSharingInvitationRequest.allowSocialAcceptance let numberAcceptors = createSharingInvitationRequest.numberOfAcceptors guard numberAcceptors >= 1 && numberAcceptors <= ServerConstants.maxNumberSharingInvitationAcceptors else { let message = "numberAcceptors <= 0 or > \(ServerConstants.maxNumberSharingInvitationAcceptors)" Log.error(message) params.completion(.failure(.message(message))) return } let result = params.repos.sharing.add( owningUserId: effectiveOwningUserId, sharingGroupUUID: createSharingInvitationRequest.sharingGroupUUID, permission: createSharingInvitationRequest.permission, allowSocialAcceptance: allowSocialAcceptance, numberAcceptors: numberAcceptors) guard case .success(let sharingInvitationUUID) = result else { let message = "Failed to add Sharing Invitation" Log.error(message) params.completion(.failure(.message(message))) return } let response = CreateSharingInvitationResponse() response.sharingInvitationUUID = sharingInvitationUUID params.completion(.success(response)) } func getSharingInvitationInfo(params:RequestProcessingParameters) { assert(params.ep.authenticationLevel == .none) guard let request = params.request as? GetSharingInvitationInfoRequest else { let message = "Did not receive GetSharingInvitationInfoRequest" Log.error(message) params.completion(.failure(.message(message))) return } // I'm not going to fiddle with removing expired invitations here. Just seems wrong with a get info method. let sharingInvitationKey = SharingInvitationRepository.LookupKey.unexpiredSharingInvitationUUID(uuid: request.sharingInvitationUUID) let lookupResult = SharingInvitationRepository(params.db).lookup(key: sharingInvitationKey, modelInit: SharingInvitation.init) guard case .found(let model) = lookupResult, let sharingInvitation = model as? SharingInvitation else { let message = "Could not find sharing invitation: \(String(describing: request.sharingInvitationUUID)). Was it stale?" Log.error(message) params.completion(.failure(.messageWithStatus(message, HTTPStatusCode.gone))) return } let response = GetSharingInvitationInfoResponse() response.permission = sharingInvitation.permission response.allowSocialAcceptance = sharingInvitation.allowSocialAcceptance params.completion(.success(response)) } private func redeem(params:RequestProcessingParameters, request: RedeemSharingInvitationRequest, sharingInvitation: SharingInvitation, sharingInvitationKey: SharingInvitationRepository.LookupKey, completion: @escaping ((RequestProcessingParameters.Response)->())) { guard let accountScheme = params.accountProperties?.accountScheme else { let message = "Could not get account scheme from account properties!" Log.error(message) params.completion(.failure(.message(message))) return } if !sharingInvitation.allowSocialAcceptance { guard accountScheme.userType == .owning else { let message = "Invitation does not allow social acceptance, but signed in user is not owning" Log.error(message) params.completion(.failure(.messageWithStatus(message, HTTPStatusCode.forbidden))) return } } guard sharingInvitation.numberAcceptors >= 1 else { let message = "Number of acceptors was 0 or less." Log.error(message) params.completion(.failure(.message(message))) return } // I'm not requiring a master version from the client-- because they don't yet have a context in which to be concerned about the master version; however, I am updating the master version because I want to inform other clients of a change in the sharing group-- i.e., of a user being added to the sharing group. guard let masterVersion = Controllers.getMasterVersion(sharingGroupUUID: sharingInvitation.sharingGroupUUID, params: params) else { let message = "Could not get master version for sharing group uuid: \(String(describing: sharingInvitation.sharingGroupUUID))" Log.error(message) completion(.failure(.message(message))) return } if let response = Controllers.updateMasterVersion(sharingGroupUUID: sharingInvitation.sharingGroupUUID, masterVersion: masterVersion, params: params, responseType: nil) { completion(response) return } if sharingInvitation.numberAcceptors == 1 { let removalResult2 = params.repos.sharing.retry { return params.repos.sharing.remove(key: sharingInvitationKey) } guard case .removed(let numberRemoved) = removalResult2, numberRemoved == 1 else { let message = "Failed removing sharing invitation!" Log.error(message) completion(.failure(.message(message))) return } } else { // numberAcceptors should be > 1 guard params.repos.sharing.decrementNumberAcceptors(sharingInvitationUUID: sharingInvitation.sharingInvitationUUID) else { let message = "Could not decrement number acceptors." Log.error(message) completion(.failure(.message(message))) return } } // The user can either: (a) already be on the system -- so this will be a request to add a sharing group to an existing user, or (b) this is a request to both create a user and have them join a sharing group. guard let credsId = params.userProfile?.id else { let message = "Could not get credsId from user profile." Log.error(message) completion(.failure(.message(message))) return } let userExists = UserController.userExists(accountType: accountScheme.accountName, credsId: credsId, userRepository: params.repos.user) switch userExists { case .doesNotExist: redeemSharingInvitationForNewUser(params:params, request: request, sharingInvitation: sharingInvitation, completion: completion) case .exists(let existingUser): redeemSharingInvitationForExistingUser(existingUser, params:params, request: request, sharingInvitation: sharingInvitation, completion: completion) case .error: let message = "Error looking up user!" Log.error(message) completion(.failure(.message(message))) } } private func redeemSharingInvitationForExistingUser(_ existingUser: User, params:RequestProcessingParameters, request: RedeemSharingInvitationRequest, sharingInvitation: SharingInvitation, completion: @escaping ((RequestProcessingParameters.Response)->())) { // Check to see if this user is already in this sharing group. We've got a lock on the sharing group, so no race condition will occur for adding user to sharing group. let key = SharingGroupUserRepository.LookupKey.primaryKeys(sharingGroupUUID: sharingInvitation.sharingGroupUUID, userId: existingUser.userId) let result = params.repos.sharingGroupUser.lookup(key: key, modelInit: SharingGroupUser.init) switch result { case .found: let message = "User id: \(existingUser.userId!) was already in sharing group: \(String(describing: sharingInvitation.sharingGroupUUID))" Log.error(message) completion(.failure(.message(message))) return case .noObjectFound: // Good: We can add this user to the sharing group. break case .error(let error): Log.error(error) completion(.failure(.message(error))) return } var owningUserId: UserId? guard let accountScheme = AccountScheme(.accountName(existingUser.accountType)) else { let message = "Could not look up AccountScheme from account type: \(String(describing: existingUser.accountType))" Log.error(message) completion(.failure(.message(message))) return } if accountScheme.userType == .sharing { owningUserId = sharingInvitation.owningUserId } guard case .success = params.repos.sharingGroupUser.add(sharingGroupUUID: sharingInvitation.sharingGroupUUID, userId: existingUser.userId, permission: sharingInvitation.permission, owningUserId: owningUserId) else { let message = "Failed on adding sharing group user for user." Log.error(message) completion(.failure(.message(message))) return } let response = RedeemSharingInvitationResponse() response.sharingGroupUUID = sharingInvitation.sharingGroupUUID response.userId = existingUser.userId completion(.success(response)) } private func redeemSharingInvitationForNewUser(params:RequestProcessingParameters, request: RedeemSharingInvitationRequest, sharingInvitation: SharingInvitation, completion: @escaping ((RequestProcessingParameters.Response)->())) { // No database creds because this is a new user-- so use params.profileCreds let user = User() user.username = params.userProfile!.displayName guard let accountScheme = params.accountProperties?.accountScheme else { let message = "Could not get account scheme from properties!" Log.error(message) completion(.failure(.message(message))) return } user.accountType = accountScheme.accountName user.credsId = params.userProfile!.id user.creds = params.profileCreds!.toJSON() var createInitialOwningUserFile = false var owningUserId: UserId? switch accountScheme.userType { case .sharing: owningUserId = sharingInvitation.owningUserId case .owning: // When the user is an owning user, they will rely on their own cloud storage to upload new files-- for sharing groups where they have upload permissions. // Cloud storage folder must be present when redeeming an invitation: a) using an owning account, and where b) that owning account type needs a cloud storage folder (e.g., Google Drive). I'm not going to concern myself with the sharing permissions of the immediate sharing invitation because they may join other sharing groups-- and have write permissions there. if params.profileCreds!.owningAccountsNeedCloudFolderName { guard let cloudFolderName = request.cloudFolderName else { let message = "No cloud folder name given when redeeming sharing invitation using owning account that needs one!" Log.error(message) completion(.failure(.message(message))) return } createInitialOwningUserFile = true user.cloudFolderName = cloudFolderName } } guard let userId = params.repos.user.add(user: user) else { let message = "Failed on adding sharing user to User!" Log.error(message) completion(.failure(.message(message))) return } guard case .success = params.repos.sharingGroupUser.add(sharingGroupUUID: sharingInvitation.sharingGroupUUID, userId: userId, permission: sharingInvitation.permission, owningUserId: owningUserId) else { let message = "Failed on adding sharing group user for new sharing user." Log.error(message) completion(.failure(.message(message))) return } let response = RedeemSharingInvitationResponse() response.sharingGroupUUID = sharingInvitation.sharingGroupUUID response.userId = userId // 11/5/17; Up until now I had been calling `generateTokensIfNeeded` for Facebook creds and that had been generating tokens. Somehow, in running my tests today, I'm getting failures from the Facebook API when I try to do this. This may only occur in testing because I'm passing long-lived access tokens. Plus, it's possible this error has gone undiagnosed until now. In testing, there is no need to generate the long-lived access tokens. var profileCreds = params.profileCreds! profileCreds.accountCreationUser = .userId(userId) profileCreds.generateTokensIfNeeded(dbCreds: nil, routerResponse: params.routerResponse, success: { if createInitialOwningUserFile { // We're creating an account for an owning user. `profileCreds` will be an owning user account and this will implement the CloudStorage protocol. guard let cloudStorageCreds = profileCreds.cloudStorage else { let message = "Could not obtain CloudStorage Creds" Log.error(message) completion(.failure(.message(message))) return } UserController.createInitialFileForOwningUser(cloudFolderName: user.cloudFolderName, cloudStorage: cloudStorageCreds) { createResponse in switch createResponse { case .success: completion(.success(response)) case .accessTokenRevokedOrExpired: // We're creating an account for an owning user. This is a fatal error-- we shouldn't have gotten to this point. Somehow authentication worked, but then a moment later the access token was revoked or expired. let message = "Yikes: Access token expired or revoked. Fatal error." Log.error(message) completion(.failure(.message(message))) case .failure: completion(.failure(nil)) } } } else { completion(.success(response)) } }, failure: { completion(.failure(nil)) }) } func redeemSharingInvitation(params:RequestProcessingParameters) { assert(params.ep.authenticationLevel == .primary) guard let request = params.request as? RedeemSharingInvitationRequest else { let message = "Did not receive RedeemSharingInvitationRequest" Log.error(message) params.completion(.failure(.message(message))) return } // Remove stale invitations. let removalKey = SharingInvitationRepository.LookupKey.staleExpiryDates let removalResult = params.repos.sharing.retry { return params.repos.sharing.remove(key: removalKey) } guard case .removed(_) = removalResult else { let message = "Failed removing stale sharing invitations" Log.error(message) params.completion(.failure(.message(message))) return } // What I want to do at this point is to simultaneously and atomically, (a) lookup the sharing invitation, and (b) delete it. I believe that since (i) I'm using mySQL transactions, and (ii) InnoDb with a default transaction level of REPEATABLE READ, this should work by first doing the lookup, and then doing the delete. let sharingInvitationKey = SharingInvitationRepository.LookupKey.sharingInvitationUUID(uuid: request.sharingInvitationUUID) let lookupResult = params.repos.sharing.lookup(key: sharingInvitationKey, modelInit: SharingInvitation.init) guard case .found(let model) = lookupResult, let sharingInvitation = model as? SharingInvitation else { let message = "Could not find sharing invitation: \(String(describing: request.sharingInvitationUUID)). Was it stale?" Log.error(message) params.completion(.failure(.message(message))) return } redeem(params: params, request: request, sharingInvitation: sharingInvitation, sharingInvitationKey: sharingInvitationKey) { response in params.completion(response) } } } <file_sep>#!/bin/bash # Purpose: Creates an application bundle for upload to the AWS Elastic Beanstalk, for running SyncServer # Usage: ./make.sh <DockerImageTag> <file>.json [<environment-variables>.yml] # :<DockerImageTag> is appended to the image name given in Dockerrun.aws.json (see the raw.materials folder) # The .json file will be used as the Server.json file to start the server. # The environment variables are a little tricky. See the README.txt in this folder. # WARNING: I believe AWS doesn't do well with Server.json files that have blank lines in the technique I'm using to transfer the file to the Docker container. # Assumes: # That this script is run from the directory the script is located in. # That the `jq` command line program is installed (e.g., brew install jq); see also https://stackoverflow.com/questions/24942875/change-json-file-by-bash-script # Examples: # Neebla production server # ./make.sh 0.21.2 ../Environments/neebla-production/Server.json ../Environments/neebla-production/configure.yml # SharedImages production server # ./make.sh 0.7.7 ../Environments/sharedimages-production/Server.json ../Environments/sharedimages-production/configure.yml # SharedImages staging server # ./make.sh 0.7.6 ../Environments/sharedimages-staging/Server.json ../Environments/sharedimages-staging/configure.yml # iOS Client testing server # ./make.sh 0.14.0 ../Environments/syncserver-testing/Server.json ../Environments/syncserver-testing/configure.yml DOCKER_IMAGE_TAG=$1 SERVER_JSON=$2 ENV_VAR_PARAM=$3 ZIPFILE=bundle.zip ENV_VARIABLES="env.variables.config" # 6 Extra blanks because config file needs these prepended before json file lines for YAML formatting. EXTRA_BLANKS=" " # Check if jq is installed. if [ "empty`command -v jq`" == "empty" ]; then echo "**** The jq command needs to be installed. See docs in this script." exit fi if [ ! -d .ebextensions ]; then mkdir .ebextensions fi if [ ! -d tmp ]; then mkdir tmp fi if [ "empty${DOCKER_IMAGE_TAG}" == "empty" ]; then echo "**** You need to give the Docker image tag as a parameter!" exit fi if [ "empty${SERVER_JSON}" == "empty" ]; then echo "**** You need to give the server .json file as a parameter!" exit fi if [ "empty${ENV_VAR_PARAM}" != "empty" ]; then if [ ! -e "${ENV_VAR_PARAM}" ]; then echo "**** Couldn't find: ${ENV_VAR_PARAM} -- giving up!" exit fi # Make sure the environment variables file is named with a .config extension. cp "${ENV_VAR_PARAM}" "$ENV_VARIABLES" mv -f "$ENV_VARIABLES" .ebextensions fi echo "Using:" echo -e "\tDocker image tag\n\t\t${DOCKER_IMAGE_TAG}" echo -e "\tEnvironment variables file\n\t\t${ENV_VAR_PARAM}" echo -e "\tServer json file\n\t\t${SERVER_JSON}" echo cp -f raw.materials/Server.json.config tmp # There's some trickyness to avoid removing white space and avoid removing the last line if it doesn't end with a newline. See https://stackoverflow.com/questions/10929453/ while IFS='' read -r line || [[ -n "$line" ]]; do echo "${EXTRA_BLANKS}$line" >> tmp/Server.json.config done < "${SERVER_JSON}" mv -f tmp/Server.json.config .ebextensions cp -f raw.materials/SyncServer.ngnix.config .ebextensions cp -f raw.materials/SyncServer.logging.config .ebextensions cp -f raw.materials/cloudwatch.config .ebextensions if [ -e ${ZIPFILE} ]; then echo "Removing old ${ZIPFILE}" rm ${ZIPFILE} fi # Modify the Docker image name in Dockerrun.aws.json with the tag given. DOCKER_IMAGE=`jq -r '.Image.Name' raw.materials/Dockerrun.aws.json` JQ_CMD=".Image.Name = \"${DOCKER_IMAGE}:${DOCKER_IMAGE_TAG}\"" jq "${JQ_CMD}" raw.materials/Dockerrun.aws.json > Dockerrun.aws.json zip -r ${ZIPFILE} Dockerrun.aws.json .ebextensions # zip -d ${ZIPFILE} __MACOSX/\* if [ -e ~/Desktop/${ZIPFILE} ]; then rm ~/Desktop/${ZIPFILE} fi mv ${ZIPFILE} ~/Desktop rm .ebextensions/* rmdir .ebextensions rmdir tmp rm Dockerrun.aws.json echo echo "application bundle ${ZIPFILE} created and moved to the Desktop-- upload this to AWS." <file_sep># See https://github.com/IBM-Swift/swift-ubuntu-docker # Note that I'm not using Ubuntu 14.04 because I'm currently using Perfect for mySQL interface # and that has problems with the mysqlclient for 14.04. See https://github.com/PerfectlySoft/Perfect-MySQL # This is for Ubuntu 16.04; It's for Swift 5.0.1 as of 6/12/19, there just is only a `latest` tag. FROM ibmcom/swift-ubuntu-xenial:latest LABEL maintainer="<NAME> <<EMAIL>>" LABEL Description="Docker image for building the Swift SyncServer server" # pkg-config below is trying to avoid: # warning: failed to retrieve search paths with pkg-config; maybe pkg-config is not installed # Without tzdata, the TimeZone Swift method fails, at least sometimes. # Install additional packages RUN apt-get -q update && \ apt-get -q install -y \ uuid-dev \ libmysqlclient-dev \ jq \ openssl \ libssl-dev \ pkg-config \ tzdata \ && rm -r /var/lib/apt/lists/* # Print Installed Swift Version RUN swift --version <file_sep>// // Controllers.swift // Server // // Created by <NAME> on 12/5/16. // // import Foundation import LoggerAPI import Credentials import Kitura import SyncServerShared protocol ControllerProtocol { static func setup() -> Bool } extension ControllerProtocol { // Make sure the current signed in user is a member of the sharing group. // `checkNotDeleted` set to true ensures the sharing group is not deleted. func sharingGroupSecurityCheck(sharingGroupUUID: String, params:RequestProcessingParameters, checkNotDeleted: Bool = true) -> Bool { guard let userId = params.currentSignedInUser?.userId else { Log.error("No userId!") return false } let sharingUserKey = SharingGroupUserRepository.LookupKey.primaryKeys(sharingGroupUUID: sharingGroupUUID, userId: userId) let lookupResult = params.repos.sharingGroupUser.lookup(key: sharingUserKey, modelInit: SharingGroupUser.init) switch lookupResult { case .found: if checkNotDeleted { // The deleted flag is in the SharingGroup (not SharingGroupUser) repo. Need to look that up. let sharingKey = SharingGroupRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let lookupResult = params.repos.sharingGroup.lookup(key: sharingKey, modelInit: SharingGroup.init) switch lookupResult { case .found(let modelObj): guard let sharingGroup = modelObj as? Server.SharingGroup else { Log.error("Could not convert model obj to SharingGroup.") return false } guard !sharingGroup.deleted else { return false } case .noObjectFound: Log.error("Could not find sharing group.") case .error(let error): Log.error("Error looking up sharing group: \(error)") } } return true case .noObjectFound: Log.error("User: \(userId) is not in sharing group: \(sharingGroupUUID)") return false case .error(let error): Log.error("Error checking if user is in sharing group: \(error)") return false } } } public class RequestProcessingParameters { let request: RequestMessage! let ep: ServerEndpoint! // For secondary authenticated endpoints, these are the immediate user's creds (i.e., they are not the effective user id creds) read from the database. It's nil otherwise. let creds: Account? // [1]. These reflect the effectiveOwningUserId of the User, if any. They will be nil if (a) the user was invited, (b) they redeemed their sharing invitation with a non-owning account, and (c) their original inviting user removed their own account. let effectiveOwningUserCreds: Account? // These are used only when we don't yet have database creds-- e.g., for endpoints that are creating users in the database. let profileCreds: Account? let userProfile: UserProfile? let accountProperties:AccountManager.AccountProperties? let currentSignedInUser:User? let db:Database! var repos:Repositories! let routerResponse:RouterResponse! let deviceUUID:String? enum Response { case success(ResponseMessage) // Fatal error processing the request, i.e., an error that could not be handled in the normal responses made in the ResponseMessage. case failure(RequestHandler.FailureResult?) } let accountDelegate: AccountDelegate let completion: (Response)->() init(request: RequestMessage, ep:ServerEndpoint, creds: Account?, effectiveOwningUserCreds: Account?, profileCreds: Account?, userProfile: UserProfile?, accountProperties: AccountManager.AccountProperties?, currentSignedInUser: User?, db:Database, repos:Repositories, routerResponse:RouterResponse, deviceUUID: String?, accountDelegate: AccountDelegate, completion: @escaping (Response)->()) { self.request = request self.ep = ep self.creds = creds self.effectiveOwningUserCreds = effectiveOwningUserCreds self.profileCreds = profileCreds self.userProfile = userProfile self.accountProperties = accountProperties self.currentSignedInUser = currentSignedInUser self.db = db self.repos = repos self.routerResponse = routerResponse self.deviceUUID = deviceUUID self.completion = completion self.accountDelegate = accountDelegate } func fail(_ message: String) { Log.error(message) completion(.failure(.message(message))) } } public class Controllers { // When adding a new controller, you must add it to this list. private static let list:[ControllerProtocol.Type] = [UserController.self, UtilController.self, FileController.self, SharingAccountsController.self, SharingGroupsController.self, PushNotificationsController.self] static func setup() -> Bool { for controller in list { if !controller.setup() { Log.error("Could not setup controller: \(controller)") return false } } return true } enum UpdateMasterVersionResult : Error, RetryRequest { case success case error(String) case masterVersionUpdate(MasterVersionInt) case deadlock case waitTimeout var shouldRetry: Bool { if case .deadlock = self { return true } else if case .waitTimeout = self { return true } else { return false } } } private static func updateMasterVersion(sharingGroupUUID:String, currentMasterVersion:MasterVersionInt, params:RequestProcessingParameters) -> UpdateMasterVersionResult { let currentMasterVersionObj = MasterVersion() // The master version reflects a sharing group. currentMasterVersionObj.sharingGroupUUID = sharingGroupUUID currentMasterVersionObj.masterVersion = currentMasterVersion let updateMasterVersionResult = params.repos.masterVersion.updateToNext(current: currentMasterVersionObj) var result:UpdateMasterVersionResult! switch updateMasterVersionResult { case .success: result = .success case .error(let error): let message = "Failed lookup in MasterVersionRepository: \(error)" Log.error(message) result = .error(message) case .deadlock: result = .deadlock case .waitTimeout: result = .waitTimeout case .didNotMatchCurrentMasterVersion: getMasterVersion(sharingGroupUUID: sharingGroupUUID, params: params) { (error, masterVersion) in if error == nil { result = .masterVersionUpdate(masterVersion!) } else { result = .error("\(error!)") } } } return result } enum GetMasterVersionError : Error { case error(String) case noObjectFound } // Synchronous callback. // Get the master version for a sharing group because the master version reflects the overall version of the data for a sharing group. static func getMasterVersion(sharingGroupUUID: String, params:RequestProcessingParameters, completion:(Error?, MasterVersionInt?)->()) { let key = MasterVersionRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let result = params.repos.masterVersion.lookup(key: key, modelInit: MasterVersion.init) switch result { case .error(let error): completion(GetMasterVersionError.error(error), nil) case .found(let model): let masterVersionObj = model as! MasterVersion completion(nil, masterVersionObj.masterVersion) case .noObjectFound: let errorMessage = "Master version record not found for: \(key)" Log.error(errorMessage) completion(GetMasterVersionError.noObjectFound, nil) } } static func getMasterVersion(sharingGroupUUID: String, params:RequestProcessingParameters) -> MasterVersionInt? { var result: MasterVersionInt? getMasterVersion(sharingGroupUUID: sharingGroupUUID, params: params) { error, masterVersion in if error == nil { result = masterVersion } } return result } // Returns nil on success. static func updateMasterVersion(sharingGroupUUID: String, masterVersion: MasterVersionInt, params:RequestProcessingParameters, responseType: MasterVersionUpdateResponse.Type?) -> RequestProcessingParameters.Response? { let updateResult = params.repos.masterVersion.retry { return updateMasterVersion(sharingGroupUUID: sharingGroupUUID, currentMasterVersion: masterVersion, params: params) } switch updateResult { case .success: return nil case .masterVersionUpdate(let updatedMasterVersion): Log.warning("Master version update: \(updatedMasterVersion)") if let responseType = responseType { var response = responseType.init() response.masterVersionUpdate = updatedMasterVersion return .success(response) } else { let message = "Master version update but no response type was given." Log.error(message) return .failure(.message(message)) } case .deadlock: return .failure(.message("Deadlock!")) case .waitTimeout: return .failure(.message("Timeout!")) case .error(let error): let message = "Failed on updateMasterVersion: \(error)" Log.error(message) return .failure(.message(message)) } } enum EffectiveOwningUserId { case found(UserId) case noObjectFound case gone case error } static func getEffectiveOwningUserId(user: User, sharingGroupUUID: String, sharingGroupUserRepo: SharingGroupUserRepository) -> EffectiveOwningUserId { if AccountScheme(.accountName(user.accountType))?.userType == .owning { return .found(user.userId) } let sharingUserKey = SharingGroupUserRepository.LookupKey.primaryKeys(sharingGroupUUID: sharingGroupUUID, userId: user.userId) let lookupResult = sharingGroupUserRepo.lookup(key: sharingUserKey, modelInit: SharingGroupUser.init) switch lookupResult { case .found(let model): let sharingGroupUser = model as! SharingGroupUser if let owningUserId = sharingGroupUser.owningUserId { return .found(owningUserId) } else { return .gone } case .noObjectFound: return .noObjectFound case .error(let error): Log.error("getEffectiveOwningUserIds: \(error)") return .error } } } <file_sep>#!/bin/bash # Purpose: Temporarily suspend an Elastic Beanstalk environment. # Usage: suspend on | off # on-- initiates suspending # off-- turns off suspending # See: # https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb3-scale.html # https://stackoverflow.com/questions/32210389/pause-an-elastic-beanstalk-app-environment # https://forums.aws.amazon.com/thread.jspa?threadID=121273 SUSPENDED=$1 NUMBER_INSTANCES=1 if [ "$SUSPENDED" == "on" ]; then echo "Suspending environment" eb scale 0 elif [ "$SUSPENDED" == "off" ]; then echo "Unsuspending environment" eb scale $NUMBER_INSTANCES else echo "Bad args-- see docs for usage" fi <file_sep>#!/bin/bash eb create sharedimages-staging --cname sharedimages-staging <file_sep>// // Synchronized.swift // Server // // Created by <NAME> on 12/28/17. // import Foundation import Dispatch class Synchronized { private let semaphore = DispatchSemaphore(value: 1) init() { } func sync(closure: () -> ()) { semaphore.wait() closure() semaphore.signal() } } <file_sep>// // ServerSetup.swift // Server // // Created by <NAME> on 12/4/16. // // import LoggerAPI import Kitura import KituraNet import KituraSession import Credentials import CredentialsGoogle import Foundation import SyncServerShared /* I'm getting the following error, after having started using SSL and self-signing certificates: [2017-05-20T21:26:32.218-06:00] [ERROR] [IncomingSocketHandler.swift:148 handleRead()] Read from socket (file descriptor 15) failed. Error = Error code: -9806(0x-264E), ERROR: SSLRead, code: -9806, reason: errSSLClosedAbort. See also: https://github.com/IBM-Swift/Kitura-net/issues/196 */ public typealias ProcessRequest = (RequestProcessingParameters)->() class RequestHandler { private var request:RouterRequest! private var response:RouterResponse! private var repositories:Repositories! private var authenticationLevel:AuthenticationLevel! private var currentSignedInUser:User? private var deviceUUID:String? private var endpoint:ServerEndpoint! private var accountDelegate: AccountDelegateHandler! init(request:RouterRequest, response:RouterResponse, endpoint:ServerEndpoint? = nil) { self.request = request self.response = response if endpoint == nil { self.authenticationLevel = .secondary } else { self.authenticationLevel = endpoint!.authenticationLevel } self.endpoint = endpoint ServerStatsKeeper.session.increment(stat: .apiRequestsCreated) Log.info("RequestHandler.init: numberCreated: \(ServerStatsKeeper.session.currentValue(stat: .apiRequestsCreated)); numberDeleted: \(ServerStatsKeeper.session.currentValue(stat: .apiRequestsDeleted));") } deinit { ServerStatsKeeper.session.increment(stat: .apiRequestsDeleted) Log.info("RequestHandler.deinit: numberCreated: \(ServerStatsKeeper.session.currentValue(stat: .apiRequestsCreated)); numberDeleted: \(ServerStatsKeeper.session.currentValue(stat: .apiRequestsDeleted));") } public func failWithError(message: String, statusCode:HTTPStatusCode = .internalServerError) { failWithError(failureResult: .messageWithStatus(message, statusCode)) } public func failWithError(failureResult: FailureResult) { setJsonResponseHeaders() let code: HTTPStatusCode var result: [String: Any] let errorKey = "error" let goneReasonKey = "goneReason" switch failureResult { case .message(let message): Log.error(message) code = .internalServerError result = [ errorKey: message ] case .messageWithStatus(let message, let statusCode): Log.error(message) code = statusCode result = [ errorKey: message ] case .goneWithReason(message: let message, let goneReason): code = .gone result = [ errorKey: message, goneReasonKey: goneReason.rawValue ] } self.response.statusCode = code self.endWith(clientResponse: .jsonDict(result)) } enum EndWithResponse { case jsonDict([String: Any]) case jsonString(String) case data(data:Data?, headers:[String:String]) case headers([String:String]) } private func endWith(clientResponse:EndWithResponse) { self.response.headers.append(ServerConstants.httpResponseCurrentServerVersion, value: Configuration.misc.deployedGitTag) if let minIOSClientVersion = Configuration.server.iOSMinimumClientVersion { self.response.headers.append( ServerConstants.httpResponseMinimumIOSClientAppVersion, value: minIOSClientVersion) } switch clientResponse { case .jsonString(let jsonString): self.response.send(jsonString) case .jsonDict(let jsonDict): if let jsonString = JSONExtras.toJSONString(dict: jsonDict) { self.response.send(jsonString) } else { let message = "Failed on json encode for jsonDict: \(jsonDict)" Log.error(message) self.response.statusCode = HTTPStatusCode.internalServerError self.response.send(message) } case .data(data: let data, headers: let headers): for (key, value) in headers { self.response.headers.append(key, value: value) } if data != nil { self.response.send(data: data!) } case .headers(let headers): for (key, value) in headers { self.response.headers.append(key, value: value) } } Log.info("REQUEST \(request.urlURL.path): ABOUT TO END ...") do { try self.response.end() Log.info("REQUEST \(request.urlURL.path): STATUS CODE: \(response.statusCode)") } catch (let error) { Log.error("Failed on `end` in endWith: \(error.localizedDescription); HTTP status code: \(response.statusCode)") } Log.info("REQUEST \(request.urlURL.path): COMPLETED") } func setJsonResponseHeaders() { self.response.headers["Content-Type"] = "application/json" } enum SuccessResult { case jsonString(String) case dataWithHeaders(Data?, headers:[String:String]) case headers([String:String]) case nothing } enum FailureResult { case message(String) case messageWithStatus(String, HTTPStatusCode) case goneWithReason(message: String, GoneReason) } enum ServerResult { case success(SuccessResult) case failure(FailureResult) } enum PermissionsResult { case success(sharingGroupUUID: String?) case failure } func handlePermissionsAndLocking(requestObject:RequestMessage) -> PermissionsResult { if let sharing = endpoint.sharing { // Endpoint uses sharing group. Must give sharingGroupUUID in request. guard let dict = requestObject.toDictionary, let sharingGroupUUID = dict[ServerEndpoint.sharingGroupUUIDKey] as? String else { self.failWithError(message: "Could not get sharing group uuid from request that uses sharing group: \(String(describing: requestObject.toDictionary))") return .failure } // The user is on the system. Whether or not they can perform the endpoint depends on their permissions for the sharing group. let key = SharingGroupUserRepository.LookupKey.primaryKeys(sharingGroupUUID: sharingGroupUUID, userId: currentSignedInUser!.userId) let result = repositories.sharingGroupUser.lookup(key: key, modelInit: SharingGroupUser.init) switch result { case .found(let model): let sharingGroupUser = model as! SharingGroupUser guard let userPermissions = sharingGroupUser.permission else { self.failWithError(message: "SharingGroupUser did not have permissions!") return .failure } if let minPermission = sharing.minPermission { guard userPermissions.hasMinimumPermission(minPermission) else { self.failWithError(message: "User did not meet minimum permissions -- needed: \(minPermission); had: \(userPermissions)!") return .failure } } case .noObjectFound: // One reason that the sharing group user might not be found is that the SharingGroupUser was removed from the system-- e.g., if an owning user is deleted, SharingGroupUser rows that have it as their owningUserId will be removed. // If a client fails with this error, it seems like some kind of client error or edge case where the client should have been updated already (i.e., from an Index endpoint call) so that it doesn't make such a request. Therefore, I'm not going to code a special case on the client to deal with this. self.failWithError(failureResult: .goneWithReason(message: "SharingGroupUser object not found!", .userRemoved)) return .failure case .error(let error): self.failWithError(message: error) return .failure } return .success(sharingGroupUUID: sharingGroupUUID) } return .success(sharingGroupUUID: nil) } // Starts a transaction, and calls the `dbOperations` closure. If the closure succeeds (no error), then commits the transaction. Otherwise, rolls it back. private func dbTransaction(_ db:Database, handleResult:@escaping (ServerResult) ->(), dbOperations:(_ callback: @escaping (ServerResult) ->())->()) { // 6/24/19; While I used to, I'm no longer including this in the transaction. This is because I can get a deadlock just on the insert of a record into the DeviceUUID table. The consequence of not including it in the transaction may include creating a db record even though the rest of the request fails. No biggie. Presumably the device would have made another successful request and the device record would get created in any event. Why not creat it now? if case .error(let errorMessage) = checkDeviceUUID() { handleResult(.failure(.message("Failed checkDeviceUUID: \(errorMessage)"))) return } if !db.startTransaction() { handleResult(.failure(.message("Could not start a transaction!"))) return } func dbTransactionHandleResult(_ result: ServerResult) { switch result { case .success(_): if !db.commit() { let message = "Error during COMMIT operation!" Log.error(message) handleResult(.failure(.message(message))) return } case .failure(_): if !db.rollback() { let message = "Error during ROLLBACK operation!" Log.error(message) handleResult(.failure(.message(message))) return } } handleResult(result) } dbOperations(dbTransactionHandleResult) } func doRequest(createRequest: @escaping (RouterRequest) -> RequestMessage?, processRequest: @escaping ProcessRequest) { setJsonResponseHeaders() let profile = request.userProfile self.deviceUUID = request.headers[ServerConstants.httpRequestDeviceUUID] Log.info("self.deviceUUID: \(String(describing: self.deviceUUID))") #if DEBUG if let profile = profile { let userId = profile.id let userName = profile.displayName Log.info("Profile: \(String(describing: profile)); userId: \(userId); userName: \(userName)") } #endif let db = Database() repositories = Repositories(db: db) accountDelegate = AccountDelegateHandler(userRepository: repositories.user) var accountProperties: AccountManager.AccountProperties? switch authenticationLevel! { case .none: break case .primary, .secondary: // Only do this if we are requiring primary or secondary authorization-- this gets account specific properties from the request, assuming we are using authorization. do { accountProperties = try AccountManager.session.getProperties(fromRequest: request) } catch (let error) { let message = "YIKES: could not get account properties from request: \(error)" Log.error(message) failWithError(message: message) return } } var dbCreds:Account? guard let requestObject = createRequest(request) else { self.failWithError(message: "Could not create request object from RouterRequest: \(String(describing: request))") return } var sharingGroupUUID: String? if authenticationLevel! == .secondary { // We have .secondary authentication-- i.e., we should have the user recorded in the database already. guard let accountProperties = accountProperties else { self.failWithError(message: "Could not get accountProperties.") return } let key = UserRepository.LookupKey.accountTypeInfo(accountType:accountProperties.accountScheme.accountName, credsId: profile!.id) let userLookup = self.repositories.user.lookup(key: key, modelInit: User.init) switch userLookup { case .found(let model): currentSignedInUser = (model as? User)! var errorString:String? do { dbCreds = try AccountManager.session.accountFromJSON(currentSignedInUser!.creds, accountName: currentSignedInUser!.accountType, user: .user(currentSignedInUser!), delegate: accountDelegate) } catch (let error) { errorString = "\(error)" } if errorString != nil || dbCreds == nil { self.failWithError(message: "Could not convert Creds of type: \(String(describing: currentSignedInUser!.accountType)) from JSON: \(String(describing: currentSignedInUser!.creds)); error: \(String(describing: errorString))") return } let result = handlePermissionsAndLocking(requestObject: requestObject) switch result { case .failure: return case .success(sharingGroupUUID: let sgid): sharingGroupUUID = sgid } case .noObjectFound: Log.error("User lookup key: \(key)") failWithError(message: "Failed on secondary authentication", statusCode: .unauthorized) return case .error(let error): failWithError(message: "Failed looking up user: \(key): \(error)", statusCode: .internalServerError) return } } #if DEBUG // Failure testing. if request.headers[ServerConstants.httpRequestEndpointFailureTestKey] != nil { self.failWithError(message: "Failure test requested by client.") return } #endif // 6/1/17; Up until this point, I had been (a) calling .end on the RouterResponse object, and (b) only after that committing the transaction (or rolling it back) on the database. However, that can generate some unwanted asynchronous processing. i.e., the network caller can potentially initiate another request *before* the database commit completes. Instead, I should be: (a) committing (or rolling back) the transaction, and then (b) calling .end. That should provide the synchronous character that I really want. if profile == nil { assert(authenticationLevel! == .none) dbTransaction(db, handleResult: handleTransactionResult) { handleResult in doRemainingRequestProcessing(dbCreds: nil, profileCreds:nil, requestObject: requestObject, db: db, profile: nil, accountProperties: nil, sharingGroupUUID: sharingGroupUUID, processRequest: processRequest, handleResult: handleResult) } } else { var credsUser:AccountCreationUser? switch authenticationLevel! { case .primary: // We don't have a userId yet for this user. break case .secondary: credsUser = .user(self.currentSignedInUser!) case .none: assertionFailure("Should never get here with authenticationLevel == .none!") } guard let accountProperties = accountProperties else { self.failWithError(message: "Do not have AccountProperties!s") return } if let profileCreds = AccountManager.session.accountFromProperties(properties: accountProperties, user: credsUser, delegate: accountDelegate) { dbTransaction(db, handleResult: handleTransactionResult) { handleResult in doRemainingRequestProcessing(dbCreds:dbCreds, profileCreds:profileCreds, requestObject: requestObject, db: db, profile: profile, accountProperties: accountProperties, sharingGroupUUID: sharingGroupUUID, processRequest: processRequest, handleResult: handleResult) } } else { handleTransactionResult(.failure(.messageWithStatus("Failed converting to Creds from profile", .unauthorized))) } } } private func handleTransactionResult(_ result:ServerResult) { // `endWith` and `failWithError` call the `RouterResponse` `end` method, and thus we have waited until the very end of processing of the request to finish and return control back to the caller. switch result { case .success(.jsonString(let jsonString)): endWith(clientResponse: .jsonString(jsonString)) case .success(.dataWithHeaders(let data, headers: let headers)): endWith(clientResponse: .data(data: data, headers: headers)) case .success(.headers(let headers)): endWith(clientResponse: .headers(headers)) case .success(.nothing): endWith(clientResponse: .jsonDict([:])) case .failure(let failureResult): failWithError(failureResult: failureResult) } } private func doRemainingRequestProcessing(dbCreds:Account?, profileCreds:Account?, requestObject:RequestMessage, db: Database, profile: UserProfile?, accountProperties: AccountManager.AccountProperties?, sharingGroupUUID: String?, processRequest: @escaping ProcessRequest, handleResult:@escaping (ServerResult) ->()) { var effectiveOwningUserCreds:Account? // For secondary authentication, we'll have a current signed in user. // Not treating a nil effectiveOwningUserId for the same reason as the `.noObjectFound` case below. if let user = currentSignedInUser, let sharingGroupUUID = sharingGroupUUID, case .found(let effectiveOwningUserId) = Controllers.getEffectiveOwningUserId(user: user, sharingGroupUUID: sharingGroupUUID, sharingGroupUserRepo: repositories.sharingGroupUser) { let effectiveOwningUserKey = UserRepository.LookupKey.userId(effectiveOwningUserId) Log.debug("effectiveOwningUserId: \(effectiveOwningUserId)") let userResults = repositories.user.lookup(key: effectiveOwningUserKey, modelInit: User.init) switch userResults { case .found(let model): guard let effectiveOwningUser = model as? User else { handleResult(.failure(.message("Could not convert effective owning user model to User."))) return } effectiveOwningUserCreds = effectiveOwningUser.credsObject guard effectiveOwningUserCreds != nil else { handleResult(.failure(.message("Could not get effective owning user creds."))) return } effectiveOwningUserCreds!.delegate = accountDelegate case .noObjectFound: // Not treating this as an error. Downstream from this, where needed, we check to see if effectiveOwningUserCreds is nil. See also [1] in Controllers.swift. Log.warning("No object found when trying to populate effectiveOwningUserCreds") case .error(let error): handleResult(.failure(.message(error))) return } } let params = RequestProcessingParameters(request: requestObject, ep:endpoint, creds: dbCreds, effectiveOwningUserCreds: effectiveOwningUserCreds, profileCreds: profileCreds, userProfile: profile, accountProperties: accountProperties, currentSignedInUser: currentSignedInUser, db:db, repos:repositories, routerResponse:response, deviceUUID: deviceUUID, accountDelegate: accountDelegate) { response in var message:ResponseMessage! switch response { case .success(let responseMessage): message = responseMessage case .failure(let failureResult): if let failureResult = failureResult { handleResult(.failure(failureResult)) } else { handleResult(.failure(.message("Could not create response object from request object"))) } return } guard let jsonString = message.jsonString else { handleResult(.failure(.message("Could not convert response message to a JSON string"))) return } switch message.responseType { case .json: handleResult(.success(.jsonString(jsonString))) case .data(let data): handleResult(.success(.dataWithHeaders(data, headers:[ServerConstants.httpResponseMessageParams:jsonString]))) case .header: handleResult(.success(.headers( [ServerConstants.httpResponseMessageParams:jsonString]))) } } // end: let params = RequestProcessingParameters // 7/16/17; Until today I had another large bug that was undetected. I was calling `processRequest` below assuming that request processing was being done *synchronously*, which was blatently untrue! This was causing `end` to be called for some requests prematurely. I've now made changes to use callbacks, and deal with the fact that asynchronous request processing is happening in many cases. processRequest(params) } // MARK: AccountDelegate enum CheckDeviceUUIDResult { case success case uuidNotNeeded case error(message: String) } private func checkDeviceUUID() -> CheckDeviceUUIDResult { switch authenticationLevel! { case .none: return .uuidNotNeeded case .primary, .secondary: if self.deviceUUID == nil { return .error(message: "Did not provide a Device UUID with header \(ServerConstants.httpRequestDeviceUUID)") } else if currentSignedInUser == nil && authenticationLevel == .primary { // If we don't have a signed in user, we can't search for existing deviceUUID's. But that's not an error. return .success } else { let key = DeviceUUIDRepository.LookupKey.deviceUUID(self.deviceUUID!) let result = repositories.deviceUUID.lookup(key: key, modelInit: DeviceUUID.init) switch result { case .error(let error): return .error(message: "Error looking up device UUID: \(error)") case .found(_): return .success case .noObjectFound: let newDeviceUUID = DeviceUUID(userId: currentSignedInUser!.userId, deviceUUID: self.deviceUUID!) let addResult = repositories.deviceUUID.add(deviceUUID: newDeviceUUID) switch addResult { case .error(let error): return .error(message: "Error adding new device UUID: \(error)") case .exceededMaximumUUIDsPerUser: return .error(message: "Exceeded maximum UUIDs per user: \(String(describing: repositories.deviceUUID.maximumNumberOfDeviceUUIDsPerUser))") case .success: return .success } } } } } } <file_sep>// // FileController+DownloadAppMetaData.swift // Server // // Created by <NAME> on 3/23/18. // import Foundation import LoggerAPI import SyncServerShared extension FileController { func downloadAppMetaData(params:RequestProcessingParameters) { guard let downloadAppMetaDataRequest = params.request as? DownloadAppMetaDataRequest else { let message = "Did not receive DownloadAppMetaDataRequest" Log.error(message) params.completion(.failure(.message(message))) return } guard sharingGroupSecurityCheck(sharingGroupUUID: downloadAppMetaDataRequest.sharingGroupUUID, params: params) else { let message = "Failed in sharing group security check." Log.error(message) params.completion(.failure(.message(message))) return } Controllers.getMasterVersion(sharingGroupUUID: downloadAppMetaDataRequest.sharingGroupUUID, params: params) { (error, masterVersion) in if error != nil { params.completion(.failure(.message("\(error!)"))) return } if masterVersion != downloadAppMetaDataRequest.masterVersion { let response = DownloadAppMetaDataResponse() Log.warning("Master version update: \(String(describing: masterVersion))") response.masterVersionUpdate = masterVersion params.completion(.success(response)) return } // Need to get the app meta data from the file index. // First, lookup the file in the FileIndex. This does an important security check too-- makes sure the fileUUID is in the sharing group. let key = FileIndexRepository.LookupKey.primaryKeys(sharingGroupUUID: downloadAppMetaDataRequest.sharingGroupUUID, fileUUID: downloadAppMetaDataRequest.fileUUID) let lookupResult = params.repos.fileIndex.lookup(key: key, modelInit: FileIndex.init) var fileIndexObj:FileIndex! switch lookupResult { case .found(let modelObj): fileIndexObj = modelObj as? FileIndex if fileIndexObj == nil { let message = "Could not convert model object to FileIndex" Log.error(message) params.completion(.failure(.message(message))) return } case .noObjectFound: let message = "Could not find file in FileIndex" Log.error(message) params.completion(.failure(.message(message))) return case .error(let error): let message = "Error looking up file in FileIndex: \(error)" Log.error(message) params.completion(.failure(.message(message))) return } if fileIndexObj!.deleted! { let message = "The file you are trying to download app meta data for has been deleted!" Log.error(message) params.completion(.failure(.message(message))) return } guard let fileIndexAppMetaDataVersion = fileIndexObj.appMetaDataVersion else { let message = "Nil app meta data version in FileIndex." Log.error(message) params.completion(.failure(.message(message))) return } guard downloadAppMetaDataRequest.appMetaDataVersion == fileIndexAppMetaDataVersion else { let message = "Expected app meta data version \(String(describing: downloadAppMetaDataRequest.appMetaDataVersion)) was not the same as the actual version \(fileIndexAppMetaDataVersion)" Log.error(message) params.completion(.failure(.message(message))) return } let response = DownloadAppMetaDataResponse() response.appMetaData = fileIndexObj.appMetaData params.completion(.success(response)) } } } <file_sep>// swift-tools-version:5.0 import PackageDescription let package = Package( name: "Server", dependencies: [ //.package(url: "https://github.com/crspybits/SwiftyAWSSNS.git", .branch("master")), .package(url: "https://github.com/crspybits/SwiftyAWSSNS.git", .upToNextMajor(from: "0.3.0")), // 7/2/17; See comment in SwiftMain with the same date. // .Package(url: "https://github.com/RuntimeTools/SwiftMetrics.git", majorVersion: 1, minor: 2), // .package(url: "../../repos/SyncServer-Shared", .branch("dev")), // .package(url: "https://github.com/crspybits/SyncServer-Shared.git", .branch("dev")), .package(url: "https://github.com/crspybits/SyncServer-Shared.git", .upToNextMajor(from: "11.1.0")), // .package(url: "../../repos/Perfect-MySQL", .branch("master")), // .package(url:"https://github.com/crspybits/Perfect-MySQL.git", from: "3.1.3"), .package(url:"https://github.com/PerfectlySoft/Perfect-MySQL.git", .upToNextMajor(from: "3.4.1")), .package(url: "https://github.com/PerfectlySoft/Perfect.git", .upToNextMajor(from: "3.1.4")), .package(url: "https://github.com/PerfectlySoft/Perfect-Thread.git", .upToNextMajor(from: "3.0.6")), .package(url: "https://github.com/IBM-Swift/Kitura.git", .upToNextMajor(from: "2.7.0")), .package(url: "https://github.com/IBM-Swift/Swift-JWT.git", from: "3.5.3"), .package(url: "https://github.com/IBM-Swift/Kitura-Credentials.git", .upToNextMajor(from: "2.4.1")), .package(url: "https://github.com/IBM-Swift/Kitura-CredentialsFacebook.git", .upToNextMajor(from: "2.3.1")), .package(url: "https://github.com/IBM-Swift/Kitura-CredentialsGoogle.git", .upToNextMajor(from: "2.3.1")), // .package(url: "../../repos/CredentialsDropbox", .branch("master")), .package(url: "https://github.com/crspybits/CredentialsDropbox.git", .upToNextMajor(from: "0.4.0")), // .package(url: "https://github.com/crspybits/CredentialsMicrosoft.git", .branch("master")), .package(url: "https://github.com/crspybits/CredentialsMicrosoft.git", from: "0.1.0"), .package(url: "https://github.com/crspybits/CredentialsAppleSignIn.git", .branch("master")), // .package(url: "https://github.com/crspybits/CredentialsAppleSignIn.git", from: "0.1.0"), .package(url: "https://github.com/IBM-Swift/HeliumLogger.git", .upToNextMajor(from: "1.8.1")) ], targets: [ .target(name: "Main", dependencies: ["Server"]), .target(name: "Server", dependencies: ["SyncServerShared", "Credentials", "CredentialsGoogle", "PerfectThread", "PerfectMySQL", "HeliumLogger", "CredentialsFacebook", "CredentialsDropbox", "Kitura", "PerfectLib", "SwiftyAWSSNS", "CredentialsMicrosoft", "CredentialsAppleSignIn", "SwiftJWT"]), .testTarget(name: "ServerTests", dependencies: ["Server", "Main", "CredentialsDropbox"]) ] ) <file_sep>// // MicrosoftCreds.swift // Server // // Created by <NAME> on 9/1/19. // import Foundation import Kitura import SyncServerShared import LoggerAPI import HeliumLogger import KituraNet // Assumes that the microsft app has been registered as multi-tenant. E.g., see https://docs.microsoft.com/en-us/graph/auth-register-app-v2?context=graph%2Fapi%2F1.0&view=graph-rest-1.0 // Originally, I thought I had to register two apps (a server and a client)-- E.g., https://paulryan.com.au/2017/oauth-on-behalf-of-flow-adal/ HOWEVER, I have only a client iOS app registered (and using that client id and secret) and thats working. class MicrosoftCreds : AccountAPICall, Account { static var accountScheme: AccountScheme = .microsoft var accountScheme: AccountScheme { return MicrosoftCreds.accountScheme } var owningAccountsNeedCloudFolderName: Bool = false var delegate: AccountDelegate? var accountCreationUser: AccountCreationUser? // Don't use the "accessToken" from the iOS MSAL for this; use the iOS MSAL idToken. var accessToken: String! var refreshToken: String? private var alreadyRefreshed = false private let scopes = "https://graph.microsoft.com/user.read+offline_access" override init?() { super.init() baseURL = "login.microsoftonline.com/common" } func needToGenerateTokens(dbCreds: Account?) -> Bool { // If we get fancy, eventually we could look at the expiry date/time in the JWT access token and estimate if we need to generate tokens. return true } enum MicrosoftError: Swift.Error { case noAccessToken case failedGettingClientIdOrSecret case badStatusCode(HTTPStatusCode?) case nilAPIResult case noDataInResult case couldNotDecodeTokens case errorSavingCredsToDatabase case noRefreshToken } struct MicrosoftTokens: Decodable { let token_type: String let scope: String let expires_in: Int let ext_expires_in: Int let access_token: String let refresh_token: String } private struct ClientInfo { let id: String let secret: String } func encoded(string: String, baseCharSet: CharacterSet = .urlQueryAllowed, additionalExcludedCharacters: String? = nil) -> String? { var charSet: CharacterSet = baseCharSet if let additionalExcludedCharacters = additionalExcludedCharacters { for char in additionalExcludedCharacters { if let scalar = char.unicodeScalars.first { charSet.remove(scalar) } } } return string.addingPercentEncoding(withAllowedCharacters: charSet) } private func getClientInfo() -> ClientInfo? { guard let clientId = Configuration.server.MicrosoftClientId, let clientSecret = Configuration.server.MicrosoftClientSecret else { Log.error("No client id or secret.") return nil } // Encode the secret-- without this, my call fails with: // AADSTS7000215: Invalid client secret is provided. // See https://stackoverflow.com/questions/41133573/microsoft-graph-rest-api-invalid-client-secret guard let clientSecretEncoded = encoded(string: clientSecret, additionalExcludedCharacters: ",/?:@&=+$#") else { Log.error("Failed encoding client secret.") return nil } return ClientInfo(id: clientId, secret: clientSecretEncoded) } /// If successful, sets the `refreshToken`. The `accessToken` must be set prior to this call. The access token, when used from the iOS MSAL library, must be the "idToken" and not the iOS MSAL "accessToken". The accessToken from the iOS MSAL library is not a JWT -- when I use it I get: "AADSTS50027: JWT token is invalid or malformed". func generateTokens(response: RouterResponse?, completion:@escaping (Swift.Error?)->()) { guard let accessToken = accessToken else{ Log.info("No accessToken from client.") completion(MicrosoftError.noAccessToken) return } guard let clientInfo = getClientInfo() else { completion(MicrosoftError.failedGettingClientIdOrSecret) return } // https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow let grantType = "urn:ietf:params:oauth:grant-type:jwt-bearer" let scopes = "https://graph.microsoft.com/user.read+offline_access" let bodyParameters = "grant_type=\(grantType)" + "&" + "client_id=\(clientInfo.id)" + "&" + "client_secret=\(clientInfo.secret)" + "&" + "assertion=\(accessToken)" + "&" + "scope=\(scopes)" + "&" + "requested_token_use=on_behalf_of" // Log.debug("bodyParameters: \(bodyParameters)") let additionalHeaders = ["Content-Type": "application/x-www-form-urlencoded"] self.apiCall(method: "POST", path: "/oauth2/v2.0/token", additionalHeaders:additionalHeaders, body: .string(bodyParameters), expectedSuccessBody: .data) { apiResult, statusCode, responseHeaders in guard statusCode == HTTPStatusCode.OK else { completion(MicrosoftError.badStatusCode(statusCode)) return } guard let apiResult = apiResult else { completion(MicrosoftError.nilAPIResult) return } guard case .data(let data) = apiResult else { completion(MicrosoftError.noDataInResult) return } let tokens: MicrosoftTokens let decoder = JSONDecoder() do { tokens = try decoder.decode(MicrosoftTokens.self, from: data) } catch let error { Log.error("Error decoding token result: \(error)") completion(MicrosoftError.couldNotDecodeTokens) return } self.accessToken = tokens.access_token self.refreshToken = tokens.refresh_token guard let delegate = self.delegate else { Log.warning("No Microsoft Creds delegate!") completion(nil) return } if delegate.saveToDatabase(account: self) { completion(nil) } else { completion(MicrosoftError.errorSavingCredsToDatabase) } } } // Use the refresh token to generate a new access token. // If error is nil when the completion handler is called, then the accessToken of this object has been refreshed. Uses delegate, if one is defined, to save refreshed creds to database. func refresh(completion:@escaping (Swift.Error?)->()) { // https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow guard let refreshToken = refreshToken else { completion(MicrosoftError.noRefreshToken) return } guard let clientInfo = getClientInfo() else { completion(MicrosoftError.failedGettingClientIdOrSecret) return } let grantType = "refresh_token" let bodyParameters = "grant_type=\(grantType)" + "&" + "client_id=\(clientInfo.id)" + "&" + "client_secret=\(clientInfo.secret)" + "&" + "scope=\(scopes)" + "&" + "refresh_token=\(refreshToken)" // Log.debug("bodyParameters: \(bodyParameters)") let additionalHeaders = ["Content-Type": "application/x-www-form-urlencoded"] self.apiCall(method: "POST", path: "/oauth2/v2.0/token", additionalHeaders:additionalHeaders, body: .string(bodyParameters), expectedSuccessBody: .data, expectedFailureBody: .json) { apiResult, statusCode, responseHeaders in guard statusCode == HTTPStatusCode.OK else { Log.error("Bad status code: \(String(describing: statusCode))") completion(MicrosoftError.badStatusCode(statusCode)) return } guard let apiResult = apiResult else { Log.error("API result was nil!") completion(MicrosoftError.nilAPIResult) return } guard case .data(let data) = apiResult else { completion(MicrosoftError.noDataInResult) return } let tokens: MicrosoftTokens let decoder = JSONDecoder() do { tokens = try decoder.decode(MicrosoftTokens.self, from: data) } catch let error { Log.error("Error decoding token result: \(error)") completion(MicrosoftError.couldNotDecodeTokens) return } // Log.debug("tokens.access_token: \(tokens.access_token)") self.accessToken = tokens.access_token self.refreshToken = tokens.refresh_token guard let delegate = self.delegate else { Log.warning("No Microsoft Creds delegate!") completion(nil) return } if delegate.saveToDatabase(account: self) { completion(nil) } else { completion(MicrosoftError.errorSavingCredsToDatabase) } } } func merge(withNewer account: Account) { guard let newerCreds = account as? MicrosoftCreds else { assertionFailure("Wrong other type of creds!") return } if let refreshToken = newerCreds.refreshToken { self.refreshToken = refreshToken } if let accessToken = newerCreds.accessToken { self.accessToken = accessToken } } static func getProperties(fromRequest request:RouterRequest) -> [String: Any] { var result = [String: Any]() if let accessToken = request.headers[ServerConstants.HTTPOAuth2AccessTokenKey] { result[ServerConstants.HTTPOAuth2AccessTokenKey] = accessToken } return result } static func fromProperties(_ properties: AccountManager.AccountProperties, user:AccountCreationUser?, delegate:AccountDelegate?) -> Account? { guard let creds = MicrosoftCreds() else { return nil } creds.accountCreationUser = user creds.delegate = delegate creds.accessToken = properties.properties[ServerConstants.HTTPOAuth2AccessTokenKey] as? String return creds } func toJSON() -> String? { var jsonDict = [String:String]() jsonDict[MicrosoftCreds.accessTokenKey] = self.accessToken jsonDict[MicrosoftCreds.refreshTokenKey] = self.refreshToken return JSONExtras.toJSONString(dict: jsonDict) } static func fromJSON(_ json: String, user: AccountCreationUser, delegate: AccountDelegate?) throws -> Account? { guard let jsonDict = json.toJSONDictionary() as? [String:String] else { Log.error("Could not convert string to JSON [String:String]: \(json)") return nil } guard let result = MicrosoftCreds() else { return nil } result.delegate = delegate result.accountCreationUser = user switch user { case .user(let user) where AccountScheme(.accountName(user.accountType))?.userType == .owning: fallthrough case .userId: try setProperty(jsonDict:jsonDict, key: accessTokenKey) { value in result.accessToken = value } default: // Sharing users not allowed. assert(false) } try setProperty(jsonDict:jsonDict, key: refreshTokenKey, required:false) { value in result.refreshToken = value } return result } override func apiCall(method:String, baseURL:String? = nil, path:String, additionalHeaders: [String:String]? = nil, additionalOptions: [ClientRequest.Options] = [], urlParameters:String? = nil, body:APICallBody? = nil, returnResultWhenNon200Code:Bool = true, expectedSuccessBody:ExpectedResponse? = nil, expectedFailureBody:ExpectedResponse? = nil, completion:@escaping (_ result: APICallResult?, HTTPStatusCode?, _ responseHeaders: HeadersContainer?)->()) { super.apiCall(method: method, baseURL: baseURL, path: path, additionalHeaders: additionalHeaders, additionalOptions: additionalOptions, urlParameters: urlParameters, body: body, returnResultWhenNon200Code: returnResultWhenNon200Code, expectedSuccessBody: expectedSuccessBody, expectedFailureBody: expectedFailureBody) { (apiCallResult, statusCode, responseHeaders) in var headers:[String:String] = additionalHeaders ?? [:] if self.expiredAccessToken(apiResult: apiCallResult, statusCode: statusCode) && !self.alreadyRefreshed { self.alreadyRefreshed = true Log.info("Attempting to refresh Microsoft access token...") self.refresh() { error in if let error = error { let message = "Failed refreshing access token: \(error)" let errorResult = ErrorResult(error: MicrosoftCreds.ErrorResult.TheError(code: MicrosoftCreds.ErrorResult.invalidAuthToken, message: message)) let encoder = JSONEncoder() guard let response = try? encoder.encode(errorResult) else { completion( APICallResult.dictionary(["error": message]), .unauthorized, nil) return } Log.error("\(message)") completion(APICallResult.data(response), .unauthorized, nil) } else { Log.info("Successfully refreshed access token!") // Refresh was successful, update the authorization header and try the operation again. headers["Authorization"] = "Bearer \(self.accessToken!)" super.apiCall(method: method, baseURL: baseURL, path: path, additionalHeaders: headers, additionalOptions: additionalOptions, urlParameters: urlParameters, body: body, returnResultWhenNon200Code: returnResultWhenNon200Code, expectedSuccessBody: expectedSuccessBody, expectedFailureBody: expectedFailureBody, completion: completion) } } } else { completion(apiCallResult, statusCode, responseHeaders) } } } private func expiredAccessToken(apiResult: APICallResult?, statusCode: HTTPStatusCode?) -> Bool { guard let apiResult = apiResult else { return false } guard case .data(let data) = apiResult else { return false } let decoder = JSONDecoder() guard let errorResult = try? decoder.decode(ErrorResult.self, from: data) else { return false } return self.accessTokenIsRevokedOrExpired(errorResult: errorResult, statusCode: statusCode) } } <file_sep>// // UserController.swift // Server // // Created by <NAME> on 12/6/16. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class UserControllerTests: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() } func testAddUserSucceedsWhenAddingNewUser() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = UUID().uuidString let testAccount:TestAccount = .primaryOwningAccount guard let addUserResponse = addNewUser(testAccount:testAccount, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } XCTAssert(addUserResponse.userId != nil) let result = UserRepository(self.db).lookup(key: .userId(addUserResponse.userId), modelInit: User.init) switch result { case .error(let error): XCTFail("\(error)") case .found(let object): let user = object as! User // Make sure that the database has a cloud folder name-- but only if that account type needs it. if TestAccount.needsCloudFolder(testAccount) { XCTAssert(user.cloudFolderName == ServerTestCase.cloudFolderName) } case .noObjectFound: XCTFail("No User Found") } // Make sure the initial file was created in users cloud storage, if one is configured. if let fileName = Configuration.server.owningUserAccountCreation.initialFileName { let options = CloudStorageFileNameOptions(cloudFolderName: ServerTestCase.cloudFolderName, mimeType: "text/plain") self.lookupFile(forOwningTestAccount: testAccount, cloudFileName: fileName, options: options) } } func testAddUserWithSharingGroupNameWorks() { let sharingGroupUUID = UUID().uuidString let deviceUUID = Foundation.UUID().uuidString let testAccount:TestAccount = .primaryOwningAccount let sharingGroupName = "SharingGroup765" guard let _ = addNewUser(testAccount:testAccount, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID, sharingGroupName:sharingGroupName) else { XCTFail() return } guard let (_, sharingGroups) = getIndex() else { XCTFail() return } guard sharingGroups.count == 1 else { XCTFail() return } XCTAssert(sharingGroups[0].sharingGroupUUID == sharingGroupUUID) XCTAssert(sharingGroups[0].sharingGroupName == sharingGroupName) XCTAssert(sharingGroups[0].deleted == false) } func testAddUserFailsWhenAddingExistingUser() { let sharingGroupUUID = UUID().uuidString let deviceUUID = Foundation.UUID().uuidString self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) performServerTest { expectation, creds in let headers = self.setupHeaders(testUser: .primaryOwningAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.addUser, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .internalServerError, "Worked on addUser request") expectation.fulfill() } } } // Purpose is to check if second add user fails because the initial file is there. func testAddRemoveAddWorks() { let deviceUUID = Foundation.UUID().uuidString let testAccount:TestAccount = .primaryOwningAccount let sharingGroupUUID1 = UUID().uuidString addNewUser(testAccount:testAccount, sharingGroupUUID: sharingGroupUUID1, deviceUUID:deviceUUID) // remove performServerTest { expectation, creds in let headers = self.setupHeaders(testUser: testAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.removeUser, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "removeUser failed") expectation.fulfill() } } let sharingGroupUUID2 = UUID().uuidString addNewUser(testAccount:testAccount, sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID) } func testCheckCredsWhenUserDoesExist() { let testingAccount:TestAccount = .primaryOwningAccount let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = UUID().uuidString self.addNewUser(testAccount: testingAccount, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) performServerTest(testAccount: testingAccount) { expectation, creds in let headers = self.setupHeaders(testUser: testingAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkCreds, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "checkCreds failed") if let dict = dict, let checkCredsResponse = try? CheckCredsResponse.decode(dict) { XCTAssert(checkCredsResponse.userId != nil) } else { XCTFail() } expectation.fulfill() } } } func testCheckCredsWhenUserDoesNotExist() { let deviceUUID = Foundation.UUID().uuidString performServerTest { expectation, creds in let headers = self.setupHeaders(testUser: .primaryOwningAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkCreds, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .unauthorized, "checkCreds failed") expectation.fulfill() } } } func testCheckCredsWithBadAccessToken() { let deviceUUID = Foundation.UUID().uuidString performServerTest { expectation, creds in let headers = self.setupHeaders(testUser: .primaryOwningAccount, accessToken: "Some junk for access token", deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.checkCreds, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .unauthorized, "checkCreds failed") expectation.fulfill() } } } func testRemoveUserFailsWithNonExistingUser() { let deviceUUID = Foundation.UUID().uuidString // Don't create the user first. performServerTest { expectation, creds in let headers = self.setupHeaders(testUser: .primaryOwningAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.removeUser, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .unauthorized, "removeUser did not fail") expectation.fulfill() } } } func testRemoveUserSucceedsWithExistingUser() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) performServerTest { expectation, creds in let headers = self.setupHeaders(testUser: .primaryOwningAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.removeUser, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "removeUser failed") expectation.fulfill() } } // Confirm that user doesn't exist any more testCheckCredsWhenUserDoesNotExist() } func testThatFilesUploadedByUserMarkedAsDeletedWhenUserRemoved() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } // Upload a file. guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID)) else { XCTFail() return } self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, sharingGroupUUID: sharingGroupUUID) // Remove the user performServerTest { expectation, creds in let headers = self.setupHeaders(testUser: .primaryOwningAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.removeUser, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "removeUser failed") expectation.fulfill() } } // Make sure file was deleted. let fileIndexResult = FileIndexRepository(db).fileIndex(forSharingGroupUUID: sharingGroupUUID) switch fileIndexResult { case .fileIndex(let fileIndex): // We don't get any file index rows for this user with the sharing group when the user was deleted. guard fileIndex.count == 0 else { XCTFail("fileIndex.count: \(fileIndex.count)") return } case .error(_): XCTFail() } let key = FileIndexRepository.LookupKey.primaryKeys(sharingGroupUUID: sharingGroupUUID, fileUUID: uploadResult.request.fileUUID) let result = FileIndexRepository(db).lookup(key: key, modelInit: FileIndex.init) switch result { case .found(let obj): guard let fileIndexObj = obj as? FileIndex else { XCTFail() return } XCTAssert(fileIndexObj.deleted == true) default: XCTFail() return } } } extension UserControllerTests { static var allTests : [(String, (UserControllerTests) -> () throws -> Void)] { return [ ("testAddUserSucceedsWhenAddingNewUser", testAddUserSucceedsWhenAddingNewUser), ("testAddUserFailsWhenAddingExistingUser", testAddUserFailsWhenAddingExistingUser), ("testAddRemoveAddWorks", testAddRemoveAddWorks), ("testCheckCredsWhenUserDoesExist", testCheckCredsWhenUserDoesExist), ("testCheckCredsWhenUserDoesNotExist", testCheckCredsWhenUserDoesNotExist), ("testCheckCredsWithBadAccessToken", testCheckCredsWithBadAccessToken), ("testRemoveUserFailsWithNonExistingUser", testRemoveUserFailsWithNonExistingUser), ("testRemoveUserSucceedsWithExistingUser", testRemoveUserSucceedsWithExistingUser), ("testThatFilesUploadedByUserMarkedAsDeletedWhenUserRemoved", testThatFilesUploadedByUserMarkedAsDeletedWhenUserRemoved), ("testAddUserWithSharingGroupNameWorks", testAddUserWithSharingGroupNameWorks) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: UserControllerTests.self) } } <file_sep>USE SyncServer_SharedImages; # USE SharedImages_Staging; ALTER TABLE Upload MODIFY fileVersion INT; ALTER TABLE Upload ADD appMetaDataVersion INT; ALTER TABLE FileIndex ADD appMetaDataVersion INT; UPDATE FileIndex SET appMetaDataVersion = 0 WHERE appMetaData IS NOT NULL;<file_sep>3/13/19 This is really v2 of the sharedimages-production server. With the name change to "Neebla". Once I get the v2 server going, and deprecate its iOS app, I'll shut the old server down.<file_sep>import XCTest @testable import ServerTests XCTMain([ testCase(HealthCheckTests.allTests), testCase(AccountAuthenticationTests_Dropbox.allTests), testCase(AccountAuthenticationTests_Facebook.allTests), testCase(AccountAuthenticationTests_Google.allTests), testCase(DatabaseModelTests.allTests), testCase(FailureTests.allTests), testCase(FileController_DoneUploadsTests.allTests), testCase(FileController_UploadTests.allTests), testCase(FileControllerTests.allTests), testCase(FileControllerTests_GetUploads.allTests), testCase(FileControllerTests_UploadDeletion.allTests), testCase(FileController_MultiVersionFiles.allTests), testCase(GeneralAuthTests.allTests), testCase(GeneralDatabaseTests.allTests), testCase(GoogleDriveTests.allTests), testCase(FileDropboxTests.allTests), testCase(MessageTests.allTests), testCase(Sharing_FileManipulationTests.allTests), testCase(SharingAccountsController_CreateSharingInvitation.allTests), testCase(SharingAccountsController_RedeemSharingInvitation.allTests), testCase(SpecificDatabaseTests.allTests), testCase(SpecificDatabaseTests_SharingInvitationRepository.allTests), testCase(SpecificDatabaseTests_Uploads.allTests), testCase(SpecificDatabaseTests_UserRepository.allTests), testCase(UserControllerTests.allTests), testCase(VersionTests.allTests), testCase(FileController_DownloadAppMetaDataTests.allTests), testCase(FileController_UploadAppMetaDataTests.allTests), testCase(FileController_FileGroupUUIDTests.allTests), testCase(SpecificDatabaseTests_SharingGroups.allTests), testCase(SpecificDatabaseTests_SharingGroupUsers.allTests), testCase(SharingGroupsControllerTests.allTests), testCase(SharingAccountsController_GetSharingInvitationInfo.allTests), testCase(MockStorageTests.allTests), testCase(MockStorageLiveTests.allTests), testCase(AccountAuthenticationTests_Microsoft.allTests), testCase(FileMicrosoftOneDriveTests.allTests) ]) <file_sep>// // CreateRoutes.swift // Server // // Created by <NAME> on 6/2/17. // // import Foundation import Kitura import SyncServerShared import LoggerAPI class CreateRoutes { private var router = Router() init() { } func addRoute(ep:ServerEndpoint, processRequest: @escaping ProcessRequest) { func handleRequest(routerRequest:RouterRequest, routerResponse:RouterResponse) { Log.info("parsedURL: \(routerRequest.parsedURL)") let handler = RequestHandler(request: routerRequest, response: routerResponse, endpoint:ep) func create(routerRequest: RouterRequest) -> RequestMessage? { let queryDict = routerRequest.queryParameters guard let request = try? ep.requestMessageType.decode(queryDict) else { Log.error("Error doing request decode") return nil } do { try request.setup(request: routerRequest) } catch (let error) { Log.error("Error doing request setup: \(error)") return nil } guard request.valid() else { Log.error("Error: Request is not valid.") return nil } return request } handler.doRequest(createRequest: create, processRequest: processRequest) } switch (ep.method) { case .get: self.router.get(ep.pathWithSuffixSlash) { routerRequest, routerResponse, _ in handleRequest(routerRequest: routerRequest, routerResponse: routerResponse) } case .post: self.router.post(ep.pathWithSuffixSlash) { routerRequest, routerResponse, _ in handleRequest(routerRequest: routerRequest, routerResponse: routerResponse) } case .patch: self.router.patch(ep.pathWithSuffixSlash) { routerRequest, routerResponse, _ in handleRequest(routerRequest: routerRequest, routerResponse: routerResponse) } case .delete: self.router.delete(ep.pathWithSuffixSlash) { routerRequest, routerResponse, _ in handleRequest(routerRequest: routerRequest, routerResponse: routerResponse) } } } func getRoutes() -> Router { ServerSetup.credentials(self.router) ServerRoutes.add(proxyRouter: self) self.router.error { request, response, _ in let handler = RequestHandler(request: request, response: response) let errorDescription: String if let error = response.error { errorDescription = "\(error)" } else { errorDescription = "Unknown error" } let message = "Server error: \(errorDescription)" handler.failWithError(message: message) } self.router.all { request, response, _ in let handler = RequestHandler(request: request, response: response) let message = "Route not found in server: \(request.originalURL)" response.statusCode = .notFound handler.failWithError(message: message) } return self.router } } <file_sep>// // TestAccounts.swift // ServerTests // // Created by <NAME> on 12/17/17. // import Foundation import SyncServerShared @testable import Server import LoggerAPI import HeliumLogger import XCTest func ==(lhs: TestAccount, rhs:TestAccount) -> Bool { return lhs.tokenKey == rhs.tokenKey && lhs.idKey == rhs.idKey } struct TestAccount { let tokenKey:KeyPath<TestConfiguration, String> // key values: e.g., Google: a refresh token; Facebook:long-lived access token. // For Microsoft, their idToken let secondTokenKey:KeyPath<TestConfiguration, String>? let idKey:KeyPath<TestConfiguration, String> let scheme: AccountScheme // tokenKey: \.DropboxAccessTokenRevoked, idKey: \.DropboxId3, scheme: .dropbox init(tokenKey:KeyPath<TestConfiguration, String>, secondTokenKey:KeyPath<TestConfiguration, String>? = nil, idKey:KeyPath<TestConfiguration, String>, scheme: AccountScheme) { self.tokenKey = tokenKey self.secondTokenKey = secondTokenKey self.idKey = idKey self.scheme = scheme } // The main owning account on which tests are conducted. #if PRIMARY_OWNING_GOOGLE1 static let primaryOwningAccount:TestAccount = .google1 #elseif PRIMARY_OWNING_DROPBOX1 static let primaryOwningAccount:TestAccount = .dropbox1 #elseif PRIMARY_OWNING_MICROSOFT1 static let primaryOwningAccount:TestAccount = .microsoft1 #else static let primaryOwningAccount:TestAccount = .google1 #endif // Secondary owning account-- must be different than primary. #if SECONDARY_OWNING_GOOGLE2 static let secondaryOwningAccount:TestAccount = .google2 #elseif SECONDARY_OWNING_DROPBOX2 static let secondaryOwningAccount:TestAccount = .dropbox2 #elseif SECONDARY_OWNING_MICROSOFT2 static let secondaryOwningAccount:TestAccount = .microsoft2 #else static let secondaryOwningAccount:TestAccount = .google2 #endif // Main account, for sharing, on which tests are conducted. It should be a different specific account than primaryOwningAccount. #if PRIMARY_SHARING_GOOGLE2 static let primarySharingAccount:TestAccount = .google2 #elseif PRIMARY_SHARING_FACEBOOK1 static let primarySharingAccount:TestAccount = .facebook1 #elseif PRIMARY_SHARING_DROPBOX2 static let primarySharingAccount:TestAccount = .dropbox2 #elseif PRIMARY_SHARING_MICROSOFT2 static let primarySharingAccount:TestAccount = .microsoft2 #else static let primarySharingAccount:TestAccount = .google2 #endif // Another sharing account -- different than the primary owning, and primary sharing accounts. #if SECONDARY_SHARING_GOOGLE3 static let secondarySharingAccount:TestAccount = .google3 #elseif SECONDARY_SHARING_FACEBOOK2 static let secondarySharingAccount:TestAccount = .facebook2 #else static let secondarySharingAccount:TestAccount = .google3 #endif static let nonOwningSharingAccount:TestAccount = .facebook1 static let google1 = TestAccount(tokenKey: \.GoogleRefreshToken, idKey: \.GoogleSub, scheme: AccountScheme.google) static let google2 = TestAccount(tokenKey: \.GoogleRefreshToken2, idKey: \.GoogleSub2, scheme: AccountScheme.google) static let google3 = TestAccount(tokenKey: \.GoogleRefreshToken3, idKey: \.GoogleSub3, scheme: .google) // https://myaccount.google.com/permissions?pli=1 static let googleRevoked = TestAccount(tokenKey: \.GoogleRefreshTokenRevoked, idKey: \.GoogleSub4, scheme: .google) static func isGoogle(_ account: TestAccount) -> Bool { return account.scheme == AccountScheme.google } static func needsCloudFolder(_ account: TestAccount) -> Bool { return account.scheme == AccountScheme.google } static let facebook1 = TestAccount(tokenKey: \.FacebookLongLivedToken1, idKey: \.FacebookId1, scheme: .facebook) static let facebook2 = TestAccount(tokenKey: \.FacebookLongLivedToken2, idKey: \.FacebookId2, scheme: .facebook) static let dropbox1 = TestAccount(tokenKey: \.DropboxAccessToken1, idKey: \.DropboxId1, scheme: .dropbox) static let dropbox2 = TestAccount(tokenKey: \.DropboxAccessToken2, idKey: \.DropboxId2, scheme: .dropbox) static let dropbox1Revoked = TestAccount(tokenKey: \.DropboxAccessTokenRevoked, idKey: \.DropboxId3, scheme: .dropbox) // All valid Microsoft TestAccounts are going to have secondTokens that are idTokens static let microsoft1 = TestAccount(tokenKey: \.microsoft1.refreshToken, secondTokenKey: \.microsoft1.idToken, idKey: \.microsoft1.id, scheme: .microsoft) static let microsoft2 = TestAccount(tokenKey: \.microsoft2.refreshToken, secondTokenKey: \.microsoft2.idToken, idKey: \.microsoft2.id, scheme: .microsoft) static let apple1 = TestAccount(tokenKey: \.apple1.refreshToken, secondTokenKey: \.apple1.authorizationCode, idKey: \.apple1.idToken, scheme: .appleSignIn) static let microsoft1ExpiredAccessToken = TestAccount(tokenKey: \.microsoft1ExpiredAccessToken.refreshToken, secondTokenKey: \.microsoft1ExpiredAccessToken.accessToken, idKey: \.microsoft1ExpiredAccessToken.id, scheme: .microsoft) static let microsoft2RevokedAccessToken = TestAccount(tokenKey: \.microsoft2RevokedAccessToken.refreshToken, secondTokenKey: \.microsoft2RevokedAccessToken.accessToken, idKey: \.microsoft2RevokedAccessToken.id, scheme: .microsoft) func token() -> String { return Configuration.test![keyPath: tokenKey] } func secondToken() -> String? { guard let secondTokenKey = secondTokenKey else { return nil } return Configuration.test![keyPath: secondTokenKey] } func id() -> String { return Configuration.test![keyPath: idKey] } static func registerHandlers() { // MARK: Google AccountScheme.google.registerHandler(type: .getCredentials) { testAccount, callback in CredsCache.credsFor(googleAccount: testAccount) { creds in callback(creds) } } // MARK: Dropbox AccountScheme.dropbox.registerHandler(type: .getCredentials) { testAccount, callback in let creds = DropboxCreds()! creds.accessToken = testAccount.token() creds.accountId = testAccount.id() callback(creds) } // MARK: Facebook AccountScheme.facebook.registerHandler(type: .getCredentials) { testAccount, callback in let creds = FacebookCreds()! creds.accessToken = testAccount.token() callback(creds) } // MARK: Microsoft AccountScheme.microsoft.registerHandler(type: .getCredentials) { testAccount, callback in CredsCache.credsFor(microsoftAccount: testAccount) { creds in callback(creds) } } } } typealias Handler = (TestAccount, @escaping (Account)->())->() private var handlers = [String: Handler]() extension AccountScheme { enum HandlerType: String { case getCredentials } private func key(for type: HandlerType) -> String { return "\(type.rawValue).\(accountName)" } func registerHandler(type: HandlerType, handler:@escaping Handler) { handlers[key(for: type)] = handler } func doHandler(for type: HandlerType, testAccount: TestAccount, callback: @escaping ((Account)->())) { let handlerKey = key(for: type) guard let handler = handlers[handlerKey] else { assert(false) return } // Log.debug("About to call handler: \(type)") handler(testAccount, callback) } // Assumes that the ServerConstants.HTTPOAuth2AccessTokenKey key has been set in the headers. func specificHeaderSetup(headers: inout [String: String], testUser: TestAccount) { switch accountName { case AccountScheme.dropbox.accountName: headers[ServerConstants.HTTPAccountIdKey] = testUser.id() case AccountScheme.microsoft.accountName: // Microsoft credentials are odd in that the "access token" is not a JWT Oauth2 token-- it's a specific Microsoft token. let msalAccessToken = headers[ServerConstants.HTTPOAuth2AccessTokenKey] headers[ServerConstants.HTTPMicrosoftAccessToken] = msalAccessToken // This is the idToken for the Microsoft account-- the real JWT Oauth2 token. headers[ServerConstants.HTTPOAuth2AccessTokenKey] = testUser.secondToken() default: break } } func deleteFile(testAccount: TestAccount, cloudFileName: String, options: CloudStorageFileNameOptions, fileNotFoundOK: Bool = false, expectation:XCTestExpectation) { switch testAccount.scheme.accountName { case AccountScheme.google.accountName: let creds = GoogleCreds()! creds.refreshToken = testAccount.token() creds.refresh { error in guard error == nil, creds.accessToken != nil else { print("Error: \(error!)") XCTFail() expectation.fulfill() return } guard let cloudStorage = creds.cloudStorage else { XCTFail() expectation.fulfill() return } cloudStorage.deleteFile(cloudFileName:cloudFileName, options:options) { result in switch result { case .success: break case .accessTokenRevokedOrExpired: XCTFail() case .failure(let error): XCTFail("\(error)") } expectation.fulfill() } } case AccountScheme.dropbox.accountName: let creds = DropboxCreds()! creds.accessToken = testAccount.token() creds.accountId = testAccount.id() guard let cloudStorage = creds.cloudStorage else { XCTFail() expectation.fulfill() return } cloudStorage.deleteFile(cloudFileName:cloudFileName, options:options) { result in switch result { case .success: break case .accessTokenRevokedOrExpired: XCTFail() case .failure: XCTFail() } expectation.fulfill() } case AccountScheme.microsoft.accountName: let creds = MicrosoftCreds()! creds.refreshToken = testAccount.token() creds.refresh { error in guard error == nil, creds.accessToken != nil else { print("Error: \(error!)") XCTFail() expectation.fulfill() return } guard let cloudStorage = creds.cloudStorage else { XCTFail() expectation.fulfill() return } cloudStorage.deleteFile(cloudFileName:cloudFileName, options:options) { result in switch result { case .success: expectation.fulfill() case .accessTokenRevokedOrExpired: XCTFail() expectation.fulfill() case .failure(let error): if fileNotFoundOK, let error = error as? MicrosoftCreds.OneDriveFailure, case .fileNotFound = error { expectation.fulfill() } else { XCTFail("Microsoft file deletion: \(error)") expectation.fulfill() } } } } default: assert(false) } } } // 12/20/17; I'm doing this because I suspect that I get test failures that occur simply because I'm asking to generate an access token from a refresh token too frequently in my tests. class CredsCache { // The key is the `sub` or id for the particular account. static var cache = [String: Account]() static func credsFor(googleAccount:TestAccount, completion: @escaping (_ creds: GoogleCreds)->()) { if let creds = cache[googleAccount.id()] { guard let creds = creds as? GoogleCreds else { assert(false) return } completion(creds) } else { Log.info("Attempting to refresh Google Creds...") let creds = GoogleCreds()! cache[googleAccount.id()] = creds creds.refreshToken = googleAccount.token() creds.refresh {[unowned creds] error in XCTAssert(error == nil, "credsFor: Failure on refresh: \(error!)") completion(creds) } } } static func credsFor(microsoftAccount:TestAccount, completion: @escaping (_ creds: MicrosoftCreds)->()) { if let creds = cache[microsoftAccount.id()] { guard let creds = creds as? MicrosoftCreds else { assert(false) return } completion(creds) } else { Log.info("Attempting to refresh Microsoft Creds...") let creds = MicrosoftCreds()! cache[microsoftAccount.id()] = creds creds.refreshToken = microsoftAccount.token() creds.refresh {[unowned creds] error in XCTAssert(error == nil, "credsFor: Failure on refresh: \(error!)") completion(creds) } } } } extension XCTestCase { @discardableResult func lookupFile(forOwningTestAccount testAccount: TestAccount, cloudFileName: String, options: CloudStorageFileNameOptions) -> Bool? { var lookupResult: Bool? let expectation = self.expectation(description: "expectation") switch testAccount.scheme.accountName { case AccountScheme.google.accountName: let creds = GoogleCreds()! creds.refreshToken = testAccount.token() creds.refresh { error in guard error == nil, creds.accessToken != nil else { XCTFail() expectation.fulfill() return } creds.lookupFile(cloudFileName:cloudFileName, options:options) { result in switch result { case .success (let found): lookupResult = found case .failure, .accessTokenRevokedOrExpired: XCTFail() } expectation.fulfill() } } case AccountScheme.dropbox.accountName: let creds = DropboxCreds()! creds.accessToken = testAccount.token() creds.accountId = testAccount.id() creds.lookupFile(cloudFileName:cloudFileName, options:options) { result in switch result { case .success (let found): lookupResult = found case .failure, .accessTokenRevokedOrExpired: XCTFail() } expectation.fulfill() } case AccountScheme.microsoft.accountName: let creds = MicrosoftCreds()! creds.refreshToken = testAccount.token() creds.refresh { error in guard error == nil, creds.accessToken != nil else { XCTFail() expectation.fulfill() return } creds.lookupFile(cloudFileName:cloudFileName, options:options) { result in switch result { case .success (let found): lookupResult = found case .failure, .accessTokenRevokedOrExpired: XCTFail() } expectation.fulfill() } } default: assert(false) } waitForExpectations(timeout: 10.0, handler: nil) return lookupResult } } <file_sep>// // SpecificDatabaseTests_UserRepository.swift // Server // // Created by <NAME> on 4/11/17. // // import XCTest @testable import Server import LoggerAPI import HeliumLogger import Credentials import CredentialsGoogle import Foundation import SyncServerShared class SpecificDatabaseTests_UserRepository: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() AccountManager.session.reset() } func addOwningUsers() { let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" user1.cloudFolderName = "folder1" let result1 = UserRepository(db).add(user: user1, validateJSON: false) XCTAssert(result1 == 1, "Bad credentialsId!") let user2 = User() user2.username = "Natasha" user2.accountType = AccountScheme.google.accountName user2.creds = "{\"accessToken\": \"SomeAccessTokenValue2\"}" user2.credsId = "200" user2.cloudFolderName = "folder2" let result2 = UserRepository(db).add(user: user2, validateJSON: false) XCTAssert(result2 == 2, "Bad credentialsId!") } func testAddOwningUser() { addOwningUsers() } func testAddOwningUserWorksIfYouGivePermissions() { let user1 = User() user1.username = "Chris" user1.accountType = AccountScheme.google.accountName user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" user1.credsId = "100" guard let _ = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail() return } } func addUser(accountType:AccountScheme.AccountName = AccountScheme.google.accountName, sharing: Bool = true) { let user1 = User() user1.username = "Chris" user1.accountType = accountType switch (accountType) { case AccountScheme.google.accountName: user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" case AccountScheme.facebook.accountName: user1.creds = "{}" case AccountScheme.dropbox.accountName: user1.creds = "{\"accessToken\": \"SomeAccessTokenValue1\"}" default: XCTFail() } user1.credsId = "100" guard let _ = UserRepository(db).add(user: user1, validateJSON: false) else { XCTFail() return } } func testAddGoogleUser() { addUser(sharing: false) } func testAddSharingFacebookUser() { addUser(accountType: AccountScheme.facebook.accountName) } func testAddDropboxUser() { addUser(accountType: AccountScheme.dropbox.accountName, sharing: false) } func testUserLookup1() { addOwningUsers() let result = UserRepository(db).lookup(key: .userId(1), modelInit:User.init) switch result { case .error(let error): XCTFail("\(error)") case .found(let object): let user = object as! User XCTAssert(user.accountType == AccountScheme.google.accountName) XCTAssert(user.username == "Chris") XCTAssert(user.creds == "{\"accessToken\": \"SomeAccessTokenValue1\"}") XCTAssert(user.userId == 1) XCTAssert(user.cloudFolderName == "folder1") case .noObjectFound: XCTFail("No User Found") } } func testUserLookup1b() { addOwningUsers() let result = UserRepository(db).lookup(key: .userId(1), modelInit: User.init) switch result { case .error(let error): XCTFail("\(error)") case .found(let object): let user = object as! User XCTAssert(user.accountType == AccountScheme.google.accountName) XCTAssert(user.username == "Chris") XCTAssert(user.creds == "{\"accessToken\": \"SomeAccessTokenValue1\"}") XCTAssert(user.userId == 1) XCTAssert(user.cloudFolderName == "folder1") case .noObjectFound: XCTFail("No User Found") } } func testUserLookup2() { // Faking this so we don't have to startup server. AccountManager.session.addAccountType(GoogleCreds.self) addOwningUsers() let result = UserRepository(db).lookup(key: .accountTypeInfo(accountType:AccountScheme.google.accountName, credsId:"100"), modelInit:User.init) switch result { case .error(let error): XCTFail("\(error)") case .found(let object): let user = object as! User XCTAssert(user.accountType == AccountScheme.google.accountName) XCTAssert(user.username == "Chris") XCTAssert(user.creds == "{\"accessToken\": \"SomeAccessTokenValue1\"}") XCTAssert(user.userId == 1) XCTAssert(user.cloudFolderName == "folder1") guard let credsObject = user.credsObject as? GoogleCreds else { XCTFail() return } XCTAssert(credsObject.accessToken == "SomeAccessTokenValue1") case .noObjectFound: XCTFail("No User Found") } } } extension SpecificDatabaseTests_UserRepository { static var allTests : [(String, (SpecificDatabaseTests_UserRepository) -> () throws -> Void)] { return [ ("testAddOwningUser", testAddOwningUser), ("testAddOwningUserWorksIfYouGivePermissions", testAddOwningUserWorksIfYouGivePermissions), ("testAddGoogleUser", testAddGoogleUser), ("testAddSharingFacebookUser", testAddSharingFacebookUser), ("testAddDropboxUser", testAddDropboxUser), ("testUserLookup1", testUserLookup1), ("testUserLookup1b", testUserLookup1b), ("testUserLookup2", testUserLookup2) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SpecificDatabaseTests_UserRepository.self) } } <file_sep>// // SharingAccountsController_CreateSharingInvitation.swift // Server // // Created by <NAME> on 4/11/17. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared // You can run this with primarySharingAccount set to any account that allows sharing. class SharingAccountsController_CreateSharingInvitation: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func successfulSharingInvitationCreation(sharingPermission: Permission, numberAcceptors: UInt = 1, allowSharingAcceptance: Bool = true, errorExpected: Bool = false) { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } self.createSharingInvitation(permission: sharingPermission, numberAcceptors: numberAcceptors, allowSharingAcceptance:allowSharingAcceptance, sharingGroupUUID:sharingGroupUUID, errorExpected: errorExpected) { expectation, invitationUUID in if !errorExpected { XCTAssert(invitationUUID != nil) guard let _ = UUID(uuidString: invitationUUID!) else { XCTFail() expectation.fulfill() return } } expectation.fulfill() } } func testSuccessfulReadSharingInvitationCreationByAnOwningUser() { successfulSharingInvitationCreation(sharingPermission: .read) } func testSuccessfulWriteSharingInvitationCreationByAnOwningUser() { successfulSharingInvitationCreation(sharingPermission: .write) } func testSuccessfulAdminSharingInvitationCreationByAnOwningUser() { successfulSharingInvitationCreation(sharingPermission: .admin) } func sharingInvitationCreationByAnAdminSharingUser(sharingUser:TestAccount, failureExpected: Bool = false) { // .primaryOwningAccount owning user is created as part of this. let testAccount:TestAccount = .primaryOwningAccount var actualSharingGroupUUID: String! var adminUserId:UserId! createSharingUser(withSharingPermission: .admin, sharingUser: sharingUser) { userId, sharingGroupUUID, _ in actualSharingGroupUUID = sharingGroupUUID adminUserId = userId } guard actualSharingGroupUUID != nil else { XCTFail() return } // Lookup the userId for the freshly created owning user. let userKey = UserRepository.LookupKey.accountTypeInfo(accountType: testAccount.scheme.accountName, credsId: testAccount.id()) let userResults = UserRepository(self.db).lookup(key: userKey, modelInit: User.init) guard case .found(let model) = userResults, let testAccountUserId = (model as? User)?.userId else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(testAccount: sharingUser, permission: .write, sharingGroupUUID: actualSharingGroupUUID, errorExpected: false) { expectation, invitationUUID in XCTAssert(invitationUUID != nil) guard let _ = UUID(uuidString: invitationUUID!) else { XCTFail() expectation.fulfill() return } sharingInvitationUUID = invitationUUID expectation.fulfill() } // Now, who is the owning user? // If the admin sharing user is an owning user, then the owning user of the invitation will be the admin sharing user. // If the admin sharing user is a sharing user, then the owning user will be the owning user (inviter) of the admin user. let key = SharingInvitationRepository.LookupKey.sharingInvitationUUID(uuid: sharingInvitationUUID) let results = SharingInvitationRepository(db).lookup(key: key, modelInit: SharingInvitation.init) guard case .found(let model2) = results, let invitation = model2 as? SharingInvitation else { XCTFail("ERROR: Did not find sharing invitation!") return } switch sharingUser.scheme.userType { case .owning: XCTAssert(invitation.owningUserId == adminUserId) case .sharing: XCTAssert(invitation.owningUserId == testAccountUserId, "ERROR: invitation.owningUserId: \(String(describing: invitation.owningUserId)) was not equal to \(testAccountUserId)") } } func testSuccessfulSharingInvitationCreationByAnAdminSharingUser() { sharingInvitationCreationByAnAdminSharingUser(sharingUser: .primarySharingAccount) } func failureOfSharingInvitationCreationByAReadSharingUser(sharingUser: TestAccount) { var actualSharingGroupUUID: String! createSharingUser(withSharingPermission: .read, sharingUser: sharingUser) { userId, sharingGroupUUID, _ in actualSharingGroupUUID = sharingGroupUUID } guard actualSharingGroupUUID != nil else { XCTFail() return } // The sharing user just created is that with account sharingUser. The following will fail because we're attempting to create a sharing invitation with a non-admin user. This non-admin (read) user is referenced by the sharingUser token. createSharingInvitation(testAccount: sharingUser, permission: .read, sharingGroupUUID: actualSharingGroupUUID, errorExpected: true) { expectation, invitationUUID in expectation.fulfill() } } func testFailureOfSharingInvitationCreationByAReadSharingUser() { failureOfSharingInvitationCreationByAReadSharingUser(sharingUser: .primarySharingAccount) } func failureOfSharingInvitationCreationByAWriteSharingUser(sharingUser: TestAccount) { var actualSharingGroupUUID: String! createSharingUser(withSharingPermission: .write, sharingUser: sharingUser) { userId, sharingGroupUUID, _ in actualSharingGroupUUID = sharingGroupUUID } guard actualSharingGroupUUID != nil else { XCTFail() return } createSharingInvitation(testAccount: sharingUser, permission: .read, sharingGroupUUID:actualSharingGroupUUID, errorExpected: true) { expectation, invitationUUID in expectation.fulfill() } } func testFailureOfSharingInvitationCreationByAWriteSharingUser() { failureOfSharingInvitationCreationByAWriteSharingUser(sharingUser: .primarySharingAccount) } func testSharingInvitationCreationFailsWithNoAuthorization() { self.performServerTest { expectation, creds in let request = CreateSharingInvitationRequest() request.permission = Permission.read // A fake sharing group id. This shouldn't be the issue that fails the request. It should fail because there is no authorization. request.sharingGroupUUID = UUID().uuidString self.performRequest(route: ServerEndpoints.createSharingInvitation, urlParameters: "?" + request.urlParameters()!, body:nil) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode != .OK, "Worked with bad request!") expectation.fulfill() } } } func testSharingInvitationCreationFailsWithoutMembershipInSharingGroup() { let deviceUUID1 = Foundation.UUID().uuidString let sharingGroupUUID1 = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID1, deviceUUID:deviceUUID1) else { XCTFail() return } let deviceUUID2 = Foundation.UUID().uuidString let sharingGroupUUID2 = Foundation.UUID().uuidString guard let _ = self.addNewUser(testAccount: .secondaryOwningAccount, sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID2) else { XCTFail() return } createSharingInvitation(testAccount: .secondaryOwningAccount, permission: .write, sharingGroupUUID:sharingGroupUUID1, errorExpected: true) { expectation, invitationUUID in expectation.fulfill() } } func testDisallowingSharingAcceptanceWorks() { successfulSharingInvitationCreation(sharingPermission: .read, allowSharingAcceptance: false) } func testThatNoAcceptorsFails() { successfulSharingInvitationCreation(sharingPermission: .read, numberAcceptors: 0, errorExpected: true) } func testThat1AcceptorsWorks() { successfulSharingInvitationCreation(sharingPermission: .read, numberAcceptors: 1) } func testThatMaxAcceptorsWorks() { successfulSharingInvitationCreation(sharingPermission: .read, numberAcceptors: ServerConstants.maxNumberSharingInvitationAcceptors) } func testThatMaxPlusOneAcceptorsFails() { successfulSharingInvitationCreation(sharingPermission: .read, numberAcceptors: ServerConstants.maxNumberSharingInvitationAcceptors + 1, errorExpected: true) } } extension SharingAccountsController_CreateSharingInvitation { static var allTests : [(String, (SharingAccountsController_CreateSharingInvitation) -> () throws -> Void)] { return [ ("testSuccessfulReadSharingInvitationCreationByAnOwningUser", testSuccessfulReadSharingInvitationCreationByAnOwningUser), ("testSuccessfulWriteSharingInvitationCreationByAnOwningUser", testSuccessfulWriteSharingInvitationCreationByAnOwningUser), ("testSuccessfulAdminSharingInvitationCreationByAnOwningUser", testSuccessfulAdminSharingInvitationCreationByAnOwningUser), ("testSuccessfulSharingInvitationCreationByAnAdminSharingUser", testSuccessfulSharingInvitationCreationByAnAdminSharingUser), ("testFailureOfSharingInvitationCreationByAReadSharingUser", testFailureOfSharingInvitationCreationByAReadSharingUser), ("testFailureOfSharingInvitationCreationByAWriteSharingUser", testFailureOfSharingInvitationCreationByAWriteSharingUser), ("testSharingInvitationCreationFailsWithNoAuthorization", testSharingInvitationCreationFailsWithNoAuthorization), ("testSharingInvitationCreationFailsWithoutMembershipInSharingGroup", testSharingInvitationCreationFailsWithoutMembershipInSharingGroup), ("testDisallowingSharingAcceptanceWorks", testDisallowingSharingAcceptanceWorks), ("testThatNoAcceptorsFails", testThatNoAcceptorsFails), ("testThat1AcceptorsWorks", testThat1AcceptorsWorks), ("testThatMaxAcceptorsWorks", testThatMaxAcceptorsWorks), ("testThatMaxPlusOneAcceptorsFails", testThatMaxPlusOneAcceptorsFails) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SharingAccountsController_CreateSharingInvitation.self) } } <file_sep>// // PushNotifications.swift // Server // // Created by <NAME> on 2/6/19. // import Foundation import SyncServerShared import SwiftyAWSSNS import LoggerAPI class PushNotifications { private(set) var sns:SwiftyAWSSNS! init?() { guard let accessKeyId = Configuration.server.awssns?.accessKeyId, let secretKey = Configuration.server.awssns?.secretKey, let region = Configuration.server.awssns?.region, let platformApplicationArn = Configuration.server.awssns?.platformApplicationArn else { let message = "Missing one of the Configuration.server.awssns values!" Log.error(message) return nil } Log.debug("accessKeyId: \(accessKeyId)") Log.debug(("secretKey: \(secretKey)")) Log.debug("region: \(region)") Log.debug("platformApplicationArn: \(platformApplicationArn)") sns = SwiftyAWSSNS(accessKeyId: accessKeyId, secretKey: secretKey, region: region, platformApplicationArn: platformApplicationArn) } static func topicName(userId: UserId) -> String { return "\(userId)" } static func format(message: String) -> String? { // Format of messages: https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html // https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html func strForJSON(json: Any) -> String? { if let result = try? JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions(rawValue: 0)) { return String(data: result, encoding: .utf8) } Log.error("Failed in strForJSON: \(json)") return nil } let messageContentsDict = ["aps": ["alert": message, "sound": "default"] ] guard let messageContentsString = strForJSON(json: messageContentsDict) else { Log.error("Failed converting messageContentsString: \(messageContentsDict)") return nil } // Looks like the top level key must be "APNS" for production; see https://forums.aws.amazon.com/thread.jspa?threadID=145907 // 2/9/19; Without the "default" key, I'm getting a failure. let messageDict = ["APNS_SANDBOX": messageContentsString, "APNS": messageContentsString, "default": messageContentsString ] guard let messageString = strForJSON(json: messageDict) else { Log.error("Failed converting messageString: \(messageDict)") return nil } return messageString } // The users in the given array will all have PN topics. // Use the format method above to format the message before passing to this method. // Returns true iff success func send(formattedMessage message: String, toUsers users: [User], completion: @escaping (_ success: Bool)->()) { let async = AsyncTailRecursion() async.start { self.sendAux(formattedMessage: message, toUsers: users, async: async, completion: completion) } } func sendAux(formattedMessage message: String, toUsers users: [User], async: AsyncTailRecursion, completion: @escaping (_ success: Bool)->()) { // Base case. if users.count == 0 { completion(true) async.done() return } let user = users[0] let topic = user.pushNotificationTopic! Log.debug("Sending push notification: \(message) to devices subscribed to topic \(topic) for user \(user.username!)") sns.publish(message: message, target: .topicArn(topic)) { [unowned self] response in switch response { case .success: async.next { let tail = (users.count > 0) ? Array(users[1..<users.count]) : [] self.sendAux(formattedMessage: message, toUsers: tail, async: async, completion: completion) } case .error(let error): Log.error("Failed on SNS publish: \(error); sending message: \(message)") completion(false) async.done() } } } } <file_sep>// // ServerTestCase.swift // Server // // Created by <NAME> on 1/7/17. // // // Base XCTestCase class- has no specific tests. import Foundation import XCTest @testable import Server import LoggerAPI import SyncServerShared import HeliumLogger import Kitura #if os(Linux) import Glibc #else import Darwin.C #endif protocol LinuxTestable { associatedtype TestClassType static var allTests : [(String, (TestClassType) -> () throws -> Void)] {get} } extension LinuxTestable { typealias LinuxTestableType = XCTestCase & LinuxTestable // Modified from https://oleb.net/blog/2017/03/keeping-xctest-in-sync/ func linuxTestSuiteIncludesAllTests<T: LinuxTestableType>(testType:T.Type) { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) // Adding 1 to linuxCount because it doesn't have *this* test. let linuxCount = testType.allTests.count + 1 let darwinCount = Int(testType.defaultTestSuite.testCaseCount) XCTAssertEqual(linuxCount, darwinCount, "\(darwinCount - linuxCount) test(s) are missing from allTests") #endif } } class ServerTestCase : XCTestCase { var db:Database! override func setUp() { super.setUp() // The same file is assumed to contain both the server configuration and test configuration keys. #if os(Linux) try! Configuration.setup(configFileFullPath: "./ServerTests.json", testConfigFileFullPath: "./ServerTests.json") #else // Assume that the configuration file(s) have been copied to /tmp before running the test. try! Configuration.setup(configFileFullPath: "/tmp/ServerTests.json", testConfigFileFullPath: "/tmp/ServerTests.json") #endif Database.remove() _ = Database.setup() self.db = Database() Log.logger = HeliumLogger() HeliumLogger.use(.debug) TestAccount.registerHandlers() } override func tearDown() { super.tearDown() Log.info("About to close...") // Otherwise we can have too many db connections open during testing. self.db.close() Log.info("Closed") } @discardableResult func checkOwingUserForSharingGroupUser(sharingGroupUUID: String, sharingUserId: UserId, sharingUser:TestAccount, owningUser: TestAccount) -> Bool { let sharingUserKey = SharingGroupUserRepository.LookupKey.primaryKeys(sharingGroupUUID: sharingGroupUUID, userId: sharingUserId) let sharingResult = SharingGroupUserRepository(db).lookup(key: sharingUserKey, modelInit: SharingGroupUser.init) var sharingGroupUser1: Server.SharingGroupUser! switch sharingResult { case .found(let model): sharingGroupUser1 = (model as! Server.SharingGroupUser) case .error, .noObjectFound: XCTFail() return false } guard let (_, sharingGroups) = getIndex(testAccount: sharingUser) else { XCTFail() return false } let filtered = sharingGroups.filter {$0.sharingGroupUUID == sharingGroupUUID} guard filtered.count == 1 else { XCTFail() return false } let sharingGroup = filtered[0] if sharingUser.scheme.userType == .owning { XCTAssert(sharingGroup.cloudStorageType == nil) XCTAssert(sharingGroupUser1.owningUserId == nil) return sharingGroupUser1.owningUserId == nil } guard let owningUserId = sharingGroupUser1.owningUserId else { XCTFail() return false } let owningUserKey = SharingGroupUserRepository.LookupKey.primaryKeys(sharingGroupUUID: sharingGroupUUID, userId: owningUserId) let owningResult = SharingGroupUserRepository(db).lookup(key: owningUserKey, modelInit: SharingGroupUser.init) var sharingGroupUser2: Server.SharingGroupUser! switch owningResult { case .found(let model): sharingGroupUser2 = (model as! Server.SharingGroupUser) case .error, .noObjectFound: XCTFail() return false } guard owningUser.scheme.userType == .owning, sharingGroupUser2.owningUserId == nil else { XCTFail() return false } let userKey = UserRepository.LookupKey.userId(owningUserId) let userResult = UserRepository(db).lookup(key: userKey, modelInit: User.init) var resultOwningUser: User! switch userResult { case .found(let model): guard let userObj = model as? User, userObj.accountType == owningUser.scheme.accountName else { XCTFail() return false } resultOwningUser = userObj case .error, .noObjectFound: XCTFail() return false } // Make sure that sharing groups returned from the server with the Index reflect, for sharing users, their "parent" owning user for the sharing group. guard let ownersCloudStorageType = sharingGroup.cloudStorageType else { XCTFail() return false } guard AccountScheme(.accountName(resultOwningUser.accountType))?.cloudStorageType == ownersCloudStorageType else { XCTFail() return false } return true } // The second sharing account joined is returned as the sharingGroupUUID @discardableResult func redeemWithAnExistingOtherSharingAccount() -> (TestAccount, sharingGroupUUID: String)? { var returnResult: (TestAccount, String)? let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString let owningUser:TestAccount = .primaryOwningAccount guard let _ = self.addNewUser(testAccount: owningUser, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return nil } var sharingInvitationUUID:String! createSharingInvitation(testAccount: owningUser, permission: .read, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let sharingUser: TestAccount = .primarySharingAccount redeemSharingInvitation(sharingUser: sharingUser, sharingInvitationUUID: sharingInvitationUUID) { _, expectation in expectation.fulfill() } // Primary sharing account user now exists. let sharingGroupUUID2 = Foundation.UUID().uuidString // Create a second sharing group and invite/redeem the primary sharing account user. guard createSharingGroup(testAccount: owningUser, sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID) else { XCTFail() return nil } createSharingInvitation(testAccount: owningUser, permission: .write, sharingGroupUUID:sharingGroupUUID2) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } var result: RedeemSharingInvitationResponse! redeemSharingInvitation(sharingUser: sharingUser, sharingInvitationUUID: sharingInvitationUUID) { response, expectation in result = response expectation.fulfill() } guard result != nil else { XCTFail() return nil } if checkOwingUserForSharingGroupUser(sharingGroupUUID: sharingGroupUUID2, sharingUserId: result.userId, sharingUser: sharingUser, owningUser: owningUser) { returnResult = (sharingUser, sharingGroupUUID2) } return returnResult } @discardableResult func uploadAppMetaDataVersion(testAccount:TestAccount = .primaryOwningAccount, deviceUUID: String, fileUUID: String, masterVersion:Int64, appMetaData: AppMetaData, sharingGroupUUID: String, expectedError: Bool = false) -> UploadAppMetaDataResponse? { var result:UploadAppMetaDataResponse? self.performServerTest(testAccount:testAccount) { expectation, testCreds in let headers = self.setupHeaders(testUser:testAccount, accessToken: testCreds.accessToken, deviceUUID:deviceUUID) let uploadAppMetaDataRequest = UploadAppMetaDataRequest() uploadAppMetaDataRequest.fileUUID = fileUUID uploadAppMetaDataRequest.masterVersion = masterVersion uploadAppMetaDataRequest.appMetaData = appMetaData uploadAppMetaDataRequest.sharingGroupUUID = sharingGroupUUID self.performRequest(route: ServerEndpoints.uploadAppMetaData, headers: headers, urlParameters: "?" + uploadAppMetaDataRequest.urlParameters()!, body:nil) { response, dict in Log.info("Status code: \(response!.statusCode)") if expectedError { XCTAssert(response!.statusCode != .OK, "Did not work on failing uploadAppMetaDataRequest request") } else { XCTAssert(response!.statusCode == .OK, "Did not work on uploadAppMetaDataRequest request") if let dict = dict, let uploadAppMetaDataResponse = try? UploadAppMetaDataResponse.decode(dict) { if uploadAppMetaDataResponse.masterVersionUpdate == nil { result = uploadAppMetaDataResponse } else { XCTFail() } } else { XCTFail() } } expectation.fulfill() } } return result } @discardableResult func downloadAppMetaDataVersion(testAccount:TestAccount = .primaryOwningAccount, deviceUUID: String, fileUUID: String, masterVersionExpectedWithDownload:Int64, expectUpdatedMasterUpdate:Bool = false, appMetaDataVersion: AppMetaDataVersionInt? = nil, sharingGroupUUID: String, expectedError: Bool = false) -> DownloadAppMetaDataResponse? { var result:DownloadAppMetaDataResponse? self.performServerTest(testAccount:testAccount) { expectation, testCreds in let headers = self.setupHeaders(testUser:testAccount, accessToken: testCreds.accessToken, deviceUUID:deviceUUID) let downloadAppMetaDataRequest = DownloadAppMetaDataRequest() downloadAppMetaDataRequest.fileUUID = fileUUID downloadAppMetaDataRequest.masterVersion = masterVersionExpectedWithDownload downloadAppMetaDataRequest.appMetaDataVersion = appMetaDataVersion downloadAppMetaDataRequest.sharingGroupUUID = sharingGroupUUID if !downloadAppMetaDataRequest.valid() { if !expectedError { XCTFail() } expectation.fulfill() return } self.performRequest(route: ServerEndpoints.downloadAppMetaData, headers: headers, urlParameters: "?" + downloadAppMetaDataRequest.urlParameters()!, body:nil) { response, dict in Log.info("Status code: \(response!.statusCode)") if expectedError { XCTAssert(response!.statusCode != .OK, "Did not work on failing downloadAppMetaDataRequest request") } else { XCTAssert(response!.statusCode == .OK, "Did not work on downloadAppMetaDataRequest request") if let dict = dict, let downloadAppMetaDataResponse = try? DownloadAppMetaDataResponse.decode(dict) { result = downloadAppMetaDataResponse if expectUpdatedMasterUpdate { XCTAssert(downloadAppMetaDataResponse.masterVersionUpdate != nil) } else { XCTAssert(downloadAppMetaDataResponse.masterVersionUpdate == nil) } } else { XCTFail() } } expectation.fulfill() } } return result } @discardableResult func healthCheck() -> HealthCheckResponse? { var result:HealthCheckResponse? performServerTest { expectation, creds in self.performRequest(route: ServerEndpoints.healthCheck) { response, dict in XCTAssert(response!.statusCode == .OK, "Failed on healthcheck request") guard let dict = dict, let healthCheckResponse = try? HealthCheckResponse.decode(dict) else { XCTFail() return } XCTAssert(healthCheckResponse.serverUptime > 0) XCTAssert(healthCheckResponse.deployedGitTag.count > 0) XCTAssert(healthCheckResponse.currentServerDateTime != nil) result = healthCheckResponse expectation.fulfill() } } return result } func deleteFile(testAccount: TestAccount, cloudFileName: String, options: CloudStorageFileNameOptions, fileNotFoundOK: Bool = false) { let expectation = self.expectation(description: "expectation") testAccount.scheme.deleteFile(testAccount: testAccount, cloudFileName: cloudFileName, options: options, fileNotFoundOK: fileNotFoundOK, expectation: expectation) waitForExpectations(timeout: 20.0, handler: nil) } @discardableResult func addNewUser(testAccount:TestAccount = .primaryOwningAccount, sharingGroupUUID: String, deviceUUID:String, cloudFolderName: String? = ServerTestCase.cloudFolderName, sharingGroupName:String? = nil) -> AddUserResponse? { var result:AddUserResponse? if let fileName = Configuration.server.owningUserAccountCreation.initialFileName { // Need to delete the initialization file in the test account, so that if we're creating the user test account for a 2nd, 3rd etc time, we don't fail. let options = CloudStorageFileNameOptions(cloudFolderName: cloudFolderName, mimeType: "text/plain") Log.debug("About to delete file.") deleteFile(testAccount: testAccount, cloudFileName: fileName, options: options, fileNotFoundOK: true) result = addNewUser2(testAccount:testAccount, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID, cloudFolderName: cloudFolderName, sharingGroupName: sharingGroupName) } else { result = addNewUser2(testAccount:testAccount, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID, cloudFolderName: cloudFolderName, sharingGroupName: sharingGroupName) } return result } private func addNewUser2(testAccount:TestAccount, sharingGroupUUID: String, deviceUUID:String, cloudFolderName: String?, sharingGroupName:String?) -> AddUserResponse? { var result:AddUserResponse? let addUserRequest = AddUserRequest() addUserRequest.cloudFolderName = cloudFolderName addUserRequest.sharingGroupName = sharingGroupName addUserRequest.sharingGroupUUID = sharingGroupUUID self.performServerTest(testAccount:testAccount) { expectation, creds in let headers = self.setupHeaders(testUser: testAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) var queryParams:String? if let params = addUserRequest.urlParameters() { queryParams = "?" + params } self.performRequest(route: ServerEndpoints.addUser, headers: headers, urlParameters: queryParams) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "Did not work on addUser request: \(response!.statusCode)") if let dict = dict, let addUserResponse = try? AddUserResponse.decode(dict) { XCTAssert(addUserResponse.userId != nil) result = addUserResponse } else { XCTFail() } expectation.fulfill() } } return result } @discardableResult // Returns sharing group UUID func createSharingGroup(testAccount:TestAccount = .primaryOwningAccount, sharingGroupUUID:String, deviceUUID:String, sharingGroup: SyncServerShared.SharingGroup? = nil, errorExpected: Bool = false) -> Bool { var result: Bool = false let createRequest = CreateSharingGroupRequest() createRequest.sharingGroupName = sharingGroup?.sharingGroupName createRequest.sharingGroupUUID = sharingGroupUUID self.performServerTest(testAccount:testAccount) { expectation, creds in let headers = self.setupHeaders(testUser: testAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) var queryParams:String? if let params = createRequest.urlParameters() { queryParams = "?" + params } self.performRequest(route: ServerEndpoints.createSharingGroup, headers: headers, urlParameters: queryParams) { response, dict in Log.info("Status code: \(response!.statusCode)") if errorExpected { XCTAssert(response!.statusCode != .OK) } else { XCTAssert(response!.statusCode == .OK, "Did not work on create sharing group request: \(response!.statusCode)") } if !errorExpected { if let dict = dict, let _ = try? CreateSharingGroupResponse.decode(dict) { result = true } else { XCTFail() } } expectation.fulfill() } } return result } @discardableResult func updateSharingGroup(testAccount:TestAccount = .primaryOwningAccount, deviceUUID:String, sharingGroup: SyncServerShared.SharingGroup, masterVersion: MasterVersionInt, expectMasterVersionUpdate: Bool = false, expectFailure: Bool = false) -> Bool { var result: Bool = false let updateRequest = UpdateSharingGroupRequest() updateRequest.sharingGroupUUID = sharingGroup.sharingGroupUUID updateRequest.sharingGroupName = sharingGroup.sharingGroupName updateRequest.masterVersion = masterVersion self.performServerTest(testAccount:testAccount) { expectation, creds in let headers = self.setupHeaders(testUser: testAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) var queryParams:String? if let params = updateRequest.urlParameters() { queryParams = "?" + params } self.performRequest(route: ServerEndpoints.updateSharingGroup, headers: headers, urlParameters: queryParams) { response, dict in Log.info("Status code: \(response!.statusCode)") if expectFailure { XCTAssert(response!.statusCode != .OK) } else { XCTAssert(response!.statusCode == .OK, "Did not work on update sharing group request: \(response!.statusCode)") if let dict = dict, let response = try? UpdateSharingGroupResponse.decode(dict) { if let _ = response.masterVersionUpdate { XCTAssert(expectMasterVersionUpdate) } else { XCTAssert(!expectMasterVersionUpdate) } result = true } else { XCTFail() } } expectation.fulfill() } } return result } @discardableResult func removeSharingGroup(testAccount:TestAccount = .primaryOwningAccount, deviceUUID:String, sharingGroupUUID: String, masterVersion: MasterVersionInt) -> Bool { var result: Bool = false let removeRequest = RemoveSharingGroupRequest() removeRequest.sharingGroupUUID = sharingGroupUUID removeRequest.masterVersion = masterVersion self.performServerTest(testAccount:testAccount) { expectation, creds in let headers = self.setupHeaders(testUser: testAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) var queryParams:String? if let params = removeRequest.urlParameters() { queryParams = "?" + params } self.performRequest(route: ServerEndpoints.removeSharingGroup, headers: headers, urlParameters: queryParams) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "Did not work on remove sharing group request: \(response!.statusCode)") if let dict = dict, let response = try? RemoveSharingGroupResponse.decode(dict) { if let _ = response.masterVersionUpdate { result = false } else { result = true } } else { XCTFail() } expectation.fulfill() } } return result } @discardableResult func removeUserFromSharingGroup(testAccount:TestAccount = .primaryOwningAccount, deviceUUID:String, sharingGroupUUID: String, masterVersion: MasterVersionInt, expectMasterVersionUpdate: Bool = false) -> Bool { var result: Bool = false let removeRequest = RemoveUserFromSharingGroupRequest() removeRequest.sharingGroupUUID = sharingGroupUUID removeRequest.masterVersion = masterVersion self.performServerTest(testAccount:testAccount) { expectation, creds in let headers = self.setupHeaders(testUser: testAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) var queryParams:String? if let params = removeRequest.urlParameters() { queryParams = "?" + params } self.performRequest(route: ServerEndpoints.removeUserFromSharingGroup, headers: headers, urlParameters: queryParams) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "Did not work on remove user from sharing group request: \(response!.statusCode)") if let dict = dict, let response = try? RemoveUserFromSharingGroupResponse.decode(dict) { Log.debug("RemoveUserFromSharingGroupResponse: Decoded sucessfully") if let _ = response.masterVersionUpdate { XCTAssert(expectMasterVersionUpdate) } else { XCTAssert(!expectMasterVersionUpdate) } result = true } else { Log.error("RemoveUserFromSharingGroupResponse: Decode failed.") XCTFail() } expectation.fulfill() } } return result } static let cloudFolderName = "CloudFolder" struct UploadFileResult { let request: UploadFileRequest let sharingGroupUUID:String? let uploadingUserId: UserId? let data: Data // The checksum sent along with the upload. let checkSum: String } enum AddUser { case no(sharingGroupUUID: String) case yes } // statusCodeExpected is only used if an error is expected. // owningAccountType will be the same type as testAccount when an owning user is uploading (you can pass nil here), and the type of the "parent" owner when a sharing user is uploading. @discardableResult func uploadServerFile(testAccount:TestAccount = .primaryOwningAccount, mimeType: MimeType = .text, owningAccountType: AccountScheme.AccountName? = nil, deviceUUID:String = Foundation.UUID().uuidString, fileUUID:String? = nil, addUser:AddUser = .yes, updatedMasterVersionExpected:Int64? = nil, fileVersion:FileVersionInt = 0, masterVersion:Int64 = 0, cloudFolderName:String? = ServerTestCase.cloudFolderName, appMetaData:AppMetaData? = nil, errorExpected:Bool = false, undelete: Int32 = 0, file: TestFile = .test1, fileGroupUUID:String? = nil, statusCodeExpected: HTTPStatusCode? = nil) -> UploadFileResult? { var sharingGroupUUID = UUID().uuidString var uploadingUserId: UserId? switch addUser { case .yes: guard let addUserResponse = self.addNewUser(testAccount:testAccount, sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID, cloudFolderName: cloudFolderName) else { XCTFail() return nil } uploadingUserId = addUserResponse.userId case .no(sharingGroupUUID: let id): sharingGroupUUID = id } var fileUUIDToSend = "" if fileUUID == nil { fileUUIDToSend = Foundation.UUID().uuidString } else { fileUUIDToSend = fileUUID! } let data:Data! switch file.contents { case .string(let string): data = string.data(using: .utf8)! case .url(let url): data = try? Data(contentsOf: url) } guard data != nil else { return nil } var checkSumType: AccountScheme.AccountName if let owningAccountType = owningAccountType { checkSumType = owningAccountType } else { checkSumType = testAccount.scheme.accountName } let requestCheckSum = file.checkSum(type: checkSumType) Log.info("Starting runUploadTest: uploadTextFile: requestCheckSum: \(String(describing: requestCheckSum))") let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUIDToSend uploadRequest.mimeType = mimeType.rawValue uploadRequest.fileVersion = fileVersion uploadRequest.masterVersion = masterVersion uploadRequest.undeleteServerFile = undelete == 1 uploadRequest.fileGroupUUID = fileGroupUUID uploadRequest.sharingGroupUUID = sharingGroupUUID uploadRequest.checkSum = requestCheckSum uploadRequest.appMetaData = appMetaData Log.info("Starting runUploadTest: uploadTextFile: uploadRequest: \(String(describing: uploadRequest.toDictionary))") guard uploadRequest.valid() else { XCTFail() Log.error("Invalid upload request!") return nil } guard runUploadTest(testAccount:testAccount, data:data, uploadRequest:uploadRequest, updatedMasterVersionExpected:updatedMasterVersionExpected, deviceUUID:deviceUUID, errorExpected: errorExpected, statusCodeExpected: statusCodeExpected) else { if !errorExpected { XCTFail() } return nil } Log.info("Completed runUploadTest: uploadTextFile") guard let checkSum = file.checkSum(type: checkSumType) else { XCTFail() return nil } return UploadFileResult(request: uploadRequest, sharingGroupUUID: sharingGroupUUID, uploadingUserId: uploadingUserId, data: data, checkSum: checkSum) } @discardableResult func uploadTextFile(testAccount:TestAccount = .primaryOwningAccount, owningAccountType: AccountScheme.AccountName? = nil, deviceUUID:String = Foundation.UUID().uuidString, fileUUID:String? = nil, addUser:AddUser = .yes, updatedMasterVersionExpected:Int64? = nil, fileVersion:FileVersionInt = 0, masterVersion:Int64 = 0, cloudFolderName:String? = ServerTestCase.cloudFolderName, appMetaData:AppMetaData? = nil, errorExpected:Bool = false, undelete: Int32 = 0, stringFile: TestFile = .test1, fileGroupUUID:String? = nil, statusCodeExpected: HTTPStatusCode? = nil) -> UploadFileResult? { return uploadServerFile(testAccount:testAccount, owningAccountType: owningAccountType, deviceUUID:deviceUUID, fileUUID:fileUUID, addUser:addUser, updatedMasterVersionExpected:updatedMasterVersionExpected, fileVersion:fileVersion, masterVersion:masterVersion, cloudFolderName:cloudFolderName, appMetaData:appMetaData, errorExpected:errorExpected, undelete: undelete, file: stringFile, fileGroupUUID:fileGroupUUID, statusCodeExpected: statusCodeExpected) } // Returns true iff the file could be uploaded. @discardableResult func runUploadTest(testAccount:TestAccount = .primaryOwningAccount, data:Data, uploadRequest:UploadFileRequest, updatedMasterVersionExpected:Int64? = nil, deviceUUID:String, errorExpected:Bool = false, statusCodeExpected: HTTPStatusCode? = nil) -> Bool { var result: Bool = true self.performServerTest(testAccount:testAccount) { expectation, testCreds in let headers = self.setupHeaders(testUser: testAccount, accessToken: testCreds.accessToken, deviceUUID:deviceUUID) // The method for ServerEndpoints.uploadFile really must be a POST to upload the file. XCTAssert(ServerEndpoints.uploadFile.method == .post) Log.debug("uploadRequest.urlParameters(): \(uploadRequest.urlParameters()!)") self.performRequest(route: ServerEndpoints.uploadFile, responseDictFrom: .header, headers: headers, urlParameters: "?" + uploadRequest.urlParameters()!, body:data) { response, dict in Log.info("Status code: \(response!.statusCode)") if errorExpected { result = false if let statusCodeExpected = statusCodeExpected { XCTAssert(response!.statusCode == statusCodeExpected) } else { XCTAssert(response!.statusCode != .OK) } } else { guard response!.statusCode == .OK, dict != nil else { XCTFail("Did not work on uploadFile request: \(response!.statusCode)") result = false expectation.fulfill() return } if let uploadResponse = try? UploadFileResponse.decode(dict!) { if updatedMasterVersionExpected == nil { guard uploadResponse.creationDate != nil, uploadResponse.updateDate != nil else { result = false expectation.fulfill() return } } else { XCTAssert(uploadResponse.masterVersionUpdate == updatedMasterVersionExpected) } } else { result = false XCTFail() } } expectation.fulfill() } } return result } func uploadFileUsingServer(testAccount:TestAccount = .primaryOwningAccount, owningAccountType: AccountScheme.AccountName? = nil, deviceUUID:String = Foundation.UUID().uuidString, fileUUID:String = Foundation.UUID().uuidString, mimeType: MimeType = .jpeg, file: TestFile, addUser:AddUser = .yes, fileVersion:FileVersionInt = 0, expectedMasterVersion:MasterVersionInt = 0, appMetaData:AppMetaData? = nil, errorExpected:Bool = false) -> UploadFileResult? { var sharingGroupUUID: String! var uploadingUserId: UserId? switch addUser { case .yes: sharingGroupUUID = UUID().uuidString guard let addUserResponse = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return nil } uploadingUserId = addUserResponse.userId case .no(sharingGroupUUID: let id): sharingGroupUUID = id } guard case .url(let url) = file.contents, let data = try? Data(contentsOf: url) else { XCTFail() return nil } var checkSumType: AccountScheme.AccountName if let owningAccountType = owningAccountType { checkSumType = owningAccountType } else { checkSumType = testAccount.scheme.accountName } let uploadRequest = UploadFileRequest() uploadRequest.fileUUID = fileUUID uploadRequest.mimeType = mimeType.rawValue uploadRequest.fileVersion = fileVersion uploadRequest.masterVersion = expectedMasterVersion uploadRequest.sharingGroupUUID = sharingGroupUUID uploadRequest.checkSum = file.checkSum(type: checkSumType) guard uploadRequest.valid() else { XCTFail() return nil } uploadRequest.appMetaData = appMetaData Log.info("Starting runUploadTest: uploadJPEGFile") runUploadTest(testAccount: testAccount, data:data, uploadRequest:uploadRequest, deviceUUID:deviceUUID, errorExpected: errorExpected) Log.info("Completed runUploadTest: uploadJPEGFile") return UploadFileResult(request: uploadRequest, sharingGroupUUID: sharingGroupUUID, uploadingUserId:uploadingUserId, data: data, checkSum: file.checkSum(type: checkSumType)) } func uploadJPEGFile(testAccount:TestAccount = .primaryOwningAccount, owningAccountType: AccountScheme.AccountName? = nil, deviceUUID:String = Foundation.UUID().uuidString, fileUUID:String = Foundation.UUID().uuidString, addUser:AddUser = .yes, fileVersion:FileVersionInt = 0, expectedMasterVersion:MasterVersionInt = 0, appMetaData:AppMetaData? = nil, errorExpected:Bool = false) -> UploadFileResult? { let jpegFile = TestFile.catJpg return uploadFileUsingServer(testAccount:testAccount, owningAccountType: owningAccountType, deviceUUID:deviceUUID, fileUUID:fileUUID, mimeType: .jpeg, file: jpegFile, addUser:addUser, fileVersion:fileVersion, expectedMasterVersion:expectedMasterVersion, appMetaData:appMetaData, errorExpected:errorExpected) } // sharingGroupName enables you to change the sharing group name during the DoneUploads. func sendDoneUploads(testAccount:TestAccount = .primaryOwningAccount, expectedNumberOfUploads:Int32?, deviceUUID:String = Foundation.UUID().uuidString, updatedMasterVersionExpected:Int64? = nil, masterVersion:Int64 = 0, sharingGroupUUID: String, sharingGroupName: String? = nil, failureExpected:Bool = false) { self.performServerTest(testAccount:testAccount) { expectation, testCreds in let headers = self.setupHeaders(testUser: testAccount, accessToken: testCreds.accessToken, deviceUUID:deviceUUID) let doneUploadsRequest = DoneUploadsRequest() doneUploadsRequest.masterVersion = masterVersion doneUploadsRequest.sharingGroupUUID = sharingGroupUUID if let sharingGroupName = sharingGroupName { doneUploadsRequest.sharingGroupName = sharingGroupName } self.performRequest(route: ServerEndpoints.doneUploads, headers: headers, urlParameters: "?" + doneUploadsRequest.urlParameters()!, body:nil) { response, dict in Log.info("Status code: \(response!.statusCode)") if failureExpected { XCTAssert(response!.statusCode != .OK, "Worked on doneUploadsRequest request!") } else { XCTAssert(response!.statusCode == .OK, "Did not work on doneUploadsRequest request") XCTAssert(dict != nil) if let doneUploadsResponse = try? DoneUploadsResponse.decode(dict!) { XCTAssert(doneUploadsResponse.masterVersionUpdate == updatedMasterVersionExpected) XCTAssert(doneUploadsResponse.numberUploadsTransferred == expectedNumberOfUploads, "doneUploadsResponse.numberUploadsTransferred: \(String(describing: doneUploadsResponse.numberUploadsTransferred)); expectedNumberOfUploads: \(String(describing: expectedNumberOfUploads))") XCTAssert(doneUploadsResponse.numberDeletionErrors == nil) } else { XCTFail() } } expectation.fulfill() } } } func getIndex(expectedFiles:[UploadFileRequest]? = nil, deviceUUID:String = Foundation.UUID().uuidString, masterVersionExpected:Int64? = nil, sharingGroupUUID: String? = nil, expectedDeletionState:[String: Bool]? = nil, errorExpected: Bool = false) { let request = IndexRequest() request.sharingGroupUUID = sharingGroupUUID guard request.valid(), let parameters = request.urlParameters() else { XCTFail() return } self.performServerTest { expectation, creds in let headers = self.setupHeaders(testUser: .primaryOwningAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.index, headers: headers, urlParameters: "?" + parameters, body:nil) { response, dict in Log.info("Status code: \(response!.statusCode)") if errorExpected { XCTAssert(response!.statusCode != .OK) } else { XCTAssert(response!.statusCode == .OK, "Did not work on IndexRequest request") XCTAssert(dict != nil) if let indexResponse = try? IndexResponse.decode(dict!) { XCTAssert(indexResponse.masterVersion == masterVersionExpected) if let expectedFiles = expectedFiles { guard let fileIndex = indexResponse.fileIndex else { XCTFail() return } XCTAssert(fileIndex.count == expectedFiles.count) fileIndex.forEach { fileInfo in Log.info("fileInfo: \(fileInfo)") let filterResult = expectedFiles.filter { uploadFileRequest in uploadFileRequest.fileUUID == fileInfo.fileUUID } XCTAssert(filterResult.count == 1) let expectedFile = filterResult[0] XCTAssert(expectedFile.fileUUID == fileInfo.fileUUID) XCTAssert(expectedFile.fileVersion == fileInfo.fileVersion) XCTAssert(expectedFile.mimeType == fileInfo.mimeType) if expectedDeletionState == nil { XCTAssert(fileInfo.deleted == false) } else { XCTAssert(fileInfo.deleted == expectedDeletionState![fileInfo.fileUUID]) } XCTAssert(fileInfo.cloudStorageType != nil) } } } else { XCTFail() } } expectation.fulfill() } } } func getIndex(testAccount: TestAccount = .primaryOwningAccount, deviceUUID:String = Foundation.UUID().uuidString, sharingGroupUUID: String? = nil) -> ([FileInfo]?, [SyncServerShared.SharingGroup])? { var result:([FileInfo]?, [SyncServerShared.SharingGroup])? self.performServerTest(testAccount: testAccount) { expectation, creds in let headers = self.setupHeaders(testUser: testAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) let request = IndexRequest() request.sharingGroupUUID = sharingGroupUUID guard request.valid() else { expectation.fulfill() XCTFail() return } var urlParameters = "" if let parameters = request.urlParameters() { urlParameters = "?" + parameters } self.performRequest(route: ServerEndpoints.index, headers: headers, urlParameters: urlParameters, body:nil) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "Did not work on IndexRequest") XCTAssert(dict != nil) guard let indexResponse = try? IndexResponse.decode(dict!), let groups = indexResponse.sharingGroups else { expectation.fulfill() XCTFail() return } if sharingGroupUUID == nil { XCTAssert(indexResponse.fileIndex == nil) XCTAssert(indexResponse.masterVersion == nil) } else { XCTAssert(indexResponse.fileIndex != nil) XCTAssert(indexResponse.masterVersion != nil) } result = (indexResponse.fileIndex, groups) expectation.fulfill() } } return result } func getMasterVersion(testAccount: TestAccount = .primaryOwningAccount, deviceUUID:String = Foundation.UUID().uuidString, sharingGroupUUID: String) -> MasterVersionInt? { var result:MasterVersionInt? self.performServerTest(testAccount: testAccount) { expectation, creds in let headers = self.setupHeaders(testUser: testAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) let request = IndexRequest() request.sharingGroupUUID = sharingGroupUUID guard request.valid() else { expectation.fulfill() XCTFail() return } var urlParameters = "" if let parameters = request.urlParameters() { urlParameters = "?" + parameters } self.performRequest(route: ServerEndpoints.index, headers: headers, urlParameters: urlParameters, body:nil) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "Did not work on IndexRequest") XCTAssert(dict != nil) guard let indexResponse = try? IndexResponse.decode(dict!) else { expectation.fulfill() XCTFail() return } result = indexResponse.masterVersion expectation.fulfill() } } return result } func getUploads(expectedFiles:[UploadFileRequest], deviceUUID:String = Foundation.UUID().uuidString, expectedCheckSums: [String: String]? = nil, matchOptionals:Bool = true, expectedDeletionState:[String: Bool]? = nil, sharingGroupUUID: String, errorExpected: Bool = false) { if expectedCheckSums != nil { XCTAssert(expectedFiles.count == expectedCheckSums!.count) } let request = GetUploadsRequest() request.sharingGroupUUID = sharingGroupUUID guard request.valid(), let params = request.urlParameters() else { XCTFail() return } self.performServerTest { expectation, creds in let headers = self.setupHeaders(testUser: .primaryOwningAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.getUploads, headers: headers, urlParameters: "?" + params, body:nil) { response, dict in Log.info("Status code: \(response!.statusCode)") if errorExpected { XCTAssert(response!.statusCode != .OK) } else { XCTAssert(response!.statusCode == .OK, "Did not work on getUploadsRequest request") XCTAssert(dict != nil) } if let getUploadsResponse = try? GetUploadsResponse.decode(dict!) { if getUploadsResponse.uploads == nil { XCTAssert(expectedFiles.count == 0) if expectedCheckSums != nil { XCTAssert(expectedCheckSums!.count == 0) } } else { XCTAssert(getUploadsResponse.uploads!.count == expectedFiles.count) _ = getUploadsResponse.uploads!.map { fileInfo in Log.info("fileInfo: \(fileInfo)") let filterResult = expectedFiles.filter { requestMessage in requestMessage.fileUUID == fileInfo.fileUUID } XCTAssert(filterResult.count == 1) let expectedFile = filterResult[0] XCTAssert(expectedFile.fileUUID == fileInfo.fileUUID) XCTAssert(expectedFile.fileVersion == fileInfo.fileVersion) if matchOptionals { XCTAssert(expectedFile.mimeType == fileInfo.mimeType) } if expectedDeletionState == nil { XCTAssert(fileInfo.deleted == false) } else { XCTAssert(fileInfo.deleted == expectedDeletionState![fileInfo.fileUUID]) } } } } else { XCTFail() } expectation.fulfill() } } } func createSharingInvitation(testAccount: TestAccount = .primaryOwningAccount, permission: Permission? = nil, numberAcceptors: UInt = 1, allowSharingAcceptance: Bool = true, deviceUUID:String = Foundation.UUID().uuidString, sharingGroupUUID: String, errorExpected: Bool = false, completion:@escaping (_ expectation: XCTestExpectation, _ sharingInvitationUUID:String?)->()) { self.performServerTest(testAccount: testAccount) { expectation, testCreds in let headers = self.setupHeaders(testUser:testAccount, accessToken: testCreds.accessToken, deviceUUID:deviceUUID) let request = CreateSharingInvitationRequest() request.sharingGroupUUID = sharingGroupUUID request.numberOfAcceptors = numberAcceptors request.allowSocialAcceptance = allowSharingAcceptance if permission != nil { request.permission = permission! } self.performRequest(route: ServerEndpoints.createSharingInvitation, headers: headers, urlParameters: "?" + request.urlParameters()!, body:nil) { response, dict in Log.info("Status code: \(response!.statusCode)") if errorExpected { XCTAssert(response!.statusCode != .OK) completion(expectation, nil) } else { XCTAssert(response!.statusCode == .OK, "Did not work on request: \(response!.statusCode)") XCTAssert(dict != nil) let response = try? CreateSharingInvitationResponse.decode(dict!) completion(expectation, response?.sharingInvitationUUID) } } } } // This also creates the owning user-- using .primaryOwningAccount func createSharingUser(withSharingPermission permission:Permission = .read, sharingUser:TestAccount = .google2, addUser:AddUser = .yes, owningUserWhenCreating:TestAccount = .primaryOwningAccount, numberAcceptors: UInt = 1, allowSharingAcceptance: Bool = true, failureExpected: Bool = false, completion:((_ newSharingUserId:UserId?, _ sharingGroupUUID: String?, _ sharingInvitationUUID:String?)->())? = nil) { // a) Create sharing invitation with one account. // b) Next, need to "sign out" of that account, and sign into another account // c) And, redeem sharing invitation with that new account. // Create the owning user, if needed. let deviceUUID = Foundation.UUID().uuidString var actualSharingGroupUUID:String! switch addUser { case .no(let sharingGroupUUID): actualSharingGroupUUID = sharingGroupUUID case .yes: actualSharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(testAccount: owningUserWhenCreating, sharingGroupUUID: actualSharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() completion?(nil, nil, nil) return } } var sharingInvitationUUID:String! createSharingInvitation(testAccount: owningUserWhenCreating, permission: permission, numberAcceptors: numberAcceptors, allowSharingAcceptance: allowSharingAcceptance, sharingGroupUUID:actualSharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } redeemSharingInvitation(sharingUser:sharingUser, sharingInvitationUUID: sharingInvitationUUID, errorExpected: failureExpected) { result, expectation in if !failureExpected { XCTAssert(result?.userId != nil && result?.sharingGroupUUID != nil) } expectation.fulfill() } if failureExpected { completion?(nil, nil, nil) } else { // Check to make sure we have a new user: let userKey = UserRepository.LookupKey.accountTypeInfo(accountType: sharingUser.scheme.accountName, credsId: sharingUser.id()) let userResults = UserRepository(self.db).lookup(key: userKey, modelInit: User.init) guard case .found(let model) = userResults else { Log.debug("sharingUser.type: \(sharingUser.scheme.accountName); sharingUser.id(): \(sharingUser.id())") XCTFail() completion?(nil, nil, nil) return } let key = SharingInvitationRepository.LookupKey.sharingInvitationUUID(uuid: sharingInvitationUUID) let results = SharingInvitationRepository(self.db).lookup(key: key, modelInit: SharingInvitation.init) if numberAcceptors <= 1 { guard case .noObjectFound = results else { XCTFail() completion?(nil, nil, nil) return } } guard let (_, sharingGroups) = getIndex() else { XCTFail() return } guard sharingGroups.count == 1 else { XCTFail() return } XCTAssert(sharingGroups[0].sharingGroupUUID == actualSharingGroupUUID) XCTAssert(sharingGroups[0].sharingGroupName == nil) XCTAssert(sharingGroups[0].deleted == false) guard sharingGroups[0].sharingGroupUsers != nil else { XCTFail() return } guard sharingGroups[0].sharingGroupUsers.count >= 2 else { XCTFail() return } sharingGroups[0].sharingGroupUsers.forEach { sgu in XCTAssert(sgu.name != nil) XCTAssert(sgu.userId != nil) } completion?((model as! User).userId, actualSharingGroupUUID, sharingInvitationUUID) } } func redeemSharingInvitation(sharingUser:TestAccount, deviceUUID:String = Foundation.UUID().uuidString, canGiveCloudFolderName: Bool = true, sharingInvitationUUID:String? = nil, errorExpected:Bool=false, completion:@escaping (_ result: RedeemSharingInvitationResponse?, _ expectation: XCTestExpectation)->()) { var actualCloudFolderName: String? if sharingUser.scheme.accountName == AccountScheme.google.accountName && canGiveCloudFolderName { actualCloudFolderName = ServerTestCase.cloudFolderName } self.performServerTest(testAccount:sharingUser) { expectation, accountCreds in let headers = self.setupHeaders(testUser: sharingUser, accessToken: accountCreds.accessToken, deviceUUID:deviceUUID) var urlParameters:String? if sharingInvitationUUID != nil { let request = RedeemSharingInvitationRequest() request.sharingInvitationUUID = sharingInvitationUUID! request.cloudFolderName = actualCloudFolderName urlParameters = "?" + request.urlParameters()! } self.performRequest(route: ServerEndpoints.redeemSharingInvitation, headers: headers, urlParameters: urlParameters, body:nil) { response, dict in Log.info("Status code: \(response!.statusCode)") var result: RedeemSharingInvitationResponse? if errorExpected { XCTAssert(response!.statusCode != .OK, "Worked on request!") } else { XCTAssert(response!.statusCode == .OK, "Did not work on request") if let dict = dict, let redeemSharingInvitationResponse = try? RedeemSharingInvitationResponse.decode(dict) { result = redeemSharingInvitationResponse } else { XCTFail() } } completion(result, expectation) } } } func getSharingInvitationInfo(sharingInvitationUUID:String? = nil, errorExpected:Bool=false, httpStatusCodeExpected: HTTPStatusCode = .OK, completion:@escaping (_ result: GetSharingInvitationInfoResponse?, _ expectation: XCTestExpectation)->()) { self.performServerTest() { expectation in var urlParameters:String? if sharingInvitationUUID != nil { let request = GetSharingInvitationInfoRequest() request.sharingInvitationUUID = sharingInvitationUUID! urlParameters = "?" + request.urlParameters()! } self.performRequest(route: ServerEndpoints.getSharingInvitationInfo, urlParameters: urlParameters) { response, dict in Log.info("Status code: \(response!.statusCode)") var result: GetSharingInvitationInfoResponse? if errorExpected { XCTAssert(response!.statusCode == httpStatusCodeExpected, "ERROR: Worked on request!") } else { XCTAssert(response!.statusCode == .OK, "Did not work on request") if let dict = dict, let getSharingInvitationInfoResponse = try? GetSharingInvitationInfoResponse.decode(dict) { result = getSharingInvitationInfoResponse } else { XCTFail() } } completion(result, expectation) } } } func getSharingInvitationInfo(sharingInvitationUUID:String? = nil, errorExpected:Bool=false, httpStatusCodeExpected: HTTPStatusCode = .OK) -> GetSharingInvitationInfoResponse? { var result:GetSharingInvitationInfoResponse? getSharingInvitationInfo(sharingInvitationUUID: sharingInvitationUUID, errorExpected: errorExpected, httpStatusCodeExpected: httpStatusCodeExpected) { response, exp in result = response exp.fulfill() } return result } func getSharingInvitationInfoWithSecondaryAuth(testAccount: TestAccount, sharingInvitationUUID:String? = nil, errorExpected:Bool=false, httpStatusCodeExpected: HTTPStatusCode = .OK, completion:@escaping (_ result: GetSharingInvitationInfoResponse?, _ expectation: XCTestExpectation)->()) { let deviceUUID = Foundation.UUID().uuidString self.performServerTest(testAccount: testAccount) { expectation, account in var urlParameters:String? let headers = self.setupHeaders(testUser:testAccount, accessToken: account.accessToken, deviceUUID:deviceUUID) if sharingInvitationUUID != nil { let request = GetSharingInvitationInfoRequest() request.sharingInvitationUUID = sharingInvitationUUID! urlParameters = "?" + request.urlParameters()! } self.performRequest(route: ServerEndpoints.getSharingInvitationInfo, headers: headers, urlParameters: urlParameters) { response, dict in Log.info("Status code: \(response!.statusCode)") var result: GetSharingInvitationInfoResponse? if errorExpected { XCTAssert(response!.statusCode == httpStatusCodeExpected, "ERROR: Worked on request!") } else { XCTAssert(response!.statusCode == .OK, "Did not work on request") if let dict = dict, let getSharingInvitationInfoResponse = try? GetSharingInvitationInfoResponse.decode(dict) { result = getSharingInvitationInfoResponse } else { XCTFail() } } completion(result, expectation) } } } func uploadDeletion(testAccount:TestAccount = .primaryOwningAccount, uploadDeletionRequest:UploadDeletionRequest, deviceUUID:String, addUser:Bool=true, updatedMasterVersionExpected:Int64? = nil, expectError:Bool = false) { if addUser { let sharingGroupUUID = UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } } self.performServerTest(testAccount:testAccount) { expectation, testCreds in let headers = self.setupHeaders(testUser:testAccount, accessToken: testCreds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.uploadDeletion, headers: headers, urlParameters: "?" + uploadDeletionRequest.urlParameters()!) { response, dict in Log.info("Status code: \(response!.statusCode)") if expectError { XCTAssert(response!.statusCode != .OK, "Did not fail on upload deletion request") } else { XCTAssert(response!.statusCode == .OK, "Did not work on upload deletion request") XCTAssert(dict != nil) if let uploadDeletionResponse = try? UploadDeletionResponse.decode(dict!) { if updatedMasterVersionExpected != nil { XCTAssert(uploadDeletionResponse.masterVersionUpdate == updatedMasterVersionExpected) } } else { XCTFail() } } expectation.fulfill() } } } @discardableResult func downloadServerFile(testAccount:TestAccount = .primaryOwningAccount, mimeType: MimeType = .text, file: TestFile = .test1, masterVersionExpectedWithDownload:Int, expectUpdatedMasterUpdate:Bool = false, appMetaData:AppMetaData? = nil, uploadFileVersion:FileVersionInt = 0, downloadFileVersion:FileVersionInt = 0, uploadFileRequest:UploadFileRequest? = nil, expectedError: Bool = false, contentsChangedExpected: Bool = false) -> DownloadFileResponse? { let deviceUUID = Foundation.UUID().uuidString let masterVersion:Int64 = 0 var actualUploadFileRequest:UploadFileRequest! var actualCheckSum:String! let beforeUploadTime = Date() var afterUploadTime:Date! var fileUUID:String! var actualSharingGroupUUID: String! if uploadFileRequest == nil { guard let uploadResult = uploadServerFile(mimeType: mimeType, deviceUUID:deviceUUID, fileVersion:uploadFileVersion, masterVersion:masterVersion, cloudFolderName: ServerTestCase.cloudFolderName, appMetaData:appMetaData, file: file), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return nil } actualSharingGroupUUID = sharingGroupUUID fileUUID = uploadResult.request.fileUUID actualUploadFileRequest = uploadResult.request actualCheckSum = uploadResult.checkSum self.sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) afterUploadTime = Date() } else { actualUploadFileRequest = uploadFileRequest actualCheckSum = uploadFileRequest!.checkSum actualSharingGroupUUID = uploadFileRequest!.sharingGroupUUID } var result:DownloadFileResponse? self.performServerTest(testAccount:testAccount) { expectation, testCreds in let headers = self.setupHeaders(testUser:testAccount, accessToken: testCreds.accessToken, deviceUUID:deviceUUID) let downloadFileRequest = DownloadFileRequest() downloadFileRequest.fileUUID = actualUploadFileRequest!.fileUUID downloadFileRequest.masterVersion = MasterVersionInt(masterVersionExpectedWithDownload) downloadFileRequest.fileVersion = downloadFileVersion downloadFileRequest.appMetaDataVersion = appMetaData?.version downloadFileRequest.sharingGroupUUID = actualSharingGroupUUID self.performRequest(route: ServerEndpoints.downloadFile, responseDictFrom:.header, headers: headers, urlParameters: "?" + downloadFileRequest.urlParameters()!, body:nil) { response, dict in Log.info("Status code: \(response!.statusCode)") if expectedError { XCTAssert(response!.statusCode != .OK, "Did not work on failing downloadFileRequest request") XCTAssert(dict == nil) } else { XCTAssert(response!.statusCode == .OK, "Did not work on downloadFileRequest request") XCTAssert(dict != nil) if let dict = dict, let downloadFileResponse = try? DownloadFileResponse.decode(dict) { result = downloadFileResponse if expectUpdatedMasterUpdate { XCTAssert(downloadFileResponse.masterVersionUpdate != nil) } else { XCTAssert(downloadFileResponse.contentsChanged == contentsChangedExpected) XCTAssert(downloadFileResponse.masterVersionUpdate == nil) var loadTesting = false if let loadTestingCloudStorage = Configuration.server.loadTestingCloudStorage, loadTestingCloudStorage { loadTesting = true } if !loadTesting { XCTAssert(downloadFileResponse.checkSum == actualCheckSum, "downloadFileResponse.checkSum: \(String(describing: downloadFileResponse.checkSum)); actualCheckSum: \(String(describing: actualCheckSum))") } XCTAssert(downloadFileResponse.appMetaData == appMetaData?.contents) guard let _ = downloadFileResponse.cloudStorageType else { XCTFail() return } XCTAssert(downloadFileResponse.checkSum != nil) } } else { XCTFail() } } expectation.fulfill() } } if let afterUploadTime = afterUploadTime, let fileUUID = fileUUID { checkThatDateFor(fileUUID: fileUUID, isBetween: beforeUploadTime, end: afterUploadTime, sharingGroupUUID: actualSharingGroupUUID) } return result } @discardableResult func downloadTextFile(testAccount:TestAccount = .primaryOwningAccount, masterVersionExpectedWithDownload:Int, expectUpdatedMasterUpdate:Bool = false, appMetaData:AppMetaData? = nil, uploadFileVersion:FileVersionInt = 0, downloadFileVersion:FileVersionInt = 0, uploadFileRequest:UploadFileRequest? = nil, expectedError: Bool = false, contentsChangedExpected: Bool = false) -> DownloadFileResponse? { return downloadServerFile(testAccount:testAccount, mimeType: .text, file: .test1, masterVersionExpectedWithDownload:masterVersionExpectedWithDownload, expectUpdatedMasterUpdate:expectUpdatedMasterUpdate, appMetaData:appMetaData, uploadFileVersion:uploadFileVersion, downloadFileVersion:downloadFileVersion, uploadFileRequest:uploadFileRequest, expectedError: expectedError, contentsChangedExpected: contentsChangedExpected) } func checkThatDateFor(fileUUID: String, isBetween start: Date, end: Date, sharingGroupUUID:String) { guard let (files, _) = getIndex(sharingGroupUUID:sharingGroupUUID), let fileInfo = files else { XCTFail() return } let file = fileInfo.filter({$0.fileUUID == fileUUID})[0] // let comp1 = file.creationDate!.compare(start) // I've been having problems here comparing dates. It seems that this is akin to the problem of comparing real numbers, and the general rule that you shouldn't test real numbers for equality. To help in this, I'm going to just use the mm/dd/yy and hh:mm:ss components of the dates. func clean(_ date: Date) -> Date { // 6/12/19; Due to Swift 5.0.1 issue; See https://stackoverflow.com/questions/56555005/swift-5-ubuntu-16-04-crash-with-datecomponents // not using Calendar.current let calendar = Calendar(identifier: .gregorian) let orig = calendar.dateComponents( [.day, .month, .year, .hour, .minute, .second], from: date) var new = DateComponents() new.day = orig.day new.month = orig.month new.year = orig.year new.hour = orig.hour new.minute = orig.minute new.second = orig.second return Calendar.current.date(from: new)! } let cleanCreationDate = clean(file.creationDate!) let cleanStart = clean(start) let cleanEnd = clean(end) XCTAssert(cleanStart <= cleanCreationDate, "start: \(cleanStart); file.creationDate: \(cleanCreationDate)") XCTAssert(cleanCreationDate <= cleanEnd, "file.creationDate: \(cleanCreationDate); end: \(cleanEnd)") } @discardableResult func uploadFile(accountType: AccountScheme.AccountName, creds: CloudStorage, deviceUUID:String, testFile: TestFile, uploadRequest:UploadFileRequest, options:CloudStorageFileNameOptions? = nil, nonStandardFileName: String? = nil, failureExpected: Bool = false, errorExpected: CloudStorageError? = nil, expectAccessTokenRevokedOrExpired: Bool = false) -> String? { var fileContentsData: Data! switch testFile.contents { case .string(let fileContents): fileContentsData = fileContents.data(using: .ascii)! case .url(let url): fileContentsData = try? Data(contentsOf: url) } guard fileContentsData != nil else { XCTFail() return nil } var cloudFileName:String! if let nonStandardFileName = nonStandardFileName { cloudFileName = nonStandardFileName } else { cloudFileName = uploadRequest.cloudFileName(deviceUUID:deviceUUID, mimeType: uploadRequest.mimeType) } let exp = expectation(description: "\(#function)\(#line)") creds.uploadFile(cloudFileName: cloudFileName, data: fileContentsData, options: options) { result in switch result { case .success(let checkSum): XCTAssert(testFile.checkSum(type: accountType) == checkSum) Log.debug("checkSum: \(checkSum)") if failureExpected { XCTFail() } case .failure(let error): if expectAccessTokenRevokedOrExpired { XCTFail() } cloudFileName = nil Log.debug("uploadFile: \(error)") if !failureExpected { XCTFail() } if let errorExpected = errorExpected { guard let error = error as? CloudStorageError else { XCTFail() exp.fulfill() return } XCTAssert(error == errorExpected) } case .accessTokenRevokedOrExpired: if !expectAccessTokenRevokedOrExpired { XCTFail() } } exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) return cloudFileName } func addSharingGroup(sharingGroupUUID: String, sharingGroupName: String? = nil) -> Bool { let result = SharingGroupRepository(db).add(sharingGroupUUID: sharingGroupUUID, sharingGroupName: sharingGroupName) switch result { case .success: return true default: XCTFail() } return false } } <file_sep>// // ServerSetup.swift // Server // // Created by <NAME> on 6/2/17. // // import Foundation import Kitura import KituraSession import Credentials import CredentialsGoogle import CredentialsFacebook import CredentialsDropbox import CredentialsMicrosoft import SyncServerShared import LoggerAPI class ServerSetup { // Just a guess. Don't know what's suitable for length. See https://github.com/IBM-Swift/Kitura/issues/917 private static let secretStringLength = 256 private static func randomString(length: Int) -> String { let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let len = UInt32(letters.length) var randomString = "" for _ in 0 ..< length { #if os(Linux) let rand = random() % Int(len) #else let rand = arc4random_uniform(len) #endif let nextChar = letters.character(at: Int(rand)) randomString += String(UnicodeScalar(nextChar)!) } return randomString } static func credentials(_ router:Router) { let secret = self.randomString(length: secretStringLength) router.all(middleware: KituraSession.Session(secret: secret)) // If credentials are not authorized by this middleware (e.g., valid Google creds), then an "unauthorized" HTTP code is sent back, with an empty response body. let credentials = Credentials() // Needed for testing. AccountManager.session.reset() if Configuration.server.allowedSignInTypes.Google == true { let googleCredentials = CredentialsGoogleToken(tokenTimeToLive: Configuration.server.signInTokenTimeToLive) credentials.register(plugin: googleCredentials) AccountManager.session.addAccountType(GoogleCreds.self) } if Configuration.server.allowedSignInTypes.Facebook == true { let facebookCredentials = CredentialsFacebookToken(tokenTimeToLive: Configuration.server.signInTokenTimeToLive) credentials.register(plugin: facebookCredentials) AccountManager.session.addAccountType(FacebookCreds.self) } if Configuration.server.allowedSignInTypes.Dropbox == true { let dropboxCredentials = CredentialsDropboxToken(tokenTimeToLive: Configuration.server.signInTokenTimeToLive) credentials.register(plugin: dropboxCredentials) AccountManager.session.addAccountType(DropboxCreds.self) } if Configuration.server.allowedSignInTypes.Microsoft == true { let microsoftCredentials = CredentialsMicrosoftToken(tokenTimeToLive: Configuration.server.signInTokenTimeToLive) credentials.register(plugin: microsoftCredentials) AccountManager.session.addAccountType(MicrosoftCreds.self) } // 8/8/17; There needs to be at least one sign-in type configured for the server to do anything. And at least one of these needs to allow owning users. If there can be no owning users, how do you create anything to share? https://github.com/crspybits/SyncServerII/issues/9 if AccountManager.session.numberAccountTypes == 0 { Log.error("There are no sign-in types configured!") exit(1) } if AccountManager.session.numberOfOwningAccountTypes == 0 { Log.error("There are no owning sign-in types configured!") exit(1) } router.all { (request, response, next) in Log.info("REQUEST RECEIVED: \(request.urlURL.path)") for route in ServerEndpoints.session.all { if route.authenticationLevel == .none && route.path == request.urlURL.path { next() return } } credentials.handle(request: request, response: response, next: next) } } } <file_sep>// // FileController+UploadAppMetaData.swift // Server // // Created by <NAME> on 3/23/18. // import Foundation import LoggerAPI import SyncServerShared extension FileController { func uploadAppMetaData(params:RequestProcessingParameters) { guard let uploadAppMetaDataRequest = params.request as? UploadAppMetaDataRequest else { Log.error("Did not receive UploadAppMetaDataRequest") params.completion(.failure(nil)) return } guard sharingGroupSecurityCheck(sharingGroupUUID: uploadAppMetaDataRequest.sharingGroupUUID, params: params) else { Log.error("Failed in sharing group security check.") params.completion(.failure(nil)) return } Controllers.getMasterVersion(sharingGroupUUID: uploadAppMetaDataRequest.sharingGroupUUID, params: params) { error, masterVersion in if error != nil { let message = "Error: \(String(describing: error))" Log.error(message) params.completion(.failure(.message(message))) return } if masterVersion != uploadAppMetaDataRequest.masterVersion { let response = UploadAppMetaDataResponse() Log.warning("Master version update: \(String(describing: masterVersion))") response.masterVersionUpdate = masterVersion params.completion(.success(response)) return } // Make sure this file is already present in the FileIndex. var existingFileInFileIndex:FileIndex? do { existingFileInFileIndex = try FileController.checkForExistingFile(params:params, sharingGroupUUID: uploadAppMetaDataRequest.sharingGroupUUID, fileUUID:uploadAppMetaDataRequest.fileUUID) } catch (let error) { let message = "Could not lookup file in FileIndex: \(error)" Log.error(message) params.completion(.failure(.message(message))) return } guard existingFileInFileIndex != nil else { let message = "File not found in FileIndex!" Log.error(message) params.completion(.failure(.message(message))) return } // Undeletion is not possible for an appMetaData upload because the file contents have been removed (on a prior upload deletion) and the appMetaData upload can't replace those file contents. if existingFileInFileIndex!.deleted { let message = "Attempt to upload app meta data for an existing file, but it has already been deleted." Log.error(message) params.completion(.failure(.message(message))) return } guard UploadRepository.isValidAppMetaDataUpload( currServerAppMetaDataVersion: existingFileInFileIndex!.appMetaDataVersion, currServerAppMetaData: existingFileInFileIndex!.appMetaData, upload:uploadAppMetaDataRequest.appMetaData) else { let message = "App meta data or version is not valid for upload." Log.error(message) params.completion(.failure(.message(message))) return } let upload = Upload() upload.deviceUUID = params.deviceUUID upload.fileUUID = uploadAppMetaDataRequest.fileUUID upload.state = .uploadingAppMetaData upload.userId = params.currentSignedInUser!.userId upload.appMetaData = uploadAppMetaDataRequest.appMetaData!.contents upload.appMetaDataVersion = uploadAppMetaDataRequest.appMetaData!.version upload.sharingGroupUUID = uploadAppMetaDataRequest.sharingGroupUUID var errorString:String? let addUploadResult = params.repos.upload.add(upload: upload, fileInFileIndex: true) switch addUploadResult { case .success: break case .duplicateEntry: // Not considering this an error for client recovery purposes. break case .aModelValueWasNil: errorString = "A model value was nil!" case .deadlock: errorString = "Deadlock" case .waitTimeout: errorString = "WaitTimeout" case .otherError(let error): errorString = error } if errorString != nil { Log.error(errorString!) params.completion(.failure(.message(errorString!))) return } let response = UploadAppMetaDataResponse() params.completion(.success(response)) } } } <file_sep>// // AppleSignInCreds+ClientSecret.swift // Server // // Created by <NAME> on 10/5/19. // import Foundation import SwiftJWT // Notes about creating the client secret: // https://auth0.com/blog/what-is-sign-in-with-apple-a-new-identity-provider/ // https://medium.com/identity-beyond-borders/adding-sign-in-with-apple-to-your-app-in-under-5mins-with-zero-code-ce36966b03f0 /* The client secret is a JWT. The parameters for this seem to be: 1) a private key generated at: https://developer.apple.com/account/resources/authkeys/list What should you use for a Key Name? 2) And your TEAM_ID, and KEY_ID The KEY_ID is from the Apple Developer Portal when you created the private key. The TEAM_ID is from your apple developer account. I'm going to use IBM's Swift-JWT package to generate this JWT at run time. */ struct ClientSecretPayload: Claims { // The issuer registered claim key, which has the value of your 10-character Team ID, obtained from your developer account. let iss: String // The issued at registered claim key, the value of which indicates the time at which the token was generated, in terms of the number of seconds since Epoch, in UTC. let iat: Date // The expiration time registered claim key, the value of which must not be greater than 15777000 (6 months in seconds) from the Current Unix Time on the server. let exp: Date // The audience registered claim key, the value of which identifies the recipient the JWT is intended for. // Since this token is meant for Apple, use https://appleid.apple.com. let aud: String // The subject registered claim key, the value of which identifies the principal that is the subject of the JWT. Use the same value as client_id as this token is meant for your application. let sub: String } extension AppleSignInCreds { func createClientSecret() -> String? { let privateKey = config.privateKey.replacingOccurrences(of: "\\n", with: "\n") guard let privateKeyData = privateKey.data(using: .utf8) else { return nil } let jwtSigner:JWTSigner // Is this going to work on Linux? if #available(OSX 10.13, *) { jwtSigner = JWTSigner.es256(privateKey: privateKeyData) } else { return nil } // I think by `kid`, they mean key id. // For the fields in the header and payload, see // https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens let header = Header(kid: config.keyId) let expiryIntervalOneDay: TimeInterval = 60 * 60 * 24 let exp = Date().addingTimeInterval(expiryIntervalOneDay) let payload = ClientSecretPayload(iss: config.teamId, iat: Date(), exp: exp, aud: "https://appleid.apple.com", sub: config.clientId) var jwt = JWT(header: header, claims: payload) let result = try? jwt.sign(using: jwtSigner) return result } } <file_sep>// // Repositories.swift // Server // // Created by <NAME> on 2/7/17. // // import Foundation struct Repositories { let db: Database lazy var user = UserRepository(db) lazy var masterVersion = MasterVersionRepository(db) lazy var fileIndex = FileIndexRepository(db) lazy var upload = UploadRepository(db) lazy var deviceUUID = DeviceUUIDRepository(db) lazy var sharing = SharingInvitationRepository(db) lazy var sharingGroup = SharingGroupRepository(db) lazy var sharingGroupUser = SharingGroupUserRepository(db) init(db: Database) { self.db = db } } <file_sep>// // FileController_MultiVersionFiles.swift // Server // // Created by <NAME> on 1/7/18. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class FileController_MultiVersionFiles: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // MARK: Upload func uploadNextFileVersion(uploadRequest: UploadFileRequest, masterVersion: MasterVersionInt, fileVersionToUpload:FileVersionInt, creationDate: Date, mimeType: String, appMetaData: AppMetaData, checkSum:String) { guard let healthCheck1 = healthCheck() else { XCTFail() return } // The use of a different device UUID here is part of this test-- that the second version can be uploaded with a different device UUID. let deviceUUID = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID: deviceUUID, fileUUID: uploadRequest.fileUUID, addUser: .no(sharingGroupUUID: uploadRequest.sharingGroupUUID), fileVersion:fileVersionToUpload, masterVersion: masterVersion, appMetaData: appMetaData), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) guard let healthCheck2 = healthCheck() else { XCTFail() return } // New upload device UUID will go into the FileIndex as that of the new uploading device. guard let (files, _) = getIndex(deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID), let fileInfoArray = files, fileInfoArray.count == 1 else { XCTFail() return } let result = fileInfoArray.filter({$0.fileUUID == uploadRequest.fileUUID}) guard result.count == 1 else { XCTFail() return } XCTAssert(result[0].deviceUUID == deviceUUID) XCTAssert(result[0].fileVersion == 1) // Make sure updateDate has changed appropriately (server should establish this). Make sure that creationDate hasn't changed. XCTAssert(healthCheck1.currentServerDateTime <= result[0].updateDate!) XCTAssert(healthCheck2.currentServerDateTime >= result[0].updateDate!) XCTAssert(result[0].creationDate == creationDate) XCTAssert(result[0].mimeType == mimeType) XCTAssert(result[0].deleted == false) XCTAssert(result[0].fileVersion == fileVersionToUpload) guard let _ = self.downloadTextFile(masterVersionExpectedWithDownload: Int(masterVersion + 1), appMetaData: appMetaData, downloadFileVersion: fileVersionToUpload, uploadFileRequest: uploadRequest) else { XCTFail() return } } // Also tests to make sure a different device UUID can upload the second version. func testUploadVersion1AfterVersion0Works() { let mimeType = "text/plain" let fileVersion:FileVersionInt = 1 let deviceUUID1 = Foundation.UUID().uuidString var appMetaDataVersion: AppMetaDataVersionInt = 0 guard let uploadResult = uploadTextFile(deviceUUID: deviceUUID1, appMetaData: AppMetaData(version: 0, contents: "Some-App-Meta-Data")), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // Send DoneUploads-- to commit version 0. sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, sharingGroupUUID: sharingGroupUUID) appMetaDataVersion += 1 var creationDate:Date! guard let (files, _) = getIndex(deviceUUID: deviceUUID1, sharingGroupUUID: sharingGroupUUID), let fileInfoArray = files, fileInfoArray.count == 1 else { XCTFail() return } creationDate = fileInfoArray[0].creationDate guard creationDate != nil else { XCTFail() return } uploadNextFileVersion(uploadRequest: uploadResult.request, masterVersion: 1, fileVersionToUpload:fileVersion, creationDate: creationDate!, mimeType: mimeType, appMetaData: AppMetaData(version: 1, contents: "Some-Other-App-Meta-Data"), checkSum:uploadResult.checkSum) } // Attempt to upload version 1 when version 0 hasn't yet been committed with DoneUploads-- should fail. func testUploadVersion1WhenVersion0HasNotBeenCommitted() { let deviceUUID1 = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID: deviceUUID1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } let deviceUUID2 = Foundation.UUID().uuidString uploadTextFile(deviceUUID: deviceUUID2, fileUUID: uploadResult.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion:1, masterVersion: 0, errorExpected: true) } // Upload version N of a file; do DoneUploads. Then try again to upload version N. That should fail. func testUploadOfSameFileVersionFails() { let deviceUUID1 = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID: deviceUUID1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // Send DoneUploads-- to commit version 0. sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, sharingGroupUUID: sharingGroupUUID) let deviceUUID2 = Foundation.UUID().uuidString uploadTextFile(deviceUUID: deviceUUID2, fileUUID: uploadResult.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion:0, masterVersion: 1, errorExpected: true) guard let (files, _) = getIndex(deviceUUID: deviceUUID1, sharingGroupUUID: sharingGroupUUID), let fileInfoArray = files, fileInfoArray.count == 1 else { XCTFail() return } let result = fileInfoArray.filter({$0.fileUUID == uploadResult.request.fileUUID}) guard result.count == 1 else { XCTFail() return } XCTAssert(result[0].deviceUUID == deviceUUID1) XCTAssert(result[0].fileVersion == 0) } func testUploadVersion1OfNewFileFails() { _ = uploadTextFile(fileVersion:1, errorExpected: true) } let appMetaData = "Some-App-Meta-Data" @discardableResult // Master version after this call is sent back. func uploadVersion(_ version: FileVersionInt, deviceUUID:String = Foundation.UUID().uuidString, fileUUID:String, startMasterVersion: MasterVersionInt = 0, addUser:AddUser = .yes) -> (MasterVersionInt, UploadFileRequest)? { var masterVersion:MasterVersionInt = startMasterVersion guard let uploadResult = uploadTextFile(deviceUUID: deviceUUID, fileUUID:fileUUID, addUser:addUser, masterVersion:masterVersion, appMetaData:AppMetaData(version: 0, contents: appMetaData)), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return nil } // Send DoneUploads-- to commit version 0. sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion:masterVersion, sharingGroupUUID: sharingGroupUUID) masterVersion += 1 var fileVersion:FileVersionInt = 1 for _ in 1...version { guard let _ = uploadTextFile(deviceUUID: deviceUUID, fileUUID: uploadResult.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion:fileVersion, masterVersion: masterVersion) else { XCTFail() return nil } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID, masterVersion: masterVersion, sharingGroupUUID: sharingGroupUUID) fileVersion += 1 masterVersion += 1 } return (masterVersion, uploadResult.request) } // Upload some number (e.g., 5) of new versions. func testSuccessiveUploadsOfNextVersionWorks() { let fileUUID = Foundation.UUID().uuidString uploadVersion(5, fileUUID:fileUUID) } func testUploadDifferentFileContentsForSecondVersionWorks() { // Upload small text file first. let deviceUUID1 = Foundation.UUID().uuidString guard let uploadResult1 = uploadTextFile(deviceUUID: deviceUUID1, appMetaData:AppMetaData(version: 0, contents: appMetaData)), let sharingGroupUUID = uploadResult1.sharingGroupUUID else { XCTFail() return } // Send DoneUploads-- to commit version 0. sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, masterVersion: 0, sharingGroupUUID: sharingGroupUUID) // Then upload some other text contents -- as version 1 of the same file. let appMetaData2 = AppMetaData(version: 1, contents: appMetaData) guard let uploadResult2 = uploadTextFile(deviceUUID: deviceUUID1, fileUUID:uploadResult1.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion: 1, masterVersion: 1, appMetaData:appMetaData2, stringFile: TestFile.test2) else { XCTFail() return } sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, masterVersion: 1, sharingGroupUUID: sharingGroupUUID) // Make sure the file contents are right. guard let (files, _) = getIndex(deviceUUID: deviceUUID1, sharingGroupUUID: sharingGroupUUID), let fileInfoArray = files, fileInfoArray.count == 1 else { XCTFail() return } let result = fileInfoArray.filter({$0.fileUUID == uploadResult1.request.fileUUID}) guard result.count == 1 else { XCTFail() return } guard let _ = self.downloadTextFile(masterVersionExpectedWithDownload: 2, appMetaData: appMetaData2, downloadFileVersion: 1, uploadFileRequest: uploadResult2.request) else { XCTFail() return } } // Next version uploaded must be +1 func testUploadOfVersion2OfVersion0FileFails() { let deviceUUID1 = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID: deviceUUID1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // Send DoneUploads-- to commit version 0. sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, sharingGroupUUID: sharingGroupUUID) let deviceUUID2 = Foundation.UUID().uuidString // This will return nil because of the expected error. uploadTextFile(deviceUUID: deviceUUID2, fileUUID: uploadResult.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion:2, masterVersion: 1, errorExpected: true) } // Next version uploaded must have the same mimeType func testUploadDifferentVersionWithDifferentMimeTypeFails() { let deviceUUID1 = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID: deviceUUID1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // Send DoneUploads-- to commit version 0. sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, sharingGroupUUID: sharingGroupUUID) guard let _ = uploadJPEGFile(deviceUUID:deviceUUID1, fileUUID: uploadResult.request.fileUUID, addUser:.no(sharingGroupUUID: sharingGroupUUID), fileVersion:1, expectedMasterVersion:1, errorExpected: true) else { XCTFail() return } } func testUploadOfTwoConsecutiveVersionsWithoutADoneUploadsAfterVersion0IsUploadedFails() { let deviceUUID1 = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID:deviceUUID1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // Send DoneUploads-- to commit version 0. sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, sharingGroupUUID: sharingGroupUUID) let deviceUUID2 = Foundation.UUID().uuidString guard let _ = uploadTextFile(deviceUUID: deviceUUID2, fileUUID: uploadResult.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion:1, masterVersion: 1, errorExpected: false) else { XCTFail() return } // Returns nil because of expected error. uploadTextFile(deviceUUID: deviceUUID2, fileUUID: uploadResult.request.fileUUID, addUser: .no(sharingGroupUUID: sharingGroupUUID), fileVersion:2, masterVersion: 1, errorExpected: true) } // MARK: Upload deletion. // Upload version 0. Try to delete version 1. func testUploadDeletionOfVersionThatDoesNotExistFails() { let deviceUUID1 = Foundation.UUID().uuidString guard let uploadResult = uploadTextFile(deviceUUID: deviceUUID1), let sharingGroupUUID = uploadResult.sharingGroupUUID else { XCTFail() return } // Send DoneUploads-- to commit version 0. sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID:deviceUUID1, sharingGroupUUID: sharingGroupUUID) let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = uploadResult.request.fileUUID uploadDeletionRequest.fileVersion = uploadResult.request.fileVersion + 1 uploadDeletionRequest.masterVersion = uploadResult.request.masterVersion + MasterVersionInt(1) uploadDeletionRequest.sharingGroupUUID = sharingGroupUUID uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID1, addUser: false, expectError: true) } func testUploadDeletionOfVersionThatExistsWorks() { let fileUUID = Foundation.UUID().uuidString guard let (masterVersion, uploadRequest) = uploadVersion(2, fileUUID:fileUUID) else { XCTFail() return } let uploadDeletionRequest = UploadDeletionRequest() uploadDeletionRequest.fileUUID = fileUUID uploadDeletionRequest.fileVersion = 2 uploadDeletionRequest.masterVersion = masterVersion uploadDeletionRequest.sharingGroupUUID = uploadRequest.sharingGroupUUID let deviceUUID = Foundation.UUID().uuidString uploadDeletion(uploadDeletionRequest: uploadDeletionRequest, deviceUUID: deviceUUID, addUser: false) sendDoneUploads(expectedNumberOfUploads: 1, deviceUUID: deviceUUID, masterVersion: masterVersion, sharingGroupUUID: uploadRequest.sharingGroupUUID) } func checkFileIndex(deviceUUID:String, fileUUID:String, fileVersion:Int32, sharingGroupUUID: String) { guard let (files, _) = getIndex(deviceUUID: deviceUUID, sharingGroupUUID: sharingGroupUUID), let fileInfoArray = files else { XCTFail() return } let result = fileInfoArray.filter({$0.fileUUID == fileUUID}) guard result.count == 1 else { XCTFail() return } XCTAssert(result[0].deviceUUID == deviceUUID) XCTAssert(result[0].fileVersion == fileVersion) } // MARK: File Index func testFileIndexReportsVariousFileVersions() { let fileUUID1 = Foundation.UUID().uuidString let fileUUID2 = Foundation.UUID().uuidString let fileUUID3 = Foundation.UUID().uuidString let deviceUUID = Foundation.UUID().uuidString guard let (masterVersion, uploadRequest) = uploadVersion(2, deviceUUID: deviceUUID, fileUUID:fileUUID1), let sharingGroupUUID = uploadRequest.sharingGroupUUID else { XCTFail() return } guard let (masterVersion2, _) = uploadVersion(3, deviceUUID: deviceUUID, fileUUID:fileUUID2, startMasterVersion: masterVersion, addUser: .no(sharingGroupUUID: sharingGroupUUID)) else { XCTFail() return } guard let _ = uploadVersion(5, deviceUUID: deviceUUID, fileUUID:fileUUID3, startMasterVersion: masterVersion2, addUser: .no(sharingGroupUUID: sharingGroupUUID)) else { XCTFail() return } checkFileIndex(deviceUUID:deviceUUID, fileUUID:fileUUID1, fileVersion:2, sharingGroupUUID: sharingGroupUUID) checkFileIndex(deviceUUID:deviceUUID, fileUUID:fileUUID2, fileVersion:3, sharingGroupUUID: sharingGroupUUID) checkFileIndex(deviceUUID:deviceUUID, fileUUID:fileUUID3, fileVersion:5, sharingGroupUUID: sharingGroupUUID) } // MARK: Download func testDownloadOfFileVersion3Works() { let fileUUID1 = Foundation.UUID().uuidString let deviceUUID = Foundation.UUID().uuidString let fileVersion:FileVersionInt = 3 guard let (masterVersion, uploadRequest) = uploadVersion(fileVersion, deviceUUID: deviceUUID, fileUUID:fileUUID1) else { XCTFail() return } let appMetaData = AppMetaData(version: 0, contents: self.appMetaData) guard let _ = downloadTextFile(masterVersionExpectedWithDownload: Int(masterVersion), appMetaData: appMetaData, downloadFileVersion: fileVersion, uploadFileRequest: uploadRequest) else { XCTFail() return } } func testDownloadOfBadVersionFails() { let fileUUID1 = Foundation.UUID().uuidString let deviceUUID = Foundation.UUID().uuidString let fileVersion:FileVersionInt = 3 guard let (masterVersion, uploadRequest) = uploadVersion(fileVersion, deviceUUID: deviceUUID, fileUUID:fileUUID1) else { XCTFail() return } let appMetaData = AppMetaData(version: 0, contents: self.appMetaData) downloadTextFile(masterVersionExpectedWithDownload: Int(masterVersion), appMetaData: appMetaData, downloadFileVersion: fileVersion+1, uploadFileRequest: uploadRequest, expectedError: true) } } extension FileController_MultiVersionFiles { static var allTests : [(String, (FileController_MultiVersionFiles) -> () throws -> Void)] { return [ ("testUploadVersion1AfterVersion0Works", testUploadVersion1AfterVersion0Works), ("testUploadVersion1WhenVersion0HasNotBeenCommitted", testUploadVersion1WhenVersion0HasNotBeenCommitted), ("testUploadOfSameFileVersionFails", testUploadOfSameFileVersionFails), ("testUploadVersion1OfNewFileFails", testUploadVersion1OfNewFileFails), ("testSuccessiveUploadsOfNextVersionWorks", testSuccessiveUploadsOfNextVersionWorks), ("testUploadDifferentFileContentsForSecondVersionWorks", testUploadDifferentFileContentsForSecondVersionWorks), ("testUploadOfVersion2OfVersion0FileFails", testUploadOfVersion2OfVersion0FileFails), ("testUploadOfTwoConsecutiveVersionsWithoutADoneUploadsAfterVersion0IsUploadedFails", testUploadOfTwoConsecutiveVersionsWithoutADoneUploadsAfterVersion0IsUploadedFails), ("testUploadDeletionOfVersionThatDoesNotExistFails", testUploadDeletionOfVersionThatDoesNotExistFails), ("testUploadDeletionOfVersionThatExistsWorks", testUploadDeletionOfVersionThatExistsWorks), ("testFileIndexReportsVariousFileVersions", testFileIndexReportsVariousFileVersions), ("testDownloadOfFileVersion3Works", testDownloadOfFileVersion3Works), ("testDownloadOfBadVersionFails", testDownloadOfBadVersionFails), ("testDownloadOfBadVersionFails", testDownloadOfBadVersionFails), ("testUploadDifferentVersionWithDifferentMimeTypeFails", testUploadDifferentVersionWithDifferentMimeTypeFails) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:FileController_MultiVersionFiles.self) } } <file_sep>// // AccountAuthenticationTests_AppleSignIn.swift // ServerTests // // Created by <NAME> on 10/5/19. // import XCTest @testable import Server import LoggerAPI import HeliumLogger class AccountAuthenticationTests_AppleSignIn: ServerTestCase, LinuxTestable { func testClientSecretGenerationWorks() { guard let appleSignInCreds = AppleSignInCreds() else { XCTFail() return } let secret = appleSignInCreds.createClientSecret() XCTAssert(secret != nil) } // This has to be tested by hand-- since the authorization codes expire in 5 minutes and can only be used once. Before running this test, populate a auth code into the apple1 account first-- this can be generated from the iOS app. #if false func testGenerateRefreshToken() { guard let appleSignInCreds = AppleSignInCreds() else { XCTFail() return } let testAccount: TestAccount = .apple1 guard let authorizationCode = testAccount.secondToken() else { XCTFail() return } let exp = expectation(description: "generate") appleSignInCreds.generateRefreshToken(serverAuthCode: authorizationCode) { error in XCTAssert(error == nil, "\(String(describing: error))") XCTAssert(appleSignInCreds.accessToken != nil) XCTAssert(appleSignInCreds.refreshToken != nil) XCTAssert(appleSignInCreds.lastRefreshTokenUsage != nil) exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } // This also has to be tested by hand-- since a refresh token can only be used at most every 24 hours func testValidateRefreshToken() { guard let appleSignInCreds = AppleSignInCreds() else { XCTFail() return } let testAccount: TestAccount = .apple1 let refreshToken = testAccount.token() let exp = expectation(description: "refresh") appleSignInCreds.validateRefreshToken(refreshToken: refreshToken) { error in XCTAssert(error == nil, "\(String(describing: error))") XCTAssert(appleSignInCreds.lastRefreshTokenValidation != nil) exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) } #endif class CredsDelegate: AccountDelegate { func saveToDatabase(account: Account) -> Bool { return false } } // No dbCreds, serverAuthCode, lastRefreshTokenValidation, refreshToken func testNeedToGenerateTokensNoGeneration() { guard let appleSignInCreds = AppleSignInCreds() else { XCTFail() return } let delegate = CredsDelegate() appleSignInCreds.delegate = delegate let result = appleSignInCreds.needToGenerateTokens(dbCreds: nil) XCTAssert(!result) switch appleSignInCreds.generateTokens { case .some(.noGeneration): break default: XCTFail() } } } extension AccountAuthenticationTests_AppleSignIn { static var allTests : [(String, (AccountAuthenticationTests_AppleSignIn) -> () throws -> Void)] { let result:[(String, (AccountAuthenticationTests_AppleSignIn) -> () throws -> Void)] = [ ("testClientSecretGenerationWorks", testClientSecretGenerationWorks), ("testNeedToGenerateTokensNoGeneration", testNeedToGenerateTokensNoGeneration) ] return result } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType:AccountAuthenticationTests_AppleSignIn.self) } } <file_sep>// // SharingInvitationRepository.swift // Server // // Created by <NAME> on 4/10/17. // // import Foundation import SyncServerShared import LoggerAPI class SharingInvitation : NSObject, Model { static let sharingInvitationUUIDKey = "sharingInvitationUUID" var sharingInvitationUUID:String! static let expiryKey = "expiry" var expiry:Date! // If you are inviting someone to join a sharing group, they may (depending on allowSocialAcceptance) join as a sharing user. i.e., they may not own cloud storage. That user will use your cloud storage. static let owningUserIdKey = "owningUserId" var owningUserId:UserId! static let sharingGroupUUIDKey = "sharingGroupUUID" var sharingGroupUUID:String! static let permissionKey = "permission" var permission: Permission! static let allowSocialAcceptanceKey = "allowSocialAcceptance" var allowSocialAcceptance: Bool! static let numberAcceptorsKey = "numberAcceptors" var numberAcceptors: UInt32! subscript(key:String) -> Any? { set { switch key { case SharingInvitation.sharingInvitationUUIDKey: sharingInvitationUUID = newValue as! String? case SharingInvitation.expiryKey: expiry = newValue as! Date? case SharingInvitation.owningUserIdKey: owningUserId = newValue as! UserId? case SharingInvitation.sharingGroupUUIDKey: sharingGroupUUID = newValue as! String? case SharingInvitation.permissionKey: permission = newValue as! Permission? case SharingInvitation.allowSocialAcceptanceKey: allowSocialAcceptance = newValue as! Bool? case SharingInvitation.numberAcceptorsKey: numberAcceptors = newValue as! UInt32? default: Log.error("key not found: \(key)") assert(false) } } get { return getValue(forKey: key) } } func typeConvertersToModel(propertyName:String) -> ((_ propertyValue:Any) -> Any?)? { switch propertyName { case SharingInvitation.permissionKey: return {(x:Any) -> Any? in return Permission(rawValue: x as! String) } case SharingInvitation.expiryKey: return {(x:Any) -> Any? in return DateExtras.date(x as! String, fromFormat: .DATETIME) } case SharingInvitation.allowSocialAcceptanceKey: return {(x:Any) -> Any? in return (x as! Int8) == 1 } default: return nil } } } class SharingInvitationRepository : Repository, RepositoryLookup { private(set) var db:Database! required init(_ db:Database) { self.db = db } var tableName:String { return SharingInvitationRepository.tableName } static var tableName:String { // Apparently the table name Lock is special-- get an error if we use it. return "SharingInvitation" } let dateFormat = DateExtras.DateFormat.DATETIME func upcreate() -> Database.TableUpcreateResult { let spMaxLen = Permission.maxStringLength() let createColumns = // Id for the sharing invitation-- I'm not using a regular sequential numeric Id here to avoid attacks where someone could enumerate sharing invitation ids. "(sharingInvitationUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + // gives time/day that the invitation will expire "expiry \(dateFormat.rawValue) NOT NULL, " + // The user that will own new files uploaded by this new user if they join as a sharing user that doesn't have cloud storage. // This is a reference into the User table. // TODO: *2* Make this a foreign key reference to the User table. "owningUserId BIGINT NOT NULL, " + // The sharing group that the person is being invited to. "sharingGroupUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + "permission VARCHAR(\(spMaxLen)) NOT NULL, " + "allowSocialAcceptance BOOL NOT NULL, " + "numberAcceptors INT UNSIGNED NOT NULL, " + "FOREIGN KEY (sharingGroupUUID) REFERENCES \(SharingGroupRepository.tableName)(\(SharingGroup.sharingGroupUUIDKey)), " + "UNIQUE (sharingInvitationUUID))" return db.createTableIfNeeded(tableName: "\(tableName)", columnCreateQuery: createColumns) } enum LookupKey : CustomStringConvertible { case unexpiredSharingInvitationUUID(uuid: String) case sharingInvitationUUID(uuid: String) case staleExpiryDates case owningUserId(UserId) var description : String { switch self { case .unexpiredSharingInvitationUUID(let uuid): return "unexpiredSharingInvitationUUID(\(uuid))" case .sharingInvitationUUID(let uuid): return "sharingInvitationUUID(\(uuid))" case .staleExpiryDates: return "staleExpiryDates" case .owningUserId(let userId): return "owningUserId(\(userId))" } } } func lookupConstraint(key:LookupKey) -> String { switch key { case .unexpiredSharingInvitationUUID(let uuid): let staleDateString = DateExtras.date(Date(), toFormat: dateFormat) return "sharingInvitationUUID = '\(uuid)' and expiry > '\(staleDateString)'" case .sharingInvitationUUID(let uuid): return "sharingInvitationUUID = '\(uuid)'" case .staleExpiryDates: let staleDateString = DateExtras.date(Date(), toFormat: dateFormat) return "expiry < '\(staleDateString)'" case .owningUserId(let userId): return "owningUserId = \(userId)" } } enum AddResult { case success(sharingInvitationUUID:String) case error(String) } func add(owningUserId:UserId, sharingGroupUUID:String, permission:Permission, allowSocialAcceptance: Bool, numberAcceptors: UInt, expiryDuration:TimeInterval = ServerConstants.sharingInvitationExpiryDuration) -> AddResult { let calendar = Calendar.current let expiryDate = calendar.date(byAdding: .second, value: Int(expiryDuration), to: Date())! let expiryDateString = DateExtras.date(expiryDate, toFormat: dateFormat) let uuid = UUID().uuidString let query = "INSERT INTO \(tableName) (sharingInvitationUUID, expiry, owningUserId, sharingGroupUUID, permission, allowSocialAcceptance, numberAcceptors) VALUES('\(uuid)', '\(expiryDateString)', \(owningUserId), '\(sharingGroupUUID)', '\(permission.rawValue)', \(allowSocialAcceptance), \(numberAcceptors));" if db.query(statement: query) { Log.info("Sucessfully created sharing invitation!") return .success(sharingInvitationUUID: uuid) } else { let error = db.error Log.error("Could not insert into \(tableName): \(error)") return .error(error) } } // numberAcceptors must be > 1 beforehand. func decrementNumberAcceptors(sharingInvitationUUID: String) -> Bool { let query = "UPDATE \(tableName) SET \(SharingInvitation.numberAcceptorsKey)=\(SharingInvitation.numberAcceptorsKey) - 1 WHERE \(SharingInvitation.sharingInvitationUUIDKey)='\(sharingInvitationUUID)' AND \(SharingInvitation.numberAcceptorsKey) > 1" if db.query(statement: query) && db.numberAffectedRows() == 1 { Log.info("Sucessfully updated sharing invitation!") return true } else { let error = db.error Log.error("Could not update sharing invitation: \(error)") return false } } } <file_sep># Assumes use of the SyncServer_SharedImages database. from locust import HttpLocust, Locust, TaskSet, task import json import uuid import random with open('accessTokens.json') as json_file: tokens = json.load(json_file) user1AccessToken = tokens["user1AccessToken"] user2AccessToken = tokens["user2AccessToken"] user1Id = 1 user2Id = 2 numberOfSharingGroupsPerUser = 5 numberOfCommonSharingGroups = 0 # across users user1SharingGroups = [] user2SharingGroups = [] def headers(deviceUUID, userAccessToken): return { "X-token-type": "GoogleToken", "access_token": userAccessToken, "SyncServer-Device-UUID": deviceUUID } def makeParams(dict): result = "" for key, value in dict.items(): if len(result) == 0: result += "?" else: result += "&" result += key + "=" + value return result # Returns an array of sharingGroupUUID's to which the user belongs. def sharingGroupsForUser(indexResponse, userId): sharingGroups = indexResponse["sharingGroups"] result = [] for sharingGroup in sharingGroups: sharingGroupUsers = sharingGroup["sharingGroupUsers"] for sharingGroupUser in sharingGroupUsers: if sharingGroupUser["userId"] == userId: result.append(sharingGroup["sharingGroupUUID"]) return result # Pass in two arrays. def intersection(sharingGroups1, sharingGroup2): return list(set(sharingGroups1) & set(sharingGroup2)) # Given set1 = {A, B, C}, set2 = {A, D, E} # Want: {B, C, D, E} def exclusion(list1, list2): s1 = set(list1) s2 = set(list2) intersection = s1 & s2 union = s1.union(s2) result = union.difference(intersection) return list(result) # Given set1 = {A, B, C}, set2 = {A} # Want: {B, C} def difference(list1, list2): s1 = set(list1) s2 = set(list2) difference = s1.difference(s2) return list(difference) def sharingGroupForUser(userId): if userId == user1Id: return random.choice(user1SharingGroups) else: return random.choice(user2SharingGroups) def randomUser(): return random.choice([user1Id, user2Id]) def accessTokenForUser(userId): if userId == user1Id: return user1AccessToken else: return user2AccessToken class MyTaskSet(TaskSet): # This gets run once when the task set starts. def setup(self): global user1SharingGroups, user2SharingGroups response = self.generalIndex(user1AccessToken) user1SharingGroups = sharingGroupsForUser(response, user1Id) response = self.generalIndex(user2AccessToken) user2SharingGroups = sharingGroupsForUser(response, user2Id) commonSharingGroups = intersection(user1SharingGroups, user2SharingGroups) numberCommonNeeded = numberOfCommonSharingGroups - len(commonSharingGroups) if numberCommonNeeded < 0: numberCommonNeeded = 0 if len(user1SharingGroups) < numberOfSharingGroupsPerUser: print("Creating sharing groups for user1") additional = [] for x in range(0, numberOfSharingGroupsPerUser - len(user1SharingGroups)): # Create a sharing group result = self.createSharingGroup(user1AccessToken) if result is None: print("Could not create sharing groups for user1!") else: additional.append(result) user1SharingGroups.extend(additional) if len(user2SharingGroups) < numberOfSharingGroupsPerUser: print("Creating sharing groups for user2") additional = [] for x in range(0, numberOfSharingGroupsPerUser - len(user2SharingGroups)): # Create a sharing group result = self.createSharingGroup(user2AccessToken) if result is None: print("Could not create sharing groups for user1!") else: additional.append(result) user2SharingGroups.extend(additional) if numberCommonNeeded > 0: print("Inviting user 2 to sharing group(s)") user1Only = difference(user1SharingGroups, commonSharingGroups) # Assumes that the number of sharing groups per user > number common. for user1SharingGroup in user1Only: # Invite user 2 to this sharing group. sharingInvitation = self.createSharingInvitation(user1AccessToken, user1SharingGroup) if sharingInvitation is None: print("Error creating sharing invitation") exit() result = self.redeemSharingInvitation(user2AccessToken, sharingInvitation) if result is None: print("Error redeeming sharing invitation") exit() commonSharingGroups.append(user1SharingGroup) if len(commonSharingGroups) >= numberOfCommonSharingGroups: break print("User 1 sharing groups: " + ' '.join(user1SharingGroups)) print("User 2 sharing groups: " + ' '.join(user2SharingGroups)) print("Common sharing groups: " + ' '.join(commonSharingGroups)) # Returns the new sharingGroupUUID, or None if the request fails. def createSharingGroup(self, accessToken): newSharingGroupUUID = str(uuid.uuid1()) params = makeParams({ "sharingGroupUUID": newSharingGroupUUID }) deviceUUID = str(uuid.uuid1()) resp = self.client.post("/CreateSharingGroup/" + params, headers=headers(deviceUUID, accessToken)) if resp.status_code not in range(200, 300): print("Error on CreateSharingGroup POST") return None return newSharingGroupUUID # Returns sharingInvitationUUID, or None if the request fails. def createSharingInvitation(self, accessToken, sharingGroupUUID): params = makeParams({ "sharingGroupUUID": sharingGroupUUID, "permission": "admin" }) deviceUUID = str(uuid.uuid1()) resp = self.client.post("/CreateSharingInvitation/" + params, headers=headers(deviceUUID, accessToken)) if resp.status_code not in range(200, 300): print("Error on CreateSharingInvitation POST") return None invitationResponse = json.loads(resp.text) sharingInvitationUUID = invitationResponse.get("sharingInvitationUUID") return sharingInvitationUUID # This needs to be executed by a different user than the creating user. # Returns sharingGroupUUID, or None if the request fails. def redeemSharingInvitation(self, accessToken, sharingInvitationUUID): params = makeParams({ "sharingInvitationUUID": sharingInvitationUUID, "cloudFolderName": "Local.SharedImages.Folder" }) deviceUUID = str(uuid.uuid1()) resp = self.client.post("/RedeemSharingInvitation/" + params, headers=headers(deviceUUID, accessToken)) if resp.status_code not in range(200, 300): print("Error on RedeemSharingInvitation POST") return None redeemResponse = json.loads(resp.text) sharingGroupUUID = redeemResponse.get("sharingGroupUUID") return sharingGroupUUID def generalIndex(self, accessToken): deviceUUID = str(uuid.uuid1()) resp = self.client.get("/Index/", headers=headers(deviceUUID, accessToken)) if resp.status_code not in range(200, 300): print("Error on Index GET") return None return json.loads(resp.text) def indexSharingGroup(self, userAccessToken, deviceUUID, sharingGroupUUID): params = makeParams({"sharingGroupUUID": sharingGroupUUID}) resp = self.client.get("/Index/" + params, headers=headers(deviceUUID, userAccessToken)) if resp.status_code not in range(200, 300): print("Error on Index GET") return None indexResponse = json.loads(resp.text) return indexResponse # Returns True iff operation works def doneUploads(self, accessToken, masterVersion, deviceUUID, sharingGroupUUID, numTries=0, maxTries=3): if numTries > maxTries: print("Error on DoneUploads: Exceeded number of retries") return False params = makeParams({ "sharingGroupUUID": sharingGroupUUID, "masterVersion": str(masterVersion) }) resp = self.client.post("/DoneUploads/" + params, headers=headers(deviceUUID, accessToken)) if resp.status_code not in range(200, 300): print("Error on DoneUploads POST") return False body = json.loads(resp.text) masterVersion = body.get("masterVersionUpdate") if masterVersion is not None: return self.doneUploads(accessToken, masterVersion, deviceUUID, sharingGroupUUID, numTries + 1) return True # Returns the updated masterVersion if there is one or None. def getMasterVersionUpdateInHeader(self, resp): respParams = None if resp.headers.get("syncserver-message-params") is None: print("Error on UploadFile: No header params") return None respParams = resp.headers["syncserver-message-params"] respParamsJSON = json.loads(respParams) masterVersion = respParamsJSON.get("masterVersionUpdate") if masterVersion is not None: return masterVersion return None # Returns True iff successful. def downloadFileAux(self, accessToken, deviceUUID, paramDict, masterVersion, numTries=0, maxTries=3): if numTries > maxTries: print("Error on DownloadFile: Exceeded number of retries") return False paramDict["masterVersion"] = str(masterVersion) params = makeParams(paramDict) resp = self.client.get("/DownloadFile/" + params, headers=headers(deviceUUID, accessToken)) if resp.status_code not in range(200, 300): print("Error on DownloadFile GET") return False masterVersion = self.getMasterVersionUpdateInHeader(resp) if masterVersion is not None: return self.downloadFileAux(accessToken, deviceUUID, paramDict, masterVersion, numTries + 1) return True # Returns working param dictioary iff successful; None if failure. def uploadFileWithRetries(self, accessToken, deviceUUID, data, paramDict, masterVersion, numTries=0, maxTries=3): if numTries > maxTries: print("Error on UploadFile: Exceeded number of retries") return None paramDict["masterVersion"] = str(masterVersion) params = makeParams(paramDict) resp = self.client.post("/UploadFile/" + params, data=data, headers=headers(deviceUUID, accessToken)) if resp.status_code not in range(200, 300): print("Error on UploadFile") return None masterVersion = self.getMasterVersionUpdateInHeader(resp) if masterVersion is not None: return self.uploadFileWithRetries(accessToken, deviceUUID, data, paramDict, masterVersion, numTries + 1) return paramDict # Return working upload dictionary if upload with DoneUploads works; None otherwise. def uploadFileAux(self, accessToken, deviceUUID, sharingGroupUUID): indexResponse = self.indexSharingGroup(accessToken, deviceUUID, sharingGroupUUID) if indexResponse is None: return None masterVersion = indexResponse["masterVersion"] fileUUID = str(uuid.uuid1()) paramDict = { "fileUUID": fileUUID, "sharingGroupUUID": sharingGroupUUID, "fileVersion": "0", "mimeType": "image/jpeg", "checkSum": "6B5B722C95BC6D5A023B6236486EBB8C".lower() } data = None with open("IMG_2963.jpeg", "r") as f: data = f.read() uploadResult = self.uploadFileWithRetries(accessToken, deviceUUID, data, paramDict, masterVersion) if uploadResult is None: return None if self.doneUploads(accessToken, masterVersion, deviceUUID, sharingGroupUUID): return uploadResult else: return None # Return True iff succeeds (no DoneUploads) def deleteFileAux(self, accessToken, deviceUUID, paramDict, masterVersion, numTries=0, maxTries=3): if numTries > maxTries: print("Error on DeleteFile: Exceeded number of retries") return False paramDict["masterVersion"] = str(masterVersion) params = makeParams(paramDict) resp = self.client.delete("/UploadDeletion/" + params, headers=headers(deviceUUID, accessToken)) if resp.status_code not in range(200, 300): print("Error on DeleteFile") return False body = json.loads(resp.text) masterVersion = body.get("masterVersionUpdate") if masterVersion is not None: return self.deleteFileAux(accessToken, deviceUUID, paramDict, masterVersion, numTries + 1) return True def downloadFileMain(self): deviceUUID = str(uuid.uuid1()) userId = randomUser() sharingGroupUUID = sharingGroupForUser(userId) accessToken = accessTokenForUser(userId) indexResponse = self.indexSharingGroup(accessToken, deviceUUID, sharingGroupUUID) if indexResponse is None: print("Error: Could not get index for downloading.") return notDeleted = list(filter(lambda file: not file["deleted"], indexResponse["fileIndex"])) if len(notDeleted) == 0: print("Cannot download file: All files deleted") return exampleFile = notDeleted[0] masterVersion = indexResponse["masterVersion"] paramDict = { "sharingGroupUUID": sharingGroupUUID, "fileUUID": exampleFile["fileUUID"], "fileVersion": str(exampleFile["fileVersion"]) } if exampleFile.get("appMetaDataVersion") is not None: paramDict["appMetaDataVersion"] = str(exampleFile["appMetaDataVersion"]) if not self.downloadFileAux(accessToken, deviceUUID, paramDict, masterVersion): print("ERROR DownloadFile GET") return print("SUCCESS DownloadFile GET: User: " + str(userId)) def indexMain(self): userId = randomUser() accessToken = accessTokenForUser(userId) self.generalIndex(accessToken) print("SUCCESS on Index: User: " + str(userId)) def indexSharingGroupMain(self): deviceUUID = str(uuid.uuid1()) userId = randomUser() sharingGroupUUID = sharingGroupForUser(userId) accessToken = accessTokenForUser(userId) indexResponse = self.indexSharingGroup(accessToken, deviceUUID, sharingGroupUUID) if indexResponse is None: print("Error: Could not get index for indexSharingGroupMain.") return def uploadFileMain(self): userId = randomUser() accessToken = accessTokenForUser(userId) sharingGroupUUID = sharingGroupForUser(userId) deviceUUID = str(uuid.uuid1()) if self.uploadFileAux(accessToken, deviceUUID, sharingGroupUUID) is None: print("Error on UploadFile") return print("SUCCESS on UploadFile: User: " + str(userId)) def deleteFileMain(self): userId = randomUser() sharingGroupUUID = sharingGroupForUser(userId) accessToken = accessTokenForUser(userId) deviceUUID = str(uuid.uuid1()) uploadResult = self.uploadFileAux(accessToken, deviceUUID, sharingGroupUUID) if uploadResult is None: print("Error on DeleteFile: Upload failed") return masterVersion = uploadResult["masterVersion"] # Need to +1 masterVersion because the value we have is after the DoneUploads with the upload. masterVersion = int(masterVersion) masterVersion += 1 masterVersion = str(masterVersion) paramDict = { "fileUUID": uploadResult["fileUUID"], "sharingGroupUUID": uploadResult["sharingGroupUUID"], "fileVersion": uploadResult["fileVersion"] } if not self.deleteFileAux(accessToken, deviceUUID, paramDict, masterVersion): print("Error on DeleteFile") return if not self.doneUploads(accessToken, masterVersion, deviceUUID, sharingGroupUUID): print("Error on DoneUploads/DeleteFile") return print("SUCCESS on DeleteFile: User: " + str(userId)) @task(5) def index(self): self.indexMain() @task(5) def indexSharingGroupTask(self): self.indexSharingGroupMain() @task(3) def downloadFile(self): self.downloadFileMain() @task(2) def uploadFile(self): self.uploadFileMain() @task(1) def deleteFile(self): self.deleteFileMain() class MyLocust(HttpLocust): task_set = MyTaskSet # https://docs.locust.io/en/stable/writing-a-locustfile.html # These are the minimum and maximum time respectively, in milliseconds, that a simulated user will wait between executing each task. min_wait = 5000 max_wait = 15000 <file_sep>// // AppleSignInCreds.swift // Server // // Created by <NAME> on 10/2/19. // import Foundation import CredentialsAppleSignIn import SyncServerShared import Kitura import HeliumLogger import LoggerAPI // For general strategy used with Apple Sign In-- see // https://stackoverflow.com/questions/58178187 // https://github.com/crspybits/CredentialsAppleSignIn and // https://forums.developer.apple.com/message/386237 class AppleSignInCreds: AccountAPICall, Account { enum AppleSignInCredsError: Swift.Error { case noCallToNeedToGenerateTokens case failedCreatingClientSecret } static let accountScheme: AccountScheme = .appleSignIn let accountScheme: AccountScheme = AppleSignInCreds.accountScheme let owningAccountsNeedCloudFolderName: Bool = false weak var delegate: AccountDelegate? var accountCreationUser: AccountCreationUser? struct DatabaseCreds: Codable { // Storing the serverAuthCode in the database so that I don't try to generate a refresh token from the same serverAuthCode twice. let serverAuthCode: String? let idToken: String let refreshToken: String? // Because Apple imposes limits about how often you can validate the refresh token. let lastRefreshTokenValidation: Date? } // This is actually an idToken, in Apple's terms. var accessToken: String! private var serverAuthCode:String? // Obtained via the serverAuthCode var refreshToken: String? var lastRefreshTokenValidation: Date? enum GenerateTokens { case noGeneration case generateRefreshToken(serverAuthCode: String) case validateRefreshToken(refreshToken: String) // Apple says we can't validate tokens more than once per day. static let minimumValidationDuration: TimeInterval = 60 * 60 * 24 static func needToValidateRefreshToken(lastRefreshTokenValidation: Date) -> Bool { let timeIntervalSinceLastValidation = Date().timeIntervalSince(lastRefreshTokenValidation) return timeIntervalSinceLastValidation >= minimumValidationDuration } } private(set) var generateTokens: GenerateTokens? let config: ServerConfiguration.AppleSignIn override init?() { guard let config = Configuration.server.appleSignIn else { return nil } self.config = config super.init() baseURL = "appleid.apple.com" } func needToGenerateTokens(dbCreds: Account?) -> Bool { // Since a) presumably we can't use a serverAuthCode more than once, and b) Apple throttles use of the refresh token, don't generate tokens unless we have a delegate to save the tokens. guard let _ = delegate else { return false } if let dbCreds = dbCreds { guard dbCreds is AppleSignInCreds else { Log.error("dbCreds were not AppleSignInCreds") return false } } // The tokens in `self` are assumed to be from the request headers -- i.e., they are new. // Do we have a new server auth code? If so, then this is our first priority. Because subsequent id tokens will be generated from the refresh token created from the server auth code? if let requestServerAuthCode = serverAuthCode { if let dbCreds = dbCreds as? AppleSignInCreds, let databaseServerAuthCode = dbCreds.serverAuthCode { if databaseServerAuthCode != requestServerAuthCode { generateTokens = .generateRefreshToken(serverAuthCode: requestServerAuthCode) return true } } else { // We don't have an existing server auth code; assume this means this is a new user. generateTokens = .generateRefreshToken(serverAuthCode: requestServerAuthCode) return true } } // Don't need to check the case where only the db creds have a server auth code because if we stored the server auth code in the database, we used it already. // Not using a new server auth code. Is it time to generate a new id token? var lastRefresh: Date? var refreshToken = "" if let dbCreds = dbCreds as? AppleSignInCreds, let last = dbCreds.lastRefreshTokenValidation, let token = dbCreds.refreshToken { lastRefresh = last refreshToken = token } else if let _ = lastRefreshTokenValidation, let token = self.refreshToken { lastRefresh = lastRefreshTokenValidation refreshToken = token } if let last = lastRefresh, GenerateTokens.needToValidateRefreshToken(lastRefreshTokenValidation: last) { generateTokens = .validateRefreshToken(refreshToken: refreshToken) return true } generateTokens = .noGeneration return false } func generateTokens(response: RouterResponse?, completion: @escaping (Error?) -> ()) { guard let generateTokens = generateTokens else { completion(AppleSignInCredsError.noCallToNeedToGenerateTokens) return } switch generateTokens { case .noGeneration: self.generateTokens = nil completion(nil) case .generateRefreshToken(serverAuthCode: let serverAuthCode): generateRefreshToken(serverAuthCode: serverAuthCode) { [weak self] error in self?.generateTokens = nil completion(error) } case .validateRefreshToken(refreshToken: let refreshToken): validateRefreshToken(refreshToken: refreshToken) { [weak self] error in self?.generateTokens = nil completion(error) } } } func merge(withNewer account: Account) { } static func getProperties(fromRequest request:RouterRequest) -> [String: Any] { var result = [String: Any]() if let authCode = request.headers[ServerConstants.HTTPOAuth2AuthorizationCodeKey] { result[ServerConstants.HTTPOAuth2AuthorizationCodeKey] = authCode } if let idToken = request.headers[ServerConstants.HTTPOAuth2AccessTokenKey] { result[ServerConstants.HTTPOAuth2AccessTokenKey] = idToken } return result } static func fromProperties(_ properties: AccountManager.AccountProperties, user:AccountCreationUser?, delegate:AccountDelegate?) -> Account? { guard let creds = AppleSignInCreds() else { return nil } creds.accountCreationUser = user creds.delegate = delegate creds.accessToken = properties.properties[ServerConstants.HTTPOAuth2AccessTokenKey] as? String creds.serverAuthCode = properties.properties[ServerConstants.HTTPOAuth2AuthorizationCodeKey] as? String return creds } func toJSON() -> String? { let databaseCreds = DatabaseCreds(serverAuthCode: serverAuthCode, idToken: accessToken, refreshToken: refreshToken, lastRefreshTokenValidation: lastRefreshTokenValidation) let encoder = JSONEncoder() guard let data = try? encoder.encode(databaseCreds) else { Log.error("Failed encoding DatabaseCreds") return nil } return String(data: data, encoding: .utf8) } static func fromJSON(_ json: String, user: AccountCreationUser, delegate: AccountDelegate?) throws -> Account? { guard let data = json.data(using: .utf8) else { return nil } let decoder = JSONDecoder() guard let databaseCreds = try? decoder.decode(DatabaseCreds.self, from: data) else { return nil } guard let result = AppleSignInCreds() else { return nil } result.delegate = delegate result.accountCreationUser = user result.serverAuthCode = databaseCreds.serverAuthCode result.accessToken = databaseCreds.idToken result.refreshToken = databaseCreds.refreshToken result.lastRefreshTokenValidation = databaseCreds.lastRefreshTokenValidation return result } } <file_sep>USE SyncServer_SharedImages; ALTER TABLE User ADD cloudFolderName VARCHAR(256); UPDATE User SET cloudFolderName = "SharedImages.Folder" WHERE userType = "owning"; # USE SharedImages_Staging; # ALTER TABLE User ADD cloudFolderName VARCHAR(256); # UPDATE User SET cloudFolderName = "Staging.SharedImages.Folder" WHERE userType = "owning";<file_sep>ASSUMPTIONS =========== * I assume you're running MacOS. :). ONE-TIME INSTALL ================ * Install the eb cli http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install-osx.html * To use the `make.sh` script (see below; it zips up your application bundle), you'll need the `jq` program installed. The make.sh script below contains, inside it, instructions on how to do this. PER SERVER ENVIRONMENT INSTALLS =============================== Note that I'm not making a big difference here between Elastic Beanstalk Applications and Environments because I'm just using a single environment within each of my applications. * Configure the eb cli for an environment in a folder. I've put mine in subfolders of devops/AWS-ElasticBeanstalk/Environments in the repo. See http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-configuration.html I get rid of the .gitignore files in these directories. I like to put them under version control. * In your environment folder, add the following to the `.elasticbeanstalk/config.yml` file in that folder. It tells the eb cli where to find your application bundle, which the make.sh script is going to place on your desktop. ``` deploy: artifact: <your-user-path>/Desktop/bundle.zip ``` See also http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-configuration.html#eb-cli3-artifact * If you later see a message like: ![update message](EnvironmentUpdateMessage.png) you need to change the version of Amazon Linux your environment is running. This version is specified in the `.elasticbeanstalk/config.yml` file. For example: ``` global: ... default_platform: Docker 17.06.2-ce ``` * Create a Server.json file -- this provides the configuration needed by SyncServer. Put that in your environment folder. (I have just put a sym link because I don't want to expose private info in my repo!). Hold off on putting the database specifics into this file. That comes below. * Create a SSL certificate for the domain or subdomain for your environment. For example, I'm using staging.syncserver.cprince.com for my staging server. It's free using the AWS Certificate Manager. As part of the creation process, AWS sends a confirmation email to several email addresses related to the domain or subdomain. E.g., you have to be the administrator on record with WHOIS for the domain or subdomain. See https://aws.amazon.com/certificate-manager/ You will need the `arn` reference for this SSL certificate in the configure.yml file below. * The configure.yml file (below) will specify an SSL certificate. You need to set up a DNS CNAME record to direct the domain or subdomain referenced by that SSL certificate to the CNAME address for the load balancer for the server. (I do this DNS work on a separate, different from AWS, hosting service-- for me, the hosting service for cprince.com). The URL for your load balancer will be something like: ``` sharedimages-staging.us-west-2.elasticbeanstalk.com ``` NOTE: The configuration I'm using is for a Classical Elastic Beanstalk load balancer (not a Network Load Balancer) and so its CNAME doesn't have a static IP address. Hence, you can't use redirection with a DNS A record (I learned this the hard way!). See also: https://forums.aws.amazon.com/thread.jspa?threadID=9061 http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-nlb.html http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html https://stackoverflow.com/questions/9935229/cname-ssl-certificates * If you want your database secured not only by password and username, but also secured behind an AWS Virtual Private Cloud (VPC), then [also follow these steps](LaunchingEnvironment-VPC.md). * Create a yml file for your environmnent (I'm calling them `configure.yml` files). There's an example in Environments/sharedimages-staging/configure.yml. It's suitable to put these files in your environment folder because they are specific to the environment. These files contain many of the parameters needed for your environment. While much of it can just be copied and used for other environments, you will probably need to change the value of a few parameters: 1. `SSLCertificateId` -- which you generated with the AWS Certificate Manager above, and is tied to a particular URL. 2. `EC2KeyName` -- which is the name of a security key pair to allow you SSH access into the EC2 instances. You need to create this using the AWS web console. 3. VPC related parameters-- If you have setup a VPC, then see [the VPC instructions](LaunchingEnvironment-VPC.md) for additional changes you'll need to make to configure.yml. Also, if you want to change parameters such as the EC2 instance type used in the environment you'll need to make changes to this file. See the README.txt in the "AWS application bundle" folder for references on the details on the contents of the configure.yml file. FOR ENVIRONMENT/DATABASE COMBO's THAT YOU REGULARLY START/SHUTDOWN, THIS IS THE PART YOU REPEAT: ================================================================================================ * Start a database for your environment. I've been using RDS mySQL. You'll need a specific database schema created, and a username and password to access that database. If you are using a VPC to connect to your database, select "No" for "Public accessibility" and [see these instructions](LaunchingEnvironment-VPC.md) for other changes you'll need when creating your database. If you are not using a VPC, then select "Yes" for "Public accessibility", and you'll also need to change the database security group to allow ingress from any IP address. * Edit your Server.json file for the environment to contain the database particulars, i.e., endpoint, username, password, database name. You *must* do this before the next step (of zipping up your application bundle) because your Server.json file goes into the zipped application bundle. * Zip up your AWS application bundle using the make.sh script within the "AWS application bundle". Do this at the command line within the "AWS application bundle" folder. The top comments of make.sh contain examples on how to run it, but the basics are that you give three command line arguments: ./make.sh `<DockerImageTag>` Server.json configure.yml As a result of running make.sh, your application bundle will contain your environment's Server.json and configure.yml files, and a few others. One of these is a file named Dockerrun.aws.json. This file, amongst other things, indicates the Docker image for SyncServer that will be used. In particular, it uses the docker image: https://hub.docker.com/r/crspybits/syncserver-runner/ with the tag `<DockerImageTag>` (that you gave to make.sh). That is, the application bundle indicates which SyncServer image to pull from hub.docker.com. To learn more about AWS application bundles, see http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/beanstalk-environment-configuration-advanced.html * Start up your environment using the eb cli. Within one of your evironment folders, run, for example: ``` eb create sharedimages-staging --cname sharedimages-staging ``` See also http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb3-create.html You can control this Elastic Beanstalk environment at the AWS UI web console. Use https://aws.amazon.com/console/ and find Elastic Beanstalk. * Hit on your server!
493602d073a45af4bc85dbc53fe9d4260ac55930
[ "SQL", "Ruby", "Swift", "Markdown", "Python", "Text", "Dockerfile", "Shell" ]
150
Shell
crspybits/SyncServerII
448ca46325c315e4b556c4a16a18e9aa94ea5db0
a563b87e25ef13b533a5297d8a056f6a754caf10
refs/heads/master
<file_sep>struct Solution; impl Solution { fn is_palindrome(x: i32) -> bool { if x < 0 { return false; } let mut reversed = 0; let mut number = x; while number > 0 { reversed = reversed * 10 + number % 10; number /= 10; } x == reversed // or compare original number as a string with the reversed string // let x_str = x.abs().to_string(); // x >= 0 && x_str == x_str.chars().rev().collect::<String>() } } #[test] fn test() { assert_eq!(Solution::is_palindrome(-123), false); assert_eq!(Solution::is_palindrome(12321), true); } <file_sep>use rustgym_msg::ClientInfo; use wasm_bindgen::prelude::*; use wasm_bindgen::*; use wasm_bindgen_futures::JsFuture; use wasm_bindgen_test::*; use web_sys::{ window, Document, HtmlAnchorElement, HtmlDivElement, HtmlElement, HtmlInputElement, HtmlTableElement, HtmlTableRowElement, HtmlTableSectionElement, HtmlVideoElement, Location, MediaDevices, MediaStream, MediaStreamConstraints, Navigator, Window, }; #[wasm_bindgen(module = "/helper.js")] extern "C" { pub fn constraints() -> JsValue; } pub fn set_panic_hook() { #[cfg(feature = "console_error_panic_hook")] console_error_panic_hook::set_once(); } pub fn document() -> Document { let window: Window = window().expect("window"); window.document().expect("document") } pub fn navigator() -> Navigator { let window: Window = window().expect("window"); window.navigator() } pub fn wsurl() -> String { let window: Window = window().expect("window"); let location: Location = window.location(); let protocol: String = location.protocol().expect("protocol"); let host: String = location.host().expect("host"); let ws_protocol = if protocol == "https:" { "wss://" } else { "ws://" }; format!("{}{}/ws/", ws_protocol, host) } pub fn search_input() -> HtmlInputElement { document() .get_element_by_id("search_input") .expect("get_element_by_id") .dyn_into::<HtmlInputElement>() .expect("HtmlInputElement") } pub fn search_suggestions() -> HtmlDivElement { document() .get_element_by_id("search_suggestions") .expect("get_element_by_id") .dyn_into::<HtmlDivElement>() .expect("HtmlDivElement") } pub fn div() -> HtmlDivElement { document() .create_element("div") .expect("create_element") .dyn_into::<HtmlDivElement>() .expect("HtmlDivElement") } pub fn search_table() -> HtmlTableElement { document() .get_element_by_id("search_table") .expect("get_element_by_id") .dyn_into::<HtmlTableElement>() .expect("HtmlTableElement") } pub fn search_results() -> HtmlTableSectionElement { document() .get_element_by_id("search_results") .expect("get_element_by_id") .dyn_into::<HtmlTableSectionElement>() .expect("HtmlTableSectionElement") } pub fn remove_children(node: &HtmlElement) -> Result<(), JsValue> { while let Some(child) = node.first_child() { node.remove_child(&child)?; } Ok(()) } pub fn tr() -> HtmlTableRowElement { document() .create_element("tr") .expect("create_element") .dyn_into::<HtmlTableRowElement>() .expect("HtmlTableRowElement") } pub fn a() -> HtmlAnchorElement { document() .create_element("a") .expect("create_element") .dyn_into::<HtmlAnchorElement>() .expect("HtmlAnchorElement") } pub fn video() -> HtmlVideoElement { document() .create_element("video") .expect("create_element") .dyn_into::<HtmlVideoElement>() .expect("HtmlVideoElement") } pub fn local_video() -> HtmlVideoElement { document() .get_element_by_id("local_video") .expect("get_element_by_id") .dyn_into::<HtmlVideoElement>() .expect("HtmlVideoElement") } pub fn remote_videos() -> HtmlDivElement { document() .get_element_by_id("remote_videos") .expect("get_element_by_id") .dyn_into::<HtmlDivElement>() .expect("HtmlDivElement") } pub async fn get_media_stream() -> Result<MediaStream, JsValue> { let navigator = navigator(); let media_devices: MediaDevices = navigator.media_devices()?; let constraints = MediaStreamConstraints::from(constraints()); let get_user_media_promise = media_devices.get_user_media_with_constraints(&constraints)?; let media_stream: MediaStream = JsFuture::from(get_user_media_promise).await?.dyn_into()?; Ok(media_stream) } pub trait MediaSupport { fn is_media_supported(&self) -> bool; } impl MediaSupport for ClientInfo { fn is_media_supported(&self) -> bool { let family: &str = self.user_agent.as_ref().expect("useragent").family.as_ref(); family == "Chrome" || family == "Safari" || family == "Firefox" || family == "Edge" } } #[wasm_bindgen_test] async fn test() { assert_eq!(get_media_stream().await.is_ok(), true); }
39425a080a7c70e2a8787bca6485a476a87b309b
[ "Rust" ]
2
Rust
lexafaxine/rustgym
9f3f7993b3b7f6c4b0de4bb934e9b2180439995e
15c185dff7b363788986fe868c5b418e5f8f38a3
refs/heads/master
<file_sep><?php namespace App\Models; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Tymon\JWTAuth\Contracts\JWTSubject; use App\Notifications\VerifyEmail; use Spatie\Permission\Traits\HasRoles; use Laravel\Cashier\Billable; use Cmgmyr\Messenger\Traits\Messagable; use Spatie\Activitylog\Traits\CausesActivity; use Illuminate\Database\Eloquent\SoftDeletes; class User extends Authenticatable implements JWTSubject, MustVerifyEmail { use Notifiable, HasRoles, Billable, Messagable, CausesActivity, SoftDeletes; protected $guard_name = 'api'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'firstname', 'lastname', 'email', 'password', ]; protected static $logName = 'user'; protected static $logAttributes = ['*']; protected static $logOnlyDirty = true; protected static $logAttributesToIgnore = [ 'last_login_at', 'updated_at']; public function getDescriptionForEvent(string $eventName): string { return "User has been {$eventName}"; } /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * Get the identifier that will be stored in the subject claim of the JWT. * * @return mixed */ public function getJWTIdentifier() { return $this->getKey(); } /** * Return a key value array, containing any custom claims to be added to the JWT. * * @return array */ public function getJWTCustomClaims() { return [ 'roles' => $this->getRoleNames(), ]; } /** * Send the email verification notification. * * @return void */ public function sendEmailVerificationNotification() { $this->notify(new VerifyEmail); } public function linkedSocialAccounts() { return $this->hasMany(LinkedSocialAccount::class); } public function verifyUser() { return $this->hasOne(VerifyUser::class); } public function admin() { return $this->hasOne(Admin::class); } public function client() { return $this->hasOne(Client::class); } public function accountant() { return $this->hasOne(Accountant::class); } public function getFullNameAttribute() { return "{$this->firstname} {$this->lastname}"; } public function setFirstNameAttribute($value) { $this->attributes['firstname'] = ucwords($value); } public function setLastNameAttribute($value) { $this->attributes['lastname'] = ucwords($value); } public function unreadClientUploadedNotifications($clientID) { return $this->notifications()->where([ ['type', 'App\\Notifications\\ClientUploaded'], ['data->client_id', $clientID], ['read_at', null], ]); } protected $casts = [ 'id' => 'int', ]; protected $appends = ['full_name']; } <file_sep><?php namespace App\Http\Controllers\Api\CMS; use App\Models\Panel; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Resources\CMS\Transformer as TransformerResource; class PanelController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $model = new Panel; return response()->json(['success' => true, 'data' => $model->all()]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $model = new Panel; $data = $request->all(); $model->fill($data); $model->save(); return response()->json(['success' => true, 'data' => $model->all()]); } /** * Display the specified resource. * * @param \App\Models\Panel $panel * @return \Illuminate\Http\Response */ public function show(Panel $panel) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\Panel $panel * @return \Illuminate\Http\Response */ public function edit(Panel $panel) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Panel $panel * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $model = new Panel; $model = $model->findOrFail($id); $data = $request->all(); $model->fill($data); $model->save(); return response()->json(['success' => true, 'data' => $model->findOrFail($id)]); } /** * Remove the specified resource from storage. * * @param \App\Models\Panel $panel * @return \Illuminate\Http\Response */ public function destroy($id) { // $model = new Panel; if($id != null) { $model = $model->findOrFail($id); $model->where('id', $id)->delete(); } return response()->json(['success' => true, 'data' => Panel::get()]); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class PagePanel extends Model { protected $connection = 'cms_db'; public $table = "page_panel"; use SoftDeletes; protected $fillable = [ 'page_id', 'panel_id', 'sort' ]; } <file_sep><?php namespace App\Http\Controllers\Api\CMS; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\URL; class FileController extends Controller { public function index(Request $request) { try { $file = $request->file('file'); $extension = $file->extension(); $mimeType = $file->getMimeType(); $filename = time().'.'.$extension; // $base = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix().'/uploads/cms/'; if(\Config::get('app.env') === 'local') { $path = Storage::disk('public')->putFileAs('uploads/cms', $file, $filename); } else { $path = Storage::disk('spaces')->putFileAs('uploads/cms', $file, $filename, 'public'); $base = 'https://'.env('DO_SPACES_BUCKET').'.sgp1.digitaloceanspaces.com'; } //Move Uploaded File return response()->json(['success' => true, 'path' => asset('storage/uploads/cms/'.$filename)]); } catch (Exception $x) { return response()->json(['success' => false, 'message' => $x, 'url' => $base]); } } public function get(Request $request) { return $request; } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Panel extends Model { protected $connection = 'cms_db'; public $table = "panel"; use SoftDeletes; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'key', 'preview_image', 'config', ]; public function content() { return $this->hasMany('App\Models\PanelContent'); } } <file_sep><?php namespace App\Http\Controllers\Api\CMS; use App\Models\PanelContent; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class PanelContentController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $model = new PanelContent; return response()->json(['success' => true, 'data' => $model->all()]); } public function getById($id) { $model = new PanelContent; $data = $model->where('page_panel_id', $id)->first(); // array_push($data[], $panel); // foreach($data as $key => $panel) { // $data[$key]['panel'] = PanelContent::find(1)->where('id', $panel->panel_id)->get(); // } return response()->json(['success' => true, 'data' => $data]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $model = new PanelContent; $data = $request->all(); $model->fill($data); $model->save(); return response()->json(['success' => true, 'data' => $model->all()]); } /** * Display the specified resource. * * @param \App\Models\PanelContent $panelContent * @return \Illuminate\Http\Response */ public function show(PanelContent $panelContent) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\PanelContent $panelContent * @return \Illuminate\Http\Response */ public function edit(PanelContent $panelContent) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\PanelContent $panelContent * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $model = new PanelContent; $model = $model->findOrFail($id); $data = $request->all(); $model->fill($data); if($model->save()) { return response()->json(['success' => true, 'data' => $model->findOrFail($id)]); } } /** * Remove the specified resource from storage. * * @param \App\Models\PanelContent $panelContent * @return \Illuminate\Http\Response */ public function destroy($id) { // $model = new PanelContent; if($id != null) { $model = $model->findOrFail($id); $model->where('id', $id)->delete(); } return response()->json(['success' => true, 'data' => PanelContent::get()]); } } <file_sep># cms-backend - git clone https://github.com/innerview47/cms-backend.git - composer install<file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class PanelContent extends Model { protected $connection = 'cms_db'; public $table = "panel_content"; use SoftDeletes; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'page_panel_id', 'css_class', 'css_id', 'full_width', 'title', 'sub_title', 'bg_image', 'bg_position', 'bg_size', 'bg_color', 'content', ]; public function panel() { return $this->belongsTo('App\Models\Panel'); } } <file_sep><?php namespace App\Http\Controllers\Api\CMS; use App\Models\Page; use App\Models\PagePanel; use App\Models\Panel; use App\Models\PanelContent; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class WebController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct(Page $page, PagePanel $pagePanel, Panel $panel, PanelContent $panelContent) { $this->page = $page; $this->pagePanel = $pagePanel; $this->panel = $panel; $this->panelContent = $panelContent; } public function index($slug) { try { $data['page'] = $this->page->find(1)->where('url', '/'.$slug)->first(); if($data['page'] != null) { $data['page_panels'] = $this->pagePanel->orderBy('sort', 'asc')->where('page_id', $data['page']->id)->get(); $data['panels'] = []; $data['content'] = []; $data['webview'] = []; foreach($data['page_panels'] as $key => $page_panel) { array_push($data['panels'], Panel::find(1)->where('id', $page_panel->panel_id)->first()); foreach($data['panels'] as $key => $pan) { array_push($data['content'], PanelContent::find(1)->where('page_panel_id', $page_panel->id)->first()); } } foreach($data['page_panels'] as $pageKey => $page_panel) { $panelz = (object) []; foreach($data['panels'] as $panelKey => $pan) { if($pan['id'] === $page_panel['panel_id']) { $panelz->id = $page_panel->id; $panelz->key = $pan->key; foreach($data['content'] as $contentKey => $content) { if($content['page_panel_id'] === $page_panel['id']) { $panelz->content = $content; unset($panelz->content->page_panel_id); unset($panelz->content->deleted_at); unset($panelz->content->created_at); unset($panelz->content->updated_at); } } } } array_push($data['webview'], $panelz); } } return $data; } catch (Exception $x) { return x; } } } <file_sep><?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::group(['prefix' => 'cms'], function () { Route::group(['prefix' => 'panel'], function () { Route::get('/' , 'PanelController@index'); Route::post('/' , 'PanelController@store'); Route::put('{id}' , 'PanelController@update'); Route::delete('{id}' , 'PanelController@destroy'); }); Route::group(['prefix' => 'page'], function () { Route::get('/' , 'PageController@index'); Route::post('/' , 'PageController@store'); Route::put('{id}' , 'PageController@update'); Route::delete('{id}' , 'PageController@destroy'); Route::group(['prefix' => 'panel'], function () { Route::get('/' , 'PagePanelController@index'); Route::get('{id}' , 'PagePanelController@getById'); Route::post('/' , 'PagePanelController@store'); Route::put('{id}' , 'PagePanelController@update'); Route::delete('{page_id}' , 'PagePanelController@destroy'); Route::group(['prefix' => 'content'], function () { Route::get('/' , 'PanelContentController@index'); Route::get('{id}' , 'PanelContentController@getById'); Route::post('/' , 'PanelContentController@store'); Route::put('{id}' , 'PanelContentController@update'); Route::delete('{page_id}' , 'PanelContentController@destroy'); }); }); }); Route::group(['prefix' => 'file'], function () { Route::post('/upload' , 'FileController@index'); Route::get('/upload' , 'FileController@get'); }); }); Route::group(['prefix' => 'web-views'], function () { Route::get('{slug}' , 'WebController@index'); });<file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Page extends Model { protected $connection = 'cms_db'; public $table = "page"; use SoftDeletes; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'url', 'meta_title', 'meta_desc', 'meta_keyword', 'meta_image', ]; }
706bac226b47f4528847157a0ad6b265e4d28567
[ "Markdown", "PHP" ]
11
PHP
innerview47/cms-backend
dbb81042bf347c8826016b8d06a334c2b171f0b4
06a3fb98baacff57efbd8a185e14911f74d0aa13
refs/heads/master
<repo_name>haoqianglyu/haoqianglyu.github.io<file_sep>/dist/music.js const ap = new APlayer({ container: document.getElementById('aplayer'), fixed: true, autoplay: false, loop: 'all', volume: 0.7, listFolded: true, listMaxHeight: 60, audio: [ { name: '春风十里', artist: '鹿先森乐队', url: 'https://mp32.9ku.com/upload/128/2016/04/06/671144.mp3', cover: '/uploads/Picture5.jpg', }, { name: 'lemon', artist: '米精玄师', url: '/uploads/Lemon_(hydro.fm).mp3', cover: '/uploads/lemon.png', }, { name: '可不可以', artist: '张紫豪', url: 'https://mp32.9ku.com/upload/128/2018/09/12/881837.mp3', cover: '/uploads/Picture1.jpg', }, { name: '辞九门回忆', artist: '等什么君', url: 'https://mp32.9ku.com/upload/128/2019/04/16/890196.mp3', cover: '/uploads/Picture2.jpg', }, { name: '爱在记忆中找你', artist: '林峯', url: 'https://mp3.9ku.com/mp3/268/267203.mp3', cover: '/uploads/Picture3.jpg', }, { name: '岁月神偷', artist: '金玟崎', url: 'https://mp3.9ku.com/hot/2014/03-19/599207.mp3', cover: '/uploads/Picture4.jpg', }, { name: 'Five Hundred Miles', artist: '<NAME>', url: 'https://mp32.9ku.com/upload/128/2020/10/03/1010017.mp3', cover: '/uploads/Picture6.jpg', }, { name: '踏山河', artist: '是七叔呢', url: 'https://mp32.9ku.com/upload/128/2020/11/27/1012453.mp3', cover: '/uploads/Picture7.jpg', }, { name: '爸爸妈妈', artist: '李荣浩', url: 'https://mp32.9ku.com/upload/128/2020/11/05/1011194.mp3', cover: '/uploads/Picture8.jpg', }, { name: '麻雀', artist: '李荣浩', url: 'https://mp32.9ku.com/upload/128/2019/12/19/1000460.mp3', cover: '/uploads/Picture9.jpg', }, { name: '李白', artist: '李荣浩', url: 'https://mp3.9ku.com/hot/2013/09-03/559420.mp3', cover: '/uploads/Picture10.jpg', }, { name: '老街', artist: '李荣浩', url: 'https://mp3.9ku.com/mp3/420/419428.mp3', cover: '/uploads/Picture11.jpg', }, { name: '偏爱', artist: '张芸京', url: 'https://mp3.9ku.com/mp3/184/183900.mp3', cover: '/uploads/Picture12.jpg', }, ] });
500ed9918aa8aaf5c8a2383f5c388bfde33593eb
[ "JavaScript" ]
1
JavaScript
haoqianglyu/haoqianglyu.github.io
a0de3000111709d70c475983fc9a06e4963d70e4
d80b61d3f4c9fcde91e78fe59a08d97a7e68089f
refs/heads/master
<file_sep>package com.nat.test.pages; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; /** * Base class for all pages */ public abstract class Page { protected WebDriver driver; /** * Class constructor * * @param driver * The driver that will be used for navigation * @throws IllegalStateException * If it's not expected page */ public Page(WebDriver driver) { this.driver = driver; String title = driver.getTitle().trim(); String expTitle = (String) getExpectedTitle(); System.out.println("title: " + title); if (null != expTitle && !title.contains(expTitle)) { throw new IllegalStateException("This is not the " + expTitle + ", this is " + title); } } public abstract CharSequence getExpectedTitle(); /** * presents in new design */ @FindBy(xpath = "//*[@class = 'Header-item position-relative mr-0 d-none d-lg-flex']") protected WebElement avatarLink; @FindBy(name = "q") protected WebElement search; @FindBy(xpath = "//*[@class='dropdown-item dropdown-signout']") protected WebElement logout; /** * Checks if the element presents on the page and visible * * @param element * * element to check * * @return true if the element presents on the page and visible */ protected boolean isElementPresents(WebElement element) { try { return element.isDisplayed(); } catch (NoSuchElementException e) { return false; } } /** * The method to logout * * @return An instance of {@link Page} class after logout */ public Page logout() { if (isElementPresents(avatarLink)) { avatarLink.click(); logout.click(); return this; } else { System.out.println("Logout is failed"); return this; } } /** * Method to search * * @param query * Search query * @return An instance of {@link Page} class with search result */ public Page search(String query) { search.clear(); search.sendKeys(query); search.submit(); return this; } }
78b74a830609beb4b665fe62ea92e5ea8d215e0c
[ "Java" ]
1
Java
marishkavasiuk/Java-Selenium-TestNG
fa5a570d17a563dd64179ee865834226ed357b5b
a023a9101a1dea3026557d87659e9446989363b4
refs/heads/master
<repo_name>yasminbraga/biblioteca<file_sep>/app/controllers/books.py from app import app, db from flask import render_template, request, redirect, url_for from app.models.models import Book from app.forms.book import BookForm @app.route('/books') def index_books(): books = Book.query.all() return render_template('books/index.html', books=books) @app.route('/books/new', methods=['GET','POST']) def new_book(): form = BookForm(request.form) if request.method == 'POST': book = Book(form) db.session.add(book) db.session.commit() return redirect(url_for('index_books')) return render_template('books/new.html', form=form) @app.route('/books/edit/<int:id>', methods=['GET','POST']) def edit_books(id): book = Book.query.get(id) form = BookForm(request.form, obj=book) if request.method == 'POST': form.populate_obj(book) db.session.add(book) db.session.commit() return redirect(url_for('index_books')) return render_template('books/edit.html', form=form) @app.route('/books/delete/<int:id>') def delete_books(id): book = Book.query.get(id) db.session.delete(book) db.session.commit() return redirect(url_for('index_books'))<file_sep>/app/controllers/series.py from app import app, db from flask import render_template, request, redirect, url_for from app.models.models import Series from app.forms.series import SeriesForm @app.route('/series') def index_series(): series = Series.query.all() return render_template('series/index.html', series=series) @app.route('/series/new', methods=["GET", "POST"]) def new_series(): form = SeriesForm(request.form) if request.method == "POST": series = Series(form) db.session.add(series) db.session.commit() return redirect(url_for("index_series")) return render_template("series/new.html", form=form) @app.route('/series/edit/<int:id>', methods=["GET", "POST"]) def edit_series(id): series = Series.query.get(id) form = SeriesForm(request.form, obj=series) if request.method == "POST": db.session.add(series) db.session.commit() return redirect(url_for('index_series')) return render_template('series/edit.html', form=form) @app.route('/series/delete/<int:id>') def delete_series(id): series = Series.query.get(id) db.session.delete(series) db.session.commit() return redirect(url_for('index_series')) <file_sep>/app/controllers/films.py from app import app, db from flask import render_template, request, redirect, url_for from app.models.models import Film from app.forms.film import FilmForm @app.route('/films') def index_films(): films = Film.query.all() return render_template('films/index.html', films=films) @app.route('/films/new', methods=['GET', 'POST']) def new_film(): form = FilmForm(request.form) if request.method == 'POST': film = Film(form) db.session.add(film) db.session.commit() return redirect(url_for('index_films')) return render_template('films/new.html', form=form) @app.route('/films/edit/<int:id>', methods=['GET', 'POST']) def edit_films(id): film = Film.query.get(id) form = FilmForm(request.form, obj=film) if request.method == 'POST': db.session.add(film) db.session.commit() return redirect(url_for('index_films')) return render_template('films/edit.html', form=form) @app.route('/films/delete/<int:id>') def delete_films(id): film = Film.query.get(id) db.session.delete(film) db.session.commit() return redirect(url_for('index_films')) <file_sep>/app/forms/film.py from flask_wtf import FlaskForm from wtforms import fields, validators class FilmForm(FlaskForm): name = fields.StringField('Name', validators=[validators.DataRequired()]) year = fields.IntegerField('Year', validators=[validators.DataRequired()]) genre = fields.StringField('Genre', validators=[validators.DataRequired()]) status = fields.BooleanField('Status', default="checked")<file_sep>/app/forms/book.py from flask_wtf import FlaskForm from wtforms import fields, validators class BookForm(FlaskForm): name = fields.StringField('Name', validators=[validators.DataRequired()]) author = fields.StringField('Author', validators=[validators.DataRequired()]) genre = fields.StringField('Genre', validators=[validators.DataRequired()]) status = fields.BooleanField('Status', default="checked")<file_sep>/app/__init__.py from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) migrate = Migrate(app, db) from app.controllers import books, films, series <file_sep>/config.py SECRET_KEY = 'ajhdalkskjdoia' SQLALCHEMY_DATABASE_PASSWORD = '<PASSWORD>' SQLALCHEMY_DATABASE_URI = 'postgresql:///biblioteca' SQLALCHEMY_TRACK_MODIFICATIONS = True<file_sep>/migrations/versions/1327d32301e1_.py """empty message Revision ID: 1327d32301e1 Revises: <PASSWORD> Create Date: 2019-09-05 19:29:26.953274 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '1<PASSWORD>' down_revision = '<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('book', sa.Column('author', sa.String(), nullable=False)) op.add_column('book', sa.Column('genre', sa.String(), nullable=False)) op.add_column('book', sa.Column('status', sa.Boolean(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('book', 'status') op.drop_column('book', 'genre') op.drop_column('book', 'author') # ### end Alembic commands ### <file_sep>/app/models/models.py from app import db class Book(db.Model): __tablename__ = 'book' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) author = db.Column(db.String, nullable=False) genre = db.Column(db.String, nullable=False) status = db.Column(db.Boolean, default=False, server_default="false") def __init__(self,form): self.name = form.name.data self.author = form.author.data self.genre = form.genre.data self.status = form.status.data class Film(db.Model): __tablename__ = 'film' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) year = db.Column(db.Integer) genre = db.Column(db.String) status = db.Column(db.Boolean) def __init__(self, form): self.name = form.name.data self.year = form.year.data self.genre = form.genre.data self.status = form.status.data class Series(db.Model): __tablename__ = 'series' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) year = db.Column(db.Integer) genre = db.Column(db.String) seasons = db.Column(db.Integer) status = db.Column(db.Boolean) def __init__(self, form): self.name = form.name.data self.year = form.year.data self.genre = form.genre.data self.seasons = form.seasons.data self.status = form.status.data
778b22b63099a181f0ebb56847d52a392f7fb364
[ "Python" ]
9
Python
yasminbraga/biblioteca
46ddb70d040f2c2a6e1439603a35c2fd88a93fd3
65dc985cb8f8ad8b6349407a48d1c1962853cb4c
refs/heads/master
<file_sep>$(function () { var basket = $('#basket') , container = $('#container') , hen = $('.hen') , eggs = $('.egg') , egg1 = $('#egg1') , egg2 = $('#egg2') , egg3 = $('#egg3') , restart = $('#restart') , score_span = $('#score') , score_1 = $('#score_1') , life_span = $('#life') , basket_width = basket.width() , basket_height = basket.height() , hen_height = hen.height() , container_height = container.height() , egg_height = eggs.height() , egg_initial_position = parseInt(eggs.css('top')) , score = 0 , life = 20 , speed = 3 , counter = 0 , score_updated = false , the_game, anim_id, egg_current_position, bullseye_num; life_span.text(life); the_game = function () { counter++; // Eggs down //if (counter > 10) egg_down(egg1); //if (counter > 80) egg_down(egg2); //if (counter > 30) egg_down(egg3); //Check eggs fall in basket if (check_catch(egg1)) { update_score(egg1); } if (check_catch(egg2)) { update_score(egg2); } if (check_catch(egg3)) { update_score(egg3); } //Check eggs has gone out of the container if (parseInt(egg1.css('top')) >= container_height - egg_height) { set_egg_to_initial_position(egg1); } else { if (counter > 10) egg_down(egg1); } if (parseInt(egg2.css('top')) >= container_height - egg_height) { set_egg_to_initial_position(egg2); } else { if (counter > 80) egg_down(egg2); } if (parseInt(egg3.css('top')) >= container_height - egg_height) { set_egg_to_initial_position(egg3); } else { if (counter > 30) egg_down(egg3); } if (life) { anim_id = requestAnimationFrame(the_game); } else { stop_the_game(); } }; anim_id = requestAnimationFrame(the_game); $(document).mousemove(function (e) { basket.css('left', e.pageX - basket_width / 2); }); restart.click(function () { location.reload(); }); function egg_down(egg) { egg_current_position = parseInt(egg.css('top')); egg.css('top', egg_current_position + speed); } function check_catch(egg) { if (collision(egg, basket) && (parseInt(egg.css('top')) >= parseInt(container_height - basket_height - egg_height)) && (parseInt(egg.css('top')) <= parseInt(container_height - basket_height))) return true return false; } function update_score(egg) { set_egg_to_initial_position(egg, false); score = score + 1; score_span.text(score); score_1.text(score); if (score % 5 === 0) { life = life + 1; } if (score % 20 === 0) { speed = speed + 1; } } function set_egg_to_initial_position(egg, update_life_flag = true) { if (update_life_flag) { update_life(); show_bullseye(egg); } egg.css('top', egg_initial_position); hide_bullseye(egg); } function update_life() { life = life - 1; if (life < 0) { life = 0; } else { life_span.text(life); } } function show_bullseye(egg) { bullseye_num = egg.attr('data-bullseye'); $('#bullseye' + bullseye_num).show(); } function hide_bullseye(egg) { setTimeout(function () { bullseye_num = egg.attr('data-bullseye'); $('#bullseye' + bullseye_num).hide(); }, 800); } function stop_the_game() { cancelAnimationFrame(anim_id); $('#restart').slideDown(); } });
d2e9e6a06ca53724c0f52471a83362c1b04693dc
[ "JavaScript" ]
1
JavaScript
GermanKingYT/arshadasgar.github.io
b9c63776ec63ffaba60f488cee41f9cc70de1311
8d10b3f8b18a316b87a44afabb7e5cba90c90433
refs/heads/master
<repo_name>f3r/electron-app<file_sep>/app/controls/utils.js var config = require('./../config.js') var multiaddr = require('multiaddr') exports = module.exports exports.apiAddrToUrl = function apiAddrToUrl (apiAddr) { var parts = multiaddr(apiAddr).nodeAddress() var url = 'http://' + parts.address + ':' + parts.port + config['webui-path'] return url } <file_sep>/README.md IPFS Native Application ======================= [![](https://img.shields.io/badge/made%20by-Protocol%20Labs-blue.svg?style=flat-square)](http://ipn.io) [![](https://img.shields.io/badge/project-IPFS-blue.svg?style=flat-square)](http://ipfs.io/) [![](https://img.shields.io/badge/freenode-%23ipfs-blue.svg?style=flat-square)](http://webchat.freenode.net/?channels=%23ipfs) [![Dependency Status](https://david-dm.org/ipfs/electron-app.svg?style=flat-square)](https://david-dm.org/ipfs/electron-app) > A Native Application for your OS to run your own IPFS Node. Built with Electron Shell ## folder structure ```bash $ tree app app ├── controls # Application controls to interact with the system ├── img │   ├── loading.gif │   └── logo.png ├── init.js ├── js # React/Frontend components │   ├── help.js │   ├── menubar.jsx # React view for all the things menu bar │   ├── toggle.jsx │   └── welcome.jsx # React component for the welcoming screen for 1st time users ├── styles │   ├── common.css │   └── menu.css └── views ├── help.html ├── menubar.html └── welcome.html ``` # usage ```bash $ npm i $ npm start ``` This launches the app and runs it in your menu bar. Click the IPFS icon to open a console. For example (in OSX): ![](https://ipfs.io/ipfs/QmU5AghSAezpYFNyuYZ7gX1zcHCheQndPtBMj1MHr5QpWL/cap.png) # packaging will be written to ./dist ### make a package for your system ```bash npm run dist ``` ### make packages for all platforms ```bash npm run dist-all ``` <file_sep>/index.js require('./build/init')() <file_sep>/app/controls/error-panel.js var BrowserWindow = require('browser-window') var path = require('path') var config = require('./../config') exports = module.exports = errorPanel function errorPanel (err) { var errorWindow = new BrowserWindow(config.window) errorWindow.loadUrl('file://' + path.resolve(__dirname, '../views/help.html')) errorWindow.webContents.on('did-finish-load', function () { errorWindow.webContents.send('err', err.toString()) }) } <file_sep>/build.sh rm -r build mkdir build 2> /dev/null mkdir build/js node_modules/.bin/browserify app/js/menubar.jsx > build/js/menubar.js node_modules/.bin/browserify app/js/welcome.jsx > build/js/welcome.js cp app/js/help.js build/js/help.js cp -r app/views build/views cp -r app/styles build/styles cp -r app/img build/img cp -r app/controls build/controls cp app/init.js build/init.js cp app/config.js build/config.js <file_sep>/app/config.js var path = require('path') var os = require('os') exports = module.exports = { 'menu-bar-width': 240, window: { icon: path.resolve(__dirname, '../node_modules/ipfs-logo/ipfs-logo-256-ice.png'), 'auto-hide-menu-bar': true, width: 800, height: 600 }, 'tray-icon': (os.platform() !== 'darwin' ? path.resolve(__dirname, '../node_modules/ipfs-logo/ipfs-logo-256-ice.png') : path.resolve(__dirname, '../node_modules/ipfs-logo/platform-icons/osx-menu-bar.png')), 'webui-path': '/webui' } <file_sep>/app/controls/open-browser.js var ipc = require('ipc') var apiAddrToUrl = require('./utils').apiAddrToUrl var init = require('./../init') var open = require('open') ipc.on('open-browser', openBrowser) function openBrowser (cb) { if (init.IPFS) { init.IPFS.config.get('Addresses.API', function (err, res) { if (err) { // TODO error should be emited to a error panel return console.error(err) } open(apiAddrToUrl(res.Value)) }) } else { // TODO error should be emited to a error panel var err = new Error('Cannot open browser, IPFS daemon not running') console.error(err) } } <file_sep>/app/controls/open-console.js var ipc = require('ipc') var BrowserWindow = require('browser-window') var config = require('./../config') var apiAddrToUrl = require('./utils').apiAddrToUrl var init = require('./../init') ipc.on('open-console', openConsole) function openConsole () { if (init.IPFS) { init.IPFS.config.get('Addresses.API', function (err, res) { if (err) { // TODO() error should be emited to a error panel return console.error(err) } var consoleWindow = new BrowserWindow(config.window) consoleWindow.loadUrl(apiAddrToUrl(res.Value)) }) } else { // TODO() error should be emited to a error panel var err = new Error('Cannot open console, IPFS daemon not running') console.error(err) } }
ce8d526536b4f23545bb90cffaa7465eb709a42f
[ "JavaScript", "Markdown", "Shell" ]
8
JavaScript
f3r/electron-app
b350f7ac8e74737082cbfd65aea631bfc4e72a61
e692043a8d72e704e9c372f3c9ee55273986f7ec
refs/heads/main
<repo_name>ash14545/discord.js-bot-with-multiple-instances<file_sep>/README.md # discord.js-bot-with-multiple-instances A discord.js bot that supports logging into multiple tokens with their own unique prefixes. <file_sep>/index.js const { Discord, Collection } = require('discord.js'); const config = require('./config.json'); for (const [token, prefix] of Object.entries(config.tokens)) { const DiscordClient = require("./struct/Client.js"); const client = new DiscordClient(); client.commands = new Collection(); client.aliases = new Collection(); client.prefix.set(token, prefix) require("./functions")(client); client.login(token) module.exports = { client: client }; };<file_sep>/functions.js const fs = require("fs"); const path = require("path"); module.exports = client => { function walk(dir, callback) { fs.readdir(dir, function (err, files) { if (err) throw err; files.forEach(function (file) { var filepath = path.join(dir, file); fs.stat(filepath, function (err, stats) { if (stats.isDirectory()) { walk(filepath, callback); } else if (stats.isFile() && file.endsWith(".js")) { let props = require(`./${filepath}`); client.commands.set(props.name, props); props.aliases.forEach(alias => { client.aliases.set(alias, props.name); }); } }); }); }); } walk(`./commands/`); fs.readdirSync('./handlers' + '/').forEach(function (file) { if (file.match(/\.js$/) !== null && file !== 'index.js') { var name = file.replace('.js', ''); exports[name] = require('./handlers/' + file)(client); }; }); }; <file_sep>/commands/helloWorld.js module.exports = { maintenance: false, category: "", name: "helloworld", aliases: ["hello"], description: "Hello world!", usage: "", cooldown: -1, clientPermissions: ['SEND_MESSAGES'], userPermissions: ['SEND_MESSAGES'], args: false, async execute(client, message, args) { message.channel.send('Hello world!'); } };
b07b490a40ed53160dc41570c5795740f8d7c1b5
[ "Markdown", "JavaScript" ]
4
Markdown
ash14545/discord.js-bot-with-multiple-instances
48368a0c22a6fe18aec537054740f25e9e347591
cfe7a7462a88e953e5631deaab22d4e7ac80f5bd
refs/heads/master
<repo_name>itsal-tsalko/WeatherStationTask<file_sep>/src/main/java/com/epam/study/store/customer/CustomerNotificationService.java package com.epam.study.store.customer; import com.epam.study.store.Item; import java.util.List; /** * @author <NAME> */ public interface CustomerNotificationService { void notifyCustomers(List<Item> items); } <file_sep>/src/main/java/com/epam/study/store/customer/Topics.java package com.epam.study.store.customer; /** * @author <NAME> */ public enum Topics { FOOD, CLOTHES, SPORT, BOOKS } <file_sep>/src/main/java/com/epam/study/news/adaptor/NewsAdapter.java package com.epam.study.news.adaptor; import com.epam.study.news.NewsType; import com.epam.study.news.TopicsAggregator; /** * @author <NAME> */ public interface NewsAdapter<T> { NewsType getNewsType(); String toUnifiedFormat(T feedData); default void publishNews(TopicsAggregator aggregator, T feedData){ aggregator.publishNews(toUnifiedFormat(feedData), getNewsType()); } } <file_sep>/src/main/java/com/epam/study/news/adaptor/WeatherAdaptor.java package com.epam.study.news.adaptor; import com.epam.study.news.NewsType; import com.epam.study.news.TopicsAggregator; import com.epam.study.weatherstation.Weather; import com.epam.study.weatherstation.WeatherStation; import com.epam.study.weatherstation.display.Display; import org.apache.log4j.Logger; /** * @author <NAME> */ public class WeatherAdaptor implements NewsAdapter<Weather>, Display { final static Logger logger = Logger.getLogger(WeatherAdaptor.class); private WeatherStation weatherStation; private TopicsAggregator topicsAggregator; public NewsType getNewsType() { return NewsType.WEATHER; } @Override public void update() { publishNews(topicsAggregator, weatherStation.getWeather()); logger.info("Published news regarding weather update"); } @Override public String toUnifiedFormat(Weather weather){ return weather.toString(); } public String display(){ return null; } @Override public void connect(WeatherStation weatherStation) { this.weatherStation = weatherStation; weatherStation.connect(this); } public void disconnect(){ } public void setTopicAggregator(TopicsAggregator topicsAggregator){ this.topicsAggregator = topicsAggregator; } } <file_sep>/src/main/java/com/epam/study/store/AdvertisementSender.java package com.epam.study.store; /** * @author <NAME> */ public interface AdvertisementSender { void send(Advertisement advertisement); } <file_sep>/src/main/java/com/epam/study/weatherstation/WeatherStation.java package com.epam.study.weatherstation; import com.epam.study.weatherstation.display.Display; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List; /** * @author <NAME> */ public class WeatherStation { final static Logger logger = Logger.getLogger(WeatherStation.class); private Weather weather; private List<Display> listeners = new ArrayList<Display>(); public Weather getWeather() { return weather; } public void setWeather(Weather weather) { this.weather = weather; notifyAllListeners(); logger.info("Weather has been updated"); } public void connect(Display listener) { listeners.add(listener); } public void disconnect(Display listener) { listeners.remove(listener); } public void notifyAllListeners() { for (Display listener : listeners) { listener.update(); } } } <file_sep>/src/main/java/com/epam/study/weatherstation/display/Display.java package com.epam.study.weatherstation.display; import com.epam.study.weatherstation.WeatherStation; /** * @author <NAME> */ public interface Display { String display(); void update(); void connect (WeatherStation weatherStation); void disconnect(); } <file_sep>/src/main/java/com/epam/study/store/Store.java package com.epam.study.store; import com.epam.study.store.customer.CustomerNotificationService; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @author <NAME> */ public class Store { final static Logger logger = Logger.getLogger(Store.class); List<CustomerNotificationService> customerNotificationServices = new ArrayList<>(); List<Item> itemList = new ArrayList<>(); Map<Subscriber, String> mapping = new HashMap<>(); public void addCustomerNotificationServices(CustomerNotificationService customer) { customerNotificationServices.add(customer); } public List<Item> getItemList() { return itemList; } public void removeItem(Item item) { itemList.remove(item); } public void addItem(Item item) { itemList.add(item); for (Subscriber subscriber : mapping.keySet()) { if (mapping.get(subscriber).contains(item.type.toString())) { subscriber.notifySubscriber(item); } } } public void subscribe(Subscriber subscriber, String pattern) { mapping.put(subscriber, pattern); } public void unsubscribe(Subscriber subscriber) { mapping.remove(subscriber); } public void sendAdvertisementsForAllCustomers() { customerNotificationServices.stream().forEach(service -> service.notifyCustomers(itemList.stream().filter(Item::isOnSale).collect(Collectors.toList()))); logger.info("Advertisements has been sent to all customers"); } } <file_sep>/src/main/java/com/epam/study/weatherstation/display/CurrentConditionsDisplay.java package com.epam.study.weatherstation.display; /** * @author <NAME> */ public class CurrentConditionsDisplay extends WeatherStationDisplay { double humidity; double temperature; double pressure; public void update() { if (weatherStation.isPresent()) { humidity = weatherStation.get().getWeather().getHumidity(); temperature = weatherStation.get().getWeather().getTemperature(); pressure = weatherStation.get().getWeather().getPressure(); } logger.info("Weather has been updated on "+ CurrentConditionsDisplay.class.getSimpleName()); } public String display() { String PATTERN = "humidity = %.2f, temperature = %.2f, pressure = %.2f"; return String.format(PATTERN, humidity, temperature, pressure); } } <file_sep>/src/main/java/com/epam/study/store/customer/WholesaleCustomerNotificationService.java package com.epam.study.store.customer; import com.epam.study.store.Advertisement; import com.epam.study.store.Item; import com.epam.study.store.AdvertisementSender; import com.epam.study.store.Store; import org.apache.log4j.Logger; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; /** * @author <NAME> */ public class WholesaleCustomerNotificationService implements CustomerNotificationService { final static Logger logger = Logger.getLogger(WholesaleCustomerNotificationService.class); private AdvertisementSender sender; public WholesaleCustomerNotificationService(Store store, AdvertisementSender sender) { store.addCustomerNotificationServices(this); this.sender = sender; } public void notifyCustomers(List<Item> items) { List<Item> filteredItems = items.stream().filter(Item::isWholeSaleItem).collect(Collectors.toList()); Advertisement advertisement = new Advertisement(filteredItems, LocalDateTime.now()); sender.send(advertisement); logger.info("Advertisement has been sent to all wholesale customers"); } }
0248d4f428c6be35aa08c071732564f1f3d6b780
[ "Java" ]
10
Java
itsal-tsalko/WeatherStationTask
32e29b44cbbb0e21dc2d47be84b28712d6b424e0
f586538d808e34472c6161da381450a40b895412
refs/heads/master
<file_sep><?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ Route::get('/', function() { // return Topic::all(); // return Article::find(1); // return User::find(2); }); Route::get('topics', function(){ return View::make("topic"); }); Route::get('topics/{id}',function($id){ $oTopic = Topic::find($id); return View::make("topic")->with("topic", $oTopic); }); Route::get('articles/create',function(){ $aTopics = Topic::lists("name","id"); return View::make("newArticleForm")->with('topics', $aTopics); }); Route::get('articles/{id}', function($id){ $oArticle = Article::find($id); return View::make("article")->with("article", $oArticle); }); Route::post('articles',function(){ $aRules = array( 'title' =>'required', 'content'=>'required', 'photo'=>'required' ); $oValidator = Validator::make(Input::all(), $aRules); if($oValidator->passes()){ //uploading photo $sNewName = Input::get("name").".".Input::file("photo")->getClientOriginalExtension(); Input::file("photo")->move("articlephotos/",$sNewName); //create new product $aDetails = Input::all(); $aDetails["photo"]= $sNewName; $oArticle = Article::create($aDetails); //redirect to topic list return Redirect::to("topics/".$oArticle->topic_id); }else{ return Redirect::to("articles/create")->withErrors($oValidator)->withInput(); } }); Route::get('users/create', function(){ return View::make("register"); }); Route::post('users',function(){ //validate input $aRules = array( 'email'=>'required|email|unique:users', 'firstname' =>'required', 'lastname' =>'required', 'password' => '<PASSWORD>' ); $messages = array( //create custom error messages for certain input fields. 'email'=>':attibute must be a vailed format.', //:attribute is input controller's name. 'required' =>':attribute must be filled.' ); $oValidator = Validator::make(Input::all(),$aRules,$messages); if($oValidator->fails()){ //output is true, which means, $oValidator fails. return Ridirect::to("users/create")->withErrors($oValidator)->withInput(); }else{ //output is false, means, $oValidator is (not failed) = passed. //so, create a new user $aDetails = Input::all(); $aDetails["password"] = <PASSWORD>($aDetails["password"]); $user = User::create($aDetails); return Redirect::to("login"); } }); Route::get('users/{id}',function($id){ $oUser = User::find($id); return View::make("userProfile")->with('user',$oUser); }); Route::get('users/{id}/edit',function($id){ $oUser = User::find($id); return View::make('editUserForm')->with('user',$oUser); }); Route::put('users/{id}',function($id){ //validate data $aRules = array( 'firstname'=>'required', 'lastname'=>'required', 'email'=>'required|email|unique:users,email,'.$id, //the third parameter is for expection. which means, this email should be unique comparing to the user table exept $id user's field. ); //table - column - filed. $oValidator = Validator::make(Input::all(),$aRules); if($oValidator->passes()){ //update user //long hand $oUser = User::find($id); $oUser->fill(Input::all()); $oUser->save(); //short hand //User::find($id)->fill(Input::all())->save(); //redirect to user page return Redirect::to('users/'.$id); }else{ //redirect to edit user form with sticky input values and errors return Redirect::to('users/'.$id.'/edit') ->withErrors($oValidator) ->withInput(); } }); Route::get('login', function(){ return View::make("loginForm"); }); Route::post('login', function(){ $aLoginDetails = array( 'email' => Input::get('email'), 'password' => Input::get('password') ); if(Auth::attempt($aLoginDetails)){ return Redirect::intended("users/".Auth::user()->id); }else{ return Redirect::to("login")->with("error","Try again!"); } }); Route::get('logout', function(){ Auth::logout(); return Redirect::to('topics/1'); });
e184987ff0a4d2f023766bbea9b378ef023aeb2e
[ "PHP" ]
1
PHP
deseloperem/blog
db58099c1c3128541da47b07c5240878be1fc015
c8a924d9006b1475ed2df8e39ebc9ed7dd795815
refs/heads/master
<file_sep> /** * which basically creates a instance of bxSlider and handles all its functionalities here */ define([ 'js/lib/jquery.bxslider', 'js/lib/jquery.fitvids' ], function(){ /** * @Class slider * * which creates a instance of bx slider and handles all the events related to it * * All data-type will instantiate this class and to avoid creating 2 instances of the same we are checking for hasCarousel class */ var Slider = function(options){ console.log("calling slider constuctor with the below parameters"); if(!options.sliderElement){ throw new Error("cliked target is(slider element) not defined. you must pass a slider element from which will retrive data for slider"); } this.options = { sliderElement : null }; $.extend(this.options,(options ? options : {})); console.log(this.options); this.init(); }; /** * All public properties are defined here */ Slider.prototype = { constructor : Slider, init : function(){ this.initVariable(); if(this.sliderElement.hasClass('hasCarousel')){ $(window).trigger('resize'); return true; }else{ this.removeEventListeners(); this.initEvents(); this.getSliderData(); } }, initVariable : function(){ this.sliderElement = this.options.sliderElement; this.sliderContainer = $(this.sliderElement.data('containerRef')); this.url = this.sliderElement.data('url'); this.carouselControllerWrapper = $('.carouselControllerWrapper'); }, initEvents : function(){ this.carouselControllerWrapper.on('click','.carouselControllerPrev', this.clickedPrevButton); this.carouselControllerWrapper.on('click','.carouselControllerNext',this.clickedNextButton); }, clickedPrevButton : function(){ $('.bx-prev').trigger('click'); }, clickedNextButton : function(){ $('.bx-next').trigger('click'); }, /** * @method removeEventListeners * Unbind all events if required */ removeEventListeners : function(){ this.carouselControllerWrapper.off('click','.carouselControllerPrev', this.clickedPrevButton); this.carouselControllerWrapper.off('click','.carouselControllerNext',this.clickedNextButton); }, getSliderData : function(){ var me = this; $.ajax({ type: "GET", dataType: "json", url: me.url, success: function(data) { me.processSliderData(data); }, error: function(data) { me.handleErrors(); } }); }, /** * @method processSliderData * @param data * Which does processing of data which is received from server/json */ processSliderData : function(data){ this.createSliderImages(data); this.createSliderDescription(data); this.sliderContainer.find('.itemDetails').first().show(); this.applySlider(); }, /** * @method applySlider * Creates a bx-slider instance */ applySlider : function(){ var me = this; var carouselRef = this.sliderContainer.find(".viewCarousel"); carouselRef.show(); carouselRef.find('.bxslider').bxSlider({ touchEnabled: true, touchEnabled: true, mode: 'horizontal', video: true, responsiv: true, autoHover: true, useCSS: false, captions: true, auto: true, parentRef: me.sliderContainer }); this.sliderElement.addClass("hasCarousel"); $(window).trigger('resize'); }, /** * @method createSliderImages * @param data * @param id * Create a slider images here */ createSliderImages : function (data, id) { var templateIdImage = this.sliderContainer.find(".bxslider").attr("data-ref-id"); var imageTemplate = Handlebars.compile($(templateIdImage).html()); this.sliderContainer.find('.bxslider').append((imageTemplate(data))); }, /** * @method createSliderDescription * @param data * @param id * Create a slider descriptions here */ createSliderDescription : function (data, id) { var templateId = this.sliderContainer.find(".carouselDescription").attr("data-ref-id"); var descriptionTemplate = Handlebars.compile($(templateId).html()); this.sliderContainer.find('.carouselDescription').append((descriptionTemplate(data))); }, /** * All ajax error handling should come here */ handleErrors : function(){ } }; return Slider; } ) <file_sep>/** * Used for defining all global application level config values */ define(function(){ return{ /** * @param autoPlayTime * used for configuring auto play timeout */ autoPlayTime : 20000 }; }); <file_sep>Studio-Wall =========== Studio wall application 1. Download tomcat from here : - http://apache.claz.org/tomcat/tomcat-7/v7.0.63/bin/apache-tomcat-7.0.63.exe 2. Download source code form : - https://github.com/jagadeeshaby/Studio-Wall.git 3. Place the downloaded source code inside C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps 4. Also inside the source code there is a deployment folder and you see “social-media.war” file inside take that and put it in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps 5. Also place the attached conf into C:\Program Files\Apache Software Foundation\Tomcat 7.0 6. Then access http://localhost:8080/Studio-Wall/index.shtml <file_sep>/** * Which creates instance of social feeds and upadtes the dom * */ define([ 'js/helpers' ], function(){ var SocialFeeds = function(options){ console.log("calling social feed constuctor"); if(!options.socialFeedContainer){ throw new Error("socialFeedContainer element is not defined. you must pass a socialFeedContainer which we wll be using it for " + "updating social feed output"); } this.options = { socialFeedContainer : $("#socialUpdates"), templateId: 'socialMessages' }; $.extend(this.options,(options ? options : {})); console.log(this.options); this.init(); }; SocialFeeds.prototype = { constructor : SocialFeeds, init : function(){ this.initvariable(); this.removeEventListenrs(); this.initEvents(); this.getSocialFeeds(); }, initvariable : function(){ this.socialFeedTemplate = this.options.socialFeedTemplate;//Handlebars.compile($(this.options.templateId).html()), this.socialFeedContainer = this.options.socialFeedContainer; this.url = this.options.socialFeedElement.data('url'); }, initEvents : function(){ $(document).on('click',".socialMediaLink",this.socialMediaLinkClicked); }, removeEventListenrs : function(){ $(document).off('click',".socialMediaLink",this.socialMediaLinkClicked); }, socialMediaLinkClicked : function(){ //window.open($(this).data('url'), "", "width="+window.innerWidth+", height="+window.innerHeight); }, getSocialFeeds : function(){ var me = this; $.ajax({ type: "GET", dataType: "json", url: me.url, success: function(data) { me.processSocialData(data); }, error: function(data) { me.handleErrors(); } }); }, processSocialData : function(data){ this.socialFeedContainer.html(''); this.socialFeedContainer.html(this.socialFeedTemplate(data)); }, handleErrors : function(){ this.socialFeedContainer.html("Failed to Load:"); } }; return SocialFeeds; } ); <file_sep>/** * All handle bar helper methods comes here */ Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) { switch (operator) { case '==': return (v1 == v2) ? options.fn(this) : options.inverse(this); case '===': return (v1 === v2) ? options.fn(this) : options.inverse(this); case '<': return (v1 < v2) ? options.fn(this) : options.inverse(this); case '<=': return (v1 <= v2) ? options.fn(this) : options.inverse(this); case '>': return (v1 > v2) ? options.fn(this) : options.inverse(this); case '>=': return (v1 >= v2) ? options.fn(this) : options.inverse(this); case '&&': return (v1 && v2) ? options.fn(this) : options.inverse(this); case '||': return (v1 || v2) ? options.fn(this) : options.inverse(this); default: return options.inverse(this); } }); Handlebars.registerHelper('dateFormat', function(context, block) { return new Date(context).toLocaleString(); }); <file_sep>/** * initializes wall home clould 9 carousal */ define([ 'js/lib/jquery.cloud9carousel', 'js/lib/jquery.reflection' ], function( carousal, reflection ){ var WallHome = function(options){ console.log("wall home contsructor called"); this.init(); }; WallHome.prototype = { constructor : WallHome, init : function(){ this.initVariable(); this.initEvents(); this.initializeCarousal(); }, initVariable : function(){ this.showcase = $("#showcase"); }, initEvents : function(){ }, initializeCarousal : function(){ var me = this; this.carousal = this.showcase.Cloud9Carousel({ itemClass: "card", buttonLeft: $("#nav > .left"), buttonRight: $("#nav > .right"), autoPlay: 1, bringToFront: true, onLoaded : function(){ me.showcase.css('visibility', 'visible'); me.showcase.css('display', 'none'); me.showcase.fadeIn(1500); }, }); } }; return WallHome; } );
d9c1d2a9041dac37718b0f93e57ac5b9d84ef3bb
[ "JavaScript", "Markdown" ]
6
JavaScript
jagadeeshaby/Studio-Wall
ed49619a96329390e8dba305b4f869154325a479
a89eec167eef4c0debf741bc8b17d27dd357255a
refs/heads/main
<file_sep>const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; var paper; var tc1, tc2, tc3; var ground var trashcan, tcIMG; function preload(){ tcIMG = loadImage("Trashcan.png"); } function setup() { createCanvas(800, 400); engine = Engine.create(); world = engine.world; //Create the Bodies Here. ground = new Ground(400,365,800,15); paper = new Paper(42,200,50)//(62,260,18); tc1 = new Trashcan(515,298,15,150); tc2 = new Trashcan(645,298,15,150); tc3 = new Trashcan(575,383,200,30); trashcan = createSprite(555,278,100,100); trashcan.addImage(tcIMG); trashcan.scale = 0.92 Engine.run(engine); } function draw() { rectMode(CENTER); background("black"); ground.display(); paper.display(); tc1.display(0); tc2.display("gray"); tc3.display(0); drawSprites(); } function keyPressed(){ if(keyCode === UP_ARROW){ Matter.Body.applyForce(paper.body, paper.body.position, {x: 370, y: -450}) } }
09937d18dbb5526f08b276a90fcf17a72f58c963
[ "JavaScript" ]
1
JavaScript
TheCoder215/Dont_Litter_Final
d3b6fdb52b9f775e92aea88cb1d4625d8dbfe935
b312608472912664f4eaee4e079d07924250b066
refs/heads/master
<repo_name>fefochico/async<file_sep>/src/route/async.js const express = require('express') var router = express.Router() var controller= require('../controller/async') router.get('/promisecallback/:iter', function(req, res, next){ controller.myasyncA(req, res, next); }) router.get('/promiseawait/:iter', function(req, res, next){ controller.myasyncB(req, res, next); }) router.get('/promiseallcallback/:iter1/:iter2', function(req, res, next){ controller.myasyncC(req, res, next); }) module.exports= router<file_sep>/src/controller/async.js var model= require('../model/async') function myasyncA(req, res, next){ var data=req.params if(!data.iter){ res.status(404).json('Missing field'); return; } model.info(data) .then(result=>{ res.status(200).json(result); }) .catch(err=>{ res.status(500).json(err); }) } async function myasyncB(req, res, next){ var data=req.params if(!data.iter){ res.status(404).json('Missing field'); return; } try { var response= await model.info(data) res.status(200).json(response) } catch (error) { res.status(500).json(error); } } function myasyncC(req, res, next){ var data1={iter: req.params.iter1} var data2={iter: req.params.iter2} if(!data1.iter){ res.status(404).json('Missing field'); return; } mypromises=[model.info(data1), model.info(data2)] Promise.all(mypromises) .then(result=>{ res.status(200).json({data1: result[0], data2: result[1]}); }) .catch(err=>{ res.status(500).json({err1: err[0], err2: err[1]}); }) } module.exports={ myasyncA, myasyncB, myasyncC }<file_sep>/README.md # async Nodejs API project to see examples of different ways to manage asynchronous tasks You have 3 routes:<br/> localhost:3000/async/promisecallback/:number <br/> Resolve a asynchronous task with promise callback <br/> localhost:3000/async/promiseawait/:number<br/> Resolve a asynchronous task with await and try/catch <br/> localhost:3000/async/promiseallcallback/:number1/:number2 <br/> Resolve 2 asynchronous tasks with promise.all callback <br/> <file_sep>/src/model/async.js function info(data){ return new Promise(function (resolve, reject){ setTimeout(()=> { var values=[]; for(let i=0; i<Number(data.iter); i++){ values.push({value: i}) } resolve(values); }, 2000); }) } module.exports={ info: info, }
2c0f146bad4375f99accb35fe83b73aa1e8b89a2
[ "JavaScript", "Markdown" ]
4
JavaScript
fefochico/async
11c6c4e0ba2e720290238cc0bd50e53bc9f8a30e
4e0c0522b4766a8ec8b2a9b75b255b3628613927
refs/heads/master
<repo_name>Yansongsongsong/financial-calculator<file_sep>/src/main/java/com/lanyu/miniprogram/repository/ReportRepository.java package com.lanyu.miniprogram.repository; import com.lanyu.miniprogram.bean.Report; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * @Author yansong * @Date 2018/10/13 12:32 */ public interface ReportRepository extends JpaRepository<Report, String> { Report getReportByWechatIdAndTimestamp(String wechatId, String timestamp); int countAllByWechatId(String wechatId); void deleteReportByWechatIdAndTimestamp(String wechatId, String timestamp); } <file_sep>/src/main/java/com/lanyu/miniprogram/bean/User.java package com.lanyu.miniprogram.bean; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.util.Date; /** * @author i343746 */ @Entity @EntityListeners(AuditingEntityListener.class) @Table(name="user") public class User { @Id @Column(name = "user_id") private String wechatId; // 姓名 用户姓名 @Column(name = "user_name") private String name; // 手机号 @Column(name = "phone") private String phone; // 服务区域, 用户所在的市级单位,根据GPS定位选择默认值,用户可更改 @Column(name = "serve_region") private String serveRegion; // 所在机构, 用户所在的单位、企业 如:XX人寿、XX银行 @Column(name = "enterprise") private String enterprise; // 分支机构 用户所在的单位、企业的分支部门 如:XX分公司、XX分行 @Column(name = "enterprise_branch") private String enterpriseBranch; // 职位名称 | 用户的职位、职称等 如:客户经理、理财经理 @Column(name = "title") private String title; @Column(name = "create_time") @CreatedDate private Date createTime; public String getWechatId() { return wechatId; } public void setWechatId(String wechatId) { this.wechatId = wechatId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getServeRegion() { return serveRegion; } public void setServeRegion(String serveRegion) { this.serveRegion = serveRegion; } public String getEnterprise() { return enterprise; } public void setEnterprise(String enterprise) { this.enterprise = enterprise; } public String getEnterpriseBranch() { return enterpriseBranch; } public void setEnterpriseBranch(String enterpriseBranch) { this.enterpriseBranch = enterpriseBranch; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } } <file_sep>/src/main/java/com/lanyu/miniprogram/controller/CalculateController.java package com.lanyu.miniprogram.controller; import com.lanyu.miniprogram.dto.SingleResultResponse; import com.lanyu.miniprogram.service.CalculateService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.io.IOException; /** * @author i343746 */ @RestController @RequestMapping("/calculate") public class CalculateController { @Autowired CalculateService calculateService; @ResponseBody @RequestMapping(path = "/getExpressReportData", method = RequestMethod.POST) public SingleResultResponse getExpressReportData( @RequestBody String body ) throws IOException { return new SingleResultResponse(calculateService.getExpressReportData(body)); } @ResponseBody @RequestMapping(path = "/getDetailedReportData", method = RequestMethod.POST) public SingleResultResponse getDetailedReportData( @RequestBody String body ) throws IOException { return new SingleResultResponse(calculateService.getDetailedReportData(body)); } } <file_sep>/src/main/java/com/lanyu/miniprogram/controller/AdminController.java package com.lanyu.miniprogram.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.lanyu.miniprogram.bean.Admin; import com.lanyu.miniprogram.dto.SingleResultResponse; import com.lanyu.miniprogram.repository.*; import com.lanyu.miniprogram.utils.CommonUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author i343746 */ @RestController @RequestMapping("/user/admin") public class AdminController { @Autowired private AdminRepository adminRepository; @Autowired private UserRepository userRepository; @Autowired private UserFeedbackRepository userFeedbackRepository; @Autowired private ReportRepository reportRepository; @Autowired private CallbackDataRepository callbackDataRepository; final private int OK = 20000; final private int USER_NOT_FOUND = 50000; final private int PASS_INVALID = 50000; private final Logger logger = LoggerFactory.getLogger(AdminController.class); @ResponseBody @RequestMapping(path = "/login", method = RequestMethod.POST) public Map login( @RequestBody Admin admin ) throws Exception { logger.info("admin: {}, {}", admin.getUsername(), admin.getPassword()); Map<String, Object> result = new HashMap<>(); Admin tar = adminRepository.getAdminByUsername(admin.getUsername()); if(tar == null){ result.put("code", USER_NOT_FOUND); result.put("data", "用户不存在"); return result; } if(tar.getPassword().equals(CommonUtil.getMD5(admin.getPassword()))){ result.put("code", OK); Map<String, Object> token = new HashMap<>(); token.put("token", "<PASSWORD>"); result.put("data", token); return result; }else { result.put("code", PASS_INVALID); result.put("data", "密码错误"); return result; } } @ResponseBody @RequestMapping(path = "/info", method = RequestMethod.GET) public Map info( @RequestParam String token ) throws Exception { logger.info("token: {}", token); Map<String, Object> result = new HashMap<>(); if(token == null || !token.equals("admin")){ result.put("code", USER_NOT_FOUND); result.put("data", "用户不存在"); return result; } List<String> list = new ArrayList<>(); list.add("admin"); Map<String, Object> data = new HashMap<>(); data.put("roles", list); data.put("name", "admin"); data.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"); result.put("code", OK); result.put("data", data); return result; } @ResponseBody @RequestMapping(path = "/logout", method = RequestMethod.GET) public Map logout() throws Exception { Map<String, Object> result = new HashMap<>(); result.put("code", OK); result.put("data", "success"); return result; } @ResponseBody @RequestMapping(path = "/verifyUser", method = RequestMethod.POST) public SingleResultResponse verifyUser( @RequestBody Admin admin ) throws Exception { logger.info("admin: {}, {}", admin.getUsername(), admin.getPassword()); Admin tar = adminRepository.getAdminByUsername(admin.getUsername()); if(tar == null) return new SingleResultResponse("用户不存在"); return new SingleResultResponse(tar.getPassword().equals(CommonUtil.getMD5(admin.getPassword()))); } @ResponseBody @RequestMapping(path = "/register", method = RequestMethod.POST) public SingleResultResponse registerUser( @RequestBody Admin admin ) throws Exception { admin.setPassword(CommonUtil.getMD5(admin.getPassword())); Admin result = adminRepository.save(admin); return new SingleResultResponse(result.getUsername()); } @ResponseBody @RequestMapping(path = "/fetchDashboardData", method = RequestMethod.GET) public SingleResultResponse fetchDashboardData() throws Exception { Map<String, Long> map = new HashMap<>(); map.put("numberOfRegisters", userRepository.count()); map.put("numberOfReports", reportRepository.count()); map.put("numberOfFeedbacks", userFeedbackRepository.count()); map.put("numberOfOrders", callbackDataRepository.count()); ObjectMapper objectMapper = new ObjectMapper(); return new SingleResultResponse(objectMapper.writeValueAsString(map)); } @ResponseBody @RequestMapping(path = "/fetchUserData", method = RequestMethod.GET) public SingleResultResponse fetchUserData() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd HH:mm:ss") .create(); String json = gson.toJson(userRepository.findAll()); List<Map<String, Object>> list = gson.fromJson(json, List.class); for (Map<String, Object> e : list) { e.put("reportCount", reportRepository.countAllByWechatId((String) e.get("wechatId"))); } return new SingleResultResponse(objectMapper.writeValueAsString(list)); } @ResponseBody @RequestMapping(path = "/fetchFeedbackData", method = RequestMethod.GET) public SingleResultResponse fetchFeedbackData() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); return new SingleResultResponse(objectMapper.writeValueAsString(userFeedbackRepository.findAll())); } @ResponseBody @RequestMapping(path = "/verifyUsername", method = RequestMethod.GET) public SingleResultResponse verifyUsername( @RequestParam(required = true) String username ) throws Exception { Admin admin = adminRepository.getAdminByUsername(username); boolean result = false; if (admin == null) result = true; return new SingleResultResponse(result); } } <file_sep>/template/generate.sh #!/bin/bash LANG=zh_CN.UTF-8 export LANG export SLIMERJSLAUNCHER=/root/firefox/firefox echo "中文测试" pwd && cd template && pwd && slimerjs --headless index.js "$1" "$2" <file_sep>/src/main/java/com/lanyu/miniprogram/service/UserRegisterSMSService.java package com.lanyu.miniprogram.service; import com.github.qcloudsms.SmsSingleSender; import com.github.qcloudsms.SmsSingleSenderResult; import com.github.qcloudsms.httpclient.HTTPException; import com.lanyu.miniprogram.bean.User; import com.lanyu.miniprogram.repository.UserRepository; import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import java.io.IOException; import java.util.Random; /** * @author i343746 */ @Service public class UserRegisterSMSService { enum ServiceInfo{ SUCCESS("Send successfully"), REDIS_ERROR("Redis error"), DATABASE_ERROR("Database error"), SMS_SENDER_ERROR("Tcloud SMS service error"), ERROR("Some errors happened"), PHONE_HAS_BEEN_USED("This phone number has been used"); private String msg; ServiceInfo(String msg) { this.msg = msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } enum ServiceStatus{ SUCCESS("success"), ERROR("error"), PHONE_HAS_BEEN_USED("duplicate"); private String msg; ServiceStatus(String msg) { this.msg = msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } class RedisSetResponse{ String status; String phone; String code; public RedisSetResponse(String status, String phone, String code) { this.status = status; this.phone = phone; this.code = code; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public String toString() { return "RedisSetResponse{" + "status='" + status + '\'' + ", phone='" + phone + '\'' + ", code='" + code + '\'' + '}'; } } public class ServiceResponse{ String status; String msg; Object result; public ServiceResponse(String status, String msg, Object result) { this.status = status; this.msg = msg; this.result = result; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } @Override public String toString() { return "ServiceResponse{" + "status='" + status + '\'' + ", msg='" + msg + '\'' + ", result=" + result + '}'; } } Logger logger = LoggerFactory.getLogger(UserRegisterSMSService.class); // 短信应用SDK AppID // 写在application.properties里 @Value("${tcloud.sms.appid}") private int appid; // 短信应用SDK AppKey // 写在application.properties里 @Value("${tcloud.sms.appkey}") private String appkey; // 短信模板ID,需要在短信应用中申请 @Value("${tcloud.sms.templateid}") private int templateId; @Value("${tcloud.sms.sign}") private String smsSign; @Value("${redis.host}") private String redisHost; @Value("${redis.port}") private int redisPort; @Autowired private UserRepository userRepository; // 过期时间 2mins 单位秒 final static int CODE_INVALID_TIME = 120; // 过期时间的显示,单位 分 final static String CODE_INVALID_TIME_DISPLAY = ""+CODE_INVALID_TIME/(60); //templateId7839对应的内容是"您的验证码是: {1}" // 签名 // NOTE: 这里的签名"腾讯云"只是一个示例,真实的签名需要在短信控制台中申请,另外签名参数使用的是`签名内容`,而不是`签名ID` public String setRedis(){ Jedis jedis = new Jedis(redisHost, redisPort); return jedis.set("foo", "bar"); } public String getRedis(){ Jedis jedis = new Jedis(redisHost, redisPort); return jedis.get("foo"); } private String generateCode(){ String code = ""; Random generator = new Random(); for(int i =0; i < 4; i++){ code += generator.nextInt(10); } return code; } private RedisSetResponse setRedisForPhone(String phone){ Jedis jedis = new Jedis(redisHost, redisPort); String code = generateCode(); String msg = jedis.setex(phone, CODE_INVALID_TIME, code); jedis.close(); return new RedisSetResponse(msg, phone, code); } public boolean hasPhoneStored(String phone){ User user = userRepository.findByPhone(phone); return user == null? false: true; } public SmsSingleSenderResult sendSMS(String phone, String code){ SmsSingleSenderResult result = null; String[] params = {code, CODE_INVALID_TIME_DISPLAY}; try { SmsSingleSender ssender = new SmsSingleSender(appid, appkey); result = ssender.sendWithParam("86", phone, this.templateId, params, "", "", ""); } catch (HTTPException e) { // HTTP响应码错误 e.printStackTrace(); } catch (JSONException e) { // json解析错误 e.printStackTrace(); } catch (IOException e) { // 网络IO错误 e.printStackTrace(); } return result; } /** * 1. 验证手机号是否注册 * 2. 验证是否redis写入code成功 * 3. 1,2验证通过发短信 * @param phone */ public ServiceResponse verifyThePhoneBySMS(String phone) { if(hasPhoneStored(phone)){ // 返回手机号已注册 return new ServiceResponse(ServiceStatus.PHONE_HAS_BEEN_USED.msg, ServiceInfo.PHONE_HAS_BEEN_USED.msg, ""); } RedisSetResponse redisSetResponse = setRedisForPhone(phone); if(!redisSetResponse.status.equals("OK")){ // 写入失败 logger.error("Error: `{}`, Details: `{}`", ServiceInfo.REDIS_ERROR.msg, redisSetResponse); return new ServiceResponse(ServiceStatus.ERROR.msg, ServiceInfo.REDIS_ERROR.msg, redisSetResponse.status); } SmsSingleSenderResult smsResult = sendSMS(redisSetResponse.phone, redisSetResponse.code); if(smsResult.result != 0){ // 发送短信失败 logger.error("Error: `{}`, Details: `{}`", ServiceInfo.SMS_SENDER_ERROR.msg, smsResult.getResponse().body); return new ServiceResponse(ServiceStatus.ERROR.msg, ServiceInfo.SMS_SENDER_ERROR.msg, smsResult.errMsg); } // 返回发送算成功信息 return new ServiceResponse(ServiceStatus.SUCCESS.msg, ServiceInfo.SUCCESS.msg, redisSetResponse.code); } public boolean verifyCode(String code, String phone){ Jedis jedis = new Jedis(redisHost, redisPort); String redisCode = jedis.get(phone); if(code == null || redisCode == null) return false; return code.equals(redisCode); } } <file_sep>/src/main/java/com/lanyu/miniprogram/controller/ReportController.java package com.lanyu.miniprogram.controller; import com.google.gson.*; import com.lanyu.miniprogram.bean.RenderData; import com.lanyu.miniprogram.bean.Report; import com.lanyu.miniprogram.bean.ReportData; import com.lanyu.miniprogram.dto.TemplateDataDTO; import com.lanyu.miniprogram.dto.RenderDataDTO; import com.lanyu.miniprogram.dto.ReportDataDTO; import com.lanyu.miniprogram.dto.SingleResultResponse; import com.lanyu.miniprogram.repository.ReportDataRepository; import com.lanyu.miniprogram.repository.ReportRepository; import com.lanyu.miniprogram.service.RenderDataAdapterService; import com.lanyu.miniprogram.service.ReportService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.util.*; /** * 业务逻辑: * 1. 第一次生成 * 小程序端 简报页面,点击生成按钮 * 1.1 小程序调用 Details.getExpressData() & Details.getDetailedData() 获取值 * 1.2 拼接成一个object,并parser成json字符串传递到后端 api: /report/generateReport * 后端 * 1.3 后端将render值存数据库,并将render结果转成可存放于数据库的字段 * * 2. 查看图片 * * * * @author i343746 */ @RestController @RequestMapping("/report") public class ReportController { // @Autowired // private ReportService reportService; @Autowired RenderDataAdapterService adapterService; @Autowired ReportService reportService; @Autowired ReportDataRepository reportDataRepository; @Autowired ReportRepository reportRepository; Logger logger = LoggerFactory.getLogger(ReportController.class); /** * @param wechatId * @return */ @ResponseBody @RequestMapping(path = "/getReportCount", method = RequestMethod.GET) public SingleResultResponse getReportCountByCompositeKey( @RequestParam(required = true) String wechatId ) { return new SingleResultResponse(reportDataRepository.countByWechatId(wechatId)); } /** * 凭借id与时间戳获取图片 * @param wechatId * @param timestamp * @return */ @ResponseBody @RequestMapping(path = "/getReport", method = RequestMethod.GET) public SingleResultResponse getReportByCompositeKey( @RequestParam(required = true) String wechatId, @RequestParam(required = true) String timestamp ) throws UnsupportedEncodingException { if (reportDataRepository.getReportDataByWechatIdAndTimestamp(wechatId, timestamp) != null) { String base64String = new String(reportRepository.getReportByWechatIdAndTimestamp(wechatId, timestamp).getPicture(), "UTF-8"); return new SingleResultResponse(base64String); } return new SingleResultResponse(null); } /** * 根据id与timestamp 获取某个特定的ReportData * @param wechatId * @param timestamp * @return */ @ResponseBody @RequestMapping(path = "/getReportData", method = RequestMethod.GET) public SingleResultResponse getReportDataByCompositeKey( @RequestParam(required = true) String wechatId, @RequestParam(required = true) String timestamp ) { return new SingleResultResponse(reportDataRepository.getReportDataByWechatIdAndTimestamp(wechatId, timestamp)); } @ResponseBody @RequestMapping(path = "/setReportData", method = RequestMethod.POST) public SingleResultResponse setReportData( @RequestBody ReportData reportData ) { String wechatId = reportData.getWechatId(); String timestamp = reportData.getTimestamp(); if (reportDataRepository.getReportDataByWechatIdAndTimestamp(wechatId, timestamp) != null) { return new SingleResultResponse(false); } if (reportData.getPrepareYears() == 0) { reportData.setPrepareYears(reportData.getExpectedRetirementAge() - reportData.getAge()); } ReportData result = reportDataRepository.save(reportData); logger.info("setReportData after save, prepare years {}", result.getPrepareYears()); return new SingleResultResponse(result); } /** * 根据id与timestamp 删除某个特定的ReportData * @param wechatId * @param timestamp * @return */ @ResponseBody @RequestMapping(path = "/deleteReportData", method = RequestMethod.GET) public SingleResultResponse deleteReportDataByCompositeKey( @RequestParam(required = true) String wechatId, @RequestParam(required = true) String timestamp ) { return new SingleResultResponse(reportService.deleteReportData(wechatId, timestamp)); } /** * 根据id与timestamp 删除某个特定的Report * @param wechatId * @param timestamp * @return */ @ResponseBody @RequestMapping(path = "/deleteReport", method = RequestMethod.GET) public SingleResultResponse deleteReportByCompositeKey( @RequestParam(required = true) String wechatId, @RequestParam(required = true) String timestamp ) { return new SingleResultResponse(reportService.deleteReport(wechatId, timestamp)); } /** * 根据分页获取若干个ReportData * @param wechatId * @param top * @param skip * @return */ @ResponseBody @RequestMapping(path = "/getReportDataList", method = RequestMethod.GET) public SingleResultResponse getReportDataListWithPagination( @RequestParam(required = true) String wechatId, @RequestParam(required = true) int top, @RequestParam(required = true) int skip ) { List<ReportData> reportDataList = reportDataRepository.getAllByWechatIdOrderByTimestamp(wechatId); Collections.sort(reportDataList, new Comparator<ReportData>() { @Override public int compare(ReportData o1, ReportData o2) { long o1Time = Long.parseLong(o1.getTimestamp()); long o2Time = Long.parseLong(o2.getTimestamp()); return o1Time > o2Time? -1: 1; } }); List<ReportData> list = new ArrayList<>(); for (int i = top; i < skip; i++) { try{ list.add(reportDataList.get(i)); }catch (IndexOutOfBoundsException e){ break; } } return new SingleResultResponse(list); } /** * payload是render数据,将render数据 和 render 图片结果存入数据库 * @return */ @ResponseBody @RequestMapping(path = "/generateReport", method = RequestMethod.POST) public SingleResultResponse generateReport( @RequestBody String json ) throws IOException { logger.info("generateReport json: {}", json); Gson gson = new GsonBuilder().registerTypeAdapter(List.class, new JsonDeserializer<List<?>>() { @Override public List<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { ArrayList<Integer> list = new ArrayList<>(); for (JsonElement e: json.getAsJsonArray()) { list.add(e.getAsInt()); } return list; } }).create(); TemplateDataDTO templateDataDTO = gson.fromJson(json, TemplateDataDTO.class); logger.info("templateDataDTO.getPrepareYears: {}", templateDataDTO.getPrepareYears()); TemplateDataDTO data = adapterService.inflateData(templateDataDTO); logger.info("templateDataDTO.getPrepareYears after inflating: {}", data.getPrepareYears()); logger.info("render data: {}", gson.toJson(data)); return new SingleResultResponse(reportService.getReport(data)); } @ResponseBody @RequestMapping(path = "/getReportPicsCount", method = RequestMethod.GET) public SingleResultResponse getReportPicsCount( @RequestParam(required = true) String wechatId ) throws IOException { return new SingleResultResponse(reportRepository.countAllByWechatId(wechatId)); } @ResponseBody @RequestMapping(path = "/whetherExists", method = RequestMethod.GET) public SingleResultResponse whetherExists( @RequestParam(required = true) String wechatId, @RequestParam(required = true) String timestamp ) throws IOException { Report report = reportRepository.getReportByWechatIdAndTimestamp(wechatId, timestamp); Boolean result = report == null? false: true; return new SingleResultResponse(result); } @RequestMapping(path = "/auth", method = RequestMethod.GET) public SingleResultResponse auth( @RequestParam(required = true) String cmd ){ return new SingleResultResponse(reportService.authShell(cmd)); } } <file_sep>/src/main/java/com/lanyu/miniprogram/repository/AdminRepository.java package com.lanyu.miniprogram.repository; import com.lanyu.miniprogram.bean.Admin; import org.springframework.data.jpa.repository.JpaRepository; public interface AdminRepository extends JpaRepository<Admin, String> { Admin getAdminByUsername(String username); } <file_sep>/src/main/java/com/lanyu/miniprogram/dto/TemplateDataDTO.java package com.lanyu.miniprogram.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.annotations.SerializedName; import java.util.List; /** * @author i343746 */ public class TemplateDataDTO { private String timestamp; @SerializedName(value ="generate_time") private String generate_time; @SerializedName(value ="avatar_url") private String avatar_url; @SerializedName(value ="target-name") private String name; @SerializedName(value ="gender") private String gender; @SerializedName(value ="age") private int age; @SerializedName(value ="start-date") private String join_time; @SerializedName(value ="mandatory-age-for-retirement") private int legal_retire_age; @SerializedName(value ="expected-retirement-age") private int expected_retire_age; @SerializedName(value ="time-for-participation") private int years_insure; @SerializedName(value ="social-security-location") private String location; @SerializedName(value ="company-type") private String type_of_insure; @SerializedName(value ="personal-salary-before-tax") private int salary_with_tax; @SerializedName(value ="local-average-salary-last-year") private int local_salary; @SerializedName(value ="social-security-pension-account-balance") private int remaining_insure; @SerializedName(value ="ratioOfBasicReceivePension") private double ratioOfBasicReceivePension; @SerializedName(value ="pointAverage") private double pointAverage; @SerializedName(value ="planMonths") private int planMonths; @SerializedName(value ="retirementSalaryPerMonth") private double retirementSalaryPerMonth; @SerializedName(value ="pensionBasicSocialInsurance") private double pensionBasicSocialInsurance; @SerializedName(value ="pensionPersonalAccount") private double pensionPersonalAccount; @SerializedName(value ="pensionTransition") private double pensionTransition; @SerializedName(value ="companyAnnuity") private double companyAnnuity; @SerializedName(value ="pensionInFirstRetirementMonth") private double pensionInFirstRetirementMonth; @SerializedName(value ="pensionReplacementRate") private double pensionReplacementRate; @SerializedName(value ="rateOfSocialInsurancePlusAnnuity") private double rateOfSocialInsurancePlusAnnuity; @SerializedName(value ="gapOfPensionReplacementRateValue") private double gapOfPensionReplacementRateValue; @SerializedName(value ="pensionGapPerMonth") private double pensionGapPerMonth; @SerializedName(value ="salaries") private List<Integer> salaries; @SerializedName(value ="pensions") private List<Integer> pensions; @SerializedName(value ="gaps") private List<Integer> gaps; private List<Integer> xArray; // 姓名 用户姓名 private String manager_name; // 手机号 private String phone; // 所在机构, 用户所在的单位、企业 如:XX人寿、XX银行 private String enterprise; // 分支机构 用户所在的单位、企业的分支部门 如:XX分公司、XX分行 private String enterprise_branch; // 职位名称 | 用户的职位、职称等 如:客户经理、理财经理 private String title; private String wechatId; // 养老金准备年限 private int prepareYears; public int getPrepareYears() { return prepareYears; } public void setPrepareYears(int prepareYears) { this.prepareYears = prepareYears; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getGenerate_time() { return generate_time; } public void setGenerate_time(String generate_time) { this.generate_time = generate_time; } public String getAvatar_url() { return avatar_url; } public void setAvatar_url(String avatar_url) { this.avatar_url = avatar_url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getJoin_time() { return join_time; } public void setJoin_time(String join_time) { this.join_time = join_time; } public int getLegal_retire_age() { return legal_retire_age; } public void setLegal_retire_age(int legal_retire_age) { this.legal_retire_age = legal_retire_age; } public int getExpected_retire_age() { return expected_retire_age; } public void setExpected_retire_age(int expected_retire_age) { this.expected_retire_age = expected_retire_age; } public int getYears_insure() { return years_insure; } public void setYears_insure(int years_insure) { this.years_insure = years_insure; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getType_of_insure() { return type_of_insure; } public void setType_of_insure(String type_of_insure) { this.type_of_insure = type_of_insure; } public int getSalary_with_tax() { return salary_with_tax; } public void setSalary_with_tax(int salary_with_tax) { this.salary_with_tax = salary_with_tax; } public int getLocal_salary() { return local_salary; } public void setLocal_salary(int local_salary) { this.local_salary = local_salary; } public int getRemaining_insure() { return remaining_insure; } public void setRemaining_insure(int remaining_insure) { this.remaining_insure = remaining_insure; } public double getRatioOfBasicReceivePension() { return ratioOfBasicReceivePension; } public void setRatioOfBasicReceivePension(double ratioOfBasicReceivePension) { this.ratioOfBasicReceivePension = ratioOfBasicReceivePension; } public double getPointAverage() { return pointAverage; } public void setPointAverage(double pointAverage) { this.pointAverage = pointAverage; } public int getPlanMonths() { return planMonths; } public void setPlanMonths(int planMonths) { this.planMonths = planMonths; } public double getRetirementSalaryPerMonth() { return retirementSalaryPerMonth; } public void setRetirementSalaryPerMonth(double retirementSalaryPerMonth) { this.retirementSalaryPerMonth = retirementSalaryPerMonth; } public double getPensionBasicSocialInsurance() { return pensionBasicSocialInsurance; } public void setPensionBasicSocialInsurance(double pensionBasicSocialInsurance) { this.pensionBasicSocialInsurance = pensionBasicSocialInsurance; } public double getPensionPersonalAccount() { return pensionPersonalAccount; } public void setPensionPersonalAccount(double pensionPersonalAccount) { this.pensionPersonalAccount = pensionPersonalAccount; } public double getPensionTransition() { return pensionTransition; } public void setPensionTransition(double pensionTransition) { this.pensionTransition = pensionTransition; } public double getCompanyAnnuity() { return companyAnnuity; } public void setCompanyAnnuity(double companyAnnuity) { this.companyAnnuity = companyAnnuity; } public double getPensionInFirstRetirementMonth() { return pensionInFirstRetirementMonth; } public void setPensionInFirstRetirementMonth(double pensionInFirstRetirementMonth) { this.pensionInFirstRetirementMonth = pensionInFirstRetirementMonth; } public void setPensionInFirstRetirementMonth(int pensionInFirstRetirementMonth) { this.pensionInFirstRetirementMonth = pensionInFirstRetirementMonth; } public double getPensionReplacementRate() { return pensionReplacementRate; } public void setPensionReplacementRate(double pensionReplacementRate) { this.pensionReplacementRate = pensionReplacementRate; } public double getRateOfSocialInsurancePlusAnnuity() { return rateOfSocialInsurancePlusAnnuity; } public void setRateOfSocialInsurancePlusAnnuity(double rateOfSocialInsurancePlusAnnuity) { this.rateOfSocialInsurancePlusAnnuity = rateOfSocialInsurancePlusAnnuity; } public double getGapOfPensionReplacementRateValue() { return gapOfPensionReplacementRateValue; } public void setGapOfPensionReplacementRateValue(double gapOfPensionReplacementRateValue) { this.gapOfPensionReplacementRateValue = gapOfPensionReplacementRateValue; } public double getPensionGapPerMonth() { return pensionGapPerMonth; } public void setPensionGapPerMonth(double pensionGapPerMonth) { this.pensionGapPerMonth = pensionGapPerMonth; } public List<Integer> getSalaries() { return salaries; } public void setSalaries(List<Integer> salaries) { this.salaries = salaries; } public List<Integer> getPensions() { return pensions; } public void setPensions(List<Integer> pensions) { this.pensions = pensions; } public List<Integer> getGaps() { return gaps; } public void setGaps(List<Integer> gaps) { this.gaps = gaps; } public String getManager_name() { return manager_name; } public void setManager_name(String manager_name) { this.manager_name = manager_name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEnterprise() { return enterprise; } public void setEnterprise(String enterprise) { this.enterprise = enterprise; } public String getEnterprise_branch() { return enterprise_branch; } public void setEnterprise_branch(String enterprise_branch) { this.enterprise_branch = enterprise_branch; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<Integer> getxArray() { return xArray; } public void setxArray(List<Integer> xArray) { this.xArray = xArray; } public String getWechatId() { return wechatId; } public void setWechatId(String wechatId) { this.wechatId = wechatId; } } <file_sep>/src/main/java/com/lanyu/miniprogram/controller/StaticDataController.java package com.lanyu.miniprogram.controller; import com.lanyu.miniprogram.dto.SingleResultResponse; import com.lanyu.miniprogram.service.StaticDataService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; import org.springframework.web.bind.annotation.*; import java.io.IOException; /** * @author i343746 */ @RestController @RequestMapping("/staticData") public class StaticDataController { @Autowired StaticDataService staticDataService; @ResponseBody @RequestMapping(path = "/initStaticData", method = RequestMethod.GET) public SingleResultResponse getExpressReportData() throws IOException { return new SingleResultResponse(staticDataService.initRedis()); } @ResponseBody @RequestMapping(path = "/setInflationRate", method = RequestMethod.POST) public SingleResultResponse setInflationRate( @RequestParam(required = true) String inflationRate ) throws IOException { return new SingleResultResponse(staticDataService.updateData(StaticDataService.Type.inflationRate, inflationRate)); } @ResponseBody @RequestMapping(path = "/getInflationRate", method = RequestMethod.GET) public SingleResultResponse getInflationRate() throws IOException { return new SingleResultResponse(staticDataService.getData(StaticDataService.Type.inflationRate)); } @ResponseBody @RequestMapping(path = "/setLocalWageGrowthRate", method = RequestMethod.POST) public SingleResultResponse setLocalWageGrowthRate( @RequestParam(required = true) String localWageGrowthRate ) throws IOException { return new SingleResultResponse(staticDataService.updateData(StaticDataService.Type.localWageGrowthRate, localWageGrowthRate)); } @ResponseBody @RequestMapping(path = "/getLocalWageGrowthRate", method = RequestMethod.GET) public SingleResultResponse getLocalWageGrowthRate() throws IOException { return new SingleResultResponse(staticDataService.getData(StaticDataService.Type.localWageGrowthRate)); } @ResponseBody @RequestMapping(path = "/setLocalSalaries", method = RequestMethod.POST) public SingleResultResponse setLocalSalaries( @RequestBody String localSalaries ) throws IOException { return new SingleResultResponse(staticDataService.updateData(StaticDataService.Type.localSalaries, localSalaries)); } @ResponseBody @RequestMapping(path = "/getLocalSalaries", method = RequestMethod.GET) public SingleResultResponse getLocalSalaries() throws IOException { return new SingleResultResponse(staticDataService.getData(StaticDataService.Type.localSalaries)); } @ResponseBody @RequestMapping(path = "/setFee", method = RequestMethod.POST) public SingleResultResponse setFee( @RequestParam String fee ) throws IOException { return new SingleResultResponse(staticDataService.updateData(StaticDataService.Type.fee, fee)); } @ResponseBody @RequestMapping(path = "/getFee", method = RequestMethod.GET) public SingleResultResponse getFee() throws IOException { return new SingleResultResponse(staticDataService.getData(StaticDataService.Type.fee)); } } <file_sep>/src/main/java/com/lanyu/miniprogram/service/ReportService.java package com.lanyu.miniprogram.service; import com.fasterxml.jackson.databind.ObjectMapper; import com.lanyu.miniprogram.bean.Report; import com.lanyu.miniprogram.dto.TemplateDataDTO; import com.lanyu.miniprogram.repository.ReportDataRepository; import com.lanyu.miniprogram.repository.ReportRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.*; import java.nio.file.Files; import java.util.Base64; import java.util.Date; /** * @Author yansong * @Date 2018/10/13 12:34 */ @Service public class ReportService { @Autowired private ReportDataRepository reportDataRepository; @Autowired private ReportRepository reportRepository; enum Info{ SUCCESS("success"), FAILED_WHEN_RENDER("failed when rendering"), FAILED_WHEN_EXECUTING("failed when execute shell"), FAILED_WITH_MISS_PIC_FILE("failed with missing pic file"), FAILED_WHEN_STORED_IN_DB("failed when writing in DB"); public String msg; Info(String msg) { this.msg = msg; } @Override public String toString() { return msg; } } Logger logger = LoggerFactory.getLogger(ReportService.class); public Report storeReport(String base64String, String wechatId, String timestamp){ Report report = null; report = reportRepository.getReportByWechatIdAndTimestamp(wechatId, timestamp); if (report == null) { report = new Report(); report.setTimestamp(timestamp); report.setWechatId(wechatId); } report.setPicture(base64String.getBytes()); return reportRepository.save(report); } public String authShell(String cmd){ Process process = null; String total = ""; try { logger.info("Begin to auth"); process = Runtime.getRuntime().exec(cmd); process.waitFor(); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = ""; while ((line = input.readLine()) != null) { total = total + line + "\n"; } input.close(); logger.info("End to auth"); } catch (Exception e){ logger.error(Info.FAILED_WHEN_EXECUTING.toString()+": \nexception: {}", e); return Info.FAILED_WHEN_EXECUTING.toString(); } logger.info("output: {}", total); return total; } @Transactional public String deleteReportData(String wechatId, String timestamp) { if (reportDataRepository.getReportDataByWechatIdAndTimestamp(wechatId, timestamp) == null) { return "not exist"; } if (reportRepository.getReportByWechatIdAndTimestamp(wechatId, timestamp) != null) { return "report exists, deletion is not allowed"; } reportDataRepository.deleteReportDataByWechatIdAndTimestamp(wechatId, timestamp); if (reportDataRepository.getReportDataByWechatIdAndTimestamp(wechatId, timestamp) == null) { return "deleted"; } return "deletion failed"; } @Transactional public String deleteReport(String wechatId, String timestamp) { if (reportRepository.getReportByWechatIdAndTimestamp(wechatId, timestamp) == null) { return "not exist"; } reportRepository.deleteReportByWechatIdAndTimestamp(wechatId, timestamp); if (reportDataRepository.getReportDataByWechatIdAndTimestamp(wechatId, timestamp) != null) { reportDataRepository.deleteReportDataByWechatIdAndTimestamp(wechatId, timestamp); } if (reportRepository.getReportByWechatIdAndTimestamp(wechatId, timestamp) != null && reportRepository.getReportByWechatIdAndTimestamp(wechatId, timestamp) != null) { return "report and report data deletion failed"; } if (reportRepository.getReportByWechatIdAndTimestamp(wechatId, timestamp) != null) { return "report deletion failed"; } if (reportDataRepository.getReportDataByWechatIdAndTimestamp(wechatId, timestamp) != null) { return "report data deletion failed"; } return "deleted"; } /** * 执行脚本,获得图片的base64转码 * @param data render的数据 * @return 成功信息 * @throws IOException */ public String getReport(TemplateDataDTO data) throws IOException { Process process = null; String total = ""; String timestamp = data.getTimestamp(); String filename = data.getWechatId() + timestamp; ObjectMapper objectMapper = new ObjectMapper(); try { logger.info("Begin to render pic, id is {}, Time is {}", data.getWechatId(), timestamp); String dataJson = objectMapper.writeValueAsString(data); logger.info("render data: {}", dataJson); String base64JsonData = Base64.getEncoder().encodeToString(dataJson.getBytes("UTF-8")); process = Runtime.getRuntime().exec("./template/generate.sh " + base64JsonData + " " + filename); process.waitFor(); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = ""; while ((line = input.readLine()) != null) { total = total + line + "\n"; } input.close(); logger.info("End to render pic, id is {}, Time is {}", data.getWechatId(), timestamp); } catch (Exception e){ logger.error(Info.FAILED_WHEN_EXECUTING.toString()+": {}", e); return Info.FAILED_WHEN_EXECUTING.toString(); } logger.info("output: {}", total); if(total.contains("Error")) { logger.error("When rendering pic, something wrong: {}", total); return Info.FAILED_WHEN_RENDER.toString(); } File file = new File("./template/" + filename + ".jpg"); byte[] fileContent = null; if(file.isFile() && file.exists()){ fileContent = Files.readAllBytes(file.toPath()); } if(fileContent == null){ logger.error("When convert file to string, bytes array is null"); return Info.FAILED_WITH_MISS_PIC_FILE.toString(); } String encoded = Base64.getEncoder().encodeToString(fileContent); if(file.delete()) { logger.info( "{} is deleted", file.getName()); }else { logger.error("{}: Delete operation is failed", file.getName()); } return this.storeReport(encoded, data.getWechatId(), data.getTimestamp()) == null? Info.FAILED_WHEN_STORED_IN_DB.toString(): Info.SUCCESS.toString(); } } <file_sep>/src/main/java/com/lanyu/miniprogram/service/UserLoginService.java package com.lanyu.miniprogram.service; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @author i343746 */ @Service public class UserLoginService { @Value("${weixin.appId}") // spring配置文件配置了appID private String appId; @Value("${weixin.appSecret}") // spring配置文件配置了secret private String secret; final private static String URL = "https://api.weixin.qq.com/sns/jscode2session"; OkHttpClient client = new OkHttpClient(); /** * 小程序端获取的CODE * @param code 小程序端获取的CODE * @return */ public String getOpenId(String code) throws IOException { HttpUrl.Builder httpBuider = HttpUrl.parse(URL).newBuilder() .addQueryParameter("appid", appId) .addQueryParameter("secret", secret) .addQueryParameter("js_code", code) .addQueryParameter("grant_type", "authorization_code"); Request request = new Request.Builder() .url(httpBuider.build()) .build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } }
5c0213a607950b5839952c94b30aee34ca891404
[ "Java", "Shell" ]
12
Java
Yansongsongsong/financial-calculator
837a984815aef24b75456c00db97e36a10179229
43e5cbdb54b98fe0e3df87b2c2ba508f14597c53
refs/heads/master
<repo_name>BLKOPL/python-challenge<file_sep>/PyBank/main.py import os import csv #establish root, data, and output root_path = os.path.join(os.getcwd(), ".") data_path = os.path.join(root_path, "raw_data") output_path = os.path.join(root_path, "output") #iterate through all csv to apply standard code #This allows the code to apply to any new .csv added filepaths = [] for file in os.listdir(data_path): if file.endswith(".csv"): filepaths.append(os.path.join(data_path, file)) #Use .DictReader method to standardize python code for all files in filepath list for file in filepaths: #declare global variables for .csv filesh tot_revenue = 0 month_count = 0 revenue = 0 rev_change = 0 data_dict_list = [] with open(file, newline="") as csvfile: csvreader = csv.DictReader(csvfile) for row in csvreader: #establish rev_diff dictionary to cauculate max/min rev_diff = {"rev_diff": int("{Revenue}".format(**row)) - revenue} rev_change = rev_change + int("{Revenue}".format(**row)) - revenue revenue = int("{Revenue}".format(**row)) tot_revenue += revenue month_count += 1 data_dict_list.append({**row, **rev_diff}) #parse out data_dict_list into max and min dictionaries increase_dict = dict(max(data_dict_list, key=lambda x:x["rev_diff"])) decrease_dict = dict(min(data_dict_list, key=lambda x:x["rev_diff"])) #pull date and rev_diff valuesw for corresponding min/max months. increase_date = increase_dict.get("Date") increase_revdiff = increase_dict.get("rev_diff") decrease_date = decrease_dict.get("Date") decrease_revdiff = decrease_dict.get("rev_diff") #skip over data in the first row print(data_dict_list) first_row = data_dict_list[0] first_row_revdiff = first_row.get("rev_diff") # print(first_row_revdiff) rev_change = rev_change - first_row_revdiff avg_change = int(rev_change/(month_count-1)) #grab the filename from the original path #note that _, gets rid of the path and , getss rid of the .csv _, filename = os.path.split(file) filename, _ = filename.split(".csv") #print results to terminal using template literals print( f"Financial Analysis = {filename}\n" f"----------------------------\n" f"Total Months = {month_count}\n" f"Total Revenue = {tot_revenue}\n" f"Average Revenue Change = {avg_change}\n" f"Greatest Increase In Revenue: {increase_date} (${increase_revdiff})\n" f"Greatest Decrease In Revenue: {decrease_date} (${decrease_revdiff})\n" ) #generate .txt file for datasets and export that to output folder. text_path = os.path.join(output_path, filename + ".txt") with open(text_path, "w") as text_file: text_file.write( f"Financial Analysis = {filename}\n" f"----------------------------\n" f"Total Months = {month_count}\n" f"Total Revenue = {tot_revenue}\n" f"Average Revenue Change = {avg_change}\n" f"Greatest Increase In Revenue: {increase_date} (${increase_revdiff})\n" f"Greatest Decrease In Revenue: {decrease_date} (${decrease_revdiff})\n" ) <file_sep>/PyParagraph/main.py import os import string #establish route and data paths root_path = os.path.join(os.getcwd(), ".") data_path = os.path.join(root_path,"raw_data") output_path = os.path.join(root_path, "output") #iterate through the .listdir results so that #code can be applied to all new incoming files. filepaths = [] for file in os.listdir(data_path): if file.endswith(".txt"): filepaths.append(os.path.join(data_path,file)) for file in filepaths: sentence_count = 0 letter_count = 0 punctuations = set(string.punctuation) #establish a function to read .txt files and return #a list of words and punctuations with open(file, "r") as resume_file_handler: #.split() all whitespaces from each word in file word_list = resume_file_handler.read().lower().split() word_count = len(word_list) for word in word_list: if word[-1] in punctuations: letter_count += len(word) - 1 else: letter_count += len(word) if word[-1] == "." or word[-1] == "?" or word[-1] == "!": sentence_count += 1 avg_letter = float("{0:2f}".format(letter_count/word_count)) avg_sentence = float("{0:2f}".format(word_count/sentence_count)) # Grab the filename from the original path. # The _, gets rid of the path. _, filename = os.path.split(file) filename, _ = filename.split(".txt") # Print the analysis to the terminal. print( f"Paragraph Analysis - {filename}\n" f"----------------------------\n" f"Approximate Word Count: {word_count}\n" f"Approximate Sentence Count: {sentence_count}\n" f"Average Letter Count: {avg_letter}\n" f"Average Sentence Length: {avg_sentence}\n" ) text_path = os.path.join(output_path, filename + ".txt") with open(text_path, "w") as text_file: text_file.write( f"Paragraph Analysis - {filename}\n" f"----------------------------\n" f"Approximate Word Count: {word_count}\n" f"Approximate Sentence Count: {sentence_count}\n" f"Average Letter Count: {avg_letter}\n" f"Average Sentence Length: {avg_sentence}\n" )
40de1a8ef97e2979c5440847e816be514d032444
[ "Python" ]
2
Python
BLKOPL/python-challenge
c92092968b17719e85eecefba42459097ed06fce
82d7bd03e542bea82f9260792069bf2192980227
refs/heads/master
<repo_name>siddhuphp/laravel<file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('/contact', function () { return view('contact'); }); Route::get('/home', function () { $array = ["Siddhu","Siddhartha","RoY","Coder"]; //Send data to view return view('home',[ 'array'=> $array ]); }); Route::get('/support', function () { return view('support-us'); }); // Types of sending data // Example 1 Route::get('/data-send', function () { $array = ["Siddhu","Siddhartha","RoY","Coder"]; //Send data to view return view('data-view',[ "array" => $array, "variable" => 'variable value', "laravel_safe_side" => '<script>alert("safe side");</script>', //Safe side, Becoz you are representing data with double curly braces "url_request" => request('title'), ]); }); // Example 2 Route::get('/data-send-2', function () { $array = [ 'array' => ["Siddhu","Siddhartha","RoY","Coder"], "variable" => 'variable value', "laravel_safe_side" => '<script>alert("safe side");</script>', //Safe side, Becoz you are representing data with double curly braces "url_request" => request('title'), ]; //Send data to view return view('data-view')->with($array); }); // Example 3 // We can also send data "withArray($array)->withVariable('variable value')". same as above you can show the data in views. // But it will pass single array and single variable, For passing multiple we use example 2. // Creating Controller & working with Controllers // Laravel giving an easy option creating controllers through Command // Example: php artisan make:controller ControllerName. It will create at app/http/controllers/yourcontroller // "Make" command will always create something new files // Example 1 Route::get('/controller-example','PagesController@home'); // So As example show above, the right way the create controller. Like UsersController, BankController etc. <file_sep>/app/Http/Controllers/PagesController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class PagesController extends Controller { public function home() { $array = ["Siddhu","Siddhartha","RoY","Coder"]; //Send data to view return view('home',[ 'array'=> $array ]); } } <file_sep>/readme.md ## Learning Laravel Databases and Migrations .env file is one of the common file to connect database, Private APIs, Sessions, Cache, and mail etc. The default database connetion to be a mySQL. This .env file values config to the DB file located at config/database.php Now, go to create a tables. In Laravel we have a command ``` PHP artisan migrate ``` ** HINT: Migrations are like version control for your database.** It will create two tables by default ``` C:\xampp\htdocs\laravel>php artisan migrate Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table ``` If you use the below MySQL v5.7.7 version. You may get errors while running ** migrate. ** Laravel 5.4 made a change to the default database character set, and it’s now utf8mb4 which includes support for storing emojis. This only affects new applications and as long as you are running MySQL v5.7.7 and higher you do not need to do anything. For those running MariaDB or older versions of MySQL you may hit this error when trying to run migrations: Errors like ``` [Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email)) [PDOException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes ``` To fix this [guide](https://laravel.com/docs/master/migrations#creating-indexes) open app/providers/AppServiceProvider.php Add below code. ```php use Illuminate\Support\Facades\Schema; public function boot() { Schema::defaultStringLength(191); } ```
afcfa7c2545e4d8618067ee34081dd470be9c0cf
[ "Markdown", "PHP" ]
3
PHP
siddhuphp/laravel
2596f916e025de22250f2b90fb9d5e2ed1b085db
4e12bb0905b93987df514624c59c9f5d9484db6a
refs/heads/master
<repo_name>wangyeee/MiniGCS<file_sep>/src/gcs/waypoint.py from pymavlink.mavutil import mavlink from PyQt5.QtCore import QObject, QPoint, QRect, Qt, QVariant, pyqtSignal from PyQt5.QtGui import (QCursor, QDoubleValidator, QIntValidator, QPalette, QValidator) from PyQt5.QtPositioning import QGeoCoordinate from PyQt5.QtWidgets import (QTableWidget, QTableWidgetItem, QWidget, QButtonGroup, QComboBox, QFormLayout, QGridLayout, QHBoxLayout, QHeaderView, QLabel, QLineEdit, QMessageBox, QPushButton, QRadioButton) from WaypointDefault import WP_DEFAULTS, WP_TYPE_NAMES, MAVWaypointParameter from UserData import UserData class Waypoint(QObject): def __init__(self, rowNumber, latitude, longitude, altitude, waypointType = mavlink.MAV_CMD_NAV_WAYPOINT, parent = None): super().__init__(parent) self.rowNumber = rowNumber self.latitude = latitude self.longitude = longitude self.altitude = altitude self.waypointType = waypointType self.mavlinkParameters = {} if self.waypointType in (mavlink.MAV_CMD_NAV_LAND_LOCAL, mavlink.MAV_CMD_NAV_TAKEOFF_LOCAL): self.mavlinkParameters[MAVWaypointParameter.PARAM5] = 0.0 self.mavlinkParameters[MAVWaypointParameter.PARAM6] = 0.0 self.mavlinkParameters[MAVWaypointParameter.PARAM7] = 0.0 else: self.mavlinkParameters[MAVWaypointParameter.PARAM5] = self.latitude self.mavlinkParameters[MAVWaypointParameter.PARAM6] = self.longitude self.mavlinkParameters[MAVWaypointParameter.PARAM7] = self.altitude def __str__(self): return 'Waypoint#{0} type: {1}({2}) @ ({3}, {4}, {5}) -- {6}'.format(self.rowNumber, WP_TYPE_NAMES[self.waypointType], self.waypointType, self.latitude, self.longitude, self.altitude, str(self.mavlinkParameters)) def getCoordinate(self): return QGeoCoordinate(self.latitude, self.longitude, self.altitude) def copy(self): c = Waypoint(self.rowNumber, self.latitude, self.longitude, self.altitude, self.parent()) c.waypointType = self.waypointType return c def toMavlinkMessage(self, sysId, compId, seq, current = 0, autocontinue = 0): item = mavlink.MAVLink_mission_item_message( sysId, compId, seq, mavlink.MAV_FRAME_GLOBAL, self.waypointType, current, autocontinue, Waypoint.defaultParameterValue(self.waypointType, MAVWaypointParameter.PARAM1) \ if MAVWaypointParameter.PARAM1 not in self.mavlinkParameters \ else self.mavlinkParameters[MAVWaypointParameter.PARAM1], Waypoint.defaultParameterValue(self.waypointType, MAVWaypointParameter.PARAM2) \ if MAVWaypointParameter.PARAM2 not in self.mavlinkParameters \ else self.mavlinkParameters[MAVWaypointParameter.PARAM2], Waypoint.defaultParameterValue(self.waypointType, MAVWaypointParameter.PARAM3) \ if MAVWaypointParameter.PARAM3 not in self.mavlinkParameters \ else self.mavlinkParameters[MAVWaypointParameter.PARAM3], Waypoint.defaultParameterValue(self.waypointType, MAVWaypointParameter.PARAM4) \ if MAVWaypointParameter.PARAM4 not in self.mavlinkParameters \ else self.mavlinkParameters[MAVWaypointParameter.PARAM4], self.mavlinkParameters[MAVWaypointParameter.PARAM5], self.mavlinkParameters[MAVWaypointParameter.PARAM6], self.mavlinkParameters[MAVWaypointParameter.PARAM7]) return item @staticmethod def defaultParameterValue(wpType, param): if wpType in WP_DEFAULTS: p = WP_DEFAULTS[wpType] if param in p: return p[param] return None @staticmethod def decimalToDMS(decimal): n = 1.0 if decimal < 0.0: decimal = 0.0 - decimal n = -1.0 degrees = int(decimal) decimal -= degrees decimal *= 60 minutes = int(decimal) decimal -= minutes decimal *= 60 return degrees * n, minutes, decimal @staticmethod def decimalFromDMS(degrees, minutes, seconds): n = 1.0 if degrees < 0.0: degrees = 0.0 - degrees n = -1.0 return n * (degrees + minutes / 60 + seconds / 3600) class WaypointListCell(QWidget): def __init__(self, moveCursorWhenFocus = False, parent = None): super().__init__(parent) self.moveCursorWhenFocus = False self.editEnable = True self.moveCursorWhenFocus = moveCursorWhenFocus def nextFocus(self): self._moveCursor() return 0 def prevFocus(self): self._moveCursor() return 0 def enableEdit(self): self.editEnable = True def disableEdit(self): self.editEnable = False def _setPaletteColor(self, base, text): p = self.palette() if p == None: p = QPalette() p.setColor(QPalette.Base, base) p.setColor(QPalette.Text, text) self.setPalette(p) def _moveCursor(self, field = None): if self.moveCursorWhenFocus: if field == None: field = self pos = field.mapToGlobal(QPoint(0,0)) ctr = field.rect().center() QCursor.setPos(pos.x() + ctr.x(), pos.y() + ctr.y()) field.setCursor(Qt.BlankCursor) class WaypointEditPanel(QWidget): def __init__(self, wp: Waypoint, edtLbl = 'Edit', delLbl = 'Remove', edtCb = None, delCb = None, parent = None): super().__init__(parent) self.waypoint = wp self.editBtn = QPushButton(edtLbl) self.delBtn = QPushButton(delLbl) l = QHBoxLayout() l.addWidget(self.editBtn) l.addWidget(self.delBtn) if edtCb != None: self.edtCb = edtCb self.editBtn.clicked.connect(lambda: self.edtCb(self.waypoint, 0)) if delCb != None: self.delCb = delCb self.delBtn.clicked.connect(lambda: self.delCb(self.waypoint, 1)) l.setContentsMargins(0, 0, 0, 0) self.setLayout(l) class WPDropDownPanel(WaypointListCell): def __init__(self, dropDownList: dict, currentSelection = 0, parent = None): super().__init__(True, parent) self.dropDown = QComboBox(self) self.dropDownList = dropDownList self.setSelection(currentSelection, True) l = QHBoxLayout() l.setContentsMargins(5, 0, 5, 0) l.addWidget(self.dropDown) self.setLayout(l) def setSelection(self, idx: QVariant, createOption = False): i = 0 for idVal, idName in self.dropDownList.items(): if createOption: self.dropDown.addItem(idName, QVariant(idVal)) if idVal == idx: self.dropDown.setCurrentIndex(i) i += 1 def getSelection(self): return self.dropDown.currentData() def getSelectionIndex(self): return self.dropDown.currentIndex() def nextFocus(self): super().nextFocus() self.dropDown.setFocus(Qt.OtherFocusReason) return 1 def prevFocus(self): super().prevFocus() self.dropDown.setFocus(Qt.OtherFocusReason) return -1 class FocusLineEdit(QLineEdit): focusGainedSignal = pyqtSignal(object) focusLostSignal = pyqtSignal(object) valueOverflowSignal = pyqtSignal(float) def __init__(self, contents, step = 1.0, parent = None): super().__init__(contents, parent) self.start = 0 self.end = 0 self.valueValidator = None self.isBeingEdited = False self.step = step def setValueRange(self, start, end, decimals = 0): self.start = start self.end = end if self.valueValidator == None: self.valueValidator = QIntValidator(self.start, self.end) if decimals < 1 else QDoubleValidator(self.start, self.end, decimals) else: if decimals > 0: self.valueValidator.setRange(self.start, self.end, decimals) else: self.valueValidator.setRange(self.start, self.end) self.setValidator(self.valueValidator) def wheelEvent(self, e): if self.isBeingEdited and self.isReadOnly() == False: if type(self.validator()) == QDoubleValidator: self.addValue(self.step * e.angleDelta().y() / 120) elif type(self.validator()) == QIntValidator: self.addValue(int(self.step * e.angleDelta().y() / 120)) def addValue(self, value): if type(self.validator()) == QDoubleValidator: v = float(self.text()) v += value v = self.__constraintValue(v) self.setText('{:.4f}'.format(v)) elif type(self.validator()) == QIntValidator: v = int(self.text()) v += value v = self.__constraintValue(v) self.setText(str(int(v))) def __constraintValue(self, value): if value > self.end: self.valueOverflowSignal.emit(self.step) value -= self.end elif value < self.start: self.valueOverflowSignal.emit(-self.step) value += self.end return value def claimFocus(self): self.setFocus(Qt.OtherFocusReason) def focusInEvent(self, e): super().focusInEvent(e) self.isBeingEdited = True self.focusGainedSignal.emit(self) def focusOutEvent(self, e): super().focusOutEvent(e) self.isBeingEdited = False self.focusLostSignal.emit(self) class WPDegreePanel(WaypointListCell): LATITUDE_TYPE = 'LAT' LONGITUDE_TYPE = 'LNG' valueChanged = pyqtSignal(object) focusInSignal = pyqtSignal(object) def __init__(self, decimalValue, ctype, cachedWP = None, parent = None): ''' ctype=LAT/LNG [deg][min][sec][EW/NS] ''' super().__init__(True, parent) self.cachedCellLocation = None self.currentInFocusEdit = None self.decimalValue = decimalValue self.cachedWP = cachedWP # Degrees Minutes Seconds d, m, s = Waypoint.decimalToDMS(self.decimalValue) self.dirType = ctype self.dirLabel = QLabel(self._getDirLabel(d, self.dirType)) self.dirLabel.adjustSize() self.degreesField = FocusLineEdit('%3d' % (d if d > 0 else -d)) self.degreesField.setFrame(False) delta = 0 if ctype == self.LATITUDE_TYPE else 90 self.degreesField.setValueRange(-90 + delta, 90 + delta) self._setFieldWidth(self.degreesField, 3) self.degreesLabel = QLabel(u'\N{DEGREE SIGN}') self.degreesLabel.adjustSize() self.minutesField = FocusLineEdit('%2d' % m) self.minutesField.setFrame(False) self.minutesField.setValueRange(0, 60) self._setFieldWidth(self.minutesField, 2) self.minutesLabel = QLabel(chr(0x2019)) self.minutesLabel.adjustSize() self.secondsField = FocusLineEdit('%.4f' % s) self.secondsField.setFrame(False) self.secondsField.setValueRange(0.0, 60.0, 4) self._setFieldWidth(self.secondsField, 7) self.secondsLabel = QLabel(chr(0x201D)) self.secondsLabel.adjustSize() self.secondsField.valueOverflowSignal.connect(self.minutesField.addValue) self.minutesField.valueOverflowSignal.connect(self.degreesField.addValue) l = QHBoxLayout() l.setContentsMargins(5, 0, 5, 0) self.degreesField.focusLostSignal.connect(self.valueChangedEvent) self.minutesField.focusLostSignal.connect(self.valueChangedEvent) self.secondsField.focusLostSignal.connect(self.valueChangedEvent) self.degreesField.focusGainedSignal.connect(self.reportInFocusEvent) self.minutesField.focusGainedSignal.connect(self.reportInFocusEvent) self.secondsField.focusGainedSignal.connect(self.reportInFocusEvent) l.addWidget(self.degreesField) l.addWidget(self.degreesLabel) l.addWidget(self.minutesField) l.addWidget(self.minutesLabel) l.addWidget(self.secondsField) l.addWidget(self.secondsLabel) l.addWidget(self.dirLabel) self.setLayout(l) def getValue(self): d = int(self.degreesField.text()) m = int(self.minutesField.text()) s = float(self.secondsField.text()) decimal = Waypoint.decimalFromDMS(d, m, s) sym = self.dirLabel.text() if sym in('S', 'W'): decimal = 0 - decimal return decimal def setValue(self, val: float): self.decimalValue = val d, m, s = Waypoint.decimalToDMS(self.decimalValue) self.degreesField.setText('%3d' % (d if d > 0 else -d)) self.minutesField.setText('%2d' % m) self.secondsField.setText('%.4f' % s) self.dirLabel.setText(self._getDirLabel(d, self.dirType)) def valueChangedEvent(self): val = self.getValue() if self.cachedWP != None: if self.dirType == self.LATITUDE_TYPE: self.cachedWP.latitude = val elif self.dirType == self.LONGITUDE_TYPE: self.cachedWP.longitude = val self.valueChanged.emit(self) def reportInFocusEvent(self, edit): self.currentInFocusEdit = edit self.focusInSignal.emit(self.cachedCellLocation) def nextFocus(self): if self.currentInFocusEdit != None: if self.currentInFocusEdit == self.degreesField: self.currentInFocusEdit = self.minutesField self.minutesField.claimFocus() self._moveCursor(self.minutesField) return 0 if self.currentInFocusEdit == self.minutesField: self.currentInFocusEdit = self.secondsField self.secondsField.claimFocus() self._moveCursor(self.secondsField) return 0 if self.currentInFocusEdit == self.secondsField: self.currentInFocusEdit = None return 1 return 0 # Not going to happen else: self.degreesField.claimFocus() self._moveCursor(self.degreesField) return 0 def prevFocus(self): if self.currentInFocusEdit != None: if self.currentInFocusEdit == self.secondsField: self.currentInFocusEdit = self.minutesField self.minutesField.claimFocus() self._moveCursor(self.minutesField) return 0 if self.currentInFocusEdit == self.minutesField: self.currentInFocusEdit = self.degreesField self.degreesField.claimFocus() self._moveCursor(self.degreesField) return 0 if self.currentInFocusEdit == self.degreesField: self.currentInFocusEdit = None return -1 return 0 # Not going to happen else: self.secondsField.claimFocus() self._moveCursor(self.secondsField) return 0 def setCellLocation(self, cell): self.cachedCellLocation = cell def enableEdit(self): super().enableEdit() self._setPaletteColor(Qt.white, Qt.black) self.degreesField.setReadOnly(False) self.minutesField.setReadOnly(False) self.secondsField.setReadOnly(False) def disableEdit(self): super().disableEdit() self._setPaletteColor(Qt.gray, Qt.darkGray) self.degreesField.setReadOnly(True) self.minutesField.setReadOnly(True) self.secondsField.setReadOnly(True) def _getDirLabel(self, deg, ctype): if ctype == 'LAT': t = 'N' if deg < 0: t = 'S' return t elif ctype == 'LNG': t = 'E' if deg < 0: t = 'W' return t return ' ' def _setFieldWidth(self, field, length): fm = field.fontMetrics() m = field.textMargins() c = field.contentsMargins() w = length * fm.width('0') + m.left() + m.right() + c.left() + c.right() field.setMaximumWidth(w + 8) class WPNumberPanel(WaypointListCell): valueChanged = pyqtSignal(object) def __init__(self, value, isInteger = False, uom = None, validator: QValidator = None, cachedWP = None, parent = None): super().__init__(True, parent) self.value = value self.isInteger = isInteger self.cachedWP = cachedWP self.editField = FocusLineEdit(str(value)) self.editField.returnPressed.connect(self.valueChangedEvent) self.editField.focusLostSignal.connect(self.valueChangedEvent) if validator == None: if self.isInteger: self.editField.setValidator(QIntValidator()) else: self.editField.setValidator(QDoubleValidator()) else: self.editField.setValidator(validator) l = QHBoxLayout() l.setContentsMargins(5, 0, 5, 0) l.addWidget(self.editField) if uom != None: self.uomLabel = QLabel(uom) l.addWidget(self.uomLabel) self.setLayout(l) def valueChangedEvent(self): if self.isInteger: self.value = int(self.editField.text()) else: self.value = float(self.editField.text()) self.valueChanged.emit(self) def getValue(self): return int(self.editField.text()) if self.isInteger else float(self.editField.text()) def setValue(self, val): if self.editField.isReadOnly() == False: self.value = val self.editField.setText(str(self.value)) def nextFocus(self): super().nextFocus() self.editField.setFocus(Qt.OtherFocusReason) return 1 def prevFocus(self): super().prevFocus() self.editField.setFocus(Qt.OtherFocusReason) return -1 def enableEdit(self): super().enableEdit() self._setPaletteColor(Qt.white, Qt.black) self.editField.setReadOnly(False) def disableEdit(self): super().disableEdit() self._setPaletteColor(Qt.gray, Qt.darkGray) self.editField.setReadOnly(True) class WaypointList(QTableWidget): requestReturnToHome = pyqtSignal() editWaypoint = pyqtSignal(object) # show popup window to edit the waypoint deleteWaypoint = pyqtSignal(object) # remove a waypoint preDeleteWaypoint = pyqtSignal(object) # signal sent before removing a waypoint cancelDeleteWaypoint = pyqtSignal(object) # signal sent for cancelled waypoint removal afterWaypointEdited = pyqtSignal(object) # signal after waypoint has been edited in the list def __init__(self, wpList, parent = None): from instruments.map import UD_MAP_KEY, UD_MAP_INIT_LATITUDE_KEY, UD_MAP_INIT_LONGITUDE_KEY super().__init__(parent) lat0 = 0.0 lng0 = 0.0 try: mapConf = UserData.getInstance().getUserDataEntry(UD_MAP_KEY) if mapConf != None: lat0 = float(mapConf[UD_MAP_INIT_LATITUDE_KEY]) lng0 = float(mapConf[UD_MAP_INIT_LONGITUDE_KEY]) except (TypeError, ValueError): pass self.homeLocation = Waypoint(0, lat0, lng0, 0, mavlink.MAV_CMD_DO_SET_HOME) self.currentInFocusCell = None self.manualSetHomeLocationSource = False # self.verticalHeader().setVisible(False) self.createTableHeader() self.wpList = wpList self.setRowCount(len(self.wpList) + 1) self.createHomeWaypointRow() # HomeEditWindow.HOME_SRC_UAV (1) -> use current drone location # HomeEditWindow.HOME_SRC_MAP (0) -> use the location of home icon on map self.homeLocation.mavlinkParameters[MAVWaypointParameter.PARAM1] = HomeEditWindow.HOME_SRC_UAV self.homeEditWindow = HomeEditWindow() self.homeEditWindow.updateHomeLocationSourceSignal.connect(self.updateHomeLocationSourceEvent) def createTableHeader(self): ''' Type, Latitude, Longitude, Altitude, Actions ''' wpHdr = ['Type', 'Latitude', 'Longitude', 'Altitude', 'Actions'] self.setColumnCount(len(wpHdr)) self.setHorizontalHeaderLabels(wpHdr) self.resizeRowsToContents() self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # self.resizeColumnsToContents() def _setRowData(self, rowNumber, dataArray): i = 0 for s in dataArray: if isinstance(s, QWidget): if hasattr(s, 'setCellLocation'): s.setCellLocation((rowNumber, i)) self.setCellWidget(rowNumber, i, s) elif isinstance(s, QTableWidgetItem): self.setItem(rowNumber, i, s) i += 1 def updateWaypoint(self, newWp: Waypoint): wpIdx = newWp.rowNumber + 1 widget = self.cellWidget(wpIdx, 0) # Type (WPDropDownPanel) widget.setSelection(QVariant(newWp.waypointType)) widget = self.cellWidget(wpIdx, 1) # Latitude(WPNumberPanel) widget.setValue(newWp.latitude) widget = self.cellWidget(wpIdx, 2) # Longitude(WPNumberPanel) widget.setValue(newWp.longitude) widget = self.cellWidget(wpIdx, 3) # Altitude(WPNumberPanel) widget.setValue(newWp.altitude) widget = self.cellWidget(wpIdx, 4) # WaypointEditPanel widget.editBtn.clicked.disconnect() widget.delBtn.clicked.disconnect() widget.editBtn.clicked.connect(lambda: self.wpButtonEvent(newWp, 0)) widget.delBtn.clicked.connect(lambda: self.wpButtonEvent(newWp, 1)) def moveWaypoint(self, wpIdx, coord: QGeoCoordinate): # print('wpidx:', wpIdx) if 0 <= wpIdx < len(self.wpList): self.wpList[wpIdx].latitude = coord.latitude() self.wpList[wpIdx].longitude = coord.longitude() self.updateWaypoint(self.wpList[wpIdx]) def updateHomeLocation(self, coord: QGeoCoordinate): self.homeLocation.latitude = coord.latitude() self.homeLocation.longitude = coord.longitude() if coord.type() == QGeoCoordinate.Coordinate3D: self.homeLocation.altitude = coord.altitude() self.setHomeLocation(self.homeLocation) def addWaypoint(self, wp: Waypoint): if wp == None: return data = [] data.append(WPDropDownPanel(WP_TYPE_NAMES, wp.waypointType)) latpanel = WPDegreePanel(wp.latitude, WPDegreePanel.LATITUDE_TYPE, wp) latpanel.valueChanged.connect(self.processWaypointOutfocusUpdate) latpanel.focusInSignal.connect(self.cellFocusChangedEvent) data.append(latpanel) lngpanel = WPDegreePanel(wp.longitude, WPDegreePanel.LONGITUDE_TYPE, wp) lngpanel.valueChanged.connect(self.processWaypointOutfocusUpdate) lngpanel.focusInSignal.connect(self.cellFocusChangedEvent) data.append(lngpanel) altipanel = WPNumberPanel(wp.altitude, uom='M', cachedWP = wp) altipanel.valueChanged.connect(self.processWaypointOutfocusUpdate) data.append(altipanel) pnl = WaypointEditPanel(wp, 'Edit', 'Remove', self.wpButtonEvent, self.wpButtonEvent) data.append(pnl) self.setRowCount(len(self.wpList) + 1) self._setRowData(wp.rowNumber + 1, data) self.scrollToBottom() def processWaypointOutfocusUpdate(self, panel): wp = panel.cachedWP if wp != None: self.__updateWaypointFromList(wp) self.afterWaypointEdited.emit(wp) def __updateWaypointFromList(self, wp: Waypoint): wpIdx = wp.rowNumber + 1 widget = self.cellWidget(wpIdx, 0) # Type (WPDropDownPanel) wp.waypointType = widget.getSelection() widget = self.cellWidget(wpIdx, 1) # Latitude(WPNumberPanel) wp.latitude = widget.getValue() widget = self.cellWidget(wpIdx, 2) # Longitude(WPNumberPanel) wp.longitude = widget.getValue() widget = self.cellWidget(wpIdx, 3) # Altitude(WPNumberPanel) wp.altitude = widget.getValue() def wpButtonEvent(self, wp: Waypoint, act): ''' route event to other components ''' if act == 0: # update self.__updateWaypointFromList(wp) self.editWaypoint.emit(wp) elif act == 1: # delete self.preDeleteWaypoint.emit(wp) cfm = QMessageBox.question(self.window(), 'Confirm removal', 'Are you sure to remove waypoint#{0} at {1}?'.format(wp.rowNumber + 1, wp.getCoordinate().toString()), QMessageBox.Yes, QMessageBox.No) if cfm == QMessageBox.Yes: self.removeRow(wp.rowNumber + 1) self.update() self.deleteWaypoint.emit(wp) else: self.cancelDeleteWaypoint.emit(wp) def highlightWaypoint(self, wp: Waypoint): self.scrollTo(self.model().index(wp.rowNumber + 1, 0)) self.selectRow(wp.rowNumber + 1) def setHomeLocation(self, h: Waypoint): wpIdx = 0 widget = self.cellWidget(wpIdx, 1) # Latitude(WPNumberPanel) widget.setValue(h.latitude) widget = self.cellWidget(wpIdx, 2) # Longitude(WPNumberPanel) widget.setValue(h.longitude) widget = self.cellWidget(wpIdx, 3) # Altitude(WPNumberPanel) widget.setValue(h.altitude) def createHomeWaypointRow(self): ''' can only be called once ''' data = [] s = QTableWidgetItem('Home') s.setTextAlignment(Qt.AlignCenter) s.setFlags(s.flags() & (~Qt.ItemIsEditable)) data.append(s) data.append(WPDegreePanel(self.homeLocation.latitude, WPDegreePanel.LATITUDE_TYPE)) data.append(WPDegreePanel(self.homeLocation.longitude, WPDegreePanel.LONGITUDE_TYPE)) data.append(WPNumberPanel(self.homeLocation.altitude, uom='M')) pnl = WaypointEditPanel(self.homeLocation, 'Edit', 'Return') pnl.editBtn.clicked.connect(self.editHomeLocation) pnl.delBtn.clicked.connect(self.requestReturnHome) data.append(pnl) self._setRowData(0, data) def editHomeLocation(self): src = self.homeLocation.mavlinkParameters[MAVWaypointParameter.PARAM1] if self.manualSetHomeLocationSource and src == HomeEditWindow.HOME_SRC_MAP: src = HomeEditWindow.HOME_SRC_MANUAL self.homeEditWindow.setInitialHomeLocationSource(src, self.homeLocation) self.homeEditWindow.show() def requestReturnHome(self): print('RTL started: {0}, {1} at {2}'.format(self.homeLocation.latitude, self.homeLocation.longitude, self.homeLocation.altitude)) cfm = QMessageBox.question(self.window(), 'Confirm RTH', 'Start return to home {}?'.format(self.homeLocation.getCoordinate().toString()), QMessageBox.Yes, QMessageBox.No) if cfm == QMessageBox.Yes: self.requestReturnToHome.emit() def removeAllRows(self): while self.rowCount() > 1: # the first row is home, which will be kept self.removeRow(1) def keyPressEvent(self, event): key = event.key() if key in (Qt.Key_Backtab, Qt.Key_Tab): # Tab/ShiftTab keys will be used to navigate between defferent line edits if self.currentInFocusCell != None: # 1. Check if current cess has multiple line edits # 2. Move to another cell row = self.currentInFocusCell[0] col = self.currentInFocusCell[1] if key == Qt.Key_Tab: ret = self.cellWidget(row, col).nextFocus() if ret == 1: if col < self.columnCount() - 2: # Skip last column col += 1 elif row < self.rowCount() - 1: row += 1 col = 0 self.currentInFocusCell = (row, col) self.cellWidget(row, col).nextFocus() elif key == Qt.Key_Backtab: ret = self.cellWidget(row, col).prevFocus() if ret == -1: if col > 0: col -= 1 elif row > 1: # skip home row row -= 1 col = self.columnCount() - 2 # Skip last column self.currentInFocusCell = (row, col) self.cellWidget(row, col).prevFocus() else: # key not in (Qt.Key_Backtab, Qt.Key_Tab) super().keyPressEvent(event) def cellFocusChangedEvent(self, cell): self.currentInFocusCell = cell def updateHomeLocationSourceEvent(self, src, coord): self.manualSetHomeLocationSource = False if src == HomeEditWindow.HOME_SRC_UAV: self.homeLocation.mavlinkParameters[MAVWaypointParameter.PARAM1] = HomeEditWindow.HOME_SRC_UAV elif src in (HomeEditWindow.HOME_SRC_MAP, HomeEditWindow.HOME_SRC_MANUAL): self.homeLocation.mavlinkParameters[MAVWaypointParameter.PARAM1] = HomeEditWindow.HOME_SRC_MAP if coord != None and src == HomeEditWindow.HOME_SRC_MANUAL: self.manualSetHomeLocationSource = True self.updateHomeLocation(coord) class HomeEditWindow(QWidget): # 1st param, src: could be HOME_SRC_MAP, HOME_SRC_UAV, or HOME_SRC_MANUAL # 2st param, coord: QGeoCoordinate object if src == HOME_SRC_MANUAL, else None updateHomeLocationSourceSignal = pyqtSignal(int, object) HOME_SRC_MAP = 0 # Must be 0 to conform mavlink protocol HOME_SRC_UAV = 1 # Must be 1 to conform mavlink protocol HOME_SRC_MANUAL = 2 def __init__(self, parent = None): super().__init__(parent) self.setWindowTitle('Edit Home Location') self.homeSrcGrp = QButtonGroup(self) l = QGridLayout() row = 0 column = 0 rowSpan = 1 columnSpan = 3 l.addWidget(QLabel('Choose data source'), row, column, rowSpan, columnSpan, Qt.AlignLeft) self.srcDroneHomeLocation = QRadioButton('Home location in the UAV', self) self.homeSrcGrp.addButton(self.srcDroneHomeLocation) row += 1 l.addWidget(self.srcDroneHomeLocation, row, column, rowSpan, columnSpan, Qt.AlignLeft) self.srcMapHomeLocation = QRadioButton('Home location on the map', self) self.homeSrcGrp.addButton(self.srcMapHomeLocation) row += 1 l.addWidget(self.srcMapHomeLocation, row, column, rowSpan, columnSpan, Qt.AlignLeft) self.srcInputHomeLocation = QRadioButton('Manual input', self) self.homeSrcGrp.addButton(self.srcInputHomeLocation) row += 1 l.addWidget(self.srcInputHomeLocation, row, column, rowSpan, columnSpan, Qt.AlignLeft) self.srcInputHomeLocation.toggled.connect(self.__enableManualInputs) row += 1 columnSpan = 1 l.addWidget(QLabel('Latitude'), row, column, rowSpan, columnSpan, Qt.AlignLeft) self.latitudeField = WPDegreePanel(0.0, WPDegreePanel.LATITUDE_TYPE) columnSpan = 2 l.addWidget(self.latitudeField, row, column + 1, rowSpan, columnSpan, Qt.AlignLeft) row += 1 columnSpan = 1 l.addWidget(QLabel('Longitude'), row, column, rowSpan, columnSpan, Qt.AlignLeft) self.longitudeField = WPDegreePanel(0.0, WPDegreePanel.LONGITUDE_TYPE) columnSpan = 2 l.addWidget(self.longitudeField, row, column + 1, rowSpan, columnSpan, Qt.AlignLeft) row += 1 columnSpan = 1 l.addWidget(QLabel('Altitude'), row, column, rowSpan, columnSpan, Qt.AlignLeft) self.altitudeField = WPNumberPanel(0.0, uom='m') columnSpan = 2 l.addWidget(self.altitudeField, row, column + 1, rowSpan, columnSpan, Qt.AlignLeft) row += 1 columnSpan = 1 self.okButton = QPushButton('OK', self) self.okButton.clicked.connect(self.__setHomeLocationSource) l.addWidget(self.okButton, row, column + 1, rowSpan, columnSpan, Qt.AlignRight) self.cancelButton = QPushButton('Cancel', self) self.cancelButton.clicked.connect(self.close) l.addWidget(self.cancelButton, row, column + 2, rowSpan, columnSpan, Qt.AlignRight) self.setInitialHomeLocationSource(HomeEditWindow.HOME_SRC_UAV) # Default to home location reported by the UAV self.setLayout(l) def setInitialHomeLocationSource(self, src, wp: Waypoint = None): if src == HomeEditWindow.HOME_SRC_UAV: self.srcDroneHomeLocation.setChecked(True) self.__enableManualInputs(False) elif src == HomeEditWindow.HOME_SRC_MAP: self.srcMapHomeLocation.setChecked(True) self.__enableManualInputs(False) elif src == HomeEditWindow.HOME_SRC_MANUAL: self.srcInputHomeLocation.setChecked(True) self.__enableManualInputs(True) if wp != None: self.latitudeField.setValue(wp.latitude) self.longitudeField.setValue(wp.longitude) self.altitudeField.setValue(wp.altitude) def __setHomeLocationSource(self): if self.srcDroneHomeLocation.isChecked(): self.updateHomeLocationSourceSignal.emit(HomeEditWindow.HOME_SRC_UAV, None) elif self.srcMapHomeLocation.isChecked(): self.updateHomeLocationSourceSignal.emit(HomeEditWindow.HOME_SRC_MAP, None) elif self.srcInputHomeLocation.isChecked(): coord = QGeoCoordinate(self.latitudeField.getValue(), self.longitudeField.getValue(), self.altitudeField.getValue()) self.updateHomeLocationSourceSignal.emit(HomeEditWindow.HOME_SRC_MANUAL, coord) self.close() def __enableManualInputs(self, checked): if checked: self.latitudeField.enableEdit() self.longitudeField.enableEdit() self.altitudeField.enableEdit() else: self.latitudeField.disableEdit() self.longitudeField.disableEdit() self.altitudeField.disableEdit() class WaypointEditWindowFactory: @staticmethod def createWaypointEditWindow(wp: Waypoint): if wp.waypointType in (mavlink.MAV_CMD_NAV_LOITER_TIME, mavlink.MAV_CMD_NAV_LOITER_TURNS, mavlink.MAV_CMD_NAV_LOITER_UNLIM, mavlink.MAV_CMD_NAV_LOITER_TO_ALT): return LoiterWaypointEditWindow(wp) if wp.waypointType in (mavlink.MAV_CMD_NAV_LAND, mavlink.MAV_CMD_NAV_LAND_LOCAL): return LandWaypointEditWindow(wp) if wp.waypointType in (mavlink.MAV_CMD_NAV_TAKEOFF, mavlink.MAV_CMD_NAV_TAKEOFF_LOCAL): return TakeoffWaypointEditWindow(wp) if wp.waypointType == mavlink.MAV_CMD_NAV_FOLLOW: return FollowWaypointEditWindow(wp) if wp.waypointType == mavlink.MAV_CMD_NAV_CONTINUE_AND_CHANGE_ALT: return ContinueAndChangeAltitudeWaypointEditWindow(wp) return WaypointEditWindow(wp) @staticmethod def createYesNoDropdown(options = None, parent = None): if options is None: options = {0 : 'No', 1 : 'Yes'} dropDown = QComboBox(parent) for data, label in options.items(): dropDown.addItem(label, QVariant(data)) return dropDown class WaypointEditWindow(QWidget): updateWaypoint = pyqtSignal(object) # send value in popup window to application def __init__(self, wp: Waypoint, parent = None): super().__init__(parent) self.waypoint = wp layout = QFormLayout() self.latField = WPDegreePanel(wp.latitude, WPDegreePanel.LATITUDE_TYPE) # QLineEdit(str(wp.latitude)) self.lngField = WPDegreePanel(wp.longitude, WPDegreePanel.LONGITUDE_TYPE) # QLineEdit(str(wp.longitude)) self.altField = WPNumberPanel(wp.altitude, uom='M') self.typeSel = WPDropDownPanel(WP_TYPE_NAMES, wp.waypointType) layout.addRow(QLabel('Latitude'), self.latField) layout.addRow(QLabel('Longitude'), self.lngField) layout.addRow(QLabel('Altitude'), self.altField) layout.addRow(QLabel('Type'), self.typeSel) self.addAdditionalFields(layout) self.actPanel = QWidget(self) self.okBtn = QPushButton('OK') self.cnlBtn = QPushButton('Cancel') pnlLay = QHBoxLayout() pnlLay.addWidget(self.okBtn) pnlLay.addWidget(self.cnlBtn) self.actPanel.setLayout(pnlLay) layout.addRow(self.actPanel) self.cnlBtn.clicked.connect(self.close) self.okBtn.clicked.connect(self.updateWaypointEvent) # self.latField.returnPressed.connect(self.okBtn.click) # self.lngField.returnPressed.connect(self.okBtn.click) self.altField.valueChanged.connect(self.okBtn.click) self.setWindowTitle('Edit Waypoint#{0}'.format(wp.rowNumber)) self.setLayout(layout) self.setGeometry(QRect(100, 100, 400, 200)) def addAdditionalFields(self, layout): if self.waypoint.waypointType == mavlink.MAV_CMD_NAV_WAYPOINT: self.holdTimeField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM1), uom='s', isInteger=True) layout.addRow(QLabel('Hold'), self.holdTimeField) self.acceptanceRadiusField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM2), uom='m') layout.addRow(QLabel('Accept Radius'), self.acceptanceRadiusField) self.passRadiusField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM3), uom='m') layout.addRow(QLabel('Pass Radius'), self.passRadiusField) self.yawAngleField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM4), uom=u'\N{DEGREE SIGN}') layout.addRow(QLabel('Yaw'), self.yawAngleField) def updateAdditionalFieldValues(self): if self.waypoint.waypointType == mavlink.MAV_CMD_NAV_WAYPOINT: self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM1] = self.holdTimeField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM2] = self.acceptanceRadiusField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM3] = self.passRadiusField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM4] = self.yawAngleField.getValue() def getFieldValue(self, param): if param in self.waypoint.mavlinkParameters: return self.waypoint.mavlinkParameters[param] return self.getDefaultParameterValue(param) def getDefaultParameterValue(self, param): if self.waypoint.waypointType == mavlink.MAV_CMD_NAV_WAYPOINT: if param == MAVWaypointParameter.PARAM1: return 0 if param in (MAVWaypointParameter.PARAM2, MAVWaypointParameter.PARAM3): return 2.0 if param == MAVWaypointParameter.PARAM4: return 0.0 return 0 def updateWaypointEvent(self): # TODO data validation self.waypoint.latitude = self.latField.getValue() self.waypoint.longitude = self.lngField.getValue() self.waypoint.altitude = self.altField.getValue() self.waypoint.waypointType = self.typeSel.getSelection() self.updateAdditionalFieldValues() print('new WP:', self.waypoint) self.updateWaypoint.emit(self.waypoint) self.close() def keyPressEvent(self, event): key = event.key() if key == Qt.Key_Escape: self.close() class ContinueAndChangeAltitudeWaypointEditWindow(WaypointEditWindow): def __init__(self, wp: Waypoint, parent = None): super().__init__(wp, parent) self.setWindowTitle('Edit Continue and Change Altitude Waypoint#{}'.format(wp.rowNumber)) def addAdditionalFields(self, layout): self.actionDropdown = WPDropDownPanel({ 0 : 'Neutral', 1 : 'Climbing', 2 : 'Descending'}, self.getFieldValue(MAVWaypointParameter.PARAM1), self) # Param1 layout.addRow(QLabel('Action'), self.actionDropdown) self.desiredAltitudeField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM7), uom='m') # Param7 layout.addRow(QLabel('Altitude'), self.desiredAltitudeField) def updateAdditionalFieldValues(self): self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM1] = self.actionDropdown.getSelectionIndex() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM7] = self.desiredAltitudeField.getValue() # def getDefaultParameterValue(self, param): class FollowWaypointEditWindow(WaypointEditWindow): def __init__(self, wp: Waypoint, parent = None): super().__init__(wp, parent) self.setWindowTitle('Edit Follow Waypoint#{}'.format(wp.rowNumber)) def addAdditionalFields(self, layout): self.followingLogicField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM1), isInteger = True) # Param1 layout.addRow(QLabel('Following'), self.followingLogicField) self.groundSpeedField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM2), uom='m/s') # Param2 layout.addRow(QLabel('Ground Speed'), self.groundSpeedField) self.radiusField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM3), uom='m') # Param3 layout.addRow(QLabel('Radius'), self.radiusField) self.yawAngleField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM4), uom=u'\N{DEGREE SIGN}') # Param4 layout.addRow(QLabel('Yaw'), self.yawAngleField) def updateAdditionalFieldValues(self): self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM1] = self.followingLogicField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM2] = self.groundSpeedField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM3] = self.radiusField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM4] = self.yawAngleField.getValue() # def getDefaultParameterValue(self, param): class TakeoffWaypointEditWindow(WaypointEditWindow): def __init__(self, wp: Waypoint, parent = None): super().__init__(wp, parent) self.setWindowTitle('Edit Takeoff Waypoint#{}'.format(wp.rowNumber)) def addAdditionalFields(self, layout): self.minPitchField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM1), uom=u'\N{DEGREE SIGN}') # Param1 layout.addRow(QLabel('Pitch'), self.minPitchField) self.yawAngleField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM4), uom=u'\N{DEGREE SIGN}') # Param4 layout.addRow(QLabel('Yaw'), self.yawAngleField) if self.waypoint.waypointType == mavlink.MAV_CMD_NAV_TAKEOFF_LOCAL: self.ascendRateField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM3), uom='m/s') # Param3 layout.addRow(QLabel('Ascend Rate'), self.ascendRateField) self.xPositionField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM6), uom='m') # Param6 layout.addRow(QLabel('X Position'), self.xPositionField) self.yPositionField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM5), uom='m') # Param5 layout.addRow(QLabel('Y Position'), self.yPositionField) self.zPositionField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM7), uom='m') # Param7 layout.addRow(QLabel('Z Position'), self.zPositionField) def updateAdditionalFieldValues(self): self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM1] = self.minPitchField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM4] = self.yawAngleField.getValue() if self.waypoint.waypointType == mavlink.MAV_CMD_NAV_TAKEOFF_LOCAL: self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM3] = self.ascendRateField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM6] = self.xPositionField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM5] = self.yPositionField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM7] = self.zPositionField.getValue() # def getDefaultParameterValue(self, param): class LandWaypointEditWindow(WaypointEditWindow): def __init__(self, wp: Waypoint, parent = None): super().__init__(wp, parent) self.setWindowTitle('Edit Land Waypoint#{}'.format(wp.rowNumber)) def addAdditionalFields(self, layout): self.yawAngleField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM4), uom=u'\N{DEGREE SIGN}') layout.addRow(QLabel('Yaw'), self.yawAngleField) # Param4 if self.waypoint.waypointType == mavlink.MAV_CMD_NAV_LAND: self.abortAltitudeField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM1), uom='m') # Param1 layout.addRow(QLabel('Abort Alt'), self.abortAltitudeField) self.landModeDropdown = WPDropDownPanel({ mavlink.PRECISION_LAND_MODE_DISABLED : 'Disabled', mavlink.PRECISION_LAND_MODE_OPPORTUNISTIC : 'Opportunistic', mavlink.PRECISION_LAND_MODE_REQUIRED : 'Required'}, self.getFieldValue(MAVWaypointParameter.PARAM2), self) # Param2 layout.addRow(QLabel('Land Mode'), self.landModeDropdown) elif self.waypoint.waypointType == mavlink.MAV_CMD_NAV_LAND_LOCAL: self.targetNumberField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM1), isInteger = True) layout.addRow(QLabel('Target'), self.targetNumberField) self.offsetField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM2), uom='m') layout.addRow(QLabel('Offset'), self.offsetField) self.descendRateField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM3), uom='m/s') layout.addRow(QLabel('Desend Rate'), self.descendRateField) self.xPositionField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM6), uom='m') # Param6 layout.addRow(QLabel('X Position'), self.xPositionField) self.yPositionField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM5), uom='m') # Param5 layout.addRow(QLabel('Y Position'), self.yPositionField) self.zPositionField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM7), uom='m') # Param7 layout.addRow(QLabel('Z Position'), self.zPositionField) def updateAdditionalFieldValues(self): self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM4] = self.yawAngleField.getValue() if self.waypoint.waypointType == mavlink.MAV_CMD_NAV_LAND: self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM1] = self.abortAltitudeField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM2] = self.landModeDropdown.getSelectionIndex() elif self.waypoint.waypointType == mavlink.MAV_CMD_NAV_LAND_LOCAL: self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM1] = self.targetNumberField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM2] = self.offsetField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM3] = self.descendRateField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM6] = self.xPositionField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM5] = self.yPositionField.getValue() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM7] = self.zPositionField.getValue() # def getDefaultParameterValue(self, param): class LoiterWaypointEditWindow(WaypointEditWindow): def __init__(self, wp: Waypoint, parent = None): super().__init__(wp, parent) self.setWindowTitle('Edit Loiter Waypoint#{}'.format(wp.rowNumber)) def addAdditionalFields(self, layout): self.loiterRadiusField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM3), uom='m') layout.addRow(QLabel('Radius'), self.loiterRadiusField) if self.waypoint.waypointType == mavlink.MAV_CMD_NAV_LOITER_TIME: self.loiterTimeField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM1), uom='s') layout.addRow(QLabel('Time'), self.loiterTimeField) elif self.waypoint.waypointType == mavlink.MAV_CMD_NAV_LOITER_TURNS: self.loiterTurnsField = WPNumberPanel(self.getFieldValue(MAVWaypointParameter.PARAM1), uom='turn') layout.addRow(QLabel('Turns'), self.loiterTurnsField) elif self.waypoint.waypointType == mavlink.MAV_CMD_NAV_LOITER_TO_ALT: self.headingRequiredDropDown = WaypointEditWindowFactory.createYesNoDropdown(parent=self) self.headingRequiredDropDown.setCurrentIndex(self.getFieldValue(MAVWaypointParameter.PARAM1)) layout.addRow(QLabel('Heading Required'), self.headingRequiredDropDown) self.xtrackLocationDropDown = WaypointEditWindowFactory.createYesNoDropdown({0 : 'Center', 1 : 'Exit'}, self) self.xtrackLocationDropDown.setCurrentIndex(self.getFieldValue(MAVWaypointParameter.PARAM4)) layout.addRow(QLabel('Xtrack Location'), self.xtrackLocationDropDown) def updateAdditionalFieldValues(self): self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM3] = self.loiterRadiusField.getValue() if self.waypoint.waypointType == mavlink.MAV_CMD_NAV_LOITER_TIME: self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM1] = self.loiterTimeField.getValue() elif self.waypoint.waypointType == mavlink.MAV_CMD_NAV_LOITER_TURNS: self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM1] = self.loiterTurnsField.getValue() elif self.waypoint.waypointType == mavlink.MAV_CMD_NAV_LOITER_TO_ALT: self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM1] = self.headingRequiredDropDown.currentIndex() self.waypoint.mavlinkParameters[MAVWaypointParameter.PARAM4] = self.xtrackLocationDropDown.currentIndex() # def getDefaultParameterValue(self, param): <file_sep>/src/gcs/fpv.py from PyQt5.QtCore import pyqtSignal, QThread from PyQt5.QtGui import QImage from cv2 import VideoCapture, cvtColor, COLOR_BGR2RGB, CAP_PROP_FPS from time import sleep, time class VideoSource(QThread): newFrameAvailable = pyqtSignal(object) def __init__(self, parent = None): super().__init__(parent) self.running = True self.pause = False def pauseVideo(self, pause): self.pause = pause class FileVideoSource(VideoSource): ''' Load a video file as video source, for test or flight replay purposes. ''' def __init__(self, fileName, parent = None): super().__init__(parent) self.cap = VideoCapture(fileName) self.frameRate = self.cap.get(CAP_PROP_FPS) self.__delay = 1.0 / self.frameRate def run(self): self.running = True while self.cap.isOpened(): if self.pause: continue _s0 = time() ret, frame = self.cap.read() if ret == True: rgbImage = cvtColor(frame, COLOR_BGR2RGB) h, w, ch = rgbImage.shape bytesPerLine = ch * w convertToQtFormat = QImage(rgbImage.data, w, h, bytesPerLine, QImage.Format_RGB888) self.newFrameAvailable.emit(convertToQtFormat) _s0 = time() - _s0 sleep(0 if _s0 >= self.__delay else self.__delay - _s0) self.running = False self.__cleanup() def __cleanup(self): self.cap.release() <file_sep>/src/gcs/instruments/map.py ''' The flight map implementation. ''' import math import os import time from pymavlink.mavutil import mavlink from PyQt5.QtCore import (QAbstractListModel, QByteArray, QModelIndex, QSize, Qt, QThread, QUrl, QVariant, pyqtSignal, pyqtSlot) from PyQt5.QtGui import QCursor from PyQt5.QtPositioning import QGeoCoordinate from PyQt5.QtQml import qmlRegisterType from PyQt5.QtQuick import QQuickItem, QQuickView from PyQt5.QtWidgets import (QHBoxLayout, QLabel, QMessageBox, QPushButton, QSplitter, QVBoxLayout, QWidget) from adsb import ADSBSource, AircraftsModel from telemetry import UD_TELEMETRY_KEY, UD_TELEMETRY_LOG_FOLDER_KEY from UserData import UserData from utils import unused from waypoint import (MAVWaypointParameter, Waypoint, WaypointEditWindowFactory, WaypointList) DEFAULT_LATITUDE = 0.0 DEFAULT_LONGITUDE = 0.0 DEFAULT_ZOOM = 1 MIN_ZOOM = 0 MAX_ZOOM = 19 MIN_DRAG_TIME = 0.1 TILE_SIZE = 256 UD_MAP_KEY = 'MAP' UD_MAP_INIT_LATITUDE_KEY = 'INIT_LATITUDE' UD_MAP_INIT_LONGITUDE_KEY = 'INIT_LONGITUDE' UD_MAP_INIT_ZOOM_KEY = 'INIT_ZOOM' class MapItem(QQuickItem): updateCoordinate = pyqtSignal(float, float, arguments=['lat', 'lng']) updateHomeCoordinate = pyqtSignal(float, float, arguments=['lat', 'lng']) updateZoomLevel = pyqtSignal(int, arguments=['zoom']) updateDroneLocation = pyqtSignal(float, float, arguments=['lat', 'lng']) updateDroneLocationUncertainty = pyqtSignal(float, float, arguments=['hacc', 'vacc']) waypointRemoved = pyqtSignal(int, arguments=['wpNumber']) # signal sent to qml to remove wp in polyline, wpNumber starts from 1 (0 is resvered for home) waypointChanged = pyqtSignal(int, float, float, arguments=['wpNumber', 'latitude', 'longitude']) # signal sent to qml to update wp in polyline waypointChangedInt = pyqtSignal(int, int, int, arguments=['wpNumber', 'x', 'y']) # signal sent to qml to update wp by cursor position in polyline waypointCreated = pyqtSignal(float, float, arguments=['lat', 'lng']) allPolylineRemoved = pyqtSignal() # signal to remove existing polyline def __init__(self, parent=None): super().__init__(parent) self.lat = 0.0 self.lng = 0.0 self.zoomLevel = DEFAULT_ZOOM def moveMapToCoordinate(self, lat, lng): self.lat = lat self.lng = lng self.updateCoordinate.emit(lat, lng) def moveHomeToCoordinate(self, lat, lng): self.updateHomeCoordinate.emit(lat, lng) def getZoomLevel(self): return self.zoomLevel def zoomMapDelta(self, delta): self.zoomMap(self.zoomLevel + delta) def zoomMap(self, absZoom): if MIN_ZOOM <= absZoom <= MAX_ZOOM: self.zoomLevel = absZoom self.updateZoomLevel.emit(self.zoomLevel) def moveMap(self, deltaLat, deltaLng): lat = self.lat + deltaLat lng = self.lng + deltaLng if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0: self.moveMapToCoordinate(lat, lng) def moveDroneLocation(self, lat, lng, hacc, vacc): self.updateDroneLocation.emit(lat, lng, hacc, vacc) class WaypointsModel(QAbstractListModel): positionRole = Qt.UserRole + 1 dotColorRole = Qt.UserRole + 2 rowNumberRole = Qt.UserRole + 3 loiterRadiusRole = Qt.UserRole + 4 createWaypointAction = pyqtSignal(object) def __init__(self, parent = None): super().__init__(parent) self.allWaypoints = [] # [Waypoint(0, 0, 0, 0)] self.redWPIdx = -1 def markWaypoint(self, wp: Waypoint): idx = self.index(wp.rowNumber) self.redWPIdx = wp.rowNumber self.dataChanged.emit(idx, idx) def unmarkWaypoint(self, wp: Waypoint): idx = self.index(wp.rowNumber) self.redWPIdx = -1 self.dataChanged.emit(idx, idx) @pyqtSlot(float, float) def createWaypoint(self, lat, lng): idx = self.rowCount() self.beginInsertRows(QModelIndex(), idx, idx) mrk = Waypoint(idx, lat, lng, 10.0) self.allWaypoints.append(mrk) self.endInsertRows() self.createWaypointAction.emit(mrk) def rowCount(self, parent=QModelIndex()): unused(parent) return len(self.allWaypoints) def data(self, index, role=Qt.DisplayRole): idx = index.row() if idx < 0 or idx > len(self.allWaypoints) - 1: return QVariant() if role == WaypointsModel.positionRole: return QVariant(self.allWaypoints[idx].getCoordinate()) if role == WaypointsModel.dotColorRole: if self.allWaypoints[idx].rowNumber == self.redWPIdx: self.redWPIdx = -1 return QVariant('red') return QVariant('green') if role == WaypointsModel.rowNumberRole: return QVariant(self.allWaypoints[idx].rowNumber) if role == WaypointsModel.loiterRadiusRole: if self.allWaypoints[idx].waypointType in (mavlink.MAV_CMD_NAV_LOITER_TIME, mavlink.MAV_CMD_NAV_LOITER_TURNS, mavlink.MAV_CMD_NAV_LOITER_UNLIM, mavlink.MAV_CMD_NAV_LOITER_TO_ALT): return QVariant(self.allWaypoints[idx].mavlinkParameters[MAVWaypointParameter.PARAM3]) return QVariant(0.0) return QVariant() def flags(self, index): if index.row() < 0 or index.row() >= len(self.allWaypoints): return Qt.NoItemFlags return Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled def roleNames(self): return { WaypointsModel.positionRole : QByteArray(b'position'), WaypointsModel.dotColorRole : QByteArray(b'dotColor'), WaypointsModel.rowNumberRole : QByteArray(b'rowNumber'), WaypointsModel.loiterRadiusRole : QByteArray(b'loiterRadius') } def updateWaypointCoordinate(self, rowNumber, newCoordinate: QGeoCoordinate): if 0 <= rowNumber < len(self.allWaypoints): # self._debug_dump_wp_list(rowNumber) wp = self.allWaypoints[rowNumber] # print('[MAP] move WP#{4} ({0}, {1}) to ({2}, {3})'.format(wp.latitude, wp.longitude, # newCoordinate.latitude(), newCoordinate.longitude(), # wp.rowNumber)) wp.latitude = newCoordinate.latitude() wp.longitude = newCoordinate.longitude() self.refreshWaypoint(wp) # self._debug_dump_wp_list(rowNumber) def refreshWaypoint(self, wp: Waypoint): idx = self.index(wp.rowNumber) self.dataChanged.emit(idx, idx) def removeWaypoint(self, wp: Waypoint): tgtWp = wp.rowNumber # self._debug_dump_wp_list(tgtWp) i = tgtWp + 1 while i < len(self.allWaypoints): self.allWaypoints[i].rowNumber -= 1 i += 1 self.beginRemoveRows(QModelIndex(), tgtWp, tgtWp) del self.allWaypoints[tgtWp] self.endRemoveRows() # self._debug_dump_wp_list() # send signal to update WP# displayed on the map unless the last WP is removed if i > tgtWp + 1: txtStart = self.index(tgtWp) txtEnd = self.index(len(self.allWaypoints) - 1) self.dataChanged.emit(txtStart, txtEnd) def removeAllWaypoint(self): self.beginRemoveRows(QModelIndex(), 0, self.rowCount()) self.allWaypoints.clear() self.endRemoveRows() def _debug_dump_wp_list(self, star = -1): for wp in self.allWaypoints: if star == wp.rowNumber: print('*' + str(wp)) else: print(str(wp)) class WaypointDragTracking(QThread): def __init__(self, mapView, hertz = 50, threshold = 2, parent = None): super().__init__(parent) self.wpIndex = 0 self.prevX = 0 self.prevY = 0 self.mapView = mapView self.delay = 1 / hertz self.threshold = threshold def startTrackingWaypoint(self, index): self.wpIndex = index self.start() def run(self): while self.mapView.isBeingDragged(): currentPos = QCursor.pos() if abs(currentPos.x() - self.prevX) > self.threshold or abs(currentPos.y() - self.prevY) > self.threshold: self.prevX = currentPos.x() self.prevY = currentPos.y() self.mapView.map.waypointChangedInt.emit(self.wpIndex, currentPos.x(), currentPos.y()) # Update ploylines in the map and the list time.sleep(self.delay) class MapView(QQuickView): selectWaypointForAction = pyqtSignal(object) updateWaypointCoordinateEvent = pyqtSignal(int, object) # WP row#, new coordinate moveHomeEvent = pyqtSignal(object) def __init__(self, qml): super().__init__() self.dragStart = False self.dragTracker = None self.mapConf = None qmlRegisterType(MapItem, 'MapItem', 1, 0, 'MapItem') self.setResizeMode(QQuickView.SizeRootObjectToView) self.wpModel = WaypointsModel() self.adsbModel = AircraftsModel() self.rootContext().setContextProperty('markerModel', self.wpModel) self.rootContext().setContextProperty('adsbModel', self.adsbModel) self.setSource(qml) if self.status() == QQuickView.Error: print('error loading qml file') else: self.map = self.rootObject() self.map.waypointSelected.connect(self.waypointEditEvent) self.map.mapDragEvent.connect(self.mapDragEvent) self.map.mapCenterChangedEvent.connect(self.mapCenterChangedEvent) self.map.mapZoomLevelChangedEvent.connect(self.mapZoomLevelChangedEvent) self.map.updateHomeLocation.connect(self.updateHomeEvent) self.dragTracker = WaypointDragTracking(self) self.adsbSources = ADSBSource.getAvailableADSBSources() for src in self.adsbSources: ud = UserData.getInstance() param = ud.getUserDataEntry(src.getConfigurationParameterKey()) if param != None and param['ENABLE']: src.lazyInit(param) src.aircraftCreateSignal.connect(self.adsbModel.addAircraft) src.aircraftUpdateSignal.connect(self.adsbModel.updateAircraft) src.aircraftDeleteSignal.connect(self.adsbModel.removeAircraft) src.start() def restorePreviousView(self): if self.map != None: lat0 = DEFAULT_LATITUDE lng0 = DEFAULT_LONGITUDE zoom0 = DEFAULT_ZOOM try: self.mapConf = UserData.getInstance().getUserDataEntry(UD_MAP_KEY) if self.mapConf != None: lat0 = float(self.mapConf[UD_MAP_INIT_LATITUDE_KEY]) lng0 = float(self.mapConf[UD_MAP_INIT_LONGITUDE_KEY]) zoom0 = int(self.mapConf[UD_MAP_INIT_ZOOM_KEY]) else: self.mapConf = {} except ValueError: pass except TypeError: pass self.map.moveMapToCoordinate(lat0, lng0) self.map.zoomMap(zoom0) def pix2lat(self, pix, piy): scale = 1 << int(self.map.getZoomLevel()) scale *= TILE_SIZE lng = 360 * pix / scale m = 4 * math.pi * piy / scale em = math.pow(math.e, m) lat = math.asin((em - 1) / (em + 1)) * 180 / math.pi return lng, lat def wheelEvent(self, event): # quicker response compared to MapGestureArea.FlickGesture self.map.zoomMapDelta(event.angleDelta().y() / 120) def keyPressEvent(self, event): key = event.key() deltaX, deltaY = self.pix2lat(10, 10) # print(key) if key == Qt.Key_Left: self.map.moveMap(0, -deltaY) elif key == Qt.Key_Right: self.map.moveMap(0, deltaY) elif key == Qt.Key_Up: self.map.moveMap(deltaX, 0) elif key == Qt.Key_Down: self.map.moveMap(-deltaX, 0) # elif key == Qt.Key_Home: # self.map.moveMapToCoordinate(LATITUDE, LONGITUDE) def waypointEditEvent(self, index): if 0 <= index < self.wpModel.rowCount(): # print('select WP#', index) self.selectWaypointForAction.emit(self.wpModel.allWaypoints[index]) def mapCenterChangedEvent(self, lat, lng): self.mapConf[UD_MAP_INIT_LATITUDE_KEY] = str(lat) self.mapConf[UD_MAP_INIT_LONGITUDE_KEY] = str(lng) UserData.getInstance().setUserDataEntry(UD_MAP_KEY, self.mapConf) def mapZoomLevelChangedEvent(self, zoom): self.mapConf[UD_MAP_INIT_ZOOM_KEY] = str(zoom) UserData.getInstance().setUserDataEntry(UD_MAP_KEY, self.mapConf) def mapDragEvent(self, index, lat, lng, actType): ''' actType = 0, start of drag actType = 1, during drag actType = 2, end of drag ''' if actType == 0: self.dragStart = True self.dragTracker.startTrackingWaypoint(index) elif actType == 1: toWp = QGeoCoordinate(lat, lng) self.updateWaypointCoordinateEvent.emit(index, toWp) elif actType == 2: if self.dragStart: toWp = QGeoCoordinate(lat, lng) self.updateWaypointCoordinateEvent.emit(index, toWp) self.dragStart = False def isBeingDragged(self): return self.dragStart def updateHomeEvent(self, lat, lng): # print('New home location: {0}, {1}'.format(lat, lng)) self.moveHomeEvent.emit(QGeoCoordinate(lat, lng)) def updateDroneLocation(self, sourceUAS, timestamp, latitude, longitude, altitude): unused(sourceUAS, timestamp, altitude) self.map.updateDroneLocation.emit(latitude, longitude) def updateDroneLocationUncertainty(self, sourceUAS, timestamp, fixtype, hdop, vdop, nosv, hacc, vacc, velacc, hdgacc): unused(sourceUAS, timestamp, fixtype, hdop, vdop, nosv, velacc, hdgacc) self.map.updateDroneLocationUncertainty.emit(hacc, vacc) def minimumSize(self): return QSize(600, 480) class MapWidget(QSplitter): uploadWaypointsToUAVEvent = pyqtSignal(object) # pass the waypoint list as parameter downloadWaypointsFromUAVSignal = pyqtSignal() def __init__(self, mapQmlFile, parent = None): super().__init__(Qt.Vertical, parent) self.mapView = MapView(QUrl.fromLocalFile(mapQmlFile)) self.waypointList = WaypointList(self.mapView.wpModel.allWaypoints, parent) self.uas = None self.horizonLine = -1 self.defaultLatitude = 30.0 self.editWPpopup = [] self.textMessageLogFile = None # log of messages displayed on messageLabel container = QWidget.createWindowContainer(self.mapView) container.setMinimumSize(self.mapView.minimumSize()) container.setMaximumSize(self.mapView.maximumSize()) container.setFocusPolicy(Qt.TabFocus) container.sizePolicy().setVerticalStretch(3) self.mapView.restorePreviousView() self.mapView.wpModel.createWaypointAction.connect(self.createWaypointEvent) self.mapView.updateWaypointCoordinateEvent.connect(self.moveWaypointEvent) self.mapView.moveHomeEvent.connect(self.updateHomeLocationEvent) self.mapView.selectWaypointForAction.connect(self.waypointList.highlightWaypoint) self.waypointList.editWaypoint.connect(self.showEditWaypointWindow) self.waypointList.deleteWaypoint.connect(self.removeWaypoint) self.waypointList.preDeleteWaypoint.connect(self.markWaypointForRemoval) self.waypointList.cancelDeleteWaypoint.connect(self.unmarkWaypointNoRemoval) self.waypointList.afterWaypointEdited.connect(self.acceptWaypointEdit) self.actionPanel = QWidget(self) # Upload/Refresh buttons self.loadWaypoints = QPushButton('Load from UAV') self.uploadWaypoints = QPushButton('Upload to UAV') self.messageLabel = QLabel('Disconnected') self.__setupTextMessageLogging() self.loadWaypoints.clicked.connect(self.loadWaypointsFromUAV) self.uploadWaypoints.clicked.connect(self.uploadWaypointsToUAV) panelLayput = QHBoxLayout() panelLayput.setSpacing(0) panelLayput.addWidget(self.messageLabel, 0, Qt.AlignLeft) panelLayput.addStretch(1) panelLayput.addWidget(self.loadWaypoints, 0, Qt.AlignRight) panelLayput.addWidget(self.uploadWaypoints, 0, Qt.AlignRight) self.actionPanel.setLayout(panelLayput) self.lowerPanel = QWidget(self) # WP list and action panel lowerLayout = QVBoxLayout() lowerLayout.setSpacing(0) lowerLayout.addWidget(self.waypointList) lowerLayout.addWidget(self.actionPanel) self.lowerPanel.setLayout(lowerLayout) self.lowerPanel.sizePolicy().setVerticalStretch(1) self.addWidget(container) self.addWidget(self.lowerPanel) def setActiveUAS(self, uas): uas.updateGlobalPositionSignal.connect(self.mapView.updateDroneLocation) uas.updateGPSStatusSignal.connect(self.mapView.updateDroneLocationUncertainty) self.uas = uas def __setupTextMessageLogging(self): tconf = UserData.getInstance().getUserDataEntry(UD_TELEMETRY_KEY) if tconf != None: name = 'MAV_{}.log'.format(int(time.time() * 1000)) self.textMessageLogFile = open(os.path.join(tconf[UD_TELEMETRY_LOG_FOLDER_KEY], name), 'w') def displayTextMessage(self, msg): if self.textMessageLogFile != None: self.textMessageLogFile.write('[{}] {}\n'.format(time.strftime('%d %b %Y %H:%M:%S', time.localtime()), msg)) self.messageLabel.setText(msg) def uploadWaypointsToUAV(self): cfm = QMessageBox.question(self.window(), 'Confirm upload', 'Are you sure to send waypoints to UAV? All onboard waypoints will be replaced.', QMessageBox.Yes, QMessageBox.No) if cfm == QMessageBox.Yes: self.uploadWaypointsToUAVEvent.emit(self.mapView.wpModel.allWaypoints) def loadWaypointsFromUAV(self): cfm = QMessageBox.question(self.window(), 'Confirm reload', 'Are you sure to reload waypoints from UAV? All current waypoints will be replaced.', QMessageBox.Yes, QMessageBox.No) if cfm == QMessageBox.Yes: print('load WP from UAV') self.downloadWaypointsFromUAVSignal.emit() def moveWaypointEvent(self, wpIdx, toWp: QGeoCoordinate): # print('[WP] move {} to ({}, {})'.format(wpIdx, toWp.latitude(), toWp.longitude())) self.mapView.wpModel.updateWaypointCoordinate(wpIdx, toWp) self.mapView.map.waypointChanged.emit(wpIdx, toWp.latitude(), toWp.longitude()) self.waypointList.moveWaypoint(wpIdx, toWp) def updateHomeLocationEvent(self, home: QGeoCoordinate): # print('update home loc: {}, {}'.format(home.latitude(), home.longitude())) self.mapView.map.moveHomeToCoordinate(home.latitude(), home.longitude()) self.waypointList.updateHomeLocation(home) def showEditWaypointWindow(self, wp: Waypoint): # print('edit wp#{0}'.format(wp.rowNumber)) popup = WaypointEditWindowFactory.createWaypointEditWindow(wp) self.editWPpopup.append(popup) popup.updateWaypoint.connect(self.acceptWaypointEdit) popup.show() def acceptWaypointEdit(self, wp: Waypoint): # print('edited WP:', wp) self.waypointList.updateWaypoint(wp) # sent new wp to map polyline self.mapView.wpModel.refreshWaypoint(wp) self.mapView.map.waypointChanged.emit(wp.rowNumber, wp.latitude, wp.longitude) def removeWaypoint(self, wp: Waypoint): # print('delete wp#{0}'.format(wp.rowNumber)) self.mapView.wpModel.removeWaypoint(wp) self.mapView.map.waypointRemoved.emit(wp.rowNumber) def createWaypointEvent(self, wp: Waypoint): # print('[new] create WP: ({0}, {1}) at {2}'.format(wp.latitude, wp.longitude, wp.altitude)) self.waypointList.addWaypoint(wp) def markWaypointForRemoval(self, wp: Waypoint): self.mapView.wpModel.markWaypoint(wp) def unmarkWaypointNoRemoval(self, wp: Waypoint): self.mapView.wpModel.unmarkWaypoint(wp) def setAllWaypoints(self, wpList): self.mapView.map.allPolylineRemoved.emit() self.waypointList.removeAllRows() self.mapView.wpModel.removeAllWaypoint() for wp in wpList: self.mapView.wpModel.createWaypoint(wp.latitude, wp.longitude) self.mapView.map.waypointCreated.emit(wp.latitude, wp.longitude) <file_sep>/src/gcs/instruments/compass.py import math from PyQt5.QtCore import Qt from PyQt5.QtSvg import QGraphicsSvgItem, QSvgRenderer from PyQt5.QtWidgets import (QGraphicsItem, QGraphicsScene, QGraphicsView, QVBoxLayout, QWidget) from utils import unused class Compass(QWidget): def __init__(self, parent): super().__init__(parent) self.uas = None svgRenderer = QSvgRenderer('res/compass.svg') self.compass = QGraphicsSvgItem() self.compass.setSharedRenderer(svgRenderer) self.compass.setCacheMode(QGraphicsItem.NoCache) self.compass.setElementId('needle') center = self.compass.boundingRect().center() self.compass.setTransformOriginPoint(center.x(), center.y()) bkgnd = QGraphicsSvgItem() bkgnd.setSharedRenderer(svgRenderer) bkgnd.setCacheMode(QGraphicsItem.NoCache) bkgnd.setElementId('background') self.compass.setPos(bkgnd.boundingRect().width() / 2 - self.compass.boundingRect().width() / 2, bkgnd.boundingRect().height() / 2 - self.compass.boundingRect().height() / 2) self.compass.setTransformOriginPoint(self.compass.boundingRect().width() / 2, self.compass.boundingRect().height() / 2) fregnd = QGraphicsSvgItem() fregnd.setSharedRenderer(svgRenderer) fregnd.setCacheMode(QGraphicsItem.NoCache) fregnd.setElementId('foreground') scene = QGraphicsScene() scene.addItem(bkgnd) scene.addItem(self.compass) scene.addItem(fregnd) scene.setSceneRect(bkgnd.boundingRect()) view = QGraphicsView(scene) view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) layout = QVBoxLayout() layout.addWidget(view) super().setLayout(layout) def setHeading(self, hdr): if math.isnan(hdr) == False: hdr *= 180.0 / math.pi self.compass.setRotation(360.0 - hdr) def updateAttitude(self, sourceUAS, timestamp, roll, pitch, yaw): unused(sourceUAS, timestamp, roll, pitch) self.setHeading(yaw) def setActiveUAS(self, uas): uas.updateAttitudeSignal.connect(self.updateAttitude) self.uas = uas <file_sep>/src/gcs/adsb.py import socket import time import subprocess import io import os from PyQt5.QtCore import (QAbstractListModel, QByteArray, QModelIndex, Qt, QThread, QVariant, pyqtSignal) from PyQt5.QtPositioning import QGeoCoordinate # https://github.com/kanflo/ADS-B-funhouse from sbs1 import SBS1Message from utils import unused class AircraftsModel(QAbstractListModel): positionRole = Qt.UserRole + 1 headingRole = Qt.UserRole + 2 callsignRole = Qt.UserRole + 3 def __init__(self, parent = None): super().__init__(parent) self.allAircrafts = [] def rowCount(self, parent=QModelIndex()): unused(parent) return len(self.allAircrafts) def __findByICAO(self, icao): for i in range(self.rowCount()): if self.allAircrafts[i].icao24 == icao: return i return -1 def updateAircraft(self, aircraft: SBS1Message): i = self.__findByICAO(aircraft.icao24) if i >= 0: idx = self.index(i) self.allAircrafts[i] = aircraft self.dataChanged.emit(idx, idx) def addAircraft(self, aircraft: SBS1Message): idx = self.rowCount() self.beginInsertRows(QModelIndex(), idx, idx) self.allAircrafts.append(aircraft) self.endInsertRows() def removeAircraft(self, aircraft: SBS1Message): i = self.__findByICAO(aircraft.icao24) if i >= 0: self.beginRemoveRows(QModelIndex(), i, i) del self.allAircrafts[i] self.endRemoveRows() def data(self, index, role=Qt.DisplayRole): idx = index.row() if idx < 0 or idx > len(self.allAircrafts) - 1: return QVariant() if role == AircraftsModel.positionRole: if self.allAircrafts[idx].lat and self.allAircrafts[idx].lon and self.allAircrafts[idx].altitude: # 3D position, altitude is displayed next to aircraft icon # Altitude from dump1090 is in feet, convert to meters by default altitudeInMeters = self.allAircrafts[idx].altitude * 0.3048 return QVariant(QGeoCoordinate(self.allAircrafts[idx].lat, self.allAircrafts[idx].lon, altitudeInMeters)) if self.allAircrafts[idx].lat and self.allAircrafts[idx].lon: # 2D position, 'Unknown Altitude' is displayed next to aircraft icon return QVariant(QGeoCoordinate(self.allAircrafts[idx].lat, self.allAircrafts[idx].lon)) return QVariant(QGeoCoordinate()) if role == AircraftsModel.headingRole: if self.allAircrafts[idx].lat and self.allAircrafts[idx].lon: if self.allAircrafts[idx].track: return QVariant(self.allAircrafts[idx].track) return QVariant(0) if role == AircraftsModel.callsignRole: if self.allAircrafts[idx].lat and self.allAircrafts[idx].lon: if self.allAircrafts[idx].callsign: return QVariant(self.allAircrafts[idx].callsign) # Display ICAO address when callsign is unavailable return QVariant('x{}'.format(self.allAircrafts[idx].icao24)) return QVariant() def flags(self, index): unused(index) return Qt.NoItemFlags def roleNames(self): return { AircraftsModel.positionRole : QByteArray(b'position'), AircraftsModel.headingRole : QByteArray(b'heading'), AircraftsModel.callsignRole : QByteArray(b'callsign') } class ADSBSource(QThread): aircraftCreateSignal = pyqtSignal(object) aircraftUpdateSignal = pyqtSignal(object) aircraftDeleteSignal = pyqtSignal(object) def __init__(self, parent = None): super().__init__(parent) self.running = True self.param = None def run(self): self.doLazyInit() while self.running: self.periodicalTask() self.cleanupTask() def stopADSB(self): self.running = False def lazyInit(self, param): self.param = param def doLazyInit(self): pass def periodicalTask(self): pass def cleanupTask(self): pass def getConfigurationParameterKey(self): return '' @staticmethod def getAvailableADSBSources(): return [ Dump1090NetClient(), Dump1090NetLocal() ] class Dump1090NetClient(ADSBSource): DEFAULT_TIMEOUT = 10 def __init__ (self, host = None, port = 0, parent = None): super().__init__(parent) self.aircrafts = {} self.sckt = None self.timeout = Dump1090NetClient.DEFAULT_TIMEOUT # default timeout, 10 seconds self.lazyInit({'HOST' : host, 'PORT' : port, 'TIMEOUT' : self.timeout}) def doLazyInit(self): host = self.param['HOST'] port = int(self.param['PORT']) if host != None and 0 < port < 65536: try: self.sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sckt.connect((host, port)) # The TIMEOUT parameter is optional self.timeout = int(self.param['TIMEOUT']) if self.timeout <= 0: self.timeout = self.DEFAULT_TIMEOUT except ConnectionRefusedError: self.sckt = None print('Failed to connect to Dump1090 {}:{}'.format(host, port)) except ValueError: pass def periodicalTask(self): if self.sckt != None: self.__receiveLatestData() self.__removeInactiveData() def __receiveLatestData(self): line = self.sckt.recv(1024) if line != b'': msg = SBS1Message(line) if msg.isValid: msg.loggedDate = time.time() # re-use loggedDate field if msg.icao24 in self.aircrafts: self.__updateMessageFields(self.aircrafts[msg.icao24], msg) self.aircraftUpdateSignal.emit(self.aircrafts[msg.icao24]) else: self.aircrafts[msg.icao24] = msg self.aircraftCreateSignal.emit(self.aircrafts[msg.icao24]) def __removeInactiveData(self): timeNow = time.time() toRemove = [] for icao, aircraft in self.aircrafts.items(): if timeNow - self.timeout > aircraft.loggedDate: toRemove.append(icao) self.aircraftDeleteSignal.emit(aircraft) for rm in toRemove: del self.aircrafts[rm] def __updateMessageFields(self, currMsg, newMsg): currMsg.messageType = currMsg.messageType if newMsg.messageType == None else newMsg.messageType currMsg.transmissionType = currMsg.transmissionType if newMsg.transmissionType == None else newMsg.transmissionType currMsg.sessionID = currMsg.sessionID if newMsg.sessionID == None else newMsg.sessionID currMsg.aircraftID = currMsg.aircraftID if newMsg.aircraftID == None else newMsg.aircraftID currMsg.flightID = currMsg.flightID if newMsg.flightID == None else newMsg.flightID currMsg.generatedDate = currMsg.generatedDate if newMsg.generatedDate == None else newMsg.generatedDate currMsg.loggedDate = currMsg.loggedDate if newMsg.loggedDate == None else newMsg.loggedDate currMsg.callsign = currMsg.callsign if newMsg.callsign == None else newMsg.callsign currMsg.altitude = currMsg.altitude if newMsg.altitude == None else newMsg.altitude currMsg.groundSpeed = currMsg.groundSpeed if newMsg.groundSpeed == None else newMsg.groundSpeed currMsg.track = currMsg.track if newMsg.track == None else newMsg.track currMsg.lat = currMsg.lat if newMsg.lat == None else newMsg.lat currMsg.lon = currMsg.lon if newMsg.lon == None else newMsg.lon currMsg.verticalRate = currMsg.verticalRate if newMsg.verticalRate == None else newMsg.verticalRate currMsg.squawk = currMsg.squawk if newMsg.squawk == None else newMsg.squawk currMsg.alert = currMsg.alert if newMsg.alert == None else newMsg.alert currMsg.emergency = currMsg.emergency if newMsg.emergency == None else newMsg.emergency currMsg.spi = currMsg.spi if newMsg.spi == None else newMsg.spi currMsg.onGround = currMsg.onGround if newMsg.onGround == None else newMsg.onGround def cleanupTask(self): self.sckt.close() def getConfigurationParameterKey(self): return 'DUMP1090SBS1' class Dump1090NetLocal(Dump1090NetClient): def __init__(self, dump1090BinPath = None, parent = None): super().__init__(parent) self.isBiasTeeSupported = False self.binCheckPass = False self.receiverProcess = None self.lazyInit({ 'DUMP1090_BIN' : dump1090BinPath, 'DEVICE_IDX' : 0, 'SBS_PORT' : 30003, 'TIMEOUT' : self.DEFAULT_TIMEOUT, 'BIAS_TEE' : False }) def doLazyInit(self): print(self.param) self.__checkDump1090Binary() if self.binCheckPass: self.__startDump1090() self.param['PORT'] = self.param['SBS_PORT'] self.param['HOST'] = 'localhost' super().doLazyInit() def __checkDump1090Binary(self): try: ps = subprocess.run([self.param['DUMP1090_BIN'], '--help'], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) if ps.returncode == 0: self.binCheckPass = True texts = io.StringIO(ps.stdout.decode('utf-8')) for text in texts: if text.startswith('--enable-bias-tee'): # Check if dump1090 supports setting bias T in RTL-SDR # Enabling bias T with supported RTL-SDR receiver and external # LNA will significantly increase range # Source: https://github.com/wangyeee/dump1090/tree/minigcs_integration # Receiver: https://www.rtl-sdr.com/rtl-sdr-blog-v-3-dongles-user-guide # LNA: https://www.rtl-sdr.com/new-product-rtl-sdr-blog-1090-mhz-ads-b-lna self.isBiasTeeSupported = True except FileNotFoundError: print('DUMP1090 not installed.') def __startDump1090(self): # dump1090 --device-index <DEVICE_IDX> --net --net-sbs-port <SBS_PORT> --enable-bias-tee cmds = [self.param['DUMP1090_BIN']] cmds.append('--device-index') cmds.append(str(self.param['DEVICE_IDX'])) cmds.append('--net') cmds.append('--net-sbs-port') cmds.append(str(self.param['SBS_PORT'])) if self.isBiasTeeSupported and self.param['BIAS_TEE']: cmds.append('--enable-bias-tee') self.receiverProcess = subprocess.Popen(cmds, stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL, cwd = os.path.dirname(self.param['DUMP1090_BIN'])) def getConfigurationParameterKey(self): return 'DUMP1090SBS1_LOCAL' def cleanupTask(self): super().cleanupTask() if self.receiverProcess != None: self.receiverProcess.kill() <file_sep>/src/gcs/instruments/plotter.py from time import time from PyQt5.QtChart import QChart, QChartView, QSplineSeries, QValueAxis from PyQt5.QtCore import Qt, QVariant, pyqtSignal from PyQt5.QtGui import QPainter from PyQt5.QtWidgets import (QSplitter, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget, QSizePolicy) from utils import unused from UserData import UserData UD_PLOTTER_WINDOW_KEY = 'PLOTTER' UD_PLOTTER_WINDOW_HEIGHT_KEY = 'WINDOW_HEIGHT' UD_PLOTTER_WINDOW_WIDTH_KEY = 'WINDOW_WIDTH' class PlotterPanel(QChart): IGNORED_ATTRIBUTES = ['time_usec', 'time_boot_ms'] def __init__(self, parent = None): super().__init__(parent) self.layout().setContentsMargins(0, 0, 0, 0) self.xRange = (0, 1) self.yRange = (0, 1) self.axisX = QValueAxis() self.axisY = QValueAxis() self.axisX.setRange(self.xRange[0], self.xRange[1]) self.axisY.setRange(self.yRange[0], self.yRange[1]) # name(msg_type.attr) = QSplineSeries self.data = {} self.visibleData = {} self.addAxis(self.axisX, Qt.AlignBottom) self.addAxis(self.axisY, Qt.AlignLeft) self.time0 = 0 self.extraYScale = 0.2 def appendMAVLinkMessage(self, msg): # print('Add msg:', msg) tm = self.__getMessageTime(msg) for attr in msg.get_fieldnames(): if attr not in PlotterPanel.IGNORED_ATTRIBUTES: k = '{}.{}'.format(msg.get_type(), attr) self.appendData(k, msg.format_attr(attr), tm) def appendData(self, key, data, msgTime): if key not in self.data: self.data[key] = QSplineSeries() self.data[key].setName(key) ser = self.data[key] ser.append(msgTime, data) if key in self.visibleData: r0 = False if msgTime < self.xRange[0]: self.xRange = (msgTime, self.xRange[1]) r0 = True elif msgTime > self.xRange[1]: self.xRange = (self.xRange[0], msgTime) r0 = True if r0: self.axisX.setRange(self.xRange[0], self.xRange[1]) r0 = False if data < self.yRange[0]: self.yRange = (data, self.yRange[1]) r0 = True elif data > self.yRange[1]: self.yRange = (self.yRange[0], data) r0 = True if r0: # add extra space for Y axis ext = self.extraYScale * (self.yRange[1] - self.yRange[0]) self.yRange = (int(self.yRange[0] - ext), int(self.yRange[1] + ext)) self.axisY.setRange(self.yRange[0], self.yRange[1]) def toggleDataVisibility(self, key, disp): if disp == 0: if key in self.visibleData: del self.visibleData[key] self.removeSeries(self.data[key]) self.__resetYRange() else: if key not in self.visibleData: self.visibleData[key] = self.data[key] self.addSeries(self.data[key]) self.data[key].attachAxis(self.axisX) self.data[key].attachAxis(self.axisY) def __resetYRange(self): self.yRange = (0, 1) self.axisY.setRange(self.yRange[0], self.yRange[1]) def __getMessageTime(self, msg): unused(msg) if self.time0 == 0: self.time0 = int(time()) * 50 return 1 return int(time()) * 50 - self.time0 class PlotItemMenu(QWidget): messageKeyRole = Qt.UserRole + 1 plotDataSignal = pyqtSignal(object, int) def __init__(self, parent = None): super().__init__(parent) self.setLayout(QVBoxLayout()) self.tree = QTreeWidget() self.tree.setHeaderHidden(True) self.tree.setColumnCount(1) self.tree.itemChanged.connect(self.__toggleDataPlot) self.layout().setContentsMargins(0, 0, 0, 0) self.layout().addWidget(self.tree) self.rootItems = [] def addMAVLinkMessage(self, msg): tp = msg.get_type() if tp not in self.rootItems: self.rootItems.append(tp) rt = QTreeWidgetItem(self.tree) rt.setText(0, tp) for attr in msg.get_fieldnames(): if attr not in PlotterPanel.IGNORED_ATTRIBUTES: chld = QTreeWidgetItem() chld.setText(0, attr) chld.setFlags(chld.flags() | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable) chld.setCheckState(0, Qt.Unchecked) chld.setData(0, PlotItemMenu.messageKeyRole, QVariant('{}.{}'.format(tp, attr))) rt.addChild(chld) self.tree.addTopLevelItem(rt) def __toggleDataPlot(self, item, col): self.plotDataSignal.emit(item.data(col, PlotItemMenu.messageKeyRole), item.checkState(col)) class PlotterWindow(QSplitter): def __init__(self, title, parent = None): super().__init__(Qt.Horizontal, parent) self.param = UserData.getInstance().getUserDataEntry(UD_PLOTTER_WINDOW_KEY, {}) self.setWindowTitle(title) self.plotMessages = { 'RAW_IMU' : None, 'SCALED_IMU' : None, 'GPS_RAW_INT' : None, 'ATTITUDE' : None, 'SCALED_PRESSURE' : None } self.chart = PlotterPanel() self.chartView = QChartView(self.chart) self.chartView.setRenderHint(QPainter.Antialiasing) self.plotControl = PlotItemMenu() self.plotControl.plotDataSignal.connect(self.chart.toggleDataVisibility) spLeft = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) spLeft.setHorizontalStretch(1) self.plotControl.setSizePolicy(spLeft) spRight = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) spRight.setHorizontalStretch(6) self.chartView.setSizePolicy(spRight) self.addWidget(self.plotControl) self.addWidget(self.chartView) if UD_PLOTTER_WINDOW_HEIGHT_KEY in self.param and UD_PLOTTER_WINDOW_WIDTH_KEY in self.param: self.resize(self.param[UD_PLOTTER_WINDOW_WIDTH_KEY], self.param[UD_PLOTTER_WINDOW_HEIGHT_KEY]) def handleMavlinkMessage(self, msg): if self.isVisible(): if msg.get_type() in self.plotMessages: self.plotControl.addMAVLinkMessage(msg) self.chart.appendMAVLinkMessage(msg) def closeEvent(self, event): s = self.size() self.param[UD_PLOTTER_WINDOW_HEIGHT_KEY] = s.height() self.param[UD_PLOTTER_WINDOW_WIDTH_KEY] = s.width() super().closeEvent(event) <file_sep>/src/gcs/instruments/barometer.py from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtGui import QColor, QFont, QTextOption, QTransform from PyQt5.QtSvg import QGraphicsSvgItem, QSvgRenderer from PyQt5.QtWidgets import (QGraphicsItem, QGraphicsScene, QGraphicsTextItem, QGraphicsView, QGridLayout, QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget) from utils import unused class Barometer(QWidget): def __init__(self, parent): super().__init__(parent) self.uas = None svgRenderer = QSvgRenderer('res/barometer.svg') bkgnd = QGraphicsSvgItem() bkgnd.setSharedRenderer(svgRenderer) bkgnd.setCacheMode(QGraphicsItem.NoCache) bkgnd.setElementId('background') scene = QGraphicsScene() scene.addItem(bkgnd) scene.setSceneRect(bkgnd.boundingRect()) self.needle = QGraphicsSvgItem() self.needle.setSharedRenderer(svgRenderer) self.needle.setCacheMode(QGraphicsItem.NoCache) self.needle.setElementId('needle') self.needle.setParentItem(bkgnd) self.needle.setPos(bkgnd.boundingRect().width() / 2 - self.needle.boundingRect().width() / 2, bkgnd.boundingRect().height() / 2 - self.needle.boundingRect().height() / 2) self.needle.setTransformOriginPoint(self.needle.boundingRect().width() / 2, self.needle.boundingRect().height() / 2) # textElement = svgRenderer.boundsOnElement('needle-text') self.digitalBaro = QGraphicsTextItem() self.digitalBaro.setDefaultTextColor(QColor(255,255,255)) self.digitalBaro.document().setDefaultTextOption(QTextOption(Qt.AlignCenter)) self.digitalBaro.setFont(QFont('monospace', 13, 60)) self.digitalBaro.setParentItem(bkgnd) txm = QTransform() txm.translate(bkgnd.boundingRect().center().x(), bkgnd.boundingRect().height() - 1.5 * self.digitalBaro.document().size().height()) self.digitalBaro.setTransform(txm, False) view = QGraphicsView(scene) view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) layout = QVBoxLayout() layout.addWidget(view) self.setLayout(layout) self.setBarometer(1000) def setBarometer(self, hbar): deg = ((hbar - 950) * 3 + 210) % 360 self.needle.setRotation(deg) self.digitalBaro.setPlainText('{:.1f}'.format(hbar)) self.digitalBaro.adjustSize() self.digitalBaro.setX(0 - self.digitalBaro.textWidth() / 2) def updateAirPressure(self, sourceUAS, timestamp, absPressure, diffPressure, temperature): unused(sourceUAS, timestamp, diffPressure, temperature) self.setBarometer(absPressure) def setActiveUAS(self, uas): uas.updateAirPressureSignal.connect(self.updateAirPressure) self.uas = uas class BarometerConfigWindow(QWidget): updatePressureAltitudeReferenceSignal = pyqtSignal(float, float) # presRef, altiRef def __init__(self, presRef, altiRef, parent = None): super().__init__(parent) self.setWindowTitle('Pressure Altitude Reference') l = QGridLayout() row = 0 l.addWidget(QLabel('Pressure Reference'), row, 0, 1, 1) self.presRefField = QLineEdit(str(presRef)) l.addWidget(self.presRefField, row, 1, 1, 1) row += 1 l.addWidget(QLabel('Altitude Reference'), row, 0, 1, 1) self.altiRefField = QLineEdit(str(altiRef)) l.addWidget(self.altiRefField, row, 1, 1, 1) row += 1 self.cancelButton = QPushButton('Cancel') self.cancelButton.clicked.connect(self.close) l.addWidget(self.cancelButton, row, 0, 1, 1) self.okButton = QPushButton('OK') self.okButton.clicked.connect(self.__updatePressureAltitudeReference) l.addWidget(self.okButton, row, 1, 1, 1) self.setLayout(l) def __updatePressureAltitudeReference(self): try: presRef = float(self.presRefField.text()) altiRef = float(self.altiRefField.text()) self.updatePressureAltitudeReferenceSignal.emit(presRef, altiRef) except ValueError: pass self.close() <file_sep>/src/gcs/res/README.md The following two image files are from [TauLabs project](https://github.com/TauLabs/TauLabs) (original the OpenPilot project). Refer to `LICENSE.txt` for more details. 1. barometer.svg 2. compass.svg The font file `vera.ttf` is copied from [QGroundControl](http://qgroundcontrol.com) project. <file_sep>/src/gcs/parameters.py from pymavlink.mavutil import mavlink from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtWidgets import (QFileDialog, QHBoxLayout, QHeaderView, QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget) PARAM_VALUE_TYPE_NAMES = { mavlink.MAV_PARAM_TYPE_UINT8 : '8-bit unsigned integer', mavlink.MAV_PARAM_TYPE_INT8 : '8-bit signed integer', mavlink.MAV_PARAM_TYPE_UINT16 : '16-bit unsigned integer', mavlink.MAV_PARAM_TYPE_INT16 : '16-bit signed integer', mavlink.MAV_PARAM_TYPE_UINT32 : '32-bit unsigned integer', mavlink.MAV_PARAM_TYPE_INT32 : '32-bit signed integer', mavlink.MAV_PARAM_TYPE_UINT64 : '64-bit unsigned integer', mavlink.MAV_PARAM_TYPE_INT64 : '64-bit signed integer', mavlink.MAV_PARAM_TYPE_REAL32 : '32-bit floating-point', mavlink.MAV_PARAM_TYPE_REAL64 : '64-bit floating-point' } PARAM_TYPE_RAW_ROLE = Qt.UserRole + 1 class ParameterList(QTableWidget): def __init__(self, paramList, parent = None): super().__init__(parent) self.paramNameIndexCache = {} self.allParams = {} self.changedParams = [] self.paramList = sorted(paramList, key = lambda p: p.param_id) print('Init param list with {} params.'.format(len(self.paramList))) self.createTableHeader() self.createTableBody(self.paramList) def createTableHeader(self): ''' [param_index], param_id, param_value, param_type ''' hdr = ['Name', 'Value', 'Type'] self.setColumnCount(len(hdr)) self.setHorizontalHeaderLabels(hdr) self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) def createTableBody(self, plist, correctCount = False): rowNumber = 0 paramCount = len(plist) self.setRowCount(paramCount) for param in plist: self.paramNameIndexCache[param.param_id] = rowNumber if correctCount: param.param_count = paramCount name = QTableWidgetItem(param.param_id) name.setFlags(name.flags() ^ Qt.ItemIsEditable) vstr = None if self._isIntegerType(param.param_type): vstr = str(int(param.param_value)) elif self._isFloatType(param.param_type): vstr = str(float(param.param_value)) else: vstr = str(param.param_value) value = QTableWidgetItem(vstr) pstr = None if param.param_type in PARAM_VALUE_TYPE_NAMES: pstr = PARAM_VALUE_TYPE_NAMES[param.param_type] else: pstr = 'UNKNOWN TYPE: {}'.format(param.param_type) ptype = QTableWidgetItem(pstr) ptype.setData(PARAM_TYPE_RAW_ROLE, int(param.param_type)) ptype.setFlags(ptype.flags() ^ Qt.ItemIsEditable) self.setItem(rowNumber, 0, name) self.setItem(rowNumber, 1, value) self.setItem(rowNumber, 2, ptype) rowNumber += 1 self.resizeRowsToContents() self.resizeColumnsToContents() def showChangedParametersOnly(self): while self.rowCount() > 0: # Remove current parameters, if any self.removeRow(0) self.createTableBody(self.changedParams, True) def collectTableBody(self): self.changedParams.clear() self.allParams.clear() changedParamIdx = 0 for rowNumber in range(self.rowCount()): name = self.item(rowNumber, 0).text() ptype = self.item(rowNumber, 2).data(PARAM_TYPE_RAW_ROLE) if self._isIntegerType(ptype): value = int(self.item(rowNumber, 1).text()) elif self._isFloatType(ptype): value = float(self.item(rowNumber, 1).text()) else: value = self.item(rowNumber, 1).text() self.allParams[name] = value oldVal = self._initValue(name) if oldVal != value and self.paramList[self.paramNameIndexCache[name]].param_type in PARAM_VALUE_TYPE_NAMES: # value of param_count will be corrected in showChangedParametersOnly() p = mavlink.MAVLink_param_value_message(name, value, ptype, 0, changedParamIdx) self.changedParams.append(p) changedParamIdx += 1 def _initValue(self, name): if name in self.paramNameIndexCache: return self.paramList[self.paramNameIndexCache[name]].param_value return 0.0 def _isIntegerType(self, ptype): return ptype in (mavlink.MAV_PARAM_TYPE_UINT8, mavlink.MAV_PARAM_TYPE_INT8, mavlink.MAV_PARAM_TYPE_UINT16, mavlink.MAV_PARAM_TYPE_INT16, mavlink.MAV_PARAM_TYPE_UINT32, mavlink.MAV_PARAM_TYPE_INT32, mavlink.MAV_PARAM_TYPE_UINT64, mavlink.MAV_PARAM_TYPE_INT64) def _isFloatType(self, ptype): return ptype in (mavlink.MAV_PARAM_TYPE_REAL32, mavlink.MAV_PARAM_TYPE_REAL64) class ParameterPanel(QWidget): uploadNewParametersSignal = pyqtSignal(object) # list of MAVLink_param_value_message def __init__(self, params, parent = None): super().__init__(parent) self.uploadUAVStep = 0 l = QVBoxLayout() self.paramList = ParameterList(params, parent) l.addWidget(self.paramList) self.actionPanel = QWidget() pLayout = QHBoxLayout() self.saveToFileButton = QPushButton('Save to file') pLayout.addWidget(self.saveToFileButton) self.saveToFileButton.clicked.connect(self.saveToFile) self.uploadButton = QPushButton('Upload to UAV >') pLayout.addWidget(self.uploadButton) self.uploadButton.clicked.connect(self.uploadToUAV) self.cancelButton = QPushButton('Cancel') pLayout.addWidget(self.cancelButton) self.cancelButton.clicked.connect(self.close) self.actionPanel.setLayout(pLayout) l.addWidget(self.actionPanel) self.setLayout(l) def uploadToUAV(self): if self.uploadUAVStep == 0: ## 'Upload to UAV' clicked self.paramList.collectTableBody() if (len(self.paramList.changedParams) == 0): QMessageBox.warning(self.window(), 'Warning', 'No changes have been made.', QMessageBox.Ok) return self.paramList.showChangedParametersOnly() self.uploadButton.setText('Confirm Upload') self.uploadUAVStep += 1 elif self.uploadUAVStep == 1: ## 'Confirm Upload' clicked self.uploadUAVStep = 0 self.uploadNewParametersSignal.emit(self.paramList.changedParams) self.close() def saveToFile(self): fileName = QFileDialog.getSaveFileName(self, 'Save Parameters', 'config.txt') self.paramList.collectTableBody() txt = open(fileName[0], 'w') for param, value in self.paramList.allParams.items(): txt.write('{} = {}\n'.format(param, value)) txt.close() self.close() <file_sep>/src/gcs/LocalGPS.py from pynmea2 import NMEAStreamReader from pynmea2.types.talker import GGA from PyQt5.QtCore import pyqtSignal, QThread from PyQt5.QtPositioning import QGeoCoordinate from serial import Serial from telemetry import ConnectionEditWindow, SerialConnectionEditTab class NMEAReceiver(QThread): locationUpdate = pyqtSignal(object) def __init__(self, port = None, baud = 9600): super().__init__() self.serialPort = Serial() self.running = False self.configureSerialPort(port, baud) def configureSerialPort(self, port, baud): self.serialPort.baudrate = baud self.serialPort.port = port def connect(self): self.serialPort.open() if self.serialPort.isOpen(): self.running = True self.start() def disconnect(self): self.running = False def run(self): streamreader = NMEAStreamReader() while self.running: data = self.serialPort.readline().decode('ASCII') if data.startswith('$GP'): for msg in streamreader.next(data): # print('{} {} {}'.format(msg_cnt, type(msg), msg)) if type(msg) is GGA: # print('location update: {}, {}'.format(msg.latitude, msg.longitude)) self.locationUpdate.emit(QGeoCoordinate(msg.latitude, msg.longitude)) if self.serialPort.isOpen(): self.serialPort.close() class GPSConfigurationWindow(ConnectionEditWindow): def __init__(self, parent = None): super().__init__(parent) self.connection = NMEAReceiver() self.setWindowTitle('GPS Configuration') def _createTabs(self): self.serialConnTab = SerialConnectionEditTab(initParams={}, parent=self) self.tabs.addTab(self.serialConnTab, 'Serial GPS Receiver') def _doConnect(self): currTab = self.tabs.currentWidget() port = currTab.portsDropDown.currentData() baud = currTab.baudDropDown.currentData() self.connection.configureSerialPort(port, int(baud)) self.connection.connect() self.close() <file_sep>/src/gcs/plugins/common.py from PyQt5.QtWidgets import QWidget, QGridLayout, QPushButton, QMessageBox, QPlainTextEdit from PyQt5.QtCore import pyqtSignal, Qt from pymavlink.mavutil import mavlink import time class AbstractControlPanel(QWidget): mavlinkTxSignal = pyqtSignal(object) # pass a mavlink message object def __init__(self, parent = None): super().__init__(parent) self.isConnected = False self.uas = None def tabName(self): return 'Tools' def processMavlinkMessage(self, msg): '''Will be invoked by other components.''' if msg != None: if msg.get_type() in self.registerMavlinkMessageListeners(): self.mavlinkMessageReceived(msg) def registerMavlinkMessageListeners(self): '''Each sub-class should return list of message types which will be passed to __mavlinkMessageReceived method.''' return [] def mavlinkMessageReceived(self, msg): # print('Error, sub-class must implement this method to process mavlink message:', msg) pass class GenericControlPanel(AbstractControlPanel): autoPilotRebootSignal = pyqtSignal() textMessageConsole = None __updateTextConsoleSignal = pyqtSignal(object) def __init__(self, parent = None): super().__init__(parent) l = QGridLayout() row = 0 self.rebootAutoPilotButton = QPushButton('Reboot AutoPilot') self.rebootAutoPilotButton.setStyleSheet('background-color: red') self.rebootAutoPilotButton.clicked.connect(self.__rebootAutoPilot) l.addWidget(self.rebootAutoPilotButton, row, 0, 1, 1, Qt.AlignLeft) row += 1 self.textMessageConsole = QPlainTextEdit(self) self.textMessageConsole.setReadOnly(True) self.textMessageConsole.document().setMaximumBlockCount(100) self.__updateTextConsoleSignal.connect(self.__textMessagePrint) l.addWidget(self.textMessageConsole, row, 0, 5, 5) self.setLayout(l) def tabName(self): return 'Mavlink' def registerMavlinkMessageListeners(self): return ['STATUSTEXT'] def mavlinkMessageReceived(self, msg): if msg.get_type() == 'STATUSTEXT': self.__updateTextConsoleSignal.emit(msg.text) def __textMessagePrint(self, msg: str): self.textMessageConsole.insertPlainText('{}: {}'.format(time.strftime('%H:%M:%S', time.localtime()), msg)) bar = self.textMessageConsole.verticalScrollBar() bar.setValue(bar.maximum()) def __rebootAutoPilot(self): if self.isConnected: cfm = QMessageBox.question(self.window(), 'Reboot AutoPilot', 'The autopilot will reboot, continue?', QMessageBox.Yes, QMessageBox.No) if cfm == QMessageBox.Yes: msg = mavlink.MAVLink_command_long_message(255, 0, mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0, 1, 0, 0, 0, 0, 0, 0) self.autoPilotRebootSignal.emit() # signal other component the reboot event self.mavlinkTxSignal.emit(msg) <file_sep>/src/gcs/instruments/statusPanel.py import sys from pymavlink.mavutil import mavlink from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtWidgets import (QApplication, QGridLayout, QLabel, QProgressBar, QPushButton, QWidget, QTabWidget, QVBoxLayout) from instruments.compass import Compass from instruments.barometer import Barometer from plugins.autoquad import AutoQuadControlPanel from plugins.paparazzi import PaparazziControlPanel from plugins.common import GenericControlPanel from telemetry import MAVLinkConnection, RadioControlTelemetryWindow from utils import unused GPS_FIX_LABELS = { mavlink.GPS_FIX_TYPE_NO_GPS : 'No GPS', mavlink.GPS_FIX_TYPE_NO_FIX : 'No fix', mavlink.GPS_FIX_TYPE_2D_FIX : '2D fix', mavlink.GPS_FIX_TYPE_3D_FIX : '3D fix', mavlink.GPS_FIX_TYPE_DGPS : 'DGPS/SBAS aided 3D fix', mavlink.GPS_FIX_TYPE_RTK_FLOAT : 'RTK 3D float', mavlink.GPS_FIX_TYPE_RTK_FIXED : 'RTK 3D fix', mavlink.GPS_FIX_TYPE_STATIC : 'Static fix', mavlink.GPS_FIX_TYPE_PPP : 'PPP 3D fix' } BATTERY_BAR_STYLE_TEMPLATE = 'QProgressBar::chunk {{background: "{0}"; \ border: 1px solid black;}}' class SystemStatusPanel(QWidget): connectToMAVLink = pyqtSignal() disconnectFromMAVLink = pyqtSignal() connectToLocalGPS = pyqtSignal() disconnectFromLocalGPS = pyqtSignal() def __init__(self, parent = None): super().__init__(parent) self.apControlPanels = {} self.tabs = QTabWidget(self) self.statusPanel = StatusSummaryPanel(self) self.tabs.addTab(self.statusPanel, 'Summary') self.compassPanel = Compass(self) self.tabs.addTab(self.compassPanel, 'Compass') self.barometerPanel = Barometer(self) self.tabs.addTab(self.barometerPanel, 'Barometer') self.genericControlPanel = GenericControlPanel() self.tabs.addTab(self.genericControlPanel, self.genericControlPanel.tabName()) self.apControlPanels[mavlink.MAV_AUTOPILOT_AUTOQUAD] = AutoQuadControlPanel() self.apControlPanels[mavlink.MAV_AUTOPILOT_PPZ] = PaparazziControlPanel() l = QVBoxLayout() l.addWidget(self.tabs) self.setLayout(l) def initializaMavlinkForControlPanels(self, mav: MAVLinkConnection): self.__linkTelemetryForControlPanel(self.genericControlPanel, mav) mav.externalMessageHandler.connect(self.__updateRCChannelValues) for ap in self.apControlPanels: self.__linkTelemetryForControlPanel(self.apControlPanels[ap], mav) def __updateRCChannelValues(self, msg): if msg.get_type() == 'RC_CHANNELS_RAW': self.statusPanel.rcTelemetryWindow.updateRCChannelValues(msg) def addAPControlPanel(self, apType): if apType in self.apControlPanels: t = self.apControlPanels[apType] self.tabs.addTab(t, t.tabName()) else: print('No control panel available for AP:', apType) def __linkTelemetryForControlPanel(self, panel, mav): mav.externalMessageHandler.connect(panel.processMavlinkMessage) panel.mavlinkTxSignal.connect(mav.sendMavlinkMessage) panel.uas = mav.uas panel.isConnected = True class StatusSummaryPanel(QWidget): def __init__(self, parent): super().__init__(parent) self.uas = None self.connectToMAVLink = parent.connectToMAVLink self.disconnectFromMAVLink = parent.disconnectFromMAVLink self.connectToLocalGPS = parent.connectToLocalGPS self.disconnectFromLocalGPS = parent.disconnectFromLocalGPS l = QGridLayout() row = 0 self.sysNameLbl = QLabel('System Status') l.addWidget(self.sysNameLbl, row, 0, 1, 3, Qt.AlignLeft) row += 1 self.armedLbl = QLabel('Disarmed') self.modeLbl = QLabel('Standby') self.gpsLbl = QLabel(GPS_FIX_LABELS[mavlink.GPS_FIX_TYPE_NO_GPS]) l.addWidget(self.armedLbl, row, 0, 1, 1, Qt.AlignLeft) l.addWidget(self.modeLbl, row, 1, 1, 1, Qt.AlignLeft) l.addWidget(self.gpsLbl, row, 2, 1, 1, Qt.AlignLeft) row += 1 l.addWidget(QLabel('Battery'), row, 0, 1, 1, Qt.AlignLeft) self.battBar = QProgressBar(self) self.battBar.setValue(0) self.battBar.setStyleSheet(BATTERY_BAR_STYLE_TEMPLATE.format('green')) l.addWidget(self.battBar, row, 1, 1, 1) self.battVoltLabel = QLabel('0.0V/0.0A') l.addWidget(self.battVoltLabel, row, 2, 1, 1) row += 1 self.radioBar = QProgressBar(self) self.radioBar.setValue(0) self.radioBar.setStyleSheet(BATTERY_BAR_STYLE_TEMPLATE.format('green')) l.addWidget(QLabel('Radio'), row, 0, 1, 1, Qt.AlignLeft) l.addWidget(self.radioBar, row, 1, 1, 1) self.radioTelemetryButton = QPushButton('Radio Telemetry') self.radioTelemetryButton.clicked.connect(self.__showRadioTelemetryWindow) l.addWidget(self.radioTelemetryButton, row, 2, 1, 1) row += 1 l.setRowStretch(row, 1) row += 1 self.editParameterButton = QPushButton('Edit Parameters') self.editParameterButton.setEnabled(False) l.addWidget(self.editParameterButton, row, 0, 1, 1, Qt.AlignLeft) self.connectButton = QPushButton('Connect') self.connectLabelShown = True self.connectButton.clicked.connect(self.toggleButtonLabel) l.addWidget(self.connectButton, row, 1, 1, 1, Qt.AlignCenter) self.localGPSButton = QPushButton('Local GPS') self.gpsLabelShown = True self.localGPSButton.clicked.connect(self.toggleGPSButtonLabel) l.addWidget(self.localGPSButton, row, 2, 1, 1, Qt.AlignLeft) self.showHUDButton = QPushButton('HUD') l.addWidget(self.showHUDButton, row, 3, 1, 1, Qt.AlignLeft) l.setColumnStretch(1, 1) self.rcTelemetryWindow = RadioControlTelemetryWindow() self.setLayout(l) def setActiveUAS(self, uas): uas.updateBatterySignal.connect(self.updateBatteryStatus) uas.updateGPSStatusSignal.connect(self.updateGPSFixStatus) self.uas = uas def updateBatteryStatus(self, sourceUAS, timestamp, voltage, current, remaining): unused(sourceUAS, timestamp) self.battVoltLabel.setText('{:.1f}V/{:.1f}A'.format(voltage, abs(current))) self.battBar.setValue(remaining) if remaining >= 60: self.battBar.setStyleSheet(BATTERY_BAR_STYLE_TEMPLATE.format('green')) elif remaining >= 30: self.battBar.setStyleSheet(BATTERY_BAR_STYLE_TEMPLATE.format('yellow')) else: self.battBar.setStyleSheet(BATTERY_BAR_STYLE_TEMPLATE.format('red')) def updateGPSFixStatus(self, sourceUAS, timestamp, fix, hdop, vdop, nosv, hacc, vacc, velacc, hdgacc): unused(sourceUAS, timestamp, hdop, vdop, nosv, hacc, vacc, velacc, hdgacc) if fix in GPS_FIX_LABELS: self.gpsLbl.setText(GPS_FIX_LABELS[fix]) else: self.gpsLbl.setText(GPS_FIX_LABELS[mavlink.GPS_FIX_TYPE_NO_FIX]) def resetConnectionButton(self): self.connectButton.setText('Connect') self.connectButton.setEnabled(True) self.editParameterButton.setEnabled(False) self.connectLabelShown = True def toggleButtonLabel(self, isConnected = False): if self.connectLabelShown: if isConnected: self.connectLabelShown = False self.connectButton.setText('Disconnect') self.connectButton.setEnabled(True) self.editParameterButton.setEnabled(True) else: self.connectToMAVLink.emit() self.connectButton.setEnabled(False) else: self.resetConnectionButton() self.disconnectFromMAVLink.emit() def toggleGPSButtonLabel(self, isConnected = False): if self.gpsLabelShown: self.connectToLocalGPS.emit() if isConnected: self.gpsLabelShown = False self.localGPSButton.setText('Disconnect GPS') else: self.disconnectFromLocalGPS.emit() self.gpsLabelShown = True self.localGPSButton.setText('Local GPS') def __showRadioTelemetryWindow(self): ''' Display realtime values for each radio channel, this could be used for pre-flight checks ''' self.rcTelemetryWindow.show() # test if __name__ == "__main__": app = QApplication(sys.argv) ssp = SystemStatusPanel() ssp.show() sys.exit(app.exec_()) <file_sep>/README.md # MiniGCS MiniGCS is a handheld MAVLink compatible drone control station This project is in early stage, contents will be added later ## GCS Software The GCS is a PyQT GUI application features realtime telemetry monitoring and mission planning. **Feature List** 1. Generic MAVLink support. 2. Primary flight display. 3. System status panel and control. 4. Waypoint based mission planning. 5. Autopilot specific control panels. 6. Flight map with ADS-B overlay. **Screenshot** ![GCS screenshot](./src/gcs/GCS_ScreenShot.png) <file_sep>/src/gcs/instruments/ControlCheck.py from PyQt5.QtWidgets import QWidget, QSlider, QHBoxLayout, QVBoxLayout, QLabel, QPushButton, QMessageBox from PyQt5.QtCore import Qt, pyqtSignal from time import time from pymavlink import mavutil class OutputSlider(QWidget): outputUpdateSignal = pyqtSignal(int, int) # seq, val def __init__(self, seq, minVal, maxVal, parent = None): super().__init__(parent) self.seq = seq self.setLayout(QHBoxLayout()) self.outputUpdateMinInterval = 100 # ms self.lastUpdateTime = time() * 1000 self.slider = QSlider(Qt.Horizontal) self.slider.setRange(minVal, maxVal) self.valueLabel = QLabel(str(minVal)) self.slider.valueChanged.connect(self.setOutputValue) self.slider.sliderReleased.connect(lambda: self.setOutputValue(self.slider.minimum() - 1)) self.slider.valueChanged.connect(lambda val: self.valueLabel.setText(str(val))) self.layout().addWidget(QLabel('Output {}'.format(seq))) self.layout().addWidget(self.slider) self.layout().addWidget(self.valueLabel) def setOutputValue(self, val): if val < self.slider.minimum(): self.outputUpdateSignal.emit(self.seq, self.slider.value()) else: now = time() * 1000 if now - self.lastUpdateTime > self.outputUpdateMinInterval: self.outputUpdateSignal.emit(self.seq, val) self.lastUpdateTime = now class ServoOutputCheckWindow(QWidget): mavlinkMotorTestSignal = pyqtSignal(object) # set servo msg def __init__(self, opNumber, parent = None): super().__init__(parent) self.setWindowTitle('Servo Output Check') self.setLayout(QVBoxLayout()) self.outputEnable = False self.outputPanels = [] for i in range(opNumber): op = OutputSlider(i + 1, 1000, 2000) op.outputUpdateSignal.connect(self.processSliderOutput) self.outputPanels.append(op) self.layout().addWidget(op) self.outputControlPanel = QWidget() self.outputControlPanel.setLayout(QHBoxLayout()) self.armButton = QPushButton('Arm') self.armButton.setStyleSheet('background-color: red') self.armButton.clicked.connect(self.__armOutput) self.closeButton = QPushButton('Close') self.closeButton.clicked.connect(self.__close) self.outputControlPanel.layout().addWidget(self.armButton) self.outputControlPanel.layout().addStretch(1) self.outputControlPanel.layout().addWidget(self.closeButton) self.layout().addWidget(self.outputControlPanel) def processSliderOutput(self, seq, val): if self.outputEnable: msg = mavutil.mavlink.MAVLink_command_long_message(255, 255, mavutil.mavlink.MAV_CMD_DO_SET_SERVO, 0, seq, val, 0, 0, 0, 0, 0) self.mavlinkMotorTestSignal.emit(msg) def showEvent(self, event): super().showEvent(event) self.__disableOutput() def hideEvent(self, event): super().hideEvent(event) self.__disableOutput() def __armOutput(self): if self.outputEnable: self.__disableOutput() else: cfm = QMessageBox.question(self.window(), 'Confirm', 'Are you sure to enable outputs?', QMessageBox.Yes, QMessageBox.No) if cfm == QMessageBox.Yes: self.outputEnable = True self.armButton.setText('Disarm') def __disableOutput(self): self.outputEnable = False self.armButton.setText('Arm') def __close(self): self.__disableOutput() self.close() <file_sep>/src/gcs/uas.py from abc import abstractmethod from math import log, sqrt from PyQt5.QtCore import QObject, pyqtSignal from pymavlink.mavutil import mavlink from utils import unused from UserData import UserData UINT16_MAX = 0xFFFF MAVLINK_LXTITUDE_SCALE = 1E7 UNIVERSAL_GAS_CONSTANT = 8.3144598 # J/(mol·K) MOLAR_MASS = 0.0289644 # kg/mol gravity = 9.80665 # m/s2 DEFAULT_ALTITUDE_REFERENCE = 0.0 # METER DEFAULT_PRESSURE_REFERENCE = 101325.0 # PA ZERO_KELVIN = -273.15 # degree UD_UAS_CONF_KEY = 'UAS' UD_UAS_CONF_GPS_SRC_KEY = 'GPS_SRC' class UASInterface(QObject): updateAttitudeSignal = pyqtSignal(object, int, float, float, float) # uas, timestamp, roll, pitch, yaw updateBatterySignal = pyqtSignal(object, int, float, float, float) # uas, timestamp, voltage, current, percent updateGlobalPositionSignal = pyqtSignal(object, int, float, float, float) # uas, timestamp, lat, lng, altitude updateGPSStatusSignal = pyqtSignal(object, int, int, int, int, int, int, int, int, int) # uas, timestamp, fix type, HDOP, VDOP, satellites visible, h acc, v acc, vel acc, hdg acc updateAirSpeedSignal = pyqtSignal(object, int, float) # uas, timestamp, speed updateGroundSpeedSignal = pyqtSignal(object, int, float) # uas, timestamp, speed updateVelocitySignal = pyqtSignal(object, int, float, float, float) # uas, timestamp, x, y, z updatePrimaryAltitudeSignal = pyqtSignal(object, int, float) # uas, timestamp, altitude updateGPSAltitudeSignal = pyqtSignal(object, int, float) # uas, timestamp, altitude updateAirPressureSignal = pyqtSignal(object, int, float, float, float) # uas, timestamp, abs press, diff press, temperature updateRCStatusSignal = pyqtSignal(object, int, int, int, int) # uas, type(local, remote), rssi, noise, errors # uas, desiredRoll, desiredPitch, desiredHeading, targetBearing, wpDist updateNavigationControllerOutputSignal = pyqtSignal(object, float, float, float, float, float) updateRCChannelsSignal = pyqtSignal(object, int, int, object) # uas, timestamp, rssi, channels mavlinkMessageTxSignal = pyqtSignal(object) # mavlink message object def __init__(self, name, parent = None): super().__init__(parent) self.uasName = name self.autopilotClass = mavlink.MAV_AUTOPILOT_GENERIC self.param = UserData.getInstance().getUserDataEntry(UD_UAS_CONF_KEY, {}) self.onboardParameters = [] self.oldOnboardParameters = [] self.onboardParamNotReceived = 0 self.messageHandlers = {} self.messageHandlers['SYS_STATUS'] = self.uasStatusHandler self.messageHandlers['GPS_RAW_INT'] = self.uasLocationHandler self.messageHandlers['GLOBAL_POSITION_INT'] = self.uasFilteredLocationHandler self.messageHandlers['SCALED_PRESSURE'] = self.uasAltitudeHandler self.messageHandlers['ATTITUDE'] = self.uasAttitudeHandler self.messageHandlers['GPS_STATUS'] = self.uasGPSStatusHandler self.messageHandlers['RADIO_STATUS'] = self.uasRadioStatusHandler self.messageHandlers['RC_CHANNELS'] = self.uasRCChannelsHandler self.messageHandlers['NAV_CONTROLLER_OUTPUT'] = self.uasNavigationControllerOutputHandler self.messageHandlers['LOCAL_POSITION_NED'] = self.uasDefaultMessageHandler self.messageHandlers['PARAM_VALUE'] = self.uasDefaultMessageHandler self.messageHandlers['HEARTBEAT'] = self.uasDefaultMessageHandler self.messageHandlers['ATTITUDE_QUATERNION'] = self.uasDefaultMessageHandler self.messageHandlers['SYSTEM_TIME'] = self.uasDefaultMessageHandler self.messageHandlers['VFR_HUD'] = self.uasDefaultMessageHandler self.messageHandlers['AUTOPILOT_VERSION'] = self.uasDefaultMessageHandler self.messageHandlers['BATTERY_STATUS'] = self.uasDefaultMessageHandler self.messageHandlers['SCALED_IMU'] = self.uasDefaultMessageHandler self.messageHandlers['RAW_IMU'] = self.uasDefaultMessageHandler self.altitudeReference = DEFAULT_ALTITUDE_REFERENCE self.pressureReference = DEFAULT_PRESSURE_REFERENCE self.signingKey = None self.initialTimestamp = 0 def receiveMAVLinkMessage(self, msg): tp = msg.get_type() if tp in self.messageHandlers: self.messageHandlers[tp](msg) else: print('UNKNOWN MSG:', msg) def setPressureAltitudeReference(self, presRef, altiRef): self.altitudeReference = altiRef self.pressureReference = presRef @abstractmethod def uasStatusHandler(self, msg): pass @abstractmethod def uasLocationHandler(self, msg): pass @abstractmethod def uasGPSStatusHandler(self, msg): pass @abstractmethod def uasFilteredLocationHandler(self, msg): pass @abstractmethod def uasAltitudeHandler(self, msg): pass @abstractmethod def uasAttitudeHandler(self, msg): pass @abstractmethod def uasRadioStatusHandler(self, msg): pass @abstractmethod def uasRCChannelsHandler(self, msg): pass @abstractmethod def uasNavigationControllerOutputHandler(self, msg): pass @abstractmethod def fetchAllOnboardParameters(self): pass def uasDefaultMessageHandler(self, msg): pass def __backupOnboardParameters(self, dest, src): ''' Copy parameters from `src` to `dest`, any existing parameters in `dest` will be removed. Parameters in `src` will also be removed after the backup. ''' while len(dest) > 0: del dest[0] while len(src) > 0: dest.append(src[0]) del src[0] def resetOnboardParameterList(self): # copy onboardParameters to oldOnboardParameters self.__backupOnboardParameters(self.oldOnboardParameters, self.onboardParameters) def restoreToOldOnboardParameterList(self): # copy oldOnboardParameters to onboardParameters self.__backupOnboardParameters(self.onboardParameters, self.oldOnboardParameters) def getPressureAltitude(self, pressure, temperature): try: kelvin = temperature - ZERO_KELVIN altitude = self.altitudeReference - (UNIVERSAL_GAS_CONSTANT * kelvin) * log(pressure / self.pressureReference) / (gravity * MOLAR_MASS) return altitude except ValueError: return 0 def acceptMessageSigningKey(self, key, ts): key0 = self.signingKey ts0 = self.initialTimestamp try: key0 = bytes.fromhex(key) except ValueError: pass try: ts0 = int(ts) except ValueError: pass self.signingKey = key0 if ts0 > self.initialTimestamp: self.initialTimestamp = ts0 if mavlink.WIRE_PROTOCOL_VERSION == '2.0': msg = mavlink.MAVLink_setup_signing_message(255, 255, self.signingKey, self.initialTimestamp) self.mavlinkMessageTxSignal.emit(msg) def allowUnsignedCallback(self, mav, msgId): unused(mav, msgId) return True class StandardMAVLinkInterface(UASInterface): DEFAULT_GPS_SRC = 'GPS_RAW_INT' def __init__(self, name, parent = None): super().__init__(name, parent) self.gpsSrc = UserData.getParameterValue(self.param, UD_UAS_CONF_GPS_SRC_KEY, StandardMAVLinkInterface.DEFAULT_GPS_SRC) def uasStatusHandler(self, msg): self.updateBatterySignal.emit(self, 0, msg.voltage_battery / 1000.0, msg.current_battery / 1000.0, msg.battery_remaining) def uasLocationHandler(self, msg): if (self.gpsSrc == msg.get_type()): self.updateGlobalPositionSignal.emit(self, msg.time_usec, msg.lat / MAVLINK_LXTITUDE_SCALE, msg.lon / MAVLINK_LXTITUDE_SCALE, msg.alt / 1000.0) self.updateGPSAltitudeSignal.emit(self, msg.time_usec, msg.alt / 1000.0) # mm -> meter if msg.vel != UINT16_MAX: self.updateGroundSpeedSignal.emit(self, msg.time_usec, msg.vel / 100 * 3.6) # cm/s to km/h self.updateGPSStatusSignal.emit(self, msg.time_usec, msg.fix_type, msg.eph, msg.epv, msg.satellites_visible, 0, 0, 0, 0) def uasFilteredLocationHandler(self, msg): if (self.gpsSrc == msg.get_type()): self.updateGlobalPositionSignal.emit(self, msg.time_boot_ms, msg.lat / MAVLINK_LXTITUDE_SCALE, msg.lon / MAVLINK_LXTITUDE_SCALE, msg.alt / 1000.0) self.updateGPSAltitudeSignal.emit(self, msg.time_boot_ms, msg.alt / 1000.0) # mm -> meter vel = msg.vx * msg.vx vel += msg.vy * msg.vy vel += msg.vz * msg.vz self.updateGroundSpeedSignal.emit(self, msg.time_boot_ms, sqrt(vel) / 100 * 3.6) # cm/s to km/h def uasAltitudeHandler(self, msg): self.updateAirPressureSignal.emit(self, msg.time_boot_ms, msg.press_abs, msg.press_diff, msg.temperature) alt = self.getPressureAltitude(msg.press_abs * 100, msg.temperature) # hPa to Pa self.updatePrimaryAltitudeSignal.emit(self, msg.time_boot_ms, alt) def uasAttitudeHandler(self, msg): self.updateAttitudeSignal.emit(self, msg.time_boot_ms, msg.roll, msg.pitch, msg.yaw) def uasRadioStatusHandler(self, msg): self.updateRCStatusSignal.emit(self, 0, msg.rssi, msg.noise, msg.rxerrors) def uasRCChannelsHandler(self, msg): rcChannels = {} for i in range(msg.chancount): ch = 'chan{}_raw'.format(i + 1) rcChannels[i + 1] = getattr(msg, ch) self.updateRCChannelsSignal.emit(self, msg.time_boot_ms, msg.rssi, rcChannels) def uasGPSStatusHandler(self, msg): # can be used to view gps SNR pass def acceptOnboardParameter(self, msg): self.onboardParameters.append(msg) self.onboardParamNotReceived = msg.param_count - msg.param_index - 1 def fetchAllOnboardParameters(self): self.resetOnboardParameterList() self.mavlinkMessageTxSignal.emit(mavlink.MAVLink_param_request_list_message(255, 0)) def uasNavigationControllerOutputHandler(self, msg): self.updateNavigationControllerOutputSignal.emit(self, msg.nav_roll, msg.nav_pitch, msg.nav_bearing, msg.target_bearing, msg.wp_dist) class AutoQuadMAVLinkInterface(StandardMAVLinkInterface): def __init__(self, name, parent = None): super().__init__(name, parent) self.autopilotClass = mavlink.MAV_AUTOPILOT_AUTOQUAD def uasLocationHandler(self, msg): self.updateGlobalPositionSignal.emit(self, msg.time_usec, msg.lat / MAVLINK_LXTITUDE_SCALE, msg.lon / MAVLINK_LXTITUDE_SCALE, msg.alt / 1000.0) self.updateGPSAltitudeSignal.emit(self, msg.time_usec, msg.alt / 1000.0) # mm -> meter self.updateGPSStatusSignal.emit(self, msg.time_usec, msg.fix_type, UINT16_MAX, UINT16_MAX, msg.satellites_visible, int(msg.eph / 100), int(msg.epv / 100), 0, 0) if msg.vel != UINT16_MAX: self.updateGroundSpeedSignal.emit(self, msg.time_usec, msg.vel / 100 * 3.6) # cm/s to km/h class UASInterfaceFactory: UAS_INTERFACES = {} @staticmethod def __initUas(): UASInterfaceFactory.UAS_INTERFACES[mavlink.MAV_AUTOPILOT_GENERIC] = StandardMAVLinkInterface('Generic MAVLink Interface') UASInterfaceFactory.UAS_INTERFACES[mavlink.MAV_AUTOPILOT_AUTOQUAD] = AutoQuadMAVLinkInterface('AutoQuad MAVLink Interface') @staticmethod def getUASInterface(dialect): if len(UASInterfaceFactory.UAS_INTERFACES) == 0: UASInterfaceFactory.__initUas() if dialect in UASInterfaceFactory.UAS_INTERFACES: return UASInterfaceFactory.UAS_INTERFACES[dialect] inst = UASInterfaceFactory.UAS_INTERFACES[mavlink.MAV_AUTOPILOT_GENERIC] inst.autopilotClass = dialect return inst <file_sep>/src/gcs/UserData.py import os import json CONFIGURATION_FILE_NAME = 'minigcs.json' class UserData: __singleton = None @staticmethod def getInstance(): if UserData.__singleton == None: UserData() return UserData.__singleton def __init__(self): if UserData.__singleton == None: self.userData = None self.confDir = self.defaultConfigurationFileDirectory() UserData.__singleton = self else: raise Exception('Call UserData.getInstance() instead.') def loadGCSConfiguration(self): fullPath = os.path.join(self.confDir, CONFIGURATION_FILE_NAME) if os.path.isfile(fullPath): dataFile = open(fullPath, 'r') self.userData = json.load(dataFile) dataFile.close() else: # Load empty configuration self.userData = {} def saveGCSConfiguration(self): dataFile = open(os.path.join(self.confDir, CONFIGURATION_FILE_NAME), 'w') json.dump(self.userData, dataFile) dataFile.close() def defaultConfigurationFileDirectory(self): if os.name == 'nt': return os.getenv('APPDATA') if os.name == 'posix': return os.getenv('HOME') return None def setUserDataEntry(self, key, value): oldValue = None if key not in self.userData else self.userData[key] self.userData[key] = value return oldValue def getUserDataEntry(self, key, defaultValue = None): if key in self.userData: return self.userData[key] if defaultValue != None: self.userData[key] = defaultValue return self.userData[key] return None @staticmethod def getParameterValue(params, key, defaultValue = None): if key in params: return params[key] params[key] = defaultValue return defaultValue class SecureData: @staticmethod def encryptConfigurationParameter(params: dict, key): pass @staticmethod def decryptConfigurationParameter(cipher, key): pass <file_sep>/src/gcs/instruments/HUD.py from math import cos, isinf, isnan from math import pi as M_PI from math import sin, sqrt from PyQt5.QtCore import (QPoint, QPointF, QRectF, QSize, QSizeF, QStandardPaths, Qt, QTimer) from PyQt5.QtGui import (QBrush, QColor, QFont, QFontDatabase, QFontMetrics, QImage, QPainter, QPen, QPixmap, QPolygon, QPolygonF, QVector3D) from PyQt5.QtOpenGL import QGLWidget from PyQt5.QtWidgets import (QAction, QFileDialog, QLabel, QMenu, QSizePolicy, QWidget, QVBoxLayout) from utils import unused class HUDWindow(QWidget): def __init__(self, hud = None, parent = None): super().__init__(parent) self.setWindowTitle('HUD') self.setMinimumSize(640, 480) if hud == None: self.hud = HUD(self) else: self.hud = hud l = QVBoxLayout() l.addWidget(self.hud) self.setLayout(l) class HUD(QLabel): DEFAULT_VWIDTH = 320.0 def __init__(self, parent = None): super().__init__(parent) self.yawInt = 0.0 self.mode = 'UNKNOWN MODE' self.state = 'UNKNOWN STATE' self.fuelStatus = '00.0V (00m:00s)' self.xCenterOffset = 0.0 self.yCenterOffset = 0.0 self.vwidth = HUD.DEFAULT_VWIDTH self.vheight = 150.0 self.vGaugeSpacing = 65.0 self.vPitchPerDeg = 6.0 # 4 mm y translation per degree self.rawBuffer1 = None self.rawBuffer2 = None self.rawImage = None self.rawLastIndex = 0 self.rawExpectedBytes = 0 self.bytesPerLine = 1 self.imageStarted = False self.receivedDepth = 8 self.receivedChannels = 1 self.receivedWidth = 640 self.receivedHeight = 480 self.warningBlinkRate = 5 self.noCamera = True self.hardwareAcceleration = True self.strongStrokeWidth = 1.5 self.normalStrokeWidth = 1.0 self.fineStrokeWidth = 0.5 self.waypointName = '' self.roll = 0.0 self.pitch = 0.0 self.yaw = 0.0 self.rollLP = 0.0 self.pitchLP = 0.0 self.yawLP = 0.0 self.yawDiff = 0.0 self.xPos = 0.0 self.yPos = 0.0 self.zPos = 0.0 self.xSpeed = 0.0 self.ySpeed = 0.0 self.zSpeed = 0.0 self.lastSpeedUpdate = 0 self.totalSpeed = 0.0 self.totalAcc = 0.0 self.lat = 0.0 self.lon = 0.0 self.alt = 0.0 self.desiredRoll = 0.0 self.desiredPitch = 0.0 self.desiredHeading = 0.0 self.targetBearing = 0.0 self.wpDist = 0.0 self.load = 0.0 self.videoRecording = '' self.nextOfflineImage = '' self.HUDInstrumentsEnabled = True self.videoEnabled = False self.imageLoggingEnabled = False self.imageLogCounter = 0 self.imageLogDirectory = None self.xImageFactor = 1.0 self.yImageFactor = 1.0 self.imageRequested = False self.videoSrc = None self.videoStarted = False self.updateInterval = 100 self.defaultColor = None self.setPointColor = None self.warningColor = None self.criticalColor = None self.infoColor = None self.fuelColor = None self.DEFAULT_BACKGROUND_IMAGE = None self.enableHUDAction: QAction = None self.enableVideoAction: QAction = None self.selectOfflineDirectoryAction: QAction = None self.attitudes = {} self.uas = None self.refreshTimer = QTimer(self) # Set auto fill to False self.setAutoFillBackground(False) # Set minimum size self.setMinimumSize(80, 60) # Set preferred size self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.scalingFactor = self.width()/self.vwidth # Set up the initial color theme. This can be updated by a styleChanged # signal from MainWindow. self.styleChanged() self.glImage = self.DEFAULT_BACKGROUND_IMAGE # Refresh timer self.refreshTimer.setInterval(self.updateInterval) self.refreshTimer.timeout.connect(self.repaint) # Resize to correct size and fill with image QWidget.resize(self, self.width(), self.height()) fontDatabase = QFontDatabase() fontFileName = './res/vera.ttf' # Font file is part of the QRC file and compiled into the app fontFamilyName = 'Bitstream Vera Sans' fontDatabase.addApplicationFont(fontFileName) font = fontDatabase.font(fontFamilyName, 'Roman', max(5, int(10.0 * self.scalingFactor * 1.2 + 0.5))) if font == None: print('ERROR! FONT NOT LOADED!') if font.family() != fontFamilyName: print('ERROR! WRONG FONT LOADED: {}'.format(fontFamilyName)) self.createActions() def sizeHint(self): return QSize(self.width(), (self.width()*3.0)/4) def styleChanged(self, newTheme = 0): unused(newTheme) # Generate a background image that's dependent on the current color scheme. fill = QImage(self.width(), self.height(), QImage.Format_Indexed8) fill.fill(0) self.DEFAULT_BACKGROUND_IMAGE = QGLWidget.convertToGLFormat(fill) self.defaultColor = QColor(0x66, 0xff, 0x00) # bright green self.setPointColor = QColor(0x82, 0x17, 0x82) self.warningColor = QColor(0xff, 0xff, 0x00) self.criticalColor = QColor(0xff, 0x00, 0x00) self.infoColor = self.defaultColor self.fuelColor = self.criticalColor def showEvent(self, event): # React only to internal (pre-display) events QWidget.showEvent(self, event) self.styleChanged() self.refreshTimer.start(self.updateInterval) if self.videoSrc != None: if self.videoStarted == False: print('starting video...') self.videoStarted = True self.videoSrc.start() self.videoSrc.pauseVideo(False) def hideEvent(self, event): # React only to internal (pre-display) events self.refreshTimer.stop() QWidget.hideEvent(self, event) if self.videoSrc != None: self.videoSrc.pauseVideo(True) def resizeEvent(self, event): QWidget.resizeEvent(self, event) self.scalingFactor = self.width() / HUD.DEFAULT_VWIDTH self.vwidth = self.width() / self.scalingFactor self.vheight = self.height() / self.scalingFactor self.styleChanged() def contextMenuEvent(self, event): menu = QMenu(self) # Update actions self.enableHUDAction.setChecked(self.HUDInstrumentsEnabled) self.enableVideoAction.setChecked(self.videoEnabled) menu.addAction(self.enableHUDAction) menu.addAction(self.enableVideoAction) menu.addAction(self.selectOfflineDirectoryAction) menu.exec(event.globalPos()) def createActions(self): self.enableHUDAction = QAction('Enable HUD', self) self.enableHUDAction.setStatusTip('Show the HUD instruments in this window') self.enableHUDAction.setCheckable(True) self.enableHUDAction.setChecked(self.HUDInstrumentsEnabled) self.enableHUDAction.triggered.connect(self.enableHUDInstruments) self.enableVideoAction = QAction('Enable Video Live feed', self) self.enableVideoAction.setStatusTip('Show the video live feed') self.enableVideoAction.setCheckable(True) self.enableVideoAction.setChecked(self.videoEnabled) self.enableVideoAction.triggered.connect(self.enableVideo) self.selectOfflineDirectoryAction = QAction('Load image log', self) self.selectOfflineDirectoryAction.setStatusTip('Load previously logged images into simulation / replay') self.selectOfflineDirectoryAction.triggered.connect(self.selectOfflineDirectory) def setActiveUAS(self, uas): uas.updateAttitudeSignal.connect(self.updateAttitude) uas.updateBatterySignal.connect(self.updateBattery) uas.updateGlobalPositionSignal.connect(self.updateGlobalPosition) uas.updateAirSpeedSignal.connect(self.updateSpeed) uas.updateGroundSpeedSignal.connect(self.updateGroundSpeed) uas.updateVelocitySignal.connect(self.updateVelocity) uas.updateNavigationControllerOutputSignal.connect(self.updateNavigationControllerOutput) self.uas = uas def setVideoSource(self, videoSrc): videoSrc.newFrameAvailable.connect(self.setImageExternal) self.videoSrc = videoSrc def updateAttitude(self, uas, timestamp, roll, pitch, yaw): unused(uas, timestamp) if isnan(roll) == False and isinf(roll) == False \ and isnan(pitch) == False and isinf(pitch)== False \ and isnan(yaw) == False and isinf(yaw) == False: self.roll = roll self.pitch = pitch*3.35 # Constant here is the 'focal length' of the projection onto the plane self.yaw = yaw self.attitudes[0] = QVector3D(roll, pitch*3.35, yaw) def updateComponentAttitude(self, uas, timestamp, component, roll, pitch, yaw): unused(uas, timestamp) if isnan(roll) == False and isinf(roll) == False \ and isnan(pitch) == False and isinf(pitch)== False \ and isnan(yaw) == False and isinf(yaw) == False: self.attitudes[component] = QVector3D(roll, pitch*3.35, yaw) # Constant here is the 'focal length' of the projection onto the plane def updateBattery(self, uas, timestamp, voltage, current, percent): unused(uas, timestamp, current) self.fuelStatus = 'BAT [{}% | {:.1f}V]'.format(percent, voltage) if percent < 20.0: self.fuelColor = self.warningColor elif percent < 10.0: self.fuelColor = self.criticalColor else: self.fuelColor = self.infoColor def receiveHeartbeat(self, uas): unused(uas) def updateThrust(self, uas, thrust): unused(uas, thrust) #updateValue(uas, "thrust", thrust, MG.TIME.getGroundTimeNow()) def updateLocalPosition(self, uas, timestamp, x, y, z): unused(uas, timestamp) self.xPos = x self.yPos = y self.zPos = z def updateGlobalPosition(self, uas, timestamp, lat, lon, altitude): unused(uas, timestamp) self.lat = lat self.lon = lon self.alt = altitude def updateVelocity(self, uas, timestamp, x, y, z): unused(uas) self.xSpeed = x self.ySpeed = y self.zSpeed = z newTotalSpeed = sqrt(self.xSpeed*self.xSpeed + self.ySpeed*self.ySpeed + self.zSpeed*self.zSpeed) self.totalAcc = (newTotalSpeed - self.totalSpeed) / ((self.lastSpeedUpdate - timestamp)/1000.0) self.totalSpeed = newTotalSpeed self.lastSpeedUpdate = timestamp def updateSpeed(self, uas, timestamp, speed): unused(uas) self.totalAcc = (speed - self.totalSpeed) / ((self.lastSpeedUpdate - timestamp)/1000.0) self.totalSpeed = speed self.lastSpeedUpdate = timestamp def updateGroundSpeed(self, uas, timestamp, gndspd): unused(uas) # only update if we haven't gotten a full 3D speed update in a while if timestamp - self.lastSpeedUpdate > 1e6: self.totalAcc = (gndspd - self.totalSpeed) / ((self.lastSpeedUpdate - timestamp)/1000.0) self.totalSpeed = gndspd self.lastSpeedUpdate = timestamp def updateState(self, uas, state): ''' Updates the current system state, but only if the uas matches the currently monitored uas. :param uas: the system the state message originates from :param state: short state text, displayed in HUD ''' unused(uas) # Only one UAS is connected at a time self.state = state def updateMode(self, uas, mode): ''' Updates the current system mode, but only if the uas matches the currently monitored uas. :param uas: the system the state message originates from :param mode: short mode text, displayed in HUD ''' unused(uas) # Only one UAS is connected at a time self.mode = mode def updateLoad(self, uas, load): unused(uas) self.load = load # updateValue(uas, "load", load, MG.TIME.getGroundTimeNow()) def updateNavigationControllerOutput(self, uas, desiredRoll, desiredPitch, desiredHeading, targetBearing, wpDist): unused(uas) self.desiredRoll = desiredRoll self.desiredPitch = desiredPitch self.desiredHeading = desiredHeading self.targetBearing = targetBearing self.wpDist = wpDist def refToScreenX(self, x): return self.scalingFactor * x def refToScreenY(self, y): return self.scalingFactor * y def paintText(self, text, color, fontSize, refX, refY, painter): ''' Paint text on top of the image and OpenGL drawings :param text: chars to write :param color: text color :param fontSize: text size in mm :param refX: position in reference units (mm of the real instrument). This is relative to the measurement unit position, NOT in pixels. :param refY: position in reference units (mm of the real instrument). This is relative to the measurement unit position, NOT in pixels. ''' prevPen = painter.pen() pPositionX = self.refToScreenX(refX) - (fontSize*self.scalingFactor*0.072) pPositionY = self.refToScreenY(refY) - (fontSize*self.scalingFactor*0.212) font = QFont('Bitstream Vera Sans') # Enforce minimum font size of 5 pixels fSize = max(5, int(fontSize*self.scalingFactor*1.26)) font.setPixelSize(fSize) metrics = QFontMetrics(font) border = max(4, metrics.leading()) rect = metrics.boundingRect(0, 0, self.width() - 2*border, int(self.height()*0.125), Qt.AlignLeft | Qt.TextWordWrap, text) painter.setPen(color) painter.setFont(font) painter.setRenderHint(QPainter.TextAntialiasing) painter.drawText(pPositionX, pPositionY, rect.width(), rect.height(), Qt.AlignCenter | Qt.TextWordWrap, text) painter.setPen(prevPen) def paintRollPitchStrips(self): pass def paintEvent(self, event): unused(event) if self.isVisible(): # Read out most important values to limit hash table lookups # Low-pass roll, pitch and yaw self.rollLP = self.roll#rollLP * 0.2f + 0.8f * roll self.pitchLP = self.pitch#pitchLP * 0.2f + 0.8f * pitch self.yawLP = self.yaw if isinf(self.yaw) == False and isnan(self.yaw) == False else self.yawLP#yawLP * 0.2f + 0.8f * yaw # Translate for yaw maxYawTrans = 60.0 newYawDiff = self.yawDiff if isinf(newYawDiff): newYawDiff = self.yawDiff if newYawDiff > M_PI: newYawDiff = newYawDiff - M_PI if newYawDiff < -M_PI: newYawDiff = newYawDiff + M_PI newYawDiff = self.yawDiff * 0.8 + newYawDiff * 0.2 self.yawDiff = newYawDiff self.yawInt += newYawDiff if self.yawInt > M_PI: self.yawInt = M_PI if self.yawInt < -M_PI: self.yawInt = -M_PI yawTrans = self.yawInt * maxYawTrans self.yawInt *= 0.6 if (yawTrans < 5.0) and (yawTrans > -5.0): yawTrans = 0 # Negate to correct direction yawTrans = -yawTrans yawTrans = 0 #qDebug() << "yaw translation" << yawTrans << "integral" << yawInt << "difference" << yawDiff << "yaw" << yaw # And if either video or the data stream is enabled, draw the next frame. if self.videoEnabled: self.xImageFactor = self.width() / float(self.glImage.width()) self.yImageFactor = self.height() / float(self.glImage.height()) painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.HighQualityAntialiasing, True) pmap = QPixmap.fromImage(self.glImage).scaledToWidth(self.width()) painter.drawPixmap(0, (self.height() - pmap.height()) / 2, pmap) # END OF OPENGL PAINTING if self.HUDInstrumentsEnabled: #glEnable(GL_MULTISAMPLE) # QT PAINTING #makeCurrent() painter.translate((self.vwidth/2.0+self.xCenterOffset)*self.scalingFactor, (self.vheight/2.0+self.yCenterOffset)*self.scalingFactor) # COORDINATE FRAME IS NOW (0,0) at CENTER OF WIDGET # Draw all fixed indicators # BATTERY self.paintText(self.fuelStatus, self.fuelColor, 6.0, (-self.vwidth/2.0) + 10, -self.vheight/2.0 + 6, painter) # Waypoint self.paintText(self.waypointName, self.defaultColor, 6.0, (-self.vwidth/3.0) + 10, +self.vheight/3.0 + 15, painter) linePen = QPen(Qt.SolidLine) linePen.setWidth(self.refLineWidthToPen(1.0)) linePen.setColor(self.defaultColor) painter.setBrush(Qt.NoBrush) painter.setPen(linePen) # YAW INDICATOR # # . # . . # ....... # _yawIndicatorWidth = 12.0 _yawIndicatorY = self.vheight/2.0 - 15.0 yawIndicator = QPolygon(4) yawIndicator.setPoint(0, QPoint(self.refToScreenX(0.0), self.refToScreenY(_yawIndicatorY))) yawIndicator.setPoint(1, QPoint(self.refToScreenX(_yawIndicatorWidth/2.0), self.refToScreenY(_yawIndicatorY+_yawIndicatorWidth))) yawIndicator.setPoint(2, QPoint(self.refToScreenX(-_yawIndicatorWidth/2.0), self.refToScreenY(_yawIndicatorY+_yawIndicatorWidth))) yawIndicator.setPoint(3, QPoint(self.refToScreenX(0.0), self.refToScreenY(_yawIndicatorY))) painter.drawPolyline(yawIndicator) painter.setPen(linePen) # CENTER # HEADING INDICATOR # # __ __ # \/\/ # _hIndicatorWidth = 20.0 _hIndicatorY = -25.0 _hIndicatorYLow = _hIndicatorY + _hIndicatorWidth / 6.0 _hIndicatorSegmentWidth = _hIndicatorWidth / 7.0 hIndicator = QPolygon(7) hIndicator.setPoint(0, QPoint(self.refToScreenX(0.0-_hIndicatorWidth/2.0), self.refToScreenY(_hIndicatorY))) hIndicator.setPoint(1, QPoint(self.refToScreenX(0.0-_hIndicatorWidth/2.0+_hIndicatorSegmentWidth*1.75), self.refToScreenY(_hIndicatorY))) hIndicator.setPoint(2, QPoint(self.refToScreenX(0.0-_hIndicatorSegmentWidth*1.0), self.refToScreenY(_hIndicatorYLow))) hIndicator.setPoint(3, QPoint(self.refToScreenX(0.0), self.refToScreenY(_hIndicatorY))) hIndicator.setPoint(4, QPoint(self.refToScreenX(0.0+_hIndicatorSegmentWidth*1.0), self.refToScreenY(_hIndicatorYLow))) hIndicator.setPoint(5, QPoint(self.refToScreenX(0.0+_hIndicatorWidth/2.0-_hIndicatorSegmentWidth*1.75), self.refToScreenY(_hIndicatorY))) hIndicator.setPoint(6, QPoint(self.refToScreenX(0.0+_hIndicatorWidth/2.0), self.refToScreenY(_hIndicatorY))) painter.drawPolyline(hIndicator) # SETPOINT _centerWidth = 8.0 painter.drawEllipse( QPointF(self.refToScreenX(min(10.0, self.desiredRoll * 10.0)), self.refToScreenY(min(10.0, self.desiredPitch * 10.0))), self.refToScreenX(_centerWidth/2.0), self.refToScreenX(_centerWidth/2.0)) _centerCrossWidth = 20.0 # left painter.drawLine(QPointF(self.refToScreenX(-_centerWidth / 2.0), self.refToScreenY(0.0)), QPointF(self.refToScreenX(-_centerCrossWidth / 2.0), self.refToScreenY(0.0))) # right painter.drawLine(QPointF(self.refToScreenX(_centerWidth / 2.0), self.refToScreenY(0.0)), QPointF(self.refToScreenX(_centerCrossWidth / 2.0), self.refToScreenY(0.0))) # top painter.drawLine(QPointF(self.refToScreenX(0.0), self.refToScreenY(-_centerWidth / 2.0)), QPointF(self.refToScreenX(0.0), self.refToScreenY(-_centerCrossWidth / 2.0))) # COMPASS _compassY = -self.vheight/2.0 + 6.0 compassRect = QRectF(QPointF(self.refToScreenX(-12.0), self.refToScreenY(_compassY)), QSizeF(self.refToScreenX(24.0), self.refToScreenY(12.0))) painter.setBrush(Qt.NoBrush) painter.setPen(linePen) painter.drawRoundedRect(compassRect, 3, 3) # YAW is in compass-human readable format, so 0 .. 360 deg. _yawDeg = (self.yawLP / M_PI) * 180.0 if _yawDeg < 0: _yawDeg += 360 if _yawDeg > 360: _yawDeg -= 360 # final safeguard for really stupid systems _yawAngle = '{:3d}'.format(int(_yawDeg) % 360) self.paintText(_yawAngle, self.defaultColor, 8.5, -9.8, _compassY + 1.7, painter) painter.setBrush(Qt.NoBrush) painter.setPen(linePen) # CHANGE RATE STRIPS self.drawChangeRateStrip(-95.0, -60.0, 40.0, -10.0, 10.0, self.zSpeed, painter) # CHANGE RATE STRIPS self.drawChangeRateStrip(95.0, -60.0, 40.0, -10.0, 10.0, self.totalAcc, painter,True) # GAUGES # Left altitude gauge _gaugeAltitude = self.alt if self.alt != 0 else -self.zPos painter.setBrush(Qt.NoBrush) painter.setPen(linePen) self.drawChangeIndicatorGauge(-self.vGaugeSpacing, 35.0, 15.0, 10.0, _gaugeAltitude, self.defaultColor, painter, False) self.paintText('alt m', self.defaultColor, 5.5, -73.0, 50, painter) # Right speed gauge self.drawChangeIndicatorGauge(self.vGaugeSpacing, 35.0, 15.0, 10.0, self.totalSpeed, self.defaultColor, painter, False) self.paintText('v m/s', self.defaultColor, 5.5, 55.0, 50, painter) # Waypoint name if self.waypointName != '': self.paintText(self.waypointName, self.defaultColor, 2.0, (-self.vwidth/3.0) + 10, +self.vheight/3.0 + 15, painter) # MOVING PARTS painter.translate(self.refToScreenX(yawTrans), 0) attColor = painter.pen().color() # Draw multi-component attitude for key in self.attitudes: att = self.attitudes[key] attColor = attColor.darker(200) painter.setPen(attColor) # Rotate view and draw all roll-dependent indicators painter.rotate((att.x()/M_PI)* -180.0) painter.translate(0, (-att.y()/M_PI)* -180.0 * self.refToScreenY(1.8)) #qDebug() << "ROLL" << roll << "PITCH" << pitch << "YAW DIFF" << valuesDot.value("roll", 0.0) # PITCH self.paintPitchLines(att.y(), painter) painter.translate(0, -(-att.y()/M_PI)* -180.0 * self.refToScreenY(1.8)) painter.rotate(-(att.x()/M_PI)* -180.0) painter.end() def paintPitchLines(self, pitch, painter): _yDeg = self.vPitchPerDeg _lineDistance = 5.0 #/< One pitch line every 10 degrees _posIncrement = _yDeg * _lineDistance _posY = _posIncrement _posLimit = sqrt(pow(self.vwidth, 2.0) + pow(self.vheight, 2.0))*3.0 _offsetAbs = pitch * _yDeg _offset = pitch if _offset < 0: _offset = -_offset _offsetCount = 0 while _offset > _lineDistance: _offset -= _lineDistance _offsetCount += 1 _iPos = int(0.5 + _lineDistance) #/< The first line _iNeg = int(-0.5 - _lineDistance) #/< The first line _offset *= _yDeg painter.setPen(self.defaultColor) _posY = -_offsetAbs + _posIncrement #+ 100# + _lineDistance while _posY < _posLimit: self.paintPitchLinePos('{:3d}'.format(_iPos), 0.0, -_posY, painter) _posY += _posIncrement _iPos += int(_lineDistance) # HORIZON # # ------------ ------------ # _pitchWidth = 30.0 _pitchGap = _pitchWidth / 2.5 _horizonColor = self.defaultColor _diagonal = sqrt(pow(self.vwidth, 2.0) + pow(self.vheight, 2.0)) _lineWidth = self.refLineWidthToPen(0.5) # Left horizon self.drawLine(0.0-_diagonal, _offsetAbs, 0.0-_pitchGap/2.0, _offsetAbs, _lineWidth, _horizonColor, painter) # Right horizon self.drawLine(0.0+_pitchGap/2.0, _offsetAbs, 0.0+_diagonal, _offsetAbs, _lineWidth, _horizonColor, painter) _posY = _offsetAbs + _posIncrement while _posY < _posLimit: self.paintPitchLineNeg('{:3d}'.format(_iNeg), 0.0, _posY, painter) _posY += _posIncrement _iNeg -= int(_lineDistance) def paintPitchLinePos(self, text, refPosX, refPosY, painter): _pitchWidth = 30.0 _pitchGap = _pitchWidth / 2.5 _pitchHeight = _pitchWidth / 12.0 _textSize = _pitchHeight * 1.6 _lineWidth = 1.5 # Positive pitch indicator: # # _______ _______ # |10 | # # Left vertical line self.drawLine(refPosX-_pitchWidth/2.0, refPosY, refPosX-_pitchWidth/2.0, refPosY+_pitchHeight, _lineWidth, self.defaultColor, painter) # Left horizontal line self.drawLine(refPosX-_pitchWidth/2.0, refPosY, refPosX-_pitchGap/2.0, refPosY, _lineWidth, self.defaultColor, painter) # Text left self.paintText(text, self.defaultColor, _textSize, refPosX-_pitchWidth/2.0 + 0.75, refPosY + _pitchHeight - 1.3, painter) # Right vertical line self.drawLine(refPosX+_pitchWidth/2.0, refPosY, refPosX+_pitchWidth/2.0, refPosY+_pitchHeight, _lineWidth, self.defaultColor, painter) # Right horizontal line self.drawLine(refPosX+_pitchWidth/2.0, refPosY, refPosX+_pitchGap/2.0, refPosY, _lineWidth, self.defaultColor, painter) def paintPitchLineNeg(self, text, refPosX, refPosY, painter): _pitchWidth = 30.0 _pitchGap = _pitchWidth / 2.5 _pitchHeight = _pitchWidth / 12.0 _textSize = _pitchHeight * 1.6 _segmentWidth = ((_pitchWidth - _pitchGap)/2.0) / 7.0 #/< Four lines and three gaps -> 7 segments _lineWidth = 1.5 # Negative pitch indicator: # # -10 # _ _ _ _| |_ _ _ _ # # # Left vertical line self.drawLine(refPosX-_pitchGap/2.0, refPosY, refPosX-_pitchGap/2.0, refPosY-_pitchHeight, _lineWidth, self.defaultColor, painter) # Left horizontal line with four segments i = 0 while i < 7: self.drawLine(refPosX-_pitchWidth/2.0+(i*_segmentWidth), refPosY, refPosX-_pitchWidth/2.0+(i*_segmentWidth)+_segmentWidth, refPosY, _lineWidth, self.defaultColor, painter) i+=2 # Text left self.paintText(text, self.defaultColor, _textSize, refPosX-_pitchWidth/2.0 + 0.75, refPosY + _pitchHeight - 1.3, painter) # Right vertical line self.drawLine(refPosX+_pitchGap/2.0, refPosY, refPosX+_pitchGap/2.0, refPosY-_pitchHeight, _lineWidth, self.defaultColor, painter) # Right horizontal line with four segments i = 0 while i < 7: self.drawLine(refPosX+_pitchWidth/2.0-(i*_segmentWidth), refPosY, refPosX+_pitchWidth/2.0-(i*_segmentWidth)-_segmentWidth, refPosY, _lineWidth, self.defaultColor, painter) i += 2 def rotatePointClockWise(self, p: QPointF, angle): ''' Standard 2x2 rotation matrix, counter-clockwise | cos(phi) sin(phi) | | -sin(phi) cos(phi) | ''' p.setX(cos(angle) * p.x() + sin(angle)* p.y()) p.setY((-1.0 * sin(angle) * p.x()) + cos(angle) * p.y()) def refLineWidthToPen(self, line): return line * 2.50 def rotatePolygonClockWiseRad(self, p: QPolygonF, angle, origin): ''' Rotate a polygon around a point :param p: polygon to rotate :param origin: the rotation center :param angle: rotation angle, in radians :return p: Polygon p rotated by angle around the origin point ''' for i in range(p.size()): curr = p.at(i) x = curr.x() y = curr.y() curr.setX(((cos(angle) * (x-origin.x())) + (-sin(angle) * (y-origin.y()))) + origin.x()) curr.setY(((sin(angle) * (x-origin.x())) + (cos(angle) * (y-origin.y()))) + origin.y()) p.replace(i, curr) def drawPolygon(self, refPolygon, painter): # Scale coordinates draw = QPolygonF(refPolygon.size()) for i in range(refPolygon.size()): curr = QPointF() curr.setX(self.refToScreenX(refPolygon.at(i).x())) curr.setY(self.refToScreenY(refPolygon.at(i).y())) draw.replace(i, curr) painter.drawPolygon(draw) def drawChangeRateStrip(self, xRef, yRef, height, minRate, maxRate, value, painter, reverse = False): _scaledValue = value # Saturate value if value > maxRate: _scaledValue = maxRate if value < minRate: _scaledValue = minRate # x (Origin: xRef, yRef) # - # | # | # | # = # | # -0.005 >| # | # - _width = height / 8.0 _lineWidth = 1.5 # Indicator lines # Top horizontal line if reverse: self.drawLine(xRef, yRef, xRef-_width, yRef, _lineWidth, self.defaultColor, painter) # Vertical main line self.drawLine(xRef-_width/2.0, yRef, xRef-_width/2.0, yRef+height, _lineWidth, self.defaultColor, painter) # Zero mark self.drawLine(xRef, yRef+height/2.0, xRef-_width, yRef+height/2.0, _lineWidth, self.defaultColor, painter) # Horizontal bottom line self.drawLine(xRef, yRef+height, xRef-_width, yRef+height, _lineWidth, self.defaultColor, painter) # Text label = '{:06.2f} >'.format(value) font = QFont('Bitstream Vera Sans') # Enforce minimum font size of 5 pixels #int fSize = qMax(5, (int)(6.0f*scalingFactor*1.26f)) font.setPixelSize(6.0 * 1.26) metrics = QFontMetrics(font) self.paintText(label, self.defaultColor, 6.0, (xRef-_width) - metrics.width(label), yRef+height-((_scaledValue - minRate)/(maxRate-minRate))*height - 1.6, painter) else: self.drawLine(xRef, yRef, xRef+_width, yRef, _lineWidth, self.defaultColor, painter) # Vertical main line self.drawLine(xRef+_width/2.0, yRef, xRef+_width/2.0, yRef+height, _lineWidth, self.defaultColor, painter) # Zero mark self.drawLine(xRef, yRef+height/2.0, xRef+_width, yRef+height/2.0, _lineWidth, self.defaultColor, painter) # Horizontal bottom line self.drawLine(xRef, yRef+height, xRef+_width, yRef+height, _lineWidth, self.defaultColor, painter) # Text label = '<{:06.2f}'.format(value) self.paintText(label, self.defaultColor, 6.0, xRef+_width/2.0, yRef+height-((_scaledValue - minRate)/(maxRate-minRate))*height - 1.6, painter) def drawSystemIndicator(self, xRef, yRef, maxNum, maxWidth, maxHeight, painter): pass def drawChangeIndicatorGauge(self, xRef, yRef, radius, expectedMaxChange, value, color, painter, solid): # Draw the circle circlePen = QPen(Qt.SolidLine) if solid == False: circlePen.setStyle(Qt.DotLine) circlePen.setColor(self.defaultColor) circlePen.setWidth(self.refLineWidthToPen(2.0)) painter.setBrush(Qt.NoBrush) painter.setPen(circlePen) self.drawCircle(xRef, yRef, radius, 200.0, 170.0, 1.5, color, painter) label = '{:05.1f}'.format(value) _textSize = radius / 2.5 # Draw the value self.paintText(label, color, _textSize, xRef-_textSize*1.7, yRef-_textSize*0.4, painter) # Draw the needle # Scale the rotation so that the gauge does one revolution # per max. change _rangeScale = (2.0 * M_PI) / expectedMaxChange _maxWidth = radius / 10.0 _minWidth = _maxWidth * 0.3 p = QPolygonF(6) p.replace(0, QPointF(xRef-_maxWidth/2.0, yRef-radius * 0.5)) p.replace(1, QPointF(xRef-_minWidth/2.0, yRef-radius * 0.9)) p.replace(2, QPointF(xRef+_minWidth/2.0, yRef-radius * 0.9)) p.replace(3, QPointF(xRef+_maxWidth/2.0, yRef-radius * 0.5)) p.replace(4, QPointF(xRef, yRef-radius * 0.46)) p.replace(5, QPointF(xRef-_maxWidth/2.0, yRef-radius * 0.5)) self.rotatePolygonClockWiseRad(p, value*_rangeScale, QPointF(xRef, yRef)) indexBrush = QBrush() indexBrush.setColor(self.defaultColor) indexBrush.setStyle(Qt.SolidPattern) painter.setPen(Qt.SolidLine) painter.setPen(self.defaultColor) painter.setBrush(indexBrush) self.drawPolygon(p, painter) def drawLine(self, refX1, refY1, refX2, refY2, width, color, painter): pen = QPen(Qt.SolidLine) pen.setWidth(self.refLineWidthToPen(width)) pen.setColor(color) painter.setPen(pen) painter.drawLine(QPoint(self.refToScreenX(refX1), self.refToScreenY(refY1)), QPoint(self.refToScreenX(refX2), self.refToScreenY(refY2))) def drawEllipse(self, refX, refY, radiusX, radiusY, startDeg, endDeg, lineWidth, color, painter): unused(startDeg, endDeg) pen = QPen(painter.pen().style()) pen.setWidth(self.refLineWidthToPen(lineWidth)) pen.setColor(color) painter.setPen(pen) painter.drawEllipse(QPointF(self.refToScreenX(refX), self.refToScreenY(refY)), self.refToScreenX(radiusX), self.refToScreenY(radiusY)) def drawCircle(self, refX, refY, radius, startDeg, endDeg, lineWidth, color, painter): self.drawEllipse(refX, refY, radius, radius, startDeg, endDeg, lineWidth, color, painter) def selectWaypoint(self, uasId, wpid): unused(uasId) self.waypointName = 'WP{}'.format(wpid) def setImageExternal(self, img): if self.videoEnabled: self.glImage = img else: self.glImage = self.DEFAULT_BACKGROUND_IMAGE def enableHUDInstruments(self, enabled): self.HUDInstrumentsEnabled = enabled def enableVideo(self, enabled): self.videoEnabled = enabled def selectOfflineDirectory(self): fileName = QFileDialog.getExistingDirectory(self, 'Select image directory', QStandardPaths.writableLocation(QStandardPaths.DesktopLocation)) if fileName != '': self.videoRecording = fileName <file_sep>/src/gcs/requirements.txt pymavlink==2.3.4 PyQt5==5.12 PyQtChart==5.12 pyserial==3.4 opencv-python==4.2.0.32 pynmea2==1.15.0 <file_sep>/src/gcs/plugins/paparazzi.py from PyQt5.QtCore import Qt # , pyqtSignal from PyQt5.QtWidgets import QGridLayout, QLabel, QPushButton, QMessageBox from pymavlink.mavutil import mavlink from plugins.common import AbstractControlPanel MAV_CMD_ACKS = { mavlink.MAV_CMD_ACK_OK : 'Command executed', mavlink.MAV_CMD_ACK_ERR_FAIL : 'Generic error', mavlink.MAV_CMD_ACK_ERR_ACCESS_DENIED : 'Command refused', mavlink.MAV_CMD_ACK_ERR_NOT_SUPPORTED : 'Command not supported', mavlink.MAV_CMD_ACK_ERR_COORDINATE_FRAME_NOT_SUPPORTED : 'Coordinate frame not supported', mavlink.MAV_CMD_ACK_ERR_COORDINATES_OUT_OF_RANGE : 'Invalid coordinate values', mavlink.MAV_CMD_ACK_ERR_X_LAT_OUT_OF_RANGE : 'Invalid latitude value', mavlink.MAV_CMD_ACK_ERR_Y_LON_OUT_OF_RANGE : 'Invalid longitude value', mavlink.MAV_CMD_ACK_ERR_Z_ALT_OUT_OF_RANGE : 'Invalid altitude value' } class PaparazziControlPanel(AbstractControlPanel): __mavlinkMessageTypes = [] cmdSent = 0 syncParamsFromUAV = False def __init__(self, parent = None): super().__init__(parent) l = QGridLayout() row = 0 l.addWidget(QLabel('Paparazzi Tools'), row, 0, 1, 3, Qt.AlignLeft) row += 1 self.accelCalibButton = QPushButton('Accel Calib.') self.paramDefaultButton = QPushButton('Reset Parameters') self.paramSaveButton = QPushButton('Save Parameters') self.paramReadButton = QPushButton('Read Parameters') self.accelCalibButton.clicked.connect(lambda: \ self.__sendMAVLinkLongMessage(target_component=mavlink.MAV_COMP_ID_IMU, command=mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, param5=4)) self.paramDefaultButton.clicked.connect(lambda: \ self.__sendMAVLinkLongMessage(command=mavlink.MAV_CMD_PREFLIGHT_STORAGE, param1=2, syncParams=True)) self.paramSaveButton.clicked.connect(lambda: \ self.__sendMAVLinkLongMessage(command=mavlink.MAV_CMD_PREFLIGHT_STORAGE, param1=1)) self.paramReadButton.clicked.connect(lambda: \ self.__sendMAVLinkLongMessage(command=mavlink.MAV_CMD_PREFLIGHT_STORAGE, param1=0, syncParams=True)) l.addWidget(self.paramSaveButton, row, 0, 1, 1, Qt.AlignLeft) l.addWidget(self.paramReadButton, row, 2, 1, 1, Qt.AlignLeft) row += 1 l.addWidget(self.accelCalibButton, row, 0, 1, 1, Qt.AlignLeft) l.addWidget(self.paramDefaultButton, row, 2, 1, 1, Qt.AlignLeft) row += 1 l.setRowStretch(row, 1) self.setLayout(l) def __sendMAVLinkLongMessage(self, target_system = 255, # set target system to 255 to let telemetry.py auto correct the values target_component = 0, command = 0, confirmation = 0, param1 = 0, param2 = 0, param3 = 0, param4 = 0, param5 = 0, param6 = 0, param7 = 0, syncParams = False): msg = mavlink.MAVLink_command_long_message(target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7) self.__addMessageType('COMMAND_ACK') self.cmdSent = command self.syncParamsFromUAV = syncParams self.mavlinkTxSignal.emit(msg) def tabName(self): return 'Paparazzi' def __addMessageType(self, msgType): if msgType not in self.__mavlinkMessageTypes: self.__mavlinkMessageTypes.append(msgType) def __removeMessageType(self, msgType): if msgType in self.__mavlinkMessageTypes: self.__mavlinkMessageTypes.remove(msgType) def registerMavlinkMessageListeners(self): return self.__mavlinkMessageTypes def mavlinkMessageReceived(self, msg): if msg.get_type() == 'COMMAND_ACK' and msg.command == self.cmdSent: if msg.result in MAV_CMD_ACKS: if msg.result == mavlink.MAV_CMD_ACK_OK: if self.syncParamsFromUAV: self.syncParamsFromUAV = False self.uas.fetchAllOnboardParameters() QMessageBox.information(self, 'Information', MAV_CMD_ACKS[msg.result], QMessageBox.Ok) else: QMessageBox.critical(self, 'Error', MAV_CMD_ACKS[msg.result], QMessageBox.Ok) self.__removeMessageType('COMMAND_ACK') <file_sep>/src/gcs/plugins/autoquad.py from PyQt5.QtCore import Qt # , pyqtSignal from PyQt5.QtWidgets import QGridLayout, QLabel, QPushButton, QMessageBox from pymavlink.mavutil import mavlink from plugins.common import AbstractControlPanel MAV_CMD_ACKS = { mavlink.MAV_CMD_ACK_OK : 'Command executed', mavlink.MAV_CMD_ACK_ERR_FAIL : 'Generic error', mavlink.MAV_CMD_ACK_ERR_ACCESS_DENIED : 'Command refused', mavlink.MAV_CMD_ACK_ERR_NOT_SUPPORTED : 'Command not supported', mavlink.MAV_CMD_ACK_ERR_COORDINATE_FRAME_NOT_SUPPORTED : 'Coordinate frame not supported', mavlink.MAV_CMD_ACK_ERR_COORDINATES_OUT_OF_RANGE : 'Invalid coordinate values', mavlink.MAV_CMD_ACK_ERR_X_LAT_OUT_OF_RANGE : 'Invalid latitude value', mavlink.MAV_CMD_ACK_ERR_Y_LON_OUT_OF_RANGE : 'Invalid longitude value', mavlink.MAV_CMD_ACK_ERR_Z_ALT_OUT_OF_RANGE : 'Invalid altitude value' } class AutoQuadControlPanel(AbstractControlPanel): __mavlinkMessageTypes = ['AQ_TELEMETRY_F', 'AQ_ESC_TELEMETRY'] cmdSent = 0 syncParamsFromUAV = False def __init__(self, parent = None): super().__init__(parent) l = QGridLayout() row = 0 l.addWidget(QLabel('AutoQuad Tools'), row, 0, 1, 3, Qt.AlignLeft) row += 1 self.fromSDButton = QPushButton('From SD') self.toSDButton = QPushButton('To SD') self.readFromFlashButton = QPushButton('Reload Flash') self.saveToFlashButton = QPushButton('Save Flash') self.dIMUTareButton = QPushButton('DIMU Tare') self.magCalibButton = QPushButton('MAG Calib.') self.calibSaveButton = QPushButton('Calib. Save') self.calibReadButton = QPushButton('Calib. Read') self.fromSDButton.clicked.connect(lambda: \ self.__sendMAVLinkLongMessage(command=mavlink.MAV_CMD_PREFLIGHT_STORAGE, param1=3, syncParams=True)) self.toSDButton.clicked.connect(lambda: \ self.__sendMAVLinkLongMessage(command=mavlink.MAV_CMD_PREFLIGHT_STORAGE, param1=2)) self.readFromFlashButton.clicked.connect(lambda: \ self.__sendMAVLinkLongMessage(command=mavlink.MAV_CMD_PREFLIGHT_STORAGE, param1=0, syncParams=True)) self.saveToFlashButton.clicked.connect(lambda: \ self.__sendMAVLinkLongMessage(command=mavlink.MAV_CMD_PREFLIGHT_STORAGE, param1=1)) self.calibSaveButton.clicked.connect(lambda: \ self.__sendMAVLinkLongMessage(target_component=mavlink.MAV_COMP_ID_IMU, command=mavlink.MAV_CMD_PREFLIGHT_STORAGE, param1=1)) self.calibReadButton.clicked.connect(lambda: \ self.__sendMAVLinkLongMessage(target_component=mavlink.MAV_COMP_ID_IMU, command=mavlink.MAV_CMD_PREFLIGHT_STORAGE, param1=0, syncParams=True)) self.dIMUTareButton.clicked.connect(lambda: \ self.__sendMAVLinkLongMessage(command=mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, param5=1)) self.magCalibButton.clicked.connect(lambda: \ self.__sendMAVLinkLongMessage(command=mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, param2=1)) l.addWidget(self.fromSDButton, row, 0, 1, 1, Qt.AlignLeft) l.addWidget(self.toSDButton, row, 2, 1, 1, Qt.AlignLeft) row += 1 l.addWidget(self.readFromFlashButton, row, 0, 1, 1, Qt.AlignLeft) l.addWidget(self.saveToFlashButton, row, 2, 1, 1, Qt.AlignLeft) row += 1 l.addWidget(self.dIMUTareButton, row, 0, 1, 1, Qt.AlignLeft) l.addWidget(self.magCalibButton, row, 2, 1, 1, Qt.AlignLeft) row += 1 l.addWidget(self.calibSaveButton, row, 0, 1, 1, Qt.AlignLeft) l.addWidget(self.calibReadButton, row, 2, 1, 1, Qt.AlignLeft) row += 1 l.setRowStretch(row, 1) self.setLayout(l) def __sendMAVLinkLongMessage(self, target_system = 255, # set target system to 255 to let telemetry.py auto correct the values target_component = 0, command = 0, confirmation = 0, param1 = 0, param2 = 0, param3 = 0, param4 = 0, param5 = 0, param6 = 0, param7 = 0, syncParams = False): msg = mavlink.MAVLink_command_long_message(target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7) self.__addMessageType('COMMAND_ACK') self.cmdSent = command self.syncParamsFromUAV = syncParams self.mavlinkTxSignal.emit(msg) def tabName(self): return 'AutoQuad' def __addMessageType(self, msgType): if msgType not in self.__mavlinkMessageTypes: self.__mavlinkMessageTypes.append(msgType) def __removeMessageType(self, msgType): if msgType in self.__mavlinkMessageTypes: self.__mavlinkMessageTypes.remove(msgType) def registerMavlinkMessageListeners(self): return self.__mavlinkMessageTypes def mavlinkMessageReceived(self, msg): if msg.get_type() == 'COMMAND_ACK' and msg.command == self.cmdSent: if msg.result in MAV_CMD_ACKS: if msg.result == mavlink.MAV_CMD_ACK_OK: if self.syncParamsFromUAV: self.syncParamsFromUAV = False self.uas.fetchAllOnboardParameters() QMessageBox.information(self, 'Information', MAV_CMD_ACKS[msg.result], QMessageBox.Ok) else: QMessageBox.critical(self, 'Error', MAV_CMD_ACKS[msg.result], QMessageBox.Ok) self.__removeMessageType('COMMAND_ACK') <file_sep>/src/gcs/main.py import os import sys import pymavlink from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy, QSplitter, QMessageBox, QAction, qApp from LocalGPS import GPSConfigurationWindow from instruments.map import MapWidget from instruments.pfd import PrimaryFlightDisplay from instruments.statusPanel import SystemStatusPanel from telemetry import ConnectionEditWindow, MAVLinkConnection, MessageSigningSetupWindow from UserData import UserData from instruments.HUD import HUDWindow from fpv import FileVideoSource from instruments.barometer import BarometerConfigWindow from uas import DEFAULT_ALTITUDE_REFERENCE, DEFAULT_PRESSURE_REFERENCE from instruments.plotter import PlotterWindow from instruments.ControlCheck import ServoOutputCheckWindow UD_MAIN_WINDOW_KEY = 'MAIN' UD_MAIN_WINDOW_HEIGHT_KEY = 'WINDOW_HEIGHT' UD_MAIN_WINDOW_WIDTH_KEY = 'WINDOW_WIDTH' class MiniGCS(QMainWindow): def __init__(self, parent = None): super().__init__(parent) self.mav = None self.param = UserData.getInstance().getUserDataEntry(UD_MAIN_WINDOW_KEY, {}) current_path = os.path.abspath(os.path.dirname(__file__)) qmlFile = os.path.join(current_path, './instruments/map.qml') self.setWindowTitle('Mini GCS') if UD_MAIN_WINDOW_HEIGHT_KEY in self.param and UD_MAIN_WINDOW_WIDTH_KEY in self.param: self.resize(self.param[UD_MAIN_WINDOW_WIDTH_KEY], self.param[UD_MAIN_WINDOW_HEIGHT_KEY]) self.teleWindow = ConnectionEditWindow() self.teleWindow.MAVLinkConnectedSignal.connect(self.createConnection) self.window = QSplitter() self.left = QSplitter(Qt.Vertical, self.window) self.pfd = PrimaryFlightDisplay(self.window) self.sts = SystemStatusPanel(self.window) self.msgSignWindow = MessageSigningSetupWindow() self.hudWindow = HUDWindow() self.hud = self.hudWindow.hud self.sts.connectToMAVLink.connect(self.teleWindow.show) self.sts.disconnectFromMAVLink.connect(self.disconnect) spPfd = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) spPfd.setVerticalStretch(3) self.pfd.setSizePolicy(spPfd) spSts = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) spSts.setVerticalStretch(2) self.sts.setSizePolicy(spSts) self.left.addWidget(self.pfd) self.left.addWidget(self.sts) spLeft = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) spLeft.setHorizontalStretch(2) self.left.setSizePolicy(spLeft) self.map = MapWidget(qmlFile) spRight = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) spRight.setHorizontalStretch(5) self.map.setSizePolicy(spRight) self.window.addWidget(self.left) self.window.addWidget(self.map) self.localGPSWindow = GPSConfigurationWindow() # TODO configurable behavior self.localGPSWindow.connection.locationUpdate.connect(self.map.updateHomeLocationEvent) self.sts.connectToLocalGPS.connect(self.localGPSWindow.show) self.sts.disconnectFromLocalGPS.connect(self.localGPSWindow.connection.disconnect) self.sts.statusPanel.showHUDButton.clicked.connect(self.hudWindow.show) self.teleWindow.cancelConnectionSignal.connect(lambda: self.sts.statusPanel.connectButton.setEnabled(True)) self.__createMenus() self.setCentralWidget(self.window) def __createMenus(self): self.exitAction = QAction('Exit', self) self.exitAction.triggered.connect(qApp.exit) menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(self.exitAction) self.localGPSAction = QAction('Local GPS', self) self.localGPSAction.triggered.connect(self.sts.statusPanel.toggleGPSButtonLabel) self.showHUDAction = QAction('HUD', self) self.showHUDAction.triggered.connect(self.hudWindow.show) self.showMsgSignAction = QAction('Message Signing', self) self.showMsgSignAction.triggered.connect(self.msgSignWindow.show) self.baroRefCfgWindow = BarometerConfigWindow(DEFAULT_ALTITUDE_REFERENCE, DEFAULT_PRESSURE_REFERENCE) self.baroRefCfgAction = QAction('Pressure Altitude Reference', self) self.baroRefCfgAction.triggered.connect(self.baroRefCfgWindow.show) self.plotterWindow = PlotterWindow('MAVLink Plotter') self.plotterAction = QAction('Plotter', self) self.plotterAction.triggered.connect(self.plotterWindow.show) self.servoOutputWindow = ServoOutputCheckWindow(8) self.servoOutputAction = QAction('Servo Output', self) self.servoOutputAction.triggered.connect(self.servoOutputWindow.show) toolsMenu = menubar.addMenu('&Tools') toolsMenu.addAction(self.localGPSAction) toolsMenu.addAction(self.showHUDAction) toolsMenu.addAction(self.showMsgSignAction) toolsMenu.addAction(self.baroRefCfgAction) toolsMenu.addAction(self.plotterAction) toolsMenu.addAction(self.servoOutputAction) def createConnection(self, conn): self.mav = MAVLinkConnection(conn, isinstance(conn, pymavlink.mavutil.mavlogfile)) self.mav.heartbeatTimeoutSignal.connect(self.sts.statusPanel.resetConnectionButton) self.mav.establishConnection() if self.mav.running == False: QMessageBox.critical(self, 'Error', 'MAVLink connection timeout', QMessageBox.Ok) return self.map.waypointList.requestReturnToHome.connect(self.mav.initializeReturnToHome) self.map.uploadWaypointsToUAVEvent.connect(self.mav.uploadWaypoints) self.map.downloadWaypointsFromUAVSignal.connect(self.mav.downloadWaypoints) self.mav.connectionEstablishedSignal.connect(lambda: \ self.sts.statusPanel.toggleButtonLabel(True)) self.sts.addAPControlPanel(self.mav.uas.autopilotClass) self.mav.newTextMessageSignal.connect(self.map.displayTextMessage) self.mav.onboardWaypointsReceivedSignal.connect(self.map.setAllWaypoints) self.pfd.setActiveUAS(self.mav.uas) self.hud.setActiveUAS(self.mav.uas) # self.hud.enableVideo(True) # fpv = FileVideoSource('test.mp4') # test only # self.hud.setVideoSource(fpv) self.mav.externalMessageHandler.connect(self.plotterWindow.handleMavlinkMessage) self.map.setActiveUAS(self.mav.uas) self.sts.statusPanel.setActiveUAS(self.mav.uas) self.sts.compassPanel.setActiveUAS(self.mav.uas) self.sts.barometerPanel.setActiveUAS(self.mav.uas) self.baroRefCfgWindow.updatePressureAltitudeReferenceSignal.connect(self.mav.uas.setPressureAltitudeReference) self.msgSignWindow.setMessageSigningKeySignal.connect(self.mav.setupMessageSigningKey) self.msgSignWindow.setMessageSigningKeySignal.connect(self.mav.uas.acceptMessageSigningKey) self.sts.statusPanel.editParameterButton.clicked.connect(self.mav.showParameterEditWindow) self.sts.initializaMavlinkForControlPanels(self.mav) self.servoOutputWindow.mavlinkMotorTestSignal.connect(self.mav.sendMavlinkMessage) self.msgSignWindow.setMAVLinkVersion(self.mav.connection.WIRE_PROTOCOL_VERSION) self.mav.start() def disconnect(self): self.mav.requestExit() def closeEvent(self, event): print('[MAIN] closeEvent') ud = UserData.getInstance() s = self.size() self.param[UD_MAIN_WINDOW_HEIGHT_KEY] = s.height() self.param[UD_MAIN_WINDOW_WIDTH_KEY] = s.width() ud.setUserDataEntry(UD_MAIN_WINDOW_KEY, self.param) try: ud.saveGCSConfiguration() print('GCS Conf saved.') except IOError: pass super().closeEvent(event) if __name__ == '__main__': app = QApplication(sys.argv) try: UserData.getInstance().loadGCSConfiguration() except IOError: sys.exit(1) frame = MiniGCS() frame.show() sys.exit(app.exec_()) <file_sep>/hardware/README.md PCB design files for hardware components used in this project. <file_sep>/src/gcs/instruments/pfd.py # -*- coding: utf-8 -*- ''' Port from qgroundcontrol PFD ''' import math from PyQt5.QtCore import (QPoint, QPointF, QRectF, Qt, QTimer, pyqtSignal, qRound) from PyQt5.QtGui import (QBrush, QColor, QFont, QFontMetrics, QLinearGradient, QPainter, QPainterPath, QPen) from PyQt5.QtWidgets import QSizePolicy, QWidget from UserData import UserData from utils import unused UD_PFD_KEY = 'PFD' UD_PFD_PRIMARY_SPEED_SOURCE_KEY = 'PRIMARY_SPEED_SOURCE' UD_PFD_PRIMARY_ALTITUDE_SOURCE_KEY = 'PRIMARY_ALTITUDE_SOURCE' class PrimaryFlightDisplay(QWidget): ROLL_SCALE_RANGE = 60 ROLL_SCALE_TICKMARKLENGTH = 0.04 ROLL_SCALE_RADIUS = 0.42 ROLL_SCALE_MARKERWIDTH = 0.06 ROLL_SCALE_MARKERHEIGHT = 0.04 LINEWIDTH = 0.0036 SMALL_TEXT_SIZE = 0.03 MEDIUM_TEXT_SIZE = SMALL_TEXT_SIZE * 1.2 LARGE_TEXT_SIZE = MEDIUM_TEXT_SIZE * 1.2 PITCH_SCALE_RESOLUTION = 5 PITCH_SCALE_HALFRANGE = 15 PITCH_SCALE_MAJORWIDTH = 0.1 PITCH_SCALE_MINORWIDTH = 0.066 PITCH_SCALE_WIDTHREDUCTION_FROM = 30 PITCH_SCALE_WIDTHREDUCTION = 0.3 SHOW_ZERO_ON_SCALES = True CROSSTRACK_MAX = 1000 CROSSTRACK_RADIUS = 0.6 COMPASS_DISK_MAJORTICK = 10 COMPASS_DISK_ARROWTICK = 45 COMPASS_DISK_MAJORLINEWIDTH = 0.006 COMPASS_DISK_MINORLINEWIDTH = 0.004 COMPASS_DISK_RESOLUTION = 10 COMPASS_SEPARATE_DISK_RESOLUTION = 5 COMPASS_DISK_MARKERWIDTH = 0.2 COMPASS_DISK_MARKERHEIGHT = 0.133 UNKNOWN_BATTERY = -1 UNKNOWN_ATTITUDE = 0 UNKNOWN_ALTITUDE = -1000 UNKNOWN_SPEED = -1 UNKNOWN_COUNT = -1 UNKNOWN_GPSFIXTYPE = -1 TAPE_GAUGES_TICKWIDTH_MAJOR = 0.25 TAPE_GAUGES_TICKWIDTH_MINOR = 0.15 # The altitude difference between top and bottom of scale ALTIMETER_LINEAR_SPAN = 50 # every 5 meters there is a tick mark ALTIMETER_LINEAR_RESOLUTION = 5 # every 10 meters there is a number ALTIMETER_LINEAR_MAJOR_RESOLUTION = 10 ALTIMETER_VVI_SPAN = 5 ALTIMETER_VVI_WIDTH = 0.2 AIRSPEED_LINEAR_SPAN = 15 AIRSPEED_LINEAR_RESOLUTION = 1 AIRSPEED_LINEAR_MAJOR_RESOLUTION = 5 tickValues = [10, 20, 30, 45, 60] compassWindNames = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'] visibilityChanged = pyqtSignal(bool) def __init__(self, parent): super().__init__(parent) self.instrumentOpagueBackground = QBrush(QColor.fromHsvF(0, 0, 0.3, 1.0)) self.instrumentBackground = QBrush(QColor.fromHsvF(0, 0, 0.3, 0.3)) self.instrumentEdgePen = QPen(QColor.fromHsvF(0, 0, 0.65, 0.5)) self.font = QFont() self.lineWidth = 2 self.fineLineWidth = 1 self.navigationTargetBearing = PrimaryFlightDisplay.UNKNOWN_ATTITUDE self.navigationCrosstrackError = 0 self.primaryAltitude = PrimaryFlightDisplay.UNKNOWN_ALTITUDE self.GPSAltitude = PrimaryFlightDisplay.UNKNOWN_ALTITUDE self.verticalVelocity = PrimaryFlightDisplay.UNKNOWN_ALTITUDE self.primarySpeed = PrimaryFlightDisplay.UNKNOWN_SPEED self.groundspeed = PrimaryFlightDisplay.UNKNOWN_SPEED self.roll = 0.0 self.pitch = 0.0 self.yaw = 0.0 self.rollspeed = 0.0 self.pitchspeed = 0.0 self.yawspeed = 0.0 self.latitude = 0.0 self.longitude = 0.0 self.additionalParameters = {} self.param = UserData.getInstance().getUserDataEntry(UD_PFD_KEY, {}) self.isGPSSpeedPrimary = UserData.getParameterValue(self.param, UD_PFD_PRIMARY_SPEED_SOURCE_KEY) == 'GPS' self.isGPSAltitudePrimary = UserData.getParameterValue(self.param, UD_PFD_PRIMARY_ALTITUDE_SOURCE_KEY) == 'GPS' self.setMinimumSize(480, 320) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.smallTestSize = self.SMALL_TEXT_SIZE self.mediumTextSize = self.MEDIUM_TEXT_SIZE self.largeTextSize = self.LARGE_TEXT_SIZE self.uiTimer = QTimer(self) self.uiTimer.setInterval(40) self.uiTimer.timeout.connect(self.update) self.uas = None def setActiveUAS(self, uas): uas.updateAttitudeSignal.connect(self.updateAttitude) uas.updateBatterySignal.connect(self.updateBatteryStatus) uas.updateGlobalPositionSignal.connect(self.updateGlobalPosition) uas.updateAirSpeedSignal.connect(self.updatePrimarySpeed) uas.updateGroundSpeedSignal.connect(self.updateGPSSpeed) uas.updateGPSStatusSignal.connect(self.updateGPSReception) uas.updateRCStatusSignal.connect(self.updateRCStatus) self.uas = uas def updateRCStatus(self, sourceUAS, rcType, rssi, noise, errors): unused(sourceUAS, rcType) self.additionalParameters['rc_rssi'] = rssi self.additionalParameters['rc_noise'] = noise self.additionalParameters['rc_errors'] = errors def updateAttitude(self, sourceUAS, timestamp, roll, pitch, yaw): scale = 180 / math.pi self.pitch = self.pitch if math.isnan(pitch) else pitch * scale self.roll = self.roll if math.isnan(roll) else roll * scale self.yaw = self.yaw if math.isnan(yaw) else yaw * scale unused(sourceUAS, timestamp) def updateAttitudeSpeed(self, sourceUAS, timestamp, rollspeed, pitchspeed, yawspeed): scale = 180 / math.pi self.rollspeed = self.rollspeed if math.isnan(rollspeed) else rollspeed * scale self.pitchspeed = self.pitchspeed if math.isnan(pitchspeed) else pitchspeed * scale self.yawspeed = self.yawspeed if math.isnan(yawspeed) else yawspeed * scale unused(sourceUAS, timestamp) def updateGlobalPosition(self, sourceUAS, timestamp, latitude, longitude, altitude): self.latitude = self.latitude if math.isnan(latitude) else latitude self.longitude = self.longitude if math.isnan(longitude) else longitude self.GPSAltitude = self.GPSAltitude if math.isnan(altitude) else altitude unused(sourceUAS, timestamp) def updatePrimaryAltitude(self, sourceUAS, timestamp, altitude): self.primaryAltitude = self.primaryAltitude if math.isnan(altitude) else altitude unused(sourceUAS, timestamp) def updateGPSAltitude(self, sourceUAS, timestamp, altitude): self.GPSAltitude = self.GPSAltitude if math.isnan(altitude) else altitude unused(sourceUAS, timestamp) def updatePrimarySpeed(self, sourceUAS, timestamp, speed): self.primarySpeed = self.primarySpeed if math.isnan(speed) else speed unused(sourceUAS, timestamp) def updateBatteryStatus(self, sourceUAS, timestamp, voltage, current, remaining): self.additionalParameters['voltage'] = voltage self.additionalParameters['current'] = current self.additionalParameters['remaining'] = remaining unused(sourceUAS, timestamp) def updateGPSReception(self, sourceUAS, timestamp, fixType, hdop, vdop, satelliteCount, hacc, vacc, velacc, hdgacc): self.additionalParameters['gps_fix'] = fixType self.additionalParameters['gps_satellite'] = satelliteCount unused(sourceUAS, timestamp, hdop, vdop, hacc, vacc, velacc, hdgacc) def updateGPSSpeed(self, sourceUAS, timestamp, speed): self.groundspeed = self.groundspeed if math.isnan(speed) else speed unused(sourceUAS, timestamp) def paintEvent(self, event): unused(event) compassAIIntrusion = 0 compassHalfSpan = 180 painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.HighQualityAntialiasing, True) tapeGaugeWidth = self.tapesGaugeWidthFor(self.width(), self.width()) aiheight = self.height() aiwidth = self.width() - tapeGaugeWidth * 2 if (aiheight > aiwidth): aiheight = aiwidth AIMainArea = QRectF(tapeGaugeWidth, 0, aiwidth, aiheight) AIPaintArea = QRectF(0, 0, self.width(), self.height()) velocityMeterArea = QRectF(0, 0, tapeGaugeWidth, aiheight) altimeterArea = QRectF(AIMainArea.right(), 0, tapeGaugeWidth, aiheight) # calc starts compassRelativeWidth = 0.75 compassBottomMargin = 0.78 compassSize = compassRelativeWidth * AIMainArea.width() # Diameter is this times the width. compassCenterY = AIMainArea.bottom() + compassSize / 4 if self.height() - compassCenterY > AIMainArea.width() / 2 * compassBottomMargin: compassCenterY = self.height()-AIMainArea.width()/2*compassBottomMargin compassCenterY = (compassCenterY * 2 + AIMainArea.bottom() + compassSize / 4) / 3 compassArea = QRectF(AIMainArea.x()+(1-compassRelativeWidth)/2*AIMainArea.width(), compassCenterY-compassSize/2, compassSize, compassSize) if self.height()-compassCenterY < compassSize/2: compassHalfSpan = math.acos((compassCenterY-self.height())*2/compassSize) * 180/math.pi + self.COMPASS_DISK_RESOLUTION if compassHalfSpan > 180: compassHalfSpan = 180 compassAIIntrusion = compassSize / 2 + AIMainArea.bottom() - compassCenterY if compassAIIntrusion < 0: compassAIIntrusion = 0 #calc ends hadClip = painter.hasClipping() painter.setClipping(True) painter.setClipRect(AIPaintArea) self.drawAIGlobalFeatures(painter, AIMainArea, AIPaintArea) self.drawAIAttitudeScales(painter, AIMainArea, compassAIIntrusion) self.drawAIAirframeFixedFeatures(painter, AIMainArea) self.drawAICompassDisk(painter, compassArea, compassHalfSpan) painter.setClipping(hadClip) if self.isGPSAltitudePrimary: self.drawAltimeter(painter, altimeterArea, self.GPSAltitude, self.primaryAltitude, self.verticalVelocity) else: self.drawAltimeter(painter, altimeterArea, self.primaryAltitude, self.GPSAltitude, self.verticalVelocity) if self.isGPSSpeedPrimary: self.drawVelocityMeter(painter, velocityMeterArea, self.groundspeed, self.primarySpeed) else: self.drawVelocityMeter(painter, velocityMeterArea, self.primarySpeed, self.groundspeed) painter.end() def showEvent(self, event): super().showEvent(event) self.uiTimer.start() self.visibilityChanged.emit(True) def hideEvent(self, event): self.uiTimer.stop() super().hideEvent(event) self.visibilityChanged.emit(False) def resizeEvent(self, e): super().resizeEvent(e) size = e.size().width() self.lineWidth = self.constrain(size * self.LINEWIDTH, 1, 6) self.fineLineWidth = self.constrain(size * self.LINEWIDTH * 2 / 3, 1, 2) self.instrumentEdgePen.setWidthF(self.fineLineWidth) self.smallTestSize = size * self.SMALL_TEXT_SIZE self.mediumTextSize = size * self.MEDIUM_TEXT_SIZE self.largeTextSize = size * self.LARGE_TEXT_SIZE def drawTextCenter(self, painter, text, pixelSize, x, y): self.font.setPixelSize(pixelSize) painter.setFont(self.font) metrics = QFontMetrics(self.font) bounds = metrics.boundingRect(text) painter.drawText(x - bounds.width() / 2, y - bounds.height() / 2, bounds.width(), bounds.height(), Qt.AlignCenter | Qt.TextDontClip, text) def drawTextLeftCenter(self, painter, text, pixelSize, x, y): self.font.setPixelSize(pixelSize) painter.setFont(self.font) metrics = QFontMetrics(self.font) bounds = metrics.boundingRect(text) painter.drawText(x , y - bounds.height() / 2, bounds.width(), bounds.height(), Qt.AlignLeft | Qt.TextDontClip, text) def drawTextRightCenter(self, painter, text, pixelSize, x, y): self.font.setPixelSize(pixelSize) painter.setFont(self.font) metrics = QFontMetrics(self.font) bounds = metrics.boundingRect(text) painter.drawText(x - bounds.width(), y - bounds.height() / 2, bounds.width(), bounds.height(), Qt.AlignRight | Qt.TextDontClip, text) def drawTextCenterTop(self, painter, text, pixelSize, x, y): self.font.setPixelSize(pixelSize) painter.setFont(self.font) metrics = QFontMetrics(self.font) bounds = metrics.boundingRect(text) painter.drawText(x - bounds.width() / 2, y + bounds.height(), bounds.width(), bounds.height(), Qt.AlignCenter | Qt.TextDontClip, text) def drawTextCenterBottom(self, painter, text, pixelSize, x, y): self.font.setPixelSize(pixelSize) painter.setFont(self.font) metrics = QFontMetrics(self.font) bounds = metrics.boundingRect(text) painter.drawText(x - bounds.width() / 2, y, bounds.width(), bounds.height(), Qt.AlignCenter, text) def drawInstrumentBackground(self, painter, edge): painter.setPen(self.instrumentEdgePen) painter.drawRect(edge) def fillInstrumentBackground(self, painter, edge): painter.setPen(self.instrumentEdgePen) painter.setBrush(self.instrumentBackground) painter.drawRect(edge) painter.setBrush(Qt.NoBrush) def fillInstrumentOpagueBackground(self, painter, edge): painter.setPen(self.instrumentEdgePen) painter.setBrush(self.instrumentOpagueBackground) painter.drawRect(edge) painter.setBrush(Qt.NoBrush) def constrain(self, value, mn, mx): if value < mn: value = mn elif value > mx: value = mx return value def pitchAngleToTranslation(self, viewHeight, pitch): return pitch * viewHeight / 65.0 #PITCHTRANSLATION def tapesGaugeWidthFor(self, containerWidth, preferredAIWidth): result = (containerWidth - preferredAIWidth) / 2.0 minimum = containerWidth / 5.5 if result < minimum: result = minimum return result def min4(self, a, b, c, d): if b < a: a = b if c < a: a = c if d < a: a = d return a def max4(self, a, b, c, d): if b > a: a = b if c > a: a = c if d > a: a = d return a def drawAIAttitudeScales(self, painter, area, intrusion): # To save computations, we do these transformations once for both scales: painter.resetTransform() painter.translate(area.center()) painter.rotate(-self.roll) saved = painter.transform() self.drawRollScale(painter, area, True, True) painter.setTransform(saved) self.drawPitchScale(painter, area, intrusion, True, True) def drawPitchScale(self, painter, area, intrusion, drawNumbersLeft, drawNumbersRight): unused(intrusion) # The area should be quadratic but if not width is the major size. w = area.width() if w < area.height(): w = area.height() pen = QPen() pen.setWidthF(self.lineWidth) pen.setColor(Qt.white) painter.setPen(pen) savedTransform = painter.transform() # find the mark nearest center snap = qRound(self.pitch / self.PITCH_SCALE_RESOLUTION) * self.PITCH_SCALE_RESOLUTION _min = snap-self.PITCH_SCALE_HALFRANGE _max = snap+self.PITCH_SCALE_HALFRANGE degrees = _min while degrees <= _max: isMajor = degrees % (self.PITCH_SCALE_RESOLUTION * 2) == 0 linewidth = self.PITCH_SCALE_MINORWIDTH if isMajor: linewidth = self.PITCH_SCALE_MAJORWIDTH if abs(degrees) > self.PITCH_SCALE_WIDTHREDUCTION_FROM: # we want: 1 at PITCH_SCALE_WIDTHREDUCTION_FROM and PITCH_SCALE_WIDTHREDUCTION at 90. # That is PITCH_SCALE_WIDTHREDUCTION + (1-PITCH_SCALE_WIDTHREDUCTION) * f(pitch) # where f(90)=0 and f(PITCH_SCALE_WIDTHREDUCTION_FROM)=1 # f(p) = (90-p) * 1/(90-PITCH_SCALE_WIDTHREDUCTION_FROM) # or PITCH_SCALE_WIDTHREDUCTION + f(pitch) - f(pitch) * PITCH_SCALE_WIDTHREDUCTION # or PITCH_SCALE_WIDTHREDUCTION (1-f(pitch)) + f(pitch) fromVertical = -90-self.pitch if self.pitch >= 0: fromVertical = 90-self.pitch if fromVertical < 0: fromVertical = -fromVertical temp = fromVertical * 1/(90.0-self.PITCH_SCALE_WIDTHREDUCTION_FROM) linewidth *= (self.PITCH_SCALE_WIDTHREDUCTION * (1-temp) + temp) shift = self.pitchAngleToTranslation(w, self.pitch - degrees) # TODO: Intrusion detection and evasion. That is, don't draw # where the compass has intruded. painter.translate(0, shift) start = QPointF(-linewidth*w, 0) end = QPointF(linewidth*w, 0) painter.drawLine(start, end) if isMajor and (drawNumbersLeft or drawNumbersRight): displayDegrees = degrees if displayDegrees > 90: displayDegrees = 180 - displayDegrees elif displayDegrees < -90: displayDegrees = -180 - displayDegrees if self.SHOW_ZERO_ON_SCALES or degrees: if drawNumbersLeft: self.drawTextRightCenter(painter, '{0}'.format(displayDegrees), self.mediumTextSize, -self.PITCH_SCALE_MAJORWIDTH * w-10, 0) if drawNumbersRight: self.drawTextLeftCenter(painter, '{0}'.format(displayDegrees), self.mediumTextSize, self.PITCH_SCALE_MAJORWIDTH * w+10, 0) painter.setTransform(savedTransform) degrees += self.PITCH_SCALE_RESOLUTION def drawRollScale(self, painter, area, drawTicks, drawNumbers): w = area.width() if w < area.height(): w = area.height() pen = QPen() pen.setWidthF(self.lineWidth) pen.setColor(Qt.white) painter.setPen(pen) # We should really do these transforms but they are assumed done by caller. # painter.resetTransform() # painter.translate(area.center()) # painter.rotate(roll) _size = w * self.ROLL_SCALE_RADIUS*2 arcArea = QRectF(-_size/2, - _size/2, _size, _size) painter.drawArc(arcArea, (90-self.ROLL_SCALE_RANGE)*16, self.ROLL_SCALE_RANGE*2*16) # painter.drawEllipse(QPoint(0,0),200,200) if drawTicks: length = len(self.tickValues) previousRotation = 0 i = 0 while i <length*2+1: degrees = 0 if i > length: degrees = -self.tickValues[i-length-1] elif i < length: degrees = self.tickValues[i] #degrees = 180 - degrees painter.rotate(degrees - previousRotation) previousRotation = degrees start = QPointF(0, -_size/2) end = QPointF(0, -(1.0+self.ROLL_SCALE_TICKMARKLENGTH)*_size/2) painter.drawLine(start, end) #QString s_number # = QString("%d").arg(degrees); #if (SHOW_ZERO_ON_SCALES || degrees) # s_number.sprintf("%d", abs(degrees)); if drawNumbers: self.drawTextCenterBottom(painter, '{0}'.format(abs(degrees)), self.mediumTextSize, 0, -(self.ROLL_SCALE_RADIUS+self.ROLL_SCALE_TICKMARKLENGTH*1.7)*w) i = i + 1 def drawAIAirframeFixedFeatures(self, painter, area): ''' red line from -7/10 to -5/10 half-width red line from 7/10 to 5/10 half-width red slanted line from -2/10 half-width to 0 red slanted line from 2/10 half-width to 0 red arrow thing under roll scale prepareTransform(painter, width, height); ''' painter.resetTransform() painter.translate(area.center()) w = area.width() h = area.height() pen = QPen() pen.setWidthF(self.lineWidth * 1.5) pen.setColor(QColor(255, 0, 0)) painter.setPen(pen) length = 0.15 side = 0.5 # The 2 lines at sides. painter.drawLine(QPointF(-side*w, 0), QPointF(-(side-length)*w, 0)) painter.drawLine(QPointF(side*w, 0), QPointF((side-length)*w, 0)) pen.setColor(QColor(255, 255, 255)) painter.setPen(pen) v = abs(self.__getAdditionalParameter('voltage')) a = abs(self.__getAdditionalParameter('current')) # Power usage self.drawTextLeftCenter(painter, '{:.1f}V'.format(v), self.smallTestSize, -side*w*0.9, side*w/4) self.drawTextLeftCenter(painter, '{:.1f}A'.format(a), self.smallTestSize, -side*w*0.9, side*w/4 + self.mediumTextSize * 1.1) # GPS groundspeed / IAS spd = '' if self.isGPSSpeedPrimary: # TODO add option to hide air speed when there is no air speed sensor spd = 'IAS ---' if self.primarySpeed == self.UNKNOWN_SPEED else 'IAS {:.1f}'.format(self.primarySpeed) else: spd = 'GS ---' if self.groundspeed == self.UNKNOWN_SPEED else 'GS {:.1f}'.format(self.groundspeed) self.drawTextLeftCenter(painter, spd, self.smallTestSize, -side*w*0.9, side*w/4 + self.mediumTextSize * 3.3) # Number of GPS satellites s = self.__getAdditionalParameter('gps_satellite') s = 0 if s == 255 else s self.drawTextRightCenter(painter, '{} {}'.format(chr(0x1F6F0), s), self.smallTestSize, side*w*0.9, side*w/4) # RC receiver RSSI s = self.__getAdditionalParameter('rc_rssi') s = 0 if s == 255 else s s /= 254.0 self.drawTextRightCenter(painter, '{} {}'.format(chr(0x1F4F6), int(s * 100.0)), self.smallTestSize, side*w*0.9, side*w/4 + self.smallTestSize * 1.5) pen.setColor(QColor(255, 0, 0)) painter.setPen(pen) rel = length / math.sqrt(2) # The gull painter.drawLine(QPointF(rel*w, rel*w/2), QPoint(0, 0)) painter.drawLine(QPointF(-rel*w, rel*w/2), QPoint(0, 0)) # The roll scale marker. markerPath = QPainterPath(QPointF(0, -w*self.ROLL_SCALE_RADIUS+1)) markerPath.lineTo(-h*self.ROLL_SCALE_MARKERWIDTH/2, -w*(self.ROLL_SCALE_RADIUS-self.ROLL_SCALE_MARKERHEIGHT)+1) markerPath.lineTo(h*self.ROLL_SCALE_MARKERWIDTH/2, -w*(self.ROLL_SCALE_RADIUS-self.ROLL_SCALE_MARKERHEIGHT)+1) markerPath.closeSubpath() painter.drawPath(markerPath) def drawAIGlobalFeatures(self, painter, mainArea, paintArea): painter.resetTransform() painter.translate(mainArea.center()) pitchPixels = self.pitchAngleToTranslation(mainArea.height(), self.pitch) gradientEnd = self.pitchAngleToTranslation(mainArea.height(), 60) if math.isnan(self.roll) == False: # check for NaN painter.rotate(-self.roll) painter.translate(0, pitchPixels) # Calculate the radius of area we need to paint to cover all. rtx = painter.transform().inverted()[0] topLeft = rtx.map(paintArea.topLeft()) topRight = rtx.map(paintArea.topRight()) bottomLeft = rtx.map(paintArea.bottomLeft()) bottomRight = rtx.map(paintArea.bottomRight()) # Just KISS... make a rectangluar basis. minx = self.min4(topLeft.x(), topRight.x(), bottomLeft.x(), bottomRight.x()) maxx = self.max4(topLeft.x(), topRight.x(), bottomLeft.x(), bottomRight.x()) miny = self.min4(topLeft.y(), topRight.y(), bottomLeft.y(), bottomRight.y()) maxy = self.max4(topLeft.y(), topRight.y(), bottomLeft.y(), bottomRight.y()) hzonLeft = QPoint(minx, 0) hzonRight = QPoint(maxx, 0) skyPath = QPainterPath(hzonLeft) skyPath.lineTo(QPointF(minx, miny)) skyPath.lineTo(QPointF(maxx, miny)) skyPath.lineTo(hzonRight) skyPath.closeSubpath() # TODO: The gradient is wrong now. skyGradient = QLinearGradient(0, -gradientEnd, 0, 0) skyGradient.setColorAt(0, QColor.fromHsvF(0.6, 1.0, 0.7)) skyGradient.setColorAt(1, QColor.fromHsvF(0.6, 0.25, 0.9)) skyBrush = QBrush(skyGradient) painter.fillPath(skyPath, skyBrush) groundPath = QPainterPath(hzonRight) groundPath.lineTo(maxx, maxy) groundPath.lineTo(minx, maxy) groundPath.lineTo(hzonLeft) groundPath.closeSubpath() groundGradient = QLinearGradient(0, gradientEnd, 0, 0) groundGradient.setColorAt(0, QColor.fromHsvF(0.25, 1, 0.5)) groundGradient.setColorAt(1, QColor.fromHsvF(0.25, 0.25, 0.5)) groundBrush = QBrush(groundGradient) painter.fillPath(groundPath, groundBrush) pen = QPen() pen.setWidthF(self.lineWidth) pen.setColor(QColor(0, 255, 0)) painter.setPen(pen) start = QPointF(-mainArea.width(), 0) end = QPoint(mainArea.width(), 0) painter.drawLine(start, end) def drawAICompassDisk(self, painter, area, halfspan): start = self.yaw - halfspan end = self.yaw + halfspan firstTick = math.ceil(start / self.COMPASS_DISK_RESOLUTION) * self.COMPASS_DISK_RESOLUTION lastTick = math.floor(end / self.COMPASS_DISK_RESOLUTION) * self.COMPASS_DISK_RESOLUTION radius = area.width()/2 innerRadius = radius * 0.96 painter.resetTransform() painter.setBrush(self.instrumentBackground) painter.setPen(self.instrumentEdgePen) painter.drawEllipse(area) painter.setBrush(Qt.NoBrush) scalePen = QPen(Qt.black) scalePen.setWidthF(self.fineLineWidth) tickYaw = firstTick while tickYaw <= lastTick: displayTick = tickYaw if displayTick < 0: displayTick += 360 elif displayTick >= 360: displayTick -= 360 # yaw is in center. off = tickYaw - self.yaw # wrap that to ]-180..180] if off <= -180: off += 360 elif off > 180: off -= 360 painter.translate(area.center()) painter.rotate(off) drewArrow = False isMajor = displayTick % self.COMPASS_DISK_MAJORTICK == 0 if displayTick == 30 or displayTick == 60 or \ displayTick ==120 or displayTick ==150 or \ displayTick ==210 or displayTick ==240 or \ displayTick ==300 or displayTick ==330: # draw a number painter.setPen(scalePen) self.drawTextCenter(painter, '{0}'.format(int(displayTick / 10)), self.smallTestSize, 0, -innerRadius*0.75) else: if displayTick % self.COMPASS_DISK_ARROWTICK == 0: if displayTick != 0: markerPath = QPainterPath(QPointF(0, -innerRadius*(1-self.COMPASS_DISK_MARKERHEIGHT/2))) markerPath.lineTo(innerRadius*self.COMPASS_DISK_MARKERWIDTH/4, -innerRadius) markerPath.lineTo(-innerRadius*self.COMPASS_DISK_MARKERWIDTH/4, -innerRadius) markerPath.closeSubpath() painter.setPen(scalePen) painter.setBrush(Qt.SolidPattern) painter.drawPath(markerPath) painter.setBrush(Qt.NoBrush) drewArrow = True if displayTick%90 == 0: # Also draw a label name = self.compassWindNames[qRound(displayTick / 45)] painter.setPen(scalePen) self.drawTextCenter(painter, name, self.mediumTextSize, 0, -innerRadius*0.75) # draw the scale lines. If an arrow was drawn, stay off from it. if drewArrow: p_start = QPoint(0, -innerRadius*0.94) else: p_start = QPoint(0, -innerRadius) if isMajor: p_end = QPoint(0, -innerRadius*0.86) else: p_end = QPoint(0, -innerRadius*0.90) painter.setPen(scalePen) painter.drawLine(p_start, p_end) painter.resetTransform() tickYaw += self.COMPASS_DISK_RESOLUTION painter.setPen(scalePen) painter.translate(area.center()) markerPath = QPainterPath(QPointF(0, -radius-2)) markerPath.lineTo(radius*self.COMPASS_DISK_MARKERWIDTH/2, -radius-radius*self.COMPASS_DISK_MARKERHEIGHT-2) markerPath.lineTo(-radius*self.COMPASS_DISK_MARKERWIDTH/2, -radius-radius*self.COMPASS_DISK_MARKERHEIGHT-2) markerPath.closeSubpath() painter.drawPath(markerPath) digitalCompassYCenter = -radius * 0.52 digitalCompassHeight = radius * 0.28 digitalCompassBottom = QPointF(0, digitalCompassYCenter+digitalCompassHeight) digitalCompassAbsoluteBottom = painter.transform().map(digitalCompassBottom) digitalCompassUpshift = 0 if digitalCompassAbsoluteBottom.y() > self.height(): digitalCompassUpshift = digitalCompassAbsoluteBottom.y() - self.height() digitalCompassRect = QRectF(-radius/3, -radius*0.52-digitalCompassUpshift, radius*2/3, radius*0.28) painter.setPen(self.instrumentEdgePen) painter.drawRoundedRect(digitalCompassRect, self.instrumentEdgePen.widthF()*2/3, self.instrumentEdgePen.widthF()*2/3) # final safeguard for really stupid systems digitalCompassValue = qRound(self.yaw) % 360 pen = QPen() pen.setWidthF(self.lineWidth) pen.setColor(Qt.white) painter.setPen(pen) self.drawTextCenter(painter, '%03d' % digitalCompassValue, self.largeTextSize, 0, -radius*0.38-digitalCompassUpshift) # The CDI if self.shouldDisplayNavigationData() and self.navigationTargetBearing != self.UNKNOWN_ATTITUDE and not math.isinf(self.navigationCrosstrackError): painter.resetTransform() painter.translate(area.center()) # TODO : Sign might be wrong? # TODO : The case where error exceeds max. Truncate to max. and make that visible somehow. # bool errorBeyondRadius = false if abs(self.navigationCrosstrackError) > self.CROSSTRACK_MAX: #errorBeyondRadius = true if self.navigationCrosstrackError > 0: self.navigationCrosstrackError = self.CROSSTRACK_MAX else: self.navigationCrosstrackError = -self.CROSSTRACK_MAX r = radius * self.CROSSTRACK_RADIUS x = self.navigationCrosstrackError / self.CROSSTRACK_MAX * r y = math.sqrt(r*r - x*x) # the positive y, there is also a negative. sillyHeading = 0 angle = sillyHeading - self.navigationTargetBearing # TODO: sign. painter.rotate(-angle) pen = QPen() pen.setWidthF(self.lineWidth) pen.setColor(Qt.black) painter.setPen(pen) painter.drawLine(QPointF(x, y), QPointF(x, -y)) def drawAltimeter(self, painter, area, primaryAltitude, secondaryAltitude, vv): unused(secondaryAltitude) painter.resetTransform() self.fillInstrumentBackground(painter, area) pen = QPen() pen.setWidthF(self.lineWidth) pen.setColor(Qt.white) painter.setPen(pen) h = area.height() w = area.width() #float secondaryAltitudeBoxHeight = mediumTextSize * 2; # The height where we being with new tickmarks. effectiveHalfHeight = h * 0.45 # not yet implemented: Display of secondary altitude. # if (isAirplane()) # effectiveHalfHeight-= secondaryAltitudeBoxHeight; markerHalfHeight = self.mediumTextSize*0.8 leftEdge = self.instrumentEdgePen.widthF()*2 rightEdge = w-leftEdge tickmarkLeft = leftEdge tickmarkRightMajor = tickmarkLeft+self.TAPE_GAUGES_TICKWIDTH_MAJOR*w tickmarkRightMinor = tickmarkLeft+self.TAPE_GAUGES_TICKWIDTH_MINOR*w numbersLeft = 0.42*w markerTip = (tickmarkLeft*2+tickmarkRightMajor)/3 scaleCenterAltitude = 0 if primaryAltitude == self.UNKNOWN_ALTITUDE else primaryAltitude # altitude scale start = scaleCenterAltitude - self.ALTIMETER_LINEAR_SPAN/2 end = scaleCenterAltitude + self.ALTIMETER_LINEAR_SPAN/2 firstTick = math.ceil(start / self.ALTIMETER_LINEAR_RESOLUTION) * self.ALTIMETER_LINEAR_RESOLUTION lastTick = math.floor(end / self.ALTIMETER_LINEAR_RESOLUTION) * self.ALTIMETER_LINEAR_RESOLUTION tickAlt = firstTick while tickAlt <= lastTick: y = (tickAlt-scaleCenterAltitude)*effectiveHalfHeight/(self.ALTIMETER_LINEAR_SPAN/2) isMajor = tickAlt % self.ALTIMETER_LINEAR_MAJOR_RESOLUTION == 0 painter.resetTransform() painter.translate(area.left(), area.center().y() - y) pen.setColor(Qt.red if tickAlt < 0 else Qt.white) painter.setPen(pen) if isMajor: painter.drawLine(tickmarkLeft, 0, tickmarkRightMajor, 0) self.drawTextLeftCenter(painter, '{0}'.format(abs(tickAlt)), self.mediumTextSize, numbersLeft, 0) else: painter.drawLine(tickmarkLeft, 0, tickmarkRightMinor, 0) tickAlt += self.ALTIMETER_LINEAR_RESOLUTION markerPath = QPainterPath(QPoint(markerTip, 0)) markerPath.lineTo(markerTip+markerHalfHeight, markerHalfHeight) markerPath.lineTo(rightEdge, markerHalfHeight) markerPath.lineTo(rightEdge, -markerHalfHeight) markerPath.lineTo(markerTip+markerHalfHeight, -markerHalfHeight) markerPath.closeSubpath() painter.resetTransform() painter.translate(area.left(), area.center().y()) pen.setWidthF(self.lineWidth) pen.setColor(Qt.white) painter.setPen(pen) painter.setBrush(Qt.SolidPattern) painter.drawPath(markerPath) painter.setBrush(Qt.NoBrush) pen.setColor(Qt.white) painter.setPen(pen) xCenter = (markerTip+rightEdge)/2 alttxt = '---' if primaryAltitude == self.UNKNOWN_ALTITUDE else '%3.0f' % primaryAltitude self.drawTextCenter(painter, alttxt, self.mediumTextSize, xCenter, 0) if vv == self.UNKNOWN_ALTITUDE: return vvPixHeight = -vv / self.ALTIMETER_VVI_SPAN * effectiveHalfHeight if abs(vvPixHeight) < markerHalfHeight: return # hidden behind marker. vvSign = -1 if vvPixHeight > 0: vvSign = 1 # QRectF vvRect(rightEdge - w*ALTIMETER_VVI_WIDTH, markerHalfHeight*vvSign, w*ALTIMETER_VVI_WIDTH, abs(vvPixHeight)*vvSign); vvArrowBegin = QPointF(rightEdge - w*self.ALTIMETER_VVI_WIDTH/2, markerHalfHeight*vvSign) vvArrowEnd = QPointF(rightEdge - w*self.ALTIMETER_VVI_WIDTH/2, vvPixHeight) painter.drawLine(vvArrowBegin, vvArrowEnd) # Yeah this is a repitition of above code but we are goigd to trash it all anyway, so no fix. vvArowHeadSize = abs(vvPixHeight - markerHalfHeight*vvSign) if vvArowHeadSize > w*self.ALTIMETER_VVI_WIDTH/3: vvArowHeadSize = w*self.ALTIMETER_VVI_WIDTH/3 xcenter = rightEdge-w*self.ALTIMETER_VVI_WIDTH/2 vvArrowHead = QPointF(xcenter+vvArowHeadSize, vvPixHeight - vvSign *vvArowHeadSize) painter.drawLine(vvArrowHead, vvArrowEnd) vvArrowHead = QPointF(xcenter-vvArowHeadSize, vvPixHeight - vvSign * vvArowHeadSize) painter.drawLine(vvArrowHead, vvArrowEnd) def drawVelocityMeter(self, painter, area, speed, secondarySpeed): unused(secondarySpeed) painter.resetTransform() self.fillInstrumentBackground(painter, area) pen = QPen() pen.setWidthF(self.lineWidth) h = area.height() w = area.width() effectiveHalfHeight = h*0.45 markerHalfHeight = self.mediumTextSize leftEdge = self.instrumentEdgePen.widthF()*2 tickmarkRight = w-leftEdge tickmarkLeftMajor = tickmarkRight-w*self.TAPE_GAUGES_TICKWIDTH_MAJOR tickmarkLeftMinor = tickmarkRight-w*self.TAPE_GAUGES_TICKWIDTH_MINOR numbersRight = 0.42*w markerTip = (tickmarkLeftMajor+tickmarkRight*2)/3 # Select between air and ground speed: centerScaleSpeed = 0 if speed == self.UNKNOWN_SPEED else speed start = centerScaleSpeed - self.AIRSPEED_LINEAR_SPAN/2 end = centerScaleSpeed +self. AIRSPEED_LINEAR_SPAN/2 firstTick = math.ceil(start / self.AIRSPEED_LINEAR_RESOLUTION) * self.AIRSPEED_LINEAR_RESOLUTION lastTick = math.floor(end / self.AIRSPEED_LINEAR_RESOLUTION) * self.AIRSPEED_LINEAR_RESOLUTION tickSpeed = firstTick while tickSpeed <= lastTick: if tickSpeed < 0: pen.setColor(Qt.red) else: pen.setColor(Qt.white) painter.setPen(pen) y = (tickSpeed-centerScaleSpeed)*effectiveHalfHeight/(self.AIRSPEED_LINEAR_SPAN/2) hasText = tickSpeed % self.AIRSPEED_LINEAR_MAJOR_RESOLUTION == 0 painter.resetTransform() painter.translate(area.left(), area.center().y() - y) if hasText: painter.drawLine(tickmarkLeftMajor, 0, tickmarkRight, 0) self.drawTextRightCenter(painter, '{0}'.format(abs(tickSpeed)), self.mediumTextSize, numbersRight, 0) else: painter.drawLine(tickmarkLeftMinor, 0, tickmarkRight, 0) tickSpeed += self.AIRSPEED_LINEAR_RESOLUTION markerPath = QPainterPath(QPoint(markerTip, 0)) markerPath.lineTo(markerTip-markerHalfHeight, markerHalfHeight) markerPath.lineTo(leftEdge, markerHalfHeight) markerPath.lineTo(leftEdge, -markerHalfHeight) markerPath.lineTo(markerTip-markerHalfHeight, -markerHalfHeight) markerPath.closeSubpath() painter.resetTransform() painter.translate(area.left(), area.center().y()) pen.setWidthF(self.lineWidth) pen.setColor(Qt.white) painter.setPen(pen) painter.setBrush(Qt.SolidPattern) painter.drawPath(markerPath) painter.setBrush(Qt.NoBrush) pen.setColor(Qt.white) painter.setPen(pen) xCenter = (markerTip+leftEdge)/2 spdtxt = '---' if speed == self.UNKNOWN_SPEED else '%3.1f' % speed self.drawTextCenter(painter, spdtxt, self.mediumTextSize, xCenter, 0) def shouldDisplayNavigationData(self): return True def __getAdditionalParameter(self, param, defaultValue = 0): if param in self.additionalParameters: return self.additionalParameters[param] return defaultValue <file_sep>/src/gcs/telemetry.py import os, struct from secrets import token_bytes from enum import Enum from time import time, sleep from collections import deque from pymavlink import mavutil from pymavlink.mavutil import mavlogfile, mavlink from pymavlink.mavwp import MAVWPLoader from PyQt5.QtCore import (QMutex, Qt, QThread, QTimer, QVariant, QObject, QWaitCondition, pyqtSignal) from PyQt5.QtWidgets import (QComboBox, QGridLayout, QLabel, QPushButton, QLineEdit, QFileDialog, QSizePolicy, QWidget, QTabWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QProgressBar) from PyQt5.QtGui import QFontMetrics from serial.tools.list_ports import comports from parameters import ParameterPanel from waypoint import Waypoint from UserData import UserData from uas import UASInterfaceFactory BAUD_RATES = { 0 : 'AUTO', 110 : '110', 300 : '300', 600 : '600', 1200 : '1200', 2400 : '2400', 4800 : '4800', 9600 : '9600', 14400 : '14400', 19200 : '19200', 38400 : '38400', 56000 : '56000', 57600 : '57600', 115200 : '115200', 128000 : '128000', 230400 : '230400', 256000 : '256000', 406800 : '406800', 921600 : '921600' } FLOW_CONTROL = { 0 : 'None', 1 : 'HW', 2 : 'SW' } PARITY = { 0 : 'None', 1 : 'Odd', 2 : 'Even' } DATA_BITS = { 8 : '8', 7 : '7', 6 : '6', 5 : '5' } STOP_BITS = { 1 : '1', 2 : '2' } MAVLINK_DIALECTS = { mavlink.MAV_AUTOPILOT_GENERIC : 'standard', # mavlink.MAV_AUTOPILOT_RESERVED : '', mavlink.MAV_AUTOPILOT_SLUGS : 'slugs', mavlink.MAV_AUTOPILOT_ARDUPILOTMEGA : 'ardupilotmega', mavlink.MAV_AUTOPILOT_OPENPILOT : 'standard', mavlink.MAV_AUTOPILOT_GENERIC_WAYPOINTS_ONLY : 'minimal', mavlink.MAV_AUTOPILOT_GENERIC_WAYPOINTS_AND_SIMPLE_NAVIGATION_ONLY : 'minimal', mavlink.MAV_AUTOPILOT_GENERIC_MISSION_FULL : 'standard', # mavlink.MAV_AUTOPILOT_INVALID : '', mavlink.MAV_AUTOPILOT_PPZ : 'paparazzi', mavlink.MAV_AUTOPILOT_UDB : 'standard', mavlink.MAV_AUTOPILOT_FP : 'standard', mavlink.MAV_AUTOPILOT_PX4 : 'standard', mavlink.MAV_AUTOPILOT_SMACCMPILOT : 'standard', mavlink.MAV_AUTOPILOT_AUTOQUAD : 'autoquad', mavlink.MAV_AUTOPILOT_ARMAZILA : 'standard', mavlink.MAV_AUTOPILOT_AEROB : 'standard', mavlink.MAV_AUTOPILOT_ASLUAV : 'ASLUAV', mavlink.MAV_AUTOPILOT_SMARTAP : 'standard', mavlink.MAV_AUTOPILOT_AIRRAILS : 'standard' } UD_TELEMETRY_KEY = 'TELEMETRY' UD_TELEMETRY_LOG_FOLDER_KEY = 'LOG_FOLDER' UD_TELEMETRY_TIMEOUT_THRESHOLD_KEY = 'TIMEOUT_THRESHOLD' UD_TELEMETRY_HEARTBEAT_TIMEOUT_KEY = 'HB_TIMEOUT' UD_TELEMETRY_LAST_CONNECTION_KEY = 'LAST_CONN' UD_TELEMETRY_LAST_CONNECTION_PORT_KEY = 'PORT' UD_TELEMETRY_LAST_CONNECTION_BAUD_RATE_KEY = 'BAUD_RATE' DEFAULT_RC_AUTO_SCALE_SAMPLES = 10 MAVLINKV2_MESSAGE_SIGNING_KEY_LEN = 32 # bytes class MavStsKeys(Enum): AP_SYS_ID = 0 VEHICLE_TYPE = 1 AP_TYPE = 2 AP_MODE = 3 CUSTOM_AP_MODE = 4 AP_SYS_STS = 5 MAVLINK_VER = 6 class MessageSigningSetupWindow(QWidget): __mavlinkVersionUpdated = pyqtSignal() setMessageSigningKeySignal = pyqtSignal(object, object) # key(hex str), initial timestamp (str of 64 bit integer) def __init__(self, mavlinkVersion = -1.0, parent = None): super().__init__(parent) self.setWindowTitle('Message Signing') self.__mavlinkVersion = mavlinkVersion self.setLayout(QGridLayout()) self.__initUI() self.__mavlinkVersionUpdated.connect(self.__initUI) def setMAVLinkVersion(self, mavlinkVersion): print('Set MAVLink version to:', mavlinkVersion) self.__mavlinkVersion = float(mavlinkVersion) self.__mavlinkVersionUpdated.emit() def __initUI(self): l = self.layout() self.cancelButton = QPushButton('Close') self.cancelButton.clicked.connect(self.close) row = 0 if self.__mavlinkVersion == 1.0: self.__errorMessage('Message signing is not available in MAVLink v1') elif self.__mavlinkVersion == 2.0: self.__errorMessage('Setup Message Signing') row += 1 l.addWidget(QLabel('Secret Key'), row, 0, 1, 1) self.msgSignSecretField = QLineEdit() l.addWidget(self.msgSignSecretField, row, 1, 1, 1) self.generateButton = QPushButton('Random') self.generateButton.clicked.connect(self.__generateRandomSigningKey) l.addWidget(self.generateButton, row, 2, 1, 1) row += 1 l.addWidget(QLabel('Initial Timestamp'), row, 0, 1, 1) self.msgSignTimeField = QLineEdit() l.addWidget(self.msgSignTimeField, row, 1, 1, 1) self.nowButton = QPushButton('Now') self.nowButton.clicked.connect(self.__getCurrentMavlinkV2Time) l.addWidget(self.nowButton, row, 2, 1, 1) row += 1 self.okayButton = QPushButton('OK') self.cancelButton.setText('Cancel') self.okayButton.clicked.connect(self.__processMsgSigningSetup) l.addWidget(self.okayButton, row, 0, 1, 1, Qt.AlignRight) l.addWidget(self.cancelButton, row, 1, 1, 1, Qt.AlignRight) ft = self.msgSignSecretField.font() if ft != None: metrics = QFontMetrics(ft) # metrics.height() ~ metrics.width() x 2 w = metrics.height() * MAVLINKV2_MESSAGE_SIGNING_KEY_LEN self.msgSignSecretField.setFixedWidth(w) self.msgSignTimeField.setFixedWidth(w) elif self.__mavlinkVersion == -1.0: self.__errorMessage('Connect to MAVLink first') else: self.__errorMessage('Unknown MAVLink version: {}'.format(self.__mavlinkVersion)) self.setLayout(l) def __errorMessage(self, msg): msgLabel = self.layout().itemAt(0) if msgLabel == None: self.layout().addWidget(QLabel(msg), 0, 0, 1, 1) else: msgLabel.widget().setText(msg) def __generateRandomSigningKey(self): key = token_bytes(MAVLINKV2_MESSAGE_SIGNING_KEY_LEN).hex() self.msgSignSecretField.setText(key) def __getCurrentMavlinkV2Time(self): # units of 10 microseconds since 01-JAN-2015 GMT # https://mavlink.io/en/guide/message_signing.html#timestamp tm = int((time() - 1420070400) * 100 * 1000) self.msgSignTimeField.setText(str(tm)) def __processMsgSigningSetup(self): self.setMessageSigningKeySignal.emit(self.msgSignSecretField.text(), self.msgSignTimeField.text()) class RadioControlTelemetryWindow(QWidget): def __init__(self, parent = None): super().__init__(parent) self.isAnyRCChannelsUpdate = False self.__defaultWidget = None self.setWindowTitle('Radio Control Telemetry') self.__createDefaultWidget() self.tabs = QTabWidget() self.tabs.addTab(self.__defaultWidget, 'RC Telemetry') self.ports = {} l = QVBoxLayout() l.addWidget(self.tabs) self.setLayout(l) def updateRCChannelValues(self, msg): if msg.port not in self.ports: if self.isAnyRCChannelsUpdate == False: self.isAnyRCChannelsUpdate = True self.tabs.removeTab(0) self.ports[msg.port] = RadioControlTelemetryPanel() self.tabs.addTab(self.ports[msg.port], 'Receiver {}'.format(msg.port)) channels = [] channels.append(msg.chan1_raw) channels.append(msg.chan2_raw) channels.append(msg.chan3_raw) channels.append(msg.chan4_raw) channels.append(msg.chan5_raw) channels.append(msg.chan6_raw) channels.append(msg.chan7_raw) channels.append(msg.chan8_raw) self.ports[msg.port].updateValues(channels) def __createDefaultWidget(self): self.__defaultWidget = QWidget() l = QVBoxLayout() l.addWidget(QLabel('No RC channel value message has been received.')) self.__defaultWidget.setLayout(l) class RadioControlTelemetryPanel(QWidget): def __init__(self, parent = None): super().__init__(parent) l = QGridLayout() self.__autoScaleSamples = DEFAULT_RC_AUTO_SCALE_SAMPLES self.channelValueRanges = [] # (min, max, samples) self.channelValueBars = [] self.channelValueLabels = [] for i in range(8): self.channelValueRanges.append((1000000, 0, 0)) self.channelValueBars.append(QProgressBar(self)) self.channelValueLabels.append(QLabel('0 ms', self)) self.channelValueBars[i].setRange(1000, 2000) self.channelValueBars[i].setTextVisible(False) l.addWidget(QLabel('Channel {}'.format(i + 1)), i, 0, 1, 1) l.addWidget(self.channelValueBars[i], i, 1, 1, 1) l.addWidget(self.channelValueLabels[i], i, 2, 1, 1) l.setColumnStretch(1, 1) self.setLayout(l) def updateValues(self, values): for i in range(8): if values[i] < self.channelValueRanges[i][0]: self.channelValueRanges[i] = (values[i], self.channelValueRanges[i][1], self.channelValueRanges[i][2]) if values[i] > self.channelValueRanges[i][1]: self.channelValueRanges[i] = (self.channelValueRanges[i][0], values[i], self.channelValueRanges[i][2]) if self.channelValueRanges[i][1] > self.channelValueRanges[i][0]: if self.channelValueRanges[i][2] < self.__autoScaleSamples: # First `self.__autoScaleSamples` samples will always be used to update scale self.channelValueBars[i].setRange(self.channelValueRanges[i][0], self.channelValueRanges[i][1]) self.channelValueRanges[i] = (self.channelValueRanges[i][0], self.channelValueRanges[i][1], self.channelValueRanges[i][2] + 1) else: # After that, only values exceeding current ranges will be updated if self.channelValueRanges[i][0] < self.channelValueBars[i].minimum(): self.channelValueBars[i].setMinimum(self.channelValueRanges[i][0]) if self.channelValueRanges[i][1] > self.channelValueBars[i].maximum(): self.channelValueBars[i].setMaximum(self.channelValueRanges[i][1]) self.channelValueBars[i].setValue(values[i]) self.channelValueLabels[i].setText('{} ms'.format(values[i])) class ConnectionEditWindow(QWidget): MAVLinkConnectedSignal = pyqtSignal(object) cancelConnectionSignal = pyqtSignal() def __init__(self, parent = None): super().__init__(parent) self.tabs = QTabWidget(self) self._createTabs() l = QVBoxLayout() l.setContentsMargins(0, 0, 0, 0) l.addWidget(self.tabs) l.addWidget(self.__createActionButtons()) self.setLayout(l) def _createTabs(self): self.serialConnTab = SerialConnectionEditTab(parent=self) self.logReplayTab = LogFileReplayEditTab(self) self.tabs.addTab(self.serialConnTab, 'Serial Link') self.tabs.addTab(self.logReplayTab, 'Log File Replay') def __createActionButtons(self): l = QHBoxLayout() l.setContentsMargins(5, 0, 5, 5) self.connectButton = QPushButton('Connect') self.closeButton = QPushButton('Close') self.connectButton.clicked.connect(self._doConnect) self.closeButton.clicked.connect(self.close) l.addWidget(self.connectButton) l.addWidget(self.closeButton) self.actionButtonWidget = QWidget() self.actionButtonWidget.setLayout(l) return self.actionButtonWidget def closeEvent(self, event): self.cancelConnectionSignal.emit() super().closeEvent(event) def _doConnect(self): currTab = self.tabs.currentWidget() if hasattr(currTab, 'doConnect'): if currTab.doConnect(): self.close() class LogFileReplaySpeedControl(mavlogfile, QObject): replayCompleteSignal = pyqtSignal() def __init__(self, filename): mavlogfile.__init__(self, filename) QObject.__init__(self) self.replaySpeed = 1.0 def pre_message(self): super().pre_message() if self._last_timestamp is not None and self.replaySpeed > 0: ts = abs(self._timestamp - self._last_timestamp) * self.replaySpeed sleep(ts) def recv(self,n=None): b = super().recv(n) if b == None or len(b) < n: self.replayCompleteSignal.emit() return b def write(self, buf): '''Log files will be open in read only mode. All write operations are ignored.''' pass class LogFileReplayEditTab(QWidget): def __init__(self, parent): super().__init__(parent) self.MAVLinkConnectedSignal = parent.MAVLinkConnectedSignal l = QVBoxLayout() l.setAlignment(Qt.AlignTop) lbl = QLabel('Choose Log File') l.addWidget(lbl) fileWidget = QWidget(self) l1 = QHBoxLayout() self.logFilePathEdit = QLineEdit(self) sp = self.logFilePathEdit.sizePolicy() sp.setHorizontalStretch(1) self.logFilePathEdit.setSizePolicy(sp) l1.addWidget(self.logFilePathEdit) self.browseButton = QPushButton('Browse') self.browseButton.clicked.connect(self.__chooseLogFile) l1.addWidget(self.browseButton) fileWidget.setLayout(l1) l.addWidget(fileWidget) self.setLayout(l) def doConnect(self): fileName = self.logFilePathEdit.text() if os.path.isfile(fileName): print('Replay Log file:', fileName) connection = LogFileReplaySpeedControl(fileName) self.MAVLinkConnectedSignal.emit(connection) return True QMessageBox.critical(self.window(), 'Error', 'Invalid log file: {}'.format(fileName), QMessageBox.Ok) return False def __chooseLogFile(self): fileName = QFileDialog.getOpenFileName(self, 'Choose Log File') if fileName != None: self.logFilePathEdit.setText(fileName[0]) class SerialConnectionEditTab(QWidget): __autoBaudStartSignal = pyqtSignal(object) def __init__(self, initParams = None, parent = None): super().__init__(parent) self.portList = {} self.autoBaud = None self.MAVLinkConnectedSignal = parent.MAVLinkConnectedSignal self.MAVLinkConnectedSignal.connect(self.__recordLastConnection) self.__autoBaudStartSignal.connect(self.__autoBaud) self.listSerialPorts() if initParams == None: self.params = self.__getLastConnectionParameter() else: self.params = initParams l = QGridLayout() row = 0 lbl, self.portsDropDown = self._createDropDown( 'Serial Port', self.portList, UserData.getParameterValue(self.params, UD_TELEMETRY_LAST_CONNECTION_PORT_KEY)) l.addWidget(lbl, row, 0, 1, 1, Qt.AlignRight) l.addWidget(self.portsDropDown, row, 1, 1, 3, Qt.AlignLeft) self.refreshButton = QPushButton('\u21BB') # Unicode for clockwise open circle arrow self.refreshButton.setFixedSize(self.portsDropDown.height(), self.portsDropDown.height()) l.addWidget(self.refreshButton, row, 4, 1, 1, Qt.AlignLeft) self.refreshButton.clicked.connect(lambda: self.listSerialPorts(self.portsDropDown)) row += 1 lbl, self.baudDropDown = self._createDropDown( 'Baud Rate', BAUD_RATES, UserData.getParameterValue(self.params, UD_TELEMETRY_LAST_CONNECTION_BAUD_RATE_KEY)) l.addWidget(lbl, row, 0, 1, 1, Qt.AlignRight) l.addWidget(self.baudDropDown, row, 1, 1, 3, Qt.AlignLeft) row += 1 lbl, self.flowDropDown = self._createDropDown('Flow Control', FLOW_CONTROL) l.addWidget(lbl, row, 0, 1, 1, Qt.AlignRight) l.addWidget(self.flowDropDown, row, 1, 1, 1, Qt.AlignLeft) lbl, self.parityDropDown = self._createDropDown('Parity', PARITY) l.addWidget(lbl, row, 2, 1, 1, Qt.AlignRight) l.addWidget(self.parityDropDown, row, 3, 1, 1, Qt.AlignLeft) row += 1 lbl, self.bitsDropDown = self._createDropDown('Data Bits', DATA_BITS) l.addWidget(lbl, row, 0, 1, 1, Qt.AlignRight) l.addWidget(self.bitsDropDown, row, 1, 1, 1, Qt.AlignLeft) lbl, self.stopDropDown = self._createDropDown('Stop Bits', STOP_BITS) l.addWidget(lbl, row, 2, 1, 1, Qt.AlignRight) l.addWidget(self.stopDropDown, row, 3, 1, 1, Qt.AlignLeft) row += 1 self.autoBaudMessageLabel = QLabel('') l.addWidget(self.autoBaudMessageLabel, row, 0, 1, 3) row += 1 self.setLayout(l) def _createDropDown(self, label, data: dict, defaultValue = None): dropDown = QComboBox(self) dropDown.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) i = 0 for key, val in data.items(): dropDown.addItem(str(val), QVariant(key)) if key == defaultValue: dropDown.setCurrentIndex(i) i += 1 return QLabel(label), dropDown def listSerialPorts(self, dropDown = None): portsInfo = sorted(comports(False)) cnts = 0 self.portList.clear() for p in portsInfo: self.portList[p.device] = p cnts += 1 if cnts == 0: self.portList['No ports available'] = 'No ports available' if dropDown != None: while dropDown.count() > 0: dropDown.removeItem(0) for key, val in self.portList.items(): dropDown.addItem(str(val), QVariant(key)) def doConnect(self): port = self.portsDropDown.currentData() baud = self.baudDropDown.currentData() if baud == 0: self.__autoBaudStartSignal.emit(port) return False # Keep window open while auto bauding connection = mavutil.mavlink_connection(port, int(baud)) self.MAVLinkConnectedSignal.emit(connection) return True def __autoBaud(self, port): self.autoBaud = AutoBaudThread(port, self) # This Tab QTabWidget QWidget self.autoBaud.finished.connect(self.parentWidget().parentWidget().parentWidget().close) self.autoBaud.autoBaudStatusUpdateSignal.connect(self.autoBaudMessageLabel.setText) self.autoBaud.start() def __recordLastConnection(self, conn): if isinstance(conn, mavlogfile) == False: self.params[UD_TELEMETRY_LAST_CONNECTION_PORT_KEY] = conn.device self.params[UD_TELEMETRY_LAST_CONNECTION_BAUD_RATE_KEY] = conn.baud def __getLastConnectionParameter(self): pParam = UserData.getInstance().getUserDataEntry(UD_TELEMETRY_KEY, {}) return UserData.getParameterValue(pParam, UD_TELEMETRY_LAST_CONNECTION_KEY, {}) class AutoBaudThread(QThread): autoBaudStatusUpdateSignal = pyqtSignal(object) def __init__(self, port, parent): super().__init__(parent) self.MAVLinkConnectedSignal = parent.MAVLinkConnectedSignal self.port = port def run(self): for b in BAUD_RATES: if b >= self.__minimumBaudRate(): self.autoBaudStatusUpdateSignal.emit('AutoBaud: try baud rate {}'.format(b)) conn = mavutil.mavlink_connection(self.port, b) hb = conn.wait_heartbeat(timeout=2.0) # set timeout to 2 second if hb == None: self.autoBaudStatusUpdateSignal.emit('AutoBaud: timeout for baud rate {}'.format(b)) # Reset environment variables after a failed attempt # Otherwise mavutil.auto_mavlink_version may result in # unexpected behaviour if 'MAVLINK09' in os.environ: del os.environ['MAVLINK09'] if 'MAVLINK20' in os.environ: del os.environ['MAVLINK20'] conn.close() else: self.autoBaudStatusUpdateSignal.emit('AutoBaud: correct baud rate is {}'.format(b)) self.MAVLinkConnectedSignal.emit(conn) return # Fail back to default mavlink baud rate self.autoBaudStatusUpdateSignal.emit('AutoBaud: default 57600') self.MAVLinkConnectedSignal.emit(mavutil.mavlink_connection(self.port, 57600)) def __minimumBaudRate(self): return 4800 class MAVLinkConnection(QThread): externalMessageHandler = pyqtSignal(object) # pass any types of message to an external handler connectionEstablishedSignal = pyqtSignal() onboardWaypointsReceivedSignal = pyqtSignal(object) # pass the list of waypoints as parameter newTextMessageSignal = pyqtSignal(object) messageTimeoutSignal = pyqtSignal(float) # pass number of seconds without receiving any messages heartbeatTimeoutSignal = pyqtSignal() DEFAULT_MESSAGE_TIMEOUT_THRESHOLD = 2.0 DEFAULT_HEARTBEAT_TIMEOUT= 5.0 def __init__(self, connection, replayMode = False, enableLog = True): super().__init__() self.internalHandlerLookup = {} self.mavStatus = {MavStsKeys.AP_SYS_ID : 1} self.isConnected = False # self.paramList = [] self.paramPanel = None self.txLock = QMutex() # uplink lock self.txResponseCond = QWaitCondition() self.txTimeoutTimer = QTimer() self.finalWPSent = False self.wpLoader = MAVWPLoader() self.onboardWPCount = 0 self.numberOfonboardWP = 0 self.onboardWP = [] self.mavlinkLogFile = None self.lastMessageReceivedTimestamp = 0.0 self.lastMessages = {} # type = (msg, timestamp) self.param = UserData.getInstance().getUserDataEntry(UD_TELEMETRY_KEY, {}) self.messageTimeoutThreshold = UserData.getParameterValue(self.param, UD_TELEMETRY_TIMEOUT_THRESHOLD_KEY, MAVLinkConnection.DEFAULT_MESSAGE_TIMEOUT_THRESHOLD) self.txTimeoutmsec = self.messageTimeoutThreshold * 1000000 # timeout for wait initial heartbeat signal self.initHeartbeatTimeout = UserData.getParameterValue(self.param, UD_TELEMETRY_HEARTBEAT_TIMEOUT_KEY, MAVLinkConnection.DEFAULT_HEARTBEAT_TIMEOUT) self.txMessageQueue = deque() self.running = True self.connection = connection self.replayMode = replayMode self.enableLog = enableLog self.uas = None if replayMode: self.enableLog = False connection.replayCompleteSignal.connect(self.requestExit) self.internalHandlerLookup['PARAM_VALUE'] = self.receiveOnboardParameter self.internalHandlerLookup['MISSION_REQUEST'] = self.receiveMissionRequest self.internalHandlerLookup['MISSION_ACK'] = self.receiveMissionAcknowledge self.internalHandlerLookup['MISSION_COUNT'] = self.receiveMissionItemCount self.internalHandlerLookup['MISSION_ITEM'] = self.receiveMissionItem self.internalHandlerLookup['DATA_STREAM'] = self.receiveDataStream self.internalHandlerLookup['PARAM_SET'] = self.receiveParameterSet self.txTimeoutTimer.timeout.connect(self._timerTimeout) self.txTimeoutTimer.setSingleShot(True) # print('waiting for heart beat...') # self._establishConnection() def requestExit(self): # print('exit conn thread...') self.running = False def run(self): while self.running: msg = self.connection.recv_match(blocking=False) if msg != None: msgType = msg.get_type() if msgType != 'BAD_DATA': # exclude BAD_DATA from any other messages self.lastMessageReceivedTimestamp = time() self.lastMessages[msgType] = (msg, self.lastMessageReceivedTimestamp) if self.enableLog: ts = int(time() * 1.0e6) & ~3 self.mavlinkLogFile.write(struct.pack('>Q', ts) + msg.get_msgbuf()) # 1. send message to external destination self.externalMessageHandler.emit(msg) # 2. process message with internal UASInterface self.uas.receiveMAVLinkMessage(msg) # 3. process message with other internal handlers if msgType in self.internalHandlerLookup: self.internalHandlerLookup[msgType](msg) else: # TODO handle BAD_DATA? print('BAD_DATA:', msg) rs = time() - self.lastMessageReceivedTimestamp if (rs > self.messageTimeoutThreshold): print('Message timeout:', rs) self.messageTimeoutSignal.emit(rs) try: txMsg = self.txMessageQueue.popleft() print('sending mavlink msg:', txMsg) self.connection.mav.send(txMsg) except IndexError: pass self.__doDisconnect() def __doDisconnect(self, txtmsg = 'Disconnected'): self.connection.close() self.isConnected = False if self.enableLog and self.mavlinkLogFile != None: self.mavlinkLogFile.close() self.uas.resetOnboardParameterList() self.newTextMessageSignal.emit(txtmsg) def establishConnection(self): hb = self.connection.wait_heartbeat(timeout=self.initHeartbeatTimeout) if hb == None: self.running = False self.__doDisconnect('Connection timeout') self.heartbeatTimeoutSignal.emit() return self.lastMessageReceivedTimestamp = time() self.__createLogFile() self.__setMavlinkDialect(hb.autopilot) self.mavStatus[MavStsKeys.VEHICLE_TYPE] = hb.type self.mavStatus[MavStsKeys.AP_TYPE] = hb.autopilot self.mavStatus[MavStsKeys.AP_MODE] = hb.base_mode self.mavStatus[MavStsKeys.CUSTOM_AP_MODE] = hb.custom_mode self.mavStatus[MavStsKeys.AP_SYS_STS] = hb.system_status self.mavStatus[MavStsKeys.MAVLINK_VER] = hb.mavlink_version # request all parameters if self.replayMode: self.newTextMessageSignal.emit('Conneced in log file replay mode') self.isConnected = True self.connectionEstablishedSignal.emit() else: self.newTextMessageSignal.emit('Conneced to AP:{}'.format(self.mavStatus[MavStsKeys.AP_TYPE])) self.uas.fetchAllOnboardParameters() def receiveOnboardParameter(self, msg): self.uas.acceptOnboardParameter(msg) self.newTextMessageSignal.emit('Param: {} = {}'.format(msg.param_id, msg.param_value)) if self.uas.onboardParamNotReceived == 0: self.newTextMessageSignal.emit('{} parameters received'.format(msg.param_count)) if self.param['DOWNLOAD_WAYPOINTS_ON_CONNECT']: self.downloadWaypoints() # request to read all onboard waypoints if self.isConnected == False: # prevent further signals when refreshing parameters self.isConnected = True self.connectionEstablishedSignal.emit() def receiveMissionItem(self, msg): self.numberOfonboardWP += 1 wp = Waypoint(msg.seq, msg.x, msg.y, msg.z) wp.waypointType = msg.command self.onboardWP.append(wp) if self.numberOfonboardWP < self.onboardWPCount: self.connection.waypoint_request_send(self.numberOfonboardWP) # read next one else: self.newTextMessageSignal.emit('Total {} waypoint(s) onboard'.format(len(self.onboardWP))) self.onboardWaypointsReceivedSignal.emit(self.onboardWP) # all done, send signal def receiveMissionItemCount(self, msg): self.onboardWPCount = msg.count if self.onboardWPCount > 0: self.connection.waypoint_request_send(0) # start reading onboard waypoints def receiveMissionRequest(self, msg): # print('missionRequest:', msg) self.sendMavlinkMessage(self.wpLoader.wp(msg.seq)) def receiveMissionAcknowledge(self, msg): print('missionRequestAck:', msg) self.txResponseCond.wakeAll() def receiveDataStream(self, msg): # DATA_STREAM {stream_id : 10, message_rate : 0, on_off : 0} print(msg) def receiveParameterSet(self, msg): # PARAM_SET {target_system : 81, target_component : 50, param_id : BFLOW_GYRO_COM, param_value : 0.0, param_type : 9} print(msg) def showParameterEditWindow(self): if self.isConnected: if self.uas.onboardParamNotReceived > 0: QMessageBox.warning(None, 'Warning', 'Please wait while receiving all onboard parameters, {} parameters left.'.format(self.uas.onboardParamNotReceived), QMessageBox.Ok) else: self.paramPanel = ParameterPanel(self.uas.onboardParameters) self.paramPanel.uploadNewParametersSignal.connect(self.uploadNewParametersEvent) self.paramPanel.show() def downloadWaypoints(self): self.connection.waypoint_request_list_send() def uploadWaypoints(self, wpList): seq = 0 for wp in wpList: item = wp.toMavlinkMessage(self.connection.target_system, self.connection.target_component, seq, 0, 1) seq += 1 self.wpLoader.add(item) print('all wp queued!') self._sendMissionCount(len(wpList)) def setHomePosition(self, wp): item = mavutil.mavlink.MAVLink_mission_item_message(self.connection.target_system, self.connection.target_component, 0, mavlink.MAV_FRAME_GLOBAL, mavlink.MAV_CMD_DO_SET_HOME , 1, 0, 1, None, None, None, wp.latitude, wp.longitude, wp.altitude) self.sendMavlinkMessage(item) def _sendMissionCount(self, cnt): print('{} waypoints to be sent'.format(cnt)) # self.txTimeoutTimer.start(self.txTimeoutmsec) self.txLock.lock() # self.connection.waypoint_clear_all_send() self.connection.waypoint_count_send(cnt) print('[CNT] wait for response...') self.txResponseCond.wait(self.txLock) self.txLock.unlock() print('[CNT] Got response!') def sendMavlinkMessage(self, msg): ''' Add a mavlink message to the tx queue ''' if msg.target_system == 255: msg.target_system = self.connection.target_system if msg.target_component == 255: msg.target_component = self.connection.target_component self.txMessageQueue.append(msg) def _timerTimeout(self): print('Timeout') self.txResponseCond.wakeAll() def navigateToWaypoint(self, wp: Waypoint): item = mavutil.mavlink.MAVLink_mission_item_message(self.connection.target_system, self.connection.target_component, 0, mavlink.MAV_FRAME_GLOBAL, mavlink.MAV_CMD_NAV_WAYPOINT, 1, 1, # Auto continue to next waypoint 0, 0, 0, 0, wp.latitude, wp.longitude, wp.altitude) self.sendMavlinkMessage(item) def initializeReturnToHome(self): self.connection.set_mode_rtl() def uploadNewParametersEvent(self, params): # the params from UI are MAVLink_param_value_message, # which are required to be consistent with all parameters # download upon connection. They will be converted to # MAVLink_param_set_message before sending to UAV for param in params: paramSet = mavutil.mavlink.MAVLink_param_set_message(self.connection.target_system, self.connection.target_component, param.param_id.encode('utf-8'), param.param_value, param.param_type) self.sendMavlinkMessage(paramSet) def setupMessageSigningKey(self, key, ts): key0 = None ts0 = 0 try: key0 = bytes.fromhex(key) except ValueError: pass try: ts0 = int(ts) except ValueError: pass if self.connection.WIRE_PROTOCOL_VERSION == '2.0': self.connection.setup_signing(key0, allow_unsigned_callback = self.uas.allowUnsignedCallback, initial_timestamp = ts0) def __createLogFile(self): if self.enableLog: name = 'MAV_{}.bin'.format(int(time() * 1000)) self.mavlinkLogFile = open(os.path.join(self.param[UD_TELEMETRY_LOG_FOLDER_KEY], name), 'wb') def __setMavlinkDialect(self, ap): mavutil.mavlink = None # reset previous dialect self.uas = UASInterfaceFactory.getUASInterface(ap) self.uas.mavlinkMessageTxSignal.connect(self.sendMavlinkMessage) if ap in MAVLINK_DIALECTS: print('Set dialect to: {} ({})'.format(MAVLINK_DIALECTS[ap], ap)) mavutil.set_dialect(MAVLINK_DIALECTS[ap]) elif ap != mavlink.MAV_AUTOPILOT_INVALID: # default to common print('Set dialect to common for unknown AP type:', ap) mavutil.set_dialect(MAVLINK_DIALECTS[mavlink.MAV_AUTOPILOT_GENERIC]) # Hot patch after setting mavlink dialect on the fly self.connection.mav = mavutil.mavlink.MAVLink(self.connection, srcSystem=self.connection.source_system, srcComponent=self.connection.source_component) self.connection.mav.robust_parsing = self.connection.robust_parsing self.connection.WIRE_PROTOCOL_VERSION = mavutil.mavlink.WIRE_PROTOCOL_VERSION <file_sep>/src/gcs/WaypointDefault.py from math import nan from enum import Enum from pymavlink.mavutil import mavlink WP_TYPE_NAMES = { mavlink.MAV_CMD_NAV_WAYPOINT : 'Waypoint', mavlink.MAV_CMD_NAV_LOITER_UNLIM : 'Loiter Unlimited', mavlink.MAV_CMD_NAV_LOITER_TURNS : 'Loiter Turns', mavlink.MAV_CMD_NAV_LOITER_TIME : 'Loiter Time', # mavlink.MAV_CMD_NAV_RETURN_TO_LAUNCH : 'Return to Launch', mavlink.MAV_CMD_NAV_LAND : 'Land', mavlink.MAV_CMD_NAV_TAKEOFF : 'Takeoff', mavlink.MAV_CMD_NAV_LAND_LOCAL : 'Land Local', mavlink.MAV_CMD_NAV_TAKEOFF_LOCAL : 'Takeoff Local', mavlink.MAV_CMD_NAV_FOLLOW : 'Follow', mavlink.MAV_CMD_NAV_CONTINUE_AND_CHANGE_ALT : 'Change Altitude', mavlink.MAV_CMD_NAV_LOITER_TO_ALT : 'Loiter to Altitude' } class MAVWaypointParameter(Enum): PARAM1 = 0 PARAM2 = 1 PARAM3 = 2 PARAM4 = 3 PARAM5 = 4 PARAM6 = 5 PARAM7 = 6 WP_NAV_WAYPOINT_DEFAULTS = { MAVWaypointParameter.PARAM1 : 0.0, MAVWaypointParameter.PARAM2 : 0.0, MAVWaypointParameter.PARAM3 : 0.0, MAVWaypointParameter.PARAM4 : nan, MAVWaypointParameter.PARAM5 : 0.0, MAVWaypointParameter.PARAM6 : 0.0, MAVWaypointParameter.PARAM7 : 0.0 } WP_NAV_LOITER_UNLIM_DEFAULTS = { #MAVWaypointParameter.PARAM1 : 0.0, #MAVWaypointParameter.PARAM2 : 0.0, MAVWaypointParameter.PARAM3 : 0.0, MAVWaypointParameter.PARAM4 : nan, MAVWaypointParameter.PARAM5 : 0.0, MAVWaypointParameter.PARAM6 : 0.0, MAVWaypointParameter.PARAM7 : 0.0 } WP_NAV_LOITER_TURNS_DEFAULTS = { MAVWaypointParameter.PARAM1 : 0.0, #MAVWaypointParameter.PARAM2 : 0.0, MAVWaypointParameter.PARAM3 : 0.0, MAVWaypointParameter.PARAM4 : nan, MAVWaypointParameter.PARAM5 : 0.0, MAVWaypointParameter.PARAM6 : 0.0, MAVWaypointParameter.PARAM7 : 0.0 } WP_NAV_LOITER_TIME_DEFAULTS = { MAVWaypointParameter.PARAM1 : 0.0, #MAVWaypointParameter.PARAM2 : 0.0, MAVWaypointParameter.PARAM3 : 0.0, MAVWaypointParameter.PARAM4 : nan, MAVWaypointParameter.PARAM5 : 0.0, MAVWaypointParameter.PARAM6 : 0.0, MAVWaypointParameter.PARAM7 : 0.0 } WP_NAV_LAND_DEFAULTS = { MAVWaypointParameter.PARAM1 : 0.0, MAVWaypointParameter.PARAM2 : mavlink.PRECISION_LAND_MODE_DISABLED, #MAVWaypointParameter.PARAM3 : 0.0, MAVWaypointParameter.PARAM4 : nan, MAVWaypointParameter.PARAM5 : 0.0, MAVWaypointParameter.PARAM6 : 0.0, MAVWaypointParameter.PARAM7 : 0.0 } WP_NAV_TAKEOFF_DEFAULTS = { MAVWaypointParameter.PARAM1 : 0.0, #MAVWaypointParameter.PARAM2 : 0.0, #MAVWaypointParameter.PARAM3 : 0.0, MAVWaypointParameter.PARAM4 : nan, MAVWaypointParameter.PARAM5 : 0.0, MAVWaypointParameter.PARAM6 : 0.0, MAVWaypointParameter.PARAM7 : 0.0 } WP_NAV_LAND_LOCAL_DEFAULTS = { MAVWaypointParameter.PARAM1 : 0.0, MAVWaypointParameter.PARAM2 : 0.0, MAVWaypointParameter.PARAM3 : 0.0, MAVWaypointParameter.PARAM4 : 0.0, MAVWaypointParameter.PARAM5 : 0.0, MAVWaypointParameter.PARAM6 : 0.0, MAVWaypointParameter.PARAM7 : 0.0 } WP_NAV_TAKEOFF_LOCAL_DEFAULTS = { MAVWaypointParameter.PARAM1 : 0.0, #MAVWaypointParameter.PARAM2 : 0.0, MAVWaypointParameter.PARAM3 : 0.0, MAVWaypointParameter.PARAM4 : 0.0, MAVWaypointParameter.PARAM5 : 0.0, MAVWaypointParameter.PARAM6 : 0.0, MAVWaypointParameter.PARAM7 : 0.0 } WP_NAV_FOLLOW_DEFAULTS = { MAVWaypointParameter.PARAM1 : 0.0, MAVWaypointParameter.PARAM2 : 0.0, MAVWaypointParameter.PARAM3 : 0.0, MAVWaypointParameter.PARAM4 : 0.0, MAVWaypointParameter.PARAM5 : 0.0, MAVWaypointParameter.PARAM6 : 0.0, MAVWaypointParameter.PARAM7 : 0.0 } WP_NAV_CONTINUE_AND_CHANGE_ALT_DEFAULTS = { MAVWaypointParameter.PARAM1 : 0.0, #MAVWaypointParameter.PARAM2 : 0.0, #MAVWaypointParameter.PARAM3 : 0.0, #MAVWaypointParameter.PARAM4 : 0.0, #MAVWaypointParameter.PARAM5 : 0.0, #MAVWaypointParameter.PARAM6 : 0.0, MAVWaypointParameter.PARAM7 : 0.0 } WP_NAV_LOITER_TO_ALT_DEFAULTS = { MAVWaypointParameter.PARAM1 : 0.0, MAVWaypointParameter.PARAM2 : 0.0, #MAVWaypointParameter.PARAM3 : 0.0, MAVWaypointParameter.PARAM4 : 0.0, MAVWaypointParameter.PARAM5 : 0.0, MAVWaypointParameter.PARAM6 : 0.0, MAVWaypointParameter.PARAM7 : 0.0 } WP_DEFAULTS = { mavlink.MAV_CMD_NAV_WAYPOINT : WP_NAV_WAYPOINT_DEFAULTS, mavlink.MAV_CMD_NAV_LOITER_UNLIM : WP_NAV_LOITER_UNLIM_DEFAULTS, mavlink.MAV_CMD_NAV_LOITER_TURNS : WP_NAV_LOITER_TURNS_DEFAULTS, mavlink.MAV_CMD_NAV_LOITER_TIME : WP_NAV_LOITER_TIME_DEFAULTS, mavlink.MAV_CMD_NAV_LAND : WP_NAV_LAND_DEFAULTS, mavlink.MAV_CMD_NAV_TAKEOFF : WP_NAV_TAKEOFF_DEFAULTS, mavlink.MAV_CMD_NAV_LAND_LOCAL : WP_NAV_LAND_LOCAL_DEFAULTS, mavlink.MAV_CMD_NAV_TAKEOFF_LOCAL : WP_NAV_TAKEOFF_LOCAL_DEFAULTS, mavlink.MAV_CMD_NAV_FOLLOW : WP_NAV_FOLLOW_DEFAULTS, mavlink.MAV_CMD_NAV_CONTINUE_AND_CHANGE_ALT : WP_NAV_CONTINUE_AND_CHANGE_ALT_DEFAULTS, mavlink.MAV_CMD_NAV_LOITER_TO_ALT : WP_NAV_LOITER_TO_ALT_DEFAULTS }
bc19819771863e0e682c25bf29e018bbd80c902e
[ "Markdown", "Python", "Text" ]
25
Python
wangyeee/MiniGCS
70458734591a56bd3918b347a729c3c201320142
3933d6bbdec7fd6ecd7ac677903087cd3925d903
refs/heads/master
<file_sep>function investmentHistoryData() { var investmentHistory = [ { invested_at: "2020-1-07 12:03pm", amount: "45000", paid: "20000", details: "View More", }, { invested_at: "2020-02-07 8:00am", amount: "10000", paid: "5000", details: "View More", }, { invested_at: "2020-02-07 3:10pm", amount: "2020-02-07", paid: "40000", details: "View More", }, ]; var investmentTable = document.querySelector("#investmentTable"); var noOfInvestment = investmentHistory.length; if (noOfInvestment > 0) { var col = []; // define an empty array for (var i = 0; i < noOfInvestment; i++) { for (var key in investmentHistory[i]) { if (col.indexOf(key) === -1) { col.push(key); } } } // CREATE TABLE HEAD . var tHead = document.querySelector("#tableHead"); // CREATE ROW FOR TABLE HEAD . var hRow = document.querySelector("#tableRow"); // ADD COLUMN HEADER TO ROW OF TABLE HEAD. tHead.appendChild(hRow); investmentTable.appendChild(tHead); // CREATE TABLE BODY . var tBody = document.createElement("tbody"); // ADD COLUMN HEADER TO ROW OF TABLE HEAD. for (var i = 0; i < noOfInvestment; i++) { var bRow = document.createElement("tr"); // CREATE ROW FOR EACH RECORD . var td = document.createElement("td"); for (var j = 0; j < col.length; j++) { var td = document.createElement("td"); if (j == 3) { td.innerHTML = '<a href="investmentDetails.html"><div style="font-size:large;" class="badge badge-success">' + investmentHistory[i][col[j]] + "</div></a>"; bRow.appendChild(td); } else { td.innerHTML = investmentHistory[i][col[j]]; bRow.appendChild(td); } } tBody.appendChild(bRow); } investmentTable.appendChild(tBody); } }
a5e022c02817036311bb68af6722833e83345a32
[ "JavaScript" ]
1
JavaScript
Ezehchibuogwu/getrich
d2f734b1549f43cefcbddbf7e4ef1850a5a6ff66
b5b85b794f2d8b65022599e52248662a09c9be66
refs/heads/master
<repo_name>sophdubs/FEND-restaurant-review-app<file_sep>/sw.js //these are all the files and images that we need to cache in order to render a functioning page offline const filesToCache = [ '/css/styles.css', '/data/restaurants.json', '/img/1.jpg', '/img/2.jpg', '/img/3.jpg', '/img/4.jpg', '/img/5.jpg', '/img/6.jpg', '/img/7.jpg', '/img/8.jpg', '/img/9.jpg', '/js/dbhelper.js', '/js/main.js', '/js/restaurant_info.js', '/', '/index.html', '/restaurant.html' ]; //This event listener will be called once the SW is registered and will open the cache if //one is not already opened and save all of the files in "filesToCache" into the cache. self.addEventListener('install', function(event){ event.waitUntil( caches.open('v1').then(function(cache){ return cache.addAll(filesToCache); }) ); }); //This event listener is waiting for fetch requests. If the event we are trying to fetch is already in the cache, //we will return the cached response. Otherwise, we will fetch the response from the browser and save it in the cache. self.addEventListener('fetch', function(event){ event.respondWith( caches.match(event.request).then(function(response){ if(response){ return response; } else { return fetch(event.request) .then(function(response) { const clonedResponse = response.clone(); caches.open('v1').then(function(cache) { cache.put(event.request, clonedResponse); }) return response; }) .catch(function(error){ console.log(error); }) } }) ); });
f8a80b8b64aafd02d10fa70ea56169d2f63517c8
[ "JavaScript" ]
1
JavaScript
sophdubs/FEND-restaurant-review-app
8b52b8adce58285c8b0c94efa03d888495fe696e
2047957057ef574bba0868fcee810974580d1096
refs/heads/master
<file_sep>import React, { Component } from 'react' import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import Paper from '@material-ui/core/Paper'; import Grid from '@material-ui/core/Grid'; import Button from '@material-ui/core/Button'; //Router import { withRouter } from 'react-router-dom'; const styles = theme => ({ content: { padding: theme.spacing.unit * 10, }, paper: { height: 90, width: 350, }, toolbar: { alignItems: 'center', justifyContent: 'flex-end', ...theme.mixins.toolbar, }, }); class ItemMenu extends Component { render() { const { classes, history, icono, primerTexto, ruta, textArea, vista } = this.props; return ( <Paper className={classes.paper}> <Grid container spacing={24}> <Grid item xs={4}> <Button variant="contained" className={vista} onClick={() => history.push(ruta)}> {icono} </Button> </Grid> <Grid item xs={1} sm container> <Grid item xs container direction="column" > <Grid item xs> <Typography gutterBottom variant="subtitle1"> {primerTexto} </Typography> <Typography color="textSecondary"> {textArea} </Typography> </Grid> </Grid> </Grid> </Grid> </Paper> ) } } ItemMenu.propTypes = { classes: PropTypes.object.isRequired, theme: PropTypes.object.isRequired, }; export default withRouter(withStyles(styles, { withTheme: true })(ItemMenu));<file_sep>import React, { Component } from 'react' import Titulo from '../../Componentes/bannerTitulos/titulo' import Menu from '../../Componentes/menus/Menu' class Inicio extends Component{ render(){ return( <div> <Titulo esActivarBotonInicio={false} titulo='Menu Soporte' /> <Menu /> </div> ); } } export default Inicio;<file_sep>//Colores const rojo = "#FF0000"; const verde = "#4caf50"; const blanco = "#FFFFFF"; export { verde, rojo, blanco, };<file_sep>import React, { Component } from 'react' import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import Toolbar from '@material-ui/core/Toolbar'; import AppBar from '@material-ui/core/AppBar'; import Typography from '@material-ui/core/Typography'; import Button from '@material-ui/core/Button'; //Router import { withRouter } from 'react-router-dom'; // Iconos import ReplyIcon from '@material-ui/icons/Reply'; const styles = theme => ({ colorTitulo: { backgroundColor: "#1b344c", }, grow: { flexGrow: 1, }, leftIcon: { marginRight: theme.spacing.unit, }, }); class BotonInicio extends Component { render() { const { classes, ruta } = this.props; return ( <Button color="inherit" onClick={ruta}> <ReplyIcon className={classes} /> Inicio </Button> ); } } class Titulo extends Component { constructor(props) { super(props); this.state = { activarBotonInicio: true }; } componentDidMount = () =>{ this.setState( { activarBotonInicio: this.props.esActivarBotonInicio } ); } render() { const { classes, history, ruta, titulo } = this.props; return ( <div> <AppBar position="static" className={classes.colorTitulo}> <Toolbar> <Typography variant="h6" color="inherit" className={classes.grow}> {titulo} </Typography> { this.state.activarBotonInicio ? <BotonInicio classes={classes.leftIcon} ruta={() => history.push(ruta)} /> : null } </Toolbar> </AppBar> </div> ) } } Titulo.defaultProps = { esActivarBotonInicio: true, ruta: '/Inicio' } Titulo.propTypes = { classes: PropTypes.object.isRequired, theme: PropTypes.object.isRequired, }; export default withRouter(withStyles(styles, { withTheme: true })(Titulo));<file_sep>import React, { Component } from 'react'; import Button from '@material-ui/core/Button'; class Pruebas extends Component { render() { return ( <div> <form onSubmit={this.handleSubmit}> <Button onClick={this.consultarReglasImpuestos } size="small" > Modal </Button> </form> </div> ); } } export default (Pruebas); <file_sep>import React, { Component } from 'react' import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import ItemMenu from '../itemMenu/ItemMenu' // Iconos import Assignment from '@material-ui/icons/Assignment'; import Class from '@material-ui/icons/Class'; import Build from '@material-ui/icons/Build'; const styles = theme => ({ root: { flexGrow: 1, }, content: { padding: theme.spacing.unit * 10, }, paper: { height: 90, width: 350, }, iconoSize: { height: 50, width: 50, }, configIconoRI: { height: 90, width: 90, left: 18, // top: 10, bottom: 30, backgroundColor: "#fd960e", color: "#FAFAFA", }, configIconoAC: { height: 90, width: 90, left: 18, // top: 10, bottom: 30, backgroundColor: "#52ab56", color: "#FAFAFA", }, configIconoOT: { height: 90, width: 90, left: 18, // top: 10, bottom: 30, backgroundColor: "#13b8cc", color: "#FAFAFA", }, }); class Menu extends Component { render() { const { classes } = this.props; return ( <div className={classes.root}> <main className={classes.content}> <Grid container spacing={24}> <Grid item xs > <ItemMenu ruta="/reglasImpuestos" primerTexto="Reglas Impuestos" vista={classes.configIconoRI} textArea="OFAS" icono={<Class className={classes.iconoSize} />} /> </Grid> <Grid item xs> <ItemMenu ruta="/AuditoriasComponentes" primerTexto="Auditorias Componentes" vista={classes.configIconoAC} textArea="Soporte" icono={<Assignment className={classes.iconoSize} />} /> </Grid> <Grid item xs> <ItemMenu ruta="/Otros" primerTexto="Otros" vista={classes.configIconoOT} textArea="ABR" icono={<Build className={classes.iconoSize} />} /> </Grid> </Grid> </main> </div> ); } } Menu.propTypes = { classes: PropTypes.object.isRequired, theme: PropTypes.object.isRequired, }; export default withStyles(styles, { withTheme: true })(Menu);<file_sep>import React, { Component } from 'react'; import { withStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import Button from '@material-ui/core/Button'; import Titulo from '../../Componentes/bannerTitulos/titulo' import Badge from '@material-ui/core/Badge'; import Typography from '@material-ui/core/Typography'; import Alertas from '../../Componentes/alert/alert' import TextField from '@material-ui/core/TextField'; const styles = theme => ({ root: { flexGrow: 1, }, button: { margin: theme.spacing.unit, backgroundColor: "#52ab56", color: "#FAFAFA", }, container: { display: 'flex', flexWrap: 'wrap', }, content: { padding: theme.spacing.unit * 5, }, textField: { marginLeft: theme.spacing.unit, marginRight: theme.spacing.unit, }, dense: { marginTop: 16, }, margin: { margin: theme.spacing.unit * 2, marginRight: theme.spacing.unit, }, padding: { padding: `0 ${theme.spacing.unit * 2}px`, }, }); class ReglasImpuestosItem extends Component { render() { const { descripcion, tipoConceptoCalculado, tipoPersona } = this.props; return ( <TableRow> <TableCell>{tipoConceptoCalculado}</TableCell> <TableCell>{descripcion}</TableCell> <TableCell>{tipoPersona}</TableCell> </TableRow> ); } } class reglasImpuestos extends Component { constructor() { super(); this.state = { itemsReglasImpuestos: [], tipoAlert: 'warning', mensaje: '', open: false }; } /** * @description Funciónm de concurrencia del render cuando hace llamados al API. */ _renderCurrencies() { const { itemsReglasImpuestos } = this.state; const { classes} = this.props; return ( <Paper className={classes.root}> <Badge color="secondary" badgeContent={itemsReglasImpuestos.length} className={classes.margin}> <Typography className={classes.padding} >Conceptos</Typography> </Badge> <Table className={classes.table}> <TableHead> <TableRow> <TableCell>Tipo concepto calculado</TableCell> <TableCell>Descripción</TableCell> <TableCell>Tipo persona</TableCell> </TableRow> </TableHead> <TableBody> { itemsReglasImpuestos.map((reglaImpuesto, index) => { return ( <ReglasImpuestosItem descripcion={reglaImpuesto.descripcion} key={index} tipoConceptoCalculado={reglaImpuesto.tipoConceptoCalculado} tipoPersona={reglaImpuesto.tipoPersona} /> ) }) } </TableBody> </Table> </Paper> ) } consultarReglasImpuestos = () => { let nitBeneficiario = this.txtNitBeneficiario.value; let nitCliente = this.txtNitCliente.value; if(nitBeneficiario === '') { nitBeneficiario = 0; nitCliente = 0; }else if(!/^[0-9]+$/g.test(nitBeneficiario) ) { nitBeneficiario = 0; nitCliente = 1; } if(nitCliente === '') { nitBeneficiario = 1; nitCliente = 0; }else if(!/^[0-9]+$/g.test(nitCliente) ) { nitBeneficiario = 1; nitCliente = 2; } fetch('http://localhost:56930/api/ConceptosCalculadosReglasImp?NitBeneficiario=' + nitBeneficiario + '&NitCliente=' + nitCliente + '') .then(res => res.json()) .then(data => { const itemsReglasImpuestos = data; this.setState({ itemsReglasImpuestos }); if(itemsReglasImpuestos.length > 0){ this.setState( {open: true, tipoAlert:'success', mensaje: 'Consulta Exitosa, '+itemsReglasImpuestos.length+' registros', }); }else { this.setState( {open: true, tipoAlert:'info', mensaje: 'Es posible que la configuración del Nit del beneficiario o del cliente este mal.', }); } if(nitBeneficiario ===0 && nitCliente ===0) { this.setState( {open: true, tipoAlert:'warning', mensaje: 'Debe ingresar el nit del beneficiario.', }); } if(nitBeneficiario === 0 && nitCliente === 1){ this.setState( {open: true, tipoAlert:'error', mensaje: 'El campo nit beneficiario debe ser numerico.', }); } if(nitBeneficiario === 1 && nitCliente === 0){ this.setState( {open: true, tipoAlert:'warning', mensaje: 'Debe ingresar el nit del cliente.', }); } if(nitBeneficiario ===1 && nitCliente === 2){ this.setState( {open: true, tipoAlert:'error', mensaje: 'El campo nit cliente debe ser numerico.', }); } }); this.setState({ open: false }); } render() { const { tipoAlert, mensaje , open } = this.state; const { classes } = this.props; return ( <div id="pagReglasImpuestos"> {this.state.open === true ? <Alertas tipoAlert={tipoAlert} mensaje={mensaje} open={open} /> : null} <Titulo titulo="Reglas impuestos"/> <main className={classes.content}> <form className={classes.container} onSubmit={this.handleSubmit}> <TextField className={classes.textField} id="txtNitBeneficiario" name="Beneficiario" label="Nit beneficiario" margin="dense" required={true} inputRef={inputElement => this.txtNitBeneficiario = inputElement} variant="outlined" /> <TextField className={classes.textField} id="txtNitCliente" name="cliente" label="Nit cliente" margin="dense" required={true} inputRef={inputElement => this.txtNitCliente = inputElement} variant="outlined" /> <Button className={classes.button} onClick={this.consultarReglasImpuestos } size="small" > Buscar </Button> </form> <br /><br /> <div> {this._renderCurrencies()} </div> </main> </div> ); } } export default withStyles(styles)(reglasImpuestos); <file_sep>import React, { Component } from 'react' import { BrowserRouter as Router, Route } from 'react-router-dom'; import Inicio from '../vistas/inicio/inicio' import reglasImpuestos from '../vistas/reglasImpuestos/reglasImpuestos' import AuditoriasComponentes from '../vistas/auditoriasComponentes/auditoriasComponentes' import CustomPaginationActionsTable from '../vistas/otros' class RouterComponent extends Component { render() { return ( <Router> <React.Fragment> <Route path="/" exact strict component={Inicio} /> <Route path="/Inicio" exact strict component={Inicio} /> <Route path="/reglasImpuestos" exact strict component={reglasImpuestos} /> <Route path="/AuditoriasComponentes" exact strict component={AuditoriasComponentes} /> <Route path="/Otros" exact strict component={CustomPaginationActionsTable} /> </React.Fragment> </Router> ) } } export default RouterComponent
1f83682977d9729f82f9e5bc56c5071b46e304ca
[ "JavaScript" ]
8
JavaScript
CamiloAranzazu/camilo
0c213851b056ae582ff34a84d0e08309cd8701e0
b8437185d51bf7792aa5f6a639b91f49704032ed
refs/heads/master
<file_sep>#!/usr/bin/env bash ssh -i ~/Google\ Drive/facebook_search.pem ec2-user@ec2-52-36-247-104.us-west-2.compute.amazonaws.com
32616bf09f0d0b7328b0ebfd07d6754cff0ca317
[ "Shell" ]
1
Shell
djdavies/fbSearch
7efaf4c77627cbcbc0f4f42d1fd1dea44f40b536
13cb5406be12a3b36a812aa5b99e8da9dcdc1dc9
refs/heads/master
<repo_name>suryatejaswi89/Event-Manager-APIs<file_sep>/src/main/java/com/events/model/Event.java package com.events.model; import java.util.Date; import org.springframework.data.annotation.Id; public class Event { @Id private String eventID; private String customerName; //private Date date; private String hallID; public Event(String customerName, String hallID){ this.customerName=customerName; //this.date=dDate; this.hallID=hallID; } public String getEventID() { return eventID; } public void setEventID(String eventID) { this.eventID = eventID; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getHallID() { return hallID; } public void setHallID(String hallID) { this.hallID = hallID; } }
efb25e3dacda7c2f5501a388b8904a0955553994
[ "Java" ]
1
Java
suryatejaswi89/Event-Manager-APIs
8d59656aa32f8b062fbb49e5efbdc1410e7f990c
144cdc6b4bdd3d82452e9f58dc1b0c6ecae72a9d
refs/heads/master
<repo_name>kubekbreha/MyPortfolio<file_sep>/js/common/settings.js //size of articles on one page var articlesForPage=5; var commentsForPage=20; //Domain name of server with articles var server="wt.kpi.fei.tuke.sk"; //var server="192.168.56.101"; <file_sep>/js/firebase/firebase_register.js firebase.auth().onAuthStateChanged(function (user) { if (user) { window.location.href = "settings.html"; } else { } }); function register() { var userEmail = document.getElementById("email_register").value; var userPass = document.getElementById("password_register").value; var userPass2 = document.getElementById("password_register2").value; if(userPass === userPass2) { firebase.auth().createUserWithEmailAndPassword(userEmail, userPass).catch(function (error) { var errorCode = error.code; var errorMessage = error.message; document.getElementById("error_message_register").innerHTML = errorMessage; }); } } function backToLogin() { window.location.href = "login.html"; }<file_sep>/js/common/messages.js /** * Show alert window with eror. * @param message test of the error. * @param xhrObj - object xhttp of request (XMLHttpRequest or jqXHR) */ function errorAlert(message,xhrObj){ window.alert(message+"\nError: "+ xhrObj.status + " (" + xhrObj.statusText + ")"); } <file_sep>/js/firebase/firebase_set_about.js var logged; //check if user is logged $(document).ready(function () { firebase.auth().onAuthStateChanged(function (user) { if (user) { logged = true; } else { logged = false; window.location.href = "index.html"; } }); }); function setAbout() { var uid = firebase.auth().currentUser.uid; var database = firebase.database(); var refUser = database.ref('users').child(uid).child("userAbout"); var authorAbout = document.getElementById("about_text_in").value; window.alert("submit"); var userData = { userName: authorAbout }; console.log("set user about data"); refUser.set(userData).then(function onSuccess(res) { window.location.href = "index.html"; }).catch(function onError(err) { Materialize.toast("Data wasnt set.", 4000); }); } <file_sep>/js/social_share.js document.addEventListener("DOMContentLoaded", function(event) { // Uses sharer.js // https://ellisonleao.github.io/sharer.js/#twitter var url = window.location.href; var title = document.title; var subject = "Read this good article"; var via = ""; console.log( url ); console.log( title ); //facebook $('#share-fb').attr('data-url', url).attr('data-sharer', 'facebook'); //twitter $('#share-tw').attr('data-url', url).attr('data-title', "Check this awesome page ").attr('data-via', via).attr('data-sharer', 'twitter'); //linkedin $('#share-li').attr('data-url', url).attr('data-sharer', 'linkedin'); // google plus $('#share-gp').attr('data-url', url).attr('data-title', title).attr('data-sharer', 'googleplus'); // email $('#share-em').attr('data-url', url).attr('data-title', title).attr('data-subject', subject).attr('data-sharer', 'email'); //Prevent basic click behavior $( ".sharer button" ).click(function() { event.preventDefault(); }); });<file_sep>/README.md # MyPortfolio This is one of my school project. You can find here Firebase login and articles and comments you can manage with REST methods. You can find Ethereum miner here. ## Screenshots <img src="readmeImg/1.png" width="280"/> <img src="readmeImg/2.png" width="280"/> <img src="readmeImg/3.png" width="280"/> ## Using * [Firebase](https://tympanus.net/codrops/) - Firebase login * [Materialize](https://materializecss.com/) - Frontend framework ## License This project is licensed under the MIT License - see the [LICENSE](https://github.com/kubekbreha/MyPortfolio/blob/master/LICENCE) file for details <file_sep>/js/navigation_scripts.js $(document).ready(function () { $('.materialboxed').materialbox(); $('.scrollspy').scrollSpy(); $(".button-collapse").sideNav(); firebase.auth().onAuthStateChanged(function (user) { if (user) { document.getElementById("log-nav").textContent = "LogOut"; document.getElementById("log-side-nav").textContent = "LogOut"; } else { document.getElementById("log-nav").textContent = "LogIn"; document.getElementById("log-side-nav").textContent = "LogIn"; } }); }); <file_sep>/js/articleForm.js var $form = $("#SKorFrm"); var artId = queryString2obj().id; if (isFinite(artId)){ console.log("edit article "+artId); $.ajax({ type: 'GET', url: "http://"+server+"/api/article/"+artId, dataType: "json", success: function (article) { $("#author").val(article.author); $("#title").val(article.title); $("#imageLink").val(article.imageLink); $("#content").val(article.content); $("#tags").val(article.tags); $("#frmTitle").html("Edit article"); }, error:function(jxhr){ window.alert("Loading article for edit failed.\nError: "+ jxhr.status + " (" + jxhr.statusText + ")"); } }); }else{ $("#frmTitle").html("Add article"); } //go back button $("#btBack").click(function(){ window.history.back() }); //commit article button $form.submit(function(event){ event.preventDefault(); if (isFinite(artId)) { prepareAndSendArticle($form,"PUT","http://"+server+"/api/article/"+artId); }else{ prepareAndSendArticle($form,"POST","http://"+server+"/api/article"); } }); //load image stuff. $("#btShowFileUpload").click(function(){ $('#fsetFileUpload').removeClass("skryty"); $('#btShowFileUpload').addClass("skryty"); }); //Send to server button $("#btFileUpload").click(function(){ uploadImg( $('#imageLink'), $('#fsetFileUpload'), $('#btShowFileUpload'), document.getElementById('flElm').files ); }); //stop loading $("#btCancelFileUpload").click(function(){ $('#fsetFileUpload').addClass("skryty"); $('#btShowFileUpload').removeClass("skryty"); }); window.onload = function() { setFirstFormElement() }; //set user name from firebase to author form function setFirstFormElement() { firebase.auth().onAuthStateChanged(function (user) { if (user) { var uid = user.uid; console.log(user.uid); var userName = ""; var database = firebase.database(); var refUser = database.ref('users').child(uid).child("userInfo"); refUser.once("value", function (snapshot) { snapshot.forEach(function (child) { if (child.key === "userName") { console.log(child.key + ": " + child.val()); userName = child.val(); document.getElementById("author").value = userName; console.log("username from form: " + userName); } }); }); } else { // window.location.href = "login.html"; } }); } /** * Proess data from form and send them to server. * @param $frm - form (jQuery objekt) * @param method - metóda, "POST" (add article) or "PUT" (edit article) * @param restURL - url of source on server */ function prepareAndSendArticle($frm, method, restURL) { //1. save data from form to object var data = {}; $frm.serializeArray().map( function(item){ var itemValueTrimmed = item.value.trim(); if(itemValueTrimmed){ data[item.name] = item.value; } } ); console.log("prepareAndSendArticle> data after saving into object:"); console.log(JSON.stringify(data)); if(data.tags){ data.tags=data.tags.split(","); data.tags=data.tags.map(function(tag) {return tag.trim()}); } console.log("prepareAndSendArticle> tags after processing:"); console.log(JSON.stringify(data)); //3.Check if needed forms was filled if(!data.title){ Materialize.toast('Article name must be filled', 4000); // alert("Article name must be filled"); return; } if(!data.content){ Materialize.toast('Text of article must be filled', 4000); //alert("Text of article must be filled"); return; } console.log("prepareAndSendArticle> All needed forms filled:"); //4. sending data if(window.confirm("You really want to save this project")){ $.ajax({ type: method, url: restURL, dataType: "json", contentType:"application/json;charset=UTF-8", data:JSON.stringify(data), success: function (response) { if(response.id){ console.log(response.id); window.location.href="article.html?id="+response.id; } }, error: function (jxhr) { Materialize.toast("Processing failed. Data was not saved. Error code:" + status + "\n" + jxhr.statusText + "\n" + jxhr.responseText, 4000); //window.alert("Processing failed. Data was not saved. Error code:" + status + "\n" + jxhr.statusText + "\n" + jxhr.responseText); } }); } } function uploadImg($imgLinkElement,$fieldsetElement, $btShowFileUploadElement, files) { if (files.length>0){ var imgData = new FormData(); imgData.append("file", files[0]); console.log("upload working"); $.ajax({ type: "POST", url: "http://"+server+"/api/fileUpload", dataType: "json", processData: false, contentType: false, data:imgData, success: function (response) { if(response.fullFileUrl){ $imgLinkElement.val(response.fullFileUrl); $btShowFileUploadElement.removeClass("skryty"); $fieldsetElement.addClass("skryty"); } }, error: function (jxhr) { Materialize.toast("Processing failed. Picture was not saved. Error code:" + status + "\n" + jxhr.statusText + "\n" + jxhr.responseText, 4000); //window.alert("Processing failed. Picture was not saved. Error code:" + status + "\n" + jxhr.statusText + "\n" + jxhr.responseText); } }); }else{ Materialize.toast("Pick picture file", 4000); window.alert("Pick picture file"); } }
6873a38022c6bd590a59431c86722f3eacbe77dd
[ "JavaScript", "Markdown" ]
8
JavaScript
kubekbreha/MyPortfolio
531cbfe009b75f0292af9188e8ba1d8e97acb4f7
460aa50024fcd43d03e745f3db66d2c2963de662
refs/heads/master
<repo_name>macedo123/TrabalhoPOOA2<file_sep>/TrabalhoOOA2/src/java/model/Rotapronta.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import dao.model.PontoParadaDao; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author aluno */ @Entity @Table(name = "rotapronta") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Rotapronta.findAll", query = "SELECT r FROM Rotapronta r") , @NamedQuery(name = "Rotapronta.findById", query = "SELECT r FROM Rotapronta r WHERE r.id = :id") , @NamedQuery(name = "Rotapronta.findByDescricao", query = "SELECT r FROM Rotapronta r WHERE r.descricao = :descricao")}) public class Rotapronta implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Basic(optional = false) @Column(name = "Descricao") private String descricao; @JoinColumn(name = "CidadeDestino", referencedColumnName = "Id") @ManyToOne(optional = false) private Cidade cidadeDestino; @JoinColumn(name = "CidadeOrigem", referencedColumnName = "Id") @ManyToOne(optional = false) private Cidade cidadeOrigem; @OneToMany(cascade = CascadeType.ALL, mappedBy = "rota") private List<Pontoparadaprevisto> pontoparadaprevistoList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "rota") private List<Rotaentrega> rotaentregaList; public Rotapronta() { } public Rotapronta(Integer id) { this.id = id; } public Rotapronta(Integer id, String descricao) { this.id = id; this.descricao = descricao; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public Cidade getCidadeDestino() { return cidadeDestino; } public void setCidadeDestino(Cidade cidadeDestino) { this.cidadeDestino = cidadeDestino; } public Cidade getCidadeOrigem() { return cidadeOrigem; } public void setCidadeOrigem(Cidade cidadeOrigem) { this.cidadeOrigem = cidadeOrigem; } @XmlTransient public List<Pontoparadaprevisto> getPontoparadaprevistoList() { return pontoparadaprevistoList; } public void setPontoparadaprevistoList(List<Pontoparadaprevisto> pontoparadaprevistoList) { this.pontoparadaprevistoList = pontoparadaprevistoList; } @XmlTransient public List<Rotaentrega> getRotaentregaList() { return rotaentregaList; } public void setRotaentregaList(List<Rotaentrega> rotaentregaList) { this.rotaentregaList = rotaentregaList; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Rotapronta)) { return false; } Rotapronta other = (Rotapronta) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "model.Rotapronta[ id=" + id + " ]"; } public boolean RotaOrigemDestinoValido(){ boolean cidadeFimOk = false; for (Pontoparadaprevisto pontoparadaprevisto : pontoparadaprevistoList) { if(pontoparadaprevisto.getDistanciaCidades().getCidadeFim().getNome().equals(cidadeDestino.getNome())){ cidadeFimOk = true; } } return cidadeFimOk; } public double DistanciaRotaMontada(){ double distanciaTotal = 0; for (Pontoparadaprevisto ponto : pontoparadaprevistoList) { distanciaTotal = distanciaTotal + ponto.getDistanciaCidades().getDistancia(); } return distanciaTotal; } public int UltimoNumeroOrdemParada(){ int ultimoNumero = 0; for (Pontoparadaprevisto ponto : pontoparadaprevistoList) { if(ponto.getOrdem() > ultimoNumero){ ultimoNumero = ponto.getOrdem(); } } return ultimoNumero; } } <file_sep>/TrabalhoOOA2/src/java/dao/model/RotaProntoDao.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao.model; import dao.BaseDao; import java.util.List; import javax.persistence.Query; import model.Rotapronta; /** * * @author aluno */ public class RotaProntoDao extends BaseDao<Rotapronta>{ public List<Rotapronta> findAll(){ open(); try{ Query q = em.createNamedQuery("Rotapronta.findAll"); return q.getResultList(); }finally{ close(); } } } <file_sep>/TrabalhoOOA2/src/java/model/Distanciacidades.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author aluno */ @Entity @Table(name = "distanciacidades") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Distanciacidades.findAll", query = "SELECT d FROM Distanciacidades d") ,@NamedQuery(name = "Distanciacidades.findById", query = "SELECT d FROM Distanciacidades d WHERE d.id = :id") ,@NamedQuery(name = "Distanciacidades.findAllCompleta", query = "SELECT d FROM Distanciacidades d JOIN Cidade ci ON d.cidadeInicio = ci JOIN Cidade cf ON d.cidadeFim = cf") ,@NamedQuery(name = "Distanciacidades.findByIdCompleta", query = "SELECT d FROM Distanciacidades d JOIN Cidade ci ON d.cidadeInicio = ci JOIN Cidade cf ON d.cidadeFim = cf " + "WHERE d.id = :id") }) public class Distanciacidades implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "Id") private Integer id; @OneToMany(cascade = CascadeType.ALL, mappedBy = "distanciaCidades") private List<Pontoparadaprevisto> pontoparadaprevistoList; @JoinColumn(name = "CidadeFim", referencedColumnName = "Id") @ManyToOne(optional = false) private Cidade cidadeFim; @JoinColumn(name = "CidadeInicio", referencedColumnName = "Id") @ManyToOne(optional = false) private Cidade cidadeInicio; @Column(name = "Distancia") private Double distancia; public Distanciacidades() { } public Distanciacidades(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Double getDistancia() { return distancia; } public void setDistancia(Double distancia) { this.distancia = distancia; } @XmlTransient public List<Pontoparadaprevisto> getPontoparadaprevistoList() { return pontoparadaprevistoList; } public void setPontoparadaprevistoList(List<Pontoparadaprevisto> pontoparadaprevistoList) { this.pontoparadaprevistoList = pontoparadaprevistoList; } public Cidade getCidadeFim() { return cidadeFim; } public void setCidadeFim(Cidade cidadeFim) { this.cidadeFim = cidadeFim; } public Cidade getCidadeInicio() { return cidadeInicio; } public void setCidadeInicio(Cidade cidadeInicio) { this.cidadeInicio = cidadeInicio; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Distanciacidades)) { return false; } Distanciacidades other = (Distanciacidades) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "model.Distanciacidades[ id=" + id + " ]"; } public String strDeParaDistancia(){ return "De - " + this.cidadeInicio.getNome() + " | Para - " + this.cidadeFim.getNome() + " | " + this.distancia.toString() + "Km"; } } <file_sep>/TrabalhoOOA2/src/java/model/Pontoparadaprevisto.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * * @author aluno */ @Entity @Table(name = "pontoparadaprevisto") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Pontoparadaprevisto.findAll", query = "SELECT p FROM Pontoparadaprevisto p") , @NamedQuery(name = "Pontoparadaprevisto.findAllCompleto", query = "SELECT p FROM Pontoparadaprevisto p join Distanciacidades dc on dc = p.distanciaCidades join Rotapronta r on r = p.rota") , @NamedQuery(name = "Pontoparadaprevisto.findAllByRotaCompleto", query = "SELECT p FROM Pontoparadaprevisto p join Distanciacidades dc on dc = p.distanciaCidades join Rotapronta r on r = p.rota WHERE p.rota.id = :idRota") , @NamedQuery(name = "Pontoparadaprevisto.findById", query = "SELECT p FROM Pontoparadaprevisto p WHERE p.id = :id") , @NamedQuery(name = "Pontoparadaprevisto.findByOrdem", query = "SELECT p FROM Pontoparadaprevisto p WHERE p.ordem = :ordem") , @NamedQuery(name = "Pontoparadaprevisto.findByTempoParada", query = "SELECT p FROM Pontoparadaprevisto p WHERE p.tempoParada = :tempoParada")}) public class Pontoparadaprevisto implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "ID") private Integer id; @Basic(optional = false) @Column(name = "Ordem") private int ordem; @Basic(optional = false) @Column(name = "TempoParada") private double tempoParada; @JoinColumn(name = "DistanciaCidades", referencedColumnName = "Id") @ManyToOne(optional = false) private Distanciacidades distanciaCidades; @JoinColumn(name = "Rota", referencedColumnName = "id") @ManyToOne(optional = false) private Rotapronta rota; public Pontoparadaprevisto() { } public Pontoparadaprevisto(Integer id) { this.id = id; } public Pontoparadaprevisto(Integer id, int ordem, double tempoParada) { this.id = id; this.ordem = ordem; this.tempoParada = tempoParada; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public int getOrdem() { return ordem; } public void setOrdem(int ordem) { this.ordem = ordem; } public double getTempoParada() { return tempoParada; } public void setTempoParada(double tempoParada) { this.tempoParada = tempoParada; } public Distanciacidades getDistanciaCidades() { return distanciaCidades; } public void setDistanciaCidades(Distanciacidades distanciaCidades) { this.distanciaCidades = distanciaCidades; } public Rotapronta getRota() { return rota; } public void setRota(Rotapronta rota) { this.rota = rota; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Pontoparadaprevisto)) { return false; } Pontoparadaprevisto other = (Pontoparadaprevisto) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "model.Pontoparadaprevisto[ id=" + id + " ]"; } } <file_sep>/TrabalhoOOA2/src/java/bean/controller/MotoristaLoginBean.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bean.controller; import dao.model.MotoristaDao; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import model.Motorista; /** * * @author Anderson2 */ @ManagedBean(name = "motoristaLg") @SessionScoped public class MotoristaLoginBean { private Motorista motoristaLogin; private String mensagem; private boolean logado; public Motorista getMotoristaLogin() { return motoristaLogin; } public void setMotoritaLogin(Motorista motoritaLogin) { this.motoristaLogin = motoristaLogin; } public String getMensagem() { return mensagem; } public void setMensagem(String mensagem) { this.mensagem = mensagem; } public boolean isLogado() { return logado; } public void setLogado(boolean logado) { this.logado = logado; } /** * Creates a new instance of MotoristaBean */ public MotoristaLoginBean() { this.mensagem = ""; motoristaLogin = new Motorista(); logado = false; } public String LoginMotorista(){ logado = false; return "./loginMotorista?faces-redirect=true"; } public String Logar(){ Motorista m = new MotoristaDao().findByLoginSenha(this.motoristaLogin.getLogin(), this.motoristaLogin.getSenha()); String retorno = "loginMotorista"; if(m != null){ this.motoristaLogin = m; logado = true; retorno = "security_admin/index"; }else{ logado = false; this.mensagem = "Login ou Senha incorretos"; } return retorno; } public String LogOut(){ this.motoristaLogin = new Motorista(); this.logado = false; return LoginMotorista(); } } <file_sep>/TrabalhoOOA2/src/java/bean/controller/ClienteLgBean.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bean.controller; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import model.Cliente; /** * * @author Anderson2 */ @ManagedBean(name = "clienteLg") @SessionScoped public class ClienteLgBean { private Cliente clienteLogin; private boolean logado; public Cliente getClienteLogin() { return clienteLogin; } public void setClienteLogin(Cliente clienteLogin) { this.clienteLogin = clienteLogin; } public boolean isLogado() { return logado; } public void setLogado(boolean logado) { this.logado = logado; } /** * Creates a new instance of ClienteBean */ public ClienteLgBean() { clienteLogin = new Cliente(); logado = false; } public String Logar(){ return "loginCliente?faces-redirect=true"; } public String LoginCliente(){ return "loginCliente?faces-redirect=true"; } } <file_sep>/TrabalhoOOA2/src/java/teste/TesteBanco.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package teste; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.NoResultException; import javax.persistence.NonUniqueResultException; import javax.persistence.Persistence; import javax.persistence.Query; import model.Cliente; /** * * @author Anderson2 */ public class TesteBanco { public static void main(String[] args){ EntityManagerFactory emf = Persistence.createEntityManagerFactory("TrabalhoOOA2PU"); EntityManager em = emf.createEntityManager(); Cliente c; try{ Query q = em.createNamedQuery("Cliente.findById"); q.setParameter("id", 1); c = (Cliente)q.getSingleResult(); System.out.println("==>" + c.getNome()); }catch(NoResultException e){ System.out.println("Nenhum Usuario Encontrado"); }catch(NonUniqueResultException e){ System.out.println("Mais de um usuario encontrado"); } } } <file_sep>/README.md # TrabalhoPOOA2 1. Monte uma aplicação web para a situação abaixo, utilize banco de dados, JSF e os conceitos visto em sala. Sistema de Gerenciamento de Entregas em Tempo Real - GETRE A empresa “Coelho Rápido” trabalha com entrega para toda Minas Gerais. Essas entregas podem ser de pequeno porte, usa-se moto, médio porte, usase carro e grande porte, faz-se uso de caminhão. Ela se encarrega de pegar o produto no cliente e levar até o destino final. Entretanto, atualmente a empresa não consegue saber com precisão aonde a entrega se encontra e quanto tempo irá demorar e nem qual percurso foi feito pelo entregador e onde ele se encontra, gerando assim um grande desconforto com o cliente. O sistema deve ser composto por: 1) A primeira parte, web, deve possuir um local para os clientes logar e solicitar um serviço de entrega. Ao solicitar a entrega o cliente deve ter uma previsão do preço a ser cobrado e do prazo de entrega. O preço depende da distância percorrida e do tipo de transporte, moto, carro ou caminhão. O cliente deve acompanhar o andamento de sua entrega, para isso basta estar logado e informar ou selecionar a entrega pendente. O cliente deve ser capaz de prever o caminho a ser percorrido e previsão de passagem por cada ponto, o horário que efetivamente passou pelo ponto. O cliente deve ser capaz de se cadastrar. 2) O motorista deve ser capa de lançar sua posição atual na entrega. 3) Na parte administrativa do site, a empresa deve ser capaz de acompanhar os pontos de parada do transporte. Essas informações devem ser usadas para calcular o tempo de chegada do produto. O sistema deve exibir uma listagem com todas as entregas, seu status e outros detalhes que julgar necessário.
2ccaa5b08c1bea64f595da9142a3a51100668be3
[ "Markdown", "Java" ]
8
Java
macedo123/TrabalhoPOOA2
14738bc49f3bbf6bd47f9abb91901827c72b785b
29c105a9f84c1d19bab4ffeb2b17535106570e46
refs/heads/master
<repo_name>nithinpariyaran08/task-manager<file_sep>/src/main/java/fsd/taskmanager/config/TaskManagerController.java package fsd.taskmanager.config; import java.util.ArrayList; import java.util.List; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import fsd.taskmanager.dto.LoginDTO; import fsd.taskmanager.dto.TaskManagerDTO; import fsd.taskmanager.service.TaskManagerService; //Sample testing @RestController public class TaskManagerController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private TaskManagerService taskManagerService; @RequestMapping(value = "/api/v1/getAllTasks", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<TaskManagerDTO>> getAllTasks() { logger.info("inside listAllTasks"); List<TaskManagerDTO> taskManagerList = taskManagerService.getAllTask(); return new ResponseEntity<List<TaskManagerDTO>>(taskManagerList, HttpStatus.OK); } @RequestMapping(value = "/api/v1/getTaskList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<String>> getTasks() { logger.info("inside listAllTasks"); List<TaskManagerDTO> taskManagerList = taskManagerService.getAllTask(); List<String> taskList = new ArrayList<String>(); taskManagerList.stream().forEach((task) -> taskList.add(task.getTaskName())); return new ResponseEntity<List<String>>(taskList, HttpStatus.OK); } @RequestMapping(value = "/api/v1/getTask/{id}", method = RequestMethod.GET) public ResponseEntity<TaskManagerDTO> getTask(@PathVariable("id") Integer id) { logger.info("inside getTask"+id); return new ResponseEntity<TaskManagerDTO>(taskManagerService.getTaskById(id), HttpStatus.OK); } @RequestMapping(value = "/api/v1/addTask", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<TaskManagerDTO> addTask(@Valid @RequestBody TaskManagerDTO taskManagerDTO) { logger.info("inside add task" + taskManagerDTO); taskManagerDTO = taskManagerService.addTask(taskManagerDTO); return new ResponseEntity<TaskManagerDTO>(taskManagerDTO, HttpStatus.OK); } @RequestMapping(value = "/api/v1/updateTask/{id}", method = RequestMethod.PUT) public ResponseEntity<TaskManagerDTO> updateTask(@PathVariable("id") Integer id, @RequestBody TaskManagerDTO taskManagerDTO) { logger.info("inside updateTask" + taskManagerDTO); TaskManagerDTO currenttaskManagerDTO = taskManagerService.getTaskById(id); currenttaskManagerDTO.setTaskId(taskManagerDTO.getTaskId()); currenttaskManagerDTO.setTaskName(taskManagerDTO.getTaskName()); currenttaskManagerDTO.setPriority(taskManagerDTO.getPriority()); currenttaskManagerDTO.setRemarks(taskManagerDTO.getRemarks()); currenttaskManagerDTO.setTaskStatus(taskManagerDTO.getTaskStatus()); taskManagerService.updateTask(currenttaskManagerDTO); return new ResponseEntity<TaskManagerDTO>(currenttaskManagerDTO, HttpStatus.OK); } @RequestMapping(value = "/api/v1/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public String checkUserLogin(LoginDTO loginDTO) { if (loginDTO.getUserName().equalsIgnoreCase("Nithin") && loginDTO.getPassword().equalsIgnoreCase("<PASSWORD>")) { return "success "; } return "Failed"; } @RequestMapping(value = "/api/v1/deleteTask/{id}", method = RequestMethod.DELETE) public ResponseEntity<TaskManagerDTO> deleteTask(@PathVariable("id") Integer id) { TaskManagerDTO taskManagerDTO = new TaskManagerDTO(); taskManagerDTO.setTaskId(id); logger.info("inside deleteTask" + taskManagerDTO); taskManagerService.deleteTask(taskManagerDTO); return new ResponseEntity<TaskManagerDTO>(taskManagerDTO, HttpStatus.OK); } } <file_sep>/src/main/java/fsd/taskmanager/service/TaskManagerService.java package fsd.taskmanager.service; import java.util.List; import fsd.taskmanager.dto.TaskManagerDTO; public interface TaskManagerService { TaskManagerDTO addTask(TaskManagerDTO taskManagerDTO); TaskManagerDTO updateTask(TaskManagerDTO taskManagerDTO); TaskManagerDTO deleteTask(TaskManagerDTO taskManagerDTO); List<TaskManagerDTO> getAllTask(); TaskManagerDTO getTaskById(Integer taskId); } <file_sep>/src/main/java/fsd/taskmanager/repository/TaskManagerRepository.java package fsd.taskmanager.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import fsd.taskmanager.entity.TaskManager; @Repository public interface TaskManagerRepository extends JpaRepository<TaskManager, Integer> { } <file_sep>/src/main/java/fsd/taskmanager/dto/ParentTaskDTO.java package fsd.taskmanager.dto; public class ParentTaskDTO { private String parentTask; public String getParentTask() { return parentTask; } public void setParentTask(String parentTask) { this.parentTask = parentTask; } @Override public boolean equals(Object obj) { ParentTaskDTO parentTaskDTO = (ParentTaskDTO) obj; if (this.parentTask.equals(parentTaskDTO.getParentTask())) { return true; } return false; } @Override public int hashCode() { int prime = 31; int result = 1; result = prime * result + ((parentTask == null ? 0 : parentTask.hashCode())); return 0; } } <file_sep>/src/main/resources/application.properties spring.datasource.url=jdbc:mysql://localhost:3306/taskmanagement?useSSL=false spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.datasource.tomcat.max-wait=20000 spring.datasource.tomcat.max-active=50 spring.datasource.tomcat.max-idle=20 spring.datasource.tomcat.min-idle=15 spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect spring.jpa.properties.hibernate.id.new_generator_mappings = false spring.jpa.properties.hibernate.format_sql = true spring.jpa.properties.hibernate.hbm2ddl.auto=update logging.level.org.hibernate.SQL=DEBUG logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE server.port=8080 server.servlet.context-path = /taskmanager<file_sep>/src/main/java/fsd/taskmanager/config/TaskManagerEnum.java package fsd.taskmanager.config; public enum TaskManagerEnum { task_added_successfully("Task added successfully"), task_updated_successfully("Task Updated successfully"), task_deleted_successfully("Task Deleted successfully"); private String statusValue; private TaskManagerEnum(String statusValue) { this.statusValue = statusValue; } public String getStatusValue() { return statusValue; } public void setStatusValue(String statusValue) { this.statusValue = statusValue; } } <file_sep>/src/main/resources/static/js/app/TaskService.js 'use strict'; angular.module('crudApp').factory('TaskService', ['$localStorage', '$http', '$q', 'urls', function ($localStorage, $http, $q, urls) { var factory = { loadAllTasks: loadAllTasks, getTaskList: getTaskList, getAllTasks: getAllTasks, getTask: getTask, createTask: createTask, updateTask: updateTask, removeTask: removeTask }; return factory; function loadAllTasks() { console.log('Fetching all tasks'); var deferred = $q.defer(); console.log(urls.USER_SERVICE_API); $http.get(urls.USER_SERVICE_API) .then( function (response) { console.log('Fetched successfully all tasks'); $localStorage.tasks = response.data; deferred.resolve(response); }, function (errResponse) { console.error('Error while loading tasks'); deferred.reject(errResponse); } ); return deferred.promise; } function getAllTasks(){ return $localStorage.tasks; } function getTaskList(){ console.log('Fetching all tasks list'); var deferred = $q.defer(); console.log(urls.GET_TASK_LIST_SERVICE_API); $http.get(urls.GET_TASK_LIST_SERVICE_API) .then( function (response) { console.log('Fetched successfully all tasks for parent task'); $localStorage.parentTasks = response.data; console.log(response.data); deferred.resolve(response); }, function (errResponse) { console.error('Error while loading tasks'); deferred.reject(errResponse); } ); return deferred.promise; } function getTask(id) { console.log('Fetching Task with id :'+id); var deferred = $q.defer(); $http.get(urls.GET_TASK_SERVICE_API+id) .then( function (response) { console.log('Fetched successfully Task with id :'+id); deferred.resolve(response.data); }, function (errResponse) { console.error('Error while loading Task with id :'+id); deferred.reject(errResponse); } ); return deferred.promise; } function createTask(task) { console.log('Creating task'); var deferred = $q.defer(); $http.post(urls.ADD_TASK_SERVICE_API, task) .then( function (response) { loadAllTasks(); deferred.resolve(response.data); }, function (errResponse) { console.error('Error while creating Task : '+errResponse.data.errorMessage); deferred.reject(errResponse); } ); return deferred.promise; } function updateTask(task,id) { console.log('Updating Task with id '+task.taskId); var deferred = $q.defer(); $http.put(urls.UPDATE_TASK_SERVICE_API +task.taskId, task) .then( function (response) { loadAllTasks(); deferred.resolve(response.data); }, function (errResponse) { console.error('Error while updating Task with id :'+task.taskId); deferred.reject(errResponse); } ); return deferred.promise; } function removeTask(id) { console.log('Removing Task with id '+id); var deferred = $q.defer(); $http.delete(urls.DELETE_TASK_SERVICE_API+id) .then( function (response) { loadAllTasks(); deferred.resolve(response.data); }, function (errResponse) { console.error('Error while removing Task with id :'+id); deferred.reject(errResponse); } ); return deferred.promise; } function endTask(task,id) { console.log('End task Task with id '+task.taskId); var deferred = $q.defer(); $http.put(urls.END_TASK_SERVICE_API +task.taskId, task) .then( function (response) { loadAllTasks(); deferred.resolve(response.data); }, function (errResponse) { console.error('Error while updating Task with id :'+task.taskId); deferred.reject(errResponse); } ); return deferred.promise; } } ]);<file_sep>/src/main/java/fsd/taskmanager/service/TaskManagerServiceImpl.java package fsd.taskmanager.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import fsd.taskmanager.dao.TaskManagerDAO; import fsd.taskmanager.dto.TaskManagerDTO; @Service public class TaskManagerServiceImpl implements TaskManagerService { @Autowired private TaskManagerDAO taskManagerDAO; @Override public TaskManagerDTO addTask(TaskManagerDTO taskManagerDTO) { return taskManagerDAO.addTask(taskManagerDTO); } @Override public TaskManagerDTO updateTask(TaskManagerDTO taskManagerDTO) { return taskManagerDAO.updateTask(taskManagerDTO); } @Override public TaskManagerDTO deleteTask(TaskManagerDTO taskManagerDTO) { return taskManagerDAO.deleteTask(taskManagerDTO); } @Override public List<TaskManagerDTO> getAllTask() { return taskManagerDAO.getAllTasks(); } @Override public TaskManagerDTO getTaskById(Integer taskId) { return taskManagerDAO.getTaskById(taskId); } } <file_sep>/src/main/resources/static/js/app/app.js var app = angular.module('crudApp',['ui.router','ngStorage']); app.constant('urls', { BASE: 'http://localhost:8080/taskmanager', USER_SERVICE_API : 'http://localhost:8080/taskmanager/api/v1/getAllTasks', GET_TASK_SERVICE_API : 'http://localhost:8080/taskmanager/api/v1/getTask/', GET_TASK_LIST_SERVICE_API : 'http://localhost:8080/taskmanager/api/v1/getTaskList', END_TASK_SERVICE_API : 'http://localhost:8080/taskmanager/api/v1/endTask/', ADD_TASK_SERVICE_API : 'http://localhost:8080/taskmanager/api/v1/addTask', UPDATE_TASK_SERVICE_API : 'http://localhost:8080/taskmanager/api/v1/updateTask/', DELETE_TASK_SERVICE_API : 'http://localhost:8080/taskmanager/api/v1/deleteTask/' }); app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/', templateUrl: 'partials/list', controller:'TaskController', controllerAs:'ctrl', resolve: { tasks: function ($q, TaskService) { console.log('Load all task'); var deferred = $q.defer(); TaskService.loadAllTasks().then(deferred.resolve, deferred.resolve); return deferred.promise; } } }); $urlRouterProvider.otherwise('/'); }]); app.controller('ctrl', function($scope, $http) { $http.get('http://localhost:8080/taskmanager/api/v1/getTaskList'). then(function(response) { $scope.parentTasks = response.data; }); });<file_sep>/src/main/java/fsd/taskmanager/dto/TaskManagerDTO.java package fsd.taskmanager.dto; import java.util.Date; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import fsd.taskmanager.config.DateSerializer; public class TaskManagerDTO { //the primary key needs to be primitive private Integer taskId; private String taskName; private int priority; @JsonSerialize(using = DateSerializer.class) private Date startDate; @JsonSerialize(using = DateSerializer.class) private Date endDate; private String taskStatus; private String remarks; private String parentTasks; @JsonInclude(JsonInclude.Include.NON_NULL) private ParentTaskDTO parentTaskDTO; public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getTaskStatus() { return taskStatus; } public void setTaskStatus(String taskStatus) { this.taskStatus = taskStatus; } public ParentTaskDTO getParentTaskDTO() { return parentTaskDTO; } public void setParentTaskDTO(ParentTaskDTO parentTaskDTO) { this.parentTaskDTO = parentTaskDTO; } public Integer getTaskId() { return taskId; } public void setTaskId(Integer taskId) { this.taskId = taskId; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } @Override public boolean equals(Object obj) { TaskManagerDTO taskManagerDTO = (TaskManagerDTO) obj; if (this.taskId == (taskManagerDTO.getTaskId())) { return true; } else return false; } @Override public int hashCode() { int prime = 31; int result = 1; result = prime * result + ((taskId == 0 ? 0 : taskId.hashCode())); return result; } @Override public String toString() { return "TaskManagerDTO [taskId=" + taskId + ", taskName=" + taskName + ", priority=" + priority + ", startDate=" + startDate + ", endDate=" + endDate + ", taskStatus=" + taskStatus + ", remarks=" + remarks + ", parentTasks=" + parentTasks + ", parentTaskDTO=" + parentTaskDTO + "]"; } public String getParentTasks() { return parentTasks; } public void setParentTasks(String parentTasks) { this.parentTasks = parentTasks; } }
0368bd88e5c531149102570bd4bc5a7ba278ad87
[ "JavaScript", "Java", "INI" ]
10
Java
nithinpariyaran08/task-manager
48d944f4e20d5f60f9fce239e057913a99c6d98c
56bee86081255c4c1fe084ba175ee79f8c7f0f50
refs/heads/master
<repo_name>jccarcia/Ejer2Recover_Linq<file_sep>/Ejer3LinqPractice_SecondTry/Program.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejer3LinqPractice_SecondTry { public class Program { static void Main(string[] args) { Ejer2(Ejer1()); Ejer3(Ejer1()); Ejer4(Ejer1()); Ejer5(46.4086282, 16.1508154, Ejer1()); Ejer6(Ejer1()); Ejer7(Ejer1()); Ejer8(Ejer1()); Ejer9(Ejer1()); Ejer10(Ejer1()); Ejer11(Ejer1()); Ejer12(Ejer1()); Ejer13(Ejer1()); Ejer14(Ejer1()); Ejer15(Ejer1()); Ejer16(Ejer1(), "Violet", 2003); } static List<Coche> Ejer1() //Crea la clase para poder cargar el Json y cargalo. { using (StreamReader lector = new StreamReader("Cars.json")) { string json = lector.ReadToEnd(); List<Coche> resultado = JsonConvert.DeserializeObject<List<Coche>>(json); return resultado; } } public static void Ejer2(List<Coche> listaCoche) //Muestra los distintos Fabricantes, sin duplicar ningún fabricante y poniendo inicialmente "Fabricante :" en todos los elementos. { var dist = listaCoche.GroupBy(x => x.Maker).Select(y => y.First()); foreach (var i in dist) { Console.WriteLine("Fabricante :" + i.Maker); } Console.ReadKey(); } public static void Ejer3(List<Coche> listaCoche) //Muestra los diferentes colores indicando Maker y Modelo también. { var ajar = listaCoche.GroupBy(x=> x.Color).Select(y => y.First()); foreach (var i in ajar) { Console.WriteLine("Color :" + i.Color + "Fabricante :" + i.Maker); } Console.ReadKey(); } static void Ejer4(List<Coche> listaCoche) //Muestra fabricante y modelo. Del color Verde. { var beti = listaCoche.Where(x => x.Color == "Green"); foreach (var i in beti) { Console.WriteLine("Frabricante :" + i.Maker + " Modelo :" + i.Model); } Console.ReadKey(); } static void Ejer5(double latitud, double longitud, List<Coche> listaCoche) //Permite al usuario introducir una latitud y una longitud. //Indica al usuario si encuentra un coche del año 1992 dentro de esa latitud y longitud facilitada. { var buscar = listaCoche.Where(x => x.Latitude == latitud && x.Longitude == longitud); foreach (var i in buscar) { if (i.Year == 1992) { Console.WriteLine("Hay un coche del año 1992"); } else { Console.WriteLine("No hay un coche del año 1992"); } } Console.ReadKey(); } static void Ejer6(List<Coche> listaCoche) //Muestra todos los coches del año posterior de 2001. { var edad = listaCoche.Where(x => x.Year >= 2001); foreach (var i in edad) { Console.WriteLine(i.Maker + " - " + i.Model); } Console.ReadKey(); } static void Ejer7(List<Coche> listaCoche) //Genera una nueva clase con modelo y fabricante. Muestra todos los coches que tengan latitud, ni longitud Convierte en la búsqueda a esa clase. { var a = listaCoche.Where(x => x.Location.Latitude == null && x.Location.Longitude == null); foreach (var i in a) { Console.WriteLine("Modelo: "+ i.Model + " Fabricante: " + i.Maker); } Console.ReadKey(); } static void Ejer8(List<Coche> listaCoche) //Busca todos los coches de color Blue y que sean anteriores al año 2000. { var e = listaCoche.Where(x => x.Year >= 2000 && x.Color == "Blue"); foreach (var i in e) { Console.WriteLine(i); } Console.ReadKey(); } static void Ejer9(List<Coche> listaCoche) //Agrupa todos los coches por fabricante, muestralos por pantalla ordenados por año. { var rav = listaCoche.OrderBy(x => x.Year).GroupBy(x => x.Maker); foreach (var i in rav) { Console.WriteLine(i.Key); } Console.ReadKey(); } static void Ejer10(List<Coche> listaCoche) //Agrupa todos los coches por modelo, muestra los colores disponibles sin duplicar la muestra. { var fabcolor = listaCoche.GroupBy(x => x.Model).Select(y => y.First()); foreach (var i in fabcolor) { Console.WriteLine(i.Maker + " - " + i.Color); } Console.ReadKey(); } static void Ejer11(List<Coche> listaCoche) //Página de 10 en 10 pulsando una tecla y muestra todos los coches disponibles { for (int i = 0; i < listaCoche.Count; i += 10) { var lista = listaCoche.Skip(0 + i).Take(10); foreach (var x in lista) { Console.WriteLine(x.ToString()); } Console.ReadKey(); } Console.ReadKey(); } static void Ejer12(List<Coche> listaCoche) //Encuentra el primer coche posterior del año 2001 del fabricante Suzuki { var suzu = listaCoche.Where(x => x.Maker == "Suzuki" && x.Year > 2001).Take(1); foreach (var i in suzu) { Console.WriteLine(i); } Console.ReadKey(); } static void Ejer13(List<Coche> listaCoche) //Muestra todos los coches que tengan guardado el año. { var ok = listaCoche.Where(x => x.Year != null); foreach (var i in ok) { Console.WriteLine(i); } Console.ReadKey(); } static void Ejer14(List<Coche> listaCoche) //Agrupa por año todos los coches y muestra la cantidad que hay de color Rosa { var col = listaCoche.Where(x => x.Color == "Pink").GroupBy(y => y.Year); foreach (var i in col) { Console.WriteLine(i); } Console.ReadKey(); } static void Ejer15(List<Coche> listaCoche) //Busca todos los coches BMW que no tengan ni año, ni color. { var bar = listaCoche.Where(x => x.Maker == "BMW" && x.Year == null && string.IsNullOrEmpty(x.Color)); foreach (var i in bar) { Console.WriteLine(i); } Console.ReadKey(); } public static void Ejer16(List<Coche> chs, string colores, int ano) //Crea un método de extensión donde se pueda introducir color y año, devolviendo el listado de Coches que no cumplan la condición. { var list = chs.Where(x => x.Color != colores && x.Year != ano); foreach (var i in list) { Console.WriteLine(i); } Console.ReadKey(); } public static class ExtensionMethods { public static void listVehiculos<T>(string color, int? ano, List<Coche> listaCoche) { var lv = listaCoche.Where(x => x.Year != ano && x.Color != color); foreach (var i in lv) { Console.WriteLine(i); } Console.ReadKey(); } } } } <file_sep>/Ejer3LinqPractice_SecondTry/Coche.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejer3LinqPractice_SecondTry { public class Location { public double? Latitude { get; set; } public double? Longitude { get; set; } } public class Coche : Location { public int id { get; set; } public string Maker { get; set; } public string Model { get; set; } public int? Year { get; set; } public string Color { get; set; } public Location Location { get; set; } public override string ToString() { String resul = ""; resul += "id : " + id + "\r\n"; resul += "Maker :" + Maker + "\r\n"; resul += "Model:" + Model + "\r\n"; resul += "Year: " + Year + "\r\n"; resul += "Color :" + Color + "\r\n"; resul += "Location :" + Longitude + "\r\n"; resul += "Latitude :" + Latitude + "\r\n" + "\r\n"; return resul; } } }
ba75e54e70b0759dcaaed130e2f5baa04b416145
[ "C#" ]
2
C#
jccarcia/Ejer2Recover_Linq
3964dcf063a6fe13a1d122eb5b95d4004d5ad355
936637ef5ba6247cdc2461c8d5539a0ef6c26be3
refs/heads/master
<repo_name>taragurung/survey<file_sep>/application/views/welcome_message.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); ?><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Welcome to CodeIgniter</title> <link href="<?php echo base_url('css/bootstrap.css'); ?>"> <script src="<?php echo base_url('js/script.js'); ?>"></script> <script src="<?php echo base_url('js/bootstrap.min.js'); ?>"></script> <style type="text/css"> ::selection { background-color: #E13300; color: white; } ::-moz-selection { background-color: #E13300; color: white; } body { background-color: #fff; margin: 40px; font: 13px/20px normal Helvetica, Arial, sans-serif; color: #4F5155; } a { color: #003399; background-color: transparent; font-weight: normal; } h1 { color: #444; background-color: transparent; border-bottom: 1px solid #D0D0D0; font-size: 19px; font-weight: normal; margin: 0 0 14px 0; padding: 14px 15px 10px 15px; } code { font-family: Consolas, Monaco, Courier New, Courier, monospace; font-size: 12px; background-color: #f9f9f9; border: 1px solid #D0D0D0; color: #002166; display: block; margin: 14px 0 14px 0; padding: 12px 10px 12px 10px; } #body { margin: 0 15px 0 15px; } p.footer { text-align: right; font-size: 11px; border-top: 1px solid #D0D0D0; line-height: 32px; padding: 0 10px 0 10px; margin: 20px 0 0 0; } #container { margin: 10px; border: 1px solid #D0D0D0; box-shadow: 0 0 8px #D0D0D0; } </style> </head> <body> <div id="container"> <h1>Welcome to CodeIgniter!</h1> <div class="surveycontainer"> Type Question Here:<input type='text' name='question'> Answer type:<select name="answertype" id="selectarea" class="form-control"> <option value="1">single choice</option> <option value="2">Text-box</option> <option value="3">Multi choice</option> </select> </div> <div class="answerfield"> <div class="singlechoice"> <input type="radio" name="singlechoice[]"><input type="text" value='Option1'> <input type="radio" name="singlechoice[]"><input type="text" value='Option2'> <input type="radio" name="singlechoice[]"><input type="text" value='Option3'> <a href="#" id="addmore">Addmore</a> </div> <div class="multichoice"> <input type="checkbox" name="multichoice[]"><input type="text" value='Option1'> <input type="checkbox" name="multichoice[]"><input type="text" value='Option2'> <input type="checkbox" name="multichoice[]"><input type="text" value='Option3'> <a href="#" id="addmore">Addmore</a> </div> </div> <div class="first"> <input type="button" value="ADD Question" id="addQ" class="btn btn-success"> </div> <div class="second"> <input type="button" value="save" class="btn btn-success"> <input type="button" value="Cancel" class="btn btn-warning"> </div> <script> jQuery(document).ready(function($) { $(".second").hide(); $('.singlechoice').hide(); $('.multichoice').hide(); }); $("#addQ").click(function(){ //$(".surveycontainer").append("Type Question Here:<input type='text' name='question'>"); $(".first").hide(); $(".second").show(); }); //need to use switch instead for better //script to show the input fields based on what is selected $("#selectarea").change(function(){ if($(this).val()=="1"){ $(".singlechoice").show(); $(".multichoice").hide(); } if($(this).val()=="2"){ $(".singlechoice").hide(); $(".multichoice").show(); } }); //script for addmore fields $("#addmore").click(function(e){ $(this).before("<input type='checkbox' name='multichoice[]'><input type='text' value='Optionmore'>"); e.preventDefault(); }); </script> </body> </html>
2508d8afb8a09345a24780c6a5127d95e607f1a9
[ "PHP" ]
1
PHP
taragurung/survey
26956fa75683653c9a4bc1e18878d6f8dc671439
1c7bb7199f4270404fb7dbc97c1e3003308d53a3
refs/heads/main
<repo_name>fangh528/test<file_sep>/php1.php <?php phpinof(); 1111
e4eb4e8dd9ac942a6c791542d6582323141f6377
[ "PHP" ]
1
PHP
fangh528/test
d09466efc914772e369e861424fe313e4144fbf3
3a43c9daed6dfca5f5d897adde48d0331b07df9d
refs/heads/master
<file_sep>package com.doublyLinkedList; /** * Created by RV on 6/26/2015. */ public class Main { public static void main(String[] args) { DoublyLinkedList lst = new DoublyLinkedList(); lst.add("hello!"); lst.add("hi!"); lst.add(3456); lst.add(45665); lst.add("welcome!"); lst.add("to world!"); lst.add("abcd"); lst.displayList(); System.out.println(); /*lst.displayListReverse(); System.out.println(); System.out.println(lst.size()); System.out.println(); lst.insertAtHead("eternal"); lst.displayList(); System.out.println(lst.size()); System.out.println(); lst.insertAtTail("most"); lst.displayList(); System.out.println(); System.out.println(lst.size()); System.out.println(); //System.out.println(lst.size2()); if (lst.contains("to world!")) { System.out.println("it contains"); } else { System.out.println("it does not contain"); } System.out.println(lst.fetch(4));*/ lst.replace(4, "welcome to heaven!"); lst.displayList(); System.out.println(lst.size()); System.out.println(); /* lst.replace("to world", "this is magic!"); lst.displayList(); System.out.println();*/ lst.insertAtIndex(5, 566734); lst.displayList(); System.out.println(lst.size()); } }
e4efc51c884b8ca5aae21b652a17f485dfdbcd96
[ "Java" ]
1
Java
varshneyanmol/doubly-linkedList-made-from-home
7a2fc72391a5177ea2f62009b2db826c43057441
0d3a63651fde42c3d379123cbbbba6acba3f5c76
refs/heads/master
<repo_name>VNextCorp/VNextOS<file_sep>/README.md ## NextOS A **fast**, **simple**, colored terminal **OS** for **ComputerCraft** ## Installation ```pastebin run w410DuNi``` #Log in >There is **no password** in default, but you can set password , typing in the shell "cpass" <file_sep>/init.lua --== APIS ==-- os.loadAPI("/.vsh/lib/base64") os.loadAPI("/.vsh/lib/vnext") os.pullEvent = os.pullEventRaw --== KERNEL BOOTING BEGIN ==-- vnext.writeLog("Loading NextOS...") if term.isColor() then cols = { info = colors.yellow, ok = colors.green, err = colors.red, } term.setTextColor(cols.info) print("term is color") vnext.writeLog("Detected colored terminal") else cols = { info = colors.white, ok = colors.white, err = colors.white } term.setTextColor(cols.info) vnext.writeLog("Detected b/w terminal") print("term is b/w") end term.setTextColor(cols.info) vnext.writeLog("Peripherals detection begin") print("peripherals detection begin") for _,side in pairs(rs.getSides()) do if peripheral.getType(side) == "drive" then term.setTextColor(cols.ok) print("detected disk drive in side "..side) vnext.writeLog("Detected disk drive on side "..side) elseif peripheral.getType(side) == "monitor" then term.setTextColor(cols.ok) print("detected monitor on side "..side) elseif peripheral.getType(side) == "printer" then term.setTextColor(cols.ok) print("detected printer on side "..side) else term.setTextColor(cols.err) print("no peripherals connected on side "..side) end end term.setTextColor(cols.info) print("floppy medium detection begin") for _,side in pairs(rs.getSides()) do if disk.hasData(side) then term.setTextColor(cols.ok) print("detected floppy disk inserted in drive "..side) else term.setTextColor(cols.err) print("disk drive "..side..": no medium found") end end if http then term.setTextColor(cols.info) print("detected HTTP support.") else term.setTextColor(cols.err) print("detected no HTTP support") end term.setTextColor(colors.white) vnext.writeLog("Loading config") if fs.exists("/.vsh/etc/config") then local configH = fs.open("/.vsh/etc/config", "r") VNext = textutils.unserialize(configH.readAll()) else vnext.crash("Config file not found") end vnext.writeLog("Log in") if fs.exists("/.vsh/bin/login") then os.pullEvent = oldpull shell.run("/.vsh/bin/login") else vnext.crash("Unknown error") end <file_sep>/usr/Applications/buttonTest.app/main.lua if os.loadAPI("/.vsh/lib/button") then term.setBackgroundColor(colors.black) term.clear() local tx, ty = term.getSize() local msg = "Hello, World!" term.setCursorPos(tx/2-#msg/2, ty/2-3) write(msg) local button1 = button.createButton("OK", math.floor(tx/2-3/2), math.floor(ty/2), colors.blue) button.drawButton(button1) while true do local _, _, x, y = os.pullEvent("mouse_click") if button.checkClick(x, y, button1) == true then term.setBackgroundColor(colors.black) term.clear() term.setCursorPos(1, 1) break end end else print("This program requires VNextOS and button API") end <file_sep>/bin/login --== APIS ==-- os.loadAPI("/.vsh/lib/base64") os.loadAPI("/.vsh/lib/vnext") oldpull = os.pullEvent os.pullEvent = os.pullEventRaw --== PROTECTION FOR SOME CLEVER ASSHOLES! ==-- if VNext.settings.loggedIn == true then print("You already logged in.") os.pullEvent = oldpull else print("NextOS v"..VNext.settings.version) if fs.exists("/.vsh/etc/passwd") then while true do write("Password:") local yourpass = tostring(read(" ")) local passH = fs.open("/.vsh/etc/passwd", "r") if yourpass == base64.decode(passH.readAll()) then passH.close() VNext.settings.loggedIn = true os.pullEvent = oldpull shell.run("/.vsh/bin/vsh") else print("Wrong password!") passH.close() end end else os.pullEvent = oldpull shell.run("/.vsh/bin/vsh") end end
0362c5ae5863837a9d7fcbd83cc04c5279d67f3f
[ "Markdown", "Shell", "Lua" ]
4
Markdown
VNextCorp/VNextOS
ed9667331d030b8517934015a6c2a53168577247
e016250989e9e7828679ef19cfb93cf01d9bd749
refs/heads/master
<file_sep># Samples for Groovy Training ## Setup ### Tools * install GGTS or Eclipse with Groovy Plugin ### Setup project * clone repository * import project ### Database * database sample uses hsqldb * start scripts (server, console) provided in folder db * setup database using application.sql ## Source Folders * scripts * hello world * variables and literals * operators * control structures * functions * exception handling * TypeChecked * closures * snippets * basic examples * oop * classes (static_types) * Traits, Categories, Mixins * Expando * MetaClass * overload operators * app * books application * setup database before testing * test * oop tests * books application tests * snippets, some tests read files from folder data * basic tests * read config files * templating * a simple build configuration<file_sep>url=$url user=$user password=$pwd<file_sep>create table messages (message varchar(256)) create table books (isbn varchar(256), title varchar (256), pages integer, price double, available boolean, publisingDate date, primary key(isbn)) insert into books values ('ISBN1', 'Title1', 200, 19.99) insert into books values ('ISBN2', 'Title2', 220, 9.99) insert into books values ('ISBN3', 'Title3', 240, 29.99) select * from books -- drop table books -- drop table messages<file_sep>url=jdbc:hsqldb:. user=SA password=url=jdbc:hsqldb:. user=SA password=
6a6f180f0492b5d29611d1aa48555f7128f168a2
[ "Markdown", "SQL", "INI" ]
4
Markdown
Javacream/org.javacream.training.groovy
e7eb63f94a0e8643f1398afd8bbef270fa90cfcb
09c234a336289ce305cb37264e67bc09ba4bf720
refs/heads/master
<file_sep>from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='Document on recapping applying various ML models on MittOS dataset', author='<NAME>', license='MIT', )
0d42b156ca1f2dd9bfb52c1f16407dfbebb2a2d5
[ "Python" ]
1
Python
adylanrff/mittos-ml-recap
fe2ad92df22c44c0a1b3f2dd5fab83f1c394ac77
50a9510102aa3d40fefcc78c1000ba16bf575e66
refs/heads/master
<file_sep><?php /** * A class to load them all. * * @author <NAME> */ class ClassLoader { private $folders = array(); const EXT = '.php'; /** * Observes several folders. * * @param array $folders */ public function folders(array $folders) { foreach ($folders as $folder): $this->folder($folder); endforeach; } /** * Observes one folder. * * @param string $folder */ public function folder($folder) { $this->recursiveWalk($folder); spl_autoload_register(array($this, 'loadClass')); } /** * Autoloads the classes. * * @param string $class */ private function loadClass($class) { $this->folders = array_unique($this->folders); foreach ($this->folders as $folder): $file = new \SplFileInfo($folder.$class.self::EXT); if ($file->isFile()): require_once $file; endif; endforeach; } /** * Iterates recursevily into directories to observe subfolders. * * @param string $folder */ private function recursiveWalk($folder) { $files = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($folder) ); foreach ($files as $file): $this->folders[] = $file->getPath().'/'; endforeach; } }<file_sep>ClassLoader =========== A PHP class to load them all. ## Mechanism ```php <?php // Import the library require_once 'path/to/ClassLoader.php'; // Create a new object $loader = new ClassLoader; // Observe one folder $loader->folder('folder1'); // Observe several folders $loader->folders(array('folder2', 'folder3')); // Now you can call your classes ;-) ``` ## Requirements This class needs PHP 5.3 or later. ## License Aenyhm's ClassLoader is licensed under the MIT license. ## Note You may prefer the [Symfony ClassLoader Component](https://github.com/symfony/ClassLoader).
9f12f5b7c87916cfc759ba975a5b3ca95d45df47
[ "Markdown", "PHP" ]
2
PHP
Aenyhm/ClassLoader
5a0cb9f2726e8d4d691d7d92dabe42288784ab30
2a011e6a049d64e6419c46ef9eef74c596597863
refs/heads/master
<repo_name>NEkate/furniture<file_sep>/scss.sh cd $1 node-sass --source-comments=map $2 $3 <file_sep>/js/main.js jQuery(function($) { var carousel= $('#carousel'); carousel .jcarousel({ wrap: 'circular' }) .jcarouselAutoscroll({ interval: 3000, target: '+=1', autostart: true }) ; carousel.on('jcarousel:scroll', function(){ var index = carousel.jcarousel('target').prop('index'); carousel .find('.pagination a') .removeClass('active') .eq(index) .addClass('active') ; }); carousel.find('li').prop('index', function (i) { return i; }); carousel.on('click', '.pagination a', function (e) { e.preventDefault(); var index = $(e.target).index(); carousel.jcarousel('scroll', index); }); var width = carousel.width(); $('<style>') .html('.carousel-width { width:' + width + 'px; }') .appendTo('body') ; });
418e411996f7b23eb3f6a2fdc6757f26f0633a59
[ "JavaScript", "Shell" ]
2
Shell
NEkate/furniture
17647b9c12b65c8b190359d0787ae9bd2434760a
56aedbe2d4af0eebcf454de1d5c542b678b25a2e
refs/heads/master
<repo_name>zhaoyuanfang12138/Recyclerview<file_sep>/app/src/main/java/com/example/lenovo/recyclerviewweek3/mvp/view/MainActivity.java package com.example.lenovo.recyclerviewweek3.mvp.view; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.widget.LinearLayout; import android.widget.Toast; import com.example.lenovo.recyclerviewweek3.R; import com.example.lenovo.recyclerviewweek3.mvp.adapter.NewsAdapter; import com.example.lenovo.recyclerviewweek3.mvp.bean.News; import com.example.lenovo.recyclerviewweek3.mvp.presenter.RecyclerPresenter; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements IView{ private RecyclerView rvList; private List<News.DataBean> list; private RecyclerPresenter presenter; private NewsAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rvList = findViewById(R.id.rv_list); initData(); list = new ArrayList<>(); //适配器 adapter = new NewsAdapter(this,list); //瀑布流管理器 RecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL); //添加管理器 rvList.setLayoutManager(layoutManager); rvList.setAdapter(adapter); } private void initData() { presenter = new RecyclerPresenter(); presenter.attach(this); presenter.getNews(); } @Override public void success(List<News.DataBean> dataBeans) { list.addAll(dataBeans); adapter.notifyDataSetChanged(); } @Override public void faied(Exception e) { Toast.makeText(this, "网络异常" + e.getMessage(), Toast.LENGTH_SHORT).show(); } } <file_sep>/app/src/main/java/com/example/lenovo/recyclerviewweek3/mvp/view/IView.java package com.example.lenovo.recyclerviewweek3.mvp.view; import com.example.lenovo.recyclerviewweek3.mvp.bean.News; import java.util.List; /** * Created by lenovo on 2018/10/21. */ public interface IView { void success(List<News.DataBean> list); void faied(Exception e); }
85ba97e52e5a7b0e3d95ae2216db07d6a8538f02
[ "Java" ]
2
Java
zhaoyuanfang12138/Recyclerview
be4cd3f297345cf2f098c6cd81ea1c0a36724686
9fbb539fd037027d1026f60fcc5eb03851a5425f
refs/heads/master
<file_sep>Opengl codes/Boundaryfill algorithm ![Output](https://github.com/greedForcode/openGL-codes/blob/master/boundary_fill_algorithm_output.gif) <file_sep>#include<GL/gl.h> #include<GL/glut.h> #include<stdio.h> struct point2D { GLint x; GLint y; } p1, p2; //structure of point struct colorPixel { GLfloat r; GLfloat g; GLfloat b; }; //structure of Color value //Function for setting new pixel color to given Point void setPixelColor(GLint x, GLint y, colorPixel color) { glColor3f(color.r, color.g, color.b); glBegin(GL_POINTS); glVertex2i(x, y); glEnd(); glFlush(); } //initial window condition setting void window_Init() { glClearColor(1.0, 1.0, 1.0, 0.0); glColor3f(0.0, 0.0, 0.0); glPointSize(1.0); //setting point size glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, 650, 0, 450); //for 2D view } //finding current color pixel to given Point colorPixel get_pixelColor(GLint x, GLint y) { colorPixel color; glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, & color); return color; } //cHECKING TWO COLOR ARE DIFFRENT IF YES THEN GIVE 1 ELSE NO int isDiffrent(colorPixel c1, colorPixel c2) { if (c1.r != c2.r || c1.g != c2.g || c1.b != c2.b) return 1; else return 0; } //Checking Boundary Point int isBoundary(colorPixel currentColor) { if (currentColor.g == 1.0 && currentColor.b == 0.0 && currentColor.r == 0.0) return 1; else return 0; } int count = 0; //function for filling India Map using BoundaryFill algorithm void boundary_fill(int x, int y, colorPixel fill_color, colorPixel boundary_color) { colorPixel currentColor = get_pixelColor(x, y); //check current pixel color colorPixel c1 = get_pixelColor(x - 1, y); colorPixel c2 = get_pixelColor(x + 1, y); colorPixel c3 = get_pixelColor(x, y - 1); colorPixel c4 = get_pixelColor(x, y + 1); //checking Boundary Condition if (isBoundary(c1) || isBoundary(c2) || isBoundary(c3) || isBoundary(c4)) return; //if current pixel is diffrent from fill color and not equal to boundary color then go to up,down,left,right and fill if (isDiffrent(currentColor, fill_color) && isDiffrent(boundary_color, currentColor)) { setPixelColor(x, y, fill_color); boundary_fill(x - 1, y, fill_color, boundary_color); boundary_fill(x, y - 1, fill_color, boundary_color); boundary_fill(x + 1, y, fill_color, boundary_color); boundary_fill(x, y + 1, fill_color, boundary_color); } } //function for scaling x_coordinate int getx(int X) { return ((int)(((-1.0) + X / 40.0) * 100) + 200) * 2 - 50; } //function for scaling y_coordinate int gety(int Y) { return ((int)(((0.5) - Y / 40.0) * 150 + 150)) * 2 - 40; } //function for drawing line between to point using DDA void DrawLine(int xx1, int yy1, int xx2, int yy2) { p1.x = xx1; p1.y = yy1; p2.x = xx2; p2.y = yy2; GLfloat dx = p2.x - p1.x; GLfloat dy = p2.y - p1.y; GLfloat x1 = p1.x; GLfloat y1 = p1.y; GLfloat step = 0; if (abs(dx) > abs(dy)) { step = abs(dx); } else { step = abs(dy); } GLfloat xInc = dx / step; GLfloat yInc = dy / step; for (float i = 1; i <= step; i++) { glVertex2i(x1, y1); x1 += xInc; y1 += yInc; } } //function for sketching map void draw_Map() { DrawLine(getx(20), gety(0), getx(25), gety(0)); DrawLine(getx(25), gety(0), getx(26), gety(1)); DrawLine(getx(26), gety(1), getx(29), gety(1)); DrawLine(getx(29), gety(1), getx(30), gety(2)); DrawLine(getx(30), gety(2), getx(35), gety(2)); DrawLine(getx(36), gety(3), getx(35), gety(2)); DrawLine(getx(36), gety(3), getx(35), gety(4)); DrawLine(getx(35), gety(5), getx(35), gety(4)); DrawLine(getx(35), gety(5), getx(33), gety(6)); DrawLine(getx(35), gety(7), getx(33), gety(6)); DrawLine(getx(35), gety(7), getx(31), gety(8)); DrawLine(getx(33), gety(9), getx(31), gety(8)); DrawLine(getx(33), gety(9), getx(36), gety(10)); DrawLine(getx(36), gety(11), getx(36), gety(10)); DrawLine(getx(36), gety(11), getx(38), gety(13)); DrawLine(getx(40), gety(15), getx(38), gety(13)); DrawLine(getx(40), gety(15), getx(41), gety(15)); DrawLine(getx(41), gety(15), getx(42), gety(16)); DrawLine(getx(47), gety(16), getx(42), gety(16)); DrawLine(getx(47), gety(16), getx(48), gety(17)); DrawLine(getx(48), gety(17), getx(50), gety(17)); DrawLine(getx(50), gety(17), getx(52), gety(15)); DrawLine(getx(55), gety(17), getx(52), gety(15)); DrawLine(getx(55), gety(17), getx(57), gety(14)); DrawLine(getx(59), gety(17), getx(57), gety(14)); DrawLine(getx(59), gety(17), getx(62), gety(17)); DrawLine(getx(63), gety(16), getx(62), gety(17)); DrawLine(getx(63), gety(16), getx(63), gety(15)); DrawLine(getx(66), gety(15), getx(63), gety(15)); DrawLine(getx(69), gety(12), getx(66), gety(15)); DrawLine(getx(69), gety(12), getx(74), gety(12)); DrawLine(getx(75), gety(13), getx(74), gety(12)); DrawLine(getx(75), gety(13), getx(78), gety(12)); DrawLine(getx(76), gety(14), getx(78), gety(12)); DrawLine(getx(76), gety(14), getx(74), gety(14)); DrawLine(getx(74), gety(15), getx(74), gety(14)); DrawLine(getx(74), gety(15), getx(72), gety(15)); DrawLine(getx(71), gety(16), getx(72), gety(15)); DrawLine(getx(71), gety(16), getx(72), gety(17)); DrawLine(getx(72), gety(17), getx(71), gety(17)); DrawLine(getx(71), gety(19), getx(71), gety(17)); DrawLine(getx(71), gety(19), getx(69), gety(21)); DrawLine(getx(68), gety(21), getx(69), gety(21)); DrawLine(getx(68), gety(21), getx(68), gety(23)); DrawLine(getx(67), gety(20), getx(68), gety(23)); DrawLine(getx(67), gety(20), getx(67), gety(22)); DrawLine(getx(66), gety(22), getx(67), gety(22)); DrawLine(getx(63), gety(19), getx(66), gety(22)); DrawLine(getx(63), gety(19), getx(60), gety(19)); DrawLine(getx(59), gety(18), getx(60), gety(19)); DrawLine(getx(59), gety(18), getx(57), gety(19)); DrawLine(getx(57), gety(21), getx(57), gety(19)); DrawLine(getx(57), gety(21), getx(60), gety(23)); DrawLine(getx(56), gety(23), getx(60), gety(23)); DrawLine(getx(56), gety(23), getx(55), gety(24)); DrawLine(getx(54), gety(24), getx(55), gety(24)); DrawLine(getx(54), gety(24), getx(51), gety(27)); DrawLine(getx(47), gety(27), getx(51), gety(27)); DrawLine(getx(47), gety(27), getx(47), gety(29)); DrawLine(getx(47), gety(29), getx(45), gety(30)); DrawLine(getx(43), gety(30), getx(45), gety(30)); DrawLine(getx(43), gety(30), getx(43), gety(31)); DrawLine(getx(42), gety(33), getx(43), gety(31)); DrawLine(getx(42), gety(33), getx(40), gety(33)); DrawLine(getx(36), gety(38), getx(40), gety(33)); DrawLine(getx(36), gety(38), getx(36), gety(39)); DrawLine(getx(35), gety(39), getx(36), gety(39)); DrawLine(getx(35), gety(39), getx(35), gety(42)); DrawLine(getx(33), gety(44), getx(35), gety(42)); DrawLine(getx(33), gety(44), getx(32), gety(43)); DrawLine(getx(30), gety(45), getx(32), gety(43)); DrawLine(getx(27), gety(45), getx(30), gety(45)); DrawLine(getx(27), gety(45), getx(26), gety(44)); DrawLine(getx(26), gety(43), getx(26), gety(44)); DrawLine(getx(26), gety(43), getx(25), gety(42)); DrawLine(getx(25), gety(41), getx(25), gety(42)); DrawLine(getx(25), gety(41), getx(18), gety(33)); DrawLine(getx(18), gety(27), getx(18), gety(33)); DrawLine(getx(18), gety(27), getx(17), gety(27)); DrawLine(getx(17), gety(22), getx(17), gety(27)); DrawLine(getx(17), gety(22), getx(15), gety(25)); DrawLine(getx(11), gety(25), getx(15), gety(25)); DrawLine(getx(11), gety(25), getx(9), gety(23)); DrawLine(getx(8), gety(23), getx(9), gety(23)); DrawLine(getx(8), gety(23), getx(6), gety(22)); DrawLine(getx(6), gety(21), getx(6), gety(22)); DrawLine(getx(6), gety(21), getx(7), gety(20)); DrawLine(getx(12), gety(20), getx(7), gety(20)); DrawLine(getx(12), gety(20), getx(14), gety(21)); DrawLine(getx(14), gety(18), getx(14), gety(21)); DrawLine(getx(14), gety(18), getx(13), gety(18)); DrawLine(getx(11), gety(16), getx(13), gety(18)); DrawLine(getx(11), gety(16), getx(12), gety(15)); DrawLine(getx(16), gety(15), getx(12), gety(15)); DrawLine(getx(16), gety(15), getx(12), gety(15)); DrawLine(getx(16), gety(15), getx(18), gety(14)); DrawLine(getx(18), gety(13), getx(18), gety(14)); DrawLine(getx(18), gety(13), getx(19), gety(13)); DrawLine(getx(21), gety(11), getx(19), gety(13)); DrawLine(getx(21), gety(11), getx(22), gety(11)); DrawLine(getx(24), gety(9), getx(22), gety(11)); DrawLine(getx(24), gety(9), getx(22), gety(8)); DrawLine(getx(22), gety(5), getx(22), gety(8)); DrawLine(getx(22), gety(5), getx(21), gety(4)); DrawLine(getx(21), gety(2), getx(21), gety(4)); DrawLine(getx(21), gety(2), getx(20), gety(0)); } //function for display void Display(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0, 1, 0); //setting green color boundary of india_map glBegin(GL_POINTS); draw_Map(); glEnd(); colorPixel fill_color = { 1.0 f, 0.0 f, 0.0 f }; // red color will be filled colorPixel boundary_color = { 0.0 f, 1.0 f, 0.0 f }; // green- boundary point2D p = { 300, 300 }; // a point inside the Map boundary_fill(p.x, p.y, fill_color, boundary_color); //call for fill the mAP glFlush(); } int main(int argc, char ** argv) { glutInit( & argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(650, 450); glutInitWindowPosition(200, 200); glutCreateWindow("Open GL"); window_Init(); glutDisplayFunc(Display); glutMainLoop(); return 0; }
951ee23079cd054d36bcc95c74baa804c9ac5521
[ "Markdown", "C++" ]
2
Markdown
sushilchaudhary627/openGL-codes
112628c58ddf67715d8b110b72a2f7e043032380
6931a1c01035abe2840acc364cbdbbf1e2445f8a
refs/heads/main
<repo_name>MyakishHentai/HotelService<file_sep>/HotelService/Models/Base/Service.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; #nullable disable namespace HotelService.Models.Base { public class Service { public Service() { CostChanges = new HashSet<CostChange>(); Favorites = new HashSet<Favorite>(); Feedbacks = new HashSet<Feedback>(); Requests = new HashSet<Request>(); } public int Id { get; set; } [Display(Name = "Категория")] public int ServiceCategoryId { get; set; } [Display(Name = "Заголовок")] [RegularExpression(@"^[А-я0-9A-z]*$")] [StringLength(20, MinimumLength = 10, ErrorMessage = "{0} должна содержать хотя бы {2} и максимум {1} символов.")] [Required(ErrorMessage = "Имя обязательно")] public string Title { get; set; } [Display(Name = "Подзаголовок")] public string Subtitle { get; set; } [Display(Name = "Описание")] public string Description { get; set; } [Display(Name = "Изображение")] public string ImagePath { get; set; } [Display(Name = "Стоимость")] public decimal Cost { get; set; } public double? Rating { get; set; } [Display(Name = "Доступность на текущий момент")] public bool AvailableState { get; set; } [Display(Name = "Возможность повторения")] public bool RepeatState { get; set; } public DateTime AddedDate { get; set; } public ServiceCategory ServiceCategory { get; set; } public ICollection<CostChange> CostChanges { get; set; } public ICollection<Favorite> Favorites { get; set; } public ICollection<Feedback> Feedbacks { get; set; } public ICollection<Request> Requests { get; set; } } } <file_sep>/HotelService/notes.txt 1) Добавить проверку при Delete в ManageRolesUsers - ТЭГ Identitu-Role проверить 2) По возможности сделать PopUp menu и уведомлениями 3) Прочитать про EF Core 4) Реализовать Chart.js 5) CRUD на manage users, orders 6) Реализовать область Client, корзина покупок и т.п.<file_sep>/HotelService/Migrations/20210610024904_Initial_D.cs using System; using Microsoft.EntityFrameworkCore.Migrations; namespace HotelService.Migrations { public partial class Initial_D : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Roles", columns: table => new { Id = table.Column<string>(type: "nvarchar(450)", nullable: false), Name = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), NormalizedName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Roles", x => x.Id); }); migrationBuilder.CreateTable( name: "ServiceCategories", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), SubCategoryId = table.Column<int>(type: "int", nullable: true), Title = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), Subtitle = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), Description = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true), ImagePath = table.Column<string>(type: "nvarchar(1024)", maxLength: 1024, nullable: true), AvailableState = table.Column<bool>(type: "bit", nullable: false, defaultValueSql: "((1))") }, constraints: table => { table.PrimaryKey("PK_ServiceCategories", x => x.Id); table.ForeignKey( name: "FK__ServiceCa__SubCa__3E52440B", column: x => x.SubCategoryId, principalTable: "ServiceCategories", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "States", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Value = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false) }, constraints: table => { table.PrimaryKey("PK_States", x => x.Id); }); migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<string>(type: "nvarchar(450)", nullable: false), FirstName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), LastName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), Patronymic = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), Gender = table.Column<string>(type: "nvarchar(16)", maxLength: 16, nullable: true), Passport = table.Column<string>(type: "nvarchar(32)", maxLength: 32, nullable: false), BirthDate = table.Column<DateTime>(type: "datetime2", nullable: true), ForeignerStatus = table.Column<bool>(type: "bit", nullable: true, defaultValueSql: "((0))"), RegistrationDate = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "(getdate())"), ImagePath = table.Column<string>(type: "nvarchar(1024)", maxLength: 1024, nullable: true), UserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), Email = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(type: "bit", nullable: false), PasswordHash = table.Column<string>(type: "nvarchar(max)", nullable: true), SecurityStamp = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true), PhoneNumber = table.Column<string>(type: "nvarchar(max)", nullable: true), PhoneNumberConfirmed = table.Column<bool>(type: "bit", nullable: false), TwoFactorEnabled = table.Column<bool>(type: "bit", nullable: false), LockoutEnd = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true), LockoutEnabled = table.Column<bool>(type: "bit", nullable: false), AccessFailedCount = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); }); migrationBuilder.CreateTable( name: "RoleClaims", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), RoleId = table.Column<string>(type: "nvarchar(450)", nullable: false), ClaimType = table.Column<string>(type: "nvarchar(max)", nullable: true), ClaimValue = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_RoleClaims", x => x.Id); table.ForeignKey( name: "FK_RoleClaims_Roles_RoleId", column: x => x.RoleId, principalTable: "Roles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Services", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), ServiceCategoryId = table.Column<int>(type: "int", nullable: false), Title = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), Subtitle = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), Description = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true), ImagePath = table.Column<string>(type: "nvarchar(1024)", maxLength: 1024, nullable: true), Cost = table.Column<decimal>(type: "decimal(8,2)", nullable: false, defaultValueSql: "((1000.00))"), Rating = table.Column<double>(type: "float", nullable: true), AvailableState = table.Column<bool>(type: "bit", nullable: false, defaultValueSql: "((1))"), RepeatState = table.Column<bool>(type: "bit", nullable: false, defaultValueSql: "((1))"), AddedDate = table.Column<DateTime>(type: "date", nullable: false, defaultValueSql: "(getdate())") }, constraints: table => { table.PrimaryKey("PK_Services", x => x.Id); table.ForeignKey( name: "FK__Services__Servic__48CFD27E", column: x => x.ServiceCategoryId, principalTable: "ServiceCategories", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Articles", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), AuthorId = table.Column<string>(type: "nvarchar(450)", maxLength: 450, nullable: false), Title = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), Review = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: false), ImagePath = table.Column<string>(type: "nvarchar(1024)", maxLength: 1024, nullable: true), WritingDate = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "(getdate())") }, constraints: table => { table.PrimaryKey("PK_Articles", x => x.Id); table.ForeignKey( name: "FK__Articles__Author__5AEE82B9", column: x => x.AuthorId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Buildings", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), AdminId = table.Column<string>(type: "nvarchar(450)", maxLength: 450, nullable: true), Name = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), Address = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), Description = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), ImagePath = table.Column<string>(type: "nvarchar(1024)", maxLength: 1024, nullable: true) }, constraints: table => { table.PrimaryKey("PK_Buildings", x => x.Id); table.ForeignKey( name: "FK__Buildings__Admin__2E1BDC42", column: x => x.AdminId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.SetNull); }); migrationBuilder.CreateTable( name: "UserClaims", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), UserId = table.Column<string>(type: "nvarchar(450)", nullable: false), ClaimType = table.Column<string>(type: "nvarchar(max)", nullable: true), ClaimValue = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_UserClaims", x => x.Id); table.ForeignKey( name: "FK_UserClaims_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "UserLogins", columns: table => new { LoginProvider = table.Column<string>(type: "nvarchar(450)", nullable: false), ProviderKey = table.Column<string>(type: "nvarchar(450)", nullable: false), ProviderDisplayName = table.Column<string>(type: "nvarchar(max)", nullable: true), UserId = table.Column<string>(type: "nvarchar(450)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_UserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_UserLogins_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "UserRoles", columns: table => new { UserId = table.Column<string>(type: "nvarchar(450)", nullable: false), RoleId = table.Column<string>(type: "nvarchar(450)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_UserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_UserRoles_Roles_RoleId", column: x => x.RoleId, principalTable: "Roles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_UserRoles_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "UserTokens", columns: table => new { UserId = table.Column<string>(type: "nvarchar(450)", nullable: false), LoginProvider = table.Column<string>(type: "nvarchar(450)", nullable: false), Name = table.Column<string>(type: "nvarchar(450)", nullable: false), Value = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_UserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_UserTokens_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "CostChanges", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), ServiceId = table.Column<int>(type: "int", nullable: false), ChangeDate = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "(getdate())"), NewCostValue = table.Column<decimal>(type: "decimal(8,2)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_CostChanges", x => x.Id); table.ForeignKey( name: "FK__CostChang__Servi__5EBF139D", column: x => x.ServiceId, principalTable: "Services", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Favorites", columns: table => new { ClientId = table.Column<string>(type: "nvarchar(450)", nullable: false), ServiceId = table.Column<int>(type: "int", nullable: false), ShowState = table.Column<bool>(type: "bit", nullable: false, defaultValueSql: "((1))") }, constraints: table => { table.PrimaryKey("PK__Favorite__5A2FA124A8632B4D", x => new { x.ClientId, x.ServiceId }); table.ForeignKey( name: "FK__Favorites__Clien__628FA481", column: x => x.ClientId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK__Favorites__Servi__6383C8BA", column: x => x.ServiceId, principalTable: "Services", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Feedback", columns: table => new { ClientId = table.Column<string>(type: "nvarchar(450)", nullable: false), ServiceId = table.Column<int>(type: "int", nullable: false), Rating = table.Column<int>(type: "int", nullable: false, defaultValueSql: "((5))"), Review = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true), WritingDate = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "(getdate())") }, constraints: table => { table.PrimaryKey("PK__Feedback__5A2FA124AF004554", x => new { x.ClientId, x.ServiceId }); table.ForeignKey( name: "FK__Feedback__Client__4F7CD00D", column: x => x.ClientId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK__Feedback__Servic__5070F446", column: x => x.ServiceId, principalTable: "Services", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Rooms", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), BuildingId = table.Column<int>(type: "int", nullable: false), Number = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), Type = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false, defaultValueSql: "('STD')"), SleepingPlaces = table.Column<int>(type: "int", nullable: false, defaultValueSql: "((1))"), Cost = table.Column<decimal>(type: "decimal(8,2)", nullable: false, defaultValueSql: "((5000.00))"), ImagePath = table.Column<string>(type: "nvarchar(1024)", maxLength: 1024, nullable: true) }, constraints: table => { table.PrimaryKey("PK_Rooms", x => x.Id); table.ForeignKey( name: "FK__Rooms__BuildingI__35BCFE0A", column: x => x.BuildingId, principalTable: "Buildings", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "RoomContracts", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), ClientId = table.Column<string>(type: "nvarchar(450)", maxLength: 450, nullable: false), RoomId = table.Column<int>(type: "int", nullable: false), ConclusionDate = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "(getdate())"), CheckInDate = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "(getdate())"), CheckOutDate = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_RoomContracts", x => x.Id); table.ForeignKey( name: "FK__RoomContr__Clien__5535A963", column: x => x.ClientId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK__RoomContr__RoomI__5629CD9C", column: x => x.RoomId, principalTable: "Rooms", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Orders", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), RoomContractId = table.Column<int>(type: "int", nullable: false), PhoneNumber = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), Name = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), PaymentDetails = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), CreditCardNumber = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), PaymentDate = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "(getdate())"), CostTotal = table.Column<decimal>(type: "decimal(10,2)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Orders", x => x.Id); table.ForeignKey( name: "FK__Orders__RoomCont__68487DD7", column: x => x.RoomContractId, principalTable: "RoomContracts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Requests", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), OrderId = table.Column<int>(type: "int", nullable: true), ServiceId = table.Column<int>(type: "int", nullable: false), Comment = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), Quantity = table.Column<int>(type: "int", nullable: false, defaultValueSql: "((1))"), DeliveryDate = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "(getdate())") }, constraints: table => { table.PrimaryKey("PK_Requests", x => x.Id); table.ForeignKey( name: "FK__Requests__OrderI__6E01572D", column: x => x.OrderId, principalTable: "Orders", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK__Requests__Servic__6EF57B66", column: x => x.ServiceId, principalTable: "Services", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "RequestStates", columns: table => new { RequestId = table.Column<int>(type: "int", nullable: false), StateId = table.Column<int>(type: "int", nullable: false), ChangeDate = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "(getdate())"), Comment = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true) }, constraints: table => { table.PrimaryKey("PK__RequestS__8F93F2C977B5AE5B", x => new { x.RequestId, x.StateId }); table.ForeignKey( name: "FK__RequestSt__Reque__75A278F5", column: x => x.RequestId, principalTable: "Requests", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK__RequestSt__State__76969D2E", column: x => x.StateId, principalTable: "States", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Articles_AuthorId", table: "Articles", column: "AuthorId"); migrationBuilder.CreateIndex( name: "IX_Buildings_AdminId", table: "Buildings", column: "AdminId"); migrationBuilder.CreateIndex( name: "IX_CostChanges_ServiceId", table: "CostChanges", column: "ServiceId"); migrationBuilder.CreateIndex( name: "IX_Favorites_ServiceId", table: "Favorites", column: "ServiceId"); migrationBuilder.CreateIndex( name: "IX_Feedback_ServiceId", table: "Feedback", column: "ServiceId"); migrationBuilder.CreateIndex( name: "IX_Orders_RoomContractId", table: "Orders", column: "RoomContractId"); migrationBuilder.CreateIndex( name: "IX_Requests_OrderId", table: "Requests", column: "OrderId"); migrationBuilder.CreateIndex( name: "IX_Requests_ServiceId", table: "Requests", column: "ServiceId"); migrationBuilder.CreateIndex( name: "IX_RequestStates_StateId", table: "RequestStates", column: "StateId"); migrationBuilder.CreateIndex( name: "IX_RoleClaims_RoleId", table: "RoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "Roles", column: "NormalizedName", unique: true, filter: "[NormalizedName] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_RoomContracts_ClientId", table: "RoomContracts", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_RoomContracts_RoomId", table: "RoomContracts", column: "RoomId"); migrationBuilder.CreateIndex( name: "IX_Rooms_BuildingId", table: "Rooms", column: "BuildingId"); migrationBuilder.CreateIndex( name: "IX_ServiceCategories_SubCategoryId", table: "ServiceCategories", column: "SubCategoryId"); migrationBuilder.CreateIndex( name: "UQ__ServiceC__2CB664DC51D9118A", table: "ServiceCategories", column: "Title", unique: true); migrationBuilder.CreateIndex( name: "IX_Services_ServiceCategoryId", table: "Services", column: "ServiceCategoryId"); migrationBuilder.CreateIndex( name: "UQ__States__07D9BBC24E50A50A", table: "States", column: "Value", unique: true); migrationBuilder.CreateIndex( name: "IX_UserClaims_UserId", table: "UserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_UserLogins_UserId", table: "UserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_UserRoles_RoleId", table: "UserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "Users", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UQ__Users__208C1D4D741BCFFE", table: "Users", column: "Passport", unique: true); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "Users", column: "NormalizedUserName", unique: true, filter: "[NormalizedUserName] IS NOT NULL"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Articles"); migrationBuilder.DropTable( name: "CostChanges"); migrationBuilder.DropTable( name: "Favorites"); migrationBuilder.DropTable( name: "Feedback"); migrationBuilder.DropTable( name: "RequestStates"); migrationBuilder.DropTable( name: "RoleClaims"); migrationBuilder.DropTable( name: "UserClaims"); migrationBuilder.DropTable( name: "UserLogins"); migrationBuilder.DropTable( name: "UserRoles"); migrationBuilder.DropTable( name: "UserTokens"); migrationBuilder.DropTable( name: "Requests"); migrationBuilder.DropTable( name: "States"); migrationBuilder.DropTable( name: "Roles"); migrationBuilder.DropTable( name: "Orders"); migrationBuilder.DropTable( name: "Services"); migrationBuilder.DropTable( name: "RoomContracts"); migrationBuilder.DropTable( name: "ServiceCategories"); migrationBuilder.DropTable( name: "Rooms"); migrationBuilder.DropTable( name: "Buildings"); migrationBuilder.DropTable( name: "Users"); } } } <file_sep>/HotelService/Service/Developer.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HotelService.Service { public class Developer { public static string Name { get; set; } public static string FirstName { get; set; } public static string LastName { get; set; } public static string Passport { get; set; } public static string Email { get; set; } public static string Password { get; set; } public static string Role { get; set; } } } <file_sep>/HotelService/Models/Base/Order.cs using System; using System.Collections.Generic; #nullable disable namespace HotelService.Models.Base { public class Order { public Order() { Requests = new HashSet<Request>(); } public int Id { get; set; } public int RoomContractId { get; set; } public string PhoneNumber { get; set; } public string Name { get; set; } public string PaymentDetails { get; set; } public string CreditCardNumber { get; set; } public DateTime PaymentDate { get; set; } public decimal CostTotal { get; set; } public RoomContract RoomContract { get; set; } public ICollection<Request> Requests { get; set; } } } <file_sep>/HotelService/Repositories/Interfaces/IOrderManager.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models.Base; namespace HotelService.Repositories.Interfaces { public interface IOrderManager : IDisposable { IQueryable<Order> Orders { get; } IQueryable<RoomContract> Contracts{ get; } IQueryable<RoomContract> GetContractsForUser(string userId); void SaveOrder(Order order); Task Save(); } } <file_sep>/HotelService/Areas/Admin/Controllers/RequestController.cs using System.IO; using System.Linq; using System.Threading.Tasks; using HotelService.Models; using HotelService.Models.Base; using HotelService.Service; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; namespace HotelService.Areas.Admin.Controllers { [Area("Admin")] [Authorize(Roles = "Admin, Developer")] public class RequestController : Controller { private const string PathImg = "img/local/services"; private HotelServiceContext m_Context; private readonly IWebHostEnvironment m_HostingEnvironment; public RequestController(HotelServiceContext context, IWebHostEnvironment hostingEnvironment) { m_Context = context; m_HostingEnvironment = hostingEnvironment; } public async Task<IActionResult> Index() { var Services = m_Context.Services.AsNoTracking().Include(x => x.ServiceCategory); return View(await Services.ToListAsync()); } [NoDirectAccess] public async Task<IActionResult> CreateEdit(int? id) { if (id is null or 0) { ViewBag.SelectCategories = new SelectList(m_Context.ServiceCategories.ToList(), "Id", "Title"); return View(new Models.Base.Service()); } var Service = await m_Context.Services.Include(x => x.ServiceCategory) .FirstOrDefaultAsync(p => p.Id == id); ViewBag.SelectCategories = new SelectList( m_Context.ServiceCategories.Where(x => x.Id != Service.ServiceCategoryId).ToList(), "Id", "Title"); if (Service != null) return View(Service); return NotFound(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> CreateEdit(Models.Base.Service service, int? id, IFormFile imagePath) { if (ModelState.IsValid) { if (imagePath != null) { service.ImagePath = Path.Combine(PathImg, imagePath.FileName); await using var Stream = new FileStream(Path.Combine(m_HostingEnvironment.WebRootPath, PathImg, imagePath.FileName), FileMode.Create); await imagePath.CopyToAsync(Stream); } //Insert if (id == 0) { m_Context.Services.Add(service); await m_Context.SaveChangesAsync(); } //Update else { m_Context.Services.Update(service); //m_Context.Entry(service).State = EntityState.Modified; await m_Context.SaveChangesAsync(); } //return RedirectToAction("Index"); return Json(new { isValid = true, html = HelperView.RenderRazorViewToString(this, "_ViewTable", m_Context.Services.Include(c => c.ServiceCategory).ToList()) }); } if (id == null) { ViewBag.SelectCategories = new SelectList(await m_Context.ServiceCategories.ToListAsync(), "Id", "Title"); } else { ViewBag.SelectCategories = new SelectList( await m_Context.ServiceCategories.Where(x => x.Id != service.ServiceCategoryId).ToListAsync(), "Id", "Title"); } // TODO: Добавить сообщение об ошибках - повторении Index return Json(new { isValid = false, html = HelperView.RenderRazorViewToString(this, "CreateEdit", service) }); } [NoDirectAccess] public async Task<IActionResult> Details(int? id) { if (id == null) return NotFound(); var Service = await m_Context.Services.AsNoTracking() .Include(x => x.ServiceCategory) .FirstOrDefaultAsync(x => x.Id == id); if (Service != null) return View(Service); return NotFound(); } [HttpGet] [NoDirectAccess] [ActionName("Delete")] public async Task<IActionResult> ConfirmDelete(int? id) { if (id == null) return NotFound(); var Service = await m_Context.Services.Include(s => s.ServiceCategory).FirstOrDefaultAsync(p => p.Id == id); if (Service != null) return View(Service); return NotFound(); } [HttpPost] public async Task<IActionResult> Delete(int? id) { if (id == null) return NotFound(); var Service = await m_Context.Services.FirstOrDefaultAsync(p => p.Id == id); if (Service == null) return NotFound(); m_Context.Services.Remove(Service); await m_Context.SaveChangesAsync(); return RedirectToAction("Index"); } } }<file_sep>/HotelService/Models/Base/ServiceCategory.cs using System; using System.Collections.Generic; #nullable disable namespace HotelService.Models.Base { public class ServiceCategory { public ServiceCategory() { InverseSubCategory = new HashSet<ServiceCategory>(); Services = new HashSet<Service>(); } public int Id { get; set; } public int? SubCategoryId { get; set; } public string Title { get; set; } public string Subtitle { get; set; } public string Description { get; set; } public string ImagePath { get; set; } public bool AvailableState { get; set; } public ServiceCategory SubCategory { get; set; } public ICollection<ServiceCategory> InverseSubCategory { get; set; } public ICollection<Service> Services { get; set; } } } <file_sep>/HotelService/Models/ShoppingCart.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models.Base; namespace HotelService.Models { public class ShoppingCart { public List<Request> Lines { get; set; } = new List<Request>(); public virtual void AddItem(Base.Service service, int quantity) { var Line = Lines.FirstOrDefault(p => p.Service.Id == service.Id); if (Line == null) { Lines.Add(new Request { Service = service, Quantity = quantity }); } else { Line.Quantity += quantity; } } public virtual void RemoveLine(Base.Service product) => Lines.RemoveAll(l => l.Service.Id == product.Id); public virtual decimal ComputeTotalValue() => Lines.Sum(e => e.Service.Cost * e.Quantity); public virtual void Clear() => Lines.Clear(); } } <file_sep>/HotelService.Tests/CartTests.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models; using HotelService.Models.Base; using Xunit; using ServiceItem = HotelService.Models.Base.Service; namespace HotelService.Tests { public class CartTests { [Fact] public void Can_Add_New_Lines() { // Arrange - create some test products var Service1 = new ServiceItem { Id = 1, Title = "P1", Cost = 200.00M}; var Service2 = new ServiceItem { Id = 2, Title = "P2", Cost = 400.00M }; // Arrange - create a new cart var Target = new ShoppingCart(); // Act Target.AddItem(Service1, 1); Target.AddItem(Service2, 1); Request[] Results = Target.Lines.ToArray(); // Assert Assert.Equal(2, Results.Length); Assert.Equal(Service1, Results[0].Service); Assert.Equal(Service2, Results[1].Service); } [Fact] public void Can_Add_Quantity_For_Existing_Lines() { var Service1 = new ServiceItem { Id = 1, Title = "P1", Cost = 200.00M }; var Service2 = new ServiceItem { Id = 2, Title = "P2", Cost = 400.00M }; // Arrange - create a new cart var Target = new ShoppingCart(); // Act Target.AddItem(Service1, 1); Target.AddItem(Service2, 1); Target.AddItem(Service1, 10); Request[] Results = Target.Lines .OrderBy(c => c.Service.Id).ToArray(); // Assert Assert.Equal(2, Results.Length); Assert.Equal(11, Results[0].Quantity); Assert.Equal(1, Results[1].Quantity); } [Fact] public void Can_Remove_Line() { // Arrange - create some test products var Service1 = new ServiceItem { Id = 1, Title = "P1", Cost = 200.00M }; var Service2 = new ServiceItem { Id = 2, Title = "P2", Cost = 400.00M }; var Service3 = new ServiceItem { Id = 3, Title = "P2", Cost = 400.00M }; // Arrange - create a new cart var Target = new ShoppingCart(); // Arrange - add some products to the cart Target.AddItem(Service1, 1); Target.AddItem(Service2, 3); Target.AddItem(Service3, 5); Target.AddItem(Service2, 1); // Act Target.RemoveLine(Service2); // Assert Assert.Empty(Target.Lines.Where(c => c.Service == Service2)); Assert.Equal(2, Target.Lines.Count()); } [Fact] public void Calculate_Cart_Total() { var Service1 = new ServiceItem { Id = 1, Title = "P1", Cost = 200.00M }; var Service2 = new ServiceItem { Id = 2, Title = "P2", Cost = 400.00M }; // Arrange - create a new cart var Target = new ShoppingCart(); // Act Target.AddItem(Service1, 1); Target.AddItem(Service2, 1); Target.AddItem(Service1, 3); decimal Result = Target.ComputeTotalValue(); // Assert Assert.Equal(1200.00M, Result); } [Fact] public void Can_Clear_Contents() { // Arrange - create some test products var Service1 = new ServiceItem { Id = 1, Title = "P1", Cost = 200.00M }; var Service2 = new ServiceItem { Id = 2, Title = "P2", Cost = 400.00M }; // Arrange - create a new cart var Target = new ShoppingCart(); // Arrange - add some items Target.AddItem(Service1, 1); Target.AddItem(Service2, 1); // Act - reset the cart Target.Clear(); // Assert Assert.Empty(Target.Lines); } } } <file_sep>/HotelService/Models/Base/Room.cs using System; using System.Collections.Generic; #nullable disable namespace HotelService.Models.Base { public class Room { public Room() { RoomContracts = new HashSet<RoomContract>(); } public int Id { get; set; } public int BuildingId { get; set; } public string Number { get; set; } public string Type { get; set; } public int SleepingPlaces { get; set; } public decimal Cost { get; set; } public string ImagePath { get; set; } public Building Building { get; set; } public ICollection<RoomContract> RoomContracts { get; set; } } } <file_sep>/HotelService/Infrastructure/RoleUsersTagHelper.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models.Base; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Razor.TagHelpers; namespace HotelService.Infrastructure { [HtmlTargetElement("td", Attributes = "identity-role")] public class RoleUsersTagHelper : TagHelper { private UserManager<User> m_UserManager; private RoleManager<Role> m_RoleManager; public RoleUsersTagHelper(UserManager<User> usermgr, RoleManager<Role> rolemgr) { m_UserManager = usermgr; m_RoleManager = rolemgr; } [HtmlAttributeName("identity-role")] public string Role { get; set; } public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { int Users = 0; //var Names = new List<string>(); var FindRole = await m_RoleManager.FindByIdAsync(Role); if (FindRole != null) { foreach (var User in m_UserManager.Users) { if (User != null && await m_UserManager.IsInRoleAsync(User, FindRole.Name)) { Users++; //Names.Add(User.UserName); } } } output.Content.SetContent(Users != 0 ? Users.ToString() : "No Users"); } } } <file_sep>/HotelService/Models/Base/Article.cs using System; using System.Collections.Generic; #nullable disable namespace HotelService.Models.Base { public class Article { public int Id { get; set; } public string AuthorId { get; set; } public string Title { get; set; } public string Review { get; set; } public string ImagePath { get; set; } public DateTime WritingDate { get; set; } public User Author { get; set; } } } <file_sep>/HotelService/Areas/Admin/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models; using HotelService.Models.Base; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace HotelService.Areas.Admin.Controllers { [Area("Admin")] [Authorize(Roles = "Admin, Developer")] public class HomeController : Controller { private UserManager<User> m_UserManager; //public IUserValidator<User> UserValidator; //private IPasswordValidator<User> m_PasswordValidator; //private IPasswordHasher<User> m_PasswordHasher; private RoleManager<Role> m_RoleManager; private HotelServiceContext m_Context; public HomeController(UserManager<User> usrMgr, RoleManager<Role> roleMgr, HotelServiceContext context) { m_UserManager = usrMgr; m_RoleManager = roleMgr; m_Context = context; } /// <summary> /// Errors. /// </summary> /// <param name="result"></param> private void AddErrorsFromResult(IdentityResult result) { foreach (var Error in result.Errors) { ModelState.AddModelError("", Error.Description); } } public ViewResult Index() { return View(); } } } <file_sep>/HotelService/Models/Base/Role.cs using Microsoft.AspNetCore.Identity; namespace HotelService.Models.Base { public class Role : IdentityRole { public Role() { } public Role(string name) : base(name) { } } public enum RoleType { Visitor, Client, Admin, ServiceSystem } } <file_sep>/HotelService/Models/Base/Feedback.cs using System; using System.Collections.Generic; #nullable disable namespace HotelService.Models.Base { public partial class Feedback { public string ClientId { get; set; } public int ServiceId { get; set; } public int Rating { get; set; } public string Review { get; set; } public DateTime WritingDate { get; set; } public User Client { get; set; } public Service Service { get; set; } } } <file_sep>/HotelService/Components/CartSummaryViewComponent.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models; using Microsoft.AspNetCore.Mvc; namespace HotelService.Components { public class CartSummaryViewComponent : ViewComponent { private ShoppingCart Cart; public CartSummaryViewComponent(ShoppingCart cartService) { Cart = cartService; } public IViewComponentResult Invoke() { return View(Cart); } } } <file_sep>/HotelService/Models/DeveloperInitializer.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models.Base; using HotelService.Service; using Microsoft.AspNetCore.Identity; namespace HotelService.Models { public class DeveloperInitializer { public static async Task InitializeAsync(UserManager<User> userManager, RoleManager<Role> roleManager) { var Roles = Enum.GetNames(typeof(RoleType)); foreach (var Role in Roles) { if (await roleManager.FindByNameAsync(Role) == null) await roleManager.CreateAsync(new Role(Role)); } if (await userManager.FindByNameAsync(Developer.Name) == null) { if (await roleManager.FindByNameAsync(Developer.Role) == null) { var Role = new Role(Developer.Role); var ResultRole = await roleManager.CreateAsync(Role); } var User = new User { UserName = Developer.Email, FirstName = Developer.FirstName, LastName = Developer.LastName, Passport = Developer.Passport, Email = Developer.Email, }; var Result = await userManager.CreateAsync(User, Developer.Password); if (Result.Succeeded) await userManager.AddToRoleAsync(User, Developer.Role); } } } } <file_sep>/HotelService/Models/Base/Request.cs using System; using System.Collections.Generic; #nullable disable namespace HotelService.Models.Base { public partial class Request { public Request() { RequestStates = new HashSet<RequestState>(); } public int Id { get; set; } public int? OrderId { get; set; } public int ServiceId { get; set; } public string Comment { get; set; } public int Quantity { get; set; } public DateTime DeliveryDate { get; set; } public Order Order { get; set; } public Service Service { get; set; } public ICollection<RequestState> RequestStates { get; set; } } } <file_sep>/HotelService/Areas/Client/Controllers/OrderController.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models; using HotelService.Models.Base; using HotelService.Repositories.Interfaces; using HotelService.Service; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; namespace HotelService.Areas.Client.Controllers { [Area("Client")] [Authorize(Roles = "Developer, Client")] public class OrderController : Controller { private ICatalogManager m_CatalogManager; private IOrderManager m_OrderManager; private ShoppingCart m_Cart; private SignInManager<User> m_SignInManager; private HotelServiceContext m_Context; public OrderController(ICatalogManager repoService, ShoppingCart cartService, IOrderManager orderManagerManager, SignInManager<User> signIn, HotelServiceContext context) { m_CatalogManager = repoService; m_Cart = cartService; m_OrderManager = orderManagerManager; m_SignInManager = signIn; m_Context = context; } public async Task<ViewResult> Checkout() { var User = await m_SignInManager.UserManager.FindByNameAsync(base.User.Identity.Name); var Contracts = m_OrderManager.GetContractsForUser(User.Id).ToList(); ViewBag.SelectContracts = new SelectList(Contracts, "Id", "Room.Number", "Room.Number", "ConclusionDate"); return View(new Order{CostTotal = m_Cart.ComputeTotalValue()}); } [HttpPost] public IActionResult Checkout(Order order) { if (!m_Cart.Lines.Any()) { ModelState.AddModelError("", "Простите, вы не добавили ни одной услуги!"); } if (!ModelState.IsValid) return View(order); order.Requests = m_Cart.Lines.ToArray(); m_OrderManager.SaveOrder(order); m_Cart.Clear(); return RedirectToAction(nameof(Completed)); } public ViewResult Completed() { return View(); } public async Task<IActionResult> Index() { var Services = m_Context.Services.AsNoTracking().Include(x => x.ServiceCategory).Where(x => x.ServiceCategoryId == 1); return View(await Services.ToListAsync()); } [NoDirectAccess] public async Task<IActionResult> Details(int? id) { if (id == null) return NotFound(); var Service = await m_Context.Services.AsNoTracking() .Include(x => x.ServiceCategory) .FirstOrDefaultAsync(x => x.Id == id); if (Service != null) return View(Service); return NotFound(); } [HttpGet] [NoDirectAccess] [ActionName("Delete")] public async Task<IActionResult> ConfirmDelete(int? id) { if (id == null) return NotFound(); var Service = await m_Context.Services.Include(s => s.ServiceCategory).FirstOrDefaultAsync(p => p.Id == id); if (Service != null) return View(Service); return NotFound(); } [HttpPost] public async Task<IActionResult> Delete(int? id) { if (id == null) return NotFound(); var Service = await m_Context.Services.FirstOrDefaultAsync(p => p.Id == id); if (Service == null) return NotFound(); m_Context.Services.Remove(Service); await m_Context.SaveChangesAsync(); return RedirectToAction("Index"); } } } <file_sep>/HotelService/Models/ViewModels/Admin/CatalogModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models.Base; namespace HotelService.Models.ViewModels.Admin { public class CatalogModel { public IEnumerable< Base.Service> Services { get; set; } public IEnumerable<ServiceCategory> Categories { get; set; } } } <file_sep>/HotelService/Repositories/OrderManager.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models; using HotelService.Models.Base; using HotelService.Repositories.Interfaces; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; namespace HotelService.Repositories { public class OrderManager : IOrderManager { private bool m_Disposed = false; HotelServiceContext m_Context; private RoleManager<Role> m_RoleManager; private UserManager<User> m_UserManager; public OrderManager(HotelServiceContext context, RoleManager<Role> roleManager, UserManager<User> userManager) { m_Context = context; m_RoleManager = roleManager; m_UserManager = userManager; } public IQueryable<ServiceCategory> Categories => m_Context.ServiceCategories.AsQueryable(); public IQueryable<Models.Base.Service> Services => m_Context.Services.AsQueryable(); public IQueryable<Order> Orders => m_Context.Orders.Include(i => i.Requests).ThenInclude(l => l.Service); public IQueryable<RoomContract> Contracts => m_Context.RoomContracts.AsQueryable(); public IQueryable<RoomContract> GetContractsForUser(string userId) { var RoomContracts = Contracts.AsNoTracking().Where(x => x.Client.Id == userId).Include(x => x.Room); return RoomContracts; } public void SaveOrder(Order order) { m_Context.AttachRange(order.Requests.Select(l => l.Service)); if (order.Id == 0) { m_Context.Orders.Add(order); } m_Context.SaveChanges(); } public async Task Save() { await m_Context.SaveChangesAsync(); } public virtual void Dispose(bool disposing) { if (!this.m_Disposed) { if (disposing) { m_Context.Dispose(); } } this.m_Disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } } <file_sep>/HotelService/Models/Base/RoomContract.cs using System; using System.Collections.Generic; #nullable disable namespace HotelService.Models.Base { public class RoomContract { public RoomContract() { Orders = new HashSet<Order>(); } public int Id { get; set; } public string ClientId { get; set; } public int RoomId { get; set; } public DateTime ConclusionDate { get; set; } public DateTime CheckInDate { get; set; } public DateTime? CheckOutDate { get; set; } public User Client { get; set; } public Room Room { get; set; } public ICollection<Order> Orders { get; set; } } } <file_sep>/HotelService/Models/Base/State.cs using System; using System.Collections.Generic; #nullable disable namespace HotelService.Models.Base { public class State { public State() { RequestStates = new HashSet<RequestState>(); } public int Id { get; set; } public string Value { get; set; } public ICollection<RequestState> RequestStates { get; set; } } } <file_sep>/HotelService/Models/Base/RequestState.cs using System; using System.Collections.Generic; #nullable disable namespace HotelService.Models.Base { public class RequestState { public int RequestId { get; set; } public int StateId { get; set; } public DateTime ChangeDate { get; set; } public string Comment { get; set; } public Request Request { get; set; } public State State { get; set; } } } <file_sep>/HotelService/Models/ViewModels/Client/CatalogModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models.Base; namespace HotelService.Models.ViewModels.Client { public class CatalogModel { public IQueryable<Base.Service> Services { get; set; } public IQueryable<ServiceCategory> Categories { get; set; } } } <file_sep>/HotelService/Areas/Client/Controllers/CartController.cs using System.Linq; using HotelService.Infrastructure; using HotelService.Models; using HotelService.Models.ViewModels.Client; using HotelService.Repositories.Interfaces; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace HotelService.Areas.Client.Controllers { [Area("Client")] [Authorize(Roles = "Developer, Client")] public class CartController : Controller { private ICatalogManager m_Catalog; private ShoppingCart m_Cart; public CartController(ICatalogManager catalog, ShoppingCart cart) { m_Catalog = catalog; m_Cart = cart; } public ViewResult Index(string returnUrl) { return View(new CartModel { Cart = m_Cart, ReturnUrl = returnUrl }); } public RedirectToActionResult AddToCart(int id, string returnUrl) { var Product = m_Catalog.Services .FirstOrDefault(p => p.Id == id); if (Product != null) { m_Cart.AddItem(Product, 1); } return RedirectToAction("Index", new {returnUrl}); } public RedirectToActionResult RemoveFromCart(int id, string returnUrl) { var Product = m_Catalog.Services .FirstOrDefault(p => p.Id == id); if (Product != null) { m_Cart.RemoveLine(Product); } return RedirectToAction("Index", new {returnUrl}); } } }<file_sep>/HotelService/Models/SessionCart.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; using HotelService.Infrastructure; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace HotelService.Models { public class SessionCart : ShoppingCart { public static ShoppingCart GetCart(IServiceProvider services) { var Session = services.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session; var Cart = Session?.GetJson<SessionCart>("Cart") ?? new SessionCart(); Cart.Session = Session; return Cart; } [JsonIgnore] public ISession Session { get; set; } public override void AddItem(Base.Service service, int quantity) { base.AddItem(service, quantity); Session.SetJson("Cart", this); } public override void RemoveLine(Base.Service service) { base.RemoveLine(service); Session.SetJson("Cart", this); } public override void Clear() { base.Clear(); Session.Remove("Cart"); } } } <file_sep>/HotelService/Models/HotelServiceContext.cs using HotelService.Models.Base; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; #nullable disable namespace HotelService.Models { public sealed class HotelServiceContext : IdentityDbContext<User, Role, string> { public HotelServiceContext() { } public HotelServiceContext(DbContextOptions<HotelServiceContext> options) : base(options) { Database.EnsureCreated(); } public DbSet<Article> Articles { get; set; } public DbSet<Building> Buildings { get; set; } public DbSet<CostChange> CostChanges { get; set; } public DbSet<Favorite> Favorites { get; set; } public DbSet<Feedback> Feedbacks { get; set; } public DbSet<Order> Orders { get; set; } public DbSet<Request> Requests { get; set; } public DbSet<RequestState> RequestStates { get; set; } public DbSet<Room> Rooms { get; set; } public DbSet<RoomContract> RoomContracts { get; set; } public DbSet<Base.Service> Services { get; set; } public DbSet<ServiceCategory> ServiceCategories { get; set; } public DbSet<State> States { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263. optionsBuilder.UseSqlServer("Server=(local);Database=HotelService;Trusted_Connection=True;"); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.HasAnnotation("Relational:Collation", "Cyrillic_General_CI_AS"); modelBuilder.Entity<Article>(entity => { entity.Property(e => e.AuthorId) .IsRequired() .HasMaxLength(450); entity.Property(e => e.ImagePath).HasMaxLength(1024); entity.Property(e => e.Review) .IsRequired() .HasMaxLength(512); entity.Property(e => e.Title) .IsRequired() .HasMaxLength(256); entity.Property(e => e.WritingDate).HasDefaultValueSql("(getdate())"); entity.HasOne(d => d.Author) .WithMany(p => p.Articles) .HasForeignKey(d => d.AuthorId) .HasConstraintName("FK__Articles__Author__5AEE82B9"); }); modelBuilder.Entity<Building>(entity => { entity.Property(e => e.Address) .IsRequired() .HasMaxLength(256); entity.Property(e => e.AdminId).HasMaxLength(450); entity.Property(e => e.Description).HasMaxLength(256); entity.Property(e => e.ImagePath).HasMaxLength(1024); entity.Property(e => e.Name) .IsRequired() .HasMaxLength(256); entity.HasOne(d => d.Admin) .WithMany(p => p.Buildings) .HasForeignKey(d => d.AdminId) .OnDelete(DeleteBehavior.SetNull) .HasConstraintName("FK__Buildings__Admin__2E1BDC42"); }); modelBuilder.Entity<CostChange>(entity => { entity.Property(e => e.ChangeDate).HasDefaultValueSql("(getdate())"); entity.Property(e => e.NewCostValue).HasColumnType("decimal(8, 2)"); entity.HasOne(d => d.Service) .WithMany(p => p.CostChanges) .HasForeignKey(d => d.ServiceId) .HasConstraintName("FK__CostChang__Servi__5EBF139D"); }); modelBuilder.Entity<Favorite>(entity => { entity.HasKey(e => new { e.ClientId, e.ServiceId }) .HasName("PK__Favorite__5A2FA124A8632B4D"); entity.Property(e => e.ShowState) .IsRequired() .HasDefaultValueSql("((1))"); entity.HasOne(d => d.Client) .WithMany(p => p.Favorites) .HasForeignKey(d => d.ClientId) .HasConstraintName("FK__Favorites__Clien__628FA481"); entity.HasOne(d => d.Service) .WithMany(p => p.Favorites) .HasForeignKey(d => d.ServiceId) .HasConstraintName("FK__Favorites__Servi__6383C8BA"); }); modelBuilder.Entity<Feedback>(entity => { entity.HasKey(e => new { e.ClientId, e.ServiceId }) .HasName("PK__Feedback__5A2FA124AF004554"); entity.ToTable("Feedback"); entity.Property(e => e.Rating).HasDefaultValueSql("((5))"); entity.Property(e => e.Review).HasMaxLength(512); entity.Property(e => e.WritingDate).HasDefaultValueSql("(getdate())"); entity.HasOne(d => d.Client) .WithMany(p => p.Feedbacks) .HasForeignKey(d => d.ClientId) .HasConstraintName("FK__Feedback__Client__4F7CD00D"); entity.HasOne(d => d.Service) .WithMany(p => p.Feedbacks) .HasForeignKey(d => d.ServiceId) .HasConstraintName("FK__Feedback__Servic__5070F446"); }); modelBuilder.Entity<Order>(entity => { entity.Property(e => e.CostTotal).HasColumnType("decimal(10, 2)"); entity.Property(e => e.CreditCardNumber) .IsRequired() .HasMaxLength(256); entity.Property(e => e.Name) .IsRequired() .HasMaxLength(256); entity.Property(e => e.PaymentDate).HasDefaultValueSql("(getdate())"); entity.Property(e => e.PaymentDetails).HasMaxLength(256); entity.Property(e => e.PhoneNumber) .IsRequired() .HasMaxLength(256); entity.HasOne(d => d.RoomContract) .WithMany(p => p.Orders) .HasForeignKey(d => d.RoomContractId) .HasConstraintName("FK__Orders__RoomCont__68487DD7"); }); modelBuilder.Entity<Request>(entity => { entity.Property(e => e.Comment).HasMaxLength(256); entity.Property(e => e.DeliveryDate).HasDefaultValueSql("(getdate())"); entity.Property(e => e.Quantity).HasDefaultValueSql("((1))"); entity.HasOne(d => d.Order) .WithMany(p => p.Requests) .HasForeignKey(d => d.OrderId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK__Requests__OrderI__6E01572D"); entity.HasOne(d => d.Service) .WithMany(p => p.Requests) .HasForeignKey(d => d.ServiceId) .HasConstraintName("FK__Requests__Servic__6EF57B66"); }); modelBuilder.Entity<RequestState>(entity => { entity.HasKey(e => new { e.RequestId, e.StateId }) .HasName("PK__RequestS__8F93F2C977B5AE5B"); entity.Property(e => e.ChangeDate).HasDefaultValueSql("(getdate())"); entity.Property(e => e.Comment).HasMaxLength(256); entity.HasOne(d => d.Request) .WithMany(p => p.RequestStates) .HasForeignKey(d => d.RequestId) .HasConstraintName("FK__RequestSt__Reque__75A278F5"); entity.HasOne(d => d.State) .WithMany(p => p.RequestStates) .HasForeignKey(d => d.StateId) .HasConstraintName("FK__RequestSt__State__76969D2E"); }); modelBuilder.Entity<Room>(entity => { entity.Property(e => e.Cost) .HasColumnType("decimal(8, 2)") .HasDefaultValueSql("((5000.00))"); entity.Property(e => e.ImagePath).HasMaxLength(1024); entity.Property(e => e.Number) .IsRequired() .HasMaxLength(256); entity.Property(e => e.SleepingPlaces).HasDefaultValueSql("((1))"); entity.Property(e => e.Type) .IsRequired() .HasMaxLength(256) .HasDefaultValueSql("('STD')"); entity.HasOne(d => d.Building) .WithMany(p => p.Rooms) .HasForeignKey(d => d.BuildingId) .HasConstraintName("FK__Rooms__BuildingI__35BCFE0A"); }); modelBuilder.Entity<RoomContract>(entity => { entity.Property(e => e.CheckInDate).HasDefaultValueSql("(getdate())"); entity.Property(e => e.ClientId) .IsRequired() .HasMaxLength(450); entity.Property(e => e.ConclusionDate).HasDefaultValueSql("(getdate())"); entity.HasOne(d => d.Client) .WithMany(p => p.RoomContracts) .HasForeignKey(d => d.ClientId) .HasConstraintName("FK__RoomContr__Clien__5535A963"); entity.HasOne(d => d.Room) .WithMany(p => p.RoomContracts) .HasForeignKey(d => d.RoomId) .HasConstraintName("FK__RoomContr__RoomI__5629CD9C"); }); modelBuilder.Entity<Base.Service>(entity => { entity.Property(e => e.AddedDate) .HasColumnType("date") .HasDefaultValueSql("(getdate())"); entity.Property(e => e.AvailableState) .IsRequired() .HasDefaultValueSql("((1))"); entity.Property(e => e.Cost) .HasColumnType("decimal(8, 2)") .HasDefaultValueSql("((1000.00))"); entity.Property(e => e.Description).HasMaxLength(512); entity.Property(e => e.ImagePath).HasMaxLength(1024); entity.Property(e => e.RepeatState) .IsRequired() .HasDefaultValueSql("((1))"); entity.Property(e => e.Subtitle) .IsRequired() .HasMaxLength(256); entity.Property(e => e.Title) .IsRequired() .HasMaxLength(256); entity.HasOne(d => d.ServiceCategory) .WithMany(p => p.Services) .HasForeignKey(d => d.ServiceCategoryId) .HasConstraintName("FK__Services__Servic__48CFD27E"); }); modelBuilder.Entity<ServiceCategory>(entity => { entity.HasIndex(e => e.Title, "UQ__ServiceC__2CB664DC51D9118A") .IsUnique(); entity.Property(e => e.AvailableState) .IsRequired() .HasDefaultValueSql("((1))"); entity.Property(e => e.Description).HasMaxLength(512); entity.Property(e => e.ImagePath).HasMaxLength(1024); entity.Property(e => e.Subtitle).HasMaxLength(256); entity.Property(e => e.Title) .IsRequired() .HasMaxLength(256); entity.HasOne(d => d.SubCategory) .WithMany(p => p.InverseSubCategory) .HasForeignKey(d => d.SubCategoryId) .HasConstraintName("FK__ServiceCa__SubCa__3E52440B"); }); modelBuilder.Entity<State>(entity => { entity.HasIndex(e => e.Value, "UQ__States__07D9BBC24E50A50A") .IsUnique(); entity.Property(e => e.Value) .IsRequired() .HasMaxLength(256); }); modelBuilder.Entity<User>(entity => { entity.HasIndex(e => e.Passport, "UQ__Users__208C1D4D741BCFFE") .IsUnique(); entity.Property(e => e.FirstName) .IsRequired() .HasMaxLength(256); entity.Property(e => e.ForeignerStatus).HasDefaultValueSql("((0))"); entity.Property(e => e.Gender).HasMaxLength(16); entity.Property(e => e.ImagePath).HasMaxLength(1024); entity.Property(e => e.LastName) .IsRequired() .HasMaxLength(256); entity.Property(e => e.Passport) .IsRequired() .HasMaxLength(32); entity.Property(e => e.Patronymic).HasMaxLength(256); entity.Property(e => e.RegistrationDate).HasDefaultValueSql("(getdate())"); }); modelBuilder.Entity<User>().ToTable(nameof(User) + 's'); modelBuilder.Entity<IdentityUserLogin<string>>().ToTable("UserLogins"); modelBuilder.Entity<IdentityUserToken<string>>().ToTable("UserTokens"); modelBuilder.Entity<IdentityUserClaim<string>>().ToTable("UserClaims"); modelBuilder.Entity<IdentityUserRole<string>>().ToTable("UserRoles"); modelBuilder.Entity<IdentityRoleClaim<string>>().ToTable("RoleClaims"); modelBuilder.Entity<Role>().ToTable(nameof(Role) + 's'); } } } <file_sep>/HotelService/Repositories/Interfaces/ICatalogManager.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models.Base; namespace HotelService.Repositories.Interfaces { public interface ICatalogManager : IDisposable { IQueryable<ServiceCategory> Categories { get; } IQueryable<Models.Base.Service> Services { get; } Task Save(); } } <file_sep>/HotelService/Areas/Client/Controllers/HomeController.cs using HotelService.Models; using HotelService.Models.Base; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; namespace HotelService.Areas.Client.Controllers { [Area("Client")] [Authorize(Roles = "Developer, Client")] public class HomeController : Controller { private UserManager<User> m_UserManager; //public IUserValidator<User> UserValidator; //private IPasswordValidator<User> m_PasswordValidator; //private IPasswordHasher<User> m_PasswordHasher; private RoleManager<Role> m_RoleManager; private HotelServiceContext m_Context; public HomeController(UserManager<User> usrMgr, RoleManager<Role> roleMgr, HotelServiceContext context) { m_UserManager = usrMgr; m_RoleManager = roleMgr; m_Context = context; } public ViewResult Index() => View(); private void AddErrorsFromResult(IdentityResult result) { foreach (var Error in result.Errors) { ModelState.AddModelError("", Error.Description); } } } } <file_sep>/HotelService/Models/Base/Building.cs using System; using System.Collections.Generic; #nullable disable namespace HotelService.Models.Base { public class Building { public Building() { Rooms = new HashSet<Room>(); } public int Id { get; set; } public string AdminId { get; set; } public string Name { get; set; } public string Address { get; set; } public string Description { get; set; } public string ImagePath { get; set; } public User Admin { get; set; } public ICollection<Room> Rooms { get; set; } } } <file_sep>/README.md # HotelService Information service system of the Hotel on ASP.NET Core with MSSQL Server. <file_sep>/HotelService/Areas/Admin/Controllers/RoleController.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using HotelService.Models; using HotelService.Models.Base; using HotelService.Models.ViewModels.Admin; using HotelService.Service; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; namespace HotelService.Areas.Admin.Controllers { [Area("Admin")] [Authorize(Roles = "Admin, Developer")] public class RoleController : Controller { private readonly HotelServiceContext m_Context; private RoleManager<Role> m_RoleManager; private UserManager<User> m_UserManager; public RoleController(UserManager<User> usrMgr, RoleManager<Role> roleMgr, HotelServiceContext context) { m_UserManager = usrMgr; m_RoleManager = roleMgr; m_Context = context; } public ViewResult Index() => View(m_RoleManager.Roles); [HttpGet] [NoDirectAccess] [ActionName("Delete")] public async Task<IActionResult> ConfirmDelete(string id) { if (id == null) return NotFound(); var Role = await m_RoleManager.FindByIdAsync(id); if (Role != null) return View(Role); return NotFound(); } [HttpPost] public async Task<IActionResult> Delete(string id) { Role role = await m_RoleManager.FindByIdAsync(id); if (role != null) { IdentityResult result = await m_RoleManager.DeleteAsync(role); if (result.Succeeded) { return RedirectToAction("Index"); } else { AddErrorsFromResult(result); } } else { ModelState.AddModelError("", "No role found"); } return View("Index", m_RoleManager.Roles); } public async Task<IActionResult> Edit(string id) { Role role = await m_RoleManager.FindByIdAsync(id); List<User> members = new List<User>(); List<User> nonMembers = new List<User>(); foreach (User user in m_UserManager.Users) { var list = await m_UserManager.IsInRoleAsync(user, role.Name) ? members : nonMembers; list.Add(user); } return View(new RoleEditModel { Role = role, Members = members, NonMembers = nonMembers }); } [HttpPost] public async Task<IActionResult> Edit(RoleModificationModel model) { IdentityResult result; if (ModelState.IsValid) { foreach (string userId in model.IdsToAdd ?? new string[] { }) { User user = await m_UserManager.FindByIdAsync(userId); if (user != null) { result = await m_UserManager.AddToRoleAsync(user, model.RoleName); if (!result.Succeeded) { AddErrorsFromResult(result); } } } foreach (string userId in model.IdsToDelete ?? new string[] { }) { User user = await m_UserManager.FindByIdAsync(userId); if (user != null) { result = await m_UserManager.RemoveFromRoleAsync(user, model.RoleName); if (!result.Succeeded) { AddErrorsFromResult(result); } } } } if (ModelState.IsValid) { return RedirectToAction(nameof(Index)); } else { return await Edit(model.RoleId); } } private void AddErrorsFromResult(IdentityResult result) { foreach (IdentityError error in result.Errors) { ModelState.AddModelError("", error.Description); } } } } <file_sep>/HotelService/Areas/Admin/Controllers/UserController.cs using HotelService.Models; using HotelService.Models.Base; using HotelService.Service; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using HotelService.Models.ViewModels.Admin; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; namespace HotelService.Areas.Admin.Controllers { [Area("Admin")] [Authorize(Roles = "Admin, Developer")] public class UserController : Controller { private readonly HotelServiceContext m_Context; private RoleManager<Role> m_RoleManager; private UserManager<User> m_UserManager; private readonly IWebHostEnvironment m_HostingEnvironment; public UserController(UserManager<User> usrMgr, RoleManager<Role> roleMgr, HotelServiceContext context, IWebHostEnvironment hostingEnvironment) { m_UserManager = usrMgr; m_RoleManager = roleMgr; m_Context = context; m_HostingEnvironment = hostingEnvironment; } public async Task<IActionResult> Index() { return View(await m_UserManager.Users.ToListAsync()); } [NoDirectAccess] public async Task<IActionResult> CreateEdit(string id) { // TODO: Добавить пол ViewBag.Genders = new SelectList(new List<string> { "Муж", "Жен" }); if (id == null) { return View(new CreateModel()); } var User = await m_UserManager.FindByIdAsync(id); if (User != null) return View(new CreateModel { Id = User.Id, UserName = User.UserName, FirstName = User.FirstName, LastName = User.LastName, Patronymic = User.Patronymic, BirthDate = User.BirthDate, Passport = User.Passport, Gender = User.Gender, Email = User.Email, PhoneNumber = User.PhoneNumber, ImagePath = User.ImagePath }); return NotFound(); } public async Task<IdentityResult> PasswordValidator(User user,string password) { var PasswordValidator = HttpContext.RequestServices.GetService( typeof(IPasswordValidator<User>)) as IPasswordValidator<User>; var ValidateResult = await PasswordValidator.ValidateAsync(m_UserManager, user, password); return ValidateResult; } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> CreateEdit(CreateModel input, string id, IFormFile imagePath) { // TODO: Проверить сохранение изображений, проверка на смену пароля if (!ModelState.IsValid) return Json(new { isValid = false, html = HelperView.RenderRazorViewToString(this, "CreateEdit", input) }); if (imagePath != null) { await using var Stream = new FileStream(Path.Combine(m_HostingEnvironment.WebRootPath, "img/local/users", imagePath.FileName), FileMode.Create); await imagePath.CopyToAsync(Stream); } var PasswordHasher = HttpContext.RequestServices.GetService(typeof(IPasswordHasher<User>)) as IPasswordHasher<User>; //Insert if (id == null) { var NewUser = new User { FirstName = input.FirstName, LastName = input.LastName, Patronymic = input.Patronymic, BirthDate = input.BirthDate, Passport = input.Passport, Gender = input.Gender, Email = input.Email, UserName = input.UserName, ImagePath = imagePath?.FileName }; var Result = await m_UserManager.CreateAsync(NewUser, input.Password); if (Result.Succeeded) { return Json(new { isValid = true, html = HelperView.RenderRazorViewToString(this, "_ViewTable", m_UserManager.Users) }); } AddErrorsFromResult(Result); return Json(new {isValid = false, html = HelperView.RenderRazorViewToString(this, "CreateEdit", input)}); } // TODO: Нужно ли обновлять пароль - всегда обновляет пароль //Update var UpdateUser = await m_UserManager.FindByIdAsync(id); var ValidateResult = await PasswordValidator(UpdateUser, input.Password); if (ValidateResult.Succeeded) { UpdateUser.ImagePath = input.ImagePath; UpdateUser.PasswordHash = PasswordHasher.HashPassword(UpdateUser, input.Password); await m_UserManager.UpdateAsync(UpdateUser); return Json(new { isValid = true, html = HelperView.RenderRazorViewToString(this, "_ViewTable", m_UserManager.Users) }); } AddErrorsFromResult(ValidateResult); return Json(new { isValid = false, html = HelperView.RenderRazorViewToString(this, "CreateEdit", input) }); } [NoDirectAccess] public async Task<IActionResult> Details(string id) { var User = await m_UserManager.FindByIdAsync(id); if (User != null) return View(User); return NotFound(); } [HttpGet] [NoDirectAccess] [ActionName("Delete")] public async Task<IActionResult> ConfirmDelete(string id) { var UserNow = await m_UserManager.FindByIdAsync(id); if (UserNow != null) return View(UserNow); return NotFound(); } [HttpPost] public async Task<IActionResult> Delete(string id) { var User = await m_UserManager.FindByIdAsync(id); if (User != null) { var Result = await m_UserManager.DeleteAsync(User); if (Result.Succeeded) { return RedirectToAction("Index"); } AddErrorsFromResult(Result); } else { ModelState.AddModelError("", "User Not Found"); } return View("Index", m_UserManager.Users); } private void AddErrorsFromResult(IdentityResult result) { foreach (var Error in result.Errors) { ModelState.AddModelError("", Error.Description); } } } }<file_sep>/HotelService/Repositories/CatalogManager.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Models; using HotelService.Models.Base; using HotelService.Repositories.Interfaces; using Microsoft.EntityFrameworkCore; namespace HotelService.Repositories { public class CatalogManager : ICatalogManager { private bool m_Disposed = false; HotelServiceContext m_Context; public CatalogManager(HotelServiceContext context) { m_Context = context; } public IQueryable<ServiceCategory> Categories => m_Context.ServiceCategories.AsQueryable(); public IQueryable<Models.Base.Service> Services => m_Context.Services.AsQueryable(); public async Task Save() { await m_Context.SaveChangesAsync(); } public virtual void Dispose(bool disposing) { if (!this.m_Disposed) { if (disposing) { m_Context.Dispose(); } } this.m_Disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } } <file_sep>/HotelService/Models/Base/User.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Identity; #nullable disable namespace HotelService.Models.Base { public class User : IdentityUser { public User() { Articles = new HashSet<Article>(); Buildings = new HashSet<Building>(); Favorites = new HashSet<Favorite>(); Feedbacks = new HashSet<Feedback>(); RoomContracts = new HashSet<RoomContract>(); } [Required(ErrorMessage = "Не указано {0}")] [RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$", ErrorMessage = "Недопустимые символы")] [StringLength(30, MinimumLength = 3, ErrorMessage = "{0} должно содержать хотя бы {2} и максимум {1} символов.")] [Display(Name = "Имя")] public string FirstName { get; set; } [Required(ErrorMessage = "Не указана {0}")] [RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$", ErrorMessage = "Недопустимые символы")] [StringLength(50, MinimumLength = 3, ErrorMessage = "{0} должна содержать хотя бы {2} и максимум {1} символов.")] [Display(Name = "Фамилия")] public string LastName { get; set; } [RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$", ErrorMessage = "Недопустимые символы")] [StringLength(50, MinimumLength = 3, ErrorMessage = "{0} должно содержать хотя бы {2} и максимум {1} символов.")] [Display(Name = "Отчество")] public string Patronymic { get; set; } [Display(Name = "Пол")] public string Gender { get; set; } [Required(ErrorMessage = "Не указан {0}")] [RegularExpression(@"^[0-9""'\s-]*$", ErrorMessage = "Недопустимые символы")] [StringLength(20, MinimumLength = 10, ErrorMessage = "{0} должен содержать хотя бы {2} и максимум {1} символов.")] [Display(Name = "Паспорт")] public string Passport { get; set; } [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{dd-MM-yyyy}", ApplyFormatInEditMode = true)] [Display(Name = "Дата рождения")] public DateTime? BirthDate { get; set; } [Display(Name = "Является иностранцем?")] public bool? ForeignerStatus { get; set; } [Display(Name = "Дата регистрации")] public DateTime RegistrationDate { get; set; } [Display(Name = "Изображение профиля")] [DataType(DataType.ImageUrl)] public string ImagePath { get; set; } public ICollection<Article> Articles { get; set; } public ICollection<Building> Buildings { get; set; } public ICollection<Favorite> Favorites { get; set; } public ICollection<Feedback> Feedbacks { get; set; } public ICollection<RoomContract> RoomContracts { get; set; } } } <file_sep>/HotelService/Models/Base/Favorite.cs using System; using System.Collections.Generic; #nullable disable namespace HotelService.Models.Base { public partial class Favorite { public string ClientId { get; set; } public int ServiceId { get; set; } public bool? ShowState { get; set; } public User Client { get; set; } public Service Service { get; set; } } } <file_sep>/HotelService/Models/Base/CostChange.cs using System; using System.Collections.Generic; #nullable disable namespace HotelService.Models.Base { public class CostChange { public int Id { get; set; } public int ServiceId { get; set; } public DateTime ChangeDate { get; set; } public decimal NewCostValue { get; set; } public Service Service { get; set; } } } <file_sep>/HotelService/Models/ViewModels/Admin/UserViewModels.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using HotelService.Models.Base; namespace HotelService.Models.ViewModels.Admin { public class CreateModel { //public User User { get; set; } public string Id { get; set; } [RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$", ErrorMessage = "Недопустимые символы")] [Display(Name = "Имя пользователя")] public string UserName { get; set; } [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{dd-MM-yyyy}", ApplyFormatInEditMode = true)] [Display(Name = "Дата рождения")] public DateTime? BirthDate { get; set; } [Required(ErrorMessage = "Не указано {0}")] //[RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$", ErrorMessage = "Недопустимые символы")] [StringLength(30, MinimumLength = 3, ErrorMessage = "{0} должно содержать хотя бы {2} и максимум {1} символов.")] [Display(Name = "Имя")] public string FirstName { get; set; } [Required(ErrorMessage = "Не указана {0}")] //[RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$", ErrorMessage = "Недопустимые символы")] [StringLength(50, MinimumLength = 3, ErrorMessage = "{0} должна содержать хотя бы {2} и максимум {1} символов.")] [Display(Name = "Фамилия")] public string LastName { get; set; } [RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$", ErrorMessage = "Недопустимые символы")] [StringLength(50, MinimumLength = 3, ErrorMessage = "{0} должно содержать хотя бы {2} и максимум {1} символов.")] [Display(Name = "Отчество")] public string Patronymic { get; set; } [Display(Name = "Пол")] public string Gender { get; set; } [Required(ErrorMessage = "Не указан {0}")] [RegularExpression(@"^[0-9""'\s-]*$", ErrorMessage = "Недопустимые символы")] [StringLength(20, MinimumLength = 10, ErrorMessage = "{0} должен содержать хотя бы {2} и максимум {1} символов.")] [Display(Name = "Паспорт")] public string Passport { get; set; } [RegularExpression(@"^[0-9""'\s-]*$", ErrorMessage = "Недопустимые символы")] [StringLength(20, MinimumLength = 6, ErrorMessage = "{0} должен содержать хотя бы {2} и максимум {1} символов.")] [Display(Name = "Телефон")] public string PhoneNumber { get; set; } [Required] [EmailAddress] public string Email { get; set; } public IEnumerable<string> Roles { get; set; } [Required] [StringLength(100, ErrorMessage = "{0} должен содержать хотя бы {2} и максимум {1} символов.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Пароль")] public string Password { get; set; } [Display(Name = "Изображение профиля")] [DataType(DataType.ImageUrl)] public string ImagePath { get; set; } [DataType(DataType.Password)] [Display(Name = "Подтвердите пароль")] [Compare("Password", ErrorMessage = "Пароли не совпадают.")] public string ConfirmPassword { get; set; } } public class RoleEditModel { public Role Role { get; set; } public IEnumerable<User> Members { get; set; } public IEnumerable<User> NonMembers { get; set; } } public class RoleModificationModel { [Required] public string RoleName { get; set; } public string RoleId { get; set; } public string[] IdsToAdd { get; set; } public string[] IdsToDelete { get; set; } } }<file_sep>/HotelService/Areas/Admin/Controllers/CatalogController.cs using System.IO; using System.Linq; using System.Threading.Tasks; using HotelService.Models; using HotelService.Models.Base; using HotelService.Models.ViewModels.Admin; using HotelService.Service; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; namespace HotelService.Areas.Admin.Controllers { [Area("Admin")] [Authorize(Roles = "Admin, Developer")] public class CatalogController : Controller { private const string PathImg = "img/local/services"; private HotelServiceContext m_Context; private readonly IWebHostEnvironment m_HostingEnvironment; private UserManager<User> m_UserManager; public CatalogController(UserManager<User> usrMgr, HotelServiceContext context, IWebHostEnvironment hostingEnvironment) { m_Context = context; m_UserManager = usrMgr; m_HostingEnvironment = hostingEnvironment; } public async Task<IActionResult> Index() { var Services = m_Context.Services.AsNoTracking().Include(x => x.ServiceCategory); var Categories = m_Context.ServiceCategories.AsNoTracking().Include(x => x.SubCategory); var Catalog = new CatalogModel { Services = await Services.ToListAsync(), Categories = await Categories.ToListAsync() }; //return View(await Categories.ToListAsync()); return View(Catalog); } [NoDirectAccess] public async Task<IActionResult> CreateEditCategory(int? id) { // Создание новой категории if (id is null or 0) { ViewBag.SelectCategories = new SelectList(m_Context.ServiceCategories.ToList(), "Id", "Title"); return View(new ServiceCategory()); } // Поиск заданной категории var Category = await m_Context.ServiceCategories.Include(x => x.SubCategory) .FirstOrDefaultAsync(p => p.Id == id); // Отправка в представление тех опций, что еще не выбраны ViewBag.SelectCategories = new SelectList( m_Context.ServiceCategories.AsNoTracking().Where(x => x.Id != Category.Id).ToList(), "Id", "Title"); if (Category != null) return View(Category); return NotFound(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> CreateEditCategory(ServiceCategory category, int? id, IFormFile imagePath) { if (ModelState.IsValid) { if (imagePath != null) { category.ImagePath = Path.Combine(PathImg, imagePath.FileName); await using var Stream = new FileStream(Path.Combine(m_HostingEnvironment.WebRootPath, PathImg, imagePath.FileName), FileMode.Create); await imagePath.CopyToAsync(Stream); } //Insert if (id == 0) { m_Context.ServiceCategories.Add(category); await m_Context.SaveChangesAsync(); } //Update else { m_Context.ServiceCategories.Update(category); await m_Context.SaveChangesAsync(); } //return RedirectToAction("Index"); return Json(new { isValid = true, html = HelperView.RenderRazorViewToString(this, "_ViewCategories", m_Context.ServiceCategories.ToList()) }); } ViewBag.SelectCategories = new SelectList(m_Context.ServiceCategories.AsNoTracking().ToList(), "Id", "Title"); // TODO: Добавить сообщение об ошибках - повторении Index return Json(new { isValid = false, html = HelperView.RenderRazorViewToString(this, "CreateEditCategory", category) }); } [NoDirectAccess] public async Task<IActionResult> DetailsCategory(int? id) { if (id == null) return NotFound(); var Category = await m_Context.ServiceCategories.AsNoTracking() .Include(x => x.SubCategory) .FirstOrDefaultAsync(x => x.Id == id); if (Category != null) return View(Category); return NotFound(); } [HttpGet] [NoDirectAccess] [ActionName("DeleteCategory")] public async Task<IActionResult> ConfirmDeleteCategory(int? id) { if (id == null) return NotFound(); var Categories = await m_Context.ServiceCategories.AsNoTracking().Include(s => s.SubCategory).FirstOrDefaultAsync(p => p.Id == id); if (Categories != null) return View(Categories); return NotFound(); } [HttpPost] public async Task<IActionResult> DeleteCategory(int? id) { if (id == null) return NotFound(); var Categories = await m_Context.ServiceCategories.FirstOrDefaultAsync(p => p.Id == id); if (Categories == null) return NotFound(); m_Context.ServiceCategories.Remove(Categories); await m_Context.SaveChangesAsync(); return RedirectToAction("Index"); } [NoDirectAccess] public async Task<IActionResult> CreateEditService(int? id) { if (id is null or 0) { ViewBag.SelectCategories = new SelectList(m_Context.ServiceCategories.ToList(), "Id", "Title"); return View(new Models.Base.Service()); } var Service = await m_Context.Services.Include(x => x.ServiceCategory) .FirstOrDefaultAsync(p => p.Id == id); ViewBag.SelectCategories = new SelectList( m_Context.ServiceCategories.Where(x => x.Id != Service.ServiceCategoryId).ToList(), "Id", "Title"); if (Service != null) return View(Service); return NotFound(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> CreateEditService(Models.Base.Service service, int? id, IFormFile imagePath) { if (ModelState.IsValid) { if (imagePath != null) { service.ImagePath = Path.Combine(PathImg, imagePath.FileName); await using var Stream = new FileStream(Path.Combine(m_HostingEnvironment.WebRootPath, PathImg, imagePath.FileName), FileMode.Create); await imagePath.CopyToAsync(Stream); } //Insert if (id == 0) { m_Context.Services.Add(service); await m_Context.SaveChangesAsync(); } //Update else { m_Context.Services.Update(service); //m_Context.Entry(service).State = EntityState.Modified; await m_Context.SaveChangesAsync(); } //return RedirectToAction("Index"); return Json(new { isValid = true, html = HelperView.RenderRazorViewToString(this, "_ViewServices", m_Context.Services.Include(c => c.ServiceCategory).ToList()) }); } if (id == null) { ViewBag.SelectCategories = new SelectList(await m_Context.ServiceCategories.ToListAsync(), "Id", "Title"); } else { ViewBag.SelectCategories = new SelectList( await m_Context.ServiceCategories.Where(x => x.Id != service.ServiceCategoryId).ToListAsync(), "Id", "Title"); } // TODO: Добавить сообщение об ошибках - повторении Index return Json(new { isValid = false, html = HelperView.RenderRazorViewToString(this, "CreateEditService", service) }); } [NoDirectAccess] public async Task<IActionResult> DetailsService(int? id) { if (id == null) return NotFound(); var Service = await m_Context.Services.AsNoTracking() .Include(x => x.ServiceCategory) .FirstOrDefaultAsync(x => x.Id == id); if (Service != null) return View(Service); return NotFound(); } [HttpGet] [NoDirectAccess] [ActionName("DeleteService")] public async Task<IActionResult> ConfirmDeleteService(int? id) { if (id == null) return NotFound(); var Service = await m_Context.Services.Include(s => s.ServiceCategory).FirstOrDefaultAsync(p => p.Id == id); if (Service != null) return View(Service); return NotFound(); } [HttpPost] public async Task<IActionResult> DeleteService(int? id) { if (id == null) return NotFound(); var Service = await m_Context.Services.FirstOrDefaultAsync(p => p.Id == id); if (Service == null) return NotFound(); m_Context.Services.Remove(Service); await m_Context.SaveChangesAsync(); return RedirectToAction("Index"); } } }<file_sep>/HotelService/Areas/Identity/Pages/Account/Register.cshtml.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using HotelService.Models.Base; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace HotelService.Areas.Identity.Pages.Account { [AllowAnonymous] public class RegisterModel : PageModel { private readonly RoleManager<Role> m_RoleManager; private readonly SignInManager<User> m_SignInManager; private readonly UserManager<User> m_UserManager; public RegisterModel( UserManager<User> userManager, RoleManager<Role> roleManager, SignInManager<User> signInManager) { m_UserManager = userManager; m_RoleManager = roleManager; m_SignInManager = signInManager; } [BindProperty] public InputModel Input { get; set; } public string ReturnUrl { get; set; } public IList<AuthenticationScheme> ExternalLogins { get; set; } public async Task OnGetAsync(string returnUrl = null) { if (User.Identity.IsAuthenticated) Response.Redirect("/Home"); ReturnUrl = returnUrl; ExternalLogins = (await m_SignInManager.GetExternalAuthenticationSchemesAsync()).ToList(); } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { Url.Content("~/"); ExternalLogins = (await m_SignInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (!ModelState.IsValid) return Page(); var NewUser = new User { UserName = Input.Email, Email = Input.Email, RegistrationDate = DateTime.Now, Passport = Input.Passport, FirstName = Input.FirstName, LastName = Input.LastName }; var Result = await m_UserManager.CreateAsync(NewUser, Input.Password); if (Result.Succeeded) { var UserNow = await m_UserManager.FindByNameAsync(NewUser.UserName); if (!await m_RoleManager.RoleExistsAsync(Input.Role.ToString())) await m_RoleManager.CreateAsync(new Role(Input.Role.ToString())); await m_UserManager.AddToRoleAsync(UserNow, Input.Role.ToString()); await m_SignInManager.PasswordSignInAsync(NewUser, Input.Password, false, false); Response.Redirect("/Home"); } foreach (var Error in Result.Errors) ModelState.AddModelError(string.Empty, Error.Description); // If we got this far, something failed, redisplay form return Page(); } public class InputModel { [Required(ErrorMessage = "Имя обязательно")] [DataType(DataType.Text)] [Display(Name = "Имя")] public string FirstName { get; set; } [Required] [DataType(DataType.Text)] [Display(Name = "Фамилия")] public string LastName { get; set; } [Required] [RegularExpression(@"^[0-9]*$")] [StringLength(20, MinimumLength = 10)] [DataType(DataType.Text)] [Display(Name = "Паспорт")] public string Passport { get; set; } [Required(ErrorMessage = "Select Role")] [Display(Name = "Права доступа")] public RoleType Role { get; set; } [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Пароль")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Подтвердите пароль")] [Compare("Password", ErrorMessage = "Пароли не совпадают.")] public string ConfirmPassword { get; set; } } } }<file_sep>/HotelService/Areas/Client/Controllers/CatalogController.cs using HotelService.Models.ViewModels.Client; using HotelService.Repositories.Interfaces; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; namespace HotelService.Areas.Client.Controllers { [Area("Client")] [Authorize(Roles = "Developer, Client")] public class CatalogController : Controller { private ICatalogManager m_Catalog; public CatalogController(ICatalogManager catalog) { m_Catalog = catalog; } public ViewResult Index() { var Catalog = new CatalogModel { Services = m_Catalog.Services, Categories = m_Catalog.Categories }; return View(Catalog); } private void AddErrorsFromResult(IdentityResult result) { foreach (var Error in result.Errors) { ModelState.AddModelError("", Error.Description); } } } } <file_sep>/HotelService/Models/ViewModels/Client/CartModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HotelService.Infrastructure; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace HotelService.Models.ViewModels.Client { public class CartModel { public ShoppingCart Cart { get; set; } public string ReturnUrl { get; set; } } }
e3628f526bd884f9c1d851679df09edb2b80e4c5
[ "Markdown", "C#", "Text" ]
44
C#
MyakishHentai/HotelService
726b10eab76124abc194c3525e24e367455484b0
4a5d1a192ac865501a65d6d6e1128f58e2620277
refs/heads/master
<repo_name>gsguglielmo/Teleprompter-2.0<file_sep>/src/AtemController.js const { Atem } = require('atem-connection'); const Jimp = require('jimp'); const PATH = require("path"); const fs = require("fs"); class AtemController{ #atem; connected; onConnectedCallbacks; constructor() { this.#atem = new Atem(); this.connected = false; this.onConnectedCallbacks = []; let _this = this; this.#atem.on("connected",()=>{ _this.connected = true; fs.writeFileSync(PATH.join(__dirname,"debug_new.json"),JSON.stringify(this.#atem.state)); _this.#onConnected(_this); }); this.#atem.on("disconnected",()=>{ _this.#onDisconnected(_this); }) } connect(ipAddress){ return new Promise(((resolve) => { if(this.connected){ resolve(); }else{ this.addOnConnectedOnce(resolve); this.#atem.connect(ipAddress); } })); } #onDisconnected(_this){ _this.connected = false; } async disconnect(){ this.connected = false; await this.#atem.disconnect(); } addOnConnected(callback){ this.onConnectedCallbacks.push({ cb: callback, once: false }); return this.onConnectedCallbacks.length-1; } addOnConnectedOnce(callback){ this.onConnectedCallbacks.push({ cb: callback, once: true }); return this.onConnectedCallbacks.length-1; } removeOnConnected(index){ this.onConnectedCallbacks.splice(index, 1); } async #onConnected(_this){ let toDelete = []; for(let i=0;i<_this.onConnectedCallbacks.length;i++){ let item = _this.onConnectedCallbacks[i]; try{ if(item.once){ toDelete.push(i); } item.cb(); }catch (e){} } for(let i=0;i<toDelete.length;i++){ _this.removeOnConnected(toDelete[i]); } } onError(callback){ this.#atem.on("error",callback); } uploadStill(path,index){ if(!this.connected)return; return new Promise(async (resolve, reject) => { try{ let file = await this.readImage(path); this.#atem.uploadStill(index % this.#atem.state.media.stillPool.length, file, PATH.basename(path), '').then( async _res => { resolve(true); }, e => { reject(e); } ); }catch (e){ reject(e); } }); } switchStill(index){ if(!this.connected)return; return this.#atem.setMediaPlayerSource({ sourceType: 1, clipIndex: 0, stillIndex: index % this.#atem.state.media.stillPool.length }); } stillToPreview(){ if(!this.connected)return; return this.#atem.changePreviewInput(3010); } key1(){ if(!this.connected)return; return this.#atem.macroRun(0); } checkStreamingService(url,key){ if(!this.connected)return false; let service = this.#atem.state.streaming.service; return service.key === key && service.url === url; } checkMacro(){ if(!this.connected)return false; return this.#atem.state.macro.macroProperties[0].isUsed; } checkDVE(DVE){ if(!this.connected)return false; let saved = DVE.settings; let current = this.#atem.state.video.mixEffects[0].upstreamKeyers[0].dveSettings; let keys = Object.keys(saved); for(let i=0;i<keys.length;i++){ if(saved[keys[i]] !== current[keys[i]]){ return false; } } return true; } setStreamingService(url, key){ if(!this.connected)return; return this.#atem.setStreamingService({ serviceName: "Teleprompter defined", url: url, key: key }); } setDVE(settings){ if(!this.connected)return; return this.#atem.setUpstreamKeyerDVESettings({ ...settings["settings"] }) } readImage(path){ return new Promise(((resolve, reject) => { Jimp.read(path).then(async (image)=>{ let data = Buffer.alloc(image.getWidth()*image.getHeight()*4); let index = 0; for(let y=0;y<image.getHeight();y++){ for(let x=0;x<image.getWidth();x++){ let pixel = Jimp.intToRGBA(image.getPixelColor(x,y)); data.writeUInt8(pixel["r"],index); data.writeUInt8(pixel["g"],index+1); data.writeUInt8(pixel["b"],index+2); data.writeUInt8(pixel["a"],index+3); index += 4; } } resolve(data); }).catch(reject); })); } } exports.AtemController = AtemController; <file_sep>/src/globalConfig.js const { app } = require('electron'); const fs = require("fs"); const path = require("path"); class GlobalConfig{ #config = { services: [], dveStyles: [] } #defaults; #configPath; constructor() { this.#configPath = path.join(app.getPath("userData"),"config.json"); if(fs.existsSync(this.#configPath)){ this.#config = JSON.parse(fs.readFileSync(this.#configPath)); }else{ this.#saveToDisk(); } this.#compatibilityChecks(); this.#defaults = require(path.join(__dirname,"defaults.json")); } #compatibilityChecks(){ } #saveToDisk(){ fs.writeFileSync(this.#configPath,JSON.stringify(this.#config)); } getServices(){ return [ ...this.#defaults.services, ...this.#config.services ] } getDVEStyles(){ return [ ...this.#defaults.dveStyles, ...this.#config.dveStyles ] } addService(name, server){ this.#config.services.push({ name: name, server: server }) this.#saveToDisk(); } removeService(index){ if(index<this.#defaults.services.length)return false; this.#config.services.splice(index-this.#defaults.services.length, 1); } } exports.GlobalConfig = GlobalConfig; <file_sep>/src/SerialController.js const SerialPort = require('serialport'); class SerialController{ #vendor; #product; #mappings; #port; #cc; #connection; constructor(vendor="3031",product="3031",mapping={next: "1",reset: "2",pause:"3",prepare:"4",start:"4"}) { this.#vendor = vendor.toUpperCase(); this.#product = product.toUpperCase(); this.#mappings = mapping; this.identify().then((port)=>{ this.#port = port["path"]; this.#connection = new SerialPort(this.#port,{ baudRate: 9600, autoOpen: false }); if(this.#cc !== undefined){ this.#connection.open((err) => { if (err) { return console.log('Error opening port: ', err.message) } this.#connection.on("data",this.#cc); }) } }).catch((e)=>{ console.error(e); }) } identify() { return new Promise(((resolve, reject) => { SerialPort.list().then((ports)=>{ for(let i=0;i<ports.length;i++){ if(ports[i]["vendorId"] === undefined || ports[i]["productId"] === undefined)continue; let vendor = ports[i]["vendorId"].toUpperCase(); let product = ports[i]["productId"].toUpperCase(); if(vendor === this.#vendor && product === this.#product){ resolve(ports[i]); return; } } console.log(ports); }).catch(reject); })); } close(){ if(this.#connection !== undefined){ this.#connection.close(); } } onKeyPressedCallback(cb){ let call = (byte)=>{ let index = byte.readUInt8(); switch (index){ case this.#mappings.next.charCodeAt(0): cb("next"); break; case this.#mappings.reset.charCodeAt(0): cb("reset"); break; case this.#mappings.pause.charCodeAt(0): cb("pause"); break; case this.#mappings.prepare.charCodeAt(0): cb("prepare"); break; case this.#mappings.start.charCodeAt(0): cb("start"); break; } }; if(this.#connection===undefined){ this.#cc = call; }else{ this.#connection.on("data",call); } } } exports.SerialController = SerialController; <file_sep>/src/mainApp.js const { app, BrowserWindow, ipcMain, screen, dialog } = require('electron'); const { getAudioDurationInSeconds } = require('get-audio-duration'); const { v4: uuidv4 } = require('uuid'); const {AtemController} = require("./AtemController.js"); const player = require('play-sound')(opts = { player: `${__dirname}\\mpg123\\mpg123.exe` }) const path = require('path'); const fs = require('fs'); const tar = require('tar-fs'); const {GlobalConfig} = require("./globalConfig.js") let songsDirectory; const serialConfig = require("./serialConfig.json"); let save = { "display_index": 0, "stills": {}, "songs": [ ], "segments": [ ] }; let secondsSinceStart = 0; let currentAudio; let {SerialController} = require("./SerialController.js"); let serialController; save.display_index = 0; save.show_status = { started: false, paused: true, currentSegment: undefined, nextSegment: undefined, is_live: false, totalTime: { minutes: 0, seconds: 0 }, segmentTime: { minutes: 0, seconds: 0 }, late: { minutes: 0, seconds: 0 }, totalLate: 0 } let webContents = []; let atemController = new AtemController(); let DIR; let globalConfig; function createWindow (config,oldWindow) { DIR = config.dir; save.name = config.config.name; save.date = config.config.date; save.uuid = config.config.uuid; save.isInitialized = config.config.isInitialized; if(save.isInitialized){ save = config.config; }else{ save.isInitialized = true; saveSettingsToDisk().then(); } if(save.uuid === undefined){ save.uuid = uuidv4(); saveSettingsToDisk().then(); } if(save.stills === undefined){ save.stills = {}; saveSettingsToDisk().then(); } //Convert project file to new version (compatibility layer) for(let i=0;i<save.segments.length;i++){ let segment = save.segments[i]; if(segment.uuid === undefined && parseInt(segment.type) === 1){ save.segments[i].uuid = getUUID(segment.filename); } } saveSettingsToDisk().then(); globalConfig = new GlobalConfig(); songsDirectory = path.join(DIR, 'songs'); if(!fs.existsSync(songsDirectory)){ fs.mkdirSync(songsDirectory); } save.show_status.paused = true; const win2 = new BrowserWindow({ width: 1300, height: 700, webPreferences: { nodeIntegration: true } }) // and load the index.html of the app. win2.loadFile('src/www/main.html') win2.removeMenu(); win2.maximize(); webContents.push(win2.webContents); oldWindow.close(); let displays = screen.getAllDisplays() ipcMain.on('compressProject',(event, arg)=>{ let name = path.basename(DIR); let exportDir = path.join(__dirname,"projectExport"); let compressedPath = path.join(__dirname,"projectExport",name+".teleprompter"); if(fs.existsSync(exportDir)){ fs.rmdirSync(exportDir,{recursive: true}); } fs.mkdirSync(exportDir); let compression = tar.pack(DIR).pipe(fs.createWriteStream( compressedPath )); compression.on('finish', function () { console.log("completed"); event.sender.send('compressProject', compressedPath.toString()); }); }); ipcMain.on('ondragstart', (event, filePath) => { event.sender.startDrag({ file: filePath, icon: path.join(__dirname,"www","projecticon_small.png") }) }) ipcMain.on('getSongs', (event, arg) => { fs.readdir(songsDirectory, async (err, files) => { //handling error if (err) { event.sender.send('getSongs',{ error: true, message: 'Unable to scan directory: ' + err }); return console.log('Unable to scan directory: ' + err); } let details = []; for(let i=0; i<files.length;i++){ let duration = await getAudioDurationInSeconds(path.join(songsDirectory,files[i])); details.push({ filename: files[i], duration: calculateDuration(duration), uuid: getUUID(files[i]) }); } save.songs = details; saveSettingsToDisk().then(); event.sender.send('getSongs', details); }); }); ipcMain.on('uploadSong', async (event, files) => { let newFiles = []; //Assigning uuids to the uploaded files for(let i=0;i<files.length;i++){ let exists = false; save.songs.forEach((song)=>{ if(song.filename === files[i].name){ exists = true; } }); if(!exists){ newFiles.push({ uuid: uuidv4(), ...files[i] }) } } event.sender.send('uploadSong', newFiles); let successFiles = []; for(let i=0;i<newFiles.length;i++){ let status = true; let duration = undefined; try{ fs.copyFileSync(newFiles[i].path,path.join(songsDirectory,newFiles[i].name)); duration = await getAudioDurationInSeconds(path.join(songsDirectory,newFiles[i].name)); duration = calculateDuration(duration); console.log(duration); }catch (e){ console.error(e.message); status = false; } successFiles.push({ status: status, duration: duration, ...newFiles[i] }); if(status){ save.songs.push({ filename: newFiles[i].name, duration: duration, uuid: newFiles[i].uuid }); } } event.sender.send('songUploadingStatusChange', successFiles); }); ipcMain.on('deleteSong', async (event, uuid) => { for(let i=0;i<save.songs.length;i++) { let song = save.songs[i]; if(song.uuid === uuid){ fs.unlinkSync(path.join(songsDirectory,song.filename)); } } event.sender.send('deleteSong', {}); }); ipcMain.on('getStills', async (event, uuid) => { event.sender.send('getStills', save.stills); }); ipcMain.on('uploadStill', async (event, uuid) => { let result = await dialog.showOpenDialogSync(win2, { properties: ['openFile'], filters: [ { name: 'Images', extensions: ['jpg', 'png'] }, ] }); if(result === undefined){ event.sender.send('uploadStill', { status: false }); return; } let stillPath = result[0]; try{ let still_dir = path.join(DIR,"stills"); //Create directory stills if not exists if(!fs.existsSync(still_dir)){ fs.mkdirSync(still_dir); } let filename = path.basename(stillPath); //File copied, now adding it to the list of stills fs.copyFileSync(stillPath,path.join(still_dir,filename)); save.stills[uuid] = { filename: filename, song_uuid: uuid }; await saveSettingsToDisk(); event.sender.send('uploadStill', { status: true, data: save.stills[uuid] }); }catch (e){ console.error(e.message); event.sender.send('uploadStill', { status: false }); } event.sender.send('uploadStill', {}); }); ipcMain.on('deleteStill', async (event, uuid) => { save.stills[uuid] = undefined; await saveSettingsToDisk(); event.sender.send('deleteStill', true); }); ipcMain.on('compressProject', async (event, uuid) => { for(let i=0;i<save.songs.length;i++) { let song = save.songs[i]; if(song.uuid === uuid){ fs.unlinkSync(path.join(songsDirectory,song.filename)); } } event.sender.send('deleteSong', {}); }); ipcMain.on('saveSegments', async (event, segments) => { save.segments = segments; if(await saveSettingsToDisk()){ event.sender.send('saveSegments',{ error: false, message: 'Saved' }); }else{ event.sender.send('saveSegments',{ error: true, message: 'Unable to save!' }); } }); ipcMain.on('loadSegments', async (event, segments) => { event.sender.send('loadSegments',save.segments); }); ipcMain.on('getVersion', async (event, segments) => { event.sender.send('getVersion',app.getVersion()); }); ipcMain.on('getShowDetails', async (event, segments) => { event.sender.send('getShowDetails', { name: save.name, date: save.date }); }); ipcMain.on('timer-play', async (event, segments) => { timerPlay(); }); ipcMain.on('timer-pause', async (event, segments) => { timerPause(); }); ipcMain.on('timer-next', async (event, segments) => { nextSegment(); }); ipcMain.on('timer-reset', async (event, segments) => { timerReset(); }); ipcMain.on('set-description', async (event, description) => { save.show_status.description = description; sendMessage("get-description",description) }); ipcMain.on('new-monitor', async (event, description) => { // Create the browser window. let externalDisplay = displays[save.display_index]; const win = new BrowserWindow({ width: 800, height: 600, x: externalDisplay.bounds.x + 50, y: externalDisplay.bounds.y + 50, webPreferences: { nodeIntegration: true } }) // and load the index.html of the app. win.loadFile('src/www/window.html') win.removeMenu(); webContents.push(win.webContents); win.setFullScreen(true); }); ipcMain.on('prepare-next-segment', async (event, stillUUID) => { if(save.stills[stillUUID] === undefined) return; let still_filename = save.stills[stillUUID].filename; let still_path = path.join(DIR,"stills",still_filename); console.log(still_path); if(!fs.existsSync(still_path))return; let upload_slot = 0; if(save.workingStill !== undefined && !isNaN(parseInt(save.workingStill))){ upload_slot = save.workingStill; } try{ console.log(atemController.connected); await atemController.uploadStill(still_path,upload_slot); await atemController.switchStill(upload_slot); await atemController.stillToPreview(); await atemController.key1(); }catch (e){ console.error(e); event.sender.send('prepare-next-segment',false); } }); ipcMain.on('atem-mini-test-connection', async (event, ipAddress) => { let success = await atemController.connect(ipAddress); event.sender.send('atem-mini-test-connection',true); save.atemIp = ipAddress; saveSettingsToDisk().then(); }); ipcMain.on('atem-disconnect', async (event, none) => { await atemController.disconnect(); event.sender.send('atem-disconnect', true); }); ipcMain.on('getServices', async (event, none) => { event.sender.send('getServices',globalConfig.getServices()); }); ipcMain.on('saveStreamingSettings', async (event, StreamingSettings) => { save.streamingURL = StreamingSettings.url; save.streamingKey = StreamingSettings.key; save.workingStill = StreamingSettings.workingStill; saveSettingsToDisk().then(); await atemController.setStreamingService(save.streamingURL,save.streamingKey); event.sender.send('saveStreamingSettings',true); }); ipcMain.on('getStreamingSettings', async (event, none) => { event.sender.send('getStreamingSettings', { url: save.streamingURL, key: save.streamingKey, workingStill: save.workingStill }); }); ipcMain.on('getAtemMiniAddress', async (event, none) => { event.sender.send('getAtemMiniAddress', { ip: save.atemIp, isConnected: atemController.connected }); }); ipcMain.on('getDVEPresets',async (event,none)=>{ event.sender.send('getDVEPresets', globalConfig.getDVEStyles()); }); ipcMain.on('getDVEStyle',async (event,none)=>{ if(save.DVE === undefined){ save.DVE = globalConfig.getDVEStyles()[0]; saveSettingsToDisk().then(); } event.sender.send('getDVEStyle', save.DVE); }); ipcMain.on('getAtemMiniStatus',async (event,none)=>{ let dveStatus = false; if(save.DVE !== undefined){ dveStatus = await atemController.checkDVE(save.DVE); } event.sender.send('getAtemMiniStatus', { connected: atemController.connected, dveSettingsCheck: dveStatus, streamingSettingsCheck: atemController.checkStreamingService(save.streamingURL,save.streamingKey), macroCheck: atemController.checkMacro() }); }); ipcMain.on('setDVEStyle',async (event,DVE)=>{ save.DVE = DVE; saveSettingsToDisk().then(); await atemController.setDVE(DVE); event.sender.send('setDVEStyle', true); }); ipcMain.on('checkSongs',async (event,none)=>{ let segments = save.segments; let missing = []; for(let i=0;i<segments.length;i++){ if(parseInt(segments[i].type) !== 1) continue; if(!fs.existsSync(path.join(songsDirectory,segments[i].filename))){ missing.push(segments[i]); } } event.sender.send('checkSongs', { missing: missing }); }); ipcMain.on('checkStills',async (event,none)=>{ let stills = save.stills; let keys = Object.keys(stills); let missing = []; for(let i=0;i<keys.length;i++){ if(!fs.existsSync(path.join(DIR,"stills",stills[keys[i]].filename))){ missing.push(stills[keys[i]]); } } event.sender.send('checkStills', { missing: missing }); }); ipcMain.on('connectController',async (event, none)=>{ let vendor = save["controllerVendor"]===undefined? "10C4" : save["controllerVendor"]; let product = save["controllerProduct"]===undefined? "EA60" : save["controllerProduct"]; if(serialController !== undefined){ serialController.close(); serialController = undefined; } if(save["controllerMappings"] === undefined){ save["controllerMappings"] = { next: "a", reset: "b", pause: "c", prepare: "d", start: "e" } } serialController = new SerialController(vendor,product,save["controllerMappings"]); serialController.onKeyPressedCallback((res)=>{ switch (res){ case "next": nextSegment() break; case "reset": timerReset() break; case "pause": timerPause() break; case "prepare": break; case "start": timerPlay(); break; } }) event.sender.send('connectController', {}); }); ipcMain.on('saveControllerSettings',async (event, settings)=>{ save["controllerVendor"] = settings.controllerVendor; save["controllerProduct"] = settings.controllerProduct; save["controllerMappings"] = settings.controllerMappings; saveSettingsToDisk().then(); event.sender.send('saveControllerSettings', true); }); ipcMain.on('getControllerSettings',async (event, settings)=>{ if(save["controllerMappings"] === undefined){ save["controllerMappings"] = { next: "a", reset: "b", pause: "c", prepare: "d", start: "e" } saveSettingsToDisk().then(); } event.sender.send('getControllerSettings', { controllerVendor: save["controllerVendor"], controllerProduct: save["controllerProduct"], controllerMappings: save["controllerMappings"] }); }); } function timerPlay(){ if(save.show_status.started){ }else{ let sgmts = save.segments; save.show_status.currentSegment = sgmts[0]; save.show_status.currentSegmentIndex = 0; save.show_status.currentSegment.started = secondsSinceStart; save.show_status.forceNext = sgmts[0].type === 1; let duration = save.show_status.currentSegment.duration.split(":"); save.show_status.segmentTime.minutes = parseInt(duration[0]); save.show_status.segmentTime.seconds = parseInt(duration[1]); save.show_status.description = ""; save.show_status.totalTime = { minutes: 0, seconds: 0 }; save.show_status.totalLate = 0; if(sgmts.length>1){ save.show_status.nextSegment = sgmts[1]; } save.show_status.started = true; playCurrentSong(); } save.show_status.paused = false; } function timerPause(){ save.show_status.paused = true; } function timerReset(){ save.show_status.started = false; save.show_status.paused = true; save.show_status.totalTime = { minutes: 0, seconds: 0 }; save.show_status.late = { minutes: 0, seconds: 0 }; save.show_status.segmentTime = { minutes: 0, seconds: 0 }; save.show_status.totalLate = 0; save.show_status.description = ""; try{ if(currentAudio!==undefined){ currentAudio.kill(); } }catch (e){} } //app.whenReady().then(createWindow); exports.createWindow = createWindow; function atem_mini_connect(ip){ return new Promise(((resolve, reject) => { ATEM_MINI.object.on('connected',()=>{ resolve(true); }); ATEM_MINI.object.connect(ip).then(); })); } app.on('window-all-closed', () => { app.quit() }) setInterval(tick, 1000); function getUUID(filename){ let uuid = uuidv4(); save.songs.forEach((song)=>{ if(song.filename === filename){ uuid = song.uuid; } }); return uuid; } function tick(){ secondsSinceStart++; if(save.show_status.started && !save.show_status.paused){ save.show_status.totalTime.seconds++; if(save.show_status.totalTime.seconds > 59){ save.show_status.totalTime.seconds -= 60; save.show_status.totalTime.minutes++; } save.show_status.segmentTime.seconds--; if(save.show_status.segmentTime.seconds < 0){ save.show_status.segmentTime.seconds = 59; save.show_status.segmentTime.minutes--; if(save.show_status.segmentTime.minutes < 0){ save.show_status.segmentTime.minutes = 0; save.show_status.segmentTime.seconds = 0; if(save.show_status.forceNext){ nextSegment(); }else{ save.show_status.late.seconds++; if(save.show_status.late.seconds > 59){ save.show_status.late.seconds = 0; save.show_status.late.minutes++; } } } } } let songToDisplay = ""; for(let i=save.show_status.currentSegmentIndex;i<save.segments.length;i++){ let segment = save.segments[i]; if(parseInt(segment.type) === 1){ songToDisplay = `${segment.title} - ${segment.author}`; break; } } sendMessage("tick",{ songToDisplay: songToDisplay, time: secondsSinceStart, ... save.show_status }) } function nextSegment(){ if(save.show_status.nextSegment !== undefined){ let late = save.show_status.late.minutes*60; late += save.show_status.late.seconds; save.show_status.totalLate += late; let notLate = save.show_status.segmentTime.minutes*60; notLate += save.show_status.segmentTime.seconds; save.show_status.totalLate -= notLate; save.show_status.late.seconds=0; save.show_status.late.minutes=0; let start = save.show_status.currentSegment.started; save.segments[save.show_status.currentSegmentIndex].realDuration = secondsSinceStart-start; saveSettingsToDisk().then(); save.show_status.currentSegment = save.show_status.nextSegment; save.show_status.currentSegment.started = secondsSinceStart; let duration = save.show_status.currentSegment.duration.split(":"); save.show_status.segmentTime.minutes = parseInt(duration[0]); save.show_status.segmentTime.seconds = parseInt(duration[1]); save.show_status.forceNext = save.show_status.currentSegment.type === 1; save.show_status.currentSegmentIndex++; if(save.segments.length-1 >= save.show_status.currentSegmentIndex+1){ save.show_status.nextSegment = save.segments[save.show_status.currentSegmentIndex+1]; }else{ save.show_status.nextSegment = undefined; } playCurrentSong(); } } function saveSettingsToDisk(){ return new Promise((resolve => { fs.writeFile(path.join(DIR,"teleprompter.json"), JSON.stringify(save), (err) => { if (err) { console.error(err.message); resolve(false); return ; } resolve(true); }); })); } function calculateDuration(durationInSeconds){ let intDuration = parseInt(durationInSeconds+""); return{ minutes: parseInt((intDuration/60)+""), seconds: intDuration%60 } } function sendMessage(channel,data){ webContents.forEach((webContent)=>{ try{ webContent.send(channel,data); }catch (e){} }); } async function playCurrentSong(){ try{ if(currentAudio!==undefined){ currentAudio.kill(); } }catch (e){} if(save.show_status.currentSegment.type !== 1)return; //${__dirname}\\songs\\${save.show_status.currentSegment.filename} currentAudio = player.play(path.join(songsDirectory,save.show_status.currentSegment.filename), function(err){ if (err && !err.killed) throw err }); } <file_sep>/src/index.js /** * This module checks for updates and if not available opens the projectManager. If an update is * available it will be installed automatically. * */ const { app,autoUpdater,dialog,BrowserWindow } = require('electron'); const isDev = require('electron-is-dev'); //Todo manage installation and update procedures if needed if (require('electron-squirrel-startup')) return app.quit(); const server = 'https://github.com/gsguglielmo/Teleprompter-2.0/releases/download/' const url = `${server}/latest` let updateWindow; autoUpdater.setFeedURL({ url }) autoUpdater.on("update-available",()=>{ updateWindow.webContents.send("updateStarted", {}); }); //Restart the app when the update is done autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName) => { autoUpdater.quitAndInstall(); }); autoUpdater.on("update-not-available",()=>{ loadProjectsManager(); }); autoUpdater.on("error",(err)=>{ console.error(err); loadProjectsManager(); }); function loadProjectsManager(){ require("./projectsManager.js").init(); if(!updateWindow.isDestroyed()){ updateWindow.close(); } } app.whenReady().then(()=>{ //Display the loading window const win = new BrowserWindow({ width: 500, height: 320, webPreferences: { nodeIntegration: true }, resizable: false, frame: false }) win.loadFile('src/www/updateCheck.html'); //win.webContents.openDevTools({ mode: 'detach' }) updateWindow = win; //Update only if we are not in a development environment if(!isDev){ //The update checks happens only once when the app is started autoUpdater.checkForUpdates(); /* setInterval(() => { autoUpdater.checkForUpdates(); console.log("check update") }, 60000);*/ }else{ loadProjectsManager(); } }); <file_sep>/forge.config.js const token = process.env.GITHUB_SECRET_TOKEN !== undefined ? process.env.GITHUB_SECRET_TOKEN : ""; module.exports = { "packagerConfig": {}, "makers": [ { "name": "@electron-forge/maker-squirrel", "config": { "name": "Teleprompter" } }, { "name": "@electron-forge/maker-zip", "platforms": [ "darwin" ] }, { "name": "@electron-forge/maker-deb", "config": {} }, { "name": "@electron-forge/maker-rpm", "config": {} } ], "publishers": [ { "name": "@electron-forge/publisher-github", "config": { "repository": { "owner": "gsguglielmo", "name": "Teleprompter-2.0" }, "draft" : true, "prerelease": true, "authToken" : token } } ] }
84d6a79fbe2ae82db15ebbd10d83b62e33f2e03e
[ "JavaScript" ]
6
JavaScript
gsguglielmo/Teleprompter-2.0
f1664af6e9e16dcb16ead82505a3b6a778e2b330
51097474d35d47a3e577427e741a662d05d2bfca
refs/heads/main
<repo_name>alvartur34/alvartur34.github.io<file_sep>/js/my_scripts.js //?-----------------------// //?---- User language ----// //?-----------------------// let userLang = navigator.userLanguage || navigator.language; let lang = userLang.split("-", 1); document.getElementById("userLang").innerHTML = lang; //?-----------------------// //?---- Smooth Scroll ----// //?-----------------------// $('a[href*="#"]').on("click", function (e) { e.preventDefault(); $("html, body").animate( { scrollTop: $($(this).attr("href")).offset().top }, 500, "linear" ); }); //?----------------// //?---- Loader ----// //?----------------// const progressBar = document.querySelector(".bar"); document.ready = () => { setTimeout(() => { progressBar.classList.add("active"); }, 1000); }; window.onload = () => { if (progressBar) { progressBar.style.width = "100%"; setTimeout(() => { document.getElementById("pageLoader").classList.add("hidde"); }, 1500); } else { console.error("Loader error, doesn't exists"); } }; //?----------------------// //?---- ScrollReavel ----// //?----------------------// ScrollReveal().reveal("main .meter span", {delay: 300}); ScrollReveal().reveal("section", {delay: 300}); ScrollReveal().reveal("main img", {delay: 300}); ScrollReveal().reveal("h1", {delay: 300}); ScrollReveal().reveal("h2", {delay: 300}); ScrollReveal().reveal("h3", {delay: 300}); ScrollReveal().reveal("h4", {delay: 300}); ScrollReveal().reveal("h5", {delay: 300}); ScrollReveal().reveal("h6", {delay: 300}); ScrollReveal().reveal("p", {delay: 300}); ScrollReveal().reveal("a", {delay: 300}); //?--------------------------------// //?---- Progressbars Animation ----// //?--------------------------------// $(window).on("scroll", function () { let list = document.querySelectorAll("main .meter span"); for (var i = 0; i < list.length; ++i) { let opa = document.querySelectorAll("main .meter span")[i]; let bar = document.querySelectorAll("main .meter span")[i]; if (opa == 1) { if (bar.style.opacity > 0) { bar.classList.remove("active"); } else { bar.classList.add("active"); } } else { if (bar.style.opacity > 0) { bar.classList.remove("active"); } else { bar.classList.add("active"); } } } });
9983c6b31abeaca57cd3baf0843817ca1657491c
[ "JavaScript" ]
1
JavaScript
alvartur34/alvartur34.github.io
1f1e113313f46606a5613ee3c7d0ec71c9aa4ef3
ed27ecc044d9a745420d0152202c650b8aefbb48
refs/heads/main
<repo_name>Laplace-Studios/MetricsCalculator.Worker<file_sep>/README.md # MetricsCalculator.Worker Ejecutar con python3 main.py REDIARIO_Consulta_Periodo_010221_30061.xlsx Se general dos archivos CSV de salida con las metricas calculadas <file_sep>/main.py import sys import pandas as pd dataset = pd.read_excel(str(sys.argv[1]) ) estaciones_mas_fallas = dataset[['Id_Avería', 'FECHA', 'Localizacion', 'DESCRIPRD']].groupby(['Localizacion', 'FECHA']).agg(['count']).sort_values(by=['FECHA' ,'Localizacion'], ascending=False) dia_mas_averias = dataset[['Localizacion', 'FECHA']].groupby(['FECHA'])['FECHA'].count() dia_mas_averias = dia_mas_averias.to_frame().rename(columns= {'FECHA': 'conteo_averias'}) estaciones_mas_fallas.to_csv('estaciones_mas_fallas.csv') dia_mas_averias.to_csv('dia_mas_averias.csv') print("Terminado")
ca0f90df91161039f4899c44b46a119b8c9bd757
[ "Markdown", "Python" ]
2
Markdown
Laplace-Studios/MetricsCalculator.Worker
cada28f6a41166d0769eb14e81118a788321b048
376258be920186a088101957a22f6678e63ae045
refs/heads/master
<repo_name>vdjango/Blessing<file_sep>/Blessing/src/net/mcshsz/event/PlayerQuitEvents.java package net.mcshsz.event; import org.bukkit.entity.Player; /** * 登出系统操作对象 * @author Dream * */ public class PlayerQuitEvents { public PlayerQuitEvents() { // TODO 自动生成的构造函数存根 } public void PlayerQuitEvent(Player Player){ if(Player.isOp()){ Player.setOp(false); } } } <file_sep>/Blessing/src/net/mcshsz/config/BssConfig.java package net.mcshsz.config; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfigurationOptions; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; import net.mcshsz.banned.main; public class BssConfig{ main plugin; /*默认配置文件*/ public BssConfig(main paramDeluxeChat){ this.plugin = paramDeluxeChat; } Logger log; public BssConfig(main paramDeluxeChat, Logger log){ this.plugin = paramDeluxeChat; } public FileConfiguration load(File file){ if (!(file.exists())) { } return YamlConfiguration.loadConfiguration(file); } public void fileNO(){ System.out.println("请检测配置文件!"); } public String MariadbLocalHost() { try{ return this.plugin.getConfig().getString("Bss.MariaDB.LocalHost"); }catch (Exception e) { fileNO(); } return null; } public String MariadbPort() { try{ return this.plugin.getConfig().getString("Bss.MariaDB.prot"); }catch (Exception e) { fileNO(); } return null; } public String MariadbRoot() { try{ return this.plugin.getConfig().getString("Bss.MariaDB.root"); }catch (Exception e) { fileNO(); } return null; } public String MariadbPasswd() { try{ return this.plugin.getConfig().getString("Bss.MariaDB.passwd"); }catch (Exception e) { fileNO(); } return null; } public String MariadbDatabases() { try{ return this.plugin.getConfig().getString("Bss.MariaDB.databases"); }catch (Exception e) { fileNO(); } return null; } public String MariadbTable() { try{ return this.plugin.getConfig().getString("Bss.MariaDB.table"); }catch (Exception e) { fileNO(); } return null; } public boolean MariadbUnicode() { try{ return this.plugin.getConfig().getBoolean("Bss.MariaDB.Unicode"); }catch (Exception e) { fileNO(); } return true; } public String MariadbEncoding() { try{ return this.plugin.getConfig().getString("Bss.MariaDB.Encoding"); }catch (Exception e) { fileNO(); } return null; } /*语言配置文件*/ public String messagePrefix() { try{ return this.plugin.getConfig().getString("messagePrefix"); }catch (Exception e) { fileNO(); } return null; } public String messageAdminDefault() { try{ return this.plugin.getConfig().getString("messageAdminDefault"); }catch (Exception e) { fileNO(); } return null; } public String messageAdminPrompt() { try{ return this.plugin.getConfig().getString("messageAdminPrompt"); }catch (Exception e) { fileNO(); } return null; } public String messageDefault() { try{ return this.plugin.getConfig().getString("messageDefault"); }catch (Exception e) { fileNO(); } return null; } public String messagePrompt() { try{ return this.plugin.getConfig().getString("messagePrompt"); }catch (Exception e) { fileNO(); } return null; } public String messageSkinDefault() { try{ return this.plugin.getConfig().getString("messageSkinDefault"); }catch (Exception e) { fileNO(); } return null; } public String messageSkinPrompt() { try{ return this.plugin.getConfig().getString("messageSkinPrompt"); }catch (Exception e) { fileNO(); } return null; } public String messageSetUpSkinDefault() { try{ return this.plugin.getConfig().getString("messageSetUpSkinDefault"); }catch (Exception e) { fileNO(); } return null; } public String messageSetUpSkinPrompt() { try{ return this.plugin.getConfig().getString("messageSetUpSkinPrompt"); }catch (Exception e) { fileNO(); } return null; } public String messageBannedDefault() { try{ return this.plugin.getConfig().getString("messageBannedDefault"); }catch (Exception e) { fileNO(); } return null; } public String messageBannedPrompt() { try{ return this.plugin.getConfig().getString("messageBannedPrompt"); }catch (Exception e) { fileNO(); } return null; } public String messageAnnouncement0() { try{ return this.plugin.getConfig().getString("announcement0"); }catch (Exception e) { fileNO(); } return null; } public String messageAnnouncement1() { try{ return this.plugin.getConfig().getString("announcement1"); }catch (Exception e) { fileNO(); } return null; } public String messageAnnouncement2() { try{ return this.plugin.getConfig().getString("announcement2"); }catch (Exception e) { fileNO(); } return null; } public String messageAnnouncement3() { try{ return this.plugin.getConfig().getString("announcement3"); }catch (Exception e) { fileNO(); } return null; } } <file_sep>/Blessing/src/net/mcshsz/config/Config.java package net.mcshsz.config; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.java.JavaPlugin; public class Config{ private final JavaPlugin plugin; private FileConfiguration config; private File configFile; private final String folderName; private final String fileName; /** * * @param plugin Main * @param folderName 文件夹 * @param fileName 文件 */ public Config(JavaPlugin plugin, String folderName, String fileName){ this.plugin = plugin; this.folderName = folderName; this.fileName = fileName; if(!plugin.getDataFolder().exists()) { plugin.getDataFolder().mkdir(); } File file=new File(plugin.getDataFolder(),fileName); if (!(file.exists())) { plugin.saveDefaultConfig(); } reloadConfig(); } Logger log; public Config(JavaPlugin plugin, Logger log, String folderName, String fileName){ this.plugin = plugin; this.folderName = folderName; this.fileName = fileName; log.log(Level.INFO, "配置文件开始加载!"); if(!plugin.getDataFolder().exists()) { plugin.getDataFolder().mkdir(); log.log(Level.INFO, "正在创建文件夹"); } File file=new File(plugin.getDataFolder(),fileName); if (!(file.exists())) { plugin.saveDefaultConfig(); log.log(Level.INFO, "正在创建配置文件"+fileName); } reloadConfig(); log.log(Level.INFO, "重新载入配置文件"+fileName); folderName=null; fileName=null; } public void createNewFile(String paramString1, String paramString2) { reloadConfig(); saveConfig(); loadConfig(paramString2); if (paramString1 != null) this.plugin.getLogger().info(paramString1); } public FileConfiguration getConfig() { if (this.config == null) { reloadConfig(); } return this.config; } public void loadConfig(String paramString) { this.config.options().header(paramString); this.config.options().copyDefaults(true); saveConfig(); } public void reloadConfig() { if (this.configFile == null) { this.configFile = new File(this.plugin.getDataFolder() + this.folderName, this.fileName); } this.config = YamlConfiguration.loadConfiguration(this.configFile); } public void saveConfig() { if ((this.config == null) || (this.configFile == null)) return; try { getConfig().save(this.configFile); } catch (IOException localIOException) { this.plugin.getLogger().log(Level.SEVERE, "配置文件无法保存 " + this.configFile, localIOException); } } } <file_sep>/Blessing/src/net/mcshsz/banned/bug.java package net.mcshsz.banned; public class bug { boolean bugs = false; public bug(String string){ if(bugs){ System.out.println("BUG调试:"+string); } } } <file_sep>/Blessing/src/net/mcshsz/html/HtmlHelper.java package net.mcshsz.html; import static java.lang.System.out; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import net.mcshsz.config.InsertDB; public class HtmlHelper implements Listener{ /** * "http://skin.mcshsz.net/csl/Dream.json"; * @param uid * @param urlstring 传入玩家皮肤站的URL,获取玩家皮肤! * @return 返回:玩家是否有皮肤! */ public static boolean WebUrl(ArrayList<String> uid, String urlstring){ ArrayList<String> Web = new ArrayList<String>(); InputStream is = null; BufferedReader br = null; BufferedWriter bw = null; try { URL url = new URL(urlstring); is = url.openStream(); // throws an IOException br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { Web.add(line); } } catch (IOException ioe) { //ioe.printStackTrace(); return false; } finally { try { if (is != null) { is.close(); } } catch (IOException ignore) { return false; } try { if (br != null) { br.close(); } } catch (IOException ignore) { return false; } try { if (bw != null) { bw.close(); } } catch (IOException ignore) { return false; } } int maxSplit = 2; String[] Webs = Web.get(0).split("errno", maxSplit); if(Webs.length>1){ return true; } return false; } public static boolean main(Player Player, String textures1, String textures2){ return false; } }
a16c23947dbf662a6d89231fe2a3959808cdb181
[ "Java" ]
5
Java
vdjango/Blessing
cc200f9b2e33b333504ca2553a7dcbd372791a58
f5a1df3ff1976873f03ea58b1599c92bc9cde6ff
refs/heads/master
<file_sep>var express=require("express"); var bodyParser=require("body-parser"); var path = require('path'); const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/gfg'); var db=mongoose.connection; db.on('error', console.log.bind(console, "connection error")); db.once('open', function(callback){ console.log("connection succeeded"); }) var app=express() app.use(bodyParser.json()); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: true })); app.post('/sign_UP', function(req,res){ var email =req.body.email; var pass = <PASSWORD>; var name = req.body.name; //var lastname = req.body.lastname; var phone =req.body.phone; var add = req.body.address; var add2 = req.body.address1; //var city = req.body.city; //var state = req.body.state; var data = { "email":email, "password":<PASSWORD>, "firstname": name, //"lastname": lastname, "phone":phone , "add":add, "add2":add2, //"city":city, //"state":state } db.collection('details').insertOne(data,function(err, collection){ if (err) throw err; console.log("Record inserted Successfully"); }); return res.redirect('signup_success.html'); }) app.get('/',function(req,res){ res.sendFile('index.html'); }); /*app.get('/registration1',function(req,res){ res.sendFile(path.join(__dirname,'./public','/registration1.html')); }); app.get('/registration2',function(req,res){ res.sendFile(path.join(__dirname,'./public','/registration2.html')); });*/ app.get('/registration',function(req,res){ res.sendFile(path.join(__dirname,'./public','/registration.html')); }); app.get('/Home',function(req,res){ res.sendFile(path.join(__dirname,'./public','/Home.html')); }); app.listen(8000, function(err) { if(!err) { console.log("app is running at 8000"); } });
8f842b7feb0f2219ca05ce92de8d9b012c5d34a5
[ "JavaScript" ]
1
JavaScript
aartisharma-pa/E-Commerce-Project
3401eb6a3e93722ca11d9da225a48d2d62cf4514
699a37475e12cd1ece5d6156ed479c446221173d
refs/heads/master
<repo_name>Forif-PythonClass/Assignments<file_sep>/Bojung/2강/예제2_coffee machine.py # coffee machine coffee = 5 while coffee != 0 : print 'Hello! How much do you have?' money = raw_input() if int(money) == 300 : print 'Here is your coffee.' coffee = coffee -1 elif int(money) > 300 : print 'Here is your coffee.' coffee = coffee - 1 print 'Here is your change, %d won. ' % (int(money)-300) elif int(money) < 300 : print 'Your money is not enough. Here is your change, %d won. ' % int(money) print "Today's coffee is done." <file_sep>/Bojung/1강/1_9 turtle.py import turtle # square turtle.pendown() turtle.begin_fill() turtle.color('red') turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.end_fill() turtle.penup() turtle.left(300) # hexagon turtle.pendown() turtle.color('green') turtle.begin_fill() turtle.forward(40) turtle.left(60) turtle.forward(40) turtle.left(60) turtle.forward(40) turtle.left(60) turtle.forward(40) turtle.left(60) turtle.forward(40) turtle.left(60) turtle.forward(40) turtle.penup() turtle.left(30) turtle.forward(100) turtle.end_fill() # circle turtle.pendown() turtle.begin_fill() turtle.color('blue') turtle.circle(50) turtle.end_fill() turtle.done() <file_sep>/Sangjin/HW2/2-11.py arr=[] for i in range (0,50): if i==0 or i==1: arr.append(1) else: arr.append(arr[i-1]+arr[i-2]) print (arr) <file_sep>/Bojung/1강/1_7 add list.py a=[38,5,6,72,1,99] b=[3,9,4,2,70,1] c = a + b c.sort(key=None,reverse=False) print c c.sort(key=int,reverse=False) print c c.sort(key=str,reverse=False) print c # int면 숫자로, str이면 문자로 (앞자리부터) <file_sep>/Bojung/2강/2_14 count numbers.py num = '101112131415' print 'We have ' + str(num.count('0')) + ' 0s.' print 'We have ' + str(num.count('1')) + ' 1s.' print 'We have ' + str(num.count('2')) + ' 2s.' print 'We have ' + str(num.count('3')) + ' 3s.' print 'We have ' + str(num.count('4')) + ' 4s.' print 'We have ' + str(num.count('5')) + ' 5s.' <file_sep>/Sangjin/HW2/2-1.py a=int(input("a:")) b=int(input("b:")) if (a%2)==0: print ("a는 짝수입니다.\n") else: print ("a는 홀수입니다.\n") if (b%2)==0: print ("b는 짝수입니다.\n") else: print ("b는 홀수입니다.\n") <file_sep>/Sangjin/HW2/2-9.py for i in range (0,4): print("*"*(i+1)) index=3; for i in range (0,3): print ("*"*index) index=index-1 <file_sep>/Bojung/1강/1_6 list functions.py a=[1,2,3,4,5,6,7,8,9] b=[2,4,8,10] c=[1,3,5,7,9,10] print a, b, c a.append(10) b.insert(2, 6) c.remove(10) print a,b,c a2 = a.count(2) a3 = a.count(3) b2 = b.count(2) b3 = b.count(3) c2 = c.count(2) c3 = c.count(3) print 'There are %d 2s and %d 3s in list a.'%(a2, a3) print 'There are %d 2s and %d 3s in list b.'%(b2, b3) print 'There are %d 2s and %d 3s in list c.'%(c2, c3) <file_sep>/Bojung/2강/2_13 drink shop.py money = 0 while money < 10000 : print '--OPEN--' print '''What do you want? We have 1. Coke, 2. Juice, 3. Energy Drink.''' beverage = int(raw_input()) if beverage == 1 : money = money + 1500 print 'Here is your coke.' elif beverage == 2 : money = money + 1200 print 'Here is your juice.' elif beverage == 3 : money = money + 2000 print 'Here is your energy drink.' print '--CLOSED--' <file_sep>/Bojung/2강/2_10 temperature.py print 'Write down the temperature that you want to change.(e.g. 60F, 108C)' temp = raw_input() if temp[-1] == 'C' : print str(float(temp[0 : -1]) / 5 *9 +32) +'F' if temp[-1] == 'F' : print str((float(temp[0 : -1]) -32) / 9 *5) +'C' <file_sep>/Bojung/1강/1_1 star.py print 'Twinkle, twinkle, little star,' print '\t How I wonder what you are!' print '\t \t Up above the world so high,' print '\t \t Like a diamond in the sky.' print 'Twinkle, twinkle, little star,' print '\t How I wonder what you are' <file_sep>/Taewook/Readme.md My name is <NAME>. I study Computer Science and Engineering at Hanyang university, Seoul. I am a member of the web & application developing club of Hanyang University. I am studying Python currently. I save all I have done in the club to this Forif repository. Thank you. Here I put my friends’ github URL. <NAME> : https://github.com/rlrlaa123/forif-python-assignment <br> <NAME> : https://github.com/hn04147/FORIF <br> Kim Sungik : https://github.com/kpic5014/FORIF <br> Kim Bojung : https://github.com/Bojung0125/ULTRA-PYTHON <br> Song Wonbin : https://github.com/swb970728/ForifPython <br> Kim Hyunwoo : https://github.com/howcanigetyourmind/howcanigetyourheart.git <br> Han Hyungseo : https://github.com/SHORELINESQUARE/TEST <br> <file_sep>/Sangjin/HW2/2-8.py import random target_num=int(random.randint(1,10)) while (1): num=int(input("숫자를 입력하시오: ")) if num==target_num: print ("Good") break; else: print("Try Again") <file_sep>/Bojung/3강/예제1 oddoreven.py def iseven(num) : if int(num)%2 == 0 : print('even') else : print('odd') num = raw_input() iseven(num) <file_sep>/Bojung/2강/2_4 list addition.py num = 0 add = 0 sum_list = [1,2,-20] while num <= 2 : add = add + int(sum_list[num]) num = num + 1 print 'The sum of the list is ' + str(add) <file_sep>/Sangjin/HW2/2-3.py name=input("name: ") age=int(input("age: ")) print("{} will be 100 after {}years".format(name,100-age)) <file_sep>/Bojung/2강/2_7 7 and 5.py a = 1500 num = [] while a <= 2700 : num = num + [a] a = a+1 answer = [] for i in num : if i % 7 == 0 : if i % 5 == 0 : answer = answer + [i] print answer <file_sep>/Bojung/2강/예제1.py import random ranNum = random.randint(1,9) print 'Hi! Please guess the number (1~9)' playerNum= raw_input() while str(ranNum) != playerNum : print 'Try again please.' playerNum = raw_input() print 'Great Job!' <file_sep>/Sangjin/HW2/2-10.py string=input("input: ") num=int(string[:-1]) if (string[-1]=='F'): print("{} = {}C".format(string,(num-32)*5/9)) elif (string[-1]=='C'): print("{} = {}F'".format(string,num*9/5+32)) <file_sep>/Sangjin/HW2/2-5.py a=['abc','xyz','aba','1221'] index=0; for i in range (0,4): if a[i][0]==a[i][-1]: index=index+1 print (index) <file_sep>/Bojung/2강/2_12 vowel consonant.py word = raw_input() if word in 'aeiou' : print "It's vowel." else : print "It's consonant." <file_sep>/Sangjin/HW2/2-13.py money=0 coke=0 juice=0 energydrink=0 while(money<10000): menu = input() if menu=="coke": money=money+1500 coke=coke+1 elif menu=="juice": money=money+1200 juice=juice+1 elif menu == "energy drink": money = money + 2000 energydrink=energydrink+1 print("총 :{}원\nCoke {}개\nJuice {}개\nEnergy Drink {}개\n".format(money,coke,juice,energydrink)) <file_sep>/Sangjin/HW2/2-7.py for i in range (1500,2701): if (i%7==0 and i%5==0): print (i,", ") <file_sep>/Bojung/1강/1_2 name.py print '<Input> \n Input first name : ', name = raw_input() print ' Input last name : ', lastname = raw_input() print '<Output> \n Your name is %s %s.'%(lastname, name) # TypeError: 'str' object is not callable <file_sep>/Bojung/1강/1_4 addition.py a = '10,11,12,13,14,15' start = 0 end = 2 add = 0 while end <= (len(a) +1) : add = add + int(a[start : end]) start = start + 3 end = end + 3 print add <file_sep>/Sangjin/HW2/2-4.py sum_list=[1,2,-20] sum=0 for i in range (0,3): sum=sum+sum_list[i] print("sum: ",sum) <file_sep>/Bojung/1강/1_3 확장자.py print 'File name : ', name = raw_input() start = name.find('.') print name [int(start)+1 : len(name)] <file_sep>/Bojung/2강/2_6 remove same things.py dup_list = [10,20,30,20,10,50,60,40,80,50,40] for i in dup_list : if dup_list.count(i) >=2 : dup_list.remove(i) print dup_list <file_sep>/Sangjin/HW4/2.py class string_: string = "" def __init__(self): self.string="" def get_String(self): self.string=input("input string:") def print_String(self): print ((self.string).upper()) _string_=string_() _string_.get_String() _string_.print_String() <file_sep>/Bojung/2강/2_8 guess the number.py # Guess the number game import random number = random.randint(1,10) print ("Take a guess between number 1 to 10.") guess = '' while guess != number : guess = raw_input() guess = int(guess) if guess != number : print 'Please try again.' if guess == number : break print 'Great job! The answer was %d' %(number) <file_sep>/Sangjin/HW3/3/3.py def merge_(text): size=len(text) textfilename="연락처.txt" f_=open(textfilename,'w') for i in range (0,size): f=open(text[i],'r') line=f.readline() f.close() f_.write(line) f_.write("\n") f_.close() print("새 파일 생성") text=[] print("종료하려면 n 임력") while(1): text_ = str(input("이름: ")) if (text_!='n'): _text_="C:/Users/<NAME>/Desktop/github/HW3/3/"+text_+".txt" text.append(_text_) elif (text_=='n'): break; merge_(text) <file_sep>/Bojung/피해라! 미세먼지_완성/main_dust_game.py # 1 - Import library import pygame import time import random import sys from pygame.locals import * # 2 - Initialize the game pygame.init() screen=pygame.display.set_mode((640, 480)) keys = [False, False, False, False] pygame.display.set_caption('We need clean air') black = (0,0,0) white = (255,255,255) red = (255,25,25) # About Frame clock = pygame.time.Clock() FRAMES_PER_SECOND = 10 playerpos=[100,100] # About timer font = pygame.font.Font(None, 38) t0=pygame.time.get_ticks() #About dust dustnum = 2 dustpos=[[random.uniform(0,640),random.uniform(0,320)] for i in range(dustnum)] # 3 - Load images background = pygame.image.load("resources/background.jpg").convert() player = pygame.image.load("resources/metamon.png") clock1 = pygame.image.load("resources/clock.png") Clock = pygame.transform.scale(clock1,(55,55)) dust = pygame.image.load("resources/dust.png") Win = pygame.image.load("resources/win.png") win = pygame.transform.scale(Win,(600,350)) GG = pygame.image.load("resources/gameover.png") gg = pygame.transform.scale(GG,(500,270)) # 3.1 - Load audio fail = pygame.mixer.Sound("resources/gamefail.wav") success = pygame.mixer.Sound("resources/gamesuccess.wav") fail.set_volume(1) success.set_volume(1) pygame.mixer.music.load("resources/bgm.mp3") pygame.mixer.music.play(-1, 0.0) pygame.mixer.music.set_volume(0.15) # 4 - keep looping through running = 1 exitcode = 0 while running: # 5 - clear the screen before drawing it again screen.fill((255,255,255)) clock.tick(FRAMES_PER_SECOND) # 6 - draw the screen elements screen.blit(background,(0,0)) screen.blit(player,playerpos) screen.blit(Clock,[575,10]) # 6.1 - timer t1=pygame.time.get_ticks() seconds=int(60-(t1-t0)/1000) if seconds<0: seconds=0 t0=t1 text=font.render(str(seconds),True,(0,0,0)) screen.blit(text,[587,27]) # 6.3 - Dust for pos in dustpos: screen.blit(dust,pos) for move in dustpos: move[0]+=random.uniform(-50,50) move[1]+=random.uniform(-50,50) for check in dustpos: if check[0] >= 620 : while check[0] >= 620 : check[0]-=30 if check[0] <= 0 : while check[0] <= 0 : check[0]+=30 if check[1] >= 450 : while check[1] >= 450 : check[1]-=20 if check[1] <= 0 : while check[1] <= 0 : check[1]+=20 # 7 - update the screen pygame.display.flip() # 8 - loop through the events for event in pygame.event.get(): if event.type== QUIT or (event.type ==KEYDOWN and event.key == K_ESCAPE): pygame.quit() exit(0) if event.type == pygame.KEYDOWN: if event.key==K_UP: keys[0]=True if event.key==K_DOWN: keys[1]=True if event.key==K_LEFT: keys[2]=True if event.key==K_RIGHT: keys[3]=True if event.type == pygame.KEYUP: if event.key==pygame.K_UP: keys[0]=False if event.key==pygame.K_DOWN: keys[1]=False if event.key==pygame.K_LEFT: keys[2]=False if event.key==pygame.K_RIGHT: keys[3]=False # 9 - Move player if keys[0]: playerpos[1]-=25 elif keys[1]: playerpos[1]+=25 if keys[2]: playerpos[0]-=25 elif keys[3]: playerpos[0]+=25 if playerpos[0]<0: playerpos[0]+=25 elif playerpos[0]>620: playerpos[0]-=25 if playerpos[1]<0: playerpos[1]+=25 elif playerpos[1]>450: playerpos[1]-=25 # 10 - Collision playerrect=pygame.Rect(player.get_rect()) playerrect.left=playerpos[0] playerrect.top=playerpos[1] for d_rect in dustpos: dustrect=pygame.Rect(dust.get_rect()) dustrect.left=d_rect[0] #height 조정 dustrect.top=d_rect[1] if dustrect.colliderect(playerrect): exitcode = 1 running = 0 #11 - Win/Lose check 60초 지나면 클리어 if pygame.time.get_ticks()>=60000: running=0 #60초가 지나면 #4의 running의 값을 0으로 바꿔줍니다. exitcode=0 if exitcode == 1:#exitcode가 1인 경우는 먼지와 플레이어가 부딪혔을때 게임오버를 표시하기위해서 설정했습니다. screen.blit(gg,(72,110)) pygame.mixer.music.stop() fail.play() elif exitcode==0: screen.blit(win,(30,70)) pygame.mixer.music.stop() success.play() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit(0) pygame.display.flip() <file_sep>/Bojung/2강/2_1 odd even.py print 'Type number.' a1 = raw_input() if int(a1) % 2 == 0 : print a1 + " is even number." else : print a1 + " is odd number." print 'Type second number.' a2 = raw_input() if int(a2) % 2 == 0 : print a2 + " is even number." else : print a2 + " is odd number." <file_sep>/Sangjin/HW3/2.py def print_even_number(list): result=[] for i in range (0,len(list)): if (list[i]%2==0): result.append(list[i]) return result; samplelist=[1,2,3,4,5,6,7,8,9] print(print_even_number(samplelist)) <file_sep>/Bojung/2강/2_5 length.py a = ['abc', 'xyz', 'aba', '1221'] for i in a : if len(i) >= 2 : if i[0] == i[-1] : print i <file_sep>/Bojung/2강/예제3_odd numbers.py # odd numbers num = 1 while num <= 10 : if num % 2 == 1: print num num = num + 1 else : num = num + 1 <file_sep>/Bojung/3강/예제2 function.py def comparelist(a,b) : c = [] for i in a : if i in b : c = c + [i] print c comparelist([1,2],[1]) <file_sep>/Sangjin/HW4/1.py class Point: def __init__(self,x_,y_): self.x=x_ self.y=y_ def setx(self,x_): self.x=x_ def sety(self,y_): self.y=y_ def move(self,dx,dy): self.x=self.x+dx self.y=self.y+dy def get(self): return (self.x,self.y) point=Point(1,2) point.setx(3) point.sety(4) point.move(2,3) print(point.get()) <file_sep>/Sangjin/HW2/2-12.py alp=input() if (alp=='a'or alp=='e'or alp=='i'or alp=='o'or alp=='u'): print ("모음입니다."); else: print ("자음입니다.") <file_sep>/Sangjin/HW2/2-6.py dup_list = [10,20,30,20,10,50,60,40,80,50,40] dup_list_ = [10,20,30,20,10,50,60,40,80,50,40] for i in range (0,10): for j in range (i+1,11): if (dup_list[i] == dup_list[j]): dup_list_.remove(dup_list[i]) dup_list_.remove (dup_list[j]) print (dup_list_) <file_sep>/Bojung/2강/2_3 100 yrs old.py print 'What is your name?' name = raw_input() print 'How old are you?' age = raw_input() age = int(age) print '%s will become 100 yrs old in %d years.' % (name, (100-age)) <file_sep>/Bojung/6강/Rocket and Alien.py # 1 - Import library import pygame from pygame.locals import * # 2 - Initialize the game pygame.init() width, height = 640, 480 screen=pygame.display.set_mode((width, height)) keys = [False, False] rocketpos = [320, 400] alienpos = [320,10] bulletpos =[] alienRorL = True # true=right/false=left clock = pygame.time.Clock() FRAMES_PER_SECOND = 10 deltat = clock.tick(FRAMES_PER_SECOND) # 3 - Load images rocket = pygame.image.load("resources/image/rocket.png") alien = pygame.image.load("resources/image/alien.png") bullet = pygame.image.load("resources/image/bullet.png") # 4 - keep looping through while 1 : screen.fill(0) deltat screen.blit(alien,alienpos) screen.blit(rocket,rocketpos) pygame.display.flip() if alienRorL == True : if alienpos[0] < 620: alienpos[0] = alienpos[0] + .2 else : alienRorL = False if alienRorL == False : if alienpos[0] > 15 : alienpos[0] = alienpos[0] - .2 else : alienRorL = True for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit(0) if event.type == pygame.KEYDOWN: if event.key==K_RIGHT: keys[0]=True elif event.key==K_LEFT: keys[1]=True elif event.key==K_SPACE: if event.type == pygame.KEYUP: if event.key==pygame.K_RIGHT: keys[0]=False elif event.key==pygame.K_LEFT: keys[1]=False if keys[0]: rocketpos[0]+=.2 elif keys[1]: rocketpos[0]-=.2 <file_sep>/Bojung/2강/2_11 fibonacci.py a = 0; b = 1; while a <= 50: print a; c = a; a = b; b = c + b; <file_sep>/Bojung/2강/2_9 stars.py a = 1 while a <= 4 : print '*'*a a = a + 1 a = a-2 while a >= 1 : print '*'*a a = a - 1 <file_sep>/Sangjin/HW1/1주차과제.py import turtle while(1): a = int(input("Input -1 to break;\nInput the question number:")) if (a==1): print("Twinkle, twinkle, little star,\n\tHow I wonder what you are!") print("\t\tUp above the world so high,\n\t\tLike a diamond in the sky.") print("Twinkle, twinkle, little star,\n\tHow I wonder what you are") print("\n") elif (a==2): firstname=input("Input first name:") lastname=input("input last name:") print("Your name is {} {}".format(lastname,firstname)) print("\n") elif (a==3): filename=input("Sample filename:") filename_=filename[filename.find('.')+1:] print("Output:{}".format(filename_)) print("\n") elif (a==4): a="101112131415" total=0 for i in range(0,12): total=total+int(a[i:i+1]) print("sum=",total) print("\n") elif(a==5): color_list=["Red","Green","White","Black"] print("{},{}".format(color_list[0],color_list[1])) print("\n") elif(a==6): a=[1,2,3,4,5,6,7,8,9] b=[2,4,8,10] c=[1,3,5,7,9,10] a.append(10) b.insert(2,6) c.remove(10) print("a=",a) print("b=",b) print("c=",c) count2=a.count(2)+b.count(2)+c.count(2) count3=a.count(3)+b.count(3)+c.count(3) print("2:{} and 3:{}".format(count2,count3)) print("\n") elif(a==7): a=[38,5,6,72,1,99] b=[3,9,4,2,70,1] c=a+b c.sort() print("answer=",c) print("\n") elif(a==8): milk=2.50 icecream=1.2 energydrink=3.50 total=2*milk+5*icecream+energydrink if (total<20): print("거스름돈 = ",20-total) print("\n") elif(a==9): t=turtle t.penup() t.goto(-250,100) t.pendown() for i in range (0,6): t.forward(100) t.left(60) t.penup() t.goto(150,100) t.pendown() for i in range(0,3): t.forward(120) t.left(120) t.penup() t.goto(-250,-250) t.pendown() index=50 for i in range(0,5): for j in range(0,4): t.forward(index) t.left(90) index=index+20 t.penup() t.goto(150,-250) t.pendown() for i in range(0,3): for j in range(0,4): t.forward(100) t.left(90) t.left(30) t.done() print("\n") elif(a==10): t=turtle for i in range(0,20): t.circle(100) t.left(18) t.done() print("\n") elif(a==-1): break elif (a==11): index=1 for i in range (0,7): for j in range(0,index): print("*") if (index==4): index=index-1 else: index=index+1 print("\n") <file_sep>/Sangjin/HW3/1.py def times(list): result = 1; for i in range (0,len(list)): result=result*list[i] return result samplelist=[8,2,3,-1,7] print(times(samplelist)) <file_sep>/README.md ### Rules * Create your own directory and upload your homework. * Never push on other person's directory.
b2c480f843501b16aa04d0a13b3a866e8cf089d8
[ "Markdown", "Python" ]
47
Python
Forif-PythonClass/Assignments
2dd7750abc40109e9fb04d1e136d0a87848ed887
31dec7ccf2314ad8474c364b43ceabe8127db462
refs/heads/master
<file_sep>using SingletonTest.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace SingletonTest.Controllers { public class MessageController : Controller { Message CurrentMessage = Message.Instance; // GET: Message public ActionResult Index() => View(); public ActionResult ViewMessage() { ViewBag.MessageText = CurrentMessage.MessageText; return View(); } public ActionResult EditMessage() => View(); public ActionResult SetMessage(string text) { CurrentMessage.MessageText = text; ViewBag.MessageText = CurrentMessage.MessageText; return View(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SingletonTest.Models { public sealed class Message { public static Message Instance { get { if (instance == null) instance = new Message(); return instance; } } public string MessageText { get => messageText; set => messageText = value; } private static Message instance; private string messageText="Message text is not set"; private Message() { } } }
8251a5912541d112e393bcbd560d8630497519eb
[ "C#" ]
2
C#
p3cet/GitIntegrationTest
588be95ec5e3bf1cfaca3b0bf13c20de832c6ec1
f40a9eeeba065279a59d30d354dd4b810e3e99f3
refs/heads/master
<file_sep> <div class="page-content page-content--privacy"> <h1 class="page-content__main-title"><span>Privacy Policy</span></h1> <h2 class=""><span>How do we process data?</span></h2> <p>We use an ATS (Applicant Tracking System) called Bullhorn to manage all information (including salary details) as well as a secure Google Drive to handle our larger files such as portfolios. You can access their independent Privacy Policies here: </p> <ul> <li><a href="https://www.bullhorn.com/privacy/" target="_blank">Bullhorn</a></li> <li><a href="https://policies.google.com/privacy?hl=en-GB&gl=uk" target="_blank">Google Drive</a></li> </ul> <h2 class=""><span>How do we share your information?</span></h2> <p>We will only ever share your information with prospective clients with your permission. </p> <h2 class=""><span>How long do we keep your details?</span></h2> <p>We store your details on an ongoing basis unless you want us to remove you. This means we’re able to search your details and get in touch with prospective new roles for you. We thoroughly enjoy having long term relationships with the talent we work with and often that means it may be months or years between you needing our services.</p> <h2 class=""><span>How will we keep in touch?</span></h2> <p>If we have a suitable role for you, or we are interested in hearing about your recommendations then we will either call or email you regarding this.</p> <p>We also occasionally send out information about our #CreativeAchievers articles or the Events we’re hosting.</p> </div> <file_sep>function OnRun($rootScope, AppSettings, PostsService, PagesService, $timeout, HelperService) { 'ngInject'; // // On initial run, get initial App data // PostsService.get(); PagesService.get(); // // function to render page with or without animation depending on last used // const endAnimation = () => { $timeout(function() { $rootScope.pageLoaded = 'page-loaded'; }, 1000); }; const renderPage = (animate) => { if (animate) { $rootScope.pageLoaded = 'animation-intro'; $timeout(function() { $rootScope.pageLoaded = 'animation-finishing'; $rootScope.$on('pagesReady', endAnimation); }, 3000); } else { $rootScope.pageLoaded = 'animation-short'; $rootScope.$on('pagesReady', endAnimation); } }; // // Check if last visit within 24 hours and call load with / without animation // if (HelperService.checkLocalStorage()) { const date = new Date(); const savedDate = Date.parse(localStorage.lastLoaded); const oneDay = 1000 * 60 * 60 * 24; if (!isNaN(savedDate)) { const interval = date - savedDate; if (interval > oneDay) { renderPage(true); localStorage.setItem('lastLoaded', date); } else { renderPage(false); } } else { renderPage(true); localStorage.setItem('lastLoaded', date); } } else { renderPage(false); } // // On State Change start - get the classes used to handle animations: // $rootScope.$on('$stateChangeStart', (event, toState, toParams, fromState) => { if (fromState.level) { $rootScope.prevPageLevel = fromState.level; } else { $rootScope.prevPageLevel = 'page'; } }); // // On State Change: // $rootScope.$on('$stateChangeSuccess', (event, toState) => { $timeout(function() { document.body.scrollTop = document.documentElement.scrollTop = 0; }, 500); // Send Analytics ga('send', 'pageview'); // jshint ignore:line // Set 'disable filter' used on Features (and child pages) $rootScope.disableFilter = toState.disableFilter; // Set page level if (toState.level) { $rootScope.pageLevel = toState.level; } else { $rootScope.pageLevel = ""; } // Set title $rootScope.pageTitle = ''; if (toState.title) { $rootScope.pageTitle += toState.title; $rootScope.pageTitle += ' \u2014 '; $rootScope.title = toState.title; } document.getElementsByClassName('ta-logo')[0].focus(); $rootScope.pageTitle += HelperService.serviceSkipValidation(AppSettings.appTitle); $rootScope.pageTitle = HelperService.serviceSkipValidation($rootScope.pageTitle); if ($rootScope.title !== "Home") { $rootScope.desktopMenuHidden = true; } else { $rootScope.desktopMenuHidden = false; } }); // // Toggle menu appearance // $rootScope.toggleMenu = () => { $rootScope.menuActive = !$rootScope.menuActive; return false; }; $rootScope.toggleDesktopMenu = () => { $rootScope.desktopMenuHidden = !$rootScope.desktopMenuHidden; return false; }; // // Set up submenu - TODO - move this into a service, or leverage the API to autogenerate // $rootScope.submenu = {}; $rootScope.submenu.features = [{ title: '#CreativeAchievers', slug: '/features/creativeachievers' }, { title: 'Advice', slug: '/features/advice' }, { title: 'Events', slug: '/features/events' }]; $rootScope.submenu.about = [{ title: 'Who we are', slug: '/about/who-we-are' }, { title: 'What we do', slug: '/about/what-we-do' }, { title: 'The specifics', slug: '/about/the-specifics' }]; } export default OnRun;<file_sep>function OnConfig($stateProvider, $locationProvider, $urlRouterProvider) { 'ngInject'; $locationProvider.html5Mode(true); $stateProvider .state('Home', { url: '/', controller: 'PageCtrl as page', templateUrl: 'home.html', title: 'Home' }) .state('Contact', { url: '/contact', controller: 'PageCtrl as page', templateUrl: 'contact.html', title: 'Contact' }) .state('PrivacyPolicy', { url: '/privacy-policy', controller: 'PageCtrl as page', templateUrl: 'privacy-policy.html', title: 'Privacy Policy' }) .state('Features', { url: '/features', disableFilter: true, controller: 'PostCtrl as page', templateUrl: 'news.html', title: 'Features' }) .state('CreativeAchievers', { url: '/features/creativeachievers', controller: 'PostCtrl as page', templateUrl: 'news.html', title: '#CreativeAchievers' }) .state('Advice', { url: '/features/advice', controller: 'PostCtrl as page', templateUrl: 'news.html', title: 'Advice' }) .state('Events', { url: '/features/events', controller: 'PostCtrl as page', templateUrl: 'news.html', title: 'Events' }) .state('Post', { url: '/news/:postSlug', controller: 'ArticleCtrl as page', templateUrl: 'post.html', level: 'sub-page' }); $urlRouterProvider.otherwise('/'); } export default OnConfig; <file_sep># Talent Atelier http://www.talentatelier.com Built as an AngularJs (1.x) SPA, consuming data from Wordpress RestAPI. ### Getting up and running 1. Clone this repo 2. Run `npm install` from the root directory 3. Run `gulp dev` 4. Your browser will automatically be opened and directed to the browser-sync proxy address 5. To prepare assets for production, run the `gulp prod` task (Note: the production task does not fire up the express server, and won't provide you with browser-sync's live reloading. Simply use `gulp dev` during development. More information below) Now that `gulp dev` is running, the server is up as well and serving files from the `/build` directory. Any changes in the `/app` directory will be automatically processed by Gulp and the changes will be injected to any open browsers pointed at the proxy address. <file_sep>// FINISH THIS: http://stefanimhoff.de/2014/gulp-tutorial-13-revisioning/ import config from '../config'; import gulp from 'gulp'; import rev from 'gulp-rev'; import collect from 'gulp-rev-collector'; gulp.task('rev', function () { global.isProd = true; return gulp.src(config.revision.src.path, {base: config.revision.src.base}) .pipe(rev()) .pipe(gulp.dest(config.revision.dest.path)) .pipe(rev.manifest({ path: config.revision.dest.manifest.name })) .pipe(gulp.dest(config.revision.dest.manifest.path)); }); gulp.task('rev:collect', function() { global.isProd = true; return gulp.src(config.collect.src) .pipe(collect({ revSuffix: '-[0-9a-f]{8,10}-?' })) .pipe(gulp.dest(config.collect.dest)); }); <file_sep>function Navigation() { return { restrict: "E", templateUrl: 'directives/navigation.html' }; } export default { name: 'navigation', fn: Navigation };<file_sep>function Submenu() { return { restrict: 'E', templateUrl: 'directives/submenu.html', scope: { submenuItems: '=', submenuTitle: '@' }, link: function ($scope) { $scope.hideSubMenu = true; $scope.$watch('hideSubMenu', function() { if (!$scope.hideSubMenu) { $scope.iconText = '-'; } else { $scope.iconText = '+'; } }); } }; } export default { name: 'submenu', fn: Submenu }; <file_sep><?php /* Plugin Name: Talent Atelier Functions Plugin URI: http://talentatelier.com/ Description: Functions needed for the TA site Version: 1.0 Author: <NAME> Author URI: http://talentatelier.com/ License: GPL */ // To make the customer underline on headers work, we need a span within each: function add_content_after_h2($content){ $content = preg_replace('/(<h2>)/i', '<h2><span>', $content); $content = preg_replace('/(<\/h2>)/i', '</h2></span>', $content); return $content; } add_filter('the_content', 'add_content_after_h2'); // Remove the 'Continue Reading' text function new_excerpt_more($more) { global $post; return '...'; } add_filter('excerpt_more', 'new_excerpt_more');<file_sep>function ArticleService($http, AppSettings) { 'ngInject'; const service = {}; service.post = {}; service.get = function(slug) { const endPoint = AppSettings.apiUrl + 'get_post&post_slug=' + slug; return $http.get(endPoint) .then(function(result) { service.post = result.data.post; return service.post; }); }; return service; } export default { name: 'ArticleService', fn: ArticleService }; <file_sep>function ArticleCtrl(ArticleService, PostsService, HelperService, $sce, $scope, $rootScope, $stateParams, $filter) { 'ngInject'; // This controller needs to have logic to check for the current post // // 1. Check the PostData JSON object for article and display if it exists // 2. Query the endpoint for the article if it does not // ViewModel const vm = this; // VM properties vm.postData = PostsService.posts; vm.cssClass = $rootScope.title; vm.currentPost = {}; // Find current article const checkJSONForArticle = (slug) => { return $filter('filter')(vm.postData, {slug: slug})[0]; }; // Get single post vm.findPost = () => { vm.currentPost = checkJSONForArticle($stateParams.postSlug); if (!vm.currentPost) { ArticleService.get($stateParams.postSlug) .then(function(response){ vm.currentPost = response; }); } $rootScope.meta = vm.currentPost.excerpt.rendered; $rootScope.pageTitle = 'Talent Atelier: ' + vm.currentPost.title.rendered; // TODO Set the title here and then // if not found $location.path('/'); }; // Init vm.refreshPosts = () => { vm.postData = PostsService.posts; if (vm.postData.length > 0) { vm.findPost(); } }; if (vm.postData.length > 0) { vm.findPost(); } $scope.$on('postsReady', vm.refreshPosts); // Trust HTML helper function vm.trust = (text) => { return HelperService.serviceSkipValidation(text); }; } export default { name: 'ArticleCtrl', fn: ArticleCtrl }; <file_sep>function Accordion() { return { restrict: 'E', templateUrl: 'directives/accordion.html', scope: { title: '=', content: '=', showContent: '=' }, link: function($scope) { $scope.expand = $scope.showContent; var toggleIcon = () => { if ($scope.expand) { $scope.iconText = "-"; $scope.showHideText = "Hide section"; } else { $scope.iconText = "+"; $scope.showHideText = "Show section"; } }; toggleIcon(); $scope.toggleAccordion = () => { $scope.expand = !$scope.expand; toggleIcon(); }; } }; } export default { name: 'accordion', fn: Accordion }; <file_sep>function PagesService($http, AppSettings, $timeout, $rootScope) { 'ngInject'; const service = { pages: {} }; const config = { timeout: AppSettings.apiTimeout }; const endPoint = AppSettings.apiUrl + 'pages/'; let counter = 0; service.get = function() { return $http.get(endPoint, config) .then( function(result) { result.data.map((post) => service.pages[post.slug] = post ); $timeout(function(){ $rootScope.$broadcast('pagesReady', null); }, 0); return service.pages; }, function(){ counter++; if (counter < 4) { service.get(); } else { console.error('Maximum retries exceeded'); } }); }; return service; } export default { name: 'PagesService', fn: PagesService };
e8245fa2f239f7be8c6be002c50e193075f88921
[ "JavaScript", "PHP", "HTML", "Markdown" ]
12
HTML
slaywell/talent_atelier
cd17a6ff7cc85efc48dbd5c25f81f05153ef5dac
af154f1dcfbdc1def0b60fe20a0ccddee6d01c93
refs/heads/master
<file_sep>class User < ApplicationRecord belongs_to :message has_one :role end <file_sep>class MessageController < ApplicationController end<file_sep>class Message < ApplicationRecord has_one :user end <file_sep>class RoleController < ApplicationController end
a7f7a654275d7af89257443c6eae97a5c4a79c3e
[ "Ruby" ]
4
Ruby
DanPetrov1/FirstRailsProject
31a68ed071d279e086ec0bbc86673b7619b8d129
7e9312e74b3c35f627f098644d99ffdf6c73050b
refs/heads/master
<file_sep>print("Hello world.") print("Joop") x = "5.23" x = float(x) print(type(x), x+5)
78fd934a7b01390cd930d28114650b977567f2f4
[ "Python" ]
1
Python
Kanomjang/Learning-Python
2164aeceb7b4bf4394d3760b5f223b95d7272191
f3b3cb3864fb053bfb409f5e1d5c9094ceb68680
refs/heads/master
<repo_name>asuishi/myeslint<file_sep>/test/brace-style.test.js /** * Tests for brace-style rule. */ //------------------------------------------------------------------------------ // Constants //------------------------------------------------------------------------------ const RULE_ID = "brace-style" const myeslint = require('../lib/myeslint') //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ test(`test "${RULE_ID}" function with error`, () => { const code = "function f() \n {}" const config = { rules: {} }; config.rules[RULE_ID] = 1; myeslint.verify(code, config); const messages = myeslint.messages expect(messages.length).toBe(1) expect(messages[0].ruleId).toBe(RULE_ID) expect(messages[0].message).toBe("Opening curly brace does not appear on the same line as the block identifier.") expect(messages[0].node.type).toBe("FunctionDeclaration") }) test(`test "${RULE_ID}" function without error`, () => { const code = "function f() {}" const config = { rules: {} }; config.rules[RULE_ID] = 1; myeslint.verify(code, config); const messages = myeslint.messages expect(messages.length).toBe(0) }) test(`test "${RULE_ID}" for with error`, () => { const code = "for(var i=0;i<2;i++) \n {}" const config = { rules: {} }; config.rules[RULE_ID] = 1; myeslint.verify(code, config); const messages = myeslint.messages expect(messages.length).toBe(1) expect(messages[0].ruleId).toBe(RULE_ID) expect(messages[0].message).toBe("Opening curly brace does not appear on the same line as the block identifier.") expect(messages[0].node.type).toBe("ForStatement") }) test(`test "${RULE_ID}" for without error`, () => { const code = "for(var i=0;i<2;i++) {}" const config = { rules: {} }; config.rules[RULE_ID] = 1; myeslint.verify(code, config); const messages = myeslint.messages expect(messages.length).toBe(0) }) <file_sep>/lib/myeslint.js let esprima = require("esprima") let estraverse = require('estraverse'); let Events = require("events") let rules = require("./rules") let RuleContext = require('./ruleContext') class Myeslint extends Events { constructor () { super() this.messages = [] this.currentText = null this.currentConfig = null } reset () { this.messages = [] this.currentText = null this.currentConfig = null this.removeAllListeners() } verify (text, config, filename) { const self = this this.reset() this.currentText = text this.currentConfig = config Object.keys(config.rules).filter((key) => { return config.rules[key] > 0 }).forEach(key => { const rule = rules.getRule(key) if (rule) { const ruleResolve = rule(new RuleContext(key, this)); // 添加规则 Object.keys(ruleResolve).forEach((nodeType) => { self.on(nodeType, ruleResolve[nodeType]); }); } else { throw new Error("Definition for rule '" + key + "' was not found."); } }); var ast = esprima.parse(text, { loc: true, range: true }) estraverse.traverse(ast, { enter(node) { self.emit(node.type, node); } }); } report (ruleId, node, message) { this.messages.push({ ruleId: ruleId, node: node, message: message, }) } } module.exports = new Myeslint()<file_sep>/README.md ### 一个简单的ESLint ### 安装 ``` npm i myeslint -g ``` ### 使用 ``` myeslint test.js [test2.js] ``` ### 配置 同eslint配置 ``` { "rules": { "no-with": 1, "brace-style": 1, "eqeqeq": 1, "no-empty": 1 } } ``` 1: 表示开启; 0:表示关闭 > 支持自定义规则 ``` myeslint -c configfile test.js ``` ### 现有规则 现在一共四个规则 - no-with 不允许使用with - brace-style if,function,for 和 { 必须在同一行 - eqeqeq 使用===和!== 不允许使用==,!= - no-empty 不允许空块({}) ### 测试 ``` npm run test ```
6bf2dc28cb96b2a6824149b38664d2d90a3e5378
[ "JavaScript", "Markdown" ]
3
JavaScript
asuishi/myeslint
79e91d7edb60a89a1a93033a074d4258417b3b6c
b82e8904e218ce4ba11b459fab8262cb5b1b017c
refs/heads/master
<file_sep>from math import radians, cos, sin, asin, sqrt # Membaca text dari file, mengembalikan multi dimentional array persis seperti file.txt def bacaTextFile(x): f = open(x,'r') file = f.readlines() operand = [] #melakukan replace beberapa character seperti koma, titik, dan newline for lines in file: lines = lines.replace("\n"," ") operand.append(lines) opfinal = [] for lines in operand: lines = lines.split() opfinal.append(lines) return opfinal ### Membaca multidimensional array dari file yang dibaca, mengembalikan listofnode ### def listOfNode(x): starting = int(x[0][0]) node = [] for i in range(1,starting+1): node.append(x[i][0]) #append list node dari array input return node # Membuat dan mengembalikan array berbentuk list of tupple, # yang berisi tupple ketetanggaan atau edges dari graph def tetangga(x,listnode): matrix = [] starting = int(x[0][0]) for i in range(starting + 1, len(x)): for j in range(len(x[starting + 1])): if(int(x[i][j]) > 0): #append edge node pada matrix yang bertetangga apabila bernilai 1 matrix.append((listnode[i-(starting+1)],listnode[j])) return matrix # Membuat list of list of location dari masing2 node # def coordinates(x): matrix =[] temp = [] starting = int(x[0][0]) for i in range(1, starting+1): temp.append(x[i][1]) for loc in temp: loc = loc.replace('(',' ') loc = loc.replace(')',' ') loc = loc.replace(',',' ') matrix.append(loc) loc = [] for lines in matrix : lines = lines.split() loc.append(lines) return loc # Membaca elemen dari list of list of location, mengembalikan jarak dengan metode haversine # def jarak(latitudeA, longitudeA, latitudeB, longitudeB): longitudeA, latitudeA, longitudeB, latitudeB = map(radians, [longitudeA, latitudeA, longitudeB, latitudeB]) dlon = longitudeB - longitudeA dlat = latitudeB - latitudeA a = sin(dlat/2)**2 + cos(latitudeA) * cos(latitudeB) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 6371 * (1000) dist = round(c*r, 3) return dist # Membaca array pada bagian matrix ketetanggan, kemudian membuat matrix bobot yang berisikan # jarak yang dihitung dengan metode haversine formula antar simpul. def matrixJarak(arr, loc): matrix = [] starting = int(arr[0][0]) for i in range(starting+1, len(arr)): temp = [] for j in range(len(loc)): temp.append(jarak(float(loc[i-(starting+1)][0]), float(loc[i-(starting+1)][1]), float(loc[j][0]), float(loc[j][1]))) matrix.append(temp) return matrix # Membaca matrix ketetanggan, mengembalikan tetangga dari suatu node def getNeighbour(arrNeigh, node): matrix = [] for elmt in arrNeigh: if elmt[0] == node: matrix.append(elmt[1]) #mengappend tetangga dari node yang ada di input #berdasarkan array ketetanggaan return matrix # Menerima sebuah array dari listnode, kemudian mencari dan mengembalikan # indeks dari node yang dicari def getIdx(array, node): i = 0 found = False while(found == False and i < len(array)): if (array[i] == node): found = True else: i += 1 if (found == True): return i else: return -1 #mengembalikan -1 apabila node tidak ditemukan # Mengurutkan list tuple yang berisi node asal, node tujuan, berdasarkan jarak antara keduanya def sortingFn(fnCandidate): # algoritma selection short for i in range(len(fnCandidate)): min_idx = i for j in range(i+1, len(fnCandidate)): if float(fnCandidate[min_idx][1]) > float(fnCandidate[j][1]): min_idx = j fnCandidate[i], fnCandidate[min_idx] = fnCandidate[min_idx], fnCandidate[i] return fnCandidate # Mencari jalur terpendek dari node asal ke node tujuan # def closestPath(srcNode, destNode, arrNeigh, Distance, listNode): candidate = [] candidateNode = [srcNode] visited = [] destIdx = getIdx(listNode, destNode) #index node yang dituju if (srcNode == destNode): return [srcNode, 0] else : currentNode = srcNode predSrc = 0 first = True while (len(candidate) > 0 or first == True): first = False currNeighbour = getNeighbour(arrNeigh, currentNode) for node in currNeighbour: if (node not in candidateNode): pred = currentNode #menyimpan prenode currentCheck = node predIdx = getIdx(listNode,pred) #indeks prenode idx = getIdx(listNode, currentCheck) #indeks node yang sedang di cek srcToN = predSrc + float(Distance[idx][predIdx]) #gn nToDest = float(Distance[idx][destIdx]) #hn temp = srcToN + nToDest #fn candidate.append((currentCheck, temp, srcToN, currentNode)) candidate = sortingFn(candidate) #sorting list candidate berdasarkan fn #memastikan untuk tidak berenti iterasi ketika terdapat kasus dimana len(candidate) = 1 dan perlu dipop, #namun masih terdapat tetangga yang harus diiterasi dari current sehingga masih memenuhi syarat while if (len(getNeighbour(arrNeigh, currentNode)) > 0 and len(candidate) == 1): candidate.append(('',9999999999,0,'')) a = candidate.pop(0) #pop elemen pertama hasil sorting visited.append((a[3],a[0],a[1],a[2])) #append prenode,currnode,fn,gn candidateNode.append(a[0]) currentNode = a[0] predSrc = float(a[2]) finalMove = getMinFn(destNode, visited) if (str(finalMove[1]) == str(destNode)): path = derivate(destNode,srcNode,visited) return path else: print("jalur tidak ditemukan") return [] # Mencari node tujuan dari list tuple visited(yang sudah dikunjungi) berdasarkan # jarak terpendek mengembalikan 1 elemen dari visited def getMinFn(destNode,visited): min = 999999999 result = visited[0] for i in range (len(visited)): if (min > float(visited[i][2]) and visited[i][1] == destNode): min = float(visited[i][2]) result = visited[i] return result # menerima input destination dan sourcenode, serta visited, kemudian menelusuri # path dari destination node ke source node, dan mengembalikan list of tupple # yang berisi node, dan jarak yang ditempuh dari src node def derivate(destNode,srcNode,visited): path = [] nodeBacktrack = destNode destTuple = getMinFn(destNode, visited) #append terakhir found = False while (found == False): for i in range(len(visited)): if (nodeBacktrack == visited[i][1]): path.append((destTuple[1],destTuple[3])) nodeBacktrack = destTuple[0] #backtrack mundur destNode = destTuple[0] if(destTuple[0] == srcNode): if(srcNode not in path): path.append((srcNode, 0)) found = True #berhenti loop destTuple = getMinFn(destNode, visited) path.reverse() #reverse list hasil append return path<file_sep>import { useState, useRef, useEffect } from "react"; import { Grid, InputLabel, Select, MenuItem, Card, CardContent, CardHeader, FormControl, IconButton, Button, Tabs, Tab, Paper, Typography, TableCell, TableBody, TableRow, TableHead, Table, } from "@material-ui/core"; import { useTheme } from "@material-ui/core/styles"; import SwipeableViews from "react-swipeable-views"; import TabPanel from "./TabPanel"; import { DirectionsSharp, BubbleChartSharp, ShowChartSharp, VisibilitySharp, VisibilityOffSharp, } from "@material-ui/icons"; import readFileRequest from "../helper/fileRequests"; import getPathRequest from "../helper/pathRequest"; const Form = ({ state, setter }) => { const [start, setStart] = useState(); const [end, setEnd] = useState(); const [value, setValue] = useState(0); const fileRef = useRef(); const theme = useTheme(); const handleFile = async () => { const file = fileRef.current.files[0]; const data = await readFileRequest(file); console.log(data); setter.setNodes(data.nodes); setter.setLines(data.neighbors); setter.setFilename(file.name); }; const findPath = async () => { if (start && end) { const data = await getPathRequest(state.filename, start, end); console.log(data); setter.setPaths(data.paths); } }; useEffect(() => { const pathNames = state.paths.map((path) => path.node); setter.setNodes( state.nodes.map((node) => pathNames.includes(node.name) ? { ...node, content: state.paths[pathNames.indexOf(node.name)].cost } : node ) ); }, [state.paths]); return ( <Grid container spacing={2} style={{ width: "100%", padding: 20 }}> <Grid item xs={12}> <Card elevation={3} alignContent="flex-start"> <CardHeader title="Pencarian Lintasan Terpendek" subheader="Sebuah implementasi algoritma A*" /> <CardContent> <Grid container spacing={3}> <Grid item xs={12} sm={4}> <FormControl style={{ width: "100%" }}> <InputLabel id="start-label">Source Node</InputLabel> <Select style={{ width: "100%" }} labelId="start-label" id="demo-simple-select" onChange={(e) => setStart(e.target.value)} > {state.nodes.map((node) => ( <MenuItem value={node.name}>{node.name}</MenuItem> ))} </Select> </FormControl> </Grid> <Grid item xs={12} sm={4}> <FormControl style={{ width: "100%" }}> <InputLabel id="end-label">Destination Node</InputLabel> <Select style={{ width: "100%" }} labelId="end-label" id="end" onChange={(e) => setEnd(e.target.value)} > {state.nodes.map((node) => ( <MenuItem value={node.name}>{node.name}</MenuItem> ))} </Select> </FormControl> </Grid> <Grid item xs={12} sm={4}> <FormControl> <Button style={{ marginTop: 10 }} variant="outlined" onClick={findPath} > Find Path </Button> </FormControl> </Grid> <Grid item xs={12} align="flex-start"> <input type="file" ref={fileRef} encType="multipart/form" onChange={handleFile} hidden /> <div style={{ display: "flex" }}> <Button variant="outlined" onClick={() => fileRef.current.click()} > load graph </Button> <Typography style={{ paddingLeft: 20, paddingTop: 10 }}> {state.filename === "" ? "No file selected" : state.filename} </Typography> </div> </Grid> </Grid> </CardContent> </Card> </Grid> <Grid item xs={12}> <Paper square elevation={3}> <Tabs value={value} indicatorColor="primary" textColor="primary" onChange={(e, val) => setValue(val)} aria-label="disabled tabs example" > <Tab icon={<DirectionsSharp />} label="Path" /> <Tab icon={<BubbleChartSharp />} label="Nodes" /> <Tab icon={<ShowChartSharp />} label="Edges" /> </Tabs> <SwipeableViews axis={theme.direction === "rtl" ? "x-reverse" : "x"} index={value} onChangeIndex={(index) => setValue(index)} > <TabPanel value={value} index={0} dir={theme.direction}> <Table aria-label="path-table"> <TableHead> <TableRow> <TableCell>Step </TableCell> <TableCell>Current Node</TableCell> <TableCell>Cumulative Cost (m)</TableCell> <TableCell>View</TableCell> </TableRow> </TableHead> <TableBody> {state.paths.map((path, index) => ( <TableRow key={index}> <TableCell>{index}</TableCell> <TableCell component="th" scope="row"> {path.node} </TableCell> <TableCell> {Math.round(path.cost * 1000) / 1000} </TableCell> <TableCell> <IconButton onClick={() => setter.setNodes( state.nodes.map((node) => node.name === path.node ? { ...node, showInfo: !node.showInfo } : node ) ) } > {state.nodes.filter( (node) => node.name === path.node )[0].showInfo ? ( <VisibilitySharp /> ) : ( <VisibilityOffSharp /> )} </IconButton> </TableCell> </TableRow> ))} </TableBody> </Table> </TabPanel> <TabPanel value={value} index={1} dir={theme.direction}> <Table aria-label="node-table"> <TableHead> <TableRow> <TableCell>No. </TableCell> <TableCell>Node Name</TableCell> <TableCell>Longitude (deg)</TableCell> <TableCell>Lattitude (deg)</TableCell> </TableRow> </TableHead> <TableBody> {state.nodes.map((node, index) => ( <TableRow key={index}> <TableCell>{index + 1}</TableCell> <TableCell component="th" scope="row"> {node.name} </TableCell> <TableCell>{node.position.lng}</TableCell> <TableCell>{node.position.lat}</TableCell> </TableRow> ))} </TableBody> </Table> </TabPanel> <TabPanel value={value} index={2} dir={theme.direction}> <Table aria-label="vertices-table"> <TableHead> <TableRow> <TableCell>No. </TableCell> <TableCell>Src. Node</TableCell> <TableCell>Dest. Node</TableCell> <TableCell>Est. Distance (m)</TableCell> </TableRow> </TableHead> <TableBody> {state.lines.map((line, index) => ( <TableRow key={index}> <TableCell>{index + 1}</TableCell> <TableCell component="th" scope="row"> {line.rel[0]} </TableCell> <TableCell>{line.rel[1]}</TableCell> <TableCell> {Math.round(line.distance * 1000) / 1000} </TableCell> </TableRow> ))} </TableBody> </Table> </TabPanel> </SwipeableViews> </Paper> </Grid> </Grid> ); }; export default Form; <file_sep>from astar import bacaTextFile, listOfNode, tetangga, coordinates, jarak, matrixJarak, getNeighbour, getIdx, sortingFn, closestPath, getMinFn, derivate from web import server import sys #apabila hanya menjalankan 'python main.py' pada terminal, maka akan dijalankan main python standar if len(sys.argv) == 1: filename = str(input("Masukkan nama file : ")) fileDir = "../test/" + x arr = bacaTextFile(fileDir) # ['A', 'B', 'C', 'D', ...] A,B,C,D,... adalah node listNode = listOfNode(arr) # [('A', 'B'), ('A', 'C'), ...] B tetangga A, C tetangga A arrNeigh = tetangga(arr, listNode) # [['1', '2'], ['2', '1'], ['1','1'], ...] elmt pertama adalah latitude, dan kedua adalah longitude loc = coordinates(arr) matrixDistance = matrixJarak(arr, loc) # 0 2 1 # 2 0 2 # 1 2 0 src = str(input("Masukkan node awal : ")) # A dest = str(input("Masukkan node tujuan : ")) # G # [('A', 0), ('B', 20.62), ('G', 159.84)], elmt kedua dari tuple dalam satuan meter jalan = closestPath(src, dest, arrNeigh, matrixDistance, listNode) print(jalan) # apabila pada terminal 'dijalankan python main.py gui' maka akan menjalankan GUI berupa # web lokal yang telah dibuat else: if sys.argv[1] == "gui": server.run(port=5000, debug=True) else: print("Invalid command, either run \"python3 main.py web\" or \"python3 main.py\"") <file_sep>from flask_cors import CORS from flask import Flask, request, send_from_directory from werkzeug.utils import secure_filename from astar import bacaTextFile, listOfNode, coordinates, matrixJarak, tetangga, closestPath import os server = Flask(__name__) CORS(server) @server.route("/") def index(): return send_from_directory(os.path.join("static", "html"), "index.html") @server.route("/read-file", methods=["POST"]) def read_file(): f = request.files["file"] f.save(os.path.join("uploads", secure_filename(f.filename))) arr = bacaTextFile(os.path.join("uploads", secure_filename(f.filename))) nodeArr = listOfNode(arr) neighArr = tetangga(arr, nodeArr) coordArr = coordinates(arr) distMatr = matrixJarak(arr, coordArr) nodeArrDict = [] for index, node in enumerate(nodeArr): nodeName = node[0] nodeDict = { "name": nodeName, "title": nodeName, "position": { "lng": float(coordArr[index][1]), "lat": float(coordArr[index][0]), } } nodeArrDict.append(nodeDict) neighArrDict = [] for index, neighbor in enumerate(neighArr): neighDict = { "rel": list(neighbor), "distance": float(distMatr[nodeArr.index(neighbor[0])][nodeArr.index(neighbor[1])]) } neighArrDict.append(neighDict) return {"nodes": nodeArrDict, "neighbors": neighArrDict} @server.route("/get-path", methods=["POST"]) def get_path(): req = request.json arr = bacaTextFile(os.path.join("uploads", req["filename"])) nodeArr = listOfNode(arr) neighArr = tetangga(arr, nodeArr) coordArr = coordinates(arr) distMatr = matrixJarak(arr, coordArr) path = closestPath(req["source"], req["destination"], neighArr, distMatr, nodeArr) retval = [] for p in path: retval.append({ "node": p[0], "cost": p[1] }) return {"paths": retval} <file_sep>const readFileRequest = async (file) => { const formData = new FormData(); formData.append("file", file); const response = await fetch("http://localhost:5000/read-file", { method: "POST", headers: { "Access-Control-Allow-Origin": "*", }, body: formData, }); const data = await response.json(); return data; }; export default readFileRequest; <file_sep>const getPathRequest = async (filename, source, destination) => { const response = await fetch("http://localhost:5000/get-path", { method: "POST", headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", }, body: JSON.stringify({ source, destination, filename, }), }); const data = await response.json(); return data; }; export default getPathRequest; <file_sep># Tugas Kecil 3 IF2122 Strategi Algoritma # Implementasi Algoritma A\* untuk Menentukan Lintasan Terpendek ## General Info Program dibuat untuk memenuhi Tugas Kecil Strategi Algoritma 3 yang dapat mencari jalur terpendek dari suatu simpul dengan melakukan penelusuran memanfaatkan algoritma A\* shortest path finding. ## Requirements 1. Python 2. Flask 3. Flask-cors 4. node.js 5. Package lain yang terdapat pada src/requrements.txt dan menginstallnya dengan memasukkan command 'pip install -r requirements.txt' pada terminal ## How to 1. Pada terminal, arahkan directory pada folder src 2. Ketik command 'python main.py gui' untuk menjalankan program dengan Google Maps API pada menggunakan browser. 3. Ketik command 'python main.py' untuk menjalankan program pada terminal 4. Pada browser, ketik 'localhost:5000' pada search form browser untuk mengakses local website 5. Klik button 'LOAD GRAPH' untuk memuat file input graf 6. Pilih node pada pada combo box 'Source Node' untuk node asal dan 'Destination Node' untuk node tujuan 7. Klik 'Find Path' untuk menemukan jalan tercepat dari 'Source Node' menuju 'Destination Node' 8. Clear pycache untuk memastikan program dapat membaca file input dengan baik. ## Program Info 1. Map atau satellite pada kiri atas digunakan merubah mode tampilan peta 2. Nodes menampilkan simpul beserta latitude dan longitude nya. 3. Edges menampilkan ketetanggaan antar simpul dan juga jaraknya. 4. Path menampilkan jalan tercepat dari 'Source Node' menuju 'Destination Node' dan total jarak yang ditempuh pada node tersebut, dan view digunakan untuk menampilkan informasi total jarak pada map. 5. Source code berada pada folder 'src' 6. Test case berada pada folder 'test' 7. Laporan berada pada folder 'doc' 8. Format file txt - Baris pertama merupakan jumlah node = N - Baris kedua hingga ke-N+1 merupakan nama node beserta lokasinya (latitude,longitude) - Baris ke-N+2 hingga baris ke-2N+1 merupakan matriks ketetanggaan ## Pembuat Program - <NAME> - 13519027 - <NAME> - 13519161 <file_sep>import React, { useEffect, useState } from "react"; import { Map, InfoWindow, Marker, Polyline, GoogleApiWrapper, } from "google-maps-react"; const MapContainer = ({ google, state, setter }) => { const bounds = new window.google.maps.LatLngBounds(); state.nodes.forEach((node) => bounds.extend(node.position)); useEffect(() => {}, [state.nodes]); return ( <Map google={google} initialCenter={{ lat: 25.36277778, lng: 49.56305556 }} zoom={20} style={{ height: "100%", width: "100%", }} bounds={bounds} containerStyle={{ height: "100%", width: "100%", }} zoomControlOptions={{ position: google.maps.ControlPosition.LEFT_CENTER, }} streetViewControlOptions={{ position: google.maps.ControlPosition.LEFT_TOP, }} fullscreenControl={false} > {state.nodes.map((node, index) => ( <Marker key={index} name={node.name} position={node.position} title={node.name} label={node.name} onClick={() => { setter.setNodes( state.nodes.map((n) => n.position === node.position ? { ...n, showInfo: true } : n ) ); }} /> ))} {state.nodes.map((node, index) => ( <InfoWindow key={index} position={{ ...node.position, lat: node.position.lat }} visible={node.showInfo} onClose={() => setter.setNodes( state.nodes.map((n) => n.position === node.position ? { ...n, showInfo: false } : n ) ) } > <h1>Node {node.name}</h1> <p> {typeof node.content !== "undefined" ? `Accumulated cost: ${Math.round(node.content * 1000) / 1000} m` : `At ${JSON.stringify(node.position)}`} </p> </InfoWindow> ))} {state.lines.map((line) => { return ( <Polyline path={state.nodes .filter( (node) => node.name === line.rel[0] || node.name === line.rel[1] ) .map((node) => node.position)} strokeColor="#FF0000" strokeOpacity={0.8} strokeWeight={1} /> ); })} {state.paths.length === 0 ? null : ( <Polyline path={state.paths.map( (path) => state.nodes.filter((node) => node.name === path.node)[0].position )} strokeColor="#000000" strokeOpacity={1} strokeWeight={3} /> )} </Map> ); }; export default GoogleApiWrapper({ apiKey: "<KEY>", })(MapContainer);
4a17bd15a5db34be728b812e082bffa4ecf5c2bc
[ "JavaScript", "Python", "Markdown" ]
8
Python
haikallf/Tucil3Stima
7ae5eba0fee5e5b7fb726388071f7394d5cacb9a
18546559f997617f1e8c2dedef6b235349331de4
refs/heads/main
<repo_name>Kennedy747/Embedded-Project<file_sep>/src/boardSupport.c /********************************************************** * STM32F439 Board Support Package * * Developed for the STM32 * * Author: Dr. <NAME> * * Source File * ***********************************************************/ #include <stdint.h> #include "stm32f439xx.h" #include "ioMapping.h" #include "boardSupport.h" #include "gpioControl.h" // Local function prototypes - These are all board specific. static void boardSupport_initGPIO(void); //******************************************************************************// // Function: boardSupport_init() // Input: // Output: // Description: Perform the basic board initialisation requests for the RMIT SOM // *****************************************************************************// void boardSupport_init() { // STM32F439II Daughter Board Configuration // The clocks for the various GPIO should be brought up here. boardSupport_initGPIO(); } //******************************************************************************// // Function: boardSupport_initGPIO() // Input: // Output: // Description: Perform the basic board initialisation requests for the RMIT SOM // *****************************************************************************// void boardSupport_initGPIO() { // Create an instance of the GPIO Configuration Struct. GPIO_Config portConfig; // The GPIO clocks for the power management have alredy been configured by the // RAM sub-system. For other GPIO and peripherals they will need to be enabled. // Configure PH4 as output - 1.2V rail. portConfig.port = GPIOH; portConfig.pin = Pin4; portConfig.mode = GPIO_Output; portConfig.pullUpDown = GPIO_No_Pull; portConfig.outputType = GPIO_Output_PushPull; portConfig.speed = GPIO_2MHz; // Configure the I/O Port. gpio_configureGPIO(&portConfig); // Enable the 1.2VA rail. gpio_setGPIO(GPIOH, Pin4); // Configure Port PH6 as output - 3.3V rail. portConfig.pin = Pin7; gpio_configureGPIO(&portConfig); gpio_setGPIO(GPIOH, Pin7); /*portConfig.port = GPIOG; portConfig.pin = Pin12; gpio_configureGPIO(&portConfig); gpio_setGPIO(GPIOG, Pin12); */ return; } //******************************************************************************// // Function: delay_software_ms() // Input: Delay time (in milliseconds) // Output: None // Description: Software driven delay loop. // *****************************************************************************// void delay_software_ms(uint32_t millisecondDelay) { // If optimisation is off, then the delay should be set at 14000 // In this function a basic software delay is utilised. uint32_t i = 0; for(i = 0; i < (millisecondDelay * 21000); i++); } //******************************************************************************// // Function: delay_software_us() // Input: Delay time (in microseconds) // Output: None // Description: Software driven delay loop. // *****************************************************************************// void delay_software_us( uint32_t usec ) { // To avoid delaying for less than usec, always round up.; uint32_t i = 0; for(i = 0; i < (usec * 21); i++); } <file_sep>/README.md # Embedded-Project ESD-I-Major-Project-Code <file_sep>/src/main.c /************************************************************************ * STM32F439 Main (C Startup File) * * Developed for the STM32 * * Author: Dr. <NAME>, <NAME>, <NAME> * * Source File * ************************************************************************/ #include <stdint.h> #include "boardSupport.h" #include "main.h" #include "stm32f439xx.h" #include "gpioControl.h" //Function Declarations ********************************************************// void init(void); void configureGPIOPins(void); void configureUSART(void); void configureADC1(void); void count1second(void); void transmitCharacter(uint8_t character); void transmitUSARTOutput(void); void usartReceivingControl(void); int8_t getCharacter(void); void decipherUSARTInput(void); void USARTFanOn(void); void USARTFanOff(void); void USARTLightOn(void); void USARTLightOff(void); void buttonCONTROL(void); void configureTIM7(void); void buttonCHECK(void); void setTIM7(int); void latchFAN(void); void latchLIGHT(void); void checkHUMIDITY(void); void triggerOUTPUTS(void); void incrementSimTimer5(void); void incrementSimTimer6(void); void incrementSimTimer7(void); // Global Variables ************************************************************// int fanStatus = 0; int lightStatus = 0; int16_t buttonState = -1; int8_t USARTLightOffStatus = -1; int8_t FanPressed = -1; int8_t LightPressed = -1; int8_t BothPressed = -1; //int8_t countVALUE = 0; //int16_t threeSecondCount = 0; int8_t lightIntensity = -1; int receivedCharacterCount = 0; int receivedCharacters[2]; int receivedCharacter = -1; int percentageHumidityValue = 0; int8_t HumidityFlag = -1; int8_t HumidityFlagPast = -1; uint16_t adcValue = 0; int8_t timer7Flag = 0; int8_t buttonValue = 0; int8_t timeOutFlag = 0; int ButtonBlock = -1; int8_t Humidity30secOFF = 0; //******************************************************************************// // Function: main() // Input : None // Return : None // Description : Entry point into the application. // *****************************************************************************// int main(void) { // Bring up the GPIO for the power regulators. boardSupport_init(); init(); while (1) { // Button Blocking Timer if((TIM5->SR & TIM_SR_UIF) == 1){ TIM5->CR1 &= ~(TIM_CR1_CEN); TIM5->SR &= ~(TIM_SR_UIF); ButtonBlock = -1; } // Checks for new usart3 input and ensures the header is received first. usartReceivingControl(); //buttonCONTROL & triggerOUTPUTS are copied from the working Just buttons project// //Checks the humidity value and determines the humidity % checkHUMIDITY(); //Always Checks Buttons buttonCONTROL(); //Latches outputs triggerOUTPUTS(); if((TIM6->SR & TIM_SR_UIF) == 1) { //Transmit Data transmitUSARTOutput(); // Restart timer TIM6->SR &= ~(TIM_SR_UIF); TIM6->CR1 |= TIM_CR1_CEN; } //Sim Timers incrementSimTimer6(); incrementSimTimer7(); incrementSimTimer5(); } } //******************************************************************************// // Function: uartReceivingControl() // Input : None // Return : None // Description : Assembles the received characters into an array and also recognises the header // *****************************************************************************// void usartReceivingControl() { receivedCharacter = -1; receivedCharacter = getCharacter(); if (receivedCharacter != -1){ if(receivedCharacterCount == 0 && receivedCharacter != '!'){ //do nothing }else{ receivedCharacters[receivedCharacterCount] = receivedCharacter; receivedCharacterCount++; } } if (receivedCharacterCount == 2){ if (receivedCharacters[1] != '!'){ decipherUSARTInput(); } receivedCharacterCount = 0; } } //******************************************************************************// // Function: getCharacter() // Input : None // Return : int8_t // Description : Determines the validity of a character // *****************************************************************************// int8_t getCharacter(void){ int8_t receivedCharacter = -1; int8_t validCharacter = -1; if(USART3->SR & USART_SR_RXNE){ receivedCharacter = USART3->DR; // Light On, Fan On = 12 // Light On, Fan Off = 8 // Light Off, Fan On = 4 // Light Off, Fan Off = 0 if(receivedCharacter == 12 || receivedCharacter == 8 || receivedCharacter == 4 || receivedCharacter == 0 || receivedCharacter == '!'){ validCharacter = 1; } // else if ((receivedCharacter == 0x0D) || (receivedCharacter == 0x0A)){ // validCharacter = 1; // } if (validCharacter == -1){ receivedCharacter = -1; } } return receivedCharacter; } //******************************************************************************// // Function: decipherUSARTInput() // Input : None // Return : None // Description : Transmits HMS information through USART. // *****************************************************************************// void decipherUSARTInput(){ // Light On, Fan On = 12 // Light On, Fan Off = 8 // Light Off, Fan On = 4 // Light Off, Fan Off = 0 switch(receivedCharacters[1]){ case 12: USARTLightOn(); USARTFanOn(); break; case 8: USARTLightOn(); USARTFanOff(); break; case 4: USARTLightOff(); USARTFanOn(); break; case 0: USARTLightOff(); USARTFanOff(); break; } } void USARTFanOn(void){ if(fanStatus == 1){return;} if(HumidityFlag == 1){return;} else { fanStatus = 1; } } void USARTFanOff(void){ if(fanStatus == 0){return;} if(HumidityFlag == 1){return;} else { fanStatus = 0; } } void USARTLightOn(void){ if(lightStatus == 1){return;} lightStatus = 1; ButtonBlock = 1; TIM5->CR1 |= TIM_CR1_CEN; } void USARTLightOff(void){ if(lightStatus == 0){return;} lightStatus = 0; ButtonBlock = 1; TIM5->CR1 |= TIM_CR1_CEN; } //******************************************************************************// // Function: transmitUSARTOutput() // Input : None // Return : None // Description : Transmits HMS information through USART. // *****************************************************************************// void transmitUSARTOutput(void){ //Transmits '!' ASCII transmitCharacter(0x21); //Transmits Humidity Percentage transmitCharacter((int)percentageHumidityValue); //Transmits Light status and fan status as two seperate bits transmitCharacter((lightStatus<<1)|fanStatus); /* SIMtransmitCharacter(0x21); SIMtransmitCharacter((int)percentageHumidityValue); SIMtransmitCharacter((lightStatus<<1)|fanStatus); */ } //******************************************************************************// // Function: transmitCharacter() // Input : None // Return : None // Description : Transmits a character. // *****************************************************************************// void transmitCharacter(uint8_t character){ while((USART3->SR & USART_SR_TXE) == 0x00); USART3->DR = character; while((USART3->SR & USART_SR_TC) == 0x00); } //******************************************************************************// // Function: checkHUMIDITY // Input : None // Return : None // Description : Checks of humidity is above 75% if so then the fan switch only turns fan off for 30 seeconds // *****************************************************************************// void checkHUMIDITY() { /* //else if(((HumidityFlag == 0) && (timeOutFlag == 1) && Humidity30secOFF == 0) || (timer7Flag == 0)) else if(HumidityFlag == 0 && buttonValue != 2) //else if((HumidityFlag == 0) && ((timer7Flag == 0) || (timeOutFlag == 0))) { //Turn off fan fanStatus = 0; //triggerOUTPUTS(); } */ //start ADC ADC3->CR2 |= ADC_CR2_SWSTART; //Wait for conversion to complete //Is cleared by reading the data register //Thus will only get stuck her for a short period while((ADC3->SR & ADC_SR_EOC) == 0x00); //Read Data register (Only bottom 16bits) adcValue = (ADC3->DR & 0xFFFF); percentageHumidityValue = ((adcValue*100)/4095); if(percentageHumidityValue > 75) { HumidityFlagPast = HumidityFlag; HumidityFlag = 1; } else { HumidityFlagPast = HumidityFlag; HumidityFlag = 0; } //if(HumidityFlag == 1 && Humidity30secOFF != 1 && (timer7Flag == 1) && (timeOutFlag == 1) ) //if(HumidityFlag == 1 && ((timer7Flag == 1) || (timeOutFlag == 1))) if(HumidityFlag == 1) { //Turn on fan fanStatus = 1; //triggerOUTPUTS(); } if(HumidityFlag == 0) { if(HumidityFlagPast == 1) { fanStatus = 0; } } } //******************************************************************************// // Function: sampleSimADC() // Input : Simulated ADC value. // Return : Simulated ADC value. // Description : Perform a simulated ADC read. // *****************************************************************************// uint16_t sampleSimADC(uint16_t simulatedValue) { uint16_t currentSample = 0; // Trigger and ADC conversion ADC1->CR2 |= ADC_CR2_SWSTART; // In simulation, set the conversion complete flag. ADC1->SR |= ADC_SR_EOC; // Wait for the conversion to complete. while((ADC1->SR & ADC_SR_EOC) == 0x00); // Get the value from the ADC currentSample = (ADC1->DR & 0x0000FFFF); // If we are running in the simulator, then just returned the passed // in value. currentSample = simulatedValue; // Return the raw ADC value. return currentSample; } //******************************************************************************// // Function: triggerOUTPUTS() // Input : None // Return : None // Description : Reads the flags and outputs based on them // *****************************************************************************// void triggerOUTPUTS() { //Checks Light Status Flag and Writes Output if(lightStatus == 1) { //And to turn off because active low outputs GPIOB->ODR &= ~GPIO_ODR_OD0; } else if(lightStatus != 1) { GPIOB->ODR |= GPIO_ODR_OD0; } //Checks Fan Status Flag and Writes Output if(fanStatus == 1) { //And to turn of cause active low outputs GPIOA->ODR &= ~GPIO_ODR_OD10; } else if(fanStatus != 1) { GPIOA->ODR |= GPIO_ODR_OD10; } } //******************************************************************************// // Function: buttonCONTROL() // Input : None // Return : None // Description : Checks the status of the buttons and checks if they have been pushed for 1 second // *****************************************************************************// void buttonCONTROL() { //Sets Humidity Lock //Read Button Inputs (only PA8,PA9) buttonState = (GPIOA->IDR & 0x300); //Reads PA3 which is Light Intensity Sensor lightIntensity = (GPIOA->IDR & 8); //If Light Button Is Pressed if(buttonState == 256) { LightPressed = 1; buttonValue = 1; } else {LightPressed = 0;} //If Fan Button Is Pressed if(buttonState == 512) { FanPressed = 1; buttonValue = 2; } else {FanPressed = 0;} //If Both Buttons ARE Pressed if(buttonState == 0) { BothPressed = 1; buttonValue = 3; } else {BothPressed = 0;} buttonCHECK(); } //******************************************************************************// // Function: buttonCHECK() // Input : None // Return : None // Description : Latches the FAN button // *****************************************************************************// void buttonCHECK() { if(((TIM7->CNT & TIM_CNT_CNT) < 0x4C2C0) && ((TIM7->CNT & TIM_CNT_CNT) != 0) && ((FanPressed || LightPressed || BothPressed) == 0) ) { //Clears Flag timeOutFlag = 0; } else{timeOutFlag = 1;} //Checks to see if a button has been pressed if((FanPressed || LightPressed || BothPressed) == 1 || (TIM7->SR & TIM_SR_UIF)) { //timeOutFlag = 1; //If the timer hasn't started then start it and UIF flag hasn't been set //Otherwise do nothing //Starts 1s timer if(timer7Flag == 0) { setTIM7(10000); timer7Flag = 1; } //If the timer has expired and the timer was started if((TIM7->SR & TIM_SR_UIF) && (timer7Flag == 1) && timeOutFlag == 1) { //Checks to only latch outputs once button is released //if(((FanPressed || LightPressed || BothPressed) == 0) && (TIM7->CNT & TIM_CNT_CNT) == 0) if(((FanPressed || LightPressed || BothPressed) == 0)) { //Clears timer 7 flag timer7Flag = 0; //Clears Status Flag TIM7->SR &= ~(TIM_SR_UIF); //Determines which output needs to be set //Fan needs to be set if((buttonValue == 2 || buttonValue == 3)) { latchFAN(); if(HumidityFlag == 1) { //Set Humidity30secOFF Flag for output blocking Humidity30secOFF = 1; //Trigger the Fan to compensate for latch above given it // will wait for the 30 seconds to expire triggerOUTPUTS(); //Starts 30s timer (30*10000) setTIM7(30000); //Hults here and waits for 30seonds to finish while((TIM7->SR & TIM_SR_UIF) == 0); //Turn off fan latchFAN(); //Clear Humidity30secOFF Flag for output blocking Humidity30secOFF = 0; } } //Light needs to be set //Also checks the lightIntensityFlag. If not set then don't effect light //if((LightPressed == 1 || BothPressed == 1) && lightIntensityFlag == 0) if((buttonValue == 1 || buttonValue == 0) && (lightIntensity == 8)) { if (ButtonBlock == -1){latchLIGHT();} } } } } //Else if buttons not pressed if((FanPressed || LightPressed || BothPressed) == 0) { //timer7Flag = 0; //if((LightPressed && lightStatus) || (FanPressed && fanStatus)) != 0){ //latchLIGHT(); //latchFAN(); } if(timeOutFlag == 0) { //Turn off timer TIM7->CR1 &= ~TIM_CR1_CEN; //Clear the reload register TIM7->ARR &= ~(TIM_ARR_ARR_Msk); //Clear the count register TIM7->CNT &= ~TIM_CNT_CNT; //Set Count value TIM7->ARR |= 0x4C2C0; //Counts to this value to give //This is where I'm gonna change the duty cycle (<2^16-1) //Clear Status Flag TIM7->SR &= ~(TIM_SR_UIF); //Sets Flags timer7Flag = 0; timeOutFlag = 1; } } //} //******************************************************************************// // Function: latchFAN() // Input : None // Return : None // Description : Latches the FAN button // *****************************************************************************// void latchFAN() { if(fanStatus == 1) {fanStatus = 0;} else if(fanStatus == 0) {fanStatus = 1;} } //******************************************************************************// // Function: latchLIGHT() // Input : None // Return : None // Description : Latches the FAN button // *****************************************************************************// void latchLIGHT() { if(lightStatus == 1) {lightStatus = 0;} else if(lightStatus == 0) {lightStatus = 1;} } //******************************************************************************// // Function: setTIM7() // Input : None // Return : None // Description : Resets the timer to 10ms and starts it // *****************************************************************************// void setTIM7(int count) { //Clear the reload register TIM7->ARR &= ~(TIM_ARR_ARR_Msk); //Set Count value TIM7->ARR |= count; //Counts to this value to give //This is where I'm gonna change the duty cycle (<2^16-1) //Clear Status Flag TIM7->SR &= ~(TIM_SR_UIF); //Start Timer TIM7->CR1 |= TIM_CR1_CEN; } //******************************************************************************// // Function: incrementSimTimer5() // Input : None // Return : None // Description : Increment the simulated. // *****************************************************************************// void incrementSimTimer5(void) { // Check if the count is enabled. if((TIM5->CR1 & TIM_CR1_CEN) == TIM_CR1_CEN) { if(TIM5->CNT == TIM5->ARR) { // Timer has expired - // Set the count complete flag in TIM5->SR |= TIM_SR_UIF; // Check to see if running in one pulse mode // If so, stop the timer. if(TIM5->CR1 & TIM_CR1_OPM) { TIM5->CR1 &= ~(TIM_CR1_CEN); } // Clear the counter. TIM5->CNT &= ~(TIM_CNT_CNT_Msk); if((TIM5->DIER & TIM_DIER_UIE) == TIM_DIER_UIE) { // Trigger interrupt handler. //TIM6_DAC_IRQHandler(); } } else { // Increment the timer. TIM5->CNT = TIM5->CNT + 1; } } } //******************************************************************************// // Function: incrementSimTimer6() // Input : None // Return : None // Description : Increment the simulated. // *****************************************************************************// void incrementSimTimer6(void) { // Check if the count is enabled. if((TIM6->CR1 & TIM_CR1_CEN) == TIM_CR1_CEN) { if(TIM6->CNT == TIM6->ARR) { // Timer has expired - // Set the count complete flag in TIM6->SR |= TIM_SR_UIF; // Check to see if running in one pulse mode // If so, stop the timer. if(TIM6->CR1 & TIM_CR1_OPM) { TIM6->CR1 &= ~(TIM_CR1_CEN); } // Clear the counter. TIM6->CNT &= ~(TIM_CNT_CNT_Msk); if((TIM6->DIER & TIM_DIER_UIE) == TIM_DIER_UIE) { // Trigger interrupt handler. //TIM6_DAC_IRQHandler(); } } else { // Increment the timer. TIM6->CNT = TIM6->CNT + 1; } } } //******************************************************************************// // Function: incrementSimTimer7() // Input : None // Return : None // Description : Increment the simulated. // *****************************************************************************// void incrementSimTimer7(void) { // Check if the count is enabled. if((TIM7->CR1 & TIM_CR1_CEN) == TIM_CR1_CEN) { if(TIM7->CNT == TIM7->ARR) { // Timer has expired - // Set the count complete flag in TIM7->SR |= TIM_SR_UIF; // Check to see if running in one pulse mode // If so, stop the timer. if(TIM7->CR1 & TIM_CR1_OPM) { TIM7->CR1 &= ~(TIM_CR1_CEN); } // Clear the counter. TIM7->CNT &= ~(TIM_CNT_CNT_Msk); if((TIM7->DIER & TIM_DIER_UIE) == TIM_DIER_UIE) { // Trigger interrupt handler. //TIM6_DAC_IRQHandler(); } } else { // Increment the timer. TIM7->CNT = TIM7->CNT + 1; } } } //*********************************************************************************************************************************************// //*********************************************************************************************************************************************// //CONFIG SECTION// //******************************************************************************// // Function: configureUSART() // Input : None // Return : None // Description : Configures the alternate function register and sets up Usart. // *****************************************************************************// void configureUSART(void) { //==Setup Alternate Function==================================================// GPIOB->AFR[1] &= ~(GPIO_AFRH_AFSEL11_Msk | GPIO_AFRH_AFSEL10_Msk); GPIOB->AFR[1] |= (0x07 << GPIO_AFRH_AFSEL11_Pos) | (0x07 << GPIO_AFRH_AFSEL10_Pos); USART3->CR1 &= ~(USART_CR1_OVER8); USART3->BRR &= 0xFFFF0000; //Set Baud Rate 9600 USART3->BRR |= (0x16 << USART_BRR_DIV_Mantissa_Pos) | (0x4E << USART_BRR_DIV_Fraction_Pos); USART3->CR1 &= ~(USART_CR1_M); USART3->CR2 &= ~(USART_CR2_STOP_Msk); USART3->CR2 |= (0x00 << USART_CR2_STOP_Pos); USART3->CR1 &= ~(USART_CR1_PCE); USART3->CR2 &= ~(USART_CR2_CLKEN | USART_CR2_CPOL | USART_CR2_CPHA); USART3->CR2 &= ~(USART_CR3_CTSE | USART_CR3_RTSE); USART3->CR1 |= (USART_CR1_TE | USART_CR1_UE | USART_CR1_RE); } //******************************************************************************// // Function: configureGPIOPorts() // Input : None // Return : None // Description : Set up the GPIO Port Pins. // *****************************************************************************// void configureGPIOPins(void) { //PB0, PA10, PA9, PA8, PA3, PF10 GPIO_Config portConfig; portConfig.port = GPIOB; portConfig.pin = Pin0; portConfig.mode = GPIO_Output; portConfig.pullUpDown = GPIO_No_Pull; portConfig.outputType = GPIO_Output_PushPull; portConfig.speed = GPIO_2MHz; // PB0 gpio_configureGPIO(&portConfig); // PA10 portConfig.port = GPIOA; portConfig.pin = Pin10; gpio_configureGPIO(&portConfig); // PA9 portConfig.pin = Pin9; portConfig.mode = GPIO_Input; gpio_configureGPIO(&portConfig); // PA8 portConfig.pin = Pin8; gpio_configureGPIO(&portConfig); // PA3 portConfig.pin = Pin3; gpio_configureGPIO(&portConfig); // PF10 portConfig.port = GPIOF; portConfig.pin = Pin10; portConfig.mode = GPIO_Analog; gpio_configureGPIO(&portConfig); GPIOB->MODER &= ~(GPIO_MODER_MODE11_Msk | GPIO_MODER_MODE10); GPIOB->MODER |= (0x02 << GPIO_MODER_MODE11_Pos) | (0x02 << GPIO_MODER_MODE10_Pos); GPIOB->AFR[1] &=~(GPIO_AFRH_AFSEL11_Msk | GPIO_AFRH_AFSEL10_Msk); GPIOB->AFR[1] |= (0x07 << GPIO_AFRH_AFSEL11_Pos | 0x07 << GPIO_AFRH_AFSEL10_Pos); } //******************************************************************************// // Function: configureADC1() // Input : None // Return : None // Description : Configure the ADC. // *****************************************************************************// void configureADC1(void){ //Turn off battery sensing ADC123_COMMON->CCR &= ~(ADC_CCR_VBATE); //Disable Temp sensor ADC123_COMMON->CCR &= ~(ADC_CCR_TSVREFE); //Sets ADC Prescaler to divide by 2 (11b) ADC123_COMMON->CCR &= ~(ADC_CCR_ADCPRE); ADC123_COMMON->CCR |= (0x03 << ADC_CCR_ADCPRE_Pos); //Turn off scan and set resolution to 12bit (00b) ADC3->CR1 &= ~((ADC_CR1_SCAN) | (0x03 << ADC_CR1_RES_Pos)); //Continuous mode, and sofeware start is off. Allignment set to right ADC3->CR2 &= ~(ADC_CR2_CONT | ADC_CR2_ALIGN | ADC_CR2_SWSTART); //Set to channel 8 which is where ADC3 is ADC3->SQR3 &= ~(ADC_SQR3_SQ1_Msk); ADC3->SQR3 |= 0x08; //Set for only One conversion ADC3->SQR1 &= ~(ADC_SQR1_L); //Set sample time to 56 cycles (11b = 0x03Hex) ADC3->SMPR2 &= ~(ADC_SMPR2_SMP0_Msk); ADC3->SMPR2 |= 0x03 << (ADC_SMPR2_SMP0_Pos); ADC3->CR2 |= ADC_CR2_ADON; } //******************************************************************************// // Function: count1Second() // Input : None // Return : None // Description : Counts 1 second. // *****************************************************************************// void count1Second() { TIM6->CR1 &= ~TIM_CR1_CEN; TIM6->PSC &= ~(TIM_PSC_PSC_Msk); TIM6->PSC |= 8399; TIM6->ARR &= ~(TIM_ARR_ARR_Msk); TIM6->ARR |= 10000; TIM6->CR1 |= TIM_CR1_OPM; TIM6->CR1 |= TIM_CR1_CEN; } //******************************************************************************// // Function: configureTIM5() // Input : None // Return : None // Description : Configures the timer 5 // *****************************************************************************// void configureTIM5(){ TIM5->CR1 &= ~(TIM_CR1_CEN); TIM5->CR1 |= TIM_CR1_OPM; TIM5->CR1 &= ~(TIM_CR1_DIR); // set to up counter TIM5->PSC &= ~(TIM_PSC_PSC_Msk); TIM5->PSC |= 8399; //Clear the reload register TIM5->ARR &= ~(TIM_ARR_ARR_Msk); TIM5->ARR |= 10000; } //******************************************************************************// // Function: configureTIM7() // Input : None // Return : None // Description : Configures the timer 7 for button press checking // *****************************************************************************// void configureTIM7() { //Turning off timer TIM7->CR1 &= ~(TIM_CR1_CEN); //Clear Prescaler TIM7->PSC &= ~(TIM_PSC_PSC_Msk); //Set Prescaler to 4199 to make a 1s Timer TIM7->PSC |= 8399; //Clear the reload register TIM7->ARR &= ~(TIM_ARR_ARR_Msk); //Set Count value //TIM7->ARR |= 0x1; //Counts to this value //Set Timer to count be poled after each count is reached TIM7->CR1 |= TIM_CR1_OPM; //Start Timer //TIM7->CR1 |= TIM_CR1_CEN; } //******************************************************************************// // Function: initRCC() // Input : None // Return : None // Description : Configure the RCC for USART3, TIM6, ADC1 and GPIO Ports. // *****************************************************************************// void init(void){ //TIM5 & TIM6 & TIM7 & USART3 RCC RCC->APB1ENR |= RCC_APB1ENR_TIM5EN | RCC_APB1ENR_TIM6EN | RCC_APB1ENR_TIM7EN | RCC_APB1ENR_USART3EN; RCC->APB1RSTR |= RCC_APB1RSTR_TIM5RST | RCC_APB1RSTR_TIM6RST | RCC_APB1RSTR_TIM7RST | RCC_APB1RSTR_USART3RST; __ASM("NOP"); __ASM("NOP"); RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM5RST) & ~(RCC_APB1RSTR_TIM6RST) & ~(RCC_APB1RSTR_TIM7RST) & ~(RCC_APB1RSTR_USART3RST); __ASM("NOP"); __ASM("NOP"); //GPIO RCC RCC->AHB1ENR = RCC->AHB1ENR | RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOBEN | RCC_AHB1ENR_GPIOFEN; RCC->AHB1RSTR = RCC->AHB1RSTR | RCC_AHB1RSTR_GPIOARST | RCC_AHB1RSTR_GPIOBRST | RCC_AHB1RSTR_GPIOFRST; __ASM("NOP"); __ASM("NOP"); RCC->AHB1RSTR = RCC->AHB1RSTR & ~(RCC_AHB1RSTR_GPIOARST) & ~(RCC_AHB1RSTR_GPIOBRST) & ~(RCC_AHB1RSTR_GPIOFRST); __ASM("NOP"); __ASM("NOP"); //ADC RCC RCC->APB2ENR |= RCC_APB2ENR_ADC1EN; RCC->APB2RSTR |= RCC_APB2RSTR_ADCRST; __ASM("NOP"); __ASM("NOP"); RCC->APB2RSTR &= ~(RCC_APB2RSTR_ADCRST); __ASM("NOP"); __ASM("NOP"); configureGPIOPins(); configureUSART(); configureADC1(); configureTIM7(); configureTIM5(); count1Second(); }
99b3ac404739dd2d4b9c6639746d269edc65e1c0
[ "Markdown", "C" ]
3
C
Kennedy747/Embedded-Project
925193a86f194bdc39ab63cca4ceecfd72326da9
c58f30e113bcec6ab48ef8908c5aaf5405cec1a7
refs/heads/master
<repo_name>rohandudam/bash-tutor<file_sep>/README.md # Interactive Tutorial For The Linux Command Line Interface (with Bash!) ## Intro After see how effective interactive tutorials have been for every other interpereted language I decided it's finally time for Bash to have it's turn. Why shouldn't there be an interactive tutorial for teaching people how to use Bash. And since most people first encounter Bash when trying to learn the Linux command line we can teach them that at the same time. ## How to use Run the `start_tutorial.sh` script to bring up the tutorial shell. <file_sep>/start_tutorial.sh #!/bin/bash # We need to properly set the $START START=${START:=`dirname $0`} CURDIR="`pwd`" cd "$START" export START="`pwd`" cd "$CURDIR" # reset progress file cat /dev/null > .progress PS1="\`history | tail -n 1 | cut -c 8- | $START/tutlib.sh\`\\ntutor:\\w\\$ " bash --noprofile --norc <file_sep>/tutlib.sh #!/bin/bash if [ ! -e $START/.progress ] then cat /dev/null > $START/.progress fi if [ ! -s $START/.progress ] then echo 1 >$START/.progress fi read lastcmd current_step=$(tail -n 1 $START/.progress) # Step 1: Navigation the directory structre. step_1(){ case "$current_step" in "1") echo "Welcome to the tutorial!" echo "Let's begin by figuring out where we are." echo "To print the present working directory we use the 'pwd' command." echo 1.1>>$START/.progress ;; "1.1") case "$lastcmd" in "pwd") echo echo "Good job!" echo "As you can see above, the current directory is \"`pwd`\"." echo if [ "`pwd`" = "$HOME" ] then echo "You are already in your home directory. You can always get back here at any time" echo "by issuing the change directory command 'cd'. Try it now." else echo "You are not in your home directory. Please change to your home directory" echo "by issuing the change directory command 'cd'." fi echo 1.2>>$START/.progress ;; *) echo "Try again. You typed \"$lastcmd\"" echo "Hint: Type 'pwd' and hit Enter to continue." ;; esac ;; "1.2") if [ "`pwd`" = "$HOME" ] then echo "Great! Now we're in your home directory." echo "Let's make a directory to use for the rest of this tutorial. To make a directory" echo "issue the make directory command 'mkdir' with the name of a directory you want to" echo "create. In this case, we'll make the 'tutorial' directory." echo 1.3>>$START/.progress else echo "Try again. You typed \"$lastcmd\"" echo "Hint: Try typing 'cd'" fi ;; "1.3") if [ -d "$HOME/tutorial" ] then echo "You've just created a directory. Now lets change into that directory. To change" echo "directory you use the command 'cd' with the name of the directory you want to" echo "change to." echo 1.4>>$START/.progress else echo "Try again. You typed \"$lastcmd\"" echo "Hint: Try typing 'mkdir tutorial'" fi ;; "1.4") if [ "`pwd`" = "$HOME/tutorial" ] then echo "Nicely done. You're now in the tutorial directory." echo 1.5>>$START/.progress else echo "Try again. You typed \"$lastcmd\"" echo "Hint: Try typing 'cd tutorial'" fi ;; esac } # Run the handler for the current step. step_${current_step%%.*}
82754258245aeba4fea2db972587f03de069e537
[ "Markdown", "Shell" ]
3
Markdown
rohandudam/bash-tutor
8cb5fb708a03b998f8ae8b74b769ab3dc6261648
d4c35c62c6c6f9fd6d625295c284ebff2b1e0769
refs/heads/master
<file_sep># test test仓库 <file_sep>// // ViewController.swift // gitHubTest项目 // // Created by jinh on 2019/7/8. // Copyright © 2019 renjian. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. creatFramework() } func creatFramework() -> Void { view.addSubview(testView) } lazy var testView : UIView = { let view = UIView(frame: CGRect(x: 100, y: 100, width: 50, height: 50)) view.backgroundColor = UIColor.orange return view }() }
bddc5d421caf50dfbab4badfa23a591a0c946c4a
[ "Markdown", "Swift" ]
2
Markdown
customAny/test
4f39ff69f64586f4e44c0b725c03224b1eda9403
cc32cca5872bd5c22218cf001fe9247babebdbc6
refs/heads/master
<repo_name>tkm603018/todo-app<file_sep>/src/components/Todo/ToDoCountItem.js import React from 'react'; import './ToDoCountItem.css'; class ToDoCountItem extends React.Component { render() { const count = localStorage.getItem("DoneCount"); return ( <div className="ToDoCountItem"> <p>{count}</p> </div> ) } } export default ToDoCountItem<file_sep>/src/components/Todo/Apptodo.js import React from 'react'; import './Apptodo.css'; import ToDoListItem from './ToDoListItem'; import ToDoAddItem from './ToDoAddItem'; import ToDoDeleteItem from './ToDoDeleteItem'; import ToDoDoneItem from './ToDoDoneItem'; import ToDoCountItem from './ToDoCountItem'; class AppTodo extends React.Component { state = { count: 0, todos: [], inputTitle: '', inputDescription: '', titlError: '', descriptionError: '', selectedIndex: null, doneCount: 0, createdAt: new Date(), } handleTitle = (event) => { this.setState({ inputTitle: event.target.value } ) } handleDiscription = (event) => { this.setState({ inputDescription: event.target.value }) } todoAdd = (e) => { e.preventDefault(); if (!this.state.inputTitle) { this.setState({ titleError: 'タイトルを入力してください' }) return } else if (!this.state.inputDescription) { this.setState({ descriptionError: '内容を入力してください' }) return } const count = this.state.count + 1; const newTodo = { count: count, title: this.state.inputTitle, description: this.state.inputDescription, createdAt: new Date() } const todo = this.state.todos.slice(); todo.push(newTodo); this.setState({ count: newTodo.count, todos: todo, inputTitle: '', inputDescription: '', titleError: '', descriptionError: '', }) console.log(todo); console.log(this.state.todos); this.todoStore(todo); } todoStore = (todo) => { localStorage.setItem("key", JSON.stringify(todo)); console.log(todo); console.log(todo.count); } todoPull = () => { var List = JSON.parse(localStorage.getItem("key")); console.log(List); console.log(this.state.count); console.log(localStorage.length); return (List) } todoSelect = (index) => { this.setState({ selectedIndex: index, }) } todoDelete = (index) => { const newTodos = JSON.parse(localStorage.getItem("key")); newTodos.splice(index, 1); localStorage.setItem("key", JSON.stringify(newTodos)); this.setState({ todos: newTodos, selectedIndex: null }) } todoDone = (index) => { const newTodos = JSON.parse(localStorage.getItem("key")); newTodos.splice(index, 1); localStorage.setItem("key", JSON.stringify(newTodos)); localStorage.setItem("DoneCount", this.state.doneCount + 1) this.setState({ todos: newTodos, selectedIndex: null, doneCount: this.state.doneCount + 1 }) } render() { return ( <div className="AppTodoAll"> <div className="AppTodoAdd"> <ToDoAddItem {...this.state} handleTitle={this.handleTitle} handleDiscription={this.handleDiscription} todoAdd={this.todoAdd} alreadyAdder={this.alreadyAdder} /> </div> <br></br> <div className="AppTodoList"> <ToDoListItem {...this.state} todoSelect={this.todoSelect} todoPull={this.todoPull} todoStore={this.todoStore} /> </div> <br></br> <div className="AppTodoDone"> <ToDoDoneItem {...this.state} todoDone={this.todoDone} /> </div> <div className="AppTodoDelete"> <ToDoDeleteItem {...this.state} todoDelete={this.todoDelete} /> </div> { /*<div className="AppTodoCount"> <ToDoCountItem {...this.state} /> </div> {/* <div className='Homepage'> <a href='../'>Back to Home</a> </div> */} </div> ) } } export default AppTodo <file_sep>/src/components/Todo/ToDoDeleteItem.js import React from 'react'; import './ToDoDeleteItem.css'; class ToDoDeleteItem extends React.Component { render() { const selectedIndex = this.props.selectedIndex; if (selectedIndex !== null) { return ( <button className="ToDoDeleteButton" onClick={() => { this.props.todoDelete(selectedIndex) }}>Delete</button> ) } else { return null; } } } export default ToDoDeleteItem<file_sep>/src/components/Home/ToDoHome.js import React from 'react'; import { Link } from 'react-router-dom'; import './ToDoHome.css'; class ToDoHome extends React.Component { render() { return ( <div className="LinkList"> <div className="HomeTitlePosition"> <h1 className="HomeTitle">Todo List</h1> </div> <Link to='/detail/todo'><div className="LinkTodo">Go to ToDopage</div></Link> <Link to='/detail/monster'><div className="LinkMonster">Go to Monsterpage</div></Link> </div > ) } } export default ToDoHome<file_sep>/src/components/Home/ToDoButton.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Monster Todoについて</title> </head> <body> <div class='What-MonsterTodo-detail'> <h1 class='Title'>MonsterTodoとは?</h1> <div class='what-MonsterTodo-detail'> <p>TodoListとはとは、日常業務で「行うべきこと」を記録しておくアプリケーションで、「○月○日までにやらなければいけない仕事」など、仕事内容に期日を組み合わせて登録することで管理するアプリです。MonsterTodoでは、完了したタスクの数に応じてMonsterのLvが上がっていき、様々なMonsteに変化します。モチベーションが維持するのが苦手な方には目に見える成果により楽しく、向上心をもってタスク管理を行うことができます。 </p> </div> <div class='detail'> <p>インストール後のトラブルにつきましては一切の責任を持ちませんのでご了承ください。</p> </div> </div> </body> </html><file_sep>/src/components/Todo/ToDoAddItem.js import React from 'react'; import './ToDoAddItem.css'; class ToDoAddItem extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.state = { visible: false }; } handleClick() { this.setState((prevState) => { return { visible: !prevState.visible }; }); } render() { return ( <div> {(this.state.visible) ? <button className="ToggleButton" onClick={this.handleClick}>{(this.state.visible) ? "" : ""}</button> : <button className="ToggleButton-false" onClick={this.handleClick}>{(this.state.visible) ? "" : ""}</button>} <div className="container"> {(this.state.visible) ? <div className="ToDoAdd"> <h3>TodoList</h3> <div className='Input'><input name='title' className="AddTitle" onChange={this.props.handleTitle} value={this.props.inputTitle} placeholder="title" /></div> {this.props.titleError}<br></br> <div className='Discription'><textarea name='discription' className="AddDiscription" onChange={this.props.handleDiscription} value={this.props.inputDescription} placeholder="description" /></div> {this.props.descriptionError} <div className='Button'><button className="AddButton" onClick={this.props.todoAdd}>Register</button></div> </div> : <div className="ToDoAdd-false"></div> } </div> </div> ) } } export default ToDoAddItem <file_sep>/src/components/Todo/ToDoAddButtonItem.js import React from 'react'; import './ToDoAddButtonItem.css'; class ToDoAddButtonItem extends React.Component { render() { return ( <div><button className="AddButton" onClick={this.props.todoAdd}>Register</button></div> ) } } export default ToDoAddButtonItem<file_sep>/src/components/Monster/MonsterImager.js import React from 'react'; import Stinky from './stinky.jpg'; import Moran from './moran.jpg'; import Salome from './salome.jpg'; import Little from './Little.jpg'; import Supergirl from './supergirl.png'; import Superman from './superman.png'; class MonsterImager extends React.Component { render() { var Level = localStorage.getItem("DoneCount"); console.log(Level); if (Level < 10) { return ( <div> <img src={Stinky} alt="ムーミン" className='image1' /> <div className='MessagePosition'><p className='Message'>まだまだこれから!</p></div> <div className='LevelPosition'><p className='Level'>Level:{Level}</p></div> </div> ) } else if (Level >= 10 && 20 > Level) { return ( <div> <img src={Moran} alt="ムーミン" className='image1' /> <div className='MessagePosition'><p className='Message'>いい感じ!</p></div> <div className='LevelPosition'><p className='Level'>Level:{Level}</p></div> </div> ) } else if (Level >= 20 && 30 > Level) { return ( <div> <img src={Salome} alt="ムーミン" className='image1' /> <div className='MessagePosition'><p className='Message'>すごい!</p></div> <div className='LevelPosition'><p className='Level'>Level:{Level}</p></div> </div> ) } else if (Level >= 30 && 40 > Level) { return ( <div> <img src={Little} alt="ムーミン" className='image1' /> <div className='MessagePosition'><p className='Message'>Todoは習慣化してきた?</p></div> <div className='LevelPosition'><p className='Level'>Level:{Level}</p></div> </div> ) } else if (Level >= 40 && 50 > Level) { return ( <div> <img src={Supergirl} alt="ムーミン" className='image1' /> <div className='MessagePosition'><p className='Message'>どこまでいけるかな?</p></div> <div className='LevelPosition'><p className='Level'>Level:{Level}</p></div> </div> ) } else { return ( <div> <img src={Superman} alt="ムーミン" className='image1' /> <div className='MessagePosition'><p className='Message'>TodoMaster!!</p></div> <div className='LevelPosition'><p className='Level'>Level:{Level}</p></div> </div> ) } } } export default MonsterImager
381bf5682103d04184856c2700554c6d30d4f1d2
[ "JavaScript", "HTML" ]
8
JavaScript
tkm603018/todo-app
cf08898c2818d04c38c07af87b16cb0d57fd1dd1
61bea3ac0b930779501d662d167fc3bc3de26e13
refs/heads/master
<file_sep>'use strict'; module.exports = (sequelize, DataTypes) => { var Website = sequelize.define('Website', { title: DataTypes.STRING, description: DataTypes.STRING, copyright: DataTypes.STRING, company: DataTypes.STRING, email: DataTypes.STRING, phone: DataTypes.STRING }, { freezeTableName: true }); Website.associate = function(models) { // associations can be defined here }; return Website; };<file_sep>'use strict'; module.exports = (sequelize, DataTypes) => { var Article = sequelize.define('Article', { title: DataTypes.STRING, content: DataTypes.TEXT }, {}); Article.associate = function(models) { // associations can be defined here Article.belongsTo(models.Category); Article.belongsToMany(models.Tag, {through: 'articleTag'}); }; Article.postArticle = function(title, content, categoryId, tagIds) { let Tag = require('../models').Tag; return Article.create({ title:title, content:content, CategoryId: categoryId }).then(function(article){ // 添加文章tag let articleId = article.id; let values = []; for (let tagId of tagIds) { Tag.findOne({where:{id:tagId}}).then(function(tag){ article.addTag(tag); }) } return article; }); } //按照分类的方式来查找文章 Article.queryByCategory = function(categoryId, pagination) { const Website = require('../models').Website; const Category = require('../models').Category; const Tag = require('../models').Tag; const moment = require('moment'); let limit = pagination.limit; let page = pagination.page; return Website.findOne().then(function(webinfo){ //网站相关信息查询 console.log(webinfo); webinfo.website_title = webinfo.title; webinfo.website_description = webinfo.description; console.log(webinfo.copyright) let locals = { 'website_title': webinfo.title, 'website_description': webinfo.description, 'copyright': webinfo.copyright, 'email': webinfo.email, 'company': webinfo.company, }; let options = { order: [['id', 'DESC']], limit: limit, offset: (page-1)*limit, where:{}, include: { model: Tag, } }; if (categoryId > 0) { options.where.CategoryId = categoryId; } locals['categoryId'] = categoryId; return Category.findAll().then(function(categories){ locals['categories'] = categories; return Tag.getAllTags().then(function(tags){ locals['tags'] = tags; return Article.findAndCount(options).then(function(articles){ // 按照条件查询文章 let pagination = [] //传给view的分页变量,和上面的pagination是两个变量 console.log('Articles Count: ' + articles.count); for (let i = 1; i <= Math.ceil(articles.count/limit); i++) { pagination.push({ tag:i+'', page: i, link:'/?' + (categoryId > 0 ? 'cate_id=' + categoryId + '&' : '') +'page=' + i }) } for (let i = 0; i < articles.rows.length; i++) { articles.rows[i]['date'] = moment(articles.rows[i]['createdAt']).format("YYYY-MM-DD hh:mm:ss"); } locals['articles'] = articles.rows; locals['total'] = articles.count; locals['pagination'] = pagination; locals['page'] = page; return locals; //return res.render('blog', locals) }); }); }); }) } //按照标签的方式来查找文章 Article.queryByTag = function(tagId, pagination) { const Website = require('../models').Website; const Category = require('../models').Category; const Tag = require('../models').Tag; const moment = require('moment'); let limit = pagination.limit; let page = pagination.page; return Website.findOne().then(function(webinfo){ //网站相关信息查询 console.log(webinfo); webinfo.website_title = webinfo.title; webinfo.website_description = webinfo.description; console.log(webinfo.copyright) let locals = { 'website_title': webinfo.title, 'website_description': webinfo.description, 'copyright': webinfo.copyright, 'email': webinfo.email, 'company': webinfo.company, }; let options = { attributes: ['id'], order: [['id', 'DESC']], limit: limit, offset: (page-1)*limit, where:{}, include: { model: Tag, where: {} }, logging: true }; if (tagId > 0) { options.include.where.id = tagId; } locals['tagId'] = tagId; return Category.findAll().then(function(categories){ locals['categories'] = categories; return Tag.getAllTags().then(function(tags){ locals['tags'] = tags; //先找出符合tag搜索条件的所有id return Article.findAll(options).then(function(articles){ let ids = []; for (let i = 0; i < articles.length; i++) { ids.push(articles[i].id); } delete options.attributes; options.where.id = {'$in': ids}; options.include.where = {}; //按照新的条件进行搜索 return Article.findAndCount(options).then(function(articles){ // 按照条件查询文章 let pagination = [] //传给view的分页变量,和上面的pagination是两个变量 console.log('Articles Count: ' + articles.count); for (let i = 1; i <= Math.ceil(articles.count/limit); i++) { pagination.push({ tag:i+'', page: i, link:'/?' + (tagId > 0 ? 'tag_id=' + tagId + '&' : '') +'page=' + i }) } for (let i = 0; i < articles.rows.length; i++) { articles.rows[i]['date'] = moment(articles.rows[i]['createdAt']).format("YYYY-MM-DD hh:mm:ss"); } locals['articles'] = articles.rows; locals['total'] = articles.count; locals['pagination'] = pagination; locals['page'] = page; return locals; //return res.render('blog', locals) }); }); }); }); }) } //按照分类的方式来查找文章 Article.queryArticle = function(articleId) { const Website = require('../models').Website; const Category = require('../models').Category; const Tag = require('../models').Tag; const moment = require('moment'); return Website.findOne().then(function(webinfo){ //网站相关信息查询 console.log(webinfo); webinfo.website_title = webinfo.title; webinfo.website_description = webinfo.description; console.log(webinfo.copyright) let locals = { 'website_title': webinfo.title, 'website_description': webinfo.description, 'copyright': webinfo.copyright, 'email': webinfo.email, 'company': webinfo.company, }; locals['articleId'] = articleId; return Category.findAll().then(function(categories){ locals['categories'] = categories; return Tag.getAllTags().then(function(tags){ locals['tags'] = tags; return Article.findOne({ where: {id: articleId}, include: { model: Tag } }).then(function(article){ // 按照条件查询文章 locals['article'] = article; return locals; }); }); }); }) } return Article; };<file_sep> //将元素的name属性的数组名称移向下一个下表。 如tag[1] --> tag[2] function nameNextArrayIndex(element) { let name = element.attr('name'); let a = name.indexOf('['); let b = name.indexOf(']'); console.log(a,b); let index = parseInt(name.substr(a+1, b-a-1)); console.log(name.substr(a+1, b-a-1)); index += 1; name = name.substr(0, a) + '[' + index + ']'; element.attr('name', name); } //将select元素恢复默认 function resetSelection(select) { select.find("option:selected").removeAttr("selected"); select.find("option[value=0]").attr("selected", "selected"); } //增加一个标签 function addTag(tag_id, tag_name) { let $tag_selector = $(".tag_selector"); console.log("Let's add tag"); let tag = $('<span class="tag"><input type="hidden" name="' + $tag_selector.attr('name') + '" value ="' + tag_id + '"/>' + tag_name + '</span>'); //tag.find('button').click(deleteTag); resetSelection($tag_selector); nameNextArrayIndex($tag_selector); $tag_selector.before(tag); } //删除标签 TODO:编写删除标签 function deleteTag() { console.log('delete tag'); return false; } $(".tag_selector").change(function(){ console.log("selection has changed"); let tag_id = $(this).val(); let tag_name = $(this).find("option:selected").text(); addTag(tag_id, tag_name); }) $("button.submit").click(function(){ let values = $("#postForm").serializeArray(); console.log(values); return false; })<file_sep> let moment = require('moment'); const Article = require('../models').Article; const Website = require('../models').Website; const Category = require('../models').Category; const Tag = require('../models').Tag; const _ = require('lodash'); //博客主页的显示 const display = function(req, res, next) { /* * get参数: * 1. cate_id: 分类id 或 tag_id: 标签id * 2. page: 页码 */ //分页信息 let page = req.query.page ? req.query.page : 1; let limit = 4; let categoryId = 0; let tagId = 0; let pagination = { page: page, limit: limit }; if (req.query.cate_id) { categoryId = req.query.cate_id; } if (req.query.tag_id) { tagId = req.query.tag_id; } if (categoryId > 0) { //按分类来找文章 Article.queryByCategory(categoryId, pagination).then(function(locals){ console.log(locals); return res.render('blog', locals); }) } else if (tagId > 0){ //按标签来找文章 Article.queryByTag(tagId, pagination).then(function(locals){ console.log(locals); return res.render('blog', locals); }) } else { //所有文章 Article.queryByCategory(0, pagination).then(function(locals){ console.log(locals); return res.render('blog', locals); }) } } //显示某一文章 const displayArticle = function(req, res, next) { /* * get参数: * 1. article_id: 文章id */ //分页信息 let page = req.query.page ? req.query.page : 1; let limit = 4; let articleId = 0; if (req.query.article_id) { articleId = req.query.article_id; } Article.queryArticle(articleId).then(function(locals){ console.log(locals); return res.render('article', locals); }) } //发文章页面的显示 const postDisplay = function(req, res, next) { let categories = Category.findAll({}).then(function(categories){ console.log(categories); Tag.findAll().then(function(tags){ res.render('post', { 'categories': categories, 'tags':tags }) }) }); } const post = function(req, res, next) { let title = req.body.title; let content = req.body.content; let categoryId = req.body.category_id; let tagId0 = req.body['tag_id[0]']; let tagId1 = req.body['tag_id[1]']; let tagId2 = req.body['tag_id[2]']; let tagIds = [tagId0, tagId1, tagId2]; console.log(tagIds); tagIds = Array.from(new Set(tagIds)); console.log(tagIds); _.remove(tagIds, function(e){ return e === undefined || e == '0'; }); console.log(tagIds); Article.postArticle(title, content, categoryId, tagIds).then(function(result){ return res.jsonp(result); }) } module.exports = { display:display, displayArticle: displayArticle, postDisplay: postDisplay, post:post, }<file_sep>var express = require('express'); var router = express.Router(); var controller = require('../controller/blog'); var Category = require('../models').Category; /* GET home page. */ router.get('/', controller.display); //显示某一文章 router.get('/article', controller.displayArticle); //显示添加文章页面 router.get('/post', controller.postDisplay); //添加文章 router.post('/post', controller.post); module.exports = router;
8a2b675b95f2b991a74eab6ac8aeb0527c6557a0
[ "JavaScript" ]
5
JavaScript
imzhangliang/MyBlog
769fb5240e16ed61e28249db51934e70e0c7981e
d6466900d04f7cc7f36dfabb5a970b63a29650a9
refs/heads/master
<repo_name>Henda88/JEE-TIMESHEET-CRUD-<file_sep>/timesheetBi-ejb/src/main/java/webapp/timesheetBi/entities/Role.java package webapp.timesheetBi.entities; public enum Role { chefDepartement, administrateur, ingénieur, technicien } <file_sep>/timesheetBiClient/src/main/java/timesheetBiClient/ManageEmployeandContrats.java package timesheetBiClient; import java.text.ParseException; import java.text.SimpleDateFormat; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import webapp.timesheetBi.entities.Contrat; import webapp.timesheetBi.entities.Employe; import webapp.timesheetBi.entities.Role; import webapp.timesheetBi.services.EmployeServiceRemote; public class ManageEmployeandContrats { public static void main(String[] args) throws NamingException, ParseException { String jndiName = "timesheetBi-ear/timesheetBi-ejb/EmployeService!webapp.timesheetBi.services.EmployeServiceRemote"; Context context = new InitialContext(); EmployeServiceRemote employeServiceRemote = (EmployeServiceRemote) context.lookup(jndiName); Employe YosraArbi = new Employe("Arbi", "Yosra", "<EMAIL>", true, Role.chefDepartement); Employe KhaledKallel = new Employe("Kallel", "khaled", "<EMAIL> ,", true, Role.ingénieur); Employe MohamedZitouni = new Employe("zitouni", "mohamed", "<EMAIL>", true, Role.technicien); Employe AymenOuali = new Employe("Ouali", "Aymen", "<EMAIL> ,", true, Role.ingénieur); Employe BouchraBouzid = new Employe("Bouzid", "bochra", "<EMAIL>", true, Role.chefDepartement); int yosraArbiID = employeServiceRemote.ajouterEmploye(YosraArbi); int khaledKallelID = employeServiceRemote.ajouterEmploye(KhaledKallel); int mohamedZitouniID = employeServiceRemote.ajouterEmploye(MohamedZitouni); int aymenOualiID = employeServiceRemote.ajouterEmploye(AymenOuali); int bouchraBouzidID = employeServiceRemote.ajouterEmploye(BouchraBouzid); int depRHID = 1; int depTelecomID = 2; employeServiceRemote.affecterEmployeADepartement(yosraArbiID, depTelecomID); employeServiceRemote.affecterEmployeADepartement(khaledKallelID, depRHID); employeServiceRemote.affecterEmployeADepartement(khaledKallelID, depTelecomID); employeServiceRemote.affecterEmployeADepartement(mohamedZitouniID, depRHID); employeServiceRemote.affecterEmployeADepartement(mohamedZitouniID, depTelecomID); employeServiceRemote.affecterEmployeADepartement(aymenOualiID, depTelecomID); employeServiceRemote.affecterEmployeADepartement(bouchraBouzidID, depRHID); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); Contrat yosraContrat = new Contrat(dateFormat.parse("01/03/2010"), "CDI", 2600); Contrat khaledContrat = new Contrat(dateFormat.parse("01/02/2015"), "CDI", 1600); Contrat mohamedContrat = new Contrat(dateFormat.parse("15/05/2013"), "CDI", 900); Contrat aymenContrat = new Contrat(dateFormat.parse("10/05/2014"), "CDI", 2000); Contrat bochraContrat = new Contrat(dateFormat.parse("12/06/2010"), "CDI", 2700); int yosraContratID = employeServiceRemote.ajouterContrat(yosraContrat); int khaledContratID = employeServiceRemote.ajouterContrat(khaledContrat); int mohamedContratID = employeServiceRemote.ajouterContrat(mohamedContrat); int aymenContratID = employeServiceRemote.ajouterContrat(aymenContrat); int bochraContratID = employeServiceRemote.ajouterContrat(bochraContrat); employeServiceRemote.affecterContratAEmploye(yosraContratID, yosraArbiID); employeServiceRemote.affecterContratAEmploye(khaledContratID, khaledKallelID); employeServiceRemote.affecterContratAEmploye(mohamedContratID, mohamedZitouniID); employeServiceRemote.affecterContratAEmploye(aymenContratID, aymenOualiID); employeServiceRemote.affecterContratAEmploye(bochraContratID, bouchraBouzidID); System.out.println(employeServiceRemote.getEmployePrenomById(yosraArbiID)); System.out.println(employeServiceRemote.getEmployePrenomById(khaledKallelID)); System.out.println(employeServiceRemote.getEmployePrenomById(mohamedZitouniID)); System.out.println(employeServiceRemote.getEmployePrenomById(aymenOualiID)); System.out.println(employeServiceRemote.getEmployePrenomById(bouchraBouzidID)); } } <file_sep>/timesheetBi-ejb/src/main/java/webapp/timesheetBi/services/EmployeService.java package webapp.timesheetBi.services; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import webapp.timesheetBi.entities.Contrat; import webapp.timesheetBi.entities.Departement; import webapp.timesheetBi.entities.Employe; @Stateless public class EmployeService implements EmployeServiceRemote { @PersistenceContext(unitName = "timesheetBi-ejb") private EntityManager em; public EmployeService() { } @Override public int ajouterEmploye(Employe employe) { em.persist(employe); return employe.getId(); } @Override public void affecterEmployeADepartement(int employeId, int depId) { Employe employeManagedEntity = em.find(Employe.class, employeId); Departement depManagedEntity = em.find(Departement.class, depId); // (test != null) && !test.isEmpty() if (depManagedEntity.getEmploye().isEmpty() && depManagedEntity.getEmploye() == null) { List<Employe> employes = new ArrayList<>(); employes.add(employeManagedEntity); depManagedEntity.setEmploye(employes); } else { depManagedEntity.getEmploye().add(employeManagedEntity); } } @Override public int ajouterContrat(Contrat contrat) { em.persist(contrat); return contrat.getReference(); } @Override public void affecterContratAEmploye(int contratId, int employeId) { Employe employeManagerEntity = em.find(Employe.class, employeId); Contrat contratManagedEntity = em.find(Contrat.class, contratId); employeManagerEntity.setContrat(contratManagedEntity); em.merge(contratManagedEntity); } @Override public String getEmployePrenomById(int employeId) { Employe employeManagerEntity = em.find(Employe.class, employeId); return employeManagerEntity.getPrenom(); } @Override public long getNombreEmployeJPQL() { //TypedQuery<long> query = em.createQuery("select count(e) from Employe e", Long.class); // return query.getSingleResult(); return 0; } @Override public List<String> getAllEmployeNamesJPQL() { List<Employe> employes = em.createQuery("select e from Employe e", Employe.class).getResultList(); List<String> employeNames = new ArrayList<>(); for (Employe employe : employes) { employeNames.add(employe.getNom()); } return employeNames; } }
e778f66ca2d3d6b7eae2f7f7960cc80f13278b3c
[ "Java" ]
3
Java
Henda88/JEE-TIMESHEET-CRUD-
349f15ce2416608f2d82f7ec11c1f4df9d6e3e94
684916cf245f34dc487786abd1273330a7ce8bb0
refs/heads/master
<file_sep>import subprocess def main(): print(subprocess.check_output(['make check'])) if __name__ == "__main__": main() <file_sep>flake: flake8 makehook check: flake <file_sep>from setuptools import setup setup( name='makehook', version='0.1.0', entry_points={ 'console_scripts': [ 'makehook = makehook.__main__:main' ] }, )
ceeb2bbbaef04cc35c3a1177ffea22d89810fcad
[ "Python", "Makefile" ]
3
Python
koaning/makehook
d6c056596c58f5420c1935a6c19dab89dabcb17d
03044d086fe227b5aa051fbf01fddae77df6ae99
refs/heads/master
<file_sep>document.addEventListener("DOMContentLoaded",function(){ const secondHand = document.querySelector('.second-hand'); const minHand = document.querySelector('.min-hand'); const hourHand = document.querySelector('.hour-hand'); function setDate(){ const now = new Date(); const seconds = now.getSeconds(); const secondsDegrees = ((seconds/60)*360) + 90; secondHand.style.transform = "rotate("+secondsDegrees+"deg)"; if(secondsDegrees === 90){ secondHand.style.transition = "none"; }else{ secondHand.style.transition = "all 0.05s"; secondHand.style.transitionTimingFunction = "cubic-bezier(0.1, 2.7, 0.58, 1)"; } const minutes = now.getMinutes(); const minutesDegrees = ((minutes/60)*360) + 90; minHand.style.transform = "rotate("+minutesDegrees+"deg)"; if(minutesDegrees === 90){ minHand.style.transition = "none"; }else{ minHand.style.transition = "all 0.05s"; minHand.style.transitionTimingFunction = "cubic-bezier(0.1, 2.7, 0.58, 1)"; } const hour = now.getHours(); const hourDegrees = ((hour/12)*360) + 90; hourHand.style.transform = "rotate("+hourDegrees+"deg)"; if(hourDegrees === 90){ hourHand.style.transition = "none"; }else{ hourHand.style.transition = "all 0.05s"; hourHand.style.transitionTimingFunction = "cubic-bezier(0.1, 2.7, 0.58, 1)"; } } setInterval(setDate,1000); })
117ad280c3b9eca6112839fa2ba48cf3d2f50939
[ "JavaScript" ]
1
JavaScript
Muli94/JavaScript30
67acb99ce2c074a04daa244cd70bf4943bbe171e
7b5d8de41b8fb2ce0bb25005fb5dddfef03e4480
refs/heads/master
<file_sep>startnumber = 0 lastnumber = 0 continueCount = "" looper = "y" while looper != "n": integercheck = True while(integercheck): try: prompt = int(input("How many numbers do you want to chain? ")) integercheck = False except: print("Invalid Selection") lastnumber = startnumber + prompt for num in range(startnumber, lastnumber): print(num) #while continueCount != "y" or continueCount != "n": continueCount = input("Continue the chain? (y/n) ") startnumber = lastnumber looper = continueCount <file_sep># TDS-GWU-Python1 Python Homework Week 1 <file_sep>import os import pandas as pd csvpath = os.path.join('.', 'Resources', 'election_data.csv') electiondata = pd.read_csv(csvpath) votesTotal = electiondata.shape[0] khanIndex = electiondata.loc[electiondata["Candidate"] == "Khan"] khanTotal = khanIndex.shape[0] correyIndex = electiondata.loc[electiondata["Candidate"] == "Correy"] correyTotal = correyIndex.shape[0] liIndex = electiondata.loc[electiondata["Candidate"] == "Li"] liTotal = liIndex.shape[0] otooleyIndex = electiondata.loc[electiondata["Candidate"] == "O'Tooley"] otooleyTotal = otooleyIndex.shape[0] winnerIndex = electiondata['Candidate'].value_counts().to_frame() winningCandidate = winnerIndex.index[0] # winningCandidateTotal = winnerIndex.iloc[0,0] totalVotesText = f"Total Votes: {votesTotal}" khanText = f"Khan: {khanTotal / votesTotal:.3%} ({khanTotal})" correyText = f"Correy: {correyTotal / votesTotal:.3%} ({correyTotal})" liText = f"Li: {liTotal / votesTotal:.3%} ({liTotal})" otooleyText = f"O'Tooley: {otooleyTotal / votesTotal:.3%} ({otooleyTotal})" winnerText = f"Winner: {winningCandidate}" print("Election Results") print("------------------------------") print(totalVotesText) print("------------------------------") print(khanText) print(correyText) print(liText) print(otooleyText) print("------------------------------") print(winnerText) print("------------------------------") outputpath = os.path.join('.', 'analysis', 'poll_data.txt') with open(outputpath, 'w') as txtfile: txtfile.write("Election Results \n") txtfile.write("------------------------------ \n") txtfile.write(totalVotesText + " \n") txtfile.write("------------------------------ \n") txtfile.write(khanText + " \n") txtfile.write(correyText + " \n") txtfile.write(liText + " \n") txtfile.write(otooleyText + " \n") txtfile.write("------------------------------ \n") txtfile.write(winnerText + " \n") txtfile.write("------------------------------ \n")<file_sep>import os import pandas as pd csvpath = os.path.join('Resources', 'budget_data.csv') budgetdata = pd.read_csv(csvpath) budgetdata["Change"] = 0 for x in range(budgetdata.shape[0]): if x == 0: budgetdata.iloc[x,2] = 0 #First row gets assigned a zero because there's no change else: budgetdata.iloc[x, 2] = budgetdata.iloc[x, 1] - budgetdata.iloc[x-1, 1] averageChange = budgetdata["Change"].sum() / (budgetdata.shape[0] - 1) #Subtract 1 because of the header greatInc = budgetdata.loc[budgetdata["Change"] == budgetdata["Change"].max()] greatLoss = budgetdata.loc[budgetdata["Change"] == budgetdata["Change"].min()] totalMonthsText = f"Total Months: {len(budgetdata['Date'].unique())}" totalAmountText = f"Total: ${round(budgetdata['Profit/Losses'].sum())}" averageChangeText = f"Average Change: ${round(averageChange,2)}" greatIncText = f"Greatest Increase In Profits: {greatInc.iloc[0,0]} (${greatInc.iloc[0,2]})" greatLossText = f"Greatest Decrease In Profits: {greatLoss.iloc[0,0]} (${greatLoss.iloc[0,2]})" print("Financial Analysis") print("----------------------------------------------------") print(totalMonthsText) print(totalAmountText) print(averageChangeText) print(greatIncText) print(greatLossText) outputpath = os.path.join('analysis', 'bank_data.txt') with open(outputpath, 'w') as txtfile: txtfile.write("Financial Analysis \n") txtfile.write("---------------------------------------------------- \n") txtfile.write(totalMonthsText + " \n") txtfile.write(totalAmountText + " \n") txtfile.write(averageChangeText + " \n") txtfile.write(greatIncText + " \n") txtfile.write(greatLossText + " \n") <file_sep>import os import csv cereal_csv = os.path.join("../Resources", "cereal.csv") with open(cereal_csv, 'r') as csvfile: cereals = csv.reader(csvfile) next(cereals, None) for x in cereals: if float(x[7]) >= 5: print(x)
3b3045988a01f01032f2e71c000049e86d07ed0f
[ "Markdown", "Python" ]
5
Python
tdstark/TDS-GWU-Python1
34b38dd5646afce40a2055a65175d92e102713b6
3f808507b5a650bf3b6bf64f26c3500a39ec94b1
refs/heads/master
<file_sep># homework1-another-coverage- [![Build Status](https://travis-ci.org/mayufo/homework1-another-coverage-.svg?branch=master)](https://travis-ci.org/mayufo/homework1-another-coverage-) [![Coverage Status](https://coveralls.io/repos/github/mayufo/homework1-another-coverage-/badge.svg?branch=)](https://coveralls.io/github/mayufo/homework1-another-coverage-?branch=)<file_sep>/** * dcate * A list consisting of elements of A followed by the * elements of B. May modify items of A. * Don't use 'new' * @param {List} A * @param {List} B * @returns {List} */ function dcate(A, B) { /** Fill in here **/ if(!(A instanceof List) || !(B instanceof List)) { throw '对象A或对象B不是List类型,亲先定义' } var obj = A; while (obj.tail !== null) { obj = obj.tail; } obj.tail = B; return A; } /** * sub * The sublist consisting of LEN items from list L, * beginning with item #START (where the first item is #0). * Does not modify the original list elements. * it is an error if the desired items don't exist. * @param {List} L * @param {Number} start * @param {Number} len * @returns {List} */ function sub(L, start, len) { /** Fill in here **/ if( !(L instanceof List) || isNaN(parseInt(start, 10)) || isNaN(parseInt(len, 10)) ) { throw '参数有问题哦!亲 检查一下' } // 转为数组 var arr = getArray(L); if(arr.length - 3 < len) { throw 'len超过链表长度啦 亲' } return List.list(arr.slice(start, parseInt(start + len, 10))) } /** * 需要转换的对象 * @param data 对象 * @returns {Array} 返回数组 */ function getArray(data) { var array = []; while (data.tail !== null ) { array.push(data.head); data = data.tail; } array.push(data.head); return array; }
2d58d8a8cc72ac8d3f693e3935577a7149926bae
[ "Markdown", "JavaScript" ]
2
Markdown
mayufo/homework1-another-coverage-
b84d52703c7ee8c3b1a3e94989ffce04eedc6192
2f10232562a1436458342e2aa971d63cabac8368
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class portalToggle : MonoBehaviour { void Update() { Vector3 localForward = Vector3.zero - transform.position; float vectorDot = Vector3.Dot((Camera.main.transform.position - this.transform.position).normalized, localForward); if (vectorDot > 0) { this.GetComponent<BoxCollider>().enabled = true; } else if (vectorDot < 0) { this.GetComponent<BoxCollider>().enabled = false; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class cameraController : MonoBehaviour { public float rotateMultiplier, scrollMultiplier, zoomMultiplier, panMultiplier, zoomMinDistance, zoomMaxDistance; private float mousePosX, mousePosY; private Vector3 currentAngle; void Update() { cameraRotate(); cameraZoom(); cameraPan(); } void cameraRotate() { //MOVES CAMERA RIGHT AND LEFT //using keyboard D and A (or arrow keys) if (Input.GetKey(KeyCode.A) | Input.GetKey(KeyCode.LeftArrow)) transform.RotateAround(Vector3.zero, Vector3.up, rotateMultiplier * Time.deltaTime); else if (Input.GetKey(KeyCode.D) | Input.GetKey(KeyCode.RightArrow)) transform.RotateAround(Vector3.zero, Vector3.down, rotateMultiplier * Time.deltaTime); else if (Input.GetKey(KeyCode.Mouse0)) transform.RotateAround(Vector3.zero, Vector3.up, 2 * rotateMultiplier * Input.GetAxis("Mouse X") * Time.deltaTime); } void cameraZoom() { float zoomDistance = Vector3.Distance(Vector3.zero, transform.position); //MOVES THE CAMERA FORWARD AND BACKWARD //using keyboard W and S (or arrow keys) if (Input.GetKey(KeyCode.W) | Input.GetKey(KeyCode.UpArrow) && zoomDistance >= zoomMinDistance) transform.position = Vector3.MoveTowards(transform.position, Vector3.zero, zoomMultiplier * Time.deltaTime); else if (Input.GetKey(KeyCode.S) | Input.GetKey(KeyCode.DownArrow) && zoomDistance <= zoomMaxDistance) transform.position = Vector3.MoveTowards(transform.position, Vector3.zero, -zoomMultiplier * Time.deltaTime); //using scroll wheel else if (Input.GetKey(KeyCode.W) == false && Input.GetKey(KeyCode.S) == false) { if (Input.GetAxis("Mouse ScrollWheel") > 0 && zoomDistance >= zoomMinDistance) transform.position = Vector3.MoveTowards(transform.position, Vector3.zero, zoomMultiplier * scrollMultiplier * Time.deltaTime); else if (Input.GetAxis("Mouse ScrollWheel") < 0 && zoomDistance <= zoomMaxDistance) transform.position = Vector3.MoveTowards(transform.position, Vector3.zero, -zoomMultiplier * scrollMultiplier * Time.deltaTime); } } void cameraPan() { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class portalCamerasController : MonoBehaviour { public Transform cameraMain, worldMain, worldLocal; void Update () { Vector3 cameraMainOffset = cameraMain.position - worldMain.position; transform.position = worldLocal.position + cameraMainOffset; float portalAngularDifference = Quaternion.Angle(worldLocal.rotation, worldMain.rotation); Quaternion portalRotationalDifference = Quaternion.AngleAxis(portalAngularDifference, Vector3.up); Vector3 newCameraDirection = portalRotationalDifference * cameraMain.forward; transform.rotation = Quaternion.LookRotation(newCameraDirection, Vector3.up); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class cameraRaycast : MonoBehaviour { public Camera[] portalCameras; public GameObject[] portals; void Update() { if (Input.GetMouseButtonDown(0)) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // do we hit our portal plane? if (Physics.Raycast(ray, out hit)) { // casts a new ray from the corresponding portalCamera in the same direction Ray portalRay = new Ray(portalCameras[GetIndex(hit.collider.gameObject)].transform.position, ray.direction); Debug.DrawRay(portalCameras[GetIndex(hit.collider.gameObject)].transform.position, ray.direction); RaycastHit portalHit; // test these camera coordinates in another raycast test if (Physics.Raycast(portalRay, out portalHit)) { GameObject target = portalHit.collider.gameObject; if(target.GetComponent<customButton>()) target.GetComponent<customButton>().OnClick(); target.GetComponent<cubeLevitation>().multiplier += 25; } } } } int GetIndex(GameObject obj) { for (int i = 0; i < portals.Length; i++) { if (portals[i] == obj) { return i; } } return -1; } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class portalTextureSetup : MonoBehaviour { public Camera[] cameras; public Material[] cameraMaterials; void Start() { for (int i = 0; i < cameras.Length; i++) { if (cameras[i].targetTexture != null) { cameras[i].targetTexture.Release(); } cameras[i].targetTexture = new RenderTexture(Screen.width, Screen.height, 24); cameraMaterials[i].mainTexture = cameras[i].targetTexture; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class customButton : MonoBehaviour { [SerializeField] bool isLink; [SerializeField] string url; [SerializeField] GameObject gameManager; public void OnClick() { if (isLink) { gameManager.GetComponent<link>().OpenLinkJSPlugin(url); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class cubeLevitation : MonoBehaviour { public float amplitude, frequency; public Vector3 degreesPerSecond; Vector3 posOffset = new Vector3(); Vector3 tempPos = new Vector3(); public float multiplier = 1; float lerpValue; void Start() { posOffset = transform.position; amplitude *= Random.Range(.5f, 1.5f); degreesPerSecond = new Vector3(degreesPerSecond.x * Random.Range(-1.5f, 1.5f), degreesPerSecond.y * Random.Range(-1.5f, 1.5f), degreesPerSecond.z * Random.Range(-1.5f, 1.5f)); } void Update() { multiplier = Mathf.Lerp(multiplier, 1, Mathf.Pow(multiplier, 2)/100000); transform.Rotate(new Vector3(Time.deltaTime * multiplier * degreesPerSecond.x, Time.deltaTime * multiplier * degreesPerSecond.y, Time.deltaTime * multiplier * degreesPerSecond.z), Space.World); tempPos = posOffset; tempPos.y += Mathf.Sin(Time.fixedTime * Mathf.PI * frequency) * amplitude; transform.position = tempPos; } } <file_sep># LeithBA.com Unity 2018.2.7f1 WebGL concept for an interactive and playful personal website. ## Getting Started You can find a running version of the project on www.tiny.cc/leithba. Make sure your browser supports WebGL. This version is hosted on www.simmer.io. ## Prerequisites Feel free to clone or download the project on your local machine for development and testing purposes. You will need Unity 2018.2.7f1. ## Built With Unity 2018.2.7f1 ## Author <NAME> ## Acknowledgments Brackeys (www.brackeys.com) for the awesome portal tutorial <NAME> (www.zohra-mradz.com) for all the support and feedback
ecd1390238423fbf14355ee874feb6a45447f37c
[ "Markdown", "C#" ]
8
C#
LeithBA/LeithBA.com
fe8958ffdf6b8d5f253618cea8d007f65b144a5c
62ec0dd60d8750430c30ce733817f5e6d8e42935
refs/heads/master
<repo_name>vijaysaimutyala/AbbrevSearch<file_sep>/app/src/main/java/com/studioemvs/abbrevsearch/RecyclerViewAdapter.java package com.studioemvs.abbrevsearch; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; /** * Created by vijsu on 10-05-2017. */ public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ResultsViewHolder>{ private List<Abbrevation> abbrevationList; private Context context; public RecyclerViewAdapter(List<Abbrevation> abbrevationList, Context context) { this.abbrevationList = abbrevationList; this.context = context; } @Override public ResultsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.dummy_layout,parent,false); final ResultsViewHolder resultsViewHolder = new ResultsViewHolder(view); return resultsViewHolder; } @Override public void onBindViewHolder(ResultsViewHolder holder, int position) { Abbrevation abbrevation = abbrevationList.get(position); holder.term.setText(abbrevation.getTerm()); holder.definition.setText(abbrevation.getDefinition()); } @Override public int getItemCount() { return abbrevationList.size(); } public class ResultsViewHolder extends RecyclerView.ViewHolder{ TextView term,definition; public ResultsViewHolder(View itemView) { super(itemView); term = (TextView)itemView.findViewById(R.id.term); definition = (TextView)itemView.findViewById(R.id.definition); } } } <file_sep>/app/src/main/java/com/studioemvs/abbrevsearch/Abbrevation.java package com.studioemvs.abbrevsearch; /** * Created by vijsu on 09-05-2017. */ public class Abbrevation { public final String term; public final String definition; public Abbrevation(String term, String definition) { this.term = term; this.definition = definition; } public String getTerm() { return term; } public String getDefinition() { return definition; } } <file_sep>/app/src/main/java/com/studioemvs/abbrevsearch/AsyncResponse.java package com.studioemvs.abbrevsearch; /** * Created by vijsu on 05-01-2017. */ public interface AsyncResponse { void processFinish(String output); } <file_sep>/app/src/main/java/com/studioemvs/abbrevsearch/XmlParser.java package com.studioemvs.abbrevsearch; import android.util.Log; import android.util.Xml; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * Created by vijsu on 09-05-2017. */ public class XmlParser { private static final String ns = null; String TAG = "XmlParser"; public List<Abbrevation> parse(InputStream in) throws XmlPullParserException,IOException{ try { Log.d(TAG, "parsing the input data"); XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,false); parser.setInput(in,null); parser.nextTag(); return readFeed(parser); }finally { in.close(); } } private List<Abbrevation> readFeed(XmlPullParser parser) throws XmlPullParserException,IOException{ List<Abbrevation> results = new ArrayList<Abbrevation>(); Log.d(TAG, "readFeed: "+ns); parser.require(XmlPullParser.START_TAG,ns,"feed"); while (parser.next() != XmlPullParser.END_TAG){ if (parser.getEventType() != XmlPullParser.START_TAG){ continue; } String name = parser.getName(); if (name.equals("result")){ results.add(readResult(parser)); }else { skip(parser); } } return results; } private Abbrevation readResult(XmlPullParser parser) throws XmlPullParserException,IOException{ parser.require(XmlPullParser.START_TAG,ns,"result"); String term = null; String definition = null; while (parser.next() != XmlPullParser.END_TAG){ if (parser.getEventType() != XmlPullParser.START_TAG){ continue; } String name = parser.getName(); if (name.equals("term")){ term = readTerm(parser); }else if (name.equals("definition")){ definition = readDefinition(parser); }else { skip(parser); } } return new Abbrevation(term,definition); } private String readTerm(XmlPullParser parser) throws IOException,XmlPullParserException{ parser.require(XmlPullParser.START_TAG,ns,"term"); String term = readTerm(parser); parser.require(XmlPullParser.END_TAG,ns,"term"); return term; } private String readDefinition(XmlPullParser parser) throws IOException,XmlPullParserException{ parser.require(XmlPullParser.START_TAG,ns,"definition"); String definition = readDefinition(parser); parser.require(XmlPullParser.END_TAG,ns,"definition"); return definition; } // Skips tags the parser isn't interested in. Uses depth to handle nested tags. i.e., // if the next tag after a START_TAG isn't a matching END_TAG, it keeps going until it // finds the matching END_TAG (as indicated by the value of "depth" being 0). private void skip(XmlPullParser parser) throws XmlPullParserException, IOException { if (parser.getEventType() != XmlPullParser.START_TAG) { throw new IllegalStateException(); } int depth = 1; while (depth != 0) { switch (parser.next()) { case XmlPullParser.END_TAG: depth--; break; case XmlPullParser.START_TAG: depth++; break; } } } }
31b5684a7b80a2ef4bf47bc983c224ec743209aa
[ "Java" ]
4
Java
vijaysaimutyala/AbbrevSearch
8b2ac91c301a80acd7964da101877b6a7247b4e7
8ea801f30d9b5edfa08967a3ad49b25448f70505
refs/heads/master
<repo_name>Reagan1947/Noise_Reduction_hearing_aid_DL<file_sep>/spectrogram_part.py # coding = utf-8 import wave import struct from scipy import * from pylab import * # 读取wav文件,我这儿读了个自己用python写的音阶的wav wavefile = wave.open('D:/Noise_Reduction_hearing_aid_DL/wav_file/zted170919_4626690iTb.wav', 'r') # open for writing # 读取wav文件的四种信息的函数。期中numframes表示一共读取了几个frames,在后面要用到滴。 nchannels = wavefile.getnchannels() sample_width = wavefile.getsampwidth() framerate = wavefile.getframerate() numframes = wavefile.getnframes() # ------------绘图部分-------------- # # 参数Print # print("channel", nchannels) # print("sample_width", sample_width) # print("framerate", framerate) # print("numframes", numframes) # 建一个y的数列,用来保存后面读的每个frame的amplitude。 y = zeros(numframes) # for循环,readframe(1)每次读一个frame,取其前两位,是左声道的信息。右声道就是后两位啦。 # unpack是struct里的一个函数,用法详见http://docs.python.org/library/struct.html。简单说来就是把#packed的string转换成原来的数据,无论是什么样的数据都返回一个tuple。这里返回的是长度为一的一个 # tuple,所以我们取它的第零位。 for i in range(numframes): val = wavefile.readframes(1) left = val[0:2] # right = val[2:4] v = struct.unpack('h', left)[0] y[i] = v # framerate就是44100,文件初读取的值。然后本程序最关键的一步!specgram!实在太简单了。。。 Fs = framerate specgram(y, NFFT=1024, Fs=Fs, noverlap=900) show() # 参数介绍 https://blog.csdn.net/shenziheng1/article/details/53868684 # ---------------绘图部分结束------------------ # # ---------------特征提取---------------------- # <file_sep>/Schedule of the project.md # Schedule of the project # 项目时间表 * 2018/12/07 **Voice Deal: MFCC** ​ **音频处理: MFCC** <file_sep>/README.md # Noise_Reduction_hearing_aid_DL # 基于深度学习的可降噪助听器 > It's onlt the arithmetic for the noise reduction hearing aid. It will be built based on Deep Learning and Machine Learing. > 这是可降噪助听器的算法部分,算法基于深度学习以及机器学习实现。 <file_sep>/generative-models-master/GAN/auxiliary_classifier_gan/ac_gan_tensorflow.py import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import os mnist = input_data.read_data_sets('../../MNIST_data', one_hot=True) mb_size = 32 X_dim = mnist.train.images.shape[1] y_dim = mnist.train.labels.shape[1] z_dim = 10 h_dim = 128 eps = 1e-8 lr = 1e-3 d_steps = 3 def plot(samples): fig = plt.figure(figsize=(4, 4)) gs = gridspec.GridSpec(4, 4) gs.update(wspace=0.05, hspace=0.05) for i, sample in enumerate(samples): ax = plt.subplot(gs[i]) plt.axis('off') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect('equal') plt.imshow(sample.reshape(28, 28), cmap='Greys_r') return fig def xavier_init(size): in_dim = size[0] with tf.device('/cpu:0'): xavier_stddev = 1. / tf.sqrt(in_dim / 2.) return tf.random_normal(shape=size, stddev=xavier_stddev) X = tf.placeholder(tf.float32, shape=[None, X_dim]) y = tf.placeholder(tf.float32, shape=[None, y_dim]) z = tf.placeholder(tf.float32, shape=[None, z_dim]) G_W1 = tf.Variable(xavier_init([z_dim + y_dim, h_dim])) G_b1 = tf.Variable(tf.zeros(shape=[h_dim])) G_W2 = tf.Variable(xavier_init([h_dim, X_dim])) G_b2 = tf.Variable(tf.zeros(shape=[X_dim])) def generator(z, c): inputs = tf.concat(axis=1, values=[z, c]) with tf.device('/cpu:0'): G_h1 = tf.nn.relu(tf.matmul(inputs, G_W1) + G_b1) G_log_prob = tf.matmul(G_h1, G_W2) + G_b2 G_prob = tf.nn.sigmoid(G_log_prob) return G_prob with tf.device('/cpu:0'): D_W1 = tf.Variable(xavier_init([X_dim, h_dim])) D_b1 = tf.Variable(tf.zeros(shape=[h_dim])) D_W2_gan = tf.Variable(xavier_init([h_dim, 1])) D_b2_gan = tf.Variable(tf.zeros(shape=[1])) D_W2_aux = tf.Variable(xavier_init([h_dim, y_dim])) D_b2_aux = tf.Variable(tf.zeros(shape=[y_dim])) def discriminator(X): with tf.device('/cpu:0'): D_h1 = tf.nn.relu(tf.matmul(X, D_W1) + D_b1) out_gan = tf.nn.sigmoid(tf.matmul(D_h1, D_W2_gan) + D_b2_gan) out_aux = tf.matmul(D_h1, D_W2_aux) + D_b2_aux return out_gan, out_aux theta_G = [G_W1, G_W2, G_b1, G_b2] theta_D = [D_W1, D_W2_gan, D_W2_aux, D_b1, D_b2_gan, D_b2_aux] def sample_z(m, n): return np.random.uniform(-1., 1., size=[m, n]) def cross_entropy(logit, y): return -tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logit, labels=y)) G_sample = generator(z, y) D_real, C_real = discriminator(X) D_fake, C_fake = discriminator(G_sample) # Cross entropy aux loss C_loss = cross_entropy(C_real, y) + cross_entropy(C_fake, y) # GAN D loss D_loss = tf.reduce_mean(tf.log(D_real + eps) + tf.log(1. - D_fake + eps)) DC_loss = -(D_loss + C_loss) # GAN's G loss G_loss = tf.reduce_mean(tf.log(D_fake + eps)) GC_loss = -(G_loss + C_loss) D_solver = (tf.train.AdamOptimizer(learning_rate=lr) .minimize(DC_loss, var_list=theta_D)) G_solver = (tf.train.AdamOptimizer(learning_rate=lr) .minimize(GC_loss, var_list=theta_G)) sess = tf.Session() sess.run(tf.global_variables_initializer()) if not os.path.exists('out/'): os.makedirs('out/') i = 0 for it in range(1000000): X_mb, y_mb = mnist.train.next_batch(mb_size) z_mb = sample_z(mb_size, z_dim) _, DC_loss_curr = sess.run( [D_solver, DC_loss], feed_dict={X: X_mb, y: y_mb, z: z_mb} ) _, GC_loss_curr = sess.run( [G_solver, GC_loss], feed_dict={X: X_mb, y: y_mb, z: z_mb} ) if it % 1000 == 0: idx = np.random.randint(0, 10) c = np.zeros([16, y_dim]) c[range(16), idx] = 1 samples = sess.run(G_sample, feed_dict={z: sample_z(16, z_dim), y: c}) print('Iter: {}; DC_loss: {:.4}; GC_loss: {:.4}; Idx; {}' .format(it, DC_loss_curr, GC_loss_curr, idx)) fig = plot(samples) plt.savefig('out/{}.png' .format(str(i).zfill(3)), bbox_inches='tight') i += 1 plt.close(fig) <file_sep>/generative-models-master/GAN/auxiliary_classifier_gan/sdg.py import tensorflow as tf with tf.device('/gpu:1'): v1 = tf.constant([1.0, 2.0, 3.0], shape=[3], name='v1') v2 = tf.constant([1.0, 2.0, 3.0], shape=[3], name='v2') sumV12 = v1 + v2 with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess: print( sess.run(sumV12)) <file_sep>/software development document.md # software development document # 软件开发文档 * 2018/12/07 摘要:采用WMA格式声音文件,利用傅里叶快速转化绘制**频谱图**TTF快速傅里叶转换。 > 为什么采用WMA格式,格式的兼容性? > > TTF快速傅里叶转换与普通傅里叶转换区别? > > **为什么选择利用频谱图进行学习**?
209fb54f18d9dd94bee3482b3ee3de281ca27b71
[ "Markdown", "Python" ]
6
Python
Reagan1947/Noise_Reduction_hearing_aid_DL
858d8caeacf42c72d2fd792f104f6fa06b3b632d
375b6c38545a456e4ce0869650460e4ee461d450
refs/heads/master
<file_sep>INSERT INTO order_items (orderid, productid) VALUES ( $1, $2);<file_sep>function getProducts(req, res, next) { req.app .get("db") .getProducts() .then(response => { return res.status(200).json(response); }) .catch(err => console.log(err)); } function getProductsByCategory(req, res, next) { if (req.params.category === "all") { req.app .get("db") .getProducts() .then(response => { return res.status(200).json(response); }) .catch(console.log); } else { req.app .get("db") .getProductsByCategory(req.params.category) .then(response => { return res.status(200).json(response); }) .catch(console.log); } } module.exports = { getProducts, getProductsByCategory }; <file_sep>UPDATE users SET full_name = $1, email = $2, address = $3 , city = $4 , state = $5 , zipcode = $6 WHERE id = $7 RETURNING *;<file_sep>SELECT * FROM dummytable;<file_sep>import React from "react"; import { Switch, Route } from "react-router-dom"; import Home from "./components/Home/Home"; import Login from "./components/subcomponents/Login/Login"; import Shop from "./components/Shop/Shop"; import Contact from "./components/Contact/Contact"; import Cart from "./components/Cart/Cart"; import AccountPage from "./components/AccountPage/AccountPage"; import OrderSubmitted from "./components/OrderSubmitted/OrderSubmitted"; export default ( <Switch> <Route exact path="/" component={Home} /> <Route path="/login" component={Login} /> <Route path="/shop" component={Shop} /> <Route path="/contact" component={Contact} /> <Route path="/cart" component={Cart} /> <Route path="/account" component={AccountPage} /> <Route path="/ordersubmitted" component={OrderSubmitted} /> <Route path="*" render={() => ( <div> <p>NotFound</p> </div> )} /> </Switch> ); <file_sep>import React from "react"; import axios from "axios"; import swal from "sweetalert"; import { withRouter } from "react-router"; import RaisedButton from "material-ui/RaisedButton"; import { connect } from "react-redux"; import { getUser } from "../../../ducks/reducer"; function Logout(props) { return ( <RaisedButton onClick={() => { swal("Successfully Logged Out"); axios .get("/api/logout") .then(response => { console.log("/logged out"); props.getUser().then(props.history.push("/login")); }) .catch(err => console.log(err)); }} className="LittleMargin" backgroundColor="#C7F3EB" > Logout </RaisedButton> ); } function mapStateToProps(state) { return state; } export default withRouter(connect(mapStateToProps, { getUser })(Logout)); <file_sep>import React from "react"; import Checkout from "../subcomponents/Checkout/Checkout"; import { connect } from "react-redux"; import { getCart, getUser, checkOut } from "../../ducks/reducer"; import CartDiv from "../subcomponents/ProductCard/CartDiv"; import axios from "axios"; import "../subcomponents/ProductCard/CartDiv.css"; import _ from "lodash"; import { withRouter } from "react-router-dom"; import swal from "sweetalert"; import RaisedButton from "material-ui/RaisedButton"; class Cart extends React.Component { constructor() { super(); this.state = { cartBasket: [] }; this.handleClick = this.handleClick.bind(this); this.handleProductionClick = this.handleProductionClick.bind(this); this.redirect = this.redirect.bind(this); } componentDidMount() { this.props.getCart(); } precisionRound(number, precision) { let factor = Math.pow(10, precision); return Math.round(number * factor) / factor; } redirect() { window.location.href = "/#/ordersubmitted"; } handleClick() { this.props.getCart(); } handleProductionClick() { console.log(this.props); if (this.props && this.props.cart.length > 0) { this.redirect(); } else { swal({ text: "Put something in your cart" }); } } render() { let cartBasket = this.props.cart.length > 0 ? _.uniqWith(this.props.cart, _.isEqual).map((val, index) => { let quantity = this.props.cart.filter( item => item.name === val.name ).length; return ( <CartDiv handleClick={this.handleClick} item={val} quantity={quantity} key={index} /> ); }) : "Nothing In Basket"; return ( <div> <h1>Total: ${this.precisionRound(this.props.total, 2) || "0"} </h1> <div className="flex column center"> <Checkout handleClick={this.handleClick} name={"<NAME>"} description={"Green"} amount={this.precisionRound(this.props.total * 1.0875, 2) || 1} onClick={this.handleClick} redirect={this.redirect} /> {true ? ( <RaisedButton onClick={this.handleProductionClick} redirect={this.redirect} label="Checkout" primary={true} className="LittleMargin" /> ) : ( "" )} </div> <div>{cartBasket}</div> </div> ); } } function mapStateToProps(state) { const { cart } = state; return state; } export default withRouter( connect(mapStateToProps, { getCart, getUser, checkOut })(Cart) ); <file_sep>SELECT * FROM orders o JOIN order_items oi ON o.orderid = oi.orderid JOIN products p ON oi.productid = p.id WHERE o.orderid = $1;<file_sep>import React from "react"; import swal from "sweetalert"; import Img from "../../imgs/jeremy-bishop-74123-unsplash.jpg"; import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from "material-ui/Card"; import FlatButton from "material-ui/FlatButton"; import Card2Point0 from "../subcomponents/ProductCard/Card2Point0"; function Home() { return <div className="Home" />; } export default Home; <file_sep>import React from "react"; import { connect } from "react-redux"; import { getUser, getOrders, getUserOrders } from "../../ducks/reducer"; import AccountInfo from "../subcomponents/AccountInfo/AccountInfo"; import Logout from "../subcomponents/Login/Logout"; import OrdersTable from "../subcomponents/OrdersTable/OrdersTable"; import TextField from "material-ui/TextField"; class AccountPage extends React.Component { constructor() { super(); this.state = { userInput: "", toggle: false }; this.handleClick = this.handleClick.bind(this); } componentDidMount() { this.props.getUser().then(response => { if (this.props.user.admin) { this.props.getOrders(); } else { this.props.getUserOrders(this.props.user.id); } }); } handleClick() { if (this.props.user.admin) { this.props.getOrders(this.state.userInput); } else { this.props.getUserOrders(this.state.userInput); } } clickHandler(id) { document.getElementById(id).value; } render() { return ( <div> <h1>{`Hello, ${this.props.user.full_name}`}</h1> <Logout /> <AccountInfo /> <button onClick={() => this.setState({ toggle: !this.state.toggle })}> Show Orders </button> {this.state.toggle ? ( <div> <div className="orderInput"> <input placeholder="Search By Order ID" id="ordersCriteria" onChange={e => this.setState({ userInput: e.target.value })} /> <button className="" onClick={this.handleClick}> Search </button> </div> <OrdersTable orders={this.props.orders} /> </div> ) : ( "" )} </div> ); } } function mapStateToProps(state) { const { user, orders } = state; return { user, orders }; } export default connect(mapStateToProps, { getUser, getOrders, getUserOrders })( AccountPage ); <file_sep>import React from "react"; import OrderRow from "./OrderRow"; import "./OrdersTable.css"; class OrdersTable extends React.Component { render() { let orders = this.props.orders; let ordersReel = []; let tableHead = []; let tableCells = []; if (orders && orders.length > 0) { for (let key in orders[0]) { if (key != "imgurl" && key != "id") { tableHead.push(<th>{key}</th>); } } orders.forEach((val, index) => ordersReel.push(<OrderRow key={index} orders={val} />) ); } return ( <table className="OrdersTable greyGridTable"> <thead> <tr>{tableHead}</tr> </thead> <tbody>{ordersReel}</tbody> </table> ); } } export default OrdersTable; <file_sep>import React from "react"; import axios from "axios"; import { connect } from "react-redux"; import { getProducts, searchProductsName } from "../../ducks/reducer"; import ProductCard from "../subcomponents/ProductCard/ProductCard"; import { BeatLoader } from "react-spinners"; import RaisedButton from "material-ui/RaisedButton"; import "../subcomponents/ProductCard/ProductCard.css"; import TextField from "material-ui/TextField"; import Card2Point0 from "../subcomponents/ProductCard/Card2Point0"; import Example from "../ExampleComponent"; class Shop extends React.Component { constructor() { super(); this.state = { category: "" }; this.selectClick = this.selectClick.bind(this); this.handleClick = this.handleClick.bind(this); } componentDidMount() { this.props.getProducts(); } handleClick() { let query = document.getElementById("NameSearch").value; if (query) { this.props.searchProductsName(this.state.category, query); } else { this.props.getProducts(this.state.category); } } selectClick(e) { // console.log(e); this.setState({ category: e }); if (e === "Select a Category") { this.props.getProducts(""); return; } this.props.getProducts(e); } render() { let cardReel = this.props.products.length > 0 ? ( this.props.products.map((val, index) => { return ( <Card2Point0 user={this.props.user} product={val} key={index} /> ); }) ) : ( <BeatLoader color="#36D7B7" /> ); return ( <div className="Shop"> <h1>Shop</h1> <div className="buttonBar"> <RaisedButton label="All" onClick={() => this.selectClick("all")} /> <RaisedButton label="Seeds" onClick={() => this.selectClick("seed")} /> <RaisedButton label="Soil" onClick={() => this.selectClick("soil")} /> <RaisedButton label="Fertilizer" className="getBack" onClick={() => this.selectClick("fertilizer")} /> <RaisedButton label="Garden Utensils" onClick={() => this.selectClick("garden utensil")} /> </div> <TextField hintText="SearchByName" id="NameSearch" className="NameSearch" /> <RaisedButton label="Search" style={{ margin: 12 }} onClick={() => this.handleClick()} primary={true} /> <div className="Gallery flex center column">{cardReel}</div> </div> ); } } function mapStateToProps(state) { const { products } = state; return state; } export default connect(mapStateToProps, { getProducts, searchProductsName })( Shop ); <file_sep>module.exports = { updateUserInfo: (req, res, next) => { const { body } = req; req.app .get("db") .updateUserInfo( body.full_name, body.email, body.address, body.city, body.state, body.zipcode, req.user.id ) .then(response => { let obj = response[0]; console.log("OBJ, ", obj); req.session.passport.user = obj; res.status(200).send(response); }) .catch(console.log); }, deleteUser: (req, res, next) => { req.app .get("db") .deleteUser(req.params.id) .then(response => { req.user = {}; req.session.destroy(() => { res.redirect(`${process.env.REDIRECT_URIS}`); }); }) .catch(err => console.log(err)); }, submitMessage: (req, res, next) => { const { body } = req; req.app .get("db") .submitMessage(body.full_name, body.email, body.message) .then(response => { res.status(200).send(response); }) .catch(err => console.log(err)); } }; <file_sep>import React from "react"; import FloatingActionButton from "material-ui/FloatingActionButton"; import ContentAdd from "material-ui/svg-icons/content/add"; import ContentRemove from "material-ui/svg-icons/content/remove"; import axios from "axios"; class CartDiv extends React.Component { constructor(props) { super(props); this.addToCart = this.addToCart.bind(this); this.deleteFromCart = this.deleteFromCart.bind(this); this.remove = this.remove.bind(this); } addToCart(e) { axios .post(`/api/cart/${this.props.item.id}`) .then(response => this.props.handleClick()); } deleteFromCart(e) { axios .delete(`/api/cart/${this.props.item.id}`) .then(response => this.props.handleClick()); } remove() { axios .delete(`/api/cart/all/${this.props.item.id}`) .then(response => this.props.handleClick().then(response => this.props.redirect()) ); } render() { return ( <div className="CartDiv"> <img src={this.props.item.imgurl} className="CartDivImg" /> <h3>{this.props.item.name}</h3> <table /> <div> <p>Qty: {this.props.quantity}</p>{" "} <FloatingActionButton onClick={this.addToCart} mini={true}> <ContentAdd /> </FloatingActionButton>{" "} <FloatingActionButton onClick={this.deleteFromCart} mini={true}> <ContentRemove /> </FloatingActionButton> </div> <button onClick={this.remove}>Remove</button> <h4>Price: {this.props.item.price * this.props.quantity}</h4> </div> ); } } export default CartDiv; <file_sep>import React from "react"; import { connect } from "react-redux"; import { getUser, editUserInfo, deleteUser } from "../../../ducks/reducer.js"; import TextField from "material-ui/TextField"; import axios from "axios"; import swal from "sweetalert"; import IconButton from "material-ui/IconButton"; import ActionSave from "material-ui/svg-icons/content/save"; import RaisedButton from "material-ui/RaisedButton"; import { withRouter } from "react-router"; class AccountInfo extends React.Component { constructor() { super(); this.state = { full_name: "", email: "", address: "", city: "", state: "", zipcode: 0 }; this.handleClick = this.handleClick.bind(this); this.deleteClick = this.deleteClick.bind(this); } componentDidMount() { this.props.getUser().then(response => this.setState({ full_name: this.props.user.full_name, email: this.props.user.email, address: this.props.user.address, city: this.props.user.city, state: this.props.user.state, zipcode: this.props.user.zipcode }) ); } handleClick(body) { this.props.editUserInfo(body).then(response => { swal({ title: "Good job!", text: "Profile Updated!" }); this.props.getUser(); // .then(response => // this.setState({ // full_name: this.props.user.full_name, // email: this.props.user.email, // address: this.props.user.address, // city: this.props.user.city, // state: this.props.user.state, // zipcode: this.props.user.zipcode // }) // ); }); } deleteClick(id) { this.props.deleteUser(id).then(response => { this.props.history.push("/login"); this.props.getUser(); }); } render() { return ( <div className="AccountInfo"> <div className="AInfo"> <h2>Account Info</h2> <div className="SaveChangesMobi"> <IconButton onClick={() => // prettier-ignore this.handleClick(this.state) } tooltip="Save Changes" touch={true} tooltipPosition="top-left" > <ActionSave /> </IconButton> </div> </div> <div className="flex"> <h3>Name: </h3> <TextField id="account-name-input" defaultValue={this.props.user.full_name} onChange={e => this.setState({ full_name: e.target.value })} /> </div> <div className="flex emailinfo"> <h3>Email: </h3> <TextField id="text-field-default" defaultValue={this.props.user.email} onChange={e => this.setState({ email: e.target.value })} /> </div> <div className="flex adressinfo"> <h3>Address: </h3> <TextField id="text-field-default" defaultValue={this.props.user.address} onChange={e => this.setState({ address: e.target.value })} /> </div> <div className="flex cityinfo"> <h3>City: </h3> <TextField id="text-field-default" defaultValue={this.props.user.city} onChange={e => this.setState({ city: e.target.value })} /> </div> <div className="flex stateinfo"> <h3>State: </h3> <TextField id="text-field-default" defaultValue={this.props.user.state} onChange={e => this.setState({ state: e.target.value })} /> </div> <div className="flex zipcodeinfo"> <h3>Zipcode: </h3> <TextField id="text-field-default" defaultValue={this.props.user.zipcode} onChange={e => this.setState({ zipcode: e.target.value })} /> </div> <div className="SaveChangesDsktp"> <RaisedButton label="Save Changes" primary={true} style={{ margin: 12, alignSelf: "center" }} onClick={() => // prettier-ignore this.handleClick(this.state) } /> <RaisedButton label="Delete Account" secondary={true} style={{ margin: 12, alignSelf: "center" }} onClick={() => { if (window.confirm("Do you really want to delete you account?")) { console.log(this.props.user); this.deleteClick(this.props.user.id); } }} /> </div> </div> ); } } function mapStateToProps(state) { return state; } export default withRouter( connect(mapStateToProps, { getUser, editUserInfo, deleteUser })(AccountInfo) ); <file_sep>INSERT INTO messages (full_name, email, message) VALUES ($1, $2, $3);<file_sep>module.exports = { getOrders: (req, res, next) => { req.app .get("db") .getOrders() .then(response => res.status(200).send(response)) .catch(err => console.log(err)); }, getOrderById: (req, res, next) => { req.app .get("db") .getOrderById(req.params.id) .then(response => res.status(200).send(response)) .catch(console.log); }, getOrderByUser: (req, res, next) => { if (req.params.id) { req.app .get("db") .getOrderByUser(req.params.id) .then(response => { console.log(req.params.id); res.status(200).send(response); }) .catch(console.log); } else { res.status(500).send(console.log("No User From Request")); } } }; <file_sep>import React from "react"; import axios from "axios"; import { connect } from "react-redux"; import { checkOut, getOrders, getCart } from "../../ducks/reducer"; import { BeatLoader } from "react-spinners"; import OrdersTable from "../subcomponents/OrdersTable/OrdersTable"; class OrderSubmitted extends React.Component { constructor() { super(); this.state = { order: [], toggle: false }; } componentDidMount() { this.props .checkOut() .then(response => this.props .getOrders(this.props.currentOrder[0].orderid) .then(response => this.props.getCart()) ); } render() { return ( <div> <h2>Order Successful</h2> <h5>Review Order Summary</h5> <button label="this.props.getOrders(this.props.currentOrder[0].orderid)" onClick={() => { this.setState({ toggle: !this.state.toggle }); this.props.getOrders(this.props.currentOrder[0].orderid); }} > Order Summary </button> {this.state.toggle ? ( <h6> {this.props.currentOrder.length > 0 ? ( <div> <OrdersTable orders={this.props.orders} /> </div> ) : ( <BeatLoader color="#36D7B7" /> )} </h6> ) : ( " " )} </div> ); } } function mapStateToProps(state) { return state; } export default connect(mapStateToProps, { checkOut, getOrders, getCart })( OrderSubmitted ); <file_sep>import React from "react"; import "./Hamburger.css"; function animate(x) { x.classList.toggle("change"); } function Hamburger() { return ( <div className="Hamburger" onClick={e => animate(e.target)}> <div className="bar1" /> <div className="bar2" /> <div className="bar3" /> </div> ); } export default Hamburger; <file_sep>import React from "react"; import axios from "axios"; import RaisedButton from "material-ui/RaisedButton"; class Login extends React.Component { componentDidMount() { axios.get("/api/me"); } render() { return ( <div> <a href={process.env.REACT_APP_LOGIN}> <RaisedButton className="LittleMargin" backgroundColor="#C7F3EB"> Login </RaisedButton> </a> </div> ); } } export default Login; <file_sep>import React from "react"; import Logo from "../../imgs/Seed-Logo.png"; import { Link } from "react-router-dom"; import Hamburger from "../subcomponents/Hamburger/Hamburger"; import Auth from "../subcomponents/Login/Auth"; export default class Header extends React.Component { constructor() { super(); this.state = { activeId: "" }; this.handleClick = this.handleClick.bind(this); } handleClick(e) { if (this.state.activeId) { document.getElementById(this.state.activeId).classList.remove("active1"); } document.getElementById(e.target.id).classList.add("active1"); this.setState({ activeId: e.target.id }); } responsivity() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; } } render() { return ( <header> <div className="flex center header"> <Link to="/"> <img src={Logo} className="Header-Logo" /> </Link> <Link to="/"> <h1>Seeds</h1> </Link> </div> <div className="NavLinks"> <div className="topnav" id="myTopnav" onClick={() => { this.responsivity(); }} > <div className="Nav-Item" id="Hamburger"> <Hamburger /> </div> <Link to="/"> <div className="Nav-Item" id="Home" onClick={e => this.handleClick(e)} > Home </div> </Link> <Link to="/Shop"> <div className="Nav-Item" id="Shop" onClick={e => this.handleClick(e)} > Shop </div> </Link> <Link to="/Cart"> <div className="Nav-Item" id="Cart" onClick={e => this.handleClick(e)} > Cart </div> </Link> <Link to="/contact"> <div className="Nav-Item" id="Contact" onClick={e => this.handleClick(e)} > Contact Us </div> </Link> <div id="Auth" className="Login/Logout" onClick={e => this.handleClick(e)} > <Auth onClick={this.handleClick} id="Auth" className="Login/Logout" /> </div> </div> </div> </header> ); } } <file_sep>import axios from "axios"; const GET_PRODUCTS = "GET_PRODUCTS"; const SEARCH_PRODUCTS_NAME = "SEARCH_PRODUCTS_NAME"; const GET_CART = "GET_CART"; const CLEAR_CART = "CLEAR_CART"; const GET_USER = "GET_USER"; const GET_ORDERS = "GET_ORDERS"; const GET_USER_ORDERS = "GET_USER_ORDERS"; const CHECKOUT = "CHECKOUT"; const EDIT_USER_INFO = "EDIT_USER_INFO"; const DELETE_USER = "DELETE_USER"; export function getProducts(param) { return { type: GET_PRODUCTS, payload: axios .get(`/api/getProducts${param ? "/" + param : ""}`) .then(response => { return response.data; }) .catch(() => []) }; } export function searchProductsName(category, query) { return { type: SEARCH_PRODUCTS_NAME, payload: axios .get(`/api/getProducts${category ? "/" + category : ""}`) .then(response => { return response.data.filter((val, index) => { return val.name.toLowerCase().includes(query.toLowerCase()); }); }) .catch(() => []) }; } export function getCart() { return { type: GET_CART, payload: axios .get("/api/cart") .then(response => { return response.data; }) .catch(() => []) }; } export function clearCart() { return { type: CLEAR_CART, payload: axios .delete("/api/clearcart") .then(response => { return response.data; }) .catch(() => []) }; } export function getUser() { return { type: GET_USER, payload: axios .get("/api/me") .then(response => { return response.data; }) .catch(() => ({})) }; } export function getOrders(criteria) { return { type: GET_ORDERS, payload: axios .get(`/api/orders${criteria ? "/" + criteria : ""}`) .then(response => response.data) .catch(() => []) }; } export function getUserOrders(uid) { return { type: GET_USER_ORDERS, payload: axios .get(`/api/userOrders/${uid}`) .then(response => response.data) .catch(() => []) }; } export function checkOut() { return { type: CHECKOUT, payload: axios .get("/api/checkOut") .then(response => { console.log(response.data); return response.data; }) .catch(() => ({})) }; } export function editUserInfo(body) { return { type: EDIT_USER_INFO, //body must be an object payload: axios .put("/api/edit", body) .then(response => { return response.data; }) .catch(() => ({})) }; } export function deleteUser(id) { return { type: DELETE_USER, payload: axios.delete(`/api/deleteUser/${id}`).catch(() => ({})) }; } const initialState = { products: [], isLoading: false, didErr: false, cart: [], total: 0, user: {}, orders: [], currentOrder: {} }; export default function reducer(state = initialState, action) { switch (action.type) { case `${SEARCH_PRODUCTS_NAME}_PENDING`: return Object.assign({}, state, { isLoading: true }); case `${SEARCH_PRODUCTS_NAME}_FULFILLED`: return Object.assign({}, state, { isLoading: false, products: action.payload }); case `${SEARCH_PRODUCTS_NAME}_REJECTED`: return Object.assign({}, state, { isLoading: false, didErr: true }); case `${DELETE_USER}_PENDING`: return Object.assign({}, state, { isLoading: true }); case `${DELETE_USER}_FULFILLED`: return Object.assign({}, state, { isLoading: false }); case `${DELETE_USER}_REJECTED`: return Object.assign({}, state, { isLoading: false, didErr: true }); case `${GET_USER}_PENDING`: return Object.assign({}, state, { isLoading: true }); case `${GET_USER}_FULFILLED`: return Object.assign({}, state, { isLoading: false, user: action.payload }); case `${GET_USER}_REJECTED`: return Object.assign({}, state, { isLoading: false, didErr: true }); case `${EDIT_USER_INFO}_PENDING`: return Object.assign({}, state, { isLoading: true }); case `${EDIT_USER_INFO}_FULFILLED`: return Object.assign({}, state, { isLoading: false, //user must be given req.user via backend user: action.payload }); case `${EDIT_USER_INFO}_REJECTED`: return Object.assign({}, state, { isLoading: false, didErr: true }); case `${CHECKOUT}_PENDING`: return Object.assign({}, state, { isLoading: true }); case `${CHECKOUT}_FULFILLED`: return Object.assign({}, state, { isLoading: false, currentOrder: action.payload }); case `${CHECKOUT}_REJECTED`: return Object.assign({}, state, { isLoading: false, didErr: true }); case `${GET_USER_ORDERS}_PENDING`: return Object.assign({}, state, { isLoading: true }); case `${GET_USER_ORDERS}_FULFILLED`: return Object.assign({}, state, { isLoading: false, orders: action.payload }); case `${GET_USER_ORDERS}_REJECTED`: return Object.assign({}, state, { isLoading: false, didErr: true }); case `${GET_ORDERS}_PENDING`: return Object.assign({}, state, { isLoading: true }); case `${GET_ORDERS}_FULFILLED`: return Object.assign({}, state, { isLoading: false, orders: action.payload }); case `${GET_ORDERS}_REJECTED`: return Object.assign({}, state, { isLoading: false, didErr: true }); case `${GET_PRODUCTS}_PENDING`: return Object.assign({}, state, { isLoading: true }); case `${GET_PRODUCTS}_FULFILLED`: return Object.assign({}, state, { isLoading: false, products: action.payload }); case `${GET_PRODUCTS}_REJECTED`: return Object.assign({}, state, { isLoading: false, didErr: true }); case `${GET_CART}_PENDING`: return Object.assign({}, state, { isLoading: true }); case `${GET_CART}_FULFILLED`: return Object.assign({}, state, { isLoading: false, cart: action.payload.cart, total: action.payload.total }); case `${GET_CART}_REJECTED`: return Object.assign({}, state, { isLoading: false, didErr: true }); default: return state; } }
6f7ba3e6d054ddb6e5c6b57b662d387519c2a766
[ "JavaScript", "SQL" ]
22
SQL
garmeil/dm11-personal-project
b32d0c896deb41931ac00e41c7ee8a58063ecce1
f9c4643b03f4aa898e6f1d849e0d8b9305854533
refs/heads/master
<repo_name>HOllarves/Etherum-Github-Donations<file_sep>/src/App.js import React, { Component } from 'react' import GithubRegister from '../build/contracts/GithubRegister.json' import getWeb3 from './utils/getWeb3' import './css/oswald.css' import './css/open-sans.css' import './css/pure-min.css' import './alert.css' import './App.css' class App extends Component { constructor(props) { super(props) const contract = require('truffle-contract'); this.state = { storageValue: 0, web3: null, userSearch: "", githubRegisterContract: contract(GithubRegister), contractInstance: {}, username: "", email: "", repoUrl: "", account: "", currentCoder: {}, alert: false } this.getCoder = this.getCoder.bind(this); this.updateSearch = this.updateSearch.bind(this); this.handleRegisterForm = this.handleRegisterForm.bind(this); this.addCoder = this.addCoder.bind(this); this.setDonation = this.setDonation.bind(this); this.makeDonation = this.makeDonation.bind(this); } componentWillMount() { // Get network provider and web3 instance. getWeb3 .then(results => { this.setState({ web3: results.web3, alert: false }); // Instantiate contract once web3 provided. this.instantiateContract(); }) .catch(() => { this.setState({ alert: "Error finding web3." }) }) } /** * Updates search string * @param {*} event */ updateSearch(event) { this.setState({ userSearch: event.target.value }); } /** * Calls the smartcontract to get a specific * developer * @param {*} event */ getCoder(event) { event.preventDefault(); this.state.contractInstance.getCoder(this.state.userSearch) .then((result) => { if (result[0] !== "") { this.currentCoder = this.extractCoder(result) this.setState({ currentCoder: this.currentCoder, alert: false }) } else { this.setState({ alert: "Developer not found" }) } }).catch((err) => { this.setState({ alert: "Developer not found" }) }) } /** * Transforms data recieved from the smart contract * to a simple javascript object * @param {*} data */ extractCoder(data) { return { name: data[0] ? data[0] : null, email: data[1] ? data[1] : null, repo: data[2] ? data[2] : null } } /** * Handles submission of * register form. Github's OAuth should be implemented * to avoid fraudulent registers. Due to time restrains I won't * be compeleting such feature. * @param {*} event */ handleRegisterForm(event) { const value = event.target.value; const name = event.target.name; this.setState({ [name]: value }); } /** * Adds a new developer to the * blockchain * @param {*} event */ addCoder(event) { event.preventDefault(); this.state.contractInstance.addCoder(this.state.username, this.state.email, this.state.repoUrl, { from: this.state.account }) .then((result) => { this.setState({ alert: false }) }).catch((err) => { this.setState({ alert: "Unable to add developer. Check logs!" }); console.log(err) }) } /** * Instantiates contract in the browser * and saves its instance in the state variable */ instantiateContract() { this.state.githubRegisterContract.setProvider(this.state.web3.currentProvider); this.state.web3.eth.getAccounts((error, accounts) => { this.state.githubRegisterContract.deployed().then((instance) => { this.setState({ contractInstance: instance, account: accounts[0], alert: false }); }) }) } /** * Performs a donation to a specific * developer. */ makeDonation() { console.log("Making donation") this.state.contractInstance.donateToCoder(this.state.username, { from: this.state.account, value: this.state.currentCoder.donation }) .then((result) => { this.setState({ alert: false }) }).catch((err) => { this.setState({ alert: "Unable to make donation. Check logs!" }); console.log(err) }) } /** * Updates inteded donation so it's correctly sent * when submitted. * @param {*} event */ setDonation(event) { this.currentCoder.donation = event.target.value * 1000000000000000000; this.setState({ currentCoder: this.currentCoder }); } render() { return ( <div className="App"> { this.state.alert ? <div id="alert"> <a className="alert">{this.state.alert}</a> </div> : null } <nav className="navbar pure-menu pure-menu-horizontal"> <a href="#" className="pure-menu-heading pure-menu-link">Donate to code</a> </nav> <main className="container"> <div className="pure-g"> <div className="pure-u-1-1"> <h1> Make a donation to your favorite coders with Ethereum!</h1> </div> <div className="pure-u-1-1"> <form className="pure-form" onSubmit={(e) => { this.getCoder(e); }}> <fieldset> <input type="text" placeholder="Username" className="pure-input-1-2" onChange={(e) => { this.updateSearch(e); }} /> <button type="submit" className="pure-button pure-button-primary">Search</button> </fieldset> </form> </div> {this.currentCoder && <div className="pure-u-1-1 coder-container"> <h1> Name: {this.state.currentCoder.name} </h1> <h1> Email: {this.state.currentCoder.email} </h1> <h1> Repo: <a href={this.state.currentCoder.repo} target="_blank">{this.state.currentCoder.repo}</a> </h1> <label> Donation (in ether): </label> <input className="pure-input-1-2" onChange={this.setDonation} type="number" /> <button className="pure-button pure-button-primary" onClick={this.makeDonation}> Donate </button> </div> } </div> <div className="pure-g"> <div className="pure-u-1-1"> <h1> Or, if you're a coder... Add yourself to recieve donations!</h1> </div> <div className="pure-u-1-2"> <form className="pure-form pure-form-stacked" onSubmit={(e) => { this.addCoder(e); }}> <fieldset> <legend>Please fill out some basic information: </legend> <label>Username: </label> <input name="username" id="user_name" type="text" placeholder="Username" onChange={this.handleRegisterForm} className="pure-input-1" /> <label>Email: </label> <input name="email" id="email" type="email" placeholder="Email" onChange={this.handleRegisterForm} className="pure-input-1" /> <label>Repo URL: </label> <input name="repoUrl" id="repo_url" type="text" placeholder="https://github.com/SomeUserName" onChange={this.handleRegisterForm} className="pure-input-1" /> <button type="submit" className="pure-button pure-button-primary ">Submit</button> </fieldset> </form> </div> </div> </main> </div> ); } } export default App <file_sep>/README.md # Etherum powered Github search This project was built using Truffle and OpenZepelling for The School of AI's Descentralized Application course 2nd submission. To run a local installation of truffle is required. You can download and install truffle following [these steps](https://github.com/trufflesuite/truffle). In my case, I used Ganache for use of the internal testrpc. For different types of deployments, settings in `truffle.js` must be tweaked. Run `truffle compile` and `truffle migrate` to push the contract to your blockchain of choice, and finally run `npm start` to start your local webserver that runs the react interface with truffle. Look for your favorite developer in the community and make a donation. Otherwise, register yourself with your username, email and github repository so other user can make donations to you. ## Warning This is just an example. No oauth is implemented so anyone can register as anyone else. Again, this is just a homework assignment :). <file_sep>/migrations/2_deploy_contracts.js var GithubRegister = artifacts.require("./GithubRegister.sol"); module.exports = function(deployer) { deployer.deploy(GithubRegister); };
c607a93d1176e69c034a3b35b322ba47129ff6dd
[ "JavaScript", "Markdown" ]
3
JavaScript
HOllarves/Etherum-Github-Donations
7efcb0e9212995623f008c0cb5c48f78d4aeedaf
fcf0e03006d5bd864dcb37c2ab0a686fd2427c61
refs/heads/master
<file_sep>using System; using System.Collections.Generic; namespace MIProject { #if WINDOWS || XBOX static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { System.IO.StreamReader file = new System.IO.StreamReader("newdata2.txt"); int n = Int32.Parse(file.ReadLine()); int m = Int32.Parse(file.ReadLine()); int mario_x = Int32.Parse(file.ReadLine()); int mario_y = Int32.Parse(file.ReadLine()); int diamonds_count = Int32.Parse(file.ReadLine()); List<int> diamonds_list = new List<int>(diamonds_count * 2); for (int i = 0; i < diamonds_count * 2; i++) { diamonds_list.Add(Int32.Parse(file.ReadLine())); } int rocks_count = Int32.Parse(file.ReadLine()); List<int> rocks_list = new List<int>(rocks_count * 2); for (int i = 0; i < rocks_count*2; i++ ) rocks_list.Add(Int32.Parse(file.ReadLine())); int concrete_count = Int32.Parse(file.ReadLine()); List<int> concrete_list = new List<int>(concrete_count * 2); for (int i = 0; i < concrete_count * 2; i++) concrete_list.Add(Int32.Parse(file.ReadLine())); file.Close(); using (Game1 game = new Game1(n, m, mario_x, mario_y, diamonds_count, diamonds_list, rocks_count, rocks_list, concrete_count, concrete_list)) { game.Run(); } } } #endif } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace testproject2 { public class Game { // Singleton private static Game instance = null; private Game() { } public static Game Instance { get { if (instance==null) { instance = new Game(); } return instance; } } public static Game NewInstance { get { instance = new Game(); return instance; } } // Fields private Int32 mapXSize = 0, mapYSize = 0; private Point initialLocation = new Point(0, 0); private List<Point> diamonds = new List<Point>() { }, rocks = new List<Point>() { }, walls = new List<Point>() { }; private List<Node> goals = new List<Node>(); private Node[,] nodeGrid = {}; // Properties public Point InitialLocation { get { return initialLocation; } } public Int32 MapXSize { get { return mapXSize; } } public Int32 MapYSize { get { return mapYSize; } } public Node[,] NodeGrid { get { return nodeGrid; } } // Prep public void LoadGame(String filePath) { StreamReader input = new StreamReader(filePath); String line; String[] tokens; try { while ((line = input.ReadLine()) != null) { tokens = line.Split(' '); switch (tokens[0]) { case "size": mapXSize = Int32.Parse(tokens[1]); mapYSize = Int32.Parse(tokens[2]); break; case "initiallocation": initialLocation.X = Int32.Parse(tokens[1]); initialLocation.Y = Int32.Parse(tokens[2]); nodeGrid = new Node[mapXSize, mapYSize]; for (int i = 0; i < mapXSize; i++) { for (int j = 0; j < mapYSize; j++) { nodeGrid[i, j] = new Node(new Point(i, j), NodeType.SAND, initialLocation); } } nodeGrid[initialLocation.X, initialLocation.Y].UpdateNode(initialLocation, NodeType.PLAYER, initialLocation); break; case "diamonds": for (int i = 2; i < tokens.Length; i += 2) { Point diamond = new Point(Int32.Parse(tokens[i]), Int32.Parse(tokens[i + 1])); diamonds.Add(diamond); nodeGrid[diamond.X, diamond.Y].UpdateNode(diamond, NodeType.DIAMOND, initialLocation); goals.Add(nodeGrid[diamond.X, diamond.Y]); } break; case "rocks": for (int i = 2; i < tokens.Length; i += 2) { Point rock = new Point(Int32.Parse(tokens[i]), Int32.Parse(tokens[i + 1])); rocks.Add(rock); nodeGrid[rock.X, rock.Y].UpdateNode(rock, NodeType.ROCK, initialLocation); if (rock.Y + 1 < mapYSize) nodeGrid[rock.X, rock.Y + 1].IsDangerous = true; } break; case "walls": for (int i = 2; i < tokens.Length; i += 2) { Point wall = new Point(Int32.Parse(tokens[i]), Int32.Parse(tokens[i + 1])); walls.Add(wall); nodeGrid[wall.X, wall.Y].UpdateNode(wall, NodeType.WALL, initialLocation); } break; } } } catch (Exception ex) { throw(ex); } } // Algorithms public List<Node> SolveAStar() { List<Node> Goals = goals, path = new List<Node>(); Node startingNode = nodeGrid[initialLocation.X, initialLocation.Y]; while(Goals.Count > 0) { Node closestGoal = Goals[0]; Int32 distanceToGoal = GetManhattanDistance(startingNode.Position, closestGoal.Position); for (int i = 1; i < Goals.Count; i++) { Int32 distanceToClosestGoalCandidate = GetManhattanDistance(startingNode.Position, Goals[i].Position); if (distanceToClosestGoalCandidate < distanceToGoal) { distanceToGoal = distanceToClosestGoalCandidate; closestGoal = Goals[i]; } } List<Node> openSet = new List<Node>(); HashSet<Node> closedSet = new HashSet<Node>(); openSet.Add(startingNode); Node currentNode; Boolean GoalReached = false; while (openSet.Count > 0) { currentNode = openSet[0]; for (int i = 1; i < openSet.Count; i++) { if (openSet[i].fCost < currentNode.fCost || (openSet[i].fCost == currentNode.fCost && openSet[i].hCost < currentNode.hCost)) { currentNode = openSet[i]; } } openSet.Remove(currentNode); closedSet.Add(currentNode); if (currentNode == closestGoal) { List<Node> pathToClosestGoal = new List<Node>(); GoalReached = true; while (currentNode != startingNode) { pathToClosestGoal.Add(currentNode); currentNode = currentNode.ParentNode; } pathToClosestGoal.Reverse(); path.AddRange(pathToClosestGoal); break; } List<Node> neighbours = GetNodeWalkableNeighbours(currentNode.Position); foreach (Node neighbour in neighbours) { if (closedSet.Contains(neighbour)) continue; if (currentNode.gCost + 1 < neighbour.gCost || !openSet.Contains(neighbour)) { neighbour.gCost = currentNode.gCost + 1; neighbour.ParentNode = currentNode; if (!openSet.Contains(neighbour)) { neighbour.SetHCost(closestGoal.Position); openSet.Add(neighbour); } } } } if (GoalReached) { startingNode = closestGoal; for (int i = 0; i < mapXSize; i++) { for (int j = 0; j < mapYSize; j++) { nodeGrid[i, j].SetGCost(startingNode.Position); } } } Goals.Remove(closestGoal); } return path; } public List<List<Node>> SolveIDDFS(Int32 maxDepth) { List<List<Node>> path = new List<List<Node>>(); for (int currentDepth = 0; currentDepth < maxDepth; currentDepth++) { List<Node> currentDepthPath = new List<Node>(); List<Node> visited = new List<Node>(); Stack<Node> stack = new Stack<Node>(); Node CurrentNode = nodeGrid[initialLocation.X, initialLocation.Y]; CurrentNode.Visited = true; stack.Push(CurrentNode); visited.Add(CurrentNode); while(stack.Count > 0) { CurrentNode = stack.Pop(); currentDepthPath.Add(CurrentNode); List<Node> neighbours = GetNodeWalkableNeighbours(CurrentNode.Position, true); foreach (Node neighbour in neighbours) { if (GetManhattanDistance(initialLocation,neighbour.Position) <= currentDepth) { neighbour.Visited = true; stack.Push(neighbour); currentDepthPath.Add(neighbour); visited.Add(neighbour); } } } foreach (Node v in visited) { v.Visited = false; } Node StartingNode = currentDepthPath[0]; currentDepthPath.RemoveAt(0); currentDepthPath.Add(StartingNode); // Last iteration //path = currentDepthPath; // All iterations path.Add(currentDepthPath); } return path; } public List<Node> SolveCSP() { List<Node> path = new List<Node>(); Stack<Node> stack = new Stack<Node>(); Node CurrentNode = nodeGrid[initialLocation.X, initialLocation.Y]; CurrentNode.Visited = true; stack.Push(CurrentNode); while (stack.Count > 0) { CurrentNode = stack.Peek(); path.Add(CurrentNode); List<Node> neighbours = GetNodeWalkableNeighbours(CurrentNode.Position, true); if(neighbours.Count > 0) { Node neighbour = neighbours.OrderBy(x => Guid.NewGuid()).FirstOrDefault(); neighbour.Visited = true; stack.Push(neighbour); path.Add(neighbour); } else { CurrentNode = stack.Pop(); } } return path; } public List<List<Node>> SolveSA(Double temperature, Double decrement) { Random random = new Random(DateTime.Now.Second); List<List<Node>> path = new List<List<Node>>(); for (Double currentTemperature = temperature; currentTemperature >= 0 ; currentTemperature-=decrement) { List<Node> TemperatureRunPath = new List<Node>(); List<Node> Goals = new List<Node>(goals); Node startingNode = nodeGrid[initialLocation.X, initialLocation.Y]; while (Goals.Count > 0) { Node closestGoal = Goals[0]; Int32 distanceToGoal = GetManhattanDistance(startingNode.Position, closestGoal.Position); for (int i = 1; i < Goals.Count; i++) { Int32 distanceToClosestGoalCandidate = GetManhattanDistance(startingNode.Position, Goals[i].Position); if (distanceToClosestGoalCandidate < distanceToGoal) { distanceToGoal = distanceToClosestGoalCandidate; closestGoal = Goals[i]; } } Stack<Node> stack = new Stack<Node>(); List<Node> visited = new List<Node>(); Node currentNode = startingNode; currentNode.Visited = true; visited.Add(currentNode); stack.Push(currentNode); Boolean GoalReached = false; while (stack.Count > 0) { currentNode = stack.Peek(); TemperatureRunPath.Add(currentNode); if (currentNode == closestGoal) { GoalReached = true; break; } if(Goals.Contains(currentNode)) { Goals.Remove(currentNode); } List<Node> neighbours = GetNodeWalkableNeighbours(currentNode.Position, true); if (neighbours.Count > 0) { Node neighbour = neighbours.OrderBy(x => Guid.NewGuid()).FirstOrDefault(); neighbour.SetHCost(closestGoal.Position); if (neighbour.hCost < currentNode.hCost || (neighbour.hCost > currentNode.hCost && random.NextDouble() < temperature)) { neighbour.Visited = true; stack.Push(neighbour); TemperatureRunPath.Add(neighbour); visited.Add(neighbour); } } else { currentNode = stack.Pop(); } } if (GoalReached) { startingNode = closestGoal; foreach (Node v in visited) { v.Visited = false; } } Goals.Remove(closestGoal); } path.Add(TemperatureRunPath); } return path; } // Helpers private List<Node> GetNodeWalkableNeighbours(Point nodePosition, Boolean removeVisitedNodes = false) { List<Node> neighbours = new List<Node>(); int neighbourX = 0, neighbourY = 0; for (int i = 0; i < 4; i++) { switch (i) { case 0: // Left neighbourX = nodePosition.X - 1; neighbourY = nodePosition.Y; break; case 1: // Right neighbourX = nodePosition.X + 1; neighbourY = nodePosition.Y; break; case 2: // Top neighbourX = nodePosition.X; neighbourY = nodePosition.Y - 1; break; case 3: // Bottom neighbourX = nodePosition.X; neighbourY = nodePosition.Y + 1; break; } if (neighbourX > -1 && neighbourX < mapXSize && neighbourY > -1 && neighbourY < mapYSize && nodeGrid[neighbourX, neighbourY].IsWalkable && !nodeGrid[neighbourX, neighbourY].IsDangerous) if (!nodeGrid[neighbourX, neighbourY].Visited || !removeVisitedNodes) neighbours.Add(nodeGrid[neighbourX, neighbourY]); } return neighbours; } public static Int32 GetManhattanDistance(Point a, Point b) { return Math.Abs(a.X - b.X) + Math.Abs(a.Y - b.Y); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Threading; namespace testproject2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void InitializeMapGrid(Node[,] NodeGrid, Int32 MapXSize, Int32 MapYSize) { MapGrid.ColumnCount = MapXSize; MapGrid.RowCount = MapYSize; for (int i = 0; i < MapXSize; i++) { MapGrid.Columns[i].HeaderCell.Value = (i + 1).ToString(); } for (int i = 0; i < MapYSize; i++) { MapGrid.Rows[i].HeaderCell.Value = (i + 1).ToString(); } foreach(Node n in NodeGrid) { MapGrid.Rows[n.Position.Y].Cells[n.Position.X].Style.BackColor = n.NodeColor; } } private void LoadGame_Click(object sender, EventArgs e) { DialogResult result = openMapFile.ShowDialog(); if (result == DialogResult.OK && File.Exists(openMapFile.FileName)) { try { CurrentDepth.Text = CurrentTemp.Text = ""; Game.NewInstance.LoadGame(openMapFile.FileName); SolveAStar.Enabled = SolveIDDFS.Enabled = IDDFSDepth.Enabled = SolveCSP.Enabled = SolveSA.Enabled = SADecrement.Enabled = SATemperature.Enabled = PlayBackSpeed.Enabled = true; InitializeMapGrid(Game.Instance.NodeGrid, Game.Instance.MapXSize, Game.Instance.MapYSize); MapGrid.ClearSelection(); } catch(Exception) { MessageBox.Show("Error occurred while reading file.", "Diamonds", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void SolveAStar_Click(object sender, EventArgs e) { AnimatePath(Game.Instance.SolveAStar()); } private void SolveIDDFS_Click(object sender, EventArgs e) { Animate2DIDDFSPath(Game.Instance.SolveIDDFS(Convert.ToInt32(IDDFSDepth.Value))); } private void SolveCSP_Click(object sender, EventArgs e) { AnimatePath(Game.Instance.SolveCSP()); } private void SolveSA_Click(object sender, EventArgs e) { Animate2DSAPath(Game.Instance.SolveSA(Convert.ToDouble(SATemperature.Value), Convert.ToDouble(SADecrement.Value))); } private void AnimatePath(List<Node> path) { SolveAStar.Enabled = SolveIDDFS.Enabled = IDDFSDepth.Enabled = SolveSA.Enabled = SADecrement.Enabled = SATemperature.Enabled = SolveCSP.Enabled = false; new Thread(() => { Point currentPosition = new Point(Game.Instance.InitialLocation.X, Game.Instance.InitialLocation.Y); Int32 speed = 0; foreach (Node n in path) { Dispatcher.CurrentDispatcher.Invoke( DispatcherPriority.Send, new Action(() => { MapGrid.Rows[currentPosition.Y].Cells[currentPosition.X].Style.BackColor = Color.White; MapGrid.Rows[n.Position.Y].Cells[n.Position.X].Style.BackColor = Color.Green; speed = GetTrackBarValue(); })); currentPosition.X = n.Position.X; currentPosition.Y = n.Position.Y; Thread.Sleep(speed); } EnableLoadGame(); }).Start(); } private void Animate2DIDDFSPath(List<List<Node>> _2DPath) { SolveAStar.Enabled = SolveIDDFS.Enabled = IDDFSDepth.Enabled = SolveSA.Enabled = SADecrement.Enabled = SATemperature.Enabled = SolveCSP.Enabled = false; Int32 CurrentDepth = 1; new Thread(() => { foreach (List<Node> temperaturePath in _2DPath) { InitializeMapGrid(Game.Instance.NodeGrid, Game.Instance.MapXSize, Game.Instance.MapYSize); SetCurrentDepthLabel(String.Format("Current Depth = {0}", CurrentDepth++)); Point currentPosition = new Point(Game.Instance.InitialLocation.X, Game.Instance.InitialLocation.Y); foreach (Node n in temperaturePath) { Dispatcher.CurrentDispatcher.Invoke( DispatcherPriority.Send, new Action(() => { MapGrid.Rows[currentPosition.Y].Cells[currentPosition.X].Style.BackColor = Color.White; MapGrid.Rows[n.Position.Y].Cells[n.Position.X].Style.BackColor = Color.Green; })); currentPosition.X = n.Position.X; currentPosition.Y = n.Position.Y; Thread.Sleep(GetTrackBarValue()); } } EnableLoadGame(); }).Start(); } private void Animate2DSAPath(List<List<Node>> _2DPath) { SolveAStar.Enabled = SolveIDDFS.Enabled = IDDFSDepth.Enabled = SolveSA.Enabled = SADecrement.Enabled = SATemperature.Enabled = SolveCSP.Enabled = false; Decimal temperature = SATemperature.Value, decrement = SADecrement.Value; new Thread(() => { foreach (List<Node> temperaturePath in _2DPath) { InitializeMapGrid(Game.Instance.NodeGrid, Game.Instance.MapXSize, Game.Instance.MapYSize); SetCurrentTemperatureLabel(String.Format("Current Temp = {0}", Math.Round(temperature, 2))); Point currentPosition = new Point(Game.Instance.InitialLocation.X, Game.Instance.InitialLocation.Y); foreach (Node n in temperaturePath) { Dispatcher.CurrentDispatcher.Invoke( DispatcherPriority.Send, new Action(() => { MapGrid.Rows[currentPosition.Y].Cells[currentPosition.X].Style.BackColor = Color.White; MapGrid.Rows[n.Position.Y].Cells[n.Position.X].Style.BackColor = Color.Green; })); currentPosition.X = n.Position.X; currentPosition.Y = n.Position.Y; Thread.Sleep(GetTrackBarValue()); } temperature -= SADecrement.Value; } EnableLoadGame(); }).Start(); } delegate int GetTrackBarValueCallback(); private int GetTrackBarValue() { if (PlayBackSpeed.InvokeRequired) { GetTrackBarValueCallback cb = new GetTrackBarValueCallback(GetTrackBarValue); return (int)PlayBackSpeed.Invoke(cb); } else { return (int)PlayBackSpeed.Value; } } public void SetCurrentTemperatureLabel(String value) { if (InvokeRequired) { this.Invoke(new Action<string>(SetCurrentTemperatureLabel), new object[] { value }); return; } CurrentTemp.Text = value; } public void SetCurrentDepthLabel(String value) { if (InvokeRequired) { this.Invoke(new Action<string>(SetCurrentDepthLabel), new object[] { value }); return; } CurrentDepth.Text = value; } public void EnableLoadGame() { if (InvokeRequired) { this.Invoke(new Action(EnableLoadGame)); return; } LoadGame.Enabled = true; } private void SATemperature_ValueChanged(object sender, EventArgs e) { if (SADecrement.Value > SATemperature.Value) SADecrement.Value = SATemperature.Value; SADecrement.Maximum = SATemperature.Value; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MI { public class Score : IComparable<Score> { public String AlgorithmName; public Int64 NumberOfNodes; public Int32 NumberOfDiamonds; public Boolean AllDiamondsCollected; public TimeSpan TimeElapsed; public Score(String algorithmName, Int64 numberOfNodes, Int32 numberOfDiamonds, Boolean allDiamondsCollected, TimeSpan timeElapsed) { AlgorithmName = algorithmName; NumberOfNodes = numberOfNodes; NumberOfDiamonds = numberOfDiamonds; AllDiamondsCollected = allDiamondsCollected; TimeElapsed = timeElapsed; } private class ScoreComparerOnAndNumberOfDiamondsAndNodes : IComparer<Score> { int IComparer<Score>.Compare(Score a, Score b) { if (a == null || b == null) throw new NullReferenceException(); if (a.NumberOfDiamonds == b.NumberOfDiamonds) return a.NumberOfNodes.CompareTo(b.NumberOfNodes); else return a.NumberOfDiamonds.CompareTo(b.NumberOfDiamonds); } } public int CompareTo(Score otherScore) { if (otherScore == null) throw new NullReferenceException(); if (this.NumberOfDiamonds == otherScore.NumberOfDiamonds) return this.TimeElapsed.CompareTo(otherScore.TimeElapsed); else return -1 * this.NumberOfDiamonds.CompareTo(otherScore.NumberOfDiamonds); } public static IComparer<Score> ComparerOnAndNumberOfDiamondsAndNodes() { return (IComparer<Score>)new ScoreComparerOnAndNumberOfDiamondsAndNodes(); } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Audio; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace MI { public static class Resources { // Backgrounds: Menu Background, Button Background public static Texture2D mainMenuBackground, scoresBackground, buttonBackground, startOptionsButtonBackground, checkboxCheckedBackground, checkboxUncheckedBackground, gameMapBackground, dirtTile, playerTile, emptyTile, diamondTile, rockTile, wallTile, deadTile; // Font public static SpriteFont menuButtonsFont, scoresFont; // Font Colors public static Color normalFontColor = Color.FromNonPremultiplied(239, 167, 20, 255), hoverFontColor = Color.FromNonPremultiplied(196, 18, 1, 255); // Audio public static SoundEffect pickupDiamond, tada, death, backgroundMusic; public static SoundEffectInstance backgroundMusicInstance; // MapFile public static String mapFilePath; // ScoresFile public static String scoresFilePath; public static void LoadContent(ContentManager content) { mainMenuBackground = content.Load<Texture2D>("Images/MainMenuBackground"); scoresBackground = content.Load<Texture2D>("Images/ScoresBackground"); gameMapBackground = content.Load<Texture2D>("Images/GameMapBackground"); buttonBackground = content.Load<Texture2D>("Images/ButtonBackground"); dirtTile = content.Load<Texture2D>("Images/Dirt"); playerTile = content.Load<Texture2D>("Images/Player"); diamondTile = content.Load<Texture2D>("Images/Diamond"); emptyTile = content.Load<Texture2D>("Images/Empty"); rockTile = content.Load<Texture2D>("Images/Rock"); wallTile = content.Load<Texture2D>("Images/Wall"); deadTile = content.Load<Texture2D>("Images/Dead"); checkboxCheckedBackground = content.Load<Texture2D>("Images/CheckBox_Checked"); checkboxUncheckedBackground = content.Load<Texture2D>("Images/CheckBox_Unchecked"); startOptionsButtonBackground = content.Load<Texture2D>("Images/StartOptionsButtonBackground"); menuButtonsFont = content.Load<SpriteFont>("Fonts/MenuButtonsFont"); scoresFont = content.Load<SpriteFont>("Fonts/ScoresFont"); pickupDiamond = content.Load<SoundEffect>("Audio/Pickup_Coin4"); tada = content.Load<SoundEffect>("Audio/Tada"); death = content.Load<SoundEffect>("Audio/death2"); backgroundMusic = content.Load<SoundEffect>("Audio/background"); backgroundMusicInstance = backgroundMusic.CreateInstance(); mapFilePath = content.RootDirectory + "\\Map.txt"; scoresFilePath = content.RootDirectory + "\\Scores.txt"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System.IO; using System.Diagnostics; using System.Text.RegularExpressions; namespace MI { public static class GameHandler { // Fields private static Int32 mapXSize = 0, mapYSize = 0; private static Point initialLocation = new Point(0, 0); private static List<Point> diamonds = new List<Point>() { }, rocks = new List<Point>() { }, walls = new List<Point>() { }; private static List<Node> goals = new List<Node>(); private static Node[,] nodeGrid = { }; private static Int32 rectangleDimension = 0; private static Int32 mapXStartPosition, mapYStartPosition; private static Int32 mapXInitialPosition = 10, mapYInitialPosition = 130; private static Int32 mapXMaxPosition = 560, mapYMaxPosition = 580; private static Point currentPlayerPosition= new Point(0,0); private static Int32 pathIndex = 0, multiPathIndex = 0; private static Decimal SATemperature = 0.3M; private static Int32 IDDFSMaxDepth = 20; private static Int32 collectedDiamonds = 0; private static Boolean gameOver = false; private static Int32 diamondFrameCounter = 0, currentDiamondFrame = 0; private static Int32 playerFrameCounter = 0, currentPlayerFrame = 0; private static List<Node> path = null; private static List<List<Node>> multiPath= null; private static GameTime prevGameTime; // Positions: Buttons, Buttons Texts private static Vector2 backButtonPosition = new Vector2(600, 525); private static Vector2 backButtonTextPosition = new Vector2(650.0f, 547.5f), gameOverTextPosition = new Vector2(580, 130), currentLevelTextPosition = new Vector2(580, 130), currentLevelNumberTextPosition = new Vector2(580, 180), scoreTextPosition = new Vector2(580, 260), scoreNumberTextPosition = new Vector2(580, 310); // Previous Mouse State: Used for detecting single clicks private static MouseState prevMouseState = Mouse.GetState(); // Buttons Hover Booleans private static Boolean backHover = false; // Manual Mode Stuff private static KeyboardState oldKeyboardState; private static KeyboardState newkeyboardState = Keyboard.GetState(); // Played Flipped Flag private static bool isPlayerFlipped = false; // Scores public static SortedSet<Score> Scores = new SortedSet<Score>(), ComputerScores = new SortedSet<Score>(), HumanScores = new SortedSet<Score>(), SAScores = new SortedSet<Score>(); // Human Time Elapsed Counter private static Stopwatch humanStopWatch = new Stopwatch(); // Human Score Nodes Counter private static Int64 humanPathNumberOfNodes = 0; // Prep private static void LoadMap() { StreamReader input = new StreamReader(Resources.mapFilePath); String line; String[] tokens; Resources.backgroundMusicInstance.Play(); try { while ((line = input.ReadLine()) != null) { tokens = line.Split(' '); switch (tokens[0]) { case "size": mapXSize = Int32.Parse(tokens[1]); mapYSize = Int32.Parse(tokens[2]); rectangleDimension = Math.Min(550 / mapXSize, 450 / mapYSize); mapXStartPosition = (((mapXMaxPosition - mapXInitialPosition) - (rectangleDimension * mapXSize)) / 2) + mapXInitialPosition; mapYStartPosition = (((mapYMaxPosition - mapYInitialPosition) - (rectangleDimension * mapYSize)) / 2) + mapYInitialPosition; break; case "initiallocation": initialLocation.X = Int32.Parse(tokens[1]); initialLocation.Y = Int32.Parse(tokens[2]); currentPlayerPosition = new Point(initialLocation.X, initialLocation.Y); nodeGrid = new Node[mapXSize, mapYSize]; for (int i = 0; i < mapXSize; i++) { for (int j = 0; j < mapYSize; j++) { nodeGrid[i, j] = new Node(new Point(i, j), new Rectangle(i * rectangleDimension + mapXStartPosition, j * rectangleDimension + mapYStartPosition, rectangleDimension, rectangleDimension), NodeType.SAND, initialLocation); } } nodeGrid[initialLocation.X, initialLocation.Y].UpdateNode(initialLocation, NodeType.PLAYER, initialLocation); break; case "diamonds": for (int i = 2; i < tokens.Length; i += 2) { Point diamond = new Point(Int32.Parse(tokens[i]), Int32.Parse(tokens[i + 1])); diamonds.Add(diamond); nodeGrid[diamond.X, diamond.Y].UpdateNode(diamond, NodeType.DIAMOND, initialLocation); goals.Add(nodeGrid[diamond.X, diamond.Y]); } break; case "rocks": for (int i = 2; i < tokens.Length; i += 2) { Point rock = new Point(Int32.Parse(tokens[i]), Int32.Parse(tokens[i + 1])); rocks.Add(rock); nodeGrid[rock.X, rock.Y].UpdateNode(rock, NodeType.ROCK, initialLocation); if (rock.Y + 1 < mapYSize) nodeGrid[rock.X, rock.Y + 1].IsDangerous = true; } break; case "walls": for (int i = 2; i < tokens.Length; i += 2) { Point wall = new Point(Int32.Parse(tokens[i]), Int32.Parse(tokens[i + 1])); walls.Add(wall); nodeGrid[wall.X, wall.Y].UpdateNode(wall, NodeType.WALL, initialLocation); } break; case "iddfsmaxdepth": IDDFSMaxDepth = Int32.Parse(tokens[1]); break; case "satemperature": SATemperature = Decimal.Parse(tokens[1]); break; } } } catch (Exception ex) { throw (ex); } } public static void LoadScores() { if(File.Exists(Resources.scoresFilePath)) { StreamReader input = new StreamReader(Resources.scoresFilePath); String line; String[] tokens; try { while ((line = input.ReadLine()) != null && (tokens = Regex.Split(line, @"\s+")).Length == 5) { Score score = new Score(tokens[0],Int32.Parse(tokens[1]), Int32.Parse(tokens[2]), Boolean.Parse(tokens[3]), TimeSpan.Parse(tokens[4])); Scores.Add(score); if(score.AlgorithmName == "Human") { HumanScores.Add(score); } else { ComputerScores.Add(score); if (score.AlgorithmName == "SA") SAScores.Add(score); } } } catch (Exception ex) { throw (ex); } finally { input.Close(); } } else { File.Create(Resources.scoresFilePath); } } public static void Update(GameTime gameTime, Game1 game, GameState gameState) { if (prevGameTime == null) prevGameTime = new GameTime(gameTime.TotalGameTime, gameTime.ElapsedGameTime); if (nodeGrid.Length == 0) LoadMap(); switch (gameState) { case GameState.MANUAL_MODE: if (!gameOver) { if (!humanStopWatch.IsRunning) humanStopWatch.Start(); ManualMode(gameTime); } else if (gameOver && humanStopWatch.IsRunning) { humanStopWatch.Stop(); Score humanScore = new Score("Human", humanPathNumberOfNodes, collectedDiamonds, collectedDiamonds == goals.Count, humanStopWatch.Elapsed); Scores.Add(humanScore); HumanScores.Add(humanScore); humanStopWatch.Reset(); } break; case GameState.ASTAR_MODE: if (path == null) { Score score; path = SolveAStar(out score); ComputerScores.Add(score); Scores.Add(score); } if(!gameOver) MovePlayerFromPath(gameTime); break; case GameState.IDDFS_MODE: if (multiPath == null) { Score score; multiPath = SolveIDDFS(out score); ComputerScores.Add(score); Scores.Add(score); } if (!gameOver) MovePlayerFrom2DPath(gameTime); break; case GameState.CSP_MODE: if (path == null) { Score score; path = SolveCSP(out score); ComputerScores.Add(score); Scores.Add(score); } if (!gameOver) MovePlayerFromPath(gameTime); break; case GameState.SA_MODE: if (path == null) { Score score; path = SolveSA(out score); ComputerScores.Add(score); Scores.Add(score); SAScores.Add(score); } if (!gameOver) MovePlayerFromPath(gameTime); break; } if (gameOver) Resources.backgroundMusicInstance.Stop(); MouseState mouseState = Mouse.GetState(); if (mouseState.X < backButtonPosition.X || mouseState.Y < backButtonPosition.Y || mouseState.X > backButtonPosition.X + Resources.buttonBackground.Width || mouseState.Y > backButtonPosition.Y + Resources.buttonBackground.Height) backHover = false; else { backHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { game.gameState = GameState.MAIN_MENU; Resources.backgroundMusicInstance.Stop(); if (humanStopWatch.IsRunning) { humanStopWatch.Stop(); Score humanScore = new Score("Human", humanPathNumberOfNodes, collectedDiamonds, collectedDiamonds == goals.Count, humanStopWatch.Elapsed); Scores.Add(humanScore); HumanScores.Add(humanScore); humanStopWatch.Reset(); } Reset(); } } if (game.gameState != GameState.MAIN_MENU && game.gameState != GameState.SCORES) prevMouseState = mouseState; } public static void Draw(GameTime gameTime, SpriteBatch spriteBatch, GameState gameState) { spriteBatch.Draw(Resources.gameMapBackground, new Vector2(0, 0), Color.White); foreach (Node n in nodeGrid) { switch (n.Type) { case NodeType.PLAYER: if(!gameOver) { playerFrameCounter += (Int32)gameTime.ElapsedGameTime.TotalMilliseconds; if (playerFrameCounter > 100) { currentPlayerFrame += 140; playerFrameCounter = 0; if (currentPlayerFrame == 840) currentPlayerFrame = 0; } } Rectangle playerRectangle = new Rectangle(currentPlayerFrame, 0, 140, 180); if(isPlayerFlipped) spriteBatch.Draw(Flip(n.NodeTile), n.Rectangle, playerRectangle, Color.White); else spriteBatch.Draw(n.NodeTile, n.Rectangle, playerRectangle, Color.White); break; case NodeType.DIAMOND: diamondFrameCounter += (Int32)gameTime.ElapsedGameTime.TotalMilliseconds; if(diamondFrameCounter > 350) { currentDiamondFrame += 140; diamondFrameCounter = 0; if (currentDiamondFrame == 280) currentDiamondFrame = 0; } Rectangle diamondRectangle = new Rectangle(currentDiamondFrame, 0, 140, 140); spriteBatch.Draw(n.NodeTile, n.Rectangle, diamondRectangle, Color.White); break; default: spriteBatch.Draw(n.NodeTile, n.Rectangle, Color.White); break; } } if(gameOver) spriteBatch.DrawString(Resources.menuButtonsFont, "game over", gameOverTextPosition, Resources.hoverFontColor); else { switch (gameState) { case GameState.IDDFS_MODE: spriteBatch.DrawString(Resources.menuButtonsFont, "current d", currentLevelTextPosition, Resources.normalFontColor); spriteBatch.DrawString(Resources.menuButtonsFont, (multiPathIndex + 1).ToString(), currentLevelNumberTextPosition, Resources.normalFontColor); break; case GameState.SA_MODE: spriteBatch.DrawString(Resources.menuButtonsFont, "current temp", currentLevelTextPosition, Resources.normalFontColor); spriteBatch.DrawString(Resources.menuButtonsFont, String.Format("{0:N2}", (SATemperature - (SATemperature * multiPathIndex))), currentLevelNumberTextPosition, Resources.normalFontColor); break; } } spriteBatch.DrawString(Resources.menuButtonsFont, "diamonds", scoreTextPosition, Resources.normalFontColor); spriteBatch.DrawString(Resources.menuButtonsFont, collectedDiamonds.ToString(), scoreNumberTextPosition, Resources.normalFontColor); // BackButton spriteBatch.Draw(Resources.buttonBackground, backButtonPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "back", backButtonTextPosition, backHover ? Resources.hoverFontColor : Resources.normalFontColor); } private static void ManualMode(GameTime gameTime) { // Make Mario follow Keyboard oldKeyboardState = newkeyboardState; newkeyboardState = Keyboard.GetState(); Point nextMove = null; if (newkeyboardState.IsKeyDown(Keys.Left) && oldKeyboardState.IsKeyUp(Keys.Left)) nextMove = new Point(currentPlayerPosition.X - 1, currentPlayerPosition.Y); else if (newkeyboardState.IsKeyDown(Keys.Right) && oldKeyboardState.IsKeyUp(Keys.Right)) nextMove = new Point(currentPlayerPosition.X + 1, currentPlayerPosition.Y); else if (newkeyboardState.IsKeyDown(Keys.Up) && oldKeyboardState.IsKeyUp(Keys.Up)) nextMove = new Point(currentPlayerPosition.X , currentPlayerPosition.Y - 1); else if (newkeyboardState.IsKeyDown(Keys.Down) && oldKeyboardState.IsKeyUp(Keys.Down)) nextMove = new Point(currentPlayerPosition.X, currentPlayerPosition.Y + 1); if (nextMove != null && nextMove.X > -1 && nextMove.X < mapXSize && nextMove.Y > -1 && nextMove.Y < mapYSize && nodeGrid[nextMove.X, nextMove.Y].IsWalkable) { humanPathNumberOfNodes++; if (currentPlayerPosition.X + 1 == nextMove.X) // Right isPlayerFlipped = true; else if (currentPlayerPosition.X - 1 == nextMove.X) // Left isPlayerFlipped = false; nodeGrid[currentPlayerPosition.X, currentPlayerPosition.Y].Type = NodeType.CLEAR; currentPlayerPosition = nextMove; if (nodeGrid[nextMove.X, nextMove.Y].IsDangerous) { nodeGrid[nextMove.X, nextMove.Y - 1].Type = NodeType.CLEAR; nodeGrid[nextMove.X, nextMove.Y].Type = NodeType.DEAD; gameOver = true; Resources.death.Play(); } else nodeGrid[nextMove.X, nextMove.Y].Type = NodeType.PLAYER; } if (diamonds.Contains(new Point(currentPlayerPosition.X, currentPlayerPosition.Y))) { collectedDiamonds++; Resources.pickupDiamond.Play(); diamonds.Remove(new Point(currentPlayerPosition.X, currentPlayerPosition.Y)); if (diamonds.Count == 0) { gameOver = true; Resources.tada.Play(); } } } private static void MovePlayerFromPath(GameTime gameTime) { if (pathIndex < path.Count && gameTime.TotalGameTime.TotalSeconds - prevGameTime.TotalGameTime.TotalSeconds > 0.05) { nodeGrid[currentPlayerPosition.X, currentPlayerPosition.Y].Type = NodeType.CLEAR; Node nextMove = path[pathIndex++]; nodeGrid[nextMove.Position.X, nextMove.Position.Y].Type = NodeType.PLAYER; if (currentPlayerPosition.X + 1 == nextMove.Position.X) // Right isPlayerFlipped = true; else if (currentPlayerPosition.X - 1 == nextMove.Position.X) // Left isPlayerFlipped = false; currentPlayerPosition = nextMove.Position; if(diamonds.Contains(new Point(currentPlayerPosition.X,currentPlayerPosition.Y))) { collectedDiamonds++; diamonds.Remove(new Point(currentPlayerPosition.X, currentPlayerPosition.Y)); } prevGameTime = new GameTime(gameTime.TotalGameTime, gameTime.ElapsedGameTime); } else if (pathIndex == path.Count) { gameOver = true; Resources.tada.Play(); } } private static void MovePlayerFrom2DPath(GameTime gameTime) { if (multiPathIndex < multiPath.Count && gameTime.TotalGameTime.TotalSeconds - prevGameTime.TotalGameTime.TotalSeconds > 0.02) { if (pathIndex < multiPath[multiPathIndex].Count) { nodeGrid[currentPlayerPosition.X, currentPlayerPosition.Y].Type = NodeType.CLEAR; Node nextMove = multiPath[multiPathIndex][pathIndex++]; nodeGrid[nextMove.Position.X, nextMove.Position.Y].Type = NodeType.PLAYER; if (currentPlayerPosition.X + 1 == nextMove.Position.X) // Right isPlayerFlipped = true; else if (currentPlayerPosition.X - 1 == nextMove.Position.X) // Left isPlayerFlipped = false; currentPlayerPosition = nextMove.Position; if (diamonds.Contains(new Point(currentPlayerPosition.X, currentPlayerPosition.Y))) { collectedDiamonds++; diamonds.Remove(new Point(currentPlayerPosition.X, currentPlayerPosition.Y)); } prevGameTime = new GameTime(gameTime.TotalGameTime, gameTime.ElapsedGameTime); } else if(pathIndex == multiPath[multiPathIndex].Count) { multiPathIndex++; currentPlayerPosition = new Point(initialLocation.X, initialLocation.Y); pathIndex = 0; } } else if (multiPathIndex == multiPath.Count) { gameOver = true; Resources.tada.Play(); } } public static void Reset() { backHover = false; gameOver = false; isPlayerFlipped = false; diamonds = new List<Point>() { }; rocks = new List<Point>() { }; walls = new List<Point>() { }; goals = new List<Node>(); nodeGrid = new Node[0,0]{}; pathIndex = 0; multiPathIndex = 0; collectedDiamonds = 0; diamondFrameCounter = 0; humanPathNumberOfNodes = 0; path = null; multiPath= null; prevGameTime = null; prevMouseState = new MouseState(0, 0, 0, ButtonState.Released, ButtonState.Released, ButtonState.Released, ButtonState.Released, ButtonState.Released); } // Game Solver // Algorithms public static List<Node> SolveAStar(out Score score) { Stopwatch sw = Stopwatch.StartNew(); Int64 numberOfNodes = -1; Int32 numberOfDiamonds = 0; List<Node> Goals = new List<Node>(goals), path = new List<Node>(); Node startingNode = nodeGrid[initialLocation.X, initialLocation.Y]; while (Goals.Count > 0) { Node closestGoal = Goals[0]; Int32 distanceToGoal = GetManhattanDistance(startingNode.Position, closestGoal.Position); for (int i = 1; i < Goals.Count; i++) { Int32 distanceToClosestGoalCandidate = GetManhattanDistance(startingNode.Position, Goals[i].Position); if (distanceToClosestGoalCandidate < distanceToGoal) { distanceToGoal = distanceToClosestGoalCandidate; closestGoal = Goals[i]; } } List<Node> openSet = new List<Node>(); HashSet<Node> closedSet = new HashSet<Node>(); openSet.Add(startingNode); Node currentNode; Boolean GoalReached = false; while (openSet.Count > 0) { numberOfNodes = Math.Max(numberOfNodes, openSet.Count); currentNode = openSet[0]; for (int i = 1; i < openSet.Count; i++) { if (openSet[i].fCost < currentNode.fCost || (openSet[i].fCost == currentNode.fCost && openSet[i].hCost < currentNode.hCost)) { currentNode = openSet[i]; } } openSet.Remove(currentNode); closedSet.Add(currentNode); if (currentNode == closestGoal) { List<Node> pathToClosestGoal = new List<Node>(); GoalReached = true; while (currentNode != startingNode) { pathToClosestGoal.Add(currentNode); currentNode = currentNode.ParentNode; } pathToClosestGoal.Reverse(); path.AddRange(pathToClosestGoal); break; } List<Node> neighbours = GetNodeWalkableNeighbours(currentNode.Position); foreach (Node neighbour in neighbours) { if (closedSet.Contains(neighbour)) continue; if (currentNode.gCost + 1 < neighbour.gCost || !openSet.Contains(neighbour)) { neighbour.gCost = currentNode.gCost + 1; neighbour.ParentNode = currentNode; if (!openSet.Contains(neighbour)) { neighbour.SetHCost(closestGoal.Position); openSet.Add(neighbour); } } } } if (GoalReached) { numberOfDiamonds++; startingNode = closestGoal; for (int i = 0; i < mapXSize; i++) { for (int j = 0; j < mapYSize; j++) { nodeGrid[i, j].SetGCost(startingNode.Position); } } } Goals.Remove(closestGoal); } sw.Stop(); score = new Score("A*", numberOfNodes, numberOfDiamonds, numberOfDiamonds == goals.Count, sw.Elapsed); return path; } public static List<List<Node>> SolveIDDFS(out Score score) { Stopwatch sw = Stopwatch.StartNew(); Int64 numberOfNodes = -1; Int32 numberOfDiamonds = 0; Boolean collectedAllDiamonds = false; List<List<Node>> path = new List<List<Node>>(); for (int currentDepth = 0; currentDepth < IDDFSMaxDepth && !collectedAllDiamonds; currentDepth++) { List<Node> Goals = goals; List<Node> currentDepthPath = new List<Node>(); List<Node> visited = new List<Node>(); Stack<Node> stack = new Stack<Node>(); Node CurrentNode = nodeGrid[initialLocation.X, initialLocation.Y]; CurrentNode.Visited = true; stack.Push(CurrentNode); visited.Add(CurrentNode); while (stack.Count > 0) { CurrentNode = stack.Pop(); currentDepthPath.Add(CurrentNode); if (Goals.Contains(CurrentNode)) { Goals.Remove(CurrentNode); numberOfDiamonds++; if (Goals.Count == 0) break; } List<Node> neighbours = GetNodeWalkableNeighbours(CurrentNode.Position, true); foreach (Node neighbour in neighbours) { if (GetManhattanDistance(initialLocation, neighbour.Position) <= currentDepth) { neighbour.Visited = true; stack.Push(neighbour); currentDepthPath.Add(neighbour); visited.Add(neighbour); } } } foreach (Node v in visited) { v.Visited = false; } Node StartingNode = currentDepthPath[0]; currentDepthPath.RemoveAt(0); currentDepthPath.Add(StartingNode); // Last iteration //path = currentDepthPath; // All iterations path.Add(currentDepthPath); numberOfNodes = Math.Max(numberOfNodes, visited.Count); collectedAllDiamonds = Goals.Count == 0; } sw.Stop(); score = new Score("IDDFS", numberOfNodes, numberOfDiamonds, collectedAllDiamonds, sw.Elapsed); return path; } public static List<Node> SolveCSP(out Score score) { Stopwatch sw = Stopwatch.StartNew(); Int64 numberOfNodes = -1; Int32 numberOfDiamonds = 0; List<Node> Goals = goals; List<Node> path = new List<Node>(); Stack<Node> stack = new Stack<Node>(); Node CurrentNode = nodeGrid[initialLocation.X, initialLocation.Y]; CurrentNode.Visited = true; stack.Push(CurrentNode); while (stack.Count > 0) { CurrentNode = stack.Peek(); path.Add(CurrentNode); numberOfNodes = Math.Max(stack.Count, numberOfNodes); if (Goals.Contains(CurrentNode)) { Goals.Remove(CurrentNode); numberOfDiamonds++; if (Goals.Count == 0) break; } List<Node> neighbours = GetNodeWalkableNeighbours(CurrentNode.Position, true); if (neighbours.Count > 0) { Node neighbour = neighbours.OrderBy(x => Guid.NewGuid()).FirstOrDefault(); neighbour.Visited = true; stack.Push(neighbour); path.Add(neighbour); } else { CurrentNode = stack.Pop(); } } sw.Stop(); score = new Score("CSP", numberOfNodes, numberOfDiamonds, Goals.Count == 0, sw.Elapsed); return path; } public static List<Node> SolveSA(out Score score) { Stopwatch sw = Stopwatch.StartNew(); Random random = new Random(DateTime.Now.Second); Int64 numberOfNodes = -1; Int32 numberOfDiamonds = 0; List<Node> path = new List<Node>(); List<Node> Goals = new List<Node>(goals); Node startingNode = nodeGrid[initialLocation.X, initialLocation.Y]; while (Goals.Count > 0) { Node closestGoal = Goals[0]; Int32 distanceToGoal = GetManhattanDistance(startingNode.Position, closestGoal.Position); for (int i = 1; i < Goals.Count; i++) { Int32 distanceToClosestGoalCandidate = GetManhattanDistance(startingNode.Position, Goals[i].Position); if (distanceToClosestGoalCandidate < distanceToGoal) { distanceToGoal = distanceToClosestGoalCandidate; closestGoal = Goals[i]; } } Stack<Node> stack = new Stack<Node>(); List<Node> visited = new List<Node>(); Node currentNode = startingNode; currentNode.SetHCost(closestGoal.Position); currentNode.Visited = true; visited.Add(currentNode); stack.Push(currentNode); Boolean GoalReached = false; while (stack.Count > 0) { currentNode = stack.Peek(); path.Add(currentNode); numberOfNodes = Math.Max(numberOfNodes, visited.Count); if (currentNode == closestGoal) { GoalReached = true; break; } if (Goals.Contains(currentNode)) { numberOfDiamonds++; Goals.Remove(currentNode); } List<Node> neighbours = GetNodeWalkableNeighbours(currentNode.Position, true); if (neighbours.Count > 0) { while(true) { Node neighbour = neighbours.OrderBy(x => Guid.NewGuid()).FirstOrDefault(); neighbour.SetHCost(closestGoal.Position); if (neighbour.hCost < currentNode.hCost || (neighbour.hCost > currentNode.hCost && Convert.ToDecimal(random.NextDouble()) < SATemperature)) { neighbour.Visited = true; stack.Push(neighbour); path.Add(neighbour); visited.Add(neighbour); break; } } } else { currentNode = stack.Pop(); } } if (GoalReached) { numberOfDiamonds++; startingNode = closestGoal; foreach (Node v in visited) { v.Visited = false; } } Goals.Remove(closestGoal); } score = new Score("SA", numberOfNodes, numberOfDiamonds, numberOfDiamonds == goals.Count, sw.Elapsed); return path; } // Helpers private static List<Node> GetNodeWalkableNeighbours(Point nodePosition, Boolean removeVisitedNodes = false) { List<Node> neighbours = new List<Node>(); int neighbourX = 0, neighbourY = 0; for (int i = 0; i < 4; i++) { switch (i) { case 0: // Left neighbourX = nodePosition.X - 1; neighbourY = nodePosition.Y; break; case 1: // Right neighbourX = nodePosition.X + 1; neighbourY = nodePosition.Y; break; case 2: // Top neighbourX = nodePosition.X; neighbourY = nodePosition.Y - 1; break; case 3: // Bottom neighbourX = nodePosition.X; neighbourY = nodePosition.Y + 1; break; } if (neighbourX > -1 && neighbourX < mapXSize && neighbourY > -1 && neighbourY < mapYSize && nodeGrid[neighbourX, neighbourY].IsWalkable && !nodeGrid[neighbourX, neighbourY].IsDangerous) if (!nodeGrid[neighbourX, neighbourY].Visited || !removeVisitedNodes) neighbours.Add(nodeGrid[neighbourX, neighbourY]); } return neighbours; } private static Int32 GetManhattanDistance(Point a, Point b) { return Math.Abs(a.X - b.X) + Math.Abs(a.Y - b.Y); } public static Texture2D Flip(Texture2D source) { bool horizontal = true, vertical = false; Texture2D flipped = new Texture2D(source.GraphicsDevice, source.Width, source.Height); Color[] data = new Color[source.Width * source.Height]; Color[] flippedData = new Color[data.Length]; source.GetData<Color>(data); for (int x = 0; x < source.Width; x++) for (int y = 0; y < source.Height; y++) { int idx = (horizontal ? source.Width - 1 - x : x) + ((vertical ? source.Height - 1 - y : y) * source.Width); flippedData[x + y * source.Width] = data[idx]; } flipped.SetData<Color>(flippedData); return flipped; } // Save scores public static void SaveScores() { StreamWriter scoresFile = new StreamWriter(Resources.scoresFilePath, false); foreach(Score s in Scores) scoresFile.WriteLine(String.Format("{0} {1,10} {2,10} {3,10} {4,25}", s.AlgorithmName, s.NumberOfNodes, s.NumberOfDiamonds, s.AllDiamondsCollected, s.TimeElapsed.ToString())); scoresFile.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace testproject2 { public class Point { public Int32 X = 0, Y = 0; public Point(Int32 x, Int32 y) { X = x; Y = y; } } } <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; namespace testproject2 { public class Node { private static Color[] NodeColors = { Color.Green, Color.Yellow, Color.White, Color.Red, Color.Gray, Color.Black }; private static Boolean[] Walkability = { true, true, true, true, false, false }; // Fields public Point Position = new Point(0,0); public NodeType Type = NodeType.SAND; public Boolean IsDangerous = false, Visited = false; public Int32 gCost = 0, hCost = 0; public Node ParentNode = null; // Constructor public Node(Point position, NodeType type, Point startPosition) { UpdateNode(position, type, startPosition); } public void UpdateNode(Point position, NodeType type, Point startPosition) { Type = type; Position = position; SetGCost(startPosition); } // Properties public Boolean IsWalkable { get { return Walkability[(int)Type]; } } public Color NodeColor { get { return NodeColors[(int)Type]; } } public Int32 fCost { get { return gCost + hCost; } } // Cost Setters public void SetHCost(Point targetNodePosition) { hCost = Game.GetManhattanDistance(this.Position, targetNodePosition); } public void SetGCost(Point targetNodePosition) { gCost = Game.GetManhattanDistance(this.Position, targetNodePosition); } } public enum NodeType { PLAYER, SAND, CLEAR, DIAMOND, ROCK, WALL } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace MIProject { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; int WINDOW_WIDTH = 800; int WINDOW_HEIGHT = 600; // Initializing Objects used in the game Texture2D sand , diamond , stone , player , concrete; Rectangle rectanglesand , rectangleDiamond , rectanglePlayer , rectangleStone , rectangleConcrete; List<Rectangle> rectangles = new List<Rectangle>(); List<Rectangle> diamonds = new List<Rectangle>(); List<Rectangle> stones = new List<Rectangle>(); List<Rectangle> concretes = new List<Rectangle>(); KeyboardState oldKeyboardState; KeyboardState newkeyboardState = Keyboard.GetState(); SpriteFont chillerRegular; Vector2 FontPos; SoundEffect pickupCoin; SoundEffect tada; bool isMarioFlipped = false; bool solveastar; int score = 0; // Variables int marioX, marioY; int diamondsCount; List<int> diamondsLocations; int rocksCount; List<int> rocksLocations; int concreteCount; List<int> concreteLocations; public Game1(int width, int height, int mariox, int marioy, int diamondsCounter,List<int>diamondsLoc, int rocksCounter, List<int> rocksLocs, int concreteCounter, List<int> concreteLocs) { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; //Initializing Variables(); WINDOW_WIDTH = width; WINDOW_HEIGHT = height; marioX = mariox; marioY = marioy; diamondsCount = diamondsCounter; diamondsLocations = new List<int>(diamondsCount * 2); diamondsLocations = diamondsLoc; rocksCount = rocksCounter; rocksLocations = new List<int>(rocksCount * 2); rocksLocations = rocksLocs; concreteCount = concreteCounter; concreteLocations = new List<int>(concreteCount * 2); concreteLocations = concreteLocs; /// Changing resolution graphics.PreferredBackBufferWidth = WINDOW_WIDTH; graphics.PreferredBackBufferHeight = WINDOW_HEIGHT; IsMouseVisible = true; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here oldKeyboardState = Keyboard.GetState(); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here // Load SpriteFont chillerRegular = Content.Load<SpriteFont>("Chiller Regular"); FontPos = new Vector2(graphics.GraphicsDevice.Viewport.Width - 50 , 50); // Loading sound pickupCoin = Content.Load<SoundEffect>("Pickup_Coin4"); tada = Content.Load<SoundEffect>("Tada"); // Load sand and draw the rectangles sand = Content.Load<Texture2D>("dirt"); diamond = Content.Load<Texture2D>("Diamond_Glowing"); stone = Content.Load<Texture2D>("stone"); player = Content.Load<Texture2D>("Mario1"); concrete = Content.Load<Texture2D>("metalwall"); // Drawing penetrable ground for (int i = 0; i < 800; i+=100 ) { for (int j = 0; j < 600; j+=100 ) { rectanglesand = new Rectangle(i, j, 100, 100); rectangles.Add(rectanglesand); } } // Initializing rectangles for drawings rectanglePlayer = new Rectangle(marioX, marioY, 100, 100); for (int i = 0; i < diamondsCount * 2; i+=2 ) { rectangleDiamond = new Rectangle(diamondsLocations[i], diamondsLocations[i+1], 100, 100); diamonds.Add(rectangleDiamond); } for (int i = 0; i < rocksCount * 2; i += 2) { rectangleStone = new Rectangle(rocksLocations[i], rocksLocations[i + 1], 100, 100); stones.Add(rectangleStone); } for (int i = 0; i < concreteCount * 2; i += 2) { rectangleConcrete = new Rectangle(concreteLocations[i], concreteLocations[i + 1], 100, 100); concretes.Add(rectangleConcrete); } } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } protected void checkCollision() { for (int i = 0; i < diamonds.Count; i++) { if (rectanglePlayer.Intersects(diamonds.ElementAt(i))) { score++; pickupCoin.Play(); diamonds.Remove(diamonds.ElementAt(i)); if (score == diamondsCount) tada.Play(); } } for (int i = 0; i < rectangles.Count; i++) { if (rectanglePlayer.Intersects(rectangles.ElementAt(i))) { rectangles.Remove(rectangles.ElementAt(i)); } } for (int i = 0; i < stones.Count; i++) { if (rectanglePlayer.Intersects(stones.ElementAt(i)) && !isMarioFlipped) { rectanglePlayer.X = stones.ElementAt(i).Left - rectanglePlayer.Width; } else if (rectanglePlayer.Intersects(stones.ElementAt(i)) && isMarioFlipped) { rectanglePlayer.X = stones.ElementAt(i).Right; } } for (int i = 0; i < concretes.Count; i++) { if (rectanglePlayer.Intersects(concretes.ElementAt(i)) && !isMarioFlipped) { rectanglePlayer.X = concretes.ElementAt(i).Left - rectanglePlayer.Width; } else if (rectanglePlayer.Intersects(concretes.ElementAt(i)) && isMarioFlipped) { rectanglePlayer.X = concretes.ElementAt(i).Right; } } } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); UpdateMarioKeyboard(); // TODO: Add your update logic here // Make Mario follow mouse /*MouseState mouseState = Mouse.GetState(); rectanglePlayer.X = mouseState.X - rectanglePlayer.Width /2; rectanglePlayer.Y = mouseState.Y - rectanglePlayer.Height / 2; // Limit movement of mario to within window if (rectanglePlayer.Left < 0) rectanglePlayer.X = 0; if (rectanglePlayer.Right > WINDOW_WIDTH) rectanglePlayer.X = WINDOW_WIDTH - rectanglePlayer.Width; if (rectanglePlayer.Top < 0) rectanglePlayer.Y = 0; if (rectanglePlayer.Bottom > WINDOW_HEIGHT) rectanglePlayer.Y = WINDOW_HEIGHT - rectanglePlayer.Height;*/ checkCollision(); if (solveastar) SolveAStar(); base.Update(gameTime); } protected void SolveAStar() { } // This function lets mario face the opposite direction public static Texture2D Flip(Texture2D source, bool vertical, bool horizontal) { Texture2D flipped = new Texture2D(source.GraphicsDevice, source.Width, source.Height); Color[] data = new Color[source.Width * source.Height]; Color[] flippedData = new Color[data.Length]; source.GetData<Color>(data); for (int x = 0; x < source.Width; x++) for (int y = 0; y < source.Height; y++) { int idx = (horizontal ? source.Width - 1 - x : x) + ((vertical ? source.Height - 1 - y : y) * source.Width); flippedData[x + y * source.Width] = data[idx]; } flipped.SetData<Color>(flippedData); return flipped; } private void UpdateMarioKeyboard() { // Make Mario follow Keyboard oldKeyboardState = newkeyboardState; newkeyboardState = Keyboard.GetState(); // If the left key is pressed if (newkeyboardState.IsKeyDown(Keys.Left) && oldKeyboardState.IsKeyUp(Keys.Left) ) { rectanglePlayer.X -= 100; if (!isMarioFlipped) { player = Flip(player, false, true); isMarioFlipped = true; } } if (newkeyboardState.IsKeyDown(Keys.Right) && oldKeyboardState.IsKeyUp(Keys.Right)) { rectanglePlayer.X += 100; if (isMarioFlipped) { player = Flip(player, false, true); isMarioFlipped = false; } } if (newkeyboardState.IsKeyDown(Keys.Up) && oldKeyboardState.IsKeyUp(Keys.Up)) { rectanglePlayer.Y -= 100; } if (newkeyboardState.IsKeyDown(Keys.Down) && oldKeyboardState.IsKeyUp(Keys.Down)) { rectanglePlayer.Y += 100; } // Limit movement of mario to within window if (rectanglePlayer.Left < 0) rectanglePlayer.X = 0; if (rectanglePlayer.Right > WINDOW_WIDTH) rectanglePlayer.X = WINDOW_WIDTH - rectanglePlayer.Width; if (rectanglePlayer.Top < 0) rectanglePlayer.Y = 0; if (rectanglePlayer.Bottom > WINDOW_HEIGHT) rectanglePlayer.Y = WINDOW_HEIGHT - rectanglePlayer.Height; } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); // TODO: Add your drawing code here // Drawing sand & Mush spriteBatch.Begin(); for (int i = 0; i < rectangles.Count; i++) { spriteBatch.Draw(sand, rectangles[i], Color.White); } for (int i = 0; i < diamonds.Count; i++) { spriteBatch.Draw(diamond, diamonds[i], Color.White); } for (int i = 0; i < stones.Count; i++) { spriteBatch.Draw(stone, stones[i], Color.White); } for (int i = 0; i < concretes.Count; i++ ) { spriteBatch.Draw(concrete, concretes[i], Color.White); } spriteBatch.Draw(player, rectanglePlayer, Color.Wheat); Vector2 FontOrigin = chillerRegular.MeasureString(score.ToString()) / 2; // Draw the string spriteBatch.DrawString(chillerRegular, score.ToString(), FontPos, Color.Red, 0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f); spriteBatch.End(); base.Draw(gameTime); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MI { public class Point : IEquatable<Point> { public Int32 X = 0, Y = 0; public Point(Int32 x, Int32 y) { X = x; Y = y; } public bool Equals(Point other) { if (other == null) return false; if (this.X == other.X && this.Y == other.Y) return true; else return false; } public override bool Equals(Object other) { if (other == null) return false; Point pointObj = other as Point; if (pointObj == null) return false; else return Equals(pointObj); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MI { public enum GameState { MAIN_MENU, SCORES, MANUAL_MODE, ASTAR_MODE, IDDFS_MODE, CSP_MODE, SA_MODE } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MI { public static class Scores { // Positions: Buttons, Buttons Texts private static Vector2 backButtonPosition = new Vector2(50, 525), computerScoresButtonPosition = new Vector2(30, 150), humanScoresButtonPosition = new Vector2(30, 220), mixedScoresButtonPosition = new Vector2(30, 300), SAScoresButtonPosition = new Vector2(30, 380); private static Vector2 backButtonTextPosition = new Vector2(100.0f, 547.5f), computerScoresButtonTextPosition = new Vector2(130f, 172.5f), humanScoresButtonTextPosition = new Vector2(130f, 242.5f), mixedScoresButtonTextPosition = new Vector2(130f, 322.5f), SAScoresButtonTextPosition = new Vector2(130f, 402.5f); private static Vector2 scoresTableHeaderPosition = new Vector2(300, 150); // Previous Mouse State: Used for detecting single clicks private static MouseState prevMouseState = Mouse.GetState(); // Buttons Hover Booleans private static Boolean backHover = false, computerScoresHover = false, humanScoresHover = false, mixedScoresHover = false, SAScoresHover = false; private static ScoreType scoreType = ScoreType.COMPUTER; public static void Update(GameTime gameTime, Game1 game) { MouseState mouseState = Mouse.GetState(); if (mouseState.X < backButtonPosition.X || mouseState.Y < backButtonPosition.Y || mouseState.X > backButtonPosition.X + Resources.buttonBackground.Width || mouseState.Y > backButtonPosition.Y + Resources.buttonBackground.Height) backHover = false; else { backHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { game.gameState = GameState.MAIN_MENU; } } if (mouseState.X < computerScoresButtonPosition.X || mouseState.Y < computerScoresButtonPosition.Y || mouseState.X > computerScoresButtonPosition.X + Resources.checkboxCheckedBackground.Width || mouseState.Y > computerScoresButtonPosition.Y + Resources.checkboxCheckedBackground.Height) computerScoresHover = false; else { computerScoresHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { scoreType = ScoreType.COMPUTER; } } if (mouseState.X < humanScoresButtonPosition.X || mouseState.Y < humanScoresButtonPosition.Y || mouseState.X > humanScoresButtonPosition.X + Resources.checkboxCheckedBackground.Width || mouseState.Y > humanScoresButtonPosition.Y + Resources.checkboxCheckedBackground.Height) humanScoresHover = false; else { humanScoresHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { scoreType = ScoreType.HUMAN; } } if (mouseState.X < mixedScoresButtonPosition.X || mouseState.Y < mixedScoresButtonPosition.Y || mouseState.X > mixedScoresButtonPosition.X + Resources.checkboxCheckedBackground.Width || mouseState.Y > mixedScoresButtonPosition.Y + Resources.checkboxCheckedBackground.Height) mixedScoresHover = false; else { mixedScoresHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { scoreType = ScoreType.MIXED; } } if (mouseState.X < SAScoresButtonPosition.X || mouseState.Y < SAScoresButtonPosition.Y || mouseState.X > SAScoresButtonPosition.X + Resources.checkboxCheckedBackground.Width || mouseState.Y > SAScoresButtonPosition.Y + Resources.checkboxCheckedBackground.Height) SAScoresHover = false; else { SAScoresHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { scoreType = ScoreType.SA; } } if (game.gameState == GameState.SCORES) prevMouseState = mouseState; } public static void Draw(GameTime gameTime, SpriteBatch spriteBatch) { spriteBatch.Draw(Resources.scoresBackground, new Vector2(0, 0), Color.White); // BackButton spriteBatch.Draw(Resources.buttonBackground, backButtonPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "back", backButtonTextPosition, backHover ? Resources.hoverFontColor : Resources.normalFontColor); // ScoresButtons spriteBatch.Draw(scoreType == ScoreType.COMPUTER? Resources.checkboxCheckedBackground : Resources.checkboxUncheckedBackground, computerScoresButtonPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "PC", computerScoresButtonTextPosition, computerScoresHover ? Resources.hoverFontColor : Resources.normalFontColor); spriteBatch.Draw(scoreType == ScoreType.HUMAN ? Resources.checkboxCheckedBackground : Resources.checkboxUncheckedBackground, humanScoresButtonPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "human", humanScoresButtonTextPosition, humanScoresHover ? Resources.hoverFontColor : Resources.normalFontColor); spriteBatch.Draw(scoreType == ScoreType.MIXED ? Resources.checkboxCheckedBackground : Resources.checkboxUncheckedBackground, mixedScoresButtonPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "mixed", mixedScoresButtonTextPosition, mixedScoresHover ? Resources.hoverFontColor : Resources.normalFontColor); spriteBatch.Draw(scoreType == ScoreType.SA ? Resources.checkboxCheckedBackground : Resources.checkboxUncheckedBackground, SAScoresButtonPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "SA", SAScoresButtonTextPosition, SAScoresHover ? Resources.hoverFontColor : Resources.normalFontColor); //Table spriteBatch.DrawString(Resources.scoresFont, String.Format("{0} {1,10} {2,10} {3,15} {4,5}", "Alg", "#Nodes", "#Diamonds", "All Diamonds", "Time"), scoresTableHeaderPosition, Color.White); switch (scoreType) { case(ScoreType.COMPUTER): printScores(spriteBatch, GameHandler.ComputerScores); break; case (ScoreType.HUMAN): printScores(spriteBatch, GameHandler.HumanScores); break; case (ScoreType.MIXED): printScores(spriteBatch, GameHandler.Scores); break; case (ScoreType.SA): printScores(spriteBatch, GameHandler.SAScores); break; } } public static void Reset() { backHover = computerScoresHover = humanScoresHover = mixedScoresHover = SAScoresHover = false; scoreType = ScoreType.COMPUTER; prevMouseState = new MouseState(0, 0, 0, ButtonState.Released, ButtonState.Released, ButtonState.Released, ButtonState.Released, ButtonState.Released); } private static void printScores(SpriteBatch spriteBatch, SortedSet<Score> scoresSet) { for (int i = 0; i < 10 && i < scoresSet.Count; i++) { Score s = scoresSet.ElementAt(i); switch (s.AlgorithmName) { case "IDDFS": spriteBatch.DrawString(Resources.scoresFont, String.Format("{0} {1,5} {2,14} {3,15} {4,15}", s.AlgorithmName, s.NumberOfNodes, s.NumberOfDiamonds, s.AllDiamondsCollected, s.TimeElapsed.ToString(@"mm\:ss\.fffffff")), new Vector2(scoresTableHeaderPosition.X, scoresTableHeaderPosition.Y + ((i + 1) * 50)), Color.White); break; case "A*": spriteBatch.DrawString(Resources.scoresFont, String.Format("{0} {1,12} {2,15} {3,15} {4,15}", s.AlgorithmName, s.NumberOfNodes, s.NumberOfDiamonds, s.AllDiamondsCollected, s.TimeElapsed.ToString(@"mm\:ss\.fffffff")), new Vector2(scoresTableHeaderPosition.X, scoresTableHeaderPosition.Y + ((i + 1) * 50)), Color.White); break; case "SA": spriteBatch.DrawString(Resources.scoresFont, String.Format("{0} {1,11} {2,15} {3,15} {4,15}", s.AlgorithmName, s.NumberOfNodes, s.NumberOfDiamonds, s.AllDiamondsCollected, s.TimeElapsed.ToString(@"mm\:ss\.fffffff")), new Vector2(scoresTableHeaderPosition.X, scoresTableHeaderPosition.Y + ((i + 1) * 50)), Color.White); break; case "CSP": spriteBatch.DrawString(Resources.scoresFont, String.Format("{0} {1,10} {2,14} {3,15} {4,15}", s.AlgorithmName, s.NumberOfNodes, s.NumberOfDiamonds, s.AllDiamondsCollected, s.TimeElapsed.ToString(@"mm\:ss\.fffffff")), new Vector2(scoresTableHeaderPosition.X, scoresTableHeaderPosition.Y + ((i + 1) * 50)), Color.White); break; case "Human": spriteBatch.DrawString(Resources.scoresFont, String.Format("{0} {1,5} {2,15} {3,15} {4,15}", s.AlgorithmName, s.NumberOfNodes, s.NumberOfDiamonds, s.AllDiamondsCollected, s.TimeElapsed.ToString(@"mm\:ss\.fffffff")), new Vector2(scoresTableHeaderPosition.X, scoresTableHeaderPosition.Y + ((i + 1) * 50)), Color.White); break; } } } } public enum ScoreType { COMPUTER, HUMAN, MIXED, SA } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MI { public class Node { private static Texture2D[] NodeTiles = { Resources.playerTile, Resources.dirtTile, Resources.emptyTile, Resources.diamondTile, Resources.rockTile, Resources.wallTile, Resources.deadTile }; private static Boolean[] Walkability = { true, true, true, true, false, false }; // Fields public Point Position = new Point(0,0); public Rectangle Rectangle = new Rectangle(); public NodeType Type = NodeType.SAND; public Boolean IsDangerous = false, Visited = false; public Int32 gCost = 0, hCost = 0; public Node ParentNode = null; // Constructor public Node(Point position, Rectangle rectangle, NodeType type, Point startPosition) { UpdateNode(position, type, startPosition); Rectangle = rectangle; } public void UpdateNode(Point position, NodeType type, Point startPosition) { Type = type; Position = position; SetGCost(startPosition); } // Properties public Boolean IsWalkable { get { return Walkability[(int)Type]; } } public Texture2D NodeTile { get { return NodeTiles[(int)Type]; } } public Int32 fCost { get { return gCost + hCost; } } // Cost Setters public void SetHCost(Point targetNodePosition) { hCost = GetManhattanDistance(this.Position, targetNodePosition); } public void SetGCost(Point targetNodePosition) { gCost = GetManhattanDistance(this.Position, targetNodePosition); } public static Int32 GetManhattanDistance(Point a, Point b) { return Math.Abs(a.X - b.X) + Math.Abs(a.Y - b.Y); } } public enum NodeType { PLAYER, SAND, CLEAR, DIAMOND, ROCK, WALL, DEAD } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MI { public static class MainMenu { // Positions: Menu Buttons, Buttons Texts private static Vector2 startButtonPosition = new Vector2(300, 250), scoresButtonPosition = new Vector2(300, 330), quitButtonPosition = new Vector2(300, 410); private static Vector2 startButtonTextPosition = new Vector2(350.0f, 272.5f), scoresButtonTextPosition = new Vector2(345.0f, 352.5f), quitButtonTextPosition = new Vector2(350.0f, 432.5f); // Positions: Start Options private static Vector2 AStarPosition = new Vector2(500, 250), IDDFSPosition = new Vector2(500, 330), CSPPosition = new Vector2(500, 410), SAPosition = new Vector2(500, 490), manualPosition = new Vector2(100, 250); private static Vector2 AStarTextPosition = new Vector2(550.0f, 272.5f), IDDFSTextPosition = new Vector2(550.0f, 352.5f), CSPTextPosition = new Vector2(550.0f, 432.5f), SATextPosition = new Vector2(550.0f, 512.5f), manualTextPosition = new Vector2(150.0f, 272.5f); // MenuButtons Hover Booleans private static Boolean startHover = false, scoresHover = false, quitHover = false; // StartOptionsButtons Hover Booleans private static Boolean AStarHover = false, IDDFSHover = false, CSPHover = false, SAHover = false, manualHover = false; // Show Start Options Boolean private static Boolean showStartOptions = false; // Previous Mouse State: Used for detecting single clicks private static MouseState prevMouseState = Mouse.GetState(); public static void Update(GameTime gameTime, Game1 game) { MouseState mouseState = Mouse.GetState(); if (mouseState.X < startButtonPosition.X || mouseState.Y < startButtonPosition.Y || mouseState.X > startButtonPosition.X + Resources.buttonBackground.Width || mouseState.Y > startButtonPosition.Y + Resources.buttonBackground.Height) startHover = false; else { startHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { showStartOptions = !showStartOptions; } } if (mouseState.X < scoresButtonPosition.X || mouseState.Y < scoresButtonPosition.Y || mouseState.X > scoresButtonPosition.X + Resources.buttonBackground.Width || mouseState.Y > scoresButtonPosition.Y + Resources.buttonBackground.Height) scoresHover = false; else { scoresHover = true; if (mouseState.LeftButton == ButtonState.Pressed && prevMouseState.LeftButton == ButtonState.Pressed) { game.gameState = GameState.SCORES; Reset(); } } if (mouseState.X < quitButtonPosition.X || mouseState.Y < quitButtonPosition.Y || mouseState.X > quitButtonPosition.X + Resources.buttonBackground.Width || mouseState.Y > quitButtonPosition.Y + Resources.buttonBackground.Height) quitHover = false; else { quitHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { game.Exit(); } } if (mouseState.X < AStarPosition.X || mouseState.Y < AStarPosition.Y || mouseState.X > AStarPosition.X + Resources.startOptionsButtonBackground.Width || mouseState.Y > AStarPosition.Y + Resources.startOptionsButtonBackground.Height) AStarHover = false; else { AStarHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { game.gameState = GameState.ASTAR_MODE; Reset(); } } if (mouseState.X < IDDFSPosition.X || mouseState.Y < IDDFSPosition.Y || mouseState.X > IDDFSPosition.X + Resources.startOptionsButtonBackground.Width || mouseState.Y > IDDFSPosition.Y + Resources.startOptionsButtonBackground.Height) IDDFSHover = false; else { IDDFSHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { game.gameState = GameState.IDDFS_MODE; Reset(); } } if (mouseState.X < CSPPosition.X || mouseState.Y < CSPPosition.Y || mouseState.X > CSPPosition.X + Resources.startOptionsButtonBackground.Width || mouseState.Y > CSPPosition.Y + Resources.startOptionsButtonBackground.Height) CSPHover = false; else { CSPHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { game.gameState = GameState.CSP_MODE; Reset(); } } if (mouseState.X < SAPosition.X || mouseState.Y < SAPosition.Y || mouseState.X > SAPosition.X + Resources.startOptionsButtonBackground.Width || mouseState.Y > SAPosition.Y + Resources.startOptionsButtonBackground.Height) SAHover = false; else { SAHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { game.gameState = GameState.SA_MODE; Reset(); } } if (mouseState.X < manualPosition.X || mouseState.Y < manualPosition.Y || mouseState.X > manualPosition.X + Resources.startOptionsButtonBackground.Width || mouseState.Y > manualPosition.Y + Resources.startOptionsButtonBackground.Height) manualHover = false; else { manualHover = true; if (mouseState.LeftButton == ButtonState.Released && prevMouseState.LeftButton == ButtonState.Pressed) { game.gameState = GameState.MANUAL_MODE; Reset(); } } if(game.gameState == GameState.MAIN_MENU) prevMouseState = mouseState; } public static void Draw(GameTime gameTime, SpriteBatch spriteBatch) { spriteBatch.Draw(Resources.mainMenuBackground, new Vector2(0, 0), Color.White); // StartButton spriteBatch.Draw(Resources.buttonBackground, startButtonPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "start", startButtonTextPosition, startHover ? Resources.hoverFontColor : Resources.normalFontColor); // ScoresButton spriteBatch.Draw(Resources.buttonBackground, scoresButtonPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "scores", scoresButtonTextPosition, scoresHover ? Resources.hoverFontColor : Resources.normalFontColor); // QuitButton spriteBatch.Draw(Resources.buttonBackground, quitButtonPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "quit", quitButtonTextPosition, quitHover ? Resources.hoverFontColor : Resources.normalFontColor); // StartOptionsButtons if (showStartOptions) { spriteBatch.Draw(Resources.startOptionsButtonBackground, AStarPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "A*", AStarTextPosition, AStarHover ? Resources.hoverFontColor : Color.White); spriteBatch.Draw(Resources.startOptionsButtonBackground, IDDFSPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "IDDFS", IDDFSTextPosition, IDDFSHover ? Resources.hoverFontColor : Color.White); spriteBatch.Draw(Resources.startOptionsButtonBackground, CSPPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "CSP", CSPTextPosition, CSPHover ? Resources.hoverFontColor : Color.White); spriteBatch.Draw(Resources.startOptionsButtonBackground, SAPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "SA", SATextPosition, SAHover ? Resources.hoverFontColor : Color.White); spriteBatch.Draw(Resources.startOptionsButtonBackground, manualPosition, Color.White); spriteBatch.DrawString(Resources.menuButtonsFont, "Play", manualTextPosition, manualHover ? Resources.hoverFontColor : Color.White); } } public static void Reset() { startHover = scoresHover = quitHover = false; showStartOptions = false; AStarHover = IDDFSHover = CSPHover = SAHover = manualHover = false; prevMouseState = new MouseState(0,0,0,ButtonState.Released,ButtonState.Released,ButtonState.Released,ButtonState.Released,ButtonState.Released); } } }
d34006a447ba686ecca8932a9ed9543898dd9d0c
[ "C#" ]
14
C#
OumarYehia/MIProject
07357af9d94b7ce0b04f8821b7b60731eaa32cde
e7a4b1fb9b2079bcf16c861ca121bbbca21c8fed
refs/heads/master
<repo_name>nathanbuchar/raven<file_sep>/gulp/tasks/watch.js /** * @fileoverview Watch Gulp task. * @author <NAME> */ 'use strict'; let gulp = require('gulp'); let plugins = require('gulp-load-plugins')({ camelize: true }); let config = require('../utils/config'); /** * @name watch * @description Watches for changes and then re-runs the specified task(s) or * restarts the server. */ gulp.task('watch', function () { plugins.sequence('build', 'livereload')(function () { gulp.watch(config.watch.icons, function () { plugins.sequence('icons')(); }); gulp.watch(config.watch.scripts, function () { plugins.sequence('scripts')(); }); gulp.watch(config.watch.styles, function () { plugins.sequence('styles')(); }); }); }); <file_sep>/gulp/tasks/livereload.js /** * @fileoverview Livereload Gulp task. * @author <NAME> */ 'use strict'; let gulp = require('gulp'); let plugins = require('gulp-load-plugins')({ camelize: true }); /** * @name livereload * @description Listen for livereload changes. * @see {@link https://www.npmjs.com/package/gulp-livereload} */ gulp.task('livereload', function () { plugins.livereload.listen(); }); <file_sep>/gulp/tasks/scripts.js /** * @fileoverview Scripts Gulp task. * @author <NAME> */ 'use strict'; let gulp = require('gulp'); let plugins = require('gulp-load-plugins')({ camelize: true }); let config = require('../utils/config'); /** * @name scripts * @description Compiles our client-side scripts via browserify into a single * app bundle, then sends it to the build. */ gulp.task('scripts', function () { return gulp.src(config.appFiles.scripts) .pipe(plugins.browserify(config.browserify)) .pipe(plugins.rename('app.bundle.js')) // .pipe(plugins.uglify(config.uglify)) .pipe(gulp.dest(config.paths.scripts.dest)) .pipe(plugins.livereload()); }); <file_sep>/gulp/tasks/base.js /** * @fileoverview Base Gulp task. * @author <NAME> */ 'use strict'; let gulp = require('gulp'); let plugins = require('gulp-load-plugins')({ camelize: true }); let config = require('../utils/config'); /** * @name base * @description Copies over basic static files into the build directory. */ gulp.task('base', function () { return gulp.src([ `${config.basePaths.src}/**/*`, `!${config.paths.data.src}`, `!${config.paths.icons.src}`, `!${config.paths.images.src}`, `!${config.paths.scripts.src}`, `!${config.paths.styles.src}` ]).pipe(gulp.dest(config.basePaths.dest)); }); <file_sep>/gulp/tasks/build.js /** * @fileoverview Compile Gulp task. * @author <NAME> */ 'use strict'; let gulp = require('gulp'); let plugins = require('gulp-load-plugins')({ camelize: true }); let config = require('../utils/config'); /** * @name build * @description Asynchronously compiles static files. */ gulp.task('build', function (cb) { plugins.sequence('clean', ['base', 'scripts', 'styles', 'icons'])(cb); }); <file_sep>/gulp/README.md # Gulp Our client-side build tasks. ### Tasks #### Default The default gulp task. This runs the `build` task. gulp #### Build This will clean and compile the application as normal. However, it will neither start the server, nor listen for file changes via Livereload. gulp clean #### Clean Cleans the build directory. gulp clean #### Icons Compiles all SVG icons into a single `icons.svg` file via `gulp-svgstore` gulp icons #### Livereload Starts the Livereload server. **Note:** This task should not be run independently. gulp livereload #### Scripts Compiles our client-side scripts into a single app bundle via Browserify, and applies any necessary transforms such as Babel. gulp scripts #### Styles Compiles our SCSS files into a single `main.css` file. gulp styles #### Watch Builds the app, starts the Livereload server, and watches for file changes. gulp watch ## Authors * [<NAME>](mailto:<EMAIL>) <file_sep>/app/cdn/index.js /** * @fileoverview Our CDN definition. * @author <NAME> */ 'use strict'; let client = require('./client'); let types = require('./types'); module.exports = function (app) { return { client: client(app), types }; }; <file_sep>/gulp/index.js /** * @fileoverview Register our Gulp tasks. * @author <NAME> * @ignore */ 'use strict'; let glob = require('glob'); let path = require('path'); glob.sync(`${__dirname}/tasks/*.js`).forEach(function (task) { require(task); }); <file_sep>/README.md # Raven JS A full-stack [Express](http://expressjs.com/) app framework running on [io.js](http://iojs.org/) intended to be a starting point to use in personal and client applications. ### Technology * [io.js](http://iojs.org/) * [Express](http://expressjs.com/) * [Jade](http://jade-lang.com/) * [Browserify](http://browserify.org/) * [Babel](http://babeljs.io/) * [Gulp](http://gulpjs.com/) * [Yeoman](http://yeoman.io/) * [Mocha](http://mochajs.org/) * [Chai](http://chaijs.com/) ### Setup First, clone the repository git clone <EMAIL>:nathanbuchar/raven.git Second, cd into the repository cd raven Last, run the setup script and follow the on-screen prompts. This assumes you already have a base version of Node JS installed. If you do not, visit [nodejs.org](http://nodejs.org) and download the latest version. npm run setup This script will install [nvm](https://github.com/creationix/nvm), io.js, global and local node packages, as well as link the Yeoman generator, and decrypt the `.env.cast5` file. If you're getting `EACCESS` errors while running the setup script, verify that you have the proper permissions. Enter the following before retrying: sudo chown -R $USER ~/.npm sudo chown -R $USER /usr/local/lib/node_modules ### Config Encryption If you make a change to the `.env` file located in the root directory, you must encrypt the file before committing to the repository. The `.env` file contains sensitive information such as API keys and secrets; For this reason we ask Git to ignore it, and it therefore will not be checked in. We do however push an encrypted version of the `.env` file, called `.env.cast5` which can be found in the root directory. We can update this file by running npm run encrypt Similarly, to decrypt the `.env.cast5` file, run npm run decrypt And enter the config password when prompted. Decryption will also occur in the setup script. ### Starting the Server First, make sure you're using the correct node engine by running nvm use This will look at the local `.nvmrc` file to determine the correct version of io.js to use. Then, to start the server, run iojs index.js or npm start ### Building To build the app via [Gulp](http://gulpjs.com), run gulp This will simply compile the app and will not start the livereload server or watch for changes. To build the app and watch for changes, run gulp watch And if you wish to deploy the app for production, run the default task with the `release` boolean flag. This compiles the app as normal, but additionally it will minify all scripts and styles. gulp --release ### Scaffolding We are using [Yeoman](http://yeoman.io) to assist in generating templatized files, such as routes, pages, and modules. To start the generator, simply run yo raven You should see the following: ``` ___ / _ \___ __ _____ ___ / , _/ _ `/ |/ / -_) _ \ /_/|_|\_,_/|___/\__/_//_/ ? What would you like to create? (Use arrow keys) ❯ Create a new module Create a new page Create a new route ``` Simply follow the instructions. ### Testing We use [Mocha](http://mochajs.org/) and [Chai](http://chaijs.com/) to run tests on our node app. Enter the following to run the tests. npm test ## Authors * [<NAME>](mailto:<EMAIL>) ## License MIT <file_sep>/app/cdn/client.js /** * @fileoverview Create a new Contentful CDN client instance. * @author <NAME> */ 'use strict'; let contentful = require('contentful'); let client = module.exports = function (app) { return contentful.createClient({ space: app.config.get('CONTENTFUL:SPACE'), accessToken: app.config.get('CONTENTFUL:KEY') }); }; <file_sep>/app/locals.js /** * @fileoverview App locals that assist Jade mixins. * @author <NAME> */ 'use strict'; let fs = require('fs-extra'); let jade = require('jade'); let path = require('path'); /** * @var {string} basedir * @description The absolute path to our Jade views base directory. This is * required to allow us to use root paths in our Jade templates, such as * `extends /global/page`. */ let basedir = module.exports.basedir = path.resolve('app', 'views'); /** * @var {object} renderModule * @description Render the Jade markup with data for a given module. * @param {string} moduleName * @param {object} data * @returns {string} markup - The rendered Jade markup. */ let renderModule = module.exports.renderModule = function (moduleName, data) { let filename = `${basedir}/modules/${moduleName}.jade`; let file = fs.readFileSync(filename); // Render the Jade template. let markup = jade.compile(file, { filename, basedir })(data); return markup; }; /** * @var {object} getData * @param {mixed} [d={}] - An object literal or path to JSON file relative * to the `app` directory. * @returns {object} - The data object. */ let getData = module.exports.getData = function (d) { if (typeof d === 'undefined') { return {}; } else if (typeof d === 'string') { let filePath = path.resolve('app', d); let data = String(fs.readFileSync(filePath)); return JSON.parse(data); } else { return d; } }; <file_sep>/gulp/tasks/default.js /** * @fileoverview Default Gulp task. * @author <NAME> */ 'use strict'; let gulp = require('gulp'); /** * @name default * @description Default Gulp task. Cleans then builds the entire application, * starts the server, and watches for changes. */ gulp.task('default', ['build']); <file_sep>/app/server.js /** * @fileoverview Our node server. * @author <NAME> */ 'use strict'; let _ = require('lodash'); let bodyParser = require('body-parser'); let chalk = require('chalk'); let compression = require('compression'); let express = require('express'); let fs = require('fs-extra'); let http = require('http'); let livereload = require('connect-livereload'); let morgan = require('morgan'); let path = require('path'); let cdn = require('./cdn'); let locals = require('./locals'); let router = require('./router'); let app = module.exports = function (config) { /** * @const {string} ENV * @description The Node environment. * @default development */ const ENV = config.get('NODE:ENV'); /** * @const {string} PATH_TO_LOGS * @description Relative path to the `logs` directory. */ const PATH_TO_LOGS = path.resolve('app', 'logs'); /** * @const {string} PATH_TO_STATIC * @description Relative path to the `static` directory. */ const PATH_TO_STATIC = path.resolve('app', 'static'); /** * @const {string} PATH_TO_VIEWS * @description Relative path to the `views` directory. */ const PATH_TO_VIEWS = path.resolve('app', 'views'); /** * @var {Express} app * @description Our Express application instance. * @see {@link https://www.npmjs.com/package/express} */ let app = express(); /** * Register configs, locals, and cdn with our Express app. */ app.config = config; app.locals = locals; app.locals._ = _; app.cdn = cdn(app); /** * Set various Express properties. * * @see {@link http://expressjs.com/4x/api.html#app.set} */ app.set('env', ENV); app.set('port', process.env.PORT || app.config.get('app:port')); app.set('view engine', 'jade'); app.set('views', PATH_TO_VIEWS); app.set('view cache', true); /** * Register various body compression and parsing middleware. */ app.use(compression()); app.use(bodyParser.json()); /** * Set up the body parser middleware encoding for Express. * * NOTE This does not handle multipart bodies, due to their complex and * typically large nature. */ app.use(bodyParser.urlencoded({ extended: true, resave: false, saveUninitialized: false })); /** * Set up our Morgan logger middleware to write all requests to a log file. * * NOTE If the `access.log` file does not exist, it is created. */ app.use(morgan('combined', { stream: fs.createOutputStream(`${PATH_TO_LOGS}/access.log`, { flags: 'a' }) })); /** * Register development-only middleware. * * NOTE Development only. */ if (ENV === 'development') { app.use(morgan('dev')); app.use(livereload()); app.set('view cache', false); } /** * Set the static public directory for our Express app. * * NOTE These files are available to the world. */ app.use(express.static(`${PATH_TO_STATIC}/.build`)); /** * Attach app to the `req` object so that we can access app properties within * our route controllers. */ app.use(function (req, res, next) { req.app = app; next(); }); /** * Register common routes with our Express app. */ router(app); /** * Register the fallback error handler with our Express app. */ app.use(function (req, res) { let errorController = require('./routes/error'); return errorController.actions.index(req, res); }); /** * Start the HTTP server and listen for requests on the designated port. */ let port = app.get('port'); app.listen(port, function () { if (ENV === 'development') { console.log(chalk.green(`Server listening on port ${port}.`)); } }); }; <file_sep>/gulp/tasks/styles.js /** * @fileoverview Styles Gulp task. * @author <NAME> */ 'use strict'; let gulp = require('gulp'); let plugins = require('gulp-load-plugins')({ camelize: true }); let config = require('../utils/config'); /** * @name styles * @description Compiles our styles into a single file. */ gulp.task('styles', function () { return gulp.src(config.appFiles.styles) .pipe(plugins.plumber()) .pipe(plugins.sass()) .pipe(plugins.autoprefixer(config.autoprefixer)) // .pipe(plugins.minifyCss()) .pipe(gulp.dest(config.paths.styles.dest)) .pipe(plugins.livereload()); }); <file_sep>/gulp/utils/config.js /** * @fileoverview Gulp configs. * @author <NAME> * @ignore */ 'use strict'; let gutil = require('gulp-util'); /** * @const {bool} IS_RELEASE * @description Whether we're using building the app for release or not. */ const IS_RELEASE = gutil.env.release; /** * @var {string} basePaths * @description Core paths to major directories such as the root app folder. */ let basePaths = { app: 'app', src: 'app/static', dest: 'app/static/.build' }; /** * @var {object} paths * @description Base source and destination paths for primary directories. */ let paths = { data: { src: `${basePaths.src}/data`, dest: `${basePaths.dest}/data` }, icons: { src: `${basePaths.src}/icons`, dest: `${basePaths.dest}/icons` }, images: { src: `${basePaths.src}/img`, dest: `${basePaths.dest}/img` }, scripts: { src: `${basePaths.src}/js`, dest: `${basePaths.dest}/js` }, styles: { src: `${basePaths.src}/sass`, dest: `${basePaths.dest}/css` } }; /** * @var {object} appFiles * @description Primary app files src paths. */ let appFiles = { data: `${paths.data.src}/**/*`, icons: `${paths.icons.src}/**/*`, images: `${paths.images.src}/**/*`, scripts: `${paths.scripts.src}/app.js`, styles: `${paths.styles.src}/main.scss` }; /** * @var {object} watch * @description Paths to watch. */ let watch = { data: `${paths.data.src}/**/*`, icons: `${paths.icons.src}/**/*`, images: `${paths.images.src}/**/*`, scripts: `${paths.scripts.src}/**/*`, styles: `${paths.styles.src}/**/*` }; /** * @var {object} browserify * @description browserify configuration. */ let browserify = { debug: ! IS_RELEASE, transform: [ 'babelify' ], noParse: [ 'jade', 'jquery', 'lodash', ] }; /** * @var {object} uglify * @description gulp-uglify configuration. */ let uglify = { mangle: false }; /** * @var {object} autoprefixer * @description gulp-autoprefixer configuration. */ let autoprefixer = { browsers: ['last 2 versions'], cascade: false }; /** * @var {object} svgstore * @description svgstore configuration. */ let svgstore = { filename: 'icons.svg' }; module.exports = { isRelease: IS_RELEASE, debug: ! IS_RELEASE, basePaths, paths, appFiles, watch, browserify, uglify, autoprefixer, svgstore }; <file_sep>/yeoman/generator-raven/app/templates/route/_template/_index.js 'use strict'; let actions = require('./actions'); module.exports = function (router) { router.get('/', actions.index); }; <file_sep>/test/specs.js /** * @fileoverview Mocha test specs. * @author <NAME> */ /* global it, describe, before, after, beforeEach, afterEach */ 'use strict'; let chai = require('chai'); let express = require('express'); let request = require('superagent'); let locals = require('../app/locals'); let app = express(); let expect = chai.expect; let should = chai.should; app.locals = locals; describe('Routing', function () { it('GET / should return 200', function (done) { request.get('localhost:4444/').end(function (err, res) { expect(res).to.exist; expect(res.status).to.equal(200); done(); }); }); it('GET /contact should return 200', function (done) { request.get('localhost:4444/contact').end(function (err, res) { expect(res).to.exist; expect(res.status).to.equal(200); done(); }); }); it('GET /docs should return 200', function (done) { request.get('localhost:4444/docs').end(function (err, res) { expect(res).to.exist; expect(res.status).to.equal(200); done(); }); }); }); describe('API', function () { it('GET /api/v1/todos should return 200', function (done) { request.get('localhost:4444/api/v1/todos').end(function (err, res) { expect(res).to.exist; expect(res.status).to.equal(200); done(); }); }); it('GET /api/v1/todos/:id should return 200', function (done) { request.get('localhost:4444/api/v1/todos/foo').end(function (err, res) { expect(res).to.exist; expect(res.status).to.equal(200); done(); }); }); }); describe('Locals', function () { it('renderModule() should render a given module', function () { let markup = app.locals.renderModule('_test', { data: { foo: 'bar' } }); expect(markup).to.be.a('string'); expect(markup).to.contain('foo is: bar'); }); it('getData() should fetch data when given a path', function () { let obj = app.locals.getData('static/data/_test.json'); expect(obj).to.be.an('object'); }); it('getData() should return the data object when given an object', function () { let data = { foo: 'bar' }; let obj = app.locals.getData(data); expect(obj).to.be.equal(data); }); it('getData() should return an object when no arguments are set', function () { let obj = app.locals.getData(); expect(obj).to.be.an('object'); }); }); <file_sep>/gulp/tasks/clean.js /** * @fileoverview Clean Gulp task. * @author <NAME> */ 'use strict'; let del = require('del'); let gulp = require('gulp'); let config = require('../utils/config'); /** * @name clean * @description Cleans out the pre-existing build folder. */ gulp.task('clean', function (cb) { del(config.basePaths.dest, function () { cb(); }); });
9cadc73b8fc74abba9bd4651d259c3eb5b40a93d
[ "JavaScript", "Markdown" ]
18
JavaScript
nathanbuchar/raven
e4c95c7870f95da943a1913da368c284c8f9b228
3f987c270df93f14095c110a22562a1fbb6ab5b5
refs/heads/master
<file_sep># CameraHelper If you want to customize your camera on Android, it will be very simple and friendly to you <file_sep>package com.lwj.camera; import android.content.Context; import android.graphics.ImageFormat; import android.hardware.Camera; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by lwj on 2017/3/8. * <EMAIL> */ public abstract class CameraHelper implements ICameraOperation { public Camera mCamera; public Camera.Parameters mCameraParameters; public final Camera.CameraInfo mCameraInfo = new Camera.CameraInfo(); public boolean mAutoFocus; public int mFacing = CameraConstants.FACING_BACK; public String mFlash; public int mDisplayOrientation; public int mCameraId; public boolean mShowingPreview; public SurfaceView mSurfaceView; public SurfaceHolder mSurfaceholder; public DisplayOrientationListener displayOrientationListener; public Context context; // 支持的 flash 模式 public ArrayList<String> flash = new ArrayList<>(); public int maxZoom; public CameraHelper(Context context, SurfaceView surfaceView) { this.context = context; this.mSurfaceView = surfaceView; mSurfaceholder = mSurfaceView.getHolder(); mSurfaceholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mSurfaceholder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder h) { } @Override public void surfaceChanged(SurfaceHolder h, int format, int width, int height) { setHeight(height); setWidth(width); if (mCamera != null) { setUpPreview(); adjustCameraParameters(); } } @Override public void surfaceDestroyed(SurfaceHolder h) { setWidth(0); setHeight(0); } }); displayOrientationListener = new DisplayOrientationListener(context) { @Override public void onUpdateOrientation() { mDisplayOrientation = displayOrientationListener.orientation; if (isOpen()) { adjustCameraParameters(); } } }; } public int height; public int width; public boolean isReady() { return height > 0 && width > 0; } public void setHeight(int height) { this.height = height; } public void setWidth(int width) { this.width = width; } @Override public int getMaxZoom() { if (isSupportZoom()) { return mCameraParameters.getMaxZoom(); } return 0; } @Override public boolean isSupportZoom() { return mCameraParameters == null && mCameraParameters.isZoomSupported(); } @Override public void setZoom(int zoomValue) { if (isSupportZoom()) { mCameraParameters.setZoom(zoomValue); } else { Log.w("CameraHelper", "The camera isn't support zoom"); } } /** * 设置预览 */ private void setUpPreview() { try { if (mShowingPreview) { mCamera.stopPreview(); } mCamera.setPreviewDisplay(mSurfaceholder); if (mShowingPreview) { mCamera.startPreview(); } } catch (IOException e) { e.printStackTrace(); } } @Override public void start() { chooseCamera(); openCamera(); if (isReady()) { setUpPreview(); } mShowingPreview = true; mCamera.startPreview(); } private void openCamera() { if (mCamera != null) { releaseCamera(); } mCamera = Camera.open(mCameraId); mCameraParameters = mCamera.getParameters(); adjustCameraParameters(); mCamera.setDisplayOrientation(90); if (callback != null) { callback.onOpen(); } } private void releaseCamera() { if (mCamera != null) { mCamera.release(); mCamera = null; if (callback != null) { callback.onClose(); } } } public abstract Camera.Size choosePreViewSize(); public abstract Camera.Size choosePictureSize(); private void adjustCameraParameters() { Camera.Size preSize = choosePreViewSize(); Camera.Size pictureSize = choosePictureSize(); if (preSize != null) { final Camera.Size currentSize = mCameraParameters.getPictureSize(); if (currentSize.width != preSize.width || currentSize.height != preSize.height) { if (mShowingPreview) { mCamera.stopPreview(); } mCameraParameters.setPreviewSize(preSize.width, preSize.height); if (pictureSize != null) { mCameraParameters.setPictureSize(pictureSize.width, pictureSize.height); } mCameraParameters.setPictureFormat(ImageFormat.JPEG); mCameraParameters.setJpegQuality(100); mCameraParameters.setJpegThumbnailQuality(100); setCameraFocus(mAutoFocus); setFlash(mFlash); } } updateCameraOrientation(); mCameraParameters.setRotation(mRotation); mCamera.setParameters(mCameraParameters); if (mShowingPreview) { mCamera.startPreview(); } } @Override public void stop() { if (mCamera != null) { mCamera.stopPreview(); } mShowingPreview = false; releaseCamera(); } @Override public void setFaceing(int facing) { if (mFacing == facing) { return; } mFacing = facing; if (isOpen()) { stop(); start(); } } @Override public void setAutoFocus(boolean autoFocus) { if (mAutoFocus == autoFocus) { return; } if (setCameraFocus(autoFocus)) { mCamera.setParameters(mCameraParameters); } } @Override public boolean getAutoFocus() { if (!isOpen()) { return mAutoFocus; } String focusMode = mCameraParameters.getFocusMode(); return focusMode != null && focusMode.contains("continuous"); } @Override public int getFaceing() { return mFacing; } @Override public void setFlash(String flash) { if (mFlash != null && mFlash.equals(flash)) { return; } this.mFlash = flash; if (setCameraFlash(flash)) { mCamera.setParameters(mCameraParameters); } } @Override public String getFlash() { return mFlash; } @Override public void setDisplayOrientation(int displayOrientation) { if (mDisplayOrientation == displayOrientation) { return; } mDisplayOrientation = displayOrientation; if (isOpen()) { int cameraRotation = calcCameraRotation(displayOrientation); mCameraParameters.setRotation(cameraRotation); mCamera.setParameters(mCameraParameters); if (mShowingPreview) { mCamera.stopPreview(); } mCamera.setDisplayOrientation(90); if (mShowingPreview) { mCamera.startPreview(); } } } @Override public void takePicture() { if (!isOpen()) { Log.e("CameraHelper", "Camera is not ready. Call start() before takePicture()."); return; } if (getAutoFocus()) { mCamera.cancelAutoFocus(); takePictureInternal(); // mCamera.autoFocus(new Camera.AutoFocusCallback() { // @Override // public void onAutoFocus(boolean success, Camera camera) { // if(success){ //// // } // } // }); } else { takePictureInternal(); } } private void takePictureInternal() { mCamera.takePicture(null, null, null, new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { if (callback != null) { callback.onPictureTaken(data); } mCamera.cancelAutoFocus(); camera.startPreview(); } }); } private void chooseCamera() { for (int i = 0, count = Camera.getNumberOfCameras(); i < count; i++) { Camera.getCameraInfo(i, mCameraInfo); if (mCameraInfo.facing == mFacing) { mCameraId = i; return; } } mCameraId = -1; } /** * 计算方向 * * @param rotation * @return */ private int calcCameraRotation(int rotation) { if (mCameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { return (360 - (mCameraInfo.orientation + rotation) % 360) % 360; } else { // back-facing return (mCameraInfo.orientation - rotation + 360) % 360; } } private boolean setCameraFocus(boolean autoFocus) { mAutoFocus = autoFocus; if (isOpen()) { final List<String> modes = mCameraParameters.getSupportedFocusModes(); if (modes == null && modes.size() <= 0) { return false; } if (autoFocus && modes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { mCameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } else if (modes.contains(Camera.Parameters.FOCUS_MODE_FIXED)) { mCameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_FIXED); } else if (modes.contains(Camera.Parameters.FOCUS_MODE_INFINITY)) { mCameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY); } else { mCameraParameters.setFocusMode(modes.get(0)); } return true; } else { return false; } } @Override public boolean isOpen() { return mCamera != null; } private boolean setCameraFlash(String flash) { if (!isOpen()) { mFlash = flash; return false; } else { if (flash == null) { return false; } List<String> modes = mCameraParameters.getSupportedFlashModes(); if (modes != null && modes.contains(flash)) { mCameraParameters.setFlashMode(flash); mFlash = flash; return true; } if (modes == null || !modes.contains(mFlash)) { mCameraParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); mFlash = CameraConstants.FLASH_OFF; return true; } return false; } } CameraCallback callback; @Override public void setOnCameraOperationListener(CameraCallback callback) { this.callback = callback; } @Override public void switchCamera() { if (mFacing == CameraConstants.FACING_BACK) { setFaceing(CameraConstants.FACING_FRONT); } else if (mFacing == CameraConstants.FACING_FRONT) { setFaceing(CameraConstants.FACING_BACK); } } private int mRotation; private void updateCameraOrientation() { if (mCamera != null) { // rotation参数为 0、90、180、270。水平方向为0。 mRotation = 90 + mDisplayOrientation == 360 ? 0 : 90 + mDisplayOrientation; if (mFacing == CameraConstants.FACING_FRONT) { if (mRotation == 90) { mRotation = 270; } else if (mRotation == 270) { mRotation = 90; } } } } @Override public void onCameraAttached() { displayOrientationListener.onAttachedToWindow(); } @Override public void onCameraDetached() { displayOrientationListener.onDetachedFromWindow(); } @Override public boolean isSupportFlash(String flash) { if (mCameraParameters == null) { return false; } List<String> modes = mCameraParameters.getSupportedFlashModes(); return modes != null && modes.contains(flash); } } <file_sep>package com.lwj.camera; import android.content.Context; import android.util.Log; import android.view.OrientationEventListener; /** * Created by lwj on 2017/3/12. * <EMAIL> */ public abstract class DisplayOrientationListener extends OrientationEventListener { public static String TAG = "DisplayOrientation"; public int orientation = 0; public DisplayOrientationListener(Context context) { super(context); } @Override public void onOrientationChanged(int rotation) { if (((rotation >= 0) && (rotation <= 45)) || (rotation > 315)) { rotation = 0; } else if ((rotation > 45) && (rotation <= 135)) { rotation = 90; } else if ((rotation > 135) && (rotation <= 225)) { rotation = 180; } else if ((rotation > 225) && (rotation <= 315)) { rotation = 270; } else { rotation = 0; } if (rotation == orientation) return; orientation = rotation; onUpdateOrientation(); } public abstract void onUpdateOrientation(); public void onAttachedToWindow() { Log.i(TAG, "enable"); this.enable(); } protected void onDetachedFromWindow() { Log.i(TAG, "disable"); this.disable(); } }
23f2aede7553e966ef09fd0eee02d0a4e4a85372
[ "Markdown", "Java" ]
3
Markdown
lwjfork/CameraHelper
9d02b96033e327fd0c3fe98c29d7155a4c8aea00
44083e5cac90a288f77e722aa373e17c7aa601d2
refs/heads/master
<file_sep># # Be sure to run `pod lib lint BlindsidedStoryboard.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # Any lines starting with a # are optional, but encouraged # # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = "BlindsidedStoryboard" s.version = "0.4.0" s.summary = "A storyboard subclass which enables injecting dependencies into view controllers using Blindside." s.description = <<-DESC Storyboards make dependency injection of view controllers challenging, because they insist on instantiating the view controllers internally. This restriction can be worked around by subclassing UIStoryboard and overriding the -instantiateViewControllerWithIdentifier: method to perform configuration work immediately following the instantiation. The same storyboard instance that is used to create the initial view controller will be used to instantiate further view controllers accessed via segues. This pod provides a BlindsidedStoryboard subclass of UIStoryboard which exemplifies this technique, integrating with the Blindside DI framework. It also contains a small sample app demonstrating how this could be used. DESC s.homepage = "https://github.com/briancroom/BlindsidedStoryboard" s.license = 'MIT' s.author = { "<NAME>" => "<EMAIL>" } s.social_media_url = 'https://twitter.com/aikoniv' s.source = { :git => "https://github.com/briancroom/BlindsidedStoryboard.git", :tag => s.version.to_s } s.ios.deployment_target = '5.0' s.tvos.deployment_target = '9.0' s.requires_arc = true s.source_files = 'Pod/Classes/**/*' s.public_header_files = 'Pod/Classes/**/*.h' s.frameworks = 'UIKit' s.dependency 'Blindside', '~> 1.1' end <file_sep># 0.4.0 * Add support for tvOS * Add BSStoryboardProvider to provide a shorthand mechanism for setting up a view controller binding * Add BSStoryboardKey which is able to instantiate a view controller without additional binding # 0.3.0 * Add support for Xcode 7 Storyboard References # 0.2.0 * Add nullability annotations * Fix header visibility in the framework # 0.1.0 * Initial release.<file_sep>source 'https://github.com/CocoaPods/Specs.git' target 'BlindsidedStoryboard-iOS_Example', :exclusive => true do platform :ios, '8.0' pod "BlindsidedStoryboard", :path => "../" end target 'BlindsidedStoryboard-tvOS_Example', :exclusive => true do platform :tvos, '9.0' pod "BlindsidedStoryboard", :path => "../" pod "Blindside", :git => 'https://github.com/jbsf/blindside.git', :branch => 'master' end target 'BlindsidedStoryboard-iOS_Tests', :exclusive => true do platform :ios, '8.0' pod "BlindsidedStoryboard", :path => "../" pod "Cedar", :git => 'https://github.com/pivotal/cedar.git', :branch => 'master' end target 'BlindsidedStoryboard-tvOS_Tests', :exclusive => true do platform :tvos, '9.0' pod "BlindsidedStoryboard", :path => "../" pod "Blindside", :git => 'https://github.com/jbsf/blindside.git', :branch => 'master' pod "Cedar", :git => 'https://github.com/pivotal/cedar.git', :branch => 'master' end <file_sep># BlindsidedStoryboard [![CI Status](http://img.shields.io/travis/briancroom/BlindsidedStoryboard.svg?style=flat)](https://travis-ci.org/briancroom/BlindsidedStoryboard) [![Version](https://img.shields.io/cocoapods/v/BlindsidedStoryboard.svg?style=flat)](http://cocoapods.org/pods/BlindsidedStoryboard) [![License](https://img.shields.io/cocoapods/l/BlindsidedStoryboard.svg?style=flat)](http://cocoapods.org/pods/BlindsidedStoryboard) [![Platform](https://img.shields.io/cocoapods/p/BlindsidedStoryboard.svg?style=flat)](http://cocoapods.org/pods/BlindsidedStoryboard) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) Storyboards make dependency injection of view controllers challenging, because they insist on instantiating the view controllers internally. This restriction can be worked around by subclassing UIStoryboard and overriding the `-instantiateViewControllerWithIdentifier:` method to perform configuration work immediately following the instantiation. The same storyboard instance that is used to create the initial view controller will be used to instantiate further view controllers accessed via segues. This library provides a `BlindsidedStoryboard` subclass of UIStoryboard which utilizes this technique, integrating with the [Blindside](https://github.com/jbsf/blindside) DI framework. It includes a small sample app demonstrating how it can be used. The `BlindsidedStoryboard(CrossStoryboardSegues)` category can be included to allow for seamless integration with [Cross Storyboard Segues](https://github.com/briancroom/CrossStoryboardSegues). Xcode 7's native storyboard references are also supported, and the same injector will continue to be used when switching storyboards. ## Usage When you create a storyboard instance to show a view controller, just do it like this: ```objective-c id<BSInjector> injector = [Blindside injectorWithModule:[[MyBlindsideModule alloc] init]]; UIStoryboard *storyboard = [BlindsidedStoryboard storyboardWithName:@"Main" bundle:nil injector:injector]; UIViewController *viewController = [storyboard instantiateInitialViewController]; ``` ```swift let injector = Blindside.injectorWithModule(MyBlindsideModule) let storyboard = BlindsidedStoryboard("Main", bundle: nil, injector: injector) let viewController = storyboard.instantiateInitialViewController() ``` `BlindsidedStoryboard` will ensure that viewController has its dependencies injected before it is returned to you. There are a few things to note: * Because the storyboard instantiates the view controller via `-initWithCoder:`, it is necessary to use `+bsProperties` to specify the class' dependencies. * Dependencies won't be available until *after* `-awakeFromNib` has been called. * You can use `-bsAwakeFromPropertyInjection` as a place to put work that needs to occur after dependencies have been injected. ## Installation BlindsidedStoryboard is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod "BlindsidedStoryboard" ``` It can also be installed as a framework using [Carthage](https://github.com/Carthage/Carthage) if you are targeting iOS 8.0 or above. To get it this way, add the following line to your Cartfile: ```ruby github "briancroom/BlindsidedStoryboard" ``` ## Author <NAME>, <EMAIL> ## License BlindsidedStoryboard is available under the MIT license. See the LICENSE file for more info.
5e2bcb32a487f3bc8e501cafcf0ad959f27db820
[ "Markdown", "Ruby" ]
4
Ruby
pivotal-brian-croom/BlindsidedStoryboard
bae63cd00133bbe243ce01ee265e8589e99b59e0
0708d89b5a816e7c09c3eaa612b4017e17e2e794
refs/heads/master
<file_sep>package com.hqj.account.utils; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import java.util.Map; /** * Created by hqj on 2018/1/24 0024. */ public class SharedHelper { private static final String sharedName = "datas"; //保存数据通用方法 public static void set(Map<String, String> map, Context mContext) { SharedPreferences sp = mContext.getSharedPreferences(sharedName, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); for(Map.Entry<String, String> entity : map.entrySet()) { editor.putString(entity.getKey(), entity.getValue()); } editor.commit(); } //保存数据通用方法 public static void set(String key, String value, Context mContext) { SharedPreferences sp = mContext.getSharedPreferences(sharedName, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString(key, value); editor.commit(); Log.i("SharedPreferences:", "写入" + key + "=" + value + "成功"); } public static String get(String key, Context mContext) { SharedPreferences sp = mContext.getSharedPreferences(sharedName, Context.MODE_PRIVATE); String value = sp.getString(key, ""); return value == null ? "" : value; } public static void remove(String key, Context mContext) { SharedPreferences sp = mContext.getSharedPreferences(sharedName, Context.MODE_PRIVATE); sp.edit().remove(key).commit(); } }<file_sep>package com.hqj.account.utils; import android.app.Activity; import android.content.pm.ActivityInfo; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.webkit.WebChromeClient; import android.webkit.WebView; /** * ReWebChomeClient * * @Author KenChung */ public class MyWebChromeClient extends WebChromeClient { private View myView; private CustomViewCallback myCallback; private WebView webView; private Window window; private Activity activity; public MyWebChromeClient() {} public MyWebChromeClient(WebView webView, Window window, Activity activity) { this.window = window; this.webView = webView; this.activity = activity; } @Override public void onShowCustomView(View view, CustomViewCallback callback) { if (myCallback != null) { myCallback.onCustomViewHidden(); myCallback = null ; return; } ViewGroup parent = (ViewGroup) webView.getParent(); parent.removeView( webView); parent.addView(view); myView = view; myCallback = callback; if(activity.getRequestedOrientation()!= ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } //定义全屏参数 int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN; //设置当前窗体为全屏显示 window.setFlags(flag, flag); } public void onHideCustomView() { if (myView != null) { if (myCallback != null) { myCallback.onCustomViewHidden(); myCallback = null ; } ViewGroup parent = (ViewGroup) myView.getParent(); parent.removeView( myView); parent.addView( webView); myView = null; } if(activity.getRequestedOrientation()!= ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } //设置当前窗体为非全屏显示 window.setFlags(0, WindowManager.LayoutParams.FLAG_FULLSCREEN); } /** * 界面加载情况 * @param view * @param title */ @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); // android 6.0 以下通过title获取 } }<file_sep>package com.hqj.account.utils; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ListAdapter; import android.widget.ListView; /** * Created by Administrator on 2018/3/15 0015. */ public class ListViewUtil { public static void setListViewBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = 0; //int maxWidth = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); //int width = listItem.getMeasuredWidth(); //if(width>maxWidth)maxWidth = width; } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); //params.width = maxWidth; listView.setLayoutParams(params); } public static void setListViewHeight(ExpandableListView listView) { ListAdapter listAdapter = listView.getAdapter(); int totalHeight = 0; int count = listAdapter.getCount(); for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); listView.requestLayout(); } /* * ExpandListView自适应高度 根据子项数量 * @param listView * @param listAdapter listView 的适配器 * */ public static void setListHeight(ExpandableListView listView, BaseExpandableListAdapter listAdapter) { int[] isExpand = new int[] { 0, 0}; if (listAdapter == null) { return; } int totalHeight = 0; int total = 0; View listItem; for (int i = 0; i < listAdapter.getGroupCount(); i++) { listItem = listAdapter.getGroupView(i, false, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); total += (listAdapter.getChildrenCount(0) - 1); } for(int i = 0; i < isExpand.length ; i++) { if (isExpand[i] == 1) for (int j = 0; j < listAdapter.getChildrenCount(i); j++) { listItem = listAdapter.getChildView(i, j, false, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); total += (listAdapter.getChildrenCount(i) - 1); } } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * total); listView.setLayoutParams(params); } } <file_sep>package com.hqj.account; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.KeyEvent; import android.view.Window; import android.view.WindowManager; public class WelcomeActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_welcome); getWindow().getDecorView().setBackgroundResource(R.mipmap.bg); new Handler().postDelayed(new Runnable() { public void run() { goHome(); } }, 2000); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode){ case KeyEvent.KEYCODE_BACK: return true; } return super.onKeyUp(keyCode, event); } private void goHome() { Intent intent = new Intent(WelcomeActivity.this, MainActivity.class); startActivity(intent); finish(); } } <file_sep>package com.hqj.account.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * Created by Administrator on 2018/1/24 0024. */ public class NetworkUtil { public static boolean hasNetwork(Context context) { ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connManager != null) { NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo(); if (activeNetInfo != null) { return activeNetInfo.isAvailable(); } } return false; } }
9bde5e480046e62bc897f0c3ab330c90670c30da
[ "Java" ]
5
Java
Heqj/account-app
6bd8f5f1093e7cf24b6bb9d93a639c0b847d102c
6b41c673ee3132cd08cdcaa7d5b7013242ae409d
refs/heads/main
<file_sep>from bs4 import BeautifulSoup import requests import pandas as pd from datetime import datetime ## PARAMETERS SET ## FROM_YEAR = 2009 TO_YEAR = 2018 FROM_MONTH = 1 TO_MONTH = 12 END_DATE = 28 ## Dataframe with column names ## df = pd.DataFrame(columns=['Average temperature (°F)', 'Average humidity (%)', 'Average dewpoint (°F)', 'Average barometer (in)', 'Average windspeed (mph)', 'Average gustspeed (mph)', 'Average direction (°deg)', 'Rainfall for month (in)', 'Rainfall for year (in)', 'Maximum rain per minute', 'Maximum temperature (°F)', 'Minimum temperature (°F)', 'Maximum humidity (%)', 'Minimum humidity (%)', 'Maximum pressure', 'Minimum pressure', 'Maximum windspeed (mph)', 'Maximum gust speed (mph)', 'Maximum heat index (°F)']) done_flag = False for year in range(FROM_YEAR, TO_YEAR + 1): if year == 2018: TO_MONTH = 10 if done_flag: break for month in range(FROM_MONTH, TO_MONTH + 1): URL = "http://www.estesparkweather.net/archive_reports.php?date=" + str(year) + str(month).zfill(2) r = requests.get(URL) soup = BeautifulSoup(r.content, "html.parser") results = dict() for row in soup.findAll('tr'): row_data = row.findAll('td') if len(row_data) == 1: single_str = row_data[0].string if results: if mindex.strftime('%Y-%m-%d') == '2018-10-29': done_flag = True break tmpdf = pd.DataFrame(results, index=[datetime.strptime(mindex.strftime('%Y-%m-%d'), '%Y-%m-%d')]) df = df.append(tmpdf, ignore_index=False) if 'Average and Extremes for Month' in single_str: break month = single_str.split()[0] mdate = single_str.split()[1] mindex = datetime.strptime(month + ' ' + mdate + ' ' + str(year), '%b %d %Y') results.clear() continue e1 = row_data[0].string e2 = row_data[1].string if 'Average temperature' in e1: tmp = e2.replace('<td>', '').strip() results['Average temperature (°F)'] = float((tmp[:tmp.index('°')]).strip()) if 'Average humidity' in e1: tmp = e2.replace('<td>', '').strip() results['Average humidity (%)'] = float((tmp[:tmp.index('%')]).strip()) if 'Average dewpoint' in e1: tmp = e2.replace('<td>', '').strip() results['Average dewpoint (°F)'] = float((tmp[:tmp.index('°')]).strip()) if 'Average barometer' in e1: tmp = e2.replace('<td>', '').strip() results['Average barometer (in)'] = float((tmp[:tmp.index(' ')]).strip()) if 'Average windspeed' in e1: tmp = e2.replace('<td>', '').strip() results['Average windspeed (mph)'] = float((tmp[:tmp.index(' ')]).strip()) if 'Average gustspeed' in e1: tmp = e2.replace('<td>', '').strip() results['Average gustspeed (mph)'] = float((tmp[:tmp.index(' ')]).strip()) if 'Average direction' in e1: tmp = e2.replace('<td>', '').strip() results['Average direction (°deg)'] = float((tmp[:tmp.index('°')]).strip()) if 'Rainfall for month' in e1: tmp = e2.replace('<td>', '').strip() results['Rainfall for month (in)'] = float((tmp[:tmp.index(' ')]).strip()) if 'Rainfall for year' in e1: tmp = e2.replace('<td>', '').strip() results['Rainfall for year (in)'] = float((tmp[:tmp.index(' ')]).strip()) if 'Maximum rain per minute' in e1: tmp = e2.replace('<td>', '').strip() results['Maximum rain per minute'] = float((tmp[:tmp.index(' ')]).strip()) if 'Maximum temperature' in e1: tmp = e2.replace('<td>', '').strip() results['Maximum temperature (°F)'] = float((tmp[:tmp.index('°')]).strip()) if 'Minimum temperature' in e1: tmp = e2.replace('<td>', '').strip() results['Minimum temperature (°F)'] = float((tmp[:tmp.index('°')]).strip()) if 'Maximum humidity' in e1: tmp = e2.replace('<td>', '').strip() results['Maximum humidity (%)'] = float((tmp[:tmp.index('%')]).strip()) if 'Minimum humidity' in e1: tmp = e2.replace('<td>', '').strip() results['Minimum humidity (%)'] = float((tmp[:tmp.index('%')]).strip()) if 'Maximum pressure' in e1: tmp = e2.replace('<td>', '').strip() results['Maximum pressure'] = float((tmp[:tmp.index(' ')]).strip()) if 'Minimum pressure' in e1: tmp = e2.replace('<td>', '').strip() results['Minimum pressure'] = float((tmp[:tmp.index(' ')]).strip()) if 'Maximum windspeed' in e1: tmp = e2.replace('<td>', '').strip() results['Maximum windspeed (mph)'] = float((tmp[:tmp.index(' ')]).strip()) if 'Maximum gust speed' in e1: tmp = e2.replace('<td>', '').strip() results['Maximum gust speed (mph)'] = float((tmp[:tmp.index(' ')]).strip()) if 'Maximum heat index' in e1: tmp = e2.replace('<td>', '').strip() results['Maximum heat index (°F)'] = float((tmp[:tmp.index('°')]).strip()) df.to_csv('weather_data.csv') <file_sep># Scraping Weather Data * In this case study you have to scrape weather data from the website <b>"http://www.estesparkweather.net/archive_reports.php?date=200901"</b> * Scrape all the available attributes of weather data for each day from 2009-01-01 to 2018-10-28 * Ignore records for missing days * Represent the scraped data as pandas dataframe object. ## Dataframe specific details ### Expected column names (order dose not matter): <table><tr><td> <ul> <li>Average temperature (°F)</li> <li>Average humidity (%)</li> <li>Average dewpoint (°F)</li> <li>Average barometer (in)</li> <li>Average windspeed (mph)</li> <li>Average gustspeed (mph)</li> <li>Average direction (°deg)</li> <li>Rainfall for month (in)</li> <li>Rainfall for year (in)</li> <li>Maximum rain per minute</li> </ul></td><td><ul> <li>Maximum temperature (°F)</li> <li>Minimum temperature (°F)</li> <li>Maximum humidity (%)</li> <li>Minimum humidity (%)</li> <li>Maximum pressure</li> <li>Minimum pressure</li> <li>Maximum windspeed (mph)</li> <li>Maximum gust speed (mph)</li> <li>Maximum heat index (°F)</li> </ul> </td></tr></table> ### More details: * Each record in the dataframe corresponds to weather deatils of a given day * Make sure the index column is date-time format (yyyy-mm-dd) * Perform necessary data cleaning and type cast each attributes to relevent data type <file_sep># Web Scraping Web Scraping is a great technique that fetches the contents of a web page directly into your code. Then you are free to manipulate the data as you wish. It is a great tool for data collection. It is often used in data science projects too. Using Web Scraping you can even download files into your local machine. Every resource on the internet is accessed by a URL after all! ;) In this repo, I will place projects that solely use the Web Scraping techniques. For other projects that use web scraping as a tool, I will place a link below: * <a href="https://github.com/Tanishk-Sharma/Python-Mini-Projects-and-Programs/tree/master/The%20Hangman%20Game#hangman-game">The Hangman Game</a>: uses Web Scraping technique to fetch words! * <a href="https://github.com/Tanishk-Sharma/Web-Scraping-Mini-Projects/tree/main/Weather%20Data#scraping-weather-data">Weather Data</a>: Scrape all the available attributes of weather data for each day from 2009-01-01 to 2018-10-28 from a website.
4f07cb3dbf1fc6902521f6b6b1d3e791d91262d1
[ "Markdown", "Python" ]
3
Python
Tanishk-Sharma/Web-Scraping-Mini-Projects
aac70413224eb41affa655d65761b6b69daa924a
c936bef396c2bd0d1af89134078d124fe6bc5909
refs/heads/master
<repo_name>1753033/AnnoyingAlarm<file_sep>/app/src/main/java/com/example/annoyingalarm/MainActivity.java package com.example.annoyingalarm; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.ImageButton; import android.widget.TextView; import com.example.annoyingalarm.alarm.AlarmFragment; import com.example.annoyingalarm.helper.DBHelper; import com.example.annoyingalarm.more.MoreFragment; import com.example.annoyingalarm.news.NewsFragment; import com.example.annoyingalarm.weather.WeatherFragment; public class MainActivity extends AppCompatActivity { final int Code_Settings = 123001; ImageButton btnAlarm, btnWeather, btnNews, btnMore; TextView tvAlarm, tvWeather, tvNews, tvMore; DBHelper dbHelper = new DBHelper(this); AlarmFragment alarmFragment = new AlarmFragment(dbHelper); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title getSupportActionBar().hide(); // hide the title bar setContentView(R.layout.activity_main); tvAlarm = findViewById(R.id.tvAlarm); tvNews = findViewById(R.id.tvNews); tvWeather = findViewById(R.id.tvWeather); tvMore = findViewById(R.id.tvMore); btnAlarm = findViewById(R.id.btnAlarm); btnAlarm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { replaceFragmentContent(alarmFragment); highlightText(tvAlarm); } }); btnWeather = findViewById(R.id.btnWeather); btnWeather.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { replaceFragmentContent(new WeatherFragment()); highlightText(tvWeather); } }); btnNews = findViewById(R.id.btnNews); btnNews.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { replaceFragmentContent(new NewsFragment()); highlightText(tvNews); } }); btnMore = findViewById(R.id.btnMore); btnMore.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { replaceFragmentContent(new MoreFragment()); highlightText(tvMore); } }); initAlarmFragment(); highlightText(tvAlarm); } private void initAlarmFragment() { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction ft = fragmentManager.beginTransaction(); ft.replace(R.id.fragment, alarmFragment); ft.commit(); } protected void replaceFragmentContent(Fragment fragment) { if (fragment != null) { FragmentManager fmgr = getSupportFragmentManager(); FragmentTransaction ft = fmgr.beginTransaction(); ft.replace(R.id.fragment, fragment); ft.commit(); } } void highlightText(TextView tv) { tvWeather.setTextColor(Color.parseColor("#718792")); tvAlarm.setTextColor(Color.parseColor("#718792")); tvMore.setTextColor(Color.parseColor("#718792")); tvNews.setTextColor(Color.parseColor("#718792")); tv.setTextColor(getColor(R.color.colorText)); } } <file_sep>/app/src/main/java/com/example/annoyingalarm/news/NewsFragment.java package com.example.annoyingalarm.news; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.example.annoyingalarm.R; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NewsFragment extends Fragment { ListView lvTitle; ArrayList<String> arrayTitle,arrayLink,arrayImg; NewsAdapter adapter; TextView tvDateNews; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater,container,savedInstanceState); View view = inflater.inflate(R.layout.fragment_news,container,false); tvDateNews = view.findViewById(R.id.tvDateNews); lvTitle = view.findViewById(R.id.lvTitle); arrayTitle = new ArrayList<>(); arrayLink = new ArrayList<>(); arrayImg = new ArrayList<>(); adapter = new NewsAdapter(getContext(),arrayTitle,arrayLink,arrayImg); lvTitle.setAdapter(adapter); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); Date date = new Date(); tvDateNews.setText(formatter.format(date)); new RSS().execute("https://vnexpress.net/rss/so-hoa.rss"); lvTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(getContext(), NewsDetailActivity.class); intent.putExtra("title",arrayTitle.get(position)); intent.putExtra("link",arrayLink.get(position)); startActivity(intent); } }); return view; } private class RSS extends AsyncTask<String,Void,String> { @Override protected String doInBackground(String... strings) { StringBuilder content = new StringBuilder(); try { URL url = new URL(strings[0]); InputStreamReader inputStreamReader = new InputStreamReader(url.openConnection().getInputStream()); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line = ""; while ((line = bufferedReader.readLine())!=null){ content.append(line); } bufferedReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return content.toString(); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); XMLDOMParser parser = new XMLDOMParser(); Document document = parser.getDocument(s); NodeList nodeList = document.getElementsByTagName("item"); NodeList nodeList1 = document.getElementsByTagName("description"); for (int i =0;i<nodeList.getLength();i++){ String cdata = nodeList1.item(i+1).getTextContent(); Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>"); Matcher matcher = p.matcher(cdata); if(matcher.find()){ arrayImg.add(matcher.group(1)); } Element element = (Element) nodeList.item(i); arrayTitle.add(parser.getValue(element,"title")); arrayLink.add(parser.getValue(element,"link")); } adapter.notifyDataSetChanged(); } } } <file_sep>/README.md # Annoying Alarm ## Project Android: Annoying Alarm - Wake you up everytime 1. 1753033 - <NAME> - <EMAIL> 2. 1753030 - <NAME> - <EMAIL> ## Mô tả chức năng link: https://drive.google.com/file/d/1YCceFuEgN4QqU8mrMTwRrR80XZpNjVom/view?usp=sharing 1. Hẹn giờ báo thức * Đây là chức năng chính của ứng dụng, cho người dùng tùy chỉnh các lựa chọn thiết lập báo thức như: thời gian, nhãn nhận biết, âm thanh, lặp lại, độ lớn âm lượng, âm lượng tăng dần. * Điểm đặc biệt là sẽ có phần chọn nhiệm vụ tắt được báo thức: o Mặc định: chỉ cần bấm tắt một lần. o Lắc: người dùng sẽ chọn số lần lắc điện thoại. o Giải bài toán: chọn số lượng và mực độ khó của bài toán. o Có thể thêm nhiều nhiệm vụ mới trong tương lai. 2. Quản lý âm thanh * Các chức năng thêm xóa một bài hát, đoạn nhạc làm chuông báo thức. 3. Đọc tin tức * Chức năng này yêu cầu thiết bị phải được kết nối với Internet. * Cung cấp những tin tức mới nhất cho người dùng, giúp người dung theo dõi thông tin mà không cần phải truy cập nhiều trang báo. 4. Theo dõi thời tiết * Yêu cầu: thiết bị kết nối Internet. * Cung cấp thông tin thời tiết trong ngày. 5. Nghe nhạc thư giản trước khi ngủ * Cho người dùng chọn những bản nhạc thư giản ngắn trước khi ngủ. * Người dùng sẽ chọn thời gian bản nhạc được phát. * Nhạc thư giản gồm những bài hát nhẹ nhàng, tiếng mưa rơi. 6. Theo dõi lịch sử giấc ngủ * Đưa ra một bảng báo cáo thời gian ngủ người dùng theo từng ngày, tuần, tháng, * Bao gồm thời gian bắt đầu ngủ và thức dậy. 7. Tùy chỉnh giao diện * Cho phép tùy chỉnh màu sắc của ứng dụng: light mode, dark mode. 8. Chế độ tiết kiệm pin * Không báo thức nếu thiết bị trong chế độ rung 9. To do list * Cho người dùng lên danh sách những việc cần làm và đánh dấu hoàn thành khi đã làm xong việc. 10. Thêm nhắc nhở * Một dạng báo thức nhưng kèm theo một sự kiện nào đó, bao gồm ghi chú, thời gian, công việc là gì. 11. Đồng bộ Google Calendar * Yêu cầu: thiết bị kết nối Internet và phải đăng nhập tài khoản google. * Đồng bộ những sự kiện với Google Calendar. 12. Hẹn giờ tắt media * Cho phép người dùng đặt thời gian, sau khoảng thời gian đó tất cả các ứng dụng phát media sẽ được tắt. Ví dụ: Youtube, Soundcloud, Facebook Video, ... 13. Đăng nhập * Đăng nhập bằng tài khoản google. 14. Đồng bộ dữ liệu cũ * Đồng bộ dữ liệu cũ nếu đã đăng nhập trước đó. * Đề xuất: dùng sqlite kết hợp firebase. 15. Thành tích * Đánh giá bằng cách tính điểm. * Điểm sẽ ứng với thời gian người dùng dậy và thời gian đặt báo thức. * Từ đó, người dùng sẽ theo dõi được tình trạng ngủ của mình và điều chỉnh lại thời gian báo thức phù hợp. Tham khảo: Alarmy ## Kế hoạch trong tuần * Tuần 1: Giao Diện - UI | MSSV | Tên thành viên | Chức năng | % Hoàn thành | |---------|------------------------|---------------------|--------------| | 1753033 | Trịnh Thái Bình | Báo thức | 100 | | | | Thời tiết | 100 | | | | Tin tức | 100 | | | | Nhạc thư giãn | 100 | | | | Thêm nhắc nhở | 100 | | | | | | | 1753030 | <NAME> | Đăng nhập | 100 | | | | Theo dõi giấc ngủ | 100 | | | | Thành tích | 100 | | | | Đồng bộ GCalender | 100 | | | | Đồng bộ dữ liệu | 100 | | | | | | | 1753028 | Nguyễ<NAME> | Tiết kiệm pin | 100 | | | | To do list | 100 | | | | Hẹn giờ tắt Media | 100 | | | | Quản lý âm thanh | 100 | | | | Tùy chỉnh giao diện | 100 | Link prototype: https://www.figma.com/file/RmN8naeVG5uLmm1Fup2ETK/Project-Android?node-id=1%3A3 * Tuần 2: Cài đặt giao diện - Layout XML | MSSV | Tên thành viên | Chức năng | % Hoàn thành | |---------|------------------------|---------------------|--------------| | 1753033 | Trịnh Thái Bình | Báo thức | 100 | | | | Thời tiết | 100 | | | | Tin tức | 100 | | | | Thêm nhắc nhở | 100 | | | | | | | 1753030 | <NAME> | Đăng nhập | 100 | | | | Theo dõi giấc ngủ | 100 | | | | Thành tích | 100 | | | | Đồng bộ GCalender | 100 | | | | | | | 1753028 | Nguyễn Trần Tuấn Anh | To do list | 100 | Link UI : https://drive.google.com/open?id=1b3Y06f8MNqxVWmXptFNP63FMunYbdxSq * Tuần 3: Cài đặt chức năng Báo thức,Tin tức,Thời tiết | Chức năng | % Giao diện | % Chức năng | |---------------------|-------------|-------------| | Báo thức | 70 | 50 | | Thời tiết | 90 | 100 | | Tin tức | 90 | 100 | Tham khảo : https://viblo.asia/p/ung-dung-alarmclock-voi-android-ZK1ov1dyG5b9 https://www.youtube.com/watch?v=hYT111gytpg&t=4s https://www.youtube.com/watch?v=syYMLWQLBQk&t=23s https://youtu.be/spvbL94cE9c <file_sep>/app/src/main/java/com/example/annoyingalarm/todo/DB.java package com.example.annoyingalarm.todo; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; public class DB extends SQLiteOpenHelper { private static final String DB_NAME = "TODOLIST"; private static final int DB_VERSION = 1; private static final String TABLE_NAME = "Tasks"; private static final String KEY_ID = "ID"; private static final String KEY_TITLE = "Title"; private static final String KEY_DESCRIPTION = "Description"; private static final String KEY_DATE = "Date"; private static final String KEY_STATUS = "Status"; private SQLiteDatabase sqLiteDatabase; public DB(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_TABLE = "create table " + TABLE_NAME + " ( " + KEY_ID + " integer primary key, " + KEY_TITLE + " text, " + KEY_DESCRIPTION + " text, " + KEY_DATE + " text, " + KEY_STATUS + " integer" + " )"; db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {} /** * Insert task into database - Todotasks * @param title * @param desc * @param date * @param status */ public void insertTask (String title, String desc, String date, int status) { sqLiteDatabase = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(KEY_TITLE, title); contentValues.put(KEY_DESCRIPTION, desc); contentValues.put(KEY_DATE, date); contentValues.put(KEY_STATUS, status); sqLiteDatabase.insert(TABLE_NAME, null, contentValues); sqLiteDatabase.close(); } public ArrayList<Task> getAllCompletedTasks () { ArrayList<Task> taskList = new ArrayList<>(); sqLiteDatabase = this.getReadableDatabase(); String selectQuery = "select * from " + TABLE_NAME + " where " + KEY_STATUS + " = 1"; Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { Task task = new Task(); task.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID))); task.setTitle(cursor.getString(cursor.getColumnIndex(KEY_TITLE))); task.setDescription(cursor.getString(cursor.getColumnIndex(KEY_DESCRIPTION))); task.setDate(cursor.getString(cursor.getColumnIndex(KEY_DATE))); task.setStatus(cursor.getInt(cursor.getColumnIndex(KEY_STATUS))); taskList.add(task); } while (cursor.moveToNext()); } sqLiteDatabase.close(); return taskList; } public ArrayList<Task> getAllTasks () { ArrayList<Task> taskList = new ArrayList<>(); sqLiteDatabase = this.getReadableDatabase(); String selectQuery = "select * from " + TABLE_NAME; Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { Task task = new Task(); task.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID))); task.setTitle(cursor.getString(cursor.getColumnIndex(KEY_TITLE))); task.setDescription(cursor.getString(cursor.getColumnIndex(KEY_DESCRIPTION))); task.setDate(cursor.getString(cursor.getColumnIndex(KEY_DATE))); task.setStatus(cursor.getInt(cursor.getColumnIndex(KEY_STATUS))); taskList.add(task); } while (cursor.moveToNext()); } sqLiteDatabase.close(); return taskList; } /** * update status of ID * @param targetID * @param status * @return */ public int updateTaskStatus (int targetID, int status) { sqLiteDatabase = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_STATUS, status); int count = sqLiteDatabase.update(TABLE_NAME, values, KEY_ID+"=?", new String[]{String.valueOf(targetID)}); sqLiteDatabase.close(); return count; } /** * @param targetTask * @param title * @param description * @param targetDate * @return */ public int updateTask(Task targetTask, String title, String description, String targetDate) { sqLiteDatabase = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_TITLE, title); values.put(KEY_DESCRIPTION, description); values.put(KEY_DATE, targetDate); int count = sqLiteDatabase.update(TABLE_NAME, values, KEY_ID+"=?", new String[]{String.valueOf(targetTask.getId())}); sqLiteDatabase.close(); return count; } /** * @param id * @return */ public boolean deleteTask(int id) { sqLiteDatabase = this.getWritableDatabase(); sqLiteDatabase.delete(TABLE_NAME, KEY_ID+"=?", new String[]{String.valueOf(id)}); sqLiteDatabase.close(); return true; } } <file_sep>/app/src/main/java/com/example/annoyingalarm/weather/WeatherAdapter.java package com.example.annoyingalarm.weather; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.annoyingalarm.R; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class WeatherAdapter extends BaseAdapter { Context context; ArrayList<Weather> arrayList; public WeatherAdapter(Context context, ArrayList<Weather> arrayList) { this.context = context; this.arrayList = arrayList; } @Override public int getCount() { return arrayList.size(); } @Override public Object getItem(int position) { return arrayList.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.custom_row_weather,null); Weather weather = arrayList.get(position); TextView tvStatus = convertView.findViewById(R.id.tvStatus); TextView tvDate = convertView.findViewById(R.id.tvDate); TextView tvMaxTemp = convertView.findViewById(R.id.tvMaxTemp); TextView tvMinTemp = convertView.findViewById(R.id.tvMinTemp); ImageView img = convertView.findViewById(R.id.imgState); tvDate.setText(weather.Date); tvStatus.setText(weather.Status); tvMaxTemp.setText(weather.maxTemp+"°C"); tvMinTemp.setText(weather.minTemp+"°C"); Picasso.with(context).load("https://openweathermap.org/img/wn/"+weather.img+".png").into(img); return convertView; } } <file_sep>/app/src/main/java/com/example/annoyingalarm/alarm/AlarmService.java package com.example.annoyingalarm.alarm; import android.app.Service; import android.content.Intent; import android.os.IBinder; import androidx.annotation.Nullable; public class AlarmService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub String type = intent.getExtras().getString("alarmType"); Boolean once = intent.getExtras().getBoolean("once"); Intent alarmIntent; if(type.equals("Math")) { alarmIntent = new Intent(getBaseContext(), AlarmScreenMathActivity.class); } else if (type.equals("Shake")){ alarmIntent = new Intent(getBaseContext(),AlarmScreenShakeActivity.class); } else { alarmIntent = new Intent(getBaseContext(), AlarmScreenActivity.class); } alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); alarmIntent.putExtras(intent); getApplication().startActivity(alarmIntent); /* if(once){ DBHelper dbHelper = new DBHelper(this); dbHelper.getAlarm(intent.getExtras().getLong("id")).setEnabled(false); }*/ AlarmManagerHelper.setAlarms(this); return super.onStartCommand(intent, flags, startId); } } <file_sep>/settings.gradle include ':app' rootProject.name='Annoying Alarm' <file_sep>/app/src/main/java/com/example/annoyingalarm/more/MoreFragment.java package com.example.annoyingalarm.more; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatDelegate; import androidx.fragment.app.Fragment; import com.example.annoyingalarm.R; import com.example.annoyingalarm.relax.RelaxActivity; import com.example.annoyingalarm.todo.TodoListActivity; public class MoreFragment extends Fragment { private static final int REQUEST_CODE_LOGIN = 0x9345; private static final String TAG = "More fragment"; private Button btnTodo, btnTheme, btnSleep; @Nullable @Override public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_more, container, false); btnTodo = view.findViewById(R.id.btnTodoList); btnTodo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent openTodo = new Intent(getContext(), TodoListActivity.class); startActivity(openTodo); } }); btnSleep = view.findViewById(R.id.btnSleepMusic); btnSleep.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent openSleep = new Intent(getContext(), RelaxActivity.class); startActivity(openSleep); } }); btnTheme = view.findViewById(R.id.btnTheme); btnTheme.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(AppCompatDelegate.getDefaultNightMode()==AppCompatDelegate.MODE_NIGHT_NO) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); } onCreateView(inflater, container, savedInstanceState); } }); return view; } } <file_sep>/app/src/main/java/com/example/annoyingalarm/weather/WeatherFragment.java package com.example.annoyingalarm.weather; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.annoyingalarm.R; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; public class WeatherFragment extends Fragment { EditText search; Button btnSearch; TextView tvCity,tvTemp,tvState,tvHumidity,tvCloud,tvWind,tvDate; ImageView iconWeather; String City; String APIKey ="4bae31b7fd7ff07e795d544f0140725f"; ListView lvWeather7days; WeatherAdapter weatherAdapter; ArrayList<Weather> arrayList; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_weather,container,false); search = view.findViewById(R.id.search); btnSearch = view.findViewById(R.id.btnSearch); tvCity = view.findViewById(R.id.tvCityName); tvTemp = view.findViewById(R.id.tvTemp); tvState = view.findViewById(R.id.tvState); tvHumidity = view.findViewById(R.id.tvHumidity); tvCloud = view.findViewById(R.id.tvCloud); tvWind = view.findViewById(R.id.tvWind); tvDate = view.findViewById(R.id.tvDate); iconWeather = view.findViewById(R.id.icon); lvWeather7days = view.findViewById(R.id.lvWeather7days); final LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.findViewById(R.id.layoutTop).getLayoutParams(); arrayList = new ArrayList<>(); weatherAdapter = new WeatherAdapter(getContext(),arrayList); lvWeather7days.setAdapter(weatherAdapter); layoutParams.setMargins(0,0,0,200); lvWeather7days.setVisibility(View.GONE); new GetDataAsyncTask().execute("Saigon"); btnSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String city = search.getText().toString(); if (city.equals("")){ City = "Saigon"; } else { City = city; } lvWeather7days.setVisibility(View.VISIBLE); layoutParams.setMargins(0,0,0,0); new GetDataAsyncTask().execute(City); new GetData7DaysAsyncTask().execute(City); } }); return view; } private class GetDataAsyncTask extends AsyncTask <String,Void,Void>{ @Override protected Void doInBackground(String... strings) { getCurrentWeatherData(strings[0]); return null; } } private class GetData7DaysAsyncTask extends AsyncTask <String,Void,Void>{ @Override protected Void doInBackground(String... strings) { get7DaysData(strings[0]); return null; } } public void getCurrentWeatherData(String data){ RequestQueue requestQueue = Volley.newRequestQueue(getContext()); String URL = "https://api.openweathermap.org/data/2.5/weather?q="+data+"&units=metric&appid="+APIKey; StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); String name = jsonObject.getString("name"); tvCity.setText(name); String dateJSON = jsonObject.getString("dt"); long trans = Long.valueOf(dateJSON); //Chuyen giay thanh mili giay Date day = new Date(trans*1000); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE dd-MM-yyyy"); String Date = simpleDateFormat.format(day); tvDate.setText(Date); JSONArray jsonArrayWeather = jsonObject.getJSONArray("weather"); JSONObject jsonObjectWeather = jsonArrayWeather.getJSONObject(0); String state = jsonObjectWeather.getString("main"); String icon = jsonObjectWeather.getString("icon"); Picasso.with(getContext()).load("https://openweathermap.org/img/wn/"+icon+".png").into(iconWeather); tvState.setText(state); JSONObject jsonObjectMain = jsonObject.getJSONObject("main"); String temp = jsonObjectMain.getString("temp"); String humidity = jsonObjectMain.getString("humidity"); Double t = Double.valueOf(temp); String tem = String.valueOf(t.intValue()); tvTemp.setText(tem+"°C"); tvHumidity.setText(humidity+"%"); JSONObject jsonObjectWind = jsonObject.getJSONObject("wind"); String wi = jsonObjectWind.getString("speed"); tvWind.setText(wi+"m/s"); JSONObject jsonObjectCloud = jsonObject.getJSONObject("clouds"); String cloud = jsonObjectCloud.getString("all"); tvCloud.setText(cloud+"%"); Log.e("JSON Object",response); } catch (JSONException e) { e.printStackTrace(); Log.e("JSON Error",e.toString()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getContext(),"Can't not find.",Toast.LENGTH_SHORT).show(); Log.e("Response Error",error.toString()); } }); requestQueue.add(stringRequest); } private void get7DaysData(String data) { if(!arrayList.isEmpty()){ arrayList.clear(); } String URL = "https://api.openweathermap.org/data/2.5/forecast/daily?q="+data+"&units=metric&cnt=7&appid="+APIKey; RequestQueue requestQueue = Volley.newRequestQueue(getContext()); StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArrayList = jsonObject.getJSONArray("list"); for (int i =1;i<jsonArrayList.length();i++){ JSONObject jsonObjectList = jsonArrayList.getJSONObject(i); String date = jsonObjectList.getString("dt"); long trans = Long.valueOf(date); //Chuyen giay thanh mili giay Date day = new Date(trans*1000); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE dd-MM-yyyy"); String Date = simpleDateFormat.format(day); JSONObject jsonObjectTemp = jsonObjectList.getJSONObject("temp"); String maxTemp = jsonObjectTemp.getString("max"); String minTemp = jsonObjectTemp.getString("min"); Double max = Double.valueOf(maxTemp); Double min = Double.valueOf(minTemp); String Max = String.valueOf(max.intValue()); String Min = String.valueOf(min.intValue()); JSONArray jsonArrayWeather = jsonObjectList.getJSONArray("weather"); JSONObject weather = jsonArrayWeather.getJSONObject(0); String status = weather.getString("description"); String icon = weather.getString("icon"); arrayList.add(new Weather(Date,status,icon,Max,Min)); } weatherAdapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); Log.e("JSON Error",e.toString()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getContext(),"Can't not find.",Toast.LENGTH_SHORT).show(); Log.e("Response Error",error.toString()); } }); requestQueue.add(stringRequest); } } <file_sep>/app/src/main/java/com/example/annoyingalarm/news/NewsAdapter.java package com.example.annoyingalarm.news; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.annoyingalarm.R; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class NewsAdapter extends BaseAdapter { private Context context; ArrayList<String> arrayTitle,arrayLink,arrayImg; public NewsAdapter(Context context, ArrayList<String> arrayTitle,ArrayList<String> arrayLink,ArrayList<String> arrayImg) { this.context = context; this.arrayTitle = arrayTitle; this.arrayLink = arrayLink; this.arrayImg=arrayImg; } @Override public int getCount() { return arrayTitle.size(); } @Override public Object getItem(int position) { return arrayTitle.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.custom_row_news,null); TextView name = convertView.findViewById(R.id.tvName); ImageView icon = convertView.findViewById(R.id.img); name.setText(arrayTitle.get(position)); Picasso.with(context).load(arrayImg.get(position)).into(icon); return convertView; } } <file_sep>/app/src/main/java/com/example/annoyingalarm/alarm/AlarmFragment.java package com.example.annoyingalarm.alarm; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ListView; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.example.annoyingalarm.helper.DBHelper; import com.example.annoyingalarm.R; public class AlarmFragment extends Fragment { ListView listViewAlarm; ImageButton btnAddAlarm; AlarmListAdapter adapter; DBHelper dbHelper; public AlarmFragment(DBHelper dbHelper){ this.dbHelper = dbHelper; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater,container,savedInstanceState); View view = inflater.inflate(R.layout.fragment_alarm, container, false); listViewAlarm = view.findViewById(R.id.listViewAlarm); adapter = new AlarmListAdapter(getContext(),dbHelper.getAlarms(),AlarmFragment.this); listViewAlarm.setAdapter(adapter); btnAddAlarm = view.findViewById(R.id.btnAddAlarm); btnAddAlarm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startAlarmDetailsActivity(-1); } }); return view; } public void startAlarmDetailsActivity(long id) { Intent intent = new Intent(getContext(), AddAlarmActivity.class); intent.putExtra("id", id); startActivityForResult(intent, 0); } public void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { adapter.setAlarms(dbHelper.getAlarms()); adapter.notifyDataSetChanged(); } } public void deleteAlarm(long id) { final long alarmId = id; AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMessage("Do you want to delete "+ dbHelper.getAlarm(alarmId).getName() +" ?") .setCancelable(true) .setNegativeButton("Cancel", null) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dbHelper.deleteAlarm(alarmId); adapter.setAlarms(dbHelper.getAlarms()); adapter.notifyDataSetChanged(); } }).show(); } public void setAlarmEnabled(long id, boolean isEnabled) { AlarmManagerHelper.cancelAlarms(getContext()); AlarmObject obj = dbHelper.getAlarm(id); obj.isEnabled = isEnabled; dbHelper.updateAlarm(obj); adapter.setAlarms(dbHelper.getAlarms()); adapter.notifyDataSetChanged(); AlarmManagerHelper.setAlarms(getContext()); } }
f69e37ac802ab3729749775ece95639ec34e7069
[ "Markdown", "Java", "Gradle" ]
11
Java
1753033/AnnoyingAlarm
8f512986f752370b29929970a755ba95d3358352
7227ab461c9390e2adfc9c0023207fc95eba668b
refs/heads/master
<repo_name>Mihail-Kostov/env<file_sep>/lib/py/xonshlib/__init__.py import os try: ENV = __xonsh_env__ except NameError: ENV = os.environ <file_sep>/img/jql/types/time.go package types import ( "fmt" "time" "github.com/ulmenhaus/env/img/jql/storage" ) // A Date denotes a specifc day in history by modeling as the // number of days (positive or negative) since 1 January 1970 UTC type Date int var ( epoch = time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC) ) // NewDate returns a new date from the encoded data func NewDate(i interface{}) (Entry, error) { if i == nil { return Date(0), nil } n, ok := i.(float64) if !ok { return nil, fmt.Errorf("failed to unpack int from: %#v", i) } return Date(n), nil } // Format formats the date func (d Date) Format(ft string) string { t := epoch.Add(time.Hour * 24 * time.Duration(d)) if ft == "" { ft = "02 Jan 2006" } return t.UTC().Format(ft) } // Reverse creates a new date from the input func (d Date) Reverse(ft, input string) (Entry, error) { if ft == "" { ft = "02 Jan 2006" } t, err := time.Parse(ft, input) if err != nil { return nil, err } return Date(t.Sub(epoch) / (time.Hour * 24)), nil } // Compare returns true iff the given object is a Date and comes // after this date func (d Date) Compare(i interface{}) bool { entry, ok := i.(Date) if !ok { return false } return entry > d } // Add increments the Date by the provided number of days func (d Date) Add(i interface{}) (Entry, error) { days, ok := i.(int) if !ok { return nil, fmt.Errorf("Dates can only be incremented by integers") } return Date(int(d) + days), nil } // Encoded returns the Date encoded as a string func (d Date) Encoded() storage.Primitive { return int(d) } <file_sep>/img/jql/ui/mainview.go package ui import ( "fmt" "os" "os/exec" "strings" "github.com/jroimartin/gocui" "github.com/ulmenhaus/env/img/jql/osm" "github.com/ulmenhaus/env/img/jql/storage" "github.com/ulmenhaus/env/img/jql/types" ) // MainViewMode is the current mode of the MainView. // It determines which subview processes inputs. type MainViewMode int const ( // MainViewModeTable is the mode for standard table // navigation, filtering, ordering, &c MainViewModeTable MainViewMode = iota // MainViewModePrompt is for when the user is being // prompted to enter information MainViewModePrompt // MainViewModeAlert is for when the user is being // shown an alert in the prompt window MainViewModeAlert // MainViewModeEdit is for when the user is editing // the value of a single cell MainViewModeEdit ) // A MainView is the overall view of the table including headers, // prompts, &c. It will also be responsible for managing differnt // interaction modes if jql supports those. type MainView struct { path string OSM *osm.ObjectStoreMapper DB *types.Database Table *types.Table Params types.QueryParams columns []string // TODO map[string]types.Entry and []types.Entry could both // be higher-level types (e.g. VerboseRow and Row) entries [][]types.Entry TableView *TableView Mode MainViewMode switching bool // on when transitioning modes has not yet been acknowleged by Layout alert string promptText string } // NewMainView returns a MainView initialized with a given Table func NewMainView(path, start string) (*MainView, error) { var store storage.Store if strings.HasSuffix(path, ".json") { store = &storage.JSONStore{} } else { return nil, fmt.Errorf("unknown file type") } mapper, err := osm.NewObjectStoreMapper(store) if err != nil { return nil, err } f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() db, err := mapper.Load(f) if err != nil { return nil, err } mv := &MainView{ path: path, OSM: mapper, DB: db, } return mv, mv.loadTable(start) } // loadTable display's the named table in the main table view func (mv *MainView) loadTable(t string) error { table, ok := mv.DB.Tables[t] if !ok { return fmt.Errorf("unknown table: %s", t) } mv.Table = table columns := []string{} widths := []int{} for _, column := range table.Columns { if strings.HasPrefix(column, "_") { // TODO note these to skip the values as well continue } widths = append(widths, 20) columns = append(columns, column) } mv.TableView = &TableView{ Values: [][]string{}, Widths: widths, } mv.columns = columns return mv.updateTableViewContents() } // Layout returns the gocui object func (mv *MainView) Layout(g *gocui.Gui) error { switching := mv.switching mv.switching = false // TODO hide prompt if not in prompt mode or alert mode maxX, maxY := g.Size() v, err := g.SetView("table", 0, 0, maxX-2, maxY-3) if err != nil { if err != gocui.ErrUnknownView { return err } v.Editable = true v.Editor = mv } v.Clear() if err := mv.TableView.WriteContents(v); err != nil { return err } prompt, err := g.SetView("prompt", 0, maxY-3, maxX-2, maxY-1) if err != nil { if err != gocui.ErrUnknownView { return err } prompt.Editable = true prompt.Editor = &PromptHandler{ Callback: mv.promptExit, } } if switching { prompt.Clear() } switch mv.Mode { case MainViewModeTable: if _, err := g.SetCurrentView("table"); err != nil { return err } g.Cursor = false case MainViewModeAlert: if _, err := g.SetCurrentView("table"); err != nil { return err } g.Cursor = false fmt.Fprintf(prompt, mv.alert) case MainViewModePrompt: if _, err := g.SetCurrentView("prompt"); err != nil { return err } g.Cursor = true prompt.Write([]byte(mv.promptText)) prompt.MoveCursor(len(mv.promptText), 0, true) mv.promptText = "" case MainViewModeEdit: if _, err := g.SetCurrentView("prompt"); err != nil { return err } g.Cursor = true prompt.Write([]byte(mv.promptText)) prompt.MoveCursor(len(mv.promptText), 0, true) mv.promptText = "" } return nil } // newEntry prompts the user for the pk to a new entry and // attempts to add an entry with that key // TODO should just create an entry if using uuids func (mv *MainView) newEntry() { mv.promptText = "create-new-entry " mv.switchMode(MainViewModePrompt) } // switchMode sets the main view's mode to the new mode and sets // the switching flag so that Layout is aware of the transition func (mv *MainView) switchMode(new MainViewMode) { mv.switching = true mv.Mode = new } // saveContents asks the osm to save the current contents to disk func (mv *MainView) saveContents() error { f, err := os.OpenFile(mv.path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return err } defer f.Close() err = mv.OSM.Dump(mv.DB, f) if err != nil { return err } return fmt.Errorf("Wrote %s", mv.path) } // Edit handles keyboard inputs while in table mode func (mv *MainView) Edit(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) { if mv.Mode == MainViewModeAlert { mv.switchMode(MainViewModeTable) } var err error defer func() { if err != nil { mv.alert = err.Error() mv.switchMode(MainViewModeAlert) } }() switch key { case gocui.KeyArrowRight: mv.TableView.Move(DirectionRight) case gocui.KeyArrowUp: mv.TableView.Move(DirectionUp) case gocui.KeyArrowLeft: mv.TableView.Move(DirectionLeft) case gocui.KeyArrowDown: mv.TableView.Move(DirectionDown) case gocui.KeyEnter: mv.switchMode(MainViewModeEdit) row, column := mv.TableView.GetSelected() mv.promptText = mv.TableView.Values[row][column] } primary := mv.Table.Primary() switch ch { case 'b': row, column := mv.TableView.GetSelected() _, err = exec.Command("open", mv.TableView.Values[row][column]).CombinedOutput() case ':': mv.switchMode(MainViewModePrompt) case 'o': _, col := mv.TableView.GetSelected() mv.Params.OrderBy = mv.columns[col] mv.Params.Dec = false err = mv.updateTableViewContents() case 'O': _, col := mv.TableView.GetSelected() mv.Params.OrderBy = mv.columns[col] mv.Params.Dec = true err = mv.updateTableViewContents() case 'i': row, col := mv.TableView.GetSelected() key := mv.entries[row][primary].Format("") // TODO should use an Update so table can modify any necessary internals new, err := mv.Table.Entries[key][col].Add(1) if err != nil { return } mv.Table.Entries[key][col] = new err = mv.updateTableViewContents() case 'I': row, col := mv.TableView.GetSelected() key := mv.entries[row][primary].Format("") // TODO should use an Update so table can modify any necessary internals new, err := mv.Table.Entries[key][col].Add(-1) if err != nil { return } mv.Table.Entries[key][col] = new err = mv.updateTableViewContents() case 's': err = mv.saveContents() case 'n': mv.newEntry() } } func (mv *MainView) updateTableViewContents() error { mv.TableView.Values = [][]string{} // NOTE putting this here to support swapping columns later header := []string{} for _, col := range mv.columns { if mv.Params.OrderBy == col { if mv.Params.Dec { col += " ^" } else { col += " v" } } header = append(header, col) } mv.TableView.Header = header entries, err := mv.Table.Query(mv.Params) if err != nil { return err } mv.entries = entries for _, row := range mv.entries { // TODO ignore hidden columns formatted := []string{} for _, entry := range row { // TODO extract actual formatting formatted = append(formatted, entry.Format("")) } mv.TableView.Values = append(mv.TableView.Values, formatted) } return nil } func (mv *MainView) promptExit(contents string, finish bool, err error) { current := mv.Mode if !finish { return } defer func() { if err != nil { mv.switchMode(MainViewModeAlert) mv.alert = err.Error() } else { mv.switchMode(MainViewModeTable) } }() if err != nil { return } switch current { case MainViewModeEdit: row, column := mv.TableView.GetSelected() primary := mv.Table.Primary() key := mv.entries[row][primary].Format("") err = mv.Table.Update(key, mv.Table.Columns[column], contents) if err != nil { return } err = mv.updateTableViewContents() return case MainViewModePrompt: parts := strings.Split(contents, " ") if len(parts) == 0 { return } command := parts[0] switch command { case "create-new-entry": if len(parts) != 2 { err = fmt.Errorf("create-new-entry takes 1 arg") return } newPK := parts[1] err = mv.Table.Insert(newPK) if err != nil { return } err = mv.updateTableViewContents() return default: err = fmt.Errorf("unknown command: %s", contents) } } } <file_sep>/img/jql/types/primitives.go package types import ( "fmt" "github.com/ulmenhaus/env/img/jql/storage" ) // A String is an array of characters type String string // NewString returns a new string from the encoded data func NewString(i interface{}) (Entry, error) { if i == nil { return String(""), nil } s, ok := i.(string) if !ok { return nil, fmt.Errorf("failed to unpack string from: %#v", i) } return String(s), nil } // Format formats the string func (s String) Format(ft string) string { return string(s) } // Reverse creates a new string from the input func (s String) Reverse(ft, input string) (Entry, error) { return String(input), nil } // Compare returns true iff the given object is a string and comes // lexicographically after this string func (s String) Compare(i interface{}) bool { entry, ok := i.(String) if !ok { return false } return entry > s } // Add concatonates the provided string with the String func (s String) Add(i interface{}) (Entry, error) { addend, ok := i.(string) if !ok { return nil, fmt.Errorf("Strings can only be concatonated with strings") } return String(string(s) + addend), nil } // Encoded returns the String encoded as a string func (s String) Encoded() storage.Primitive { return string(s) } <file_sep>/img/jql/osm/mapper.go package osm import ( "fmt" "io" "sort" "strings" "github.com/ulmenhaus/env/img/jql/storage" "github.com/ulmenhaus/env/img/jql/types" ) const schemataTableName = "_schemata" var ( constructors = map[string]types.FieldValueConstructor{ "string": types.NewString, "date": types.NewDate, } ) // An ObjectStoreMapper is responsible for converting between the // internal representation of a database and the encoded version // used by storage drivers type ObjectStoreMapper struct { store storage.Store } // NewObjectStoreMapper returns a new ObjectStoreMapper given a storage driver func NewObjectStoreMapper(store storage.Store) (*ObjectStoreMapper, error) { return &ObjectStoreMapper{ store: store, }, nil } // Load takes the given reader of a serialized databse and returns a databse object func (osm *ObjectStoreMapper) Load(src io.Reader) (*types.Database, error) { // XXX needs refactor raw, err := osm.store.Read(src) if err != nil { return nil, err } schemata, ok := raw[schemataTableName] if !ok { return nil, fmt.Errorf("missing schema table") } // field index is non deterministic which will lead to random output // we could have another attribute for "_presentation" which contains // column order and widths fieldsByTable := map[string][]string{} primariesByTable := map[string]string{} constructorsByTable := map[string][]types.FieldValueConstructor{} for name, schema := range schemata { parts := strings.Split(name, ".") if len(parts) != 2 { return nil, fmt.Errorf("invalid column name: %s", name) } table := parts[0] column := parts[1] // TODO schema validation outside of loop -- this is inefficient fieldTypeRaw, ok := schema["type"] if !ok { return nil, fmt.Errorf("missing type for %s.%s", table, column) } fieldType, ok := fieldTypeRaw.(string) if !ok { return nil, fmt.Errorf("invalid type %#v", fieldTypeRaw) } if strings.HasPrefix(fieldType, "foreign.") || strings.HasPrefix(fieldType, "dynamic.") { // TODO implement foreign keys and dymanic columns // ignoring for now continue } if primary, ok := schema["primary"]; ok { if primaryB, ok := primary.(bool); ok && primaryB { if currentPrimary, ok := primariesByTable[table]; ok { return nil, fmt.Errorf("Duplicate primary keys for %s: %s %s", table, currentPrimary, column) } primariesByTable[table] = column } } constructor := constructors[fieldType] if !ok { return nil, fmt.Errorf("invalid type '%s'", fieldType) } byTable, ok := fieldsByTable[table] if !ok { fieldsByTable[table] = []string{column} constructorsByTable[table] = []types.FieldValueConstructor{constructor} } else { fieldsByTable[table] = append(byTable, column) constructorsByTable[table] = append(constructorsByTable[table], constructor) } } indexMap := map[string]int{} for table, byTable := range fieldsByTable { sort.Slice(byTable, func(i, j int) bool { return byTable[i] < byTable[j] }) for index, column := range byTable { indexMap[fmt.Sprintf("%s.%s", table, column)] = index } if _, ok := primariesByTable[table]; !ok { return nil, fmt.Errorf("No primary key for table: %s", table) } } delete(raw, schemataTableName) db := &types.Database{ Schemata: schemata, Tables: map[string]*types.Table{}, } for name, encoded := range raw { primary, ok := primariesByTable[name] if !ok { return nil, fmt.Errorf("Unknown table: %s", name) } // TODO use a constructor and Inserts -- that way the able can map // columns by name table := types.NewTable(fieldsByTable[name], map[string][]types.Entry{}, primary, constructorsByTable[name]) db.Tables[name] = table for pk, fields := range encoded { row := make([]types.Entry, len(fieldsByTable[name])) table.Entries[pk] = row fields[primary] = pk for column, value := range fields { fullName := fmt.Sprintf("%s.%s", name, column) index, ok := indexMap[fullName] if !ok { return nil, fmt.Errorf("unknown column: %s", fullName) } schema, ok := schemata[fullName] if !ok { return nil, fmt.Errorf("missing schema for %s.%s", name, column) } // TODO use structured data from above schema validation // instead of keying map fieldType := schema["type"].(string) constructor, ok := constructors[fieldType] if !ok { return nil, fmt.Errorf("invalid type '%s'", fieldType) } typedVal, err := constructor(value) if err != nil { return nil, err } row[index] = typedVal } } } return db, nil } // Dump takes the database and serializes it using the storage driver func (osm *ObjectStoreMapper) Dump(db *types.Database, dst io.Writer) error { encoded := storage.EncodedDatabase{ schemataTableName: db.Schemata, } for name, table := range db.Tables { encodedTable := storage.EncodedTable{} pkCol := table.Primary() for pk, row := range table.Entries { // TODO inconsistent use of entry in types and storage encodedEntry := storage.EncodedEntry{} for i, entry := range row { if i != pkCol { encodedEntry[table.Columns[i]] = entry.Encoded() } } encodedTable[pk] = encodedEntry } encoded[name] = encodedTable } err := osm.store.Write(dst, encoded) return err } <file_sep>/img/jql/ui/table.go package ui import ( "fmt" "io" ) // A Direction denotes which way to move a cursor when navigating // a table view type Direction int const ( // DirectionRight denotes moving the cursor right DirectionRight Direction = iota // DirectionUp denotes moving the cursor up DirectionUp // DirectionLeft denotes moving the cursor left DirectionLeft // DirectionDown denotes moving the cursor down DirectionDown ) // A TableView is a gocui object for vizualizing tabular data type TableView struct { Header []string Values [][]string Widths []int row int column int } // Move moves the table's cursor in the input direction func (tv *TableView) Move(d Direction) { switch d { case DirectionRight: if len(tv.Values) > 0 && tv.column < len(tv.Values[0])-1 { tv.column++ } case DirectionUp: if tv.row > 0 { tv.row-- } case DirectionLeft: if tv.column > 0 { tv.column-- } case DirectionDown: if tv.row < len(tv.Values)-1 { tv.row++ } } } // WriteContents writes the contents of the table to a gocui view func (tv *TableView) WriteContents(v io.Writer) error { // TODO paginate horizantally and vertically // Also figure out how to make the cursor disappear when inactive content := "" for j, val := range tv.Header { width := tv.Widths[j] if len(val) >= width { val = val[:width] } else { diff := width - len(val) for k := 0; k < diff; k++ { val += " " } } content += " " + val + " " } content += "\n" for i, row := range tv.Values { for j, val := range row { width := tv.Widths[j] if len(val) >= width { val = val[:width] } else { diff := width - len(val) for k := 0; k < diff; k++ { val += " " } } if i == tv.row && j == tv.column { content += "> " + val + " " } else { content += " " + val + " " } } content += "\n" } _, err := fmt.Fprintf(v, content) return err } // GetSelected returns the selected row and column func (tv *TableView) GetSelected() (int, int) { return tv.row, tv.column }
e9b30b9289dd3e2aa030b04e8462e47a97d16e6f
[ "Python", "Go" ]
6
Python
Mihail-Kostov/env
630a41a306798d6b36bcc235823305675028f87a
8392c00b6808fc6b5ec963c8ded04858a15548ab
refs/heads/main
<file_sep>import fetch from 'node-fetch' import {URL} from 'url' import {IFeatureCollection, TCoordinate} from '../types/omsApiServiceTypes' /** * Получение содержимое GeoJSON для города по названию * @param name Название города * @returns TCoordinate - координаты границ города в системе OSM */ export default async function fetchCityBoundaries(cityName: string): Promise<TCoordinate> { try { const coordinates = await requestCityBoundariesWithGeoJson(cityName) return coordinates } catch (error) { console.error( '\ [error] getCityID: failed to get osm coordinates of city.\n\ [error] getCityID: return []\n\ [error] getCityID: ', error ) return [] } } async function requestCityBoundariesWithGeoJson(cityName: string): Promise<TCoordinate> { const url = new URL('https://nominatim.openstreetmap.org/search.php') url.searchParams.append('q', cityName) url.searchParams.append('polygon_geojson', '1') url.searchParams.append('accept-language', 'ru') url.searchParams.append('limit', '1') url.searchParams.append('format', 'geojson') const res = await fetch(url, {method: 'GET'}) const data: IFeatureCollection = await res.json() // TODO Simple first const coordinates = data.features.pop().geometry.coordinates return coordinates } <file_sep>export interface IFeatureCollection { features: IFeature[] } export interface IFeature { geometry: { type: string coordinates: TCoordinate } } export type TCoordinate = number | number[] | TCoordinate[] <file_sep>import getGeoJsonOfCities from './utils/getGeoJsonOfCities' async function main() { await getGeoJsonOfCities() console.info('done') } main() <file_sep>import getCities from './readCitiesTxt' import clearDist from './clearDist' import makeGeoJson from './makeGeoJson' import fetchCityBoundaries from './fetchCityBoundaries' /** * Получение координат границ этих городов. * Источник (Список городов): Текстовый файл, в котором на каждой строке написано название города на Русском языке. * Результат (Файлы geo.json с координатами границ городов) */ export default async function getGeoJsonOfCities() { const cities = getCities() clearDist() for (const cityName of cities) { const coordinates = await fetchCityBoundaries(cityName) makeGeoJson(cityName, coordinates) console.info(`make ${cityName}.geo.json`) } } <file_sep>import {TCoordinate} from '../types/omsApiServiceTypes' const fs = require('fs'), path = require('path') export default function makeGeoJson(fileName: string, coordinates: TCoordinate): void { const distPath = path.resolve('dist') const filePath = path.resolve('dist/' + fileName + '.geo.json') try { // Check dist/ !fs.existsSync(distPath) && fs.mkdirSync(distPath) // Make file const fileData = JSON.stringify(coordinates) fs.writeFileSync(filePath, fileData, {flag: 'w'}) } catch (error) { console.error('\ [error] makeGeoJson: failed to make file geo.json.\n\ [error] makeGeoJson: ', error) } } <file_sep>up: docker-compose up install: docker-compose run node npm install run: docker-compose run node npm run start start: up install run .PHONY: start \ up install run<file_sep>const fs = require('fs'), path = require('path') /** * Метод извлекает список городов из файла configs/cities.txt * @param file путь к файлу отно * @returns Массив названий городов */ export default function readCitiesTxt(): string[] { const filePath = path.resolve('src/configs/cities.txt') try { const cities = fs .readFileSync(filePath, 'utf8') .toString() .split('\n') .map((line: string) => line.trim()) return cities } catch (error) { console.error( '\ [error] getCities: failed to get names of city.\n\ [error] getCities: return []\n\ [error] getCities: ', error ) return [] } } <file_sep>const fs = require('fs'), path = require('path') export default function clearDist() { const distPath = path.resolve('dist') try { // Check dist/ !fs.existsSync(distPath) && fs.mkdirSync(distPath) // Clear dist/ fs.readdirSync(distPath).forEach((file) => { fs.unlinkSync(path.join(distPath, file)) }) } catch (error) { console.error('\ [error] makeGeoJson: failed to clear directory dist/\n\ [error] makeGeoJson: ', error) } } <file_sep>FROM node:14-alpine WORKDIR /project EXPOSE 8080<file_sep># City-boundaries Application «Node.JS-Приложение для доступа к информации OSM» - Node.js - OSM API - Typescript - Makafile - Docker - Docker-composer Запуск в контейнере: > make start Запус локально: > npm install > npm start<file_sep>Что можно улучшить ? Можно перейти к сервисной структуре проекта. Выделить доменные сущности, слои контроллеров, сервисов, репозиториев (моделей) Можно организовать сервис с API для получения координа по названию города Можно организовать сущность для конфигурации сервиса Можно перейти в node-fetch на axois для единообразия с фронтом Можно изменить политику обработки ошибок Можно перейти к асинхронным операциям работы с файлами Можно изменить метод получения названий и читать по одной строке
5686010400a31dbe4b6f6213e9bca742ce76980d
[ "Markdown", "TypeScript", "Makefile", "Dockerfile" ]
11
TypeScript
Tom-Challenger/ciry-boundries
3a7d7fbaefd7dd3bdb8330eaf6538dd5a9ee3474
587b49ac979103253d3fdfe7b725fc1ac3549e9a
refs/heads/main
<file_sep>from flight_data import FlightData import requests from datetime import date, timedelta from dateutil.relativedelta import relativedelta FLIGHT_KEY = "YOUR FLIGHT KEY" FLIGHT_API = "https://tequila-api.kiwi.com" FLIGHT_IATA = "/locations/query" FLIGHT_SEARCH = "/v2/search" FLIGHT_HEADER = { "apikey": FLIGHT_KEY, } tomorrow = date.today() + timedelta(days=1) tomorrow = tomorrow.strftime("%d/%m/%Y") six_month = date.today() + relativedelta(months=+6) six_month = six_month.strftime("%d/%m/%Y") parameters = { "date_from": tomorrow, "date_to": six_month, "fly_from": "AMS", "fly_to": "AMS", "nights_in_dst_from": 7, "nights_in_dst_to": 28, "flight_type": "round", "max_stopovers": 0, "one_for_city": 1, } class FlightSearch: # This class is responsible for talking to the Flight Search API. def get_iata(self, city_name): parameters = { "term": city_name, "location_types": "city", } iata_data = requests.get(url=f"{FLIGHT_API}{FLIGHT_IATA}", params=parameters, headers=FLIGHT_HEADER) return iata_data.json()["locations"][0]["code"] def get_price(self, fly_from, fly_to): destination = {"fly_to": fly_to, "fly_from": fly_from} parameters.update(destination) price_data = requests.get(url=f"{FLIGHT_API}{FLIGHT_SEARCH}", params=parameters, headers=FLIGHT_HEADER) try: data = price_data.json()["data"][0] except IndexError: parameters["max_stopovers"] = 1 price_data = requests.get(url=f"{FLIGHT_API}{FLIGHT_SEARCH}", params=parameters, headers=FLIGHT_HEADER) try: data = price_data.json()["data"][0] except IndexError: print("No flights found.") return None flight_data = FlightData( price=data["price"], origin_city=data["route"][0]["cityFrom"], origin_airport=data["route"][0]["flyFrom"], destination_city=data["route"][0]["cityTo"], destination_airport=data["route"][0]["flyTo"], out_date=data["route"][0]["local_departure"].split("T")[0], return_date=data["route"][1]["local_departure"].split("T")[0], stop_overs=1, via_city=data["route"][0]["cityTo"], ) print(f"{flight_data.destination_city}: {flight_data.price} Euro with Stopover in {flight_data.via_city}") return flight_data else: flight_data = FlightData( price=data["price"], origin_city=data["route"][0]["cityFrom"], origin_airport=data["route"][0]["flyFrom"], destination_city=data["route"][0]["cityTo"], destination_airport=data["route"][0]["flyTo"], out_date=data["route"][0]["local_departure"].split("T")[0], return_date=data["route"][1]["local_departure"].split("T")[0] ) print(f"{flight_data.destination_city}: {flight_data.price} Euro") return flight_data <file_sep># ask the user to add her name to a google sheet # check the requested cities (also in google sheet) against a price # if price is available send an email from data_manager import DataManager from flight_search import FlightSearch from notification_manager import NotificationManager data_manager = DataManager() flight_search = FlightSearch() notification_manager = NotificationManager() DEPARTURE_CITY = "AMS" KEY_IATA_CODE = "IATA Code" # user input (name, email) data_manager.add_new_user() # for entries in google sheet, if iata code is empty, search for iata code based on city name sheet_data = data_manager.get_data() print(len(sheet_data)) for x in range(len(sheet_data)): if sheet_data[x][KEY_IATA_CODE] == "": sheet_data[x][KEY_IATA_CODE] = flight_search.get_iata(sheet_data[x]["City"]) # update entries in google sheet data_manager.update_iatacode(sheet_data) # get all emails from user data sheet user_data = data_manager.get_email() user_emails = [entry["Email"] for entry in user_data] # search for price for x in range(len(sheet_data)): flight = flight_search.get_price(fly_from=DEPARTURE_CITY, fly_to=sheet_data[x][KEY_IATA_CODE]) # email info to user if flight is not None and flight.price < sheet_data[x]["Lowest Price"]: content = f"Subject: Low Price! {flight.price} - {flight.origin_city}-{flight.destination_city}\n\nOnly {flight.price} Euro to fly from {flight.origin_city} to {flight.destination_city}, from {flight.out_date} to {flight.return_date}.\n" if flight.stop_overs > 0: content += f"\nFlight has {flight.stop_overs} stop over, via {flight.via_city}." notification_manager.send_email(message=content, email_list=user_emails) <file_sep>import gspread from oauth2client.service_account import ServiceAccountCredentials # add credentials to the account SCOPE = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] CREDS = ServiceAccountCredentials.from_json_keyfile_name('YOUR KEY.json', SCOPE) # authorize the clientsheet client = gspread.authorize(CREDS) # get the instance of the Spreadsheet sheet = client.open('FlightDeals') # get the first sheet of the Spreadsheet sheet_instance = sheet.get_worksheet(0) sheet_user = sheet.get_worksheet(1) class DataManager: def __init__(self): self.destination_nfo = {} def get_data(self): self.destination_nfo = sheet_instance.get_all_records() return self.destination_nfo def update_iatacode(self, sheet_data): print(sheet_data) for x in range(len(sheet_data)): sheet_instance.update_acell(f"B{x+2}", sheet_data[x]["IATA Code"]) def add_new_user(self): ### User input to sign up for flight club print("""Welcome to our Flight Club.\n We find the best flight deals and mail you the lowest prices.""") first_name = input("What ist your first name? ") last_name = input("What is your last name? ") email = input("What is your email? ") email_confirm = input("Please confirm (retype) your email. ") if email == email_confirm: user_entry = [first_name, last_name, email] empty_row_user_sheet = len(sheet_user.get_all_records()) + 2 sheet_user.insert_row(user_entry, empty_row_user_sheet) print("You are in the club!") def get_email(self): self.user_data = sheet_user.get_all_records() return self.user_data <file_sep>import smtplib MY_EMAIL = "SENDER EMAIL" MY_SMTP = "smtp.gmail.com" PASSWORD = "<PASSWORD>" class NotificationManager: # sending notifications with the deal flight details. def send_email(self, message, email_list): for user_email in email_list: with smtplib.SMTP(MY_SMTP) as email: email.starttls() email.login(user=MY_EMAIL, password=<PASSWORD>) email.sendmail(from_addr=MY_EMAIL, to_addrs=user_email, msg=message)<file_sep># Flight_Deal_Finder Inspired by jacksflightclub.com Checks flights and pices against a given list of flights (in a google sheet, see screenshot 1). If cheaper price available, send email to list of people (from google sheet, see screenshot 2). Possibility for user input, to add a new email to the google sheet.
71c2cc3912f63272a5f4b814d8f5fdf048a6fbff
[ "Markdown", "Python" ]
5
Python
B-Benja/Flight_Deal_Finder
98b1f04aff828d0388d8b6281b9868e9fd3e447c
572b08503a1b010f8e325ea39e73ccfe65c0f31d
refs/heads/master
<file_sep># TicTacToeDemo Play tic tac toe game with device <a href="https://imgflip.com/gif/318nli"><img src="https://i.imgflip.com/318nli.gif" title="made at imgflip.com"/></a> <file_sep>package com.example.talha.tictactoedemo import android.graphics.Color import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.Button import android.widget.ImageButton import android.widget.Toast import kotlinx.android.synthetic.main.activity_game.* import java.util.* import kotlin.collections.ArrayList class MainActivity:AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_game) } protected fun clickMethod(view:View){ val btnSelected:Button = view as Button var cellId=0 try { when(btnSelected.id){ R.id.btn1 -> { cellId=1 } R.id.btn2 -> { cellId=2 } R.id.btn3 -> cellId=3 R.id.btn4 -> cellId=4 R.id.btn5 -> cellId=5 R.id.btn6 -> cellId=6 R.id.btn7 -> cellId=7 R.id.btn8 -> cellId=8 R.id.btn9 -> cellId=9 } }catch (e:Exception){ } playGame(cellId,btnSelected) } var player1 = ArrayList<Int>() var player2 = ArrayList<Int>() var activePlayer = 1 fun playGame(cellId:Int,btnSelected:Button){ var winner = -1 if (activePlayer==1){ btnSelected.setText("X") btnSelected.setBackgroundColor(Color.GREEN) player1.add(cellId) activePlayer = 2 autoPlay() }else{ btnSelected.setText("O") btnSelected.setBackgroundColor(Color.YELLOW) player2.add(cellId) activePlayer = 1 } btnSelected.isEnabled = false if (player1.contains(1)&&player1.contains(2)&&player1.contains(3)){ winner = 1 }else if (player1.contains(4)&&player1.contains(5)&&player1.contains(6)){ winner = 1 }else if (player1.contains(7)&&player1.contains(8)&&player1.contains(9)){ winner = 1 }else if (player1.contains(1)&&player1.contains(4)&&player1.contains(7)){ winner = 1 }else if (player1.contains(2)&&player1.contains(5)&&player1.contains(8)){ winner = 1 }else if (player1.contains(3)&&player1.contains(6)&&player1.contains(9)){ winner = 1 }else if (player1.contains(1)&&player1.contains(5)&&player1.contains(9)){ winner = 1 } if (player2.contains(1)&&player2.contains(2)&&player2.contains(3)){ winner = 2 }else if (player2.contains(4)&&player2.contains(5)&&player2.contains(6)){ winner = 2 }else if (player2.contains(7)&&player2.contains(8)&&player2.contains(9)){ winner = 2 }else if (player2.contains(1)&&player2.contains(4)&&player2.contains(7)){ winner = 2 }else if (player2.contains(2)&&player2.contains(5)&&player2.contains(8)){ winner = 2 }else if (player2.contains(3)&&player2.contains(6)&&player2.contains(9)){ winner = 2 }else if (player2.contains(1)&&player2.contains(5)&&player2.contains(9)){ winner = 2 } if (winner!=-1){ if (winner == 1){ Toast.makeText(this,"Player1 wins",Toast.LENGTH_SHORT).show() }else{ Toast.makeText(this,"Player2 wins",Toast.LENGTH_SHORT).show() } } } fun autoPlay(){ var emptyCell = ArrayList<Int>() for (cellId in 1..9){ if (!(player1.contains(cellId)|| player2.contains(cellId))){ emptyCell.add(cellId) } } var random = Random() var randomIndex = random.nextInt(emptyCell.size-0)+0 val cellId = emptyCell.get(randomIndex) var btnSelect:Button? when(cellId){ 1-> btnSelect = btn1 2-> btnSelect = btn2 3-> btnSelect = btn3 4-> btnSelect = btn4 5-> btnSelect = btn5 6-> btnSelect = btn6 7-> btnSelect = btn7 8-> btnSelect = btn8 9-> btnSelect = btn9 else ->{ btnSelect = btn1 } } playGame(cellId,btnSelect) } }
351deb6aa21cc7ce2460f1587053292f5b3d3b4a
[ "Markdown", "Kotlin" ]
2
Markdown
talharizvi/TicTacToeDemo
e20dd3549a8f4aa553cc078f83d46a5d5fa89f3e
b0347c97351bf105a5d554bde7aea5972c3d449d