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
<file_sep>import json import pandas as pd countries_dict = {} # countries_list = [] # with open('static/world.json', 'r') as worldfile: # data = json.load(worldfile) # countries = data["objects"]["subunits"]["geometries"] # print(countries) # for country in countries: # countries_dict[country["properties"]["name"]] = country["id"] # countries_list.append(country["properties"]["name"]) # # print(countries_dict) # countries_list.sort() # print(countries_list) df_fips = pd.read_csv("csse_covid_19_data/UID_ISO_FIPS_LookUp_Table.csv") print(df_fips.head()) covid_countries_dict = {} for index, row in df_fips.iterrows(): covid_countries_dict[row['Country_Region']] = row['iso3'] print(covid_countries_dict)<file_sep>function lineplot(data) { var margin = {top: 20, right: 20, bottom: 30, left: 70}, width = 700 - margin.left - margin.right, height = 300 - margin.top - margin.bottom; // parse the date / time var parseTime = d3.time.format("%m/%d/%y"); // set the ranges var x = d3.time.scale().range([0, width]); var y = d3.scale.linear().range([height, 0]); // define the 1st line var valueline = d3.svg.line() .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.deaths); }); // define the 2nd line var valueline2 = d3.svg.line() .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.confirmed); }); var valueline3 = d3.svg.line() .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.recovered); }); // append the svg obgect to the body of the page // appends a 'group' element to 'svg' // moves the 'group' element to the top left margin var svg = d3.select("#line_plot").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // Get the data // d3.csv("https://raw.githubusercontent.com/AparnaDutt/AparnaDutt/master/myfile.csv", function(error, data) { // console.log(data) // if (error) throw error; console.log(data) // format the data data.forEach(function(d) { d.date = parseTime.parse(d.date); d.deaths = +d.deaths; d.confirmed = +d.confirmed; }); // Scale the range of the data x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([0, d3.max(data, function(d) { return Math.max(d.deaths, Math.max(d.confirmed,d.recovered)); })]); // Add the valueline path. deaths line svg.append("path") .data([data]) .attr("class", "line") .attr("d", valueline); // Add the valueline2 path. confirmed line svg.append("path") .data([data]) .attr("class", "line") .style("stroke", "red") .attr("d", valueline2); // Add the valueline3 path. recovered line svg.append("path") .data([data]) .attr("class", "line") .style("stroke", "green") .attr("d", valueline3); // Add the X Axis svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.svg.axis().scale(x)) .selectAll("text") .attr("y", 0) .attr("x", 9) .attr("dy", ".35em") .attr("transform", "rotate(90)") .style("text-anchor", "start");; // Add the Y Axis svg.append("g") .call(d3.svg.axis().scale(y).orient("left")); // }); }<file_sep># Import required packages import pandas as pd from sklearn import decomposition from sklearn import manifold from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from sklearn.metrics import pairwise_distances import json from flask import Flask, render_template, request import numpy as np import random import matplotlib.pyplot as plt df_confirmed = pd.read_csv('csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv') df_deaths = pd.read_csv('csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv') df_recovered = pd.read_csv('csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv') columns_to_be_removed = ['Province/State', 'Lat', 'Long'] df_confirmed = df_confirmed.drop(columns_to_be_removed, axis= 1) df_deaths = df_deaths.drop(columns_to_be_removed, axis= 1) df_recovered = df_recovered.drop(columns_to_be_removed, axis= 1) df_confirmed = df_confirmed.groupby(['Country/Region']).sum() df_deaths = df_deaths.groupby(['Country/Region']).sum() df_recovered = df_recovered.groupby(['Country/Region']).sum() df_confirmed = df_confirmed.T df_deaths = df_deaths.T df_recovered = df_recovered.T df_confirmed['Total'] = df_confirmed.iloc[:, 1:].sum(axis=1) df_deaths['Total'] = df_deaths.iloc[:, 1:].sum(axis=1) df_recovered['Total'] = df_recovered.iloc[:, 1:].sum(axis=1) df_daily = pd.read_csv('csse_covid_19_data/csse_covid_19_daily_reports/05-17-2020.csv') columns_to_be_removed = ["FIPS", "Admin2", "Province_State", "Last_Update", "Lat", "Long_", "Combined_Key"] df_daily = df_daily.drop(columns_to_be_removed, axis= 1) df_daily = df_daily.groupby(['Country_Region']).sum() df_complete_sum = df_daily.sum(axis = 0) def getDateWiseDataForLinePlot(columnName): dates = df_confirmed.index confirmed = df_confirmed[columnName] deaths = df_deaths[columnName] recovered = df_recovered[columnName] data = [] for i in range(len(dates)): data.append({"date": dates[i], "confirmed": confirmed[i], "deaths": deaths[i], "recovered": recovered[i]}) return data def get_pie_chart_data(country): confirmed = df_confirmed[country].iloc[-1] deaths = df_deaths[country].iloc[-1] recovered = df_recovered[country].iloc[-1] active = confirmed - (deaths + recovered) #{"Confirmed":4713620,"Deaths":315185,"Recovered":1733963,"Active":2661908} return {"Confirmed": confirmed, "Deaths": deaths, "Recovered": recovered, "Active": active} def parallel_coordinateData(): #taking top 20 countries for parallel coordinates df_top_20 = df_daily df_top_20.sort_values(by=['Confirmed'], inplace=True, ascending=False) cols = ["Confirmed", "Active", "Recovered", "Deaths"] df_top_20 = df_top_20[cols] df_top_20 = df_top_20.head(20) df_top_20 = df_top_20.drop("US") print(df_top_20) top_20_countries_list = [] for index, row in df_top_20.iterrows(): country_json = {} country_json["Country"] = index country_json["Confirmed"] = row["Confirmed"] country_json["Active"] = row["Active"] country_json["Recovered"] = row["Recovered"] country_json["Deaths"] = row["Deaths"] top_20_countries_list.append(country_json) # print(top_20_countries_list) return top_20_countries_list def getDataForMap(type): #for map df_fips = pd.read_csv("csse_covid_19_data/UID_ISO_FIPS_LookUp_Table.csv") covid_countries_dict = {} for index, row in df_fips.iterrows(): covid_countries_dict[row['Country_Region']] = row['iso3'] countries_list = covid_countries_dict.keys() cases_list = [] for index, row in df_daily.iterrows(): cases_list.append({"key": str(covid_countries_dict[index]), "doc_count": row[type]}) return cases_list def bar_chart_data(): df_age_data = pd.read_csv("csse_covid_19_data/age_deaths_data.csv") data = [] for index, row in df_age_data.iterrows(): data.append({"Age": row["Age"], "Number_of_Deaths": row["Number of Deaths"]}) return data line_plot_data = getDateWiseDataForLinePlot("Total") pie_chart_data = get_pie_chart_data("Total") map_data = getDataForMap("Confirmed") parallelcoordinates_data = parallel_coordinateData() barchart_data = bar_chart_data() columns_in_map = ["Confirmed", "Deaths", "Active"] world_json_data = json.load(open("static/world.json")) data = { "took": 492, "timed_out": "false", "_shards": { "total": 5, "successful": 3, "failed": 0 }, "hits": { "total": 30111166, "max_score": 0, "hits": [] }, "aggregations": { "world_map": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0 } } } data["aggregations"]["world_map"]["buckets"] = map_data app = Flask(__name__) # By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods. @app.route("/", methods=['POST', 'GET']) def index(): return render_template("index.html", mockdata = data, worldJSON = world_json_data, parallelcoordinates = parallelcoordinates_data, piechartdata = pie_chart_data, lineplotdata = line_plot_data, barchartdata = barchart_data, columns = columns_in_map) @app.route("/mapclick", methods=['POST', 'GET']) def onclickofmap(): global parallelcoordinates_data global barchart_data global data print(request.args.get('countryname')) clicked_country = request.args.get('countryname') line_plot_data = getDateWiseDataForLinePlot(clicked_country) pie_chart_data = get_pie_chart_data(clicked_country) return render_template("body-html.html", mockdata = data, worldJSON = json.load(open("static/world.json")), parallelcoordinates = parallelcoordinates_data, piechartdata = pie_chart_data, lineplotdata = line_plot_data, barchartdata = barchart_data, columns = columns_in_map) @app.route("/updatemap", methods=['POST', 'GET']) def updateMap(): global parallelcoordinates_data global pie_chart_data global line_plot_data global barchart_data global data columns_in_map = ["Confirmed", "Deaths", "Active"] print(request.args.get('selected_column')) selected_column = request.args.get('selected_column') map_data = getDataForMap(selected_column) data["aggregations"]["world_map"]["buckets"] = map_data columns_in_map.remove(selected_column) columns_in_map.insert(0, selected_column) return render_template("body-html.html", mockdata = data, worldJSON = json.load(open("static/world.json")), parallelcoordinates = parallelcoordinates_data, piechartdata = pie_chart_data, lineplotdata = line_plot_data, barchartdata = barchart_data, columns = columns_in_map) if __name__ == "__main__": app.run(debug=True)<file_sep>import pandas as pd df_confirmed = pd.read_csv('csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv') df_deaths = pd.read_csv('csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv') df_recovered = pd.read_csv('csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv') columns_to_be_removed = ['Province/State', 'Lat', 'Long'] df_confirmed = df_confirmed.drop(columns_to_be_removed, axis= 1) df_deaths = df_deaths.drop(columns_to_be_removed, axis= 1) df_recovered = df_recovered.drop(columns_to_be_removed, axis= 1) df_confirmed = df_confirmed.groupby(['Country/Region']).sum() df_deaths = df_deaths.groupby(['Country/Region']).sum() df_recovered = df_recovered.groupby(['Country/Region']).sum() df_confirmed = df_confirmed.T df_deaths = df_deaths.T df_recovered = df_recovered.T # print(df_confirmed["US"]) # print(df_deaths["US"]) # print(df_recovered["US"]) df_daily = pd.read_csv('csse_covid_19_data/csse_covid_19_daily_reports/05-17-2020.csv') columns_to_be_removed = ["FIPS", "Admin2", "Province_State", "Last_Update", "Lat", "Long_", "Combined_Key"] df_daily = df_daily.drop(columns_to_be_removed, axis= 1) df_daily = df_daily.groupby(['Country_Region']).sum() # print(df_daily) df_daily.sort_values(by=['Confirmed'], inplace=True, ascending=False) # print(df_daily) cols = ["Confirmed", "Active", "Recovered", "Deaths"] df_daily = df_daily[cols] df_top_20 = df_daily.head(20) df_top_20.to_csv("static/daily20.csv") df_daily = df_daily.T # df_daily.to_csv("static/daily.csv") # print(df_daily["US"])
112389ae522d9a333b4dbdad94d1e84d7104978c
[ "JavaScript", "Python" ]
4
Python
suryasoma/Covid19Dashboard
0c565e6e9b44a6151460f7f9fccd977837944d50
5ae124a22e236775772c0e94c5817a0f9d0ff990
refs/heads/master
<file_sep># Product Inventory - We have users and products - Products have name and brand - Products also have variants of color or size - A user has products and variants of that product but not necessarily all of them - A user's inventory contains the users products and the variants they have of that product ## Seeding the database ``` php artisan db:seed ``` Will create 5 users with 10 products each and 2 variants of that product. ## Running the tests After seeding the database you can run ```$xslt phpunit ``` Or if that doesn't work: ```$xslt php vendor\phpunit\phpunit\phpunit ``` For nice colored output you can add some parameters ```$xslt php vendor\phpunit\phpunit\phpunit --colors=always --testdox ``` ## Endpoints **Products** Retrieve product by id ``` GET /api/products/{id} ``` Add product ``` POST /api/products/create ``` ```json { "name": "Product Name", "brand": "Product Brand", "variants": [ { "type": "color", "value": "blue" } ] } ``` Delete Product ``` DELETE /api/products/{id}/delete ``` **User** Get User's Inventory ``` GET /api/user/{id}/products ```<file_sep><?php use Illuminate\Database\Seeder; class ProductsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Create the products for ($i = 0; $i < 20; $i++) { $product = factory('App\Product')->create([ 'name' => 'Product '.($i+1) ]); } } } <file_sep><?php use Illuminate\Database\Seeder; class VariantsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Add Variants to the products foreach(\App\Product::all() as $product) { $product->variants()->saveMany(factory('App\Variant', 5)->create()); } } } <file_sep><?php use Illuminate\Support\Str; use Faker\Generator as Faker; $factory->define(App\Variant::class, function (Faker $faker) { $variantTypes = array("color","size"); $size = array("small","medium","large","x-large","xx-large"); $type = $variantTypes[array_rand($variantTypes)]; if($type == "color") { $value = $faker->colorName; } else { $value = $size[array_rand($size)]; } return [ 'type' => $type, 'value' => $value, 'product_id' => 1 ]; }); <file_sep><?php namespace Tests\Unit; use App\Product; use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; class ProductTest extends TestCase { use WithFaker; /** * A basic test example. * * @return void */ public function testCreateProduct() { $productData = [ 'name' => $this->faker->word, 'brand' => $this->faker->company ]; $this->postJson('api/products/create', $productData) ->assertStatus(200) ->assertJsonFragment([ 'name' => $productData['name'], 'brand' => $productData['brand'] ]) ->assertJsonStructure([ 'name', 'brand', 'updated_at', 'created_at', 'id', 'variants' ]); } public function testRetrieveProduct() { $product = Product::inRandomOrder()->first(); $this->getJson('api/products/'.$product->id) ->assertStatus(200) ->assertJsonFragment([ 'name' => $product->name, 'brand' => $product->brand ]) ->assertJsonStructure([ 'name', 'brand', 'updated_at', 'created_at', 'id', 'variants' ]); } public function testDeleteProduct() { $product = factory('App\Product')->create(); $this->deleteJson('api/products/'.$product->id.'/delete') ->assertStatus(200) ->assertJsonFragment([ 'name' => $product->name, 'brand' => $product->brand ]) ->assertJsonStructure([ 'name', 'brand', 'updated_at', 'created_at', 'id' ]); $this->assertDatabaseMissing('products', ['id' => $product->id]); $this->assertDatabaseMissing('variants', ['product_id' => $product->id]); } } <file_sep><?php use Illuminate\Database\Seeder; class UserProductsSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Attach products to users \App\User::all()->each(function (\App\User $user) { $products = \App\Product::inRandomOrder()->limit(10)->get()->each(function(\App\Product $product) use($user) { $user->products()->attach($product->id); $variants = $product->variants()->inRandomOrder()->limit(2)->get()->each(function (\App\Variant $variant) use ($user) { $user->variants()->attach($variant->id); }); }); }); } } <file_sep><?php namespace Tests\Unit; use App\User; use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; class UserTest extends TestCase { /** * A basic test example. * * @return void */ public function testGetProducts() { $user = User::whereHas('products')->inRandomOrder()->first(); $this->getJson("/api/user/$user->id/products") ->assertStatus(200) ->assertJsonStructure([ '*' => [ 'id', 'name', 'brand', 'created_at', 'updated_at', 'variants' => [ '*' => [ 'id', 'type', 'value', 'product_id', 'created_at', 'updated_at' ] ] ] ]); } } <file_sep><?php namespace App\Http\Controllers; use App\Product; use Illuminate\Http\Request; class ProductController extends Controller { public function view($id) { return Product::with('variants')->where('id',$id)->first(); } public function create(Request $request) { $product = Product::create($request->all()); if(!empty($request->variants)) $product->variants()->createMany($request->variants); return Product::with('variants')->where('id', $product->id)->first(); } public function delete(Product $product) { $product->variants()->delete(); $product->delete(); return $product; } }
bc04f0721ba073c83b97c1752de0317981d73177
[ "Markdown", "PHP" ]
8
Markdown
javif89/product-inventory
e2d223e990e852642124a801bcf9838c4614a3ec
12824cbb9e8839f6e795e637a4a884181f6a5e12
refs/heads/master
<file_sep>import React from 'react'; import './Landing.css'; import Flash from "./../../Assets/flash.png"; const Landing=()=>{ return( <div className="landing-container"> <div className="landing-left"> <h1 className="landing-header">can you type...</h1> <div className="typewriter-container"> <p>Fast?</p> <p>Correct?</p> <p>Quick</p> </div> </div> <div className="landing-right"> <img className="flash-image" src={Flash} alt="hero"/> </div> </div> ); } export default Landing;
44e526de23ce0f564f00cc16dbdb9f1237b536a4
[ "JavaScript" ]
1
JavaScript
Digvijaysingh0707/Flash-type
a041cbd38d17045fe575301cffb342d9e6011179
88e7cbe97e67f09cc50a7dd9e7fac2ed45faf806
refs/heads/master
<file_sep>import { Component } from '@angular/core'; import { HttpModule, RequestOptions, XHRBackend, Http, Response, Headers } from "@angular/http"; import { ReactiveFormsModule, FormsModule, FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import 'rxjs/add/operator/map' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; dbdata: any = null; private apiUrl = "http://localhost:7070/isha/all" constructor(private http: Http) { this.getData(); this.add(); } private getData() { return this.http.get(this.apiUrl).map((res: Response) => res.json()) } private add() { this.getData().subscribe(data => { this.dbdata=data; console.log(data); console.log(this.dbdata); }) } }
526084369ef5b4ad791b1b36351b6e64b5c4dfb0
[ "TypeScript" ]
1
TypeScript
isha2510/angular_example
68726c42bdb78a7357b138b88d34b0b5caf31ca1
300f59f147c768334d15219ff752497b133d1acd
refs/heads/master
<repo_name>RarceD/ESP_32_noob<file_sep>/Access_Point/main.c //This is just for testing the struct manipulation: #include <stdio.h> #include <stdint.h> #include "AP.h" //For compile: 'gcc main.c AP.c' int main() { light_open_info lamp; lamp.starts[1] = 22; printf("%i\n", lamp.starts[1]); modified_struct(&lamp, 24); printf("%i", lamp.starts[1]); return 0; } <file_sep>/2560/main/app_responses.h #include <PubSubClient.h> #include <ArduinoJson.h> #include "pinout.h" #define FUKING_SLOW_TIME_PG 400 extern Entity sys; extern uint8_t reset_unit[]; void pg_serial_date(int day, int month, int year); void pg_listen(); void pg_time_check(int *hour, int *minute, int *weekday); int calcrc(char ptr[], int length); void pg_serial_action_valve(bool state, uint8_t valve, uint8_t time_hours, uint8_t time_minutes); void action_prog_pg(uint8_t state, char program); void change_time_pg(uint8_t week, uint8_t hours, uint8_t minutes, uint8_t seconds); //, uint8_t *day, uint8_t *hours, uint8_t *minutes) void write_start_stop_pg(bool from, String time, uint8_t dir); void write_percentage_pg(uint16_t position, uint16_t percentage); uint8_t time_to_pg_format(uint8_t hours, uint8_t minutes); void change_week_pg(char *date, uint8_t lenght, uint8_t program); void pg_serial_fertirrigation(uint8_t valve_number, uint8_t wait_h, uint8_t wait_m, uint8_t water_h, uint8_t water_m); void pg_serial_activate_fertirrigation(bool active); void pg_serial_restart(); void web_to_pg_pump_associations(char pump_associations[]); void shift_pumps(int valve_int, int pump); void write_master_pump_association(char pump[], uint8_t len); void pg_irrig_day(uint8_t *watering_days, uint8_t number_watering_days); #define MAX_JSON_SIZE 512 bool send_stop_program; WiFiClient wifiClient; PubSubClient client(wifiClient); uint16_t pg_reag_to_web(uint16_t pg_time); //It return the time ok in minutes to the web void json_program_starts(uint8_t program); void reconnect(); void send_web(char *topic, unsigned int length, int id); void json_program_starts(uint8_t program); void json_program_valves(uint8_t program); void json_clear_starts(uint8_t program); void json_query(const char id[], char status[]); void json_program_action(bool open, char program); void json_valve_action(bool open, uint8_t valve, uint8_t hours, uint8_t minutes); void json_week_days(uint8_t program, uint8_t week_day); uint16_t pg_reag_to_web(uint16_t pg_time); void init_mqtt(); void callback(char *topic, byte *payload, unsigned int length); void reconnect() { int restart = 0; while (!client.connected()) { LOG("Attempting MQTT connection..."); // Create a random client ID String clientId = "Rarced-"; clientId += String(random(0xffff), HEX); // Attempt to connect if (client.connect(clientId.c_str(), MQTT_USER, MQTT_PASSWORD)) { LOGLN("connected"); String topic = String(sys.uuid_) + "/+/app"; client.subscribe(topic.c_str()); LOGLN(topic); digitalWrite(LED_WIFI, HIGH); } else { digitalWrite(LED_WIFI, LOW); LOG("failed, rc="); LOG(client.state()); LOGLN(" try again in 5 seconds"); if (restart > 10) esp_restart(); else restart++; delay(3000); } } } void send_web(char *topic, unsigned int length, int id) { String ack_topic = String(topic); String identifier = String(id); char json[40]; DynamicJsonBuffer jsonBuffer(27); JsonObject &root = jsonBuffer.createObject(); root.set("id", id); root.set("success", "true"); root.printTo(json); client.publish((String(sys.uuid_) + ack_topic).c_str(), (const uint8_t *)json, strlen(json), false); } void json_program_starts(uint8_t program) { char program_letters[] = {'A', 'B', 'C', 'D', 'E', 'F'}; //Generate the structure of the program via json DynamicJsonBuffer jsonBuffer(128); JsonObject &root = jsonBuffer.createObject(); uint8_t index_program = program; //I generate the json only for the program request root["prog"] = String(program_letters[index_program]); JsonArray &starts = root.createNestedArray("starts"); //Generate all the starts for (uint8_t index_time = 0; index_time < 6; index_time++) if (prog[index_program].start[index_time][0] != 255) { String minutes, hours; if (prog[index_program].start[index_time][0] < 10) hours = '0' + String(prog[index_program].start[index_time][0]); else hours = String(prog[index_program].start[index_time][0]); if (prog[index_program].start[index_time][1] < 10) minutes = '0' + String(prog[index_program].start[index_time][1]); else minutes = String(prog[index_program].start[index_time][1]); starts.add(hours + ":" + minutes); } int water = (int)(prog[index_program].waterPercent); if (water < 0) water = 100; root["water"] = water; char json[150]; root.printTo(json); client.publish((String(sys.uuid_) + "/program").c_str(), (const uint8_t *)json, strlen(json), false); } void json_program_valves(uint8_t program) { DynamicJsonBuffer jsonBuffer(200); JsonObject &root = jsonBuffer.createObject(); char program_letters[] = {'A', 'B', 'C', 'D', 'E', 'F'}; //Generate the structure of the program via json root["prog"] = String(program_letters[program]); JsonArray &valves = root.createNestedArray("valves"); for (uint8_t index_valves = 0; index_valves < 14; index_valves++) { LOGLN(prog[program].irrigTime[index_valves]); if (prog[program].irrigTime[index_valves] <= 200) { JsonObject &irrig = root.createNestedObject(""); LOGLN(prog[program].irrigTime[index_valves]); irrig["v"] = index_valves + 1; int time_compleat = pg_reag_to_web((uint16_t)prog[program].irrigTime[index_valves]); uint16_t time_in_format_h; uint16_t time_in_format_m; if (time_compleat >= 60) { time_in_format_h = time_compleat / 60; time_in_format_m = time_compleat % 60; String h = String(time_in_format_h); String m = String(time_in_format_m); if (h.length() == 1) h = '0' + h; if (m.length() == 1) m = '0' + m; irrig["time"] = h + ":" + m; } else { String x = String(time_compleat); if (x.length() == 1) x = '0' + x; irrig["time"] = "00:" + x; } valves.add(irrig); } } char json[300]; root.printTo(json); client.publish((String(sys.uuid_) + "/program").c_str(), (const uint8_t *)json, strlen(json), false); } void json_clear_starts(uint8_t program) { //I clear the starts info char program_letters[] = {'A', 'B', 'C', 'D', 'E', 'F'}; DynamicJsonBuffer jsonBuffer(43); JsonObject &root = jsonBuffer.createObject(); root["prog"] = String(program_letters[program]); JsonArray &starts = root.createNestedArray("starts"); char json[43]; root.printTo(json); client.publish((String(sys.uuid_) + "/program").c_str(), (const uint8_t *)json, strlen(json), false); } void json_query(const char id[], char status[]) { DynamicJsonBuffer jsonBuffer(344); JsonObject &root = jsonBuffer.createObject(); root["id"] = String(id); root["status"] = String(status); root["connection"] = getStrength(5); int hour = 0; int weekday = 0; int minute = 0; pg_time_check(&hour, &minute, &weekday); String hour_query, min_query; if (hour < 10) hour_query = "0" + String(hour, DEC); else hour_query = String(hour, DEC); if (minute < 10) min_query = "0" + String(minute, DEC); else min_query = String(minute, DEC); root["date"] = "01/01/2021 " + hour_query + ":" + min_query; //I send the time to the web: //I check if there is any program active and I send to the web: JsonArray &active_json = root.createNestedArray("prog_active"); char program_letters[] = {'A', 'B', 'C', 'D', 'E', 'F'}; for (uint8_t prog = 0; prog < 6; prog++) if (active.programs[prog]) active_json.add(String(program_letters[prog])); //I generate the main json frame char json[350]; root.printTo(json); client.publish((String(sys.uuid_) + "/query").c_str(), (const uint8_t *)json, strlen(json), false); // root.prettyPrintTo(Serial); } void json_program_action(bool open, char program) { //Publish in /manprog topic and send to the app whats happening DynamicJsonBuffer jsonBuffer(100); JsonObject &root = jsonBuffer.createObject(); root["prog"] = String(program); if (open) root["action"] = 1; else root["action"] = 0; char json[200]; root.printTo(json); // root.prettyPrintTo(Serial); client.publish((String(sys.uuid_) + "/manprog").c_str(), (const uint8_t *)json, strlen(json), false); } void json_valve_action(bool open, uint8_t valve, uint8_t hours, uint8_t minutes) { DynamicJsonBuffer jsonBuffer(100); JsonObject &root = jsonBuffer.createObject(); JsonObject &oasis = root.createNestedObject("valves"); JsonObject &info = oasis.createNestedObject(""); info["v"] = valve; if (open) { info["action"] = 1; String str_hours = String(hours); if (str_hours.length() == 1) str_hours = '0' + str_hours; String str_minutes = String(minutes); if (str_minutes.length() == 1) str_minutes = '0' + str_minutes; info["time"] = str_hours + ":" + str_minutes; } else info["action"] = 0; char json[200]; root.printTo(json); // root.prettyPrintTo(Serial); client.publish((String(sys.uuid_) + "/manvalve").c_str(), (const uint8_t *)json, strlen(json), false); } void json_week_days(uint8_t program, uint8_t week_day) { char program_letters[] = {'A', 'B', 'C', 'D', 'E', 'F'}; String str_week_day; uint8_t compare_operation = 1; for (int i = 1; i <= 7; i++) { if (week_day & compare_operation) { str_week_day += String(i); str_week_day += ","; } compare_operation *= 2; } str_week_day.remove(str_week_day.length() - 1, 1); DynamicJsonBuffer jsonBuffer(200); JsonObject &root = jsonBuffer.createObject(); root["prog"] = String(program_letters[program]); root["week_day"] = "[" + str_week_day + "]"; char json[200]; root.printTo(json); client.publish((String(sys.uuid_) + "/program").c_str(), (const uint8_t *)json, strlen(json), false); // root.prettyPrintTo(Serial); } uint16_t pg_reag_to_web(uint16_t pg_time) //It return the time ok in minutes to the web { uint8_t combinations[12][2] = {{72, 1}, {84, 2}, {96, 3}, {108, 4}, {120, 5}, {132, 6}, {144, 7}, {156, 8}, {168, 9}, {180, 10}, {192, 11}, {204, 12}}; if (pg_time < 60) return pg_time; //First obtein the hours uint8_t index = 0; while (index++ < 12) if (pg_time < combinations[index][0]) break; //Obtein the hours and minutes and print them uint16_t hours = (uint16_t)combinations[index][1]; uint16_t min = (pg_time - 60 - 12 * (hours - 1)) * 5; printf("La hora real es: %i:%i \n", hours, min); return (hours * 60 + min); } void json_send_programs(int i, int id) { DynamicJsonBuffer jsonBuffer(6300); JsonObject &root = jsonBuffer.createObject(); char program_letters[] = {'A', 'B', 'C', 'D', 'E', 'F'}; if (id > 10) { root["id"] = id; } root["prog"] = String(program_letters[i]); root["water"] = prog[i].waterPercent; root["interval"] = 1; root["interval_init"] = 0; JsonArray &week_day = root.createNestedArray("week_day"); String str_week_day; uint8_t compare_operation = 1; uint8_t week_day_number = prog[i].wateringDay; for (int j = 1; j <= 7; j++) { if (week_day_number & compare_operation) week_day.add(j); compare_operation *= 2; } JsonArray &starts = root.createNestedArray("starts"); for (int j = 0; j < 6; j++) { String start_min, start_hours; if (prog[i].start[j][0] == 0 && prog[i].start[j][0] == 0) starts.add(String("")); // LOGLN("nop start day"); else { if (prog[i].start[j][0] < 9) start_min = "0" + String(prog[i].start[j][0]); else start_min = String(prog[i].start[j][0]); if (prog[i].start[j][1] < 9) start_hours = "0" + String(prog[i].start[j][1]); else start_hours = String(prog[i].start[j][1]); starts.add(start_min + ":" + start_hours); } } root["from"] = String("01/01"); root["to"] = String("31/12"); JsonArray &valves = root.createNestedArray("valves"); for (int j = 0; j < 128; j++) { JsonObject &irrig = root.createNestedObject(""); irrig["v"] = j + 1; int hours = prog[i].irrigTime[j] / 60; int minutes = prog[i].irrigTime[j] - hours * 60; //TODO: // LOGLN(prog[i].irrigTime[j]); // LOGLN(hours); // LOGLN(minutes); String str_hours, str_minutes; if (hours > 9) str_hours = String(hours); else str_hours = "0" + String(hours); if (minutes > 9) str_minutes = String(minutes); else str_minutes = "0" + String(minutes); if (hours == 0 && minutes == 0) irrig["time"] = ""; else irrig["time"] = str_hours + ":" + str_minutes; valves.add(irrig); } char json[3700]; // root.prettyPrintTo(Serial); // char json[200]; root.printTo(json); client.publish((String(sys.uuid_) + "/program").c_str(), (const uint8_t *)json, strlen(json), false); // delay(FUKING_SLOW_TIME_PG); } void callback(char *topic, byte *payload, unsigned int length) { //Create the json buffer: DynamicJsonBuffer jsonBuffer(8084); //Parse the huge topic JsonObject &parsed = jsonBuffer.parseObject(payload); LOGLN(esp_get_free_heap_size()); LOGLN(esp_get_minimum_free_heap_size()); int identifier = parsed["id"].as<int>(); // This is for the sendding function app // Obtein the topic String sTopic = String(topic); // Then I identify the topic related with if (identifier >= 1) { LOG("Inside parser:"); LOGLN(sTopic); if (sTopic.indexOf("manvalve") != -1) //done { // delay(1000); //I firts of all parse the message JsonArray &valves = parsed["valves"]; //I obtein the values of the parser info: String valve_time; int valve_number[128], valve_action[128], valve_min[128], valve_hours[128]; //Start the game: for (int index_oasis = 0; index_oasis < valves.size(); index_oasis++) { valve_number[index_oasis] = valves[index_oasis]["v"].as<int>(); valve_action[index_oasis] = valves[index_oasis]["action"].as<int>(); LOG("->"); LOG(valve_number[index_oasis]); LOG(":"); LOGLN(valve_action[index_oasis]); if (valve_action[index_oasis] == 1) // If I have to open then I have to obtein the time { valve_time = valves[index_oasis]["time"].as<String>(); // I parse the valve time valve_hours[index_oasis] = (valve_time.charAt(0) - '0') * 10 + (valve_time.charAt(1) - '0'); valve_min[index_oasis] = (valve_time.charAt(3) - '0') * 10 + (valve_time.charAt(4) - '0'); /////////////////////////////////////////////////////////////////// LOG("El valor de válvula es la:"); LOG(valve_number[index_oasis]); LOG("durante "); LOG(valve_hours[index_oasis]); LOG(":"); LOGLN(valve_min[index_oasis]); active.valves[index_oasis] = true; pg_serial_action_valve(valve_action[index_oasis], valve_number[index_oasis], valve_hours[index_oasis], valve_min[index_oasis]); } else if (valve_action[index_oasis] == 0) { LOG("APAGAR LA: "); LOGLN(valve_number[index_oasis]); pg_serial_action_valve(valve_action[index_oasis], valve_number[index_oasis], valve_hours[index_oasis], valve_min[index_oasis]); active.valves[index_oasis] = false; } delay(FUKING_SLOW_TIME_PG); pg_listen(); } send_web("/manvalve", sizeof("/manvalve"), identifier); //I send via radio to the receiver } else if (sTopic.indexOf("manprog") != -1) //done { //I obtein the values of the parser info: uint8_t activate = parsed["action"]; // LOGLN(activate); String manual_program; manual_program = parsed["prog"].as<String>(); // I first send it to delay(500); action_prog_pg(activate, manual_program.charAt(0)); //I send the command tom PG char program_letters[] = {'A', 'B', 'C', 'D', 'E', 'F'}; for (uint8_t index_prog; index_prog < 6; index_prog++) if (program_letters[index_prog] == manual_program.charAt(0)) if (activate == 1) active.programs[index_prog] = true; else active.programs[index_prog] = false; send_web("/manprog", sizeof("/manprog"), identifier); // I send ack to the app } else if (sTopic.indexOf("oasis") != -1) //done { LOGLN("Publish in /oasis/app"); JsonArray &oasis = parsed["oasis"]; LOGLN("The value of the assignations are:"); uint8_t assigned_id[4]; uint8_t ide[15]; for (uint8_t oasis_num = 0; oasis_num < oasis.size(); oasis_num++) { ide[oasis_num] = oasis[oasis_num]["id"]; LOG("El oasis "); LOGLN(ide[oasis_num]); LOG("Tiene Asignadas las siguientes salidas: "); for (uint8_t d = 0; d < sizeof(assigned_id); d++) { assigned_id[d] = oasis[oasis_num]["assign"][d]; LOG(assigned_id[d]); LOG(", "); } LOGLN(""); // change_oasis_assigned(ide[oasis_num], assigned_id); } send_web("/oasis", sizeof("/oasis"), identifier); } else if (sTopic.indexOf("program") != -1) //done { //I parse the letter of the program String manual_program = parsed["prog"].as<String>(); //I determin the positions of the PG in which I have to write uint16_t position_starts = 416; // This is the position of the starts in PG EEPROM memmory uint16_t mem_pos = 1024; // This is the position of the starts in PG EEPROM memmory uint16_t position_percentage = 144; // This is the position of the irrig % in PG EEPROM memmory uint8_t position_week = 0xB0; //This is for the week day starts uint8_t position_from_to = 0xC0; //For changing the starting and stop irrig day, not year bool return_pg_program = true; switch (manual_program.charAt(0)) { case 'B': position_starts = 428; mem_pos = 1152; position_percentage = 146; position_week = 0xB1; position_from_to = 0xC4; break; case 'C': position_starts = 440; mem_pos = 1280; position_percentage = 148; position_week = 0xB2; position_from_to = 0xC8; break; case 'D': position_starts = 452; mem_pos = 1408; position_percentage = 150; position_week = 0xB3; position_from_to = 0xCC; break; case 'E': position_starts = 0x1D0; mem_pos = 1536; position_percentage = 152; position_week = 0xB4; position_from_to = 0xD0; break; case 'F': position_starts = 476; mem_pos = 1664; position_percentage = 154; position_week = 0xB5; position_from_to = 0xD4; break; default: break; } //I parse the array of starts and valves, if there's any JsonArray &starts = parsed["starts"]; //done if (starts.success()) { return_pg_program = false; //It sometimes fail and disconnect to the broker, that why I call this //First parse all the existed starts: String str_time; //For writting in the memmory uint16_t time_prog[6][2]; uint16_t start_time_hours = 0, start_time_min = 0; String mem_starts_h; for (uint8_t index_starts = 0; index_starts < starts.size(); index_starts++) { str_time = starts[index_starts].as<String>(); LOGLN(str_time); time_prog[index_starts][0] = (str_time.charAt(0) - '0') * 10 + (str_time.charAt(1) - '0'); //save hours time_prog[index_starts][1] = (str_time.charAt(3) - '0') * 10 + (str_time.charAt(4) - '0'); //save minutes LOG("El valor del arranque "); LOG(index_starts); LOG(" es de: "); LOG(time_prog[index_starts][0]); LOG(":"); LOGLN(time_prog[index_starts][1]); delay(FUKING_SLOW_TIME_PG); for (uint8_t times_2 = 0; times_2 < 2; times_2++) { //First format the info y PG language start_time_hours = time_to_pg_format(0, time_prog[index_starts][times_2]); String mem_time_start_hours = String(start_time_hours, HEX); mem_time_start_hours.toUpperCase(); if (mem_time_start_hours.length() != 2) mem_time_start_hours = '0' + mem_time_start_hours; mem_starts_h = String(position_starts + times_2, HEX); mem_starts_h.toUpperCase(); //Not that is compleatly in HEX I copy in the data buffer ////cmd_write_data[13] = mem_starts_h.charAt(0); ////cmd_write_data[14] = mem_starts_h.charAt(1); ////cmd_write_data[15] = mem_starts_h.charAt(2); ////cmd_write_data[17] = mem_time_start_hours.charAt(0); ////cmd_write_data[18] = mem_time_start_hours.charAt(1); //calcrc((char *)////cmd_write_data, sizeof(//cmd_write_data) - 2); //Serial2.write(//cmd_write_data, sizeof(//cmd_write_data)); for (int i = 0; i < sizeof(//cmd_write_data); i++) LOGW(//cmd_write_data[i]); delay(FUKING_SLOW_TIME_PG); pg_listen(); client.loop(); } position_starts += 2; } //Clear all the starts that are not defined and could be saved in pg memmory: uint8_t start_to_clear = 6 - starts.size(); uint16_t position_end = position_starts + 6; // try to write in 0x1AA and then in 0x1A8 while (start_to_clear > 0) { for (uint8_t times = 0; times <= 1; times++) { //First clear from the bottom to the top of the memmory: delay(800); mem_starts_h = String(position_end + times, HEX); mem_starts_h.toUpperCase(); //cmd_write_data[13] = mem_starts_h.charAt(0); //cmd_write_data[14] = mem_starts_h.charAt(1); //cmd_write_data[15] = mem_starts_h.charAt(2); //cmd_write_data[17] = 'F'; //cmd_write_data[18] = 'F'; //calcrc((char *)//cmd_write_data, sizeof(//cmd_write_data) - 2); //Serial2.write(//cmd_write_data, sizeof(//cmd_write_data)); for (int i = 0; i < sizeof(//cmd_write_data); i++) LOGW(//cmd_write_data[i]); LOGLN(" "); delay(FUKING_SLOW_TIME_PG); pg_listen(); client.loop(); } start_to_clear--; position_end -= 2; } } //WEEK STARTS: JsonArray &week_day = parsed["week_day"]; //done if (week_day.success()) { return_pg_program = false; String day = ""; for (uint8_t items = 0; items < week_day.size(); items++) day += week_day[items].as<String>(); char days[day.length() + 1]; day.toCharArray(days, sizeof(days)); change_week_pg(days, sizeof(days), position_week); delay(FUKING_SLOW_TIME_PG); } JsonArray &valves = parsed["valves"]; //almost done if (valves.success()) { return_pg_program = false; if (valves.size() == 0) { LOGLN("Clear all the valves"); for (uint8_t index_valves = 0; index_valves < 30; index_valves++) { String mem_starts = String(mem_pos, HEX); mem_starts.toUpperCase(); //cmd_write_data[13] = mem_starts.charAt(0); //cmd_write_data[14] = mem_starts.charAt(1); //cmd_write_data[15] = mem_starts.charAt(2); //cmd_write_data[17] = '0'; //cmd_write_data[18] = '0'; //calcrc((char *)//cmd_write_data, sizeof(//cmd_write_data) - 2); //Serial2.write(//cmd_write_data, sizeof(//cmd_write_data)); int i; for (i = 0; i < sizeof(//cmd_write_data); i++) LOGW(//cmd_write_data[i]); mem_pos++; delay(FUKING_SLOW_TIME_PG); pg_listen(); client.loop(); } } else { // LOG("Exists Valves"); String irrig_time; //The string for the 00:00 time format uint16_t number_valves; uint16_t val = 0; uint16_t clear_num = 1; // send_web("/program", sizeof("/program"), identifier); for (uint16_t index_valves = 0; index_valves < 30; index_valves++) { uint16_t time_valves[2]; //This is a huge and ridiculous irrig_time = valves[index_valves]["time"].as<String>(); LOG(number_valves + 1); number_valves = valves[index_valves]["v"].as<uint16_t>() - 1; time_valves[0] = (irrig_time.charAt(0) - '0') * 10 + (irrig_time.charAt(1) - '0'); //save hours time_valves[1] = (irrig_time.charAt(3) - '0') * 10 + (irrig_time.charAt(4) - '0'); //save minutes LOG("Los tiempos de la válvula "); LOG(number_valves + 1); LOG(" son: "); LOG(time_valves[0]); LOG(":"); LOGLN(time_valves[1]); //Obtein the number of the valves and write the EEPROM memmory in correct positions val = time_to_pg_format(time_valves[0], time_valves[1]); String mem_time = String(val, HEX); if (mem_time.length() == 1) mem_time = '0' + mem_time; mem_time.toUpperCase(); LOGLN(mem_time); String mem_starts = String(mem_pos + number_valves, HEX); mem_starts.toUpperCase(); //cmd_write_data[13] = mem_starts.charAt(0); //cmd_write_data[14] = mem_starts.charAt(1); //cmd_write_data[15] = mem_starts.charAt(2); //cmd_write_data[17] = mem_time.charAt(0); //cmd_write_data[18] = mem_time.charAt(1); //calcrc((char *)//cmd_write_data, sizeof(//cmd_write_data) - 2); //Serial2.write(//cmd_write_data, sizeof(//cmd_write_data)); for (int i = 0; i < sizeof(//cmd_write_data); i++) LOGW(//cmd_write_data[i]); delay(FUKING_SLOW_TIME_PG); LOGLN(" "); clear_num++; pg_listen(); client.loop(); } } } //Write in the PG memmory the irrig % uint16_t irrig_percent = parsed["water"].as<uint16_t>(); if (parsed["water"].success()) { return_pg_program = false; LOGLN("Water:"); LOGLN(position_percentage); LOGLN(irrig_percent); write_percentage_pg(position_percentage, irrig_percent); } if (parsed["from"].success()) { return_pg_program = false; String time_from = parsed["from"].as<String>(); write_start_stop_pg(true, time_from, position_from_to); String time_to = parsed["to"].as<String>(); write_start_stop_pg(false, time_to, position_from_to); // send_web("/program", sizeof("/program"), identifier); } if (return_pg_program) { if (manual_program.charAt(0) == 'A') json_send_programs(0, identifier); else if (manual_program.charAt(0) == 'B') json_send_programs(1, identifier); else if (manual_program.charAt(0) == 'C') json_send_programs(2, identifier); else if (manual_program.charAt(0) == 'D') json_send_programs(3, identifier); else if (manual_program.charAt(0) == 'E') json_send_programs(4, identifier); } else send_web("/program", sizeof("/program"), identifier); } else if (sTopic.indexOf("query") != -1) //done { json_query(String(identifier).c_str(), "AUTO"); } else if (sTopic.indexOf("general") != -1) //receive the delay between valves and mv and valve { if (parsed["pump_delay"].success() || parsed["valve_delay"].success()) { int pump_delay = 0; int valve_delay = 0; pump_delay = parsed["pump_delay"].as<int>(); valve_delay = parsed["valve_delay"].as<int>(); if (pump_delay < 0) pump_delay = 0xFF + pump_delay + 1; //cmd_write_data[13] = '0'; //cmd_write_data[14] = '5'; //cmd_write_data[15] = '1'; String ret_valve = String(valve_delay, HEX); if (ret_valve.length() == 1) ret_valve = '0' + ret_valve; ret_valve.toUpperCase(); //cmd_write_data[17] = ret_valve.charAt(0); //cmd_write_data[18] = ret_valve.charAt(1); //calcrc((char *)//cmd_write_data, sizeof(//cmd_write_data) - 2); //Serial2.write(//cmd_write_data, sizeof(//cmd_write_data)); //real send to PG int i; for (i = 0; i < sizeof(//cmd_write_data); i++) LOGW(//cmd_write_data[i]); delay(800); //cmd_write_data[13] = '0'; //cmd_write_data[14] = '5'; //cmd_write_data[15] = '0'; String ret_mv = String(pump_delay, HEX); if (ret_mv.length() == 1) ret_mv = '0' + ret_mv; ret_mv.toUpperCase(); //cmd_write_data[17] = ret_mv.charAt(0); //cmd_write_data[18] = ret_mv.charAt(1); //calcrc((char *)//cmd_write_data, sizeof(//cmd_write_data) - 2); //Serial2.write(//cmd_write_data, sizeof(//cmd_write_data)); //real send to PG for (i = 0; i < sizeof(//cmd_write_data); i++) LOGW(//cmd_write_data[i]); } if (parsed["date"].success()) { String web_time = parsed["date"].as<String>(); uint8_t time_hours = (web_time.charAt(11) - '0') * 10 + (web_time.charAt(12) - '0'); uint8_t time_min = (web_time.charAt(14) - '0') * 10 + (web_time.charAt(15) - '0'); int time_day = (web_time.charAt(0) - '0') * 10 + (web_time.charAt(1) - '0'); int time_month = (web_time.charAt(3) - '0') * 10 + (web_time.charAt(4) - '0'); int time_year = (web_time.charAt(8) - '0') * 10 + (web_time.charAt(9) - '0'); uint16_t d = time_day; uint16_t m = time_month; uint16_t y = 2000 + time_year; uint16_t weekday = (d += m < 3 ? y-- : y - 2, 23 * m / 9 + d + 4 + y / 4 - y / 100 + y / 400) % 7; //Set PG in time: if (weekday == 0) weekday = 7; change_time_pg(weekday, time_hours, time_min, time_min); //year/month/week/day/hour/min delay(300); pg_serial_date(time_day, time_month, time_year); } if (parsed["fertirrigations"].success()) { String fertirrigation = parsed["fertirrigations"].as<String>(); LOGLN(fertirrigation); uint8_t time_fertirrigation_wait[4][2]; uint8_t time_fertirrigation_irrigation[4][2]; uint8_t index_valves = 3; uint8_t f = 0; while (f < fertirrigation.length() && index_valves >= 0) { time_fertirrigation_irrigation[index_valves][0] = (fertirrigation.charAt(f++) - '0') * 10 + (fertirrigation.charAt(f++) - '0'); time_fertirrigation_irrigation[index_valves][1] = (fertirrigation.charAt(f++) - '0') * 10 + (fertirrigation.charAt(f++) - '0'); time_fertirrigation_wait[index_valves][0] = (fertirrigation.charAt(f++) - '0') * 10 + (fertirrigation.charAt(f++) - '0'); time_fertirrigation_wait[index_valves][1] = (fertirrigation.charAt(f++) - '0') * 10 + (fertirrigation.charAt(f++) - '0'); LOG("El fertirrigante "); LOG(14 - index_valves); LOG(" tiene el siguiente tiempo de espera: "); LOG(time_fertirrigation_wait[index_valves][0]); LOG(":"); LOG(time_fertirrigation_wait[index_valves][1]); LOG(" y el tiempo de riego es: "); LOG(time_fertirrigation_irrigation[index_valves][0]); LOG(":"); LOGLN(time_fertirrigation_irrigation[index_valves][1]); pg_serial_fertirrigation(index_valves, time_fertirrigation_wait[index_valves][0], time_fertirrigation_wait[index_valves][1], time_fertirrigation_irrigation[index_valves][0], time_fertirrigation_irrigation[index_valves][1]); index_valves--; pg_listen(); client.loop(); } } if (parsed["config"].success()) { String activate_fertirrigation = parsed["config"].as<String>(); LOGLN(activate_fertirrigation); bool active = false; for (int i = 0; i < activate_fertirrigation.length(); i++) { if (activate_fertirrigation.charAt(i) == '1') { active = true; break; } LOGW(activate_fertirrigation.charAt(i)); } active ? pg_serial_activate_fertirrigation(true) : pg_serial_activate_fertirrigation(false); } if (parsed["pump_associations"].success()) { //This should be on the parser.success... LOGLN("pump_associations"); const char *pump_associations = parsed["pump_associations"]; for (int i = 0; i < 10; i++) { LOGW(pump_associations[i]); } char data_asso[] = "0000000000000000000000000000000007000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; for (int i = 0; i < sizeof(data_asso); i++) data_asso[i] = pump_associations[i]; //I obtein the values and write on memmory: // web_to_pg_pump_associations(data_pump); int pump_mem = 0x100; int index_ = 0; while (index_ < sizeof(data_asso) - 2) { char valve_number[] = "00"; valve_number[0] = data_asso[index_++]; valve_number[1] = data_asso[index_++]; String str_pos = String(pump_mem++, HEX); str_pos.toUpperCase(); //cmd_write_data[13] = str_pos.charAt(0); //cmd_write_data[14] = str_pos.charAt(1); //cmd_write_data[15] = str_pos.charAt(2); //I add the numbers: //cmd_write_data[17] = valve_number[0]; //cmd_write_data[18] = valve_number[1]; //calcrc((char *)//cmd_write_data, sizeof(//cmd_write_data) - 2); //Serial2.write(//cmd_write_data, sizeof(//cmd_write_data)); LOGLN(" "); delay(FUKING_SLOW_TIME_PG); client.loop(); } pg_serial_restart(); delay(500); } if (parsed["master_pump_associations"].success()) { // //Parse the master pump association: LOGLN("master_pump_associations"); String master_pump = parsed["master_pump_associations"].as<String>(); char data_pump[] = "C0F8FF02000002002000000008008080"; for (int i = 0; i < 33; i++) data_pump[i] = master_pump[i]; //I obtein the values and write on memmory: uint8_t pump_mem_position = 0x80; uint8_t index = 0; while (index < sizeof(data_pump) - 2) { char valve_number[] = "00"; valve_number[0] = data_pump[index++]; valve_number[1] = data_pump[index++]; String str_pos = String(pump_mem_position++, HEX); str_pos.toUpperCase(); //cmd_write_data[13] = '0'; //cmd_write_data[14] = str_pos.charAt(0); //cmd_write_data[15] = str_pos.charAt(1); //cmd_write_data[17] = valve_number[0]; //cmd_write_data[18] = valve_number[1]; //calcrc((char *)//cmd_write_data, sizeof(//cmd_write_data) - 2); //Serial2.write(//cmd_write_data, sizeof(//cmd_write_data)); for (int i = 0; i < sizeof(//cmd_write_data); i++) LOGW(//cmd_write_data[i]); LOGLN(" "); pg_listen(); delay(FUKING_SLOW_TIME_PG); client.loop(); } delay(FUKING_SLOW_TIME_PG); } if (parsed["pump_ids"].success()) { String pump_ids = parsed["pump_ids"].as<String>(); LOGLN(pump_ids); int pos = 0; for (int i = 0; i < pump_ids.length(); i++) { String pump_position = String(0x180 + pos, HEX); if (pump_position.length() == 1) pump_position = '0' + pump_position; //cmd_write_data[13] = pump_position.charAt(0); //cmd_write_data[14] = pump_position.charAt(1); //cmd_write_data[15] = pump_position.charAt(2); String write_pg_pumps = String(pump_ids.charAt(i++)) + String(pump_ids.charAt(i)); if (write_pg_pumps.length() == 1) write_pg_pumps = '0' + write_pg_pumps; write_pg_pumps.toUpperCase(); //cmd_write_data[17] = write_pg_pumps.charAt(0); //cmd_write_data[18] = write_pg_pumps.charAt(1); //calcrc((char *)//cmd_write_data, sizeof(//cmd_write_data) - 2); //Serial2.write(//cmd_write_data, sizeof(//cmd_write_data)); //real send to PG for (int j = 0; j < sizeof(//cmd_write_data); j++) LOGW(//cmd_write_data[j]); delay(FUKING_SLOW_TIME_PG); pos++; } } if (parsed["pause"].success()) { int pause = parsed["pause"].as<int>(); LOG("I pause the programmer for: "); LOGLN(pause); String mem_pause = String(pause, HEX); mem_pause.toUpperCase(); if (mem_pause.length() != 2) mem_pause = '0' + mem_pause; //Not that is compleatly in HEX I copy in the data buffer //cmd_write_data[13] = '0'; //cmd_write_data[14] = '4'; //cmd_write_data[15] = 'E'; //cmd_write_data[17] = mem_pause.charAt(0); //cmd_write_data[18] = mem_pause.charAt(1); //calcrc((char *)//cmd_write_data, sizeof(//cmd_write_data) - 2); // //Serial2.write(//cmd_write_data, sizeof(//cmd_write_data)); for (int i = 0; i < sizeof(//cmd_write_data); i++) LOGW(//cmd_write_data[i]); delay(600); } send_web("/general", sizeof("/general"), identifier); } else if (sTopic.indexOf("stop") != -1) //I stop all the stuff open { uint8_t index_close = 0; for (; index_close < 14; index_close++) if (active.valves[index_close]) { pg_serial_action_valve(false, index_close + 1, 0, 0); delay(1000); } char program_letters[] = {'A', 'B', 'C', 'D', 'E', 'F'}; for (index_close = 0; index_close < 6; index_close++) if (active.programs[index_close]) { action_prog_pg(0, program_letters[index_close]); //I send the command tom PG active.programs[index_close] = false; send_stop_program = true; delay(800); } stop_man_web.manual_web = false; stop_man_web.number_timers = 0; for (uint8_t c = 0; c < 10; c++) { stop_man_web.active[c] = false; stop_man_web.valve_number[c] = 0; stop_man_web.millix[c] = 0; stop_man_web.times[c] = 0; } send_web("/stop", sizeof("/stop"), identifier); } else if (sTopic.indexOf("command") != -1) //I stop all the stuff open { send_web("/command", sizeof("/command"), identifier); delay(FUKING_SLOW_TIME_PG); pg_serial_restart(); delay(FUKING_SLOW_TIME_PG); } } } void web_to_pg_pump_associations(char pump_associations[]) { int real_pump = 8; // 8 7 6 5 4 3 2 1 asignation // 16 15 14 13 12 11 10 9 char valve_number[] = "00"; uint8_t index = 0; int times = 0; while (times < 16) { valve_number[0] = pump_associations[index++]; valve_number[1] = pump_associations[index++]; // printf("Char: 0x%c%c \n", valve_number[0], valve_number[1]); int valve_int = (int)strtol(valve_number, NULL, 16); LOGLN(valve_int); shift_pumps(valve_int, real_pump); real_pump += 8; times++; } } void shift_pumps(int valve_int, int pump) { // printf("The number is: %d\n", valve_int); int compare = 0b10000000; for (int i = 0; i < 8; i++) { if (valve_int & compare) { LOG("The number is: "); LOGLN(pump); } compare = compare >> 0x01; pump--; } } void init_mqtt() { client.setServer(mqtt_server, MQTT_PORT); client.setCallback(callback); reconnect(); } <file_sep>/2560/main/rtc_controller.h #ifndef RTC_CONTROLLER #define RTC_CONTROLLER #include "pinout.h" #include "secrets.h" typedef struct { bool open; uint8_t interval; uint8_t startDay; uint8_t wateringDay; uint16_t waterPercent; uint8_t start[6][2]; uint16_t irrigTime[14]; } program; program prog[6]; void check_schedule_on() { int hour = 0; int weekday = 0; int minute = 0; // pg_time_check(&hour, &minute, &weekday); LOG(hour); LOG(":"); LOG(minute); LOG(" - day: "); LOGLN(weekday); for (int index_prog = 0; index_prog < 6; index_prog++) { //check if the program is open I will have to close: if (prog[index_prog].open) { } //if not open I will check if it time to: else { for (int index_start = 0; index_start < 6; index_start++) if (prog[index_prog].start[index_start][0] == hour) if (prog[index_prog].start[index_start][1] == minute) { LOG("Start program "); char program_letters[] = {'A', 'B', 'C', 'D', 'E', 'F'}; LOGLN(program_letters[index_prog]); prog[index_prog].open = true; // if (hour != 0) // json_program_action(true, program_letters[index_prog]); } } } } void check_schedule_off() { for (int index_prog = 0; index_prog < 6; index_prog++) { } } #endif RTC_CONTROLLER <file_sep>/2560/main/main.ino #define MQTT_MAX_PACKET_SIZE 7084 #include "secrets.h" #include "periodic_task.h" #include "wifi_config.h" #include "pinout.h" #include "mqtt_interections.h" #include "rtc_controller.h" #include "SPI.h" #include "Adafruit_GFX.h" #include "Adafruit_ILI9341.h" #include "logos.h" #define _cs 5 // 3 goes to TFT CS #define _dc 2 // 4 goes to TFT DC #define _mosi 23 // 5 goes to TFT MOSI #define _sclk 18 // 6 goes to TFT SCK/CLK #define _rst 4 // ESP RST to TFT RESET #define _miso // Not connected Adafruit_ILI9341 tft = Adafruit_ILI9341(_cs, _dc, _mosi, _sclk, _rst); void setup() { Serial.begin(115200); //Initialize all the controller peripherals: pinMode(LED, OUTPUT); digitalWrite(LED, HIGH); pinMode(LED_WIFI, OUTPUT); strcpy(sys.uuid_, UUID); auto_wifi_connect(); init_mqtt(); config_timer(); digitalWrite(LED_WIFI, HIGH); digitalWrite(LED, LOW); //Define the rotatory encoder: pinMode(ENCODER_CLK, INPUT); pinMode(ENCODER_DT, INPUT); pinMode(ENCODER_SW, INPUT); attachInterrupt(ENCODER_DT, isr, FALLING); //Define the screen tft.begin(); tft.setRotation(45); tft.fillScreen(ILI9341_WHITE); // tft.drawBitmap(40, 0, logo, 240, 240, ILI9341_DARKGREY); int h = 240, w = 240, row, col, buffidx = 0; for (row = 0; row < h; row++) for (col = 0; col < w; col++) tft.drawPixel(col + 40, row, pgm_read_word(color_image + buffidx++)); uint32_t debounced_timer = 0; bool led_off = false; uint32_t test_timer = millis(); while (true) { if (xSemaphoreTake(timer_mqtt, 0) == pdTRUE) { digitalWrite(LED, HIGH); uint32_t isrCount = 0, isrTime = 0; // Read the interrupt count and time portENTER_CRITICAL(&timerMux); isrCount = isrCounter; isrTime = lastIsrAt; portEXIT_CRITICAL(&timerMux); LOG("Counter ISR:"); LOGLN(isrCount); led_off = true; // LOGLN(sys.selector_auto); if (isrCount % 2 == 0) { refresh_msg(isrTime); // check_schedule_on(); tft.fillScreen(ILI9341_BLACK); tft.drawBitmap(20, 50, sprinkler, 100, 100, ILI9341_NAVY); tft.drawBitmap(200, 50, irrigating, 100, 100, ILI9341_GREENYELLOW); tft.drawBitmap(0, 190, wifi, 50, 50, ILI9341_PURPLE); } } if (led_off && millis() - lastIsrAt >= 800) { led_off = false; digitalWrite(LED, LOW); } // if (millis() - test_timer >= 1000) // { // test_timer = millis(); // LOGLN(interrupt_counter); // } if (isr_encoder_flag) { if (millis() - debounced_timer >= DEBOUNCED_TIME) { digitalWrite(LED, LOW); delay(2); digitalWrite(LED, HIGH); if (digitalRead(ENCODER_CLK) == LOW) LOGLN("DERECHA"); else LOGLN("IZQUIERDA"); debounced_timer = millis(); tft.drawBitmap(0, 190, wifi, 50, 50, ILI9341_PURPLE); } isr_encoder_flag = false; } if (digitalRead(ENCODER_SW) == LOW) { LOGLN("PUSH"); tft.fillScreen(ILI9341_BLACK); tft.drawBitmap(20, 50, sprinkler, 100, 100, ILI9341_NAVY); // delay(DEBOUNCED_TIME); } reconnect(); client.loop(); } } void loop() { } <file_sep>/Access_Point/AP.c #include "AP.h" void modified_struct(light_open_info *lamp, uint8_t hola) { lamp->starts[1] = ++hola; lamp->week_day[1] = ++hola; lamp->starts[1] = ++hola; }<file_sep>/BLE_2560/gatt_server/components/irrigarion_controller/irrigarion_controller.c #include "irrigation_controller.h" #include "nvs_flash.h" #include "nvs.h" // #include "nvs.hpp" // Global data for storing all the program information: Irrigation_program irrigation_program[4]; void irrig_controller_init_data() { esp_err_t ret; // Initialize NVS: ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase()); ret = nvs_flash_init(); } ESP_ERROR_CHECK(ret); // Open printf("\n"); printf("Opening Non-Volatile Storage (NVS): "); nvs_handle_t my_handle; ret = nvs_open("storage", NVS_READWRITE, &my_handle); if (ret != ESP_OK) { printf("Error (%s) opening NVS handle!\n", esp_err_to_name(ret)); } else { printf("Done\n"); // Read printf("Reading restart counter from NVS ... "); //int32_t restart_counter = 0; // value will default to 0, if not set yet in NVS irrigation_program[0].water_percentage = 12; nvs_handle_t my_handle; // ret = nvs_get_i8(my_handle, "a_water_percentage", &irrigation_program[0].water_percentage); // printf((ret != ESP_OK) ? "Failed!\n" : "Done Getting a_water_percentage\n"); // printf("%i", irrigation_program[0].water_percentage); /* printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_hour_0", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_hour_1", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_hour_2", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_hour_3", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_min_0", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_min_1", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_min_2", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_min_3", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v0", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v1", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v2", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v3", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v4", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v5", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v6", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v7", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v0", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v1", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v2", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v3", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v4", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v5", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v6", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v7", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); */ //Get the data: // for (uint8_t index_program = 0; index_program < MAX_NUMBER_PROGRAM; index_program++) // { // nvs_get_i8(my_handle, "prog_A_", &restart_counter); // uint8_t water_percentage; //0 - 10 -20 - 400% // uint8_t start_hour[MAX_NUMBER_PROGRAM]; //0-24 h // uint8_t start_min[MAX_NUMBER_PROGRAM]; //0-59 min // uint8_t time_hour[MAX_NUMBER_VALVES]; //0 min a 12 min // uint8_t time_min[MAX_NUMBER_VALVES]; //0 min a 60 min // } // switch (ret) // { // case ESP_OK: // printf("Done\n"); // printf("Restart counter = %d\n", restart_counter); // break; // case ESP_ERR_NVS_NOT_FOUND: // printf("The value is not initialized yet!\n"); // break; // default: // printf("Error (%s) reading!\n", esp_err_to_name(ret)); // } // Write /* printf("Writing program data from nvs memmory: "); ret = nvs_set_i8(my_handle, "a_water_percentage", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_hour_0", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_hour_1", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_hour_2", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_hour_3", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_min_0", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_min_1", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_min_2", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_start_min_3", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v0", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v1", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v2", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v3", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v4", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v5", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v6", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_hour_v7", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v0", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v1", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v2", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v3", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v4", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v5", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v6", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); ret = nvs_set_i8(my_handle, "a_time_min_v7", 0); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); // Commit written value. // After setting any values, nvs_commit() must be called to ensure changes are written // to flash storage. Implementations may write to storage at other times, // but this is not guaranteed. printf("Committing updates in NVS ... "); ret = nvs_commit(my_handle); printf((ret != ESP_OK) ? "Failed!\n" : "Done\n"); */ // Close nvs_close(my_handle); } } void irrig_controller_save_data() { for (uint8_t index_program = 0; index_program < MAX_NUMBER_PROGRAM; index_program++) { printf("%i", irrigation_program[index_program].water_percentage); } } <file_sep>/BLE_2560/gatt_server/components/irrigarion_controller/CMakeLists.txt idf_component_register(SRCS "irrigarion_controller.c" INCLUDE_DIRS "." REQUIRES main) <file_sep>/README.md ## 1.1. Bluethoot tecnology Learn everything related with bluethoot tecnology and ESP32 diferent modes. ### 1.1.1. BLE vs Bluetooth 3.0 basics Bluethoot: * Short Range * Low power (meh, I have tested and 120mA...) * Low data rate * f = ISM 2.400GHz and 79 channels | Clasic Bluetooth |BLE | | :---: | :---: | |High datarate |Low datarate | |Long range |Small range | |High power consumption |Low power consumption | |Audio Steamming | - | |Class 4 - 0.5mW | 10 mW max | |Class 1 - 100mW | - | ### 1.1.2. Topology: Master/Slave: * up to 7 slaves in a "piconet" * "parkel" slaves -> They are sleep but in the net * FHSS: Frecuency Hoppping Spread Spectum, it hops in frecuencies in order to not interfeer with other devise near it. * TDM: Time domain multiplexing, the master devise set time periods of 625uS to let the others on the network to comunicate with them. Every time happends the fecuency change. The connection between elements can be SCO (Synchronous Connection Oriented) or ACL (Asynchronous Connection-Less). ### 1.1.3. Data format: This always happend in 625uS Synchronization is from the master's ID | Access Code |Header |Payload| | :---: | :---: |:---: | | 72 bits |54 bits |0-2745 bits| * Access code: | Preamble |Synchronization |Trailer| | :---: | :---: |:---: | | 4 bits |64 bits |4 bits| * Header: | AM_ADDR |Type |Flow |ARQN |SEQN |HEC| | :---: | :---: | :---: | :---: |:---: |:---: | | 3 bits |4 bits |1 bits|1 bits|1 bits|8 bits| - AM_ADDR: Active member address, one master 7 slaves - Type: 12 packets for SCO and ACL - HEC: Header Error Check like CRC * Payload (Data): | DATA | | :---: | ### 1.1.4. Profiles: * They define the attributes, services or formats -> How to talk to the devise. * There are dozen of profiles. * SPP (Serial Port Protocol): Es one of the profiles more used. * They are in the application layer and the fix the bottom protocols. #### Host Stack: It mostly happens on top of them. | - |- |APPLICATION| - | -| | :---: | :---: | :---: | :---: |:---: | | TCS |OBEX |- |WAP | SDP| | - |- |RF COMM | -|- | | Lotgic | Link |Control |Adaption |Protocol| #### Controller Stack: Chil level, it happends on hardware. | HCI (Host control Interface) AT commands | | :---: | | Link Manager Protocol | | BasebandX/Link Controller | | Radio | ### 1.2. GAP generic access profile Makes your device visible to the outside world, is the protocol for get connected with others blue. ### 1.3. GATT GATT is an acronym for the Generic Attribute Profile , and it defines the way that two Bluetooth Low Energy devices transfer data back and forth using concepts called Services and Characteristics. It makes use of a generic data protocol called the Attribute Protocol (ATT), which is used to store Services, Characteristics and related data in a simple lookup table using 16-bit IDs for each entry in the table. * connections are exclusive * BLE peripheral can only be connected to one central device at a time #### 1.3.1 Profiles Are a pre-defined collection of Services #### 1.3.2 Services A service can have one or more characteristics, and each service distinguishes itself from other servicesby means of a unique numeric ID called a UUID, which can be either 16-bit (for officially adopted BLEServices) #### 1.3.3 Characteristics The lowest level concept in GATT transactions is the Characteristic, which encapsulates a single data point (though it may contain an array of related data. They are also used to send data back to the BLE peripheral, since you are also able to write to characteristic. <file_sep>/RFID_UHF/SYSIoT_UHF_Reader_SDK/SYSIoT_UHF_Reader_SDK/SDK/SourceCode/c#/NetReaderGA/NetReader/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.Collections; //Queue using System.Globalization; using BarChart; using ZedGraph; using RFID_Reader_Cmds; using xSocketDLL; namespace NetReader { public partial class Form1 : Form { private bool bAutoSend = false; private int LoopNum_cnt = 0; public xClient rpClient; private Thread threadClient; private Thread threadFramePaser; Queue qClient = new Queue(0xFFFFF); //------------------------------------- DataTable basic_table = new DataTable(); DataSet ds_basic = null; string pc = string.Empty; string epc = string.Empty; string crc = string.Empty; string rssi = string.Empty; string antno = string.Empty; int FailEPCNum = 0; int SucessEPCNum = 0; double errnum = 0; double db_errEPCNum = 0; double db_LoopNum_cnt = 0; string per = "0.000"; //------------------------------------- DataTable advanced_table = new DataTable(); DataSet ds_advanced = null; private String timeFormat = "yyyy/MM/dd HH:mm:ss.ff"; //private String timeFormat = System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern.ToString() + " HH:mm:ss.ff"; static string[] strBuff = new String[4096]; int rowIndex = 0; int initDataTableLen = 1; //Inital the line number of Datatable //---------------------------- //public ReceiveParser rp; //---------------------------- private static byte ReaderDeviceAddress = ConstCode.READER_DEVICEADDR_BROADCAST;//0xFF; public Form1() { InitializeComponent(); TagAccessInital(); } private void Form1_Load(object sender, EventArgs e) { //------------------------------------------------------- //DataGridView ds_basic = new DataSet(); basic_table = BasicGetEPCHead(); ds_basic.Tables.Add(basic_table); DataView BasicDataViewEpc = ds_basic.Tables[0].DefaultView; this.dgvEpcBasic.DataSource = BasicDataViewEpc; Basic_DGV_ColumnsWidth(this.dgvEpcBasic); this.dgvEpcBasic.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dgvEpcBasic_DataBindingComplete); //------------------------------------------------------- ds_advanced = new DataSet(); advanced_table = AdvancedGetEPCHead(); ds_advanced.Tables.Add(advanced_table); DataView AdvancedDataViewEpc = ds_advanced.Tables[0].DefaultView; this.dgv_epc2.DataSource = AdvancedDataViewEpc; Advanced_DGV_ColumnsWidth(this.dgv_epc2); this.dgv_epc2.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dgv_epc2_DataBindingComplete); //-------------------------------------------------------- int i; for (i = 0; i < 255; i++) { cbxDeviceAddr.Items.Add(i.ToString("D03")); } i = 255; cbxDeviceAddr.Items.Add(i.ToString("D03") + " Broadcast"); cbxDeviceAddr.SelectedIndex = 255;//Default to use Broadcast Address to conncect the Reader, if we do not know the Reader's device address. ReaderDeviceAddr_Inital(); //-------------------------------------------------------- Zed_Inital(); ReadTagInital(); SensorTag_Inital();// SystemSettingInital(); //-------------------------------------------------------- // Net rpClient = new xClient(); //-------------------------------------------------------- //rp = new ReceiveParser(); //rp.PacketReceived += new EventHandler<StrArrEventArgs>(rp_PaketReceived); InitAddEvent(rp_PaketReceived); // Add a EventHandler //this.dgvEpcBasic.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dgvEpcBasic_DataBindingComplete); byte MainVer = 0, MtypeVer = 0, MinorVer = 0; Commands.GetDllVersion(ref MainVer, ref MtypeVer, ref MinorVer); string strDllVer = MainVer.ToString("X02") + "." + MtypeVer.ToString("X02") + "." + MinorVer.ToString("X02"); setToolStripStatusMessage1("UHF RFID Reader Demo. DLL Version: " + strDllVer, Color.Red); } private void Form1_Closing(object sender, FormClosingEventArgs e) { button_Close_Click(null, null); } //----------------------------------------------------- private delegate void SetTextBoxDelegate(object sender, string strtext); private void setTextBoxInvoke(object sender,string strtext) { if (this.txtSend.InvokeRequired) { SetTextBoxDelegate md = new SetTextBoxDelegate(this.setTextBoxInvoke); this.Invoke(md, new object[] {sender, strtext }); } else ( (TextBox)sender).Text = strtext; } /// <summary> /// ///////////////////////////////////////////////////////////////////////////////Interface Inital /// </summary> #region Interface Inital private const int _BASIC_TABLE_INDEX_NO_ = 0; private const int _BASIC_TABLE_INDEX_PC_ = 1; private const int _BASIC_TABLE_INDEX_EPC_ = 2; private const int _BASIC_TABLE_INDEX_CRC_ = 3; private const int _BASIC_TABLE_INDEX_RSSI_ = 4; private const int _BASIC_TABLE_INDEX_CNT_ = 5; private const int _BASIC_TABLE_INDEX_PER_ = 6; private const int _BASIC_TABLE_INDEX_ANT_ = 7; private DataTable BasicGetEPCHead() { basic_table.TableName = "EPC"; basic_table.Columns.Add("No.", typeof(string)); // 0 basic_table.Columns.Add("PC", typeof(string)); // 1 basic_table.Columns.Add("EPC", typeof(string)); // 2 basic_table.Columns.Add("CRC", typeof(string)); // 3 basic_table.Columns.Add("RSSI(dB)", typeof(string)); // 4 basic_table.Columns.Add("CNT", typeof(string)); // 5 basic_table.Columns.Add("PER(%)", typeof(string)); // 6 basic_table.Columns.Add("ANT", typeof(string)); // 7 for (int i = 0; i <= initDataTableLen - 1; i++) { basic_table.Rows.Add(new object[] { null }); } basic_table.AcceptChanges(); return basic_table; } private void Basic_DGV_ColumnsWidth(DataGridView dataGridView1) { //dataGridView1.Columns[6].SortMode = DataGridViewColumnSortMode.Programmatic; dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.ColumnHeadersHeight = 40; //dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_BASIC_TABLE_INDEX_NO_].Width = 40; //dataGridView1.Columns[0].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_BASIC_TABLE_INDEX_NO_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_BASIC_TABLE_INDEX_NO_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_BASIC_TABLE_INDEX_PC_].Width = 60; //dataGridView1.Columns[1].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_BASIC_TABLE_INDEX_PC_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_BASIC_TABLE_INDEX_PC_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_BASIC_TABLE_INDEX_EPC_].Width = 290; //dataGridView1.Columns[_BASIC_TABLE_INDEX_EPC_].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_BASIC_TABLE_INDEX_EPC_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_BASIC_TABLE_INDEX_EPC_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_BASIC_TABLE_INDEX_CRC_].Width = 60; //dataGridView1.Columns[_BASIC_TABLE_INDEX_CRC_].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_BASIC_TABLE_INDEX_CRC_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_BASIC_TABLE_INDEX_CRC_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_BASIC_TABLE_INDEX_RSSI_].Width = 75; //dataGridView1.Columns[_BASIC_TABLE_INDEX_RSSI_].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_BASIC_TABLE_INDEX_RSSI_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_BASIC_TABLE_INDEX_RSSI_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //dataGridView1.Columns[5].Width = 70; ////dataGridView1.Columns[5].DefaultCellStyle.Font = new Font("Lucida Console", 10); //dataGridView1.Columns[5].Resizable = DataGridViewTriState.False; //dataGridView1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_BASIC_TABLE_INDEX_CNT_].Width = 70; //dataGridView1.Columns[_BASIC_TABLE_INDEX_CNT_].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_BASIC_TABLE_INDEX_CNT_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_BASIC_TABLE_INDEX_CNT_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_BASIC_TABLE_INDEX_PER_].Width = 72; //dataGridView1.Columns[_BASIC_TABLE_INDEX_PER_].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_BASIC_TABLE_INDEX_PER_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_BASIC_TABLE_INDEX_PER_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //dataGridView1.Columns[_BASIC_TABLE_INDEX_ANT_].Visible = false; dataGridView1.Columns[_BASIC_TABLE_INDEX_ANT_].Width = 50; //dataGridView1.Columns[_BASIC_TABLE_INDEX_ANT_].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_BASIC_TABLE_INDEX_ANT_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_BASIC_TABLE_INDEX_ANT_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; } private const int _ADV_TABLE_INDEX_NO_ = 0; private const int _ADV_TABLE_INDEX_PC_ = 1; private const int _ADV_TABLE_INDEX_EPC_ = 2; private const int _ADV_TABLE_INDEX_CRC_ = 3; private const int _ADV_TABLE_INDEX_CNT_ = 4; private const int _ADV_TABLE_INDEX_ANT_ = 5; private DataTable AdvancedGetEPCHead() { advanced_table.TableName = "EPC"; advanced_table.Columns.Add("No.", typeof(string)); //0 advanced_table.Columns.Add("PC", typeof(string)); //1 advanced_table.Columns.Add("EPC", typeof(string)); //2 advanced_table.Columns.Add("CRC", typeof(string)); //3 advanced_table.Columns.Add("CNT", typeof(string)); //4 advanced_table.Columns.Add("ANT", typeof(string)); //5 for (int i = 0; i <= initDataTableLen - 1; i++) { advanced_table.Rows.Add(new object[] { null }); } advanced_table.AcceptChanges(); return advanced_table; } private void Advanced_DGV_ColumnsWidth(DataGridView dataGridView1) { //dataGridView1.Columns[6].SortMode = DataGridViewColumnSortMode.Programmatic; dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.ColumnHeadersHeight = 40; //dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_ADV_TABLE_INDEX_NO_].Width = 40; //dataGridView1.Columns[_ADV_TABLE_INDEX_NO_].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_ADV_TABLE_INDEX_NO_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_ADV_TABLE_INDEX_NO_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_ADV_TABLE_INDEX_PC_].Width = 60; //dataGridView1.Columns[_ADV_TABLE_INDEX_PC_].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_ADV_TABLE_INDEX_PC_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_ADV_TABLE_INDEX_PC_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_ADV_TABLE_INDEX_EPC_].Width = 240; //dataGridView1.Columns[_ADV_TABLE_INDEX_EPC_].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_ADV_TABLE_INDEX_EPC_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_ADV_TABLE_INDEX_EPC_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_ADV_TABLE_INDEX_CRC_].Width = 60; //dataGridView1.Columns[_ADV_TABLE_INDEX_CRC_].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_ADV_TABLE_INDEX_CRC_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_ADV_TABLE_INDEX_CRC_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_ADV_TABLE_INDEX_CNT_].Width = 52; //dataGridView1.Columns[_ADV_TABLE_INDEX_CNT_].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_ADV_TABLE_INDEX_CNT_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_ADV_TABLE_INDEX_CNT_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_ADV_TABLE_INDEX_ANT_].Width = 40; //dataGridView1.Columns[_ADV_TABLE_INDEX_ANT_].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_ADV_TABLE_INDEX_ANT_].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_ADV_TABLE_INDEX_ANT_].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; } private void dgvEpcBasic_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { this.dgvEpcBasic.ClearSelection(); //double totalCnt = 0; //if (e.ListChangedType == ListChangedType.ItemChanged || e.ListChangedType == ListChangedType.ItemMoved) { //for (int i = 0; i < this.dgvEpcBasic.Rows.Count; i++) //{ // string cnt = this.dgvEpcBasic.Rows[i].Cells[5].Value.ToString(); // if (null != cnt && !"".Equals(cnt)) // { // totalCnt += Convert.ToInt32(cnt); // } //} //for (int i = 0; i < this.dgvEpcBasic.Rows.Count; i++) //{ // string cnt = this.dgvEpcBasic.Rows[i].Cells[5].Value.ToString(); // if (null != cnt && !"".Equals(cnt)) // { // int sigleCnt = Convert.ToInt32(cnt); // int r = 0xFF & (int)(sigleCnt / totalCnt * 255); // this.dgvEpcBasic.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(0xff,255 - r,255 - r); // } //} pbx_Inv_Indicator.Visible = true; } } private void dgv_epc2_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { //if (e.ListChangedType == ListChangedType.ItemChanged || e.ListChangedType == ListChangedType.ItemAdded) { for (int i = 0; i < this.dgv_epc2.Rows.Count; i++) { if (i % 2 == 0) { this.dgv_epc2.Rows[i].DefaultCellStyle.BackColor = Color.AliceBlue; } } } } private void GetEPC(string pc, string epc, string crc, string rssi, string antno, string per) { //this.dgv_epc2.ClearSelection(); bool isFoundEpc = false; string newEpcItemCnt; int indexEpc = 0; int EpcItemCnt; uint EpcTagCounter = Convert.ToUInt32(textBox_EPC_TagCounter.Text); EpcTagCounter++; textBox_EPC_TagCounter.Text = EpcTagCounter.ToString(); if (rowIndex <= initDataTableLen) { EpcItemCnt = rowIndex; } else { EpcItemCnt = basic_table.Rows.Count; EpcItemCnt = advanced_table.Rows.Count; } for (int j = 0; j < EpcItemCnt; j++) { if (basic_table.Rows[j][2].ToString() == epc && basic_table.Rows[j][1].ToString() == pc) { indexEpc = j; isFoundEpc = true; break; } } if (EpcItemCnt < initDataTableLen) //basic_table.Rows[EpcItemCnt][0].ToString() == "" { if (!isFoundEpc || EpcItemCnt == 0) { if (EpcItemCnt + 1 < 10) { newEpcItemCnt = "0" + Convert.ToString(EpcItemCnt + 1); } else { newEpcItemCnt = Convert.ToString(EpcItemCnt + 1); } try { basic_table.Rows[EpcItemCnt][_BASIC_TABLE_INDEX_NO_] = newEpcItemCnt; // EpcItemCnt + 1; basic_table.Rows[EpcItemCnt][_BASIC_TABLE_INDEX_PC_] = pc; basic_table.Rows[EpcItemCnt][_BASIC_TABLE_INDEX_EPC_] = epc; basic_table.Rows[EpcItemCnt][_BASIC_TABLE_INDEX_CRC_] = crc; basic_table.Rows[EpcItemCnt][_BASIC_TABLE_INDEX_RSSI_] = rssi; basic_table.Rows[EpcItemCnt][_BASIC_TABLE_INDEX_CNT_] = 1; basic_table.Rows[EpcItemCnt][_BASIC_TABLE_INDEX_PER_] = "0.000"; basic_table.Rows[EpcItemCnt][_BASIC_TABLE_INDEX_ANT_] = 0;//System.DateTime.Now.ToString(timeFormat); advanced_table.Rows[EpcItemCnt][_ADV_TABLE_INDEX_NO_] = newEpcItemCnt; // EpcItemCnt + 1; advanced_table.Rows[EpcItemCnt][_ADV_TABLE_INDEX_PC_] = pc; advanced_table.Rows[EpcItemCnt][_ADV_TABLE_INDEX_EPC_] = epc; advanced_table.Rows[EpcItemCnt][_ADV_TABLE_INDEX_CRC_] = crc; advanced_table.Rows[EpcItemCnt][_ADV_TABLE_INDEX_CNT_] = 1; advanced_table.Rows[EpcItemCnt][_ADV_TABLE_INDEX_ANT_] = 0; rowIndex++; } catch (System.Exception ex) { Console.WriteLine(ex.Message); } textBox_EPC_Tag_Total.Text = newEpcItemCnt; } else { if (indexEpc + 1 < 10) { newEpcItemCnt = "0" + Convert.ToString(indexEpc + 1); } else { newEpcItemCnt = Convert.ToString(indexEpc + 1); } try { basic_table.Rows[indexEpc][_BASIC_TABLE_INDEX_NO_] = newEpcItemCnt; // indexEpc + 1; basic_table.Rows[indexEpc][_BASIC_TABLE_INDEX_RSSI_] = rssi; basic_table.Rows[indexEpc][_BASIC_TABLE_INDEX_CNT_] = Convert.ToInt32(basic_table.Rows[indexEpc][_BASIC_TABLE_INDEX_CNT_].ToString()) + 1; basic_table.Rows[indexEpc][_BASIC_TABLE_INDEX_PER_] = per; basic_table.Rows[indexEpc][_BASIC_TABLE_INDEX_ANT_] = antno;//System.DateTime.Now.ToString(timeFormat); advanced_table.Rows[indexEpc][_ADV_TABLE_INDEX_NO_] = newEpcItemCnt; // indexEpc + 1; advanced_table.Rows[indexEpc][_ADV_TABLE_INDEX_CNT_] = Convert.ToInt32(advanced_table.Rows[indexEpc][_ADV_TABLE_INDEX_CNT_].ToString()) + 1; advanced_table.Rows[indexEpc][_ADV_TABLE_INDEX_ANT_] = antno;//Convert.ToInt32(advanced_table.Rows[indexEpc][_ADV_TABLE_INDEX_ANT_].ToString()) + 1; } catch (System.Exception ex) { Console.WriteLine(ex.Message); } } } else { if (!isFoundEpc || EpcItemCnt == 0) { if (EpcItemCnt + 1 < 10) { newEpcItemCnt = "0" + Convert.ToString(EpcItemCnt + 1); } else { newEpcItemCnt = Convert.ToString(EpcItemCnt + 1); } basic_table.Rows.Add(new object[] { newEpcItemCnt, pc, epc, crc, rssi, "1", "0.000", antno }); advanced_table.Rows.Add(new object[] { newEpcItemCnt, pc, epc, crc, "1", antno }); rowIndex++; textBox_EPC_Tag_Total.Text = newEpcItemCnt; } else { if (indexEpc + 1 < 10) { newEpcItemCnt = "0" + Convert.ToString(indexEpc + 1); } else { newEpcItemCnt = Convert.ToString(indexEpc + 1); } try { basic_table.Rows[indexEpc][_BASIC_TABLE_INDEX_NO_] = newEpcItemCnt; // indexEpc + 1; basic_table.Rows[indexEpc][_BASIC_TABLE_INDEX_RSSI_] = rssi; basic_table.Rows[indexEpc][_BASIC_TABLE_INDEX_CNT_] = Convert.ToInt32(basic_table.Rows[indexEpc][_BASIC_TABLE_INDEX_CNT_].ToString()) + 1; basic_table.Rows[indexEpc][_BASIC_TABLE_INDEX_PER_] = per; basic_table.Rows[indexEpc][_BASIC_TABLE_INDEX_ANT_] = antno;//System.DateTime.Now.ToString(timeFormat); advanced_table.Rows[indexEpc][_ADV_TABLE_INDEX_NO_] = newEpcItemCnt; // indexEpc + 1; advanced_table.Rows[indexEpc][_ADV_TABLE_INDEX_CNT_] = Convert.ToInt32(advanced_table.Rows[indexEpc][_ADV_TABLE_INDEX_CNT_].ToString()) + 1; advanced_table.Rows[indexEpc][_ADV_TABLE_INDEX_ANT_] = antno; //Convert.ToInt32(advanced_table.Rows[indexEpc][_ADV_TABLE_INDEX_ANT_].ToString()) + 1; } catch (System.Exception ex) { Console.WriteLine(ex.Message); } } } } private void setStatus(string msg, Color color) { //rtbxStatus.Text = msg; //rtbxStatus.ForeColor = color; setToolStripStatusMessage1(msg, color); } private void setToolStripStatusMessage1(string msg, Color color) { toolStripStatusLabel1.Text = msg; toolStripStatusLabel1.ForeColor = color; } private void setToolStripStatusMessage2(string msg, Color color) { toolStripStatusLabel2.Text = msg; toolStripStatusLabel2.ForeColor = color; } private void setToolStripStatusMessage3(string msg, Color color) { toolStripStatusLabel3.Text = msg; toolStripStatusLabel3.ForeColor = color; } #endregion //////////////////////////////////////////////////////////////////////String Convert #region String Convert /* string类型转成byte[]: byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str ); byte[]转成string: string str = System.Text.Encoding.Default.GetString ( byteArray ); string类型转成ASCII byte[]: ("01" 转成 byte[] = new byte[]{ 0x30,0x31}) byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str ); ASCIIbyte[]转成string: (byte[] = new byte[]{ 0x30, 0x31} 转成"01") string str = System.Text.Encoding.ASCII.GetString ( byteArray ); byte[]转16进制格式string: new byte[]{ 0x30, 0x31}转成"3031": */ private string[] String16toString2(string S) { string[] S_array = new string[8]; int intS = Convert.ToInt32(S, 16); for (int i = 7; i >= 0; i--) { S_array[i] = "0"; if (intS >= System.Math.Pow(2, i)) S_array[i] = "1"; intS = intS - Convert.ToInt32(S_array[i]) * Convert.ToInt32(System.Math.Pow(2, i)); } return S_array; } private string StringToString(string S) { string Str = null; int S_num = Convert.ToInt32(S, 16); if (S_num < 16) { Str = "0" + S; } else { Str = S; } return Str; } private string[] StringArrayToStringArray(string[] S) { string[] Str = new string[S.Length]; for (int i = 0; i < S.Length; i++) { int S_num = Convert.ToInt32(S[i], 16); if (S_num < 16) { Str[i] = "0" + S[i]; } else { Str[i] = S[i]; } } return Str; } private byte[] StringsToBytes(string[] B) { byte[] BToInt32 = new byte[B.Length]; for (int i = 0; i < B.Length; i++) { BToInt32[i] = StringToByte(B[i]); } return BToInt32; } private byte StringToByte(string Str) { for (int i = Str.Length; i < 2; i++) { Str += "0"; } return (byte)(Convert.ToInt32(Str, 16)); } private string AutoAddSpace(string Str) { String StrDone = string.Empty; int i; for (i = 0; i < (Str.Length - 2); i = i + 2) { StrDone = StrDone + Str[i] + Str[i + 1] + " "; } if (Str.Length % 2 == 0 && Str.Length != 0) { if (Str.Length == i + 1) { StrDone = StrDone + Str[i]; } else { StrDone = StrDone + Str[i] + Str[i + 1]; } } else { StrDone = StrDone + StringToString(Str[i].ToString()); } return StrDone; } /// <summary> /// 将一条十六进制字符串转换为ASCII /// </summary> /// <param name="hexstring">一条十六进制字符串</param> /// <returns>返回一条ASCII码</returns> public static string HexStringToASCII(string hexstring) { byte[] bt = HexStringToBinary(hexstring); string lin = ""; for (int i = 0; i < bt.Length; i++) { lin = lin + bt[i] + " "; } string[] ss = lin.Trim().Split(new char[] { ' ' }); char[] c = new char[ss.Length]; int a; for (int i = 0; i < c.Length; i++) { a = Convert.ToInt32(ss[i]); c[i] = Convert.ToChar(a); } string b = new string(c); return b; } /**/ /// <summary> /// 16进制字符串转换为二进制数组 /// </summary> /// <param name="hexstring">用空格切割字符串</param> /// <returns>返回一个二进制字符串</returns> public static byte[] HexStringToBinary(string hexstring) { string[] tmpary = hexstring.Trim().Split(' '); byte[] buff = new byte[tmpary.Length]; for (int i = 0; i < buff.Length; i++) { buff[i] = Convert.ToByte(tmpary[i], 16); } return buff; } public static byte[] HexStringToBinary1(string hexstring) { string strhex = hexstring.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", ""); //Clear the ilegal string:' ', string str; int k = 0; byte[] buff = new byte[strhex.Length / 2]; for (int i = 0; i < buff.Length; i++) { str = strhex.Substring(k, 2); k = k + 2; buff[i] = Convert.ToByte(str, 16); } return buff; } #endregion /// <summary> /// ///////////////////////////////////////////////////////////////// Net Data Reciever /// </summary> #region Net Process private ulong ulClientRecvByteCounter = 0; private ulong ulClientRecvEnqueueCounter = 0; private ulong ulClientRecvQueueCounter = 0; private ulong ulClientRecvDequeueCounter = 0; static private ReaderWriterLock _rwlock = new ReaderWriterLock(); private void ClientRecvMsgThread() { byte[] byteArray = new byte[0x1FFFF]; //System.Text.Encoding.ASCII.GetBytes(str); int i,iRecv; qClient.Clear(); while (bConnectToServerFlag) { try { iRecv = rpClient.ReceiveBytes(ref byteArray); if (iRecv==0) continue; ulClientRecvByteCounter = ulClientRecvByteCounter + (ulong)iRecv; // Request Write Lock _rwlock.AcquireWriterLock(500); for (i = 0; i < iRecv; i++) { qClient.Enqueue(byteArray[i]); ulClientRecvEnqueueCounter++; } _rwlock.ReleaseWriterLock(); } catch (Exception ex) { //_rwlock.ReleaseWriterLock(); MessageBox.Show("RecvMsgThread Error:"+ex.Message+"!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } /*finally { // Release Write Lock _rwlock.ReleaseWriterLock(); } */ } } private ulong ClientRecvByteCounter = 0; private delegate void ClientRecvByteCntDelegate(string strCnttext); private void set_txtClientRecvByteCnt(string strCnttext) { if (this.textBox_RecvByteCounter.InvokeRequired) { ClientRecvByteCntDelegate md = new ClientRecvByteCntDelegate(this.set_txtClientRecvByteCnt); this.Invoke(md, new object[] { strCnttext }); } else this.textBox_RecvByteCounter.Text = strCnttext; } public event EventHandler<StrArrEventArgs> clientEvtHandlerPacketReceived; // public void InitAddEvent(EventHandler<StrArrEventArgs> addEvent) { //this.OnAddEvent = addEvent; this.clientEvtHandlerPacketReceived += new EventHandler<StrArrEventArgs>(addEvent); } private void ClientFramePaserThread() { byte[] byteArray = new byte[4096]; //System.Text.Encoding.ASCII.GetBytes(str); int i, iQsize; byte[] ReaderRespFrame = new byte[655350];//bytesToRead]; int ReaderRespLength = 0; int apist; int index = 0; while (bConnectToServerFlag) { try { // try { iQsize = qClient.Count;// Get Current Queue Size if (iQsize == 0) continue; ulClientRecvQueueCounter = ulClientRecvQueueCounter + (ulong)iQsize; _rwlock.AcquireReaderLock(1000); for (i = 0; i < iQsize; i++) { byteArray[i] = (byte)qClient.Dequeue(); ulClientRecvDequeueCounter++; apist = Commands.ReaderRespFrameParser(Commands.ReaderDeviceAddr, byteArray[i]); if (apist == 0x00) { ReaderRespFrame = DataConvert.StructToBytes(Commands.ReaderRespFramePacket); ReaderRespLength = (int)(ReaderRespFrame[3] + 3); string[] array3 = new string[ReaderRespLength + 1L]; for (index = 0; index < ReaderRespLength; index++) { array3[index] = ReaderRespFrame[index].ToString("X2"); } iQsize = 0;// this.clientEvtHandlerPacketReceived(this, new StrArrEventArgs(array3)); // Generate a receive Event Handler } } ClientRecvByteCounter = ClientRecvByteCounter + (ulong)iQsize; set_txtClientRecvByteCnt(ClientRecvByteCounter.ToString()); _rwlock.ReleaseReaderLock(); } catch (Exception ex) { //_rwlock.ReleaseWriterLock(); MessageBox.Show("Frame Parser Error:" + ex.Message + "!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } /*finally { _rwlock.ReleaseReaderLock(); }*/ } catch (ApplicationException) // 如果请求读锁失败 { Console.WriteLine("Paser Error!"); } } } #endregion // ///////////////////////////////////////////////// #region Data PacketRecive Process; //----------------------------------------- private void rp_PaketReceived(object sender, StrArrEventArgs e) { string[] packetRx = e.Data; string strPacket = string.Empty; for (int i = 0; i < packetRx.Length; i++) { strPacket += packetRx[i] + " "; } this.Invoke((EventHandler)(delegate { txtCOMRxCnt.Text = (Convert.ToInt32(txtCOMRxCnt.Text) + packetRx.Length).ToString(); txtCOMRxCnt_adv.Text = txtCOMRxCnt.Text; //auto clear received data region int txtReceive_len = txtReceive.Lines.Length; //txtReceive.GetLineFromCharIndex(txtReceive.Text.Length + 1); if (cbxAutoClear.Checked) { if (txtReceive_len > 9) { txtReceive.Text = string.Empty; } } //-------------------------------------------------- int dis; //int packetRxLen = Marshal.SizeOf(Commands.ReaderRespFramePacket);//Convert.ToInt16(packetRx[3],10); byte[] packetRxHex = new byte[256];//packetRxLen]; packetRxHex = DataConvert.GetHexBytes(strPacket, out dis); Commands.ReaderResponseFrameString rxStrPkts = new Commands.ReaderResponseFrameString(true); rxStrPkts = Commands.GetReaderResponsFrameStringStructFromHexBuffer(packetRxHex); //Commands.ReaderResponseFrame RdRecv = (Commands.ReaderResponseFrame)RFID_Reader_Cmds.DataConvert.BytesToStruct(packetRxHex, Commands.ReaderRespFramePacket.GetType()); //---------------------------------------------------- if (rxStrPkts.strStatus == ConstCode.FAIL_OK) { rp_PaketOK(rxStrPkts); } else {// rxStrPkts.strStatus rp_PacketFail(rxStrPkts.strStatus, rxStrPkts.strLength, rxStrPkts.strParameters); if (rxStrPkts.strCmdH == ConstCode.CMD_SENSORTAG_READ) { SensorTag_MessageProcessFailed(rxStrPkts); } } if (cbxRxVisable.Checked == true) { this.txtReceive.Text = this.txtReceive.Text + strPacket + "\r\n"; } #if TRACE //Console.WriteLine("a packet received!"); #endif })); } //--------------------------------- private void rp_PaketOK(Commands.ReaderResponseFrameString rxStrPkts) { setStatus("", Color.MediumSeaGreen); if (rxStrPkts.strCmdH == ConstCode.CMD_EXE_FAILED) { } else if (rxStrPkts.strCmdH == ConstCode.CMD_SET_QUERY_PARA) //SetQuery { MessageBox.Show("Query Parameters has set up", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (rxStrPkts.strCmdH == ConstCode.CMD_GET_QUERY_PARA) //GetQuery { string infoGetQuery = string.Empty; string[] strMSB = String16toString2(rxStrPkts.strParameters[0]); string[] strLSB = String16toString2(rxStrPkts.strParameters[1]); int intQ = Convert.ToInt32(strLSB[6]) * 8 + Convert.ToInt32(strLSB[5]) * 4 + Convert.ToInt32(strLSB[4]) * 2 + Convert.ToInt32(strLSB[3]); string strM = string.Empty; if ((strMSB[6] + strMSB[5]) == "00") { strM = "1"; } else if ((strMSB[6] + strMSB[5]) == "01") { strM = "2"; } else if ((strMSB[6] + strMSB[5]) == "10") { strM = "4"; } else if ((strMSB[6] + strMSB[5]) == "11") { strM = "8"; } string strTRext = string.Empty; if (strMSB[4] == "0") { strTRext = "NoPilot"; } else { strTRext = "UsePilot"; } string strTarget = string.Empty; if (strLSB[7] == "0") { strTarget = "A"; } else { strTarget = "B"; } infoGetQuery = "DR=" + strMSB[7] + ", "; infoGetQuery = infoGetQuery + "M=" + strM + ", "; infoGetQuery = infoGetQuery + "TRext=" + strTRext + ", "; infoGetQuery = infoGetQuery + "Sel=" + strMSB[3] + strMSB[2] + ", "; infoGetQuery = infoGetQuery + "Session=" + strMSB[1] + strMSB[0] + ", "; infoGetQuery = infoGetQuery + "Target=" + strTarget + ", "; infoGetQuery = infoGetQuery + "Q=" + intQ; MessageBox.Show(infoGetQuery, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (rxStrPkts.strCmdH == ConstCode.CMD_INVENTORY || rxStrPkts.strCmdH == ConstCode.CMD_MULTI_ID) //Succeed to Read EPC { //Console.Beep(); SucessEPCNum = SucessEPCNum + 1; db_errEPCNum = FailEPCNum; db_LoopNum_cnt = db_LoopNum_cnt + 1; errnum = (db_errEPCNum / db_LoopNum_cnt) * 100; per = string.Format("{0:0.000}", errnum); int rssidBm = Convert.ToInt16(rxStrPkts.strParameters[0], 16); // rssidBm is negative && in bytes if (rssidBm > 127) { rssidBm = -((-rssidBm) & 0xFF); } rssidBm = rssidBm - (-10);//Hardware compensation. rssidBm -= Convert.ToInt32(tbxCoupling.Text, 10); rssidBm = rssidBm - (3); // rssidBm -= Convert.ToInt32(tbxAntennaGain.Text, 10); rssi = rssidBm.ToString(); int PCEPCLength = ((Convert.ToInt32((rxStrPkts.strParameters[1]), 16)) / 8 + 1) * 2; pc = rxStrPkts.strParameters[1] + " " + rxStrPkts.strParameters[2]; epc = string.Empty; for (int i = 0; i < PCEPCLength - 2; i++) { epc = epc + rxStrPkts.strParameters[3 + i]; } epc = Commands.AutoAddSpace(epc); crc = rxStrPkts.strParameters[1 + PCEPCLength] + " " + rxStrPkts.strParameters[2 + PCEPCLength]; antno = rxStrPkts.strParameters[3 + PCEPCLength]; if (bSensorTag_InventoryFlag == false) GetEPC(pc, epc, crc, rssi, antno, per); else SensorTag_GetEPC(pc, epc, crc, rssi, per); }// else if (rxStrPkts.strCmdH == ConstCode.CMD_STOP_MULTI) // { string strStatus = rxStrPkts.strParameters[0] + rxStrPkts.strParameters[1] + rxStrPkts.strParameters[2] + rxStrPkts.strParameters[3]; string strStatus1 = DataConvert.HexToDec(strStatus); int ReadTagNumber = Convert.ToInt32(strStatus1); this.btnInvtMulti.UseVisualStyleBackColor = true;//2019-04-18 setStatus("Stop Read Multi-Tag!", Color.MediumSeaGreen); setToolStripStatusMessage2("Tag Counter:" + ReadTagNumber.ToString(), Color.MediumBlue); } else if (rxStrPkts.strCmdH == ConstCode.CMD_READ_DATA) //Read Tag Memory { string strInvtReadData = ""; txtInvtRWData.Text = ""; txtOperateEpc.Text = ""; int dataLen = Convert.ToInt32(rxStrPkts.strLength, 16); int pcEpcLen = Convert.ToInt32(rxStrPkts.strParameters[0], 16); for (int i = 0; i < pcEpcLen; i++) { txtOperateEpc.Text += rxStrPkts.strParameters[i + 1] + " "; } //for (int i = 0; i < dataLen - pcEpcLen - 1; i++) dataLen = dataLen - 6; dataLen = dataLen - pcEpcLen; dataLen = dataLen - 2;// -1; for (int i = 0; i < dataLen; i++) { strInvtReadData = strInvtReadData + rxStrPkts.strParameters[i + pcEpcLen + 1]; } txtInvtRWData.Text = Commands.AutoAddSpace(strInvtReadData); setStatus("Read Memory Success:" + txtInvtRWData.Text, Color.MediumSeaGreen); } /* doing...... else if (rxStrPkts.strCmdH == ConstCode.CMD_RFM_TAG) //Read RFM Tag Memory SureLion { setStatus("Read RFM Memory Success", Color.MediumSeaGreen); } * */ else if (rxStrPkts.strCmdH == ConstCode.CMD_SENSORTAG_READ) // Read Sensor Tag //SureLion { SensorTag_MessageProcessOK(rxStrPkts); //setToolStripStatusMessage1("Readed a Sensor Tag! ", Color.MediumSeaGreen); } else if (rxStrPkts.strCmdH == ConstCode.CMD_WRITE_DATA) { //MessageBox.Show("Write Memory Success!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); getSuccessTagEpc(rxStrPkts.strParameters); setStatus("Write Memory Success:" + txtInvtRWData.Text, Color.MediumSeaGreen); } else if (rxStrPkts.strCmdH == ConstCode.CMD_LOCK_UNLOCK) { //MessageBox.Show("Lock Success!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); getSuccessTagEpc(rxStrPkts.strParameters); setStatus("Lock Success", Color.MediumSeaGreen); } else if (rxStrPkts.strCmdH == ConstCode.CMD_KILL) { //MessageBox.Show("Kill Success!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); getSuccessTagEpc(rxStrPkts.strParameters); setStatus("Kill Success", Color.MediumSeaGreen); } /* else if (rxStrPkts.strCmdH == ConstCode.CMD_NXP_CHANGE_CONFIG) { int pcEpcLen = getSuccessTagEpc(rxStrPkts.strParameters); string configWord = rxStrPkts.strParameters[pcEpcLen + 1] + rxStrPkts.strParameters[pcEpcLen + 2]; setStatus("NXP Tag Change Config Success, Config Word: 0x" + configWord, Color.MediumSeaGreen); } else if (rxStrPkts.strCmdH == ConstCode.CMD_NXP_CHANGE_EAS) { getSuccessTagEpc(rxStrPkts.strParameters); setStatus("NXP Tag Change EAS Success", Color.MediumSeaGreen); } else if (rxStrPkts.strCmdH == ConstCode.CMD_NXP_READPROTECT) { getSuccessTagEpc(rxStrPkts.strParameters); setStatus("NXP Tag ReadProtect Success", Color.MediumSeaGreen); } else if (rxStrPkts.strCmdH == ConstCode.CMD_NXP_RESET_READPROTECT) { getSuccessTagEpc(rxStrPkts.strParameters); setStatus("NXP Tag Reset ReadProtect Success", Color.MediumSeaGreen); } else if (rxStrPkts.strCmdH == ConstCode.CMD_NXP_EAS_ALARM) { setStatus("NXP Tag EAS Alarm Success", Color.MediumSeaGreen); } else if (rxStrPkts.strCmdH == ConstCode.CMD_IPJ_MONZA_QT_READ) // Monza tag QT Read command response { int pcEpcLen = getSuccessTagEpc(rxStrPkts.strParameters); string QTcontrol = rxStrPkts.strParameters[pcEpcLen + 1] + rxStrPkts.strParameters[pcEpcLen + 2]; int controlWord = Convert.ToUInt16(QTcontrol, 16); string QT_SR = ((controlWord & 0x8000) == 0) ? "0" : "1"; string QT_MEM = ((controlWord & 0x4000) == 0) ? "0" : "1"; setStatus("QT Read Success, QT Control Word: 0x" + QTcontrol + ", QT_SR=" + QT_SR + ", QT_MEM=" + QT_MEM, Color.MediumSeaGreen); } else if (rxStrPkts.strCmdH == ConstCode.CMD_IPJ_MONZA_QT_WRITE) // Monza tag QT Write command response { getSuccessTagEpc(rxStrPkts.strParameters); setStatus("QT Write Success", Color.MediumSeaGreen); }*/ else if (rxStrPkts.strCmdH == ConstCode.CMD_GET_SELECT_PARA) //GetQuery { string infoGetSelParam = string.Empty; string[] strSelCombParam = String16toString2(rxStrPkts.strParameters[0]); string strSelTarget = strSelCombParam[7] + strSelCombParam[6] + strSelCombParam[5]; string strSelAction = strSelCombParam[4] + strSelCombParam[3] + strSelCombParam[2]; string strSelMemBank = strSelCombParam[1] + strSelCombParam[0]; string strSelTargetInfo = null; if (strSelTarget == "000") { strSelTargetInfo = "S0"; } else if (strSelTarget == "001") { strSelTargetInfo = "S1"; } else if (strSelTarget == "010") { strSelTargetInfo = "S2"; } else if (strSelTarget == "011") { strSelTargetInfo = "S3"; } else if (strSelTarget == "100") { strSelTargetInfo = "SL"; } else { strSelTargetInfo = "RFU"; } string strSelMemBankInfo = null; if (strSelMemBank == "00") { strSelMemBankInfo = "RFU"; } else if (strSelMemBank == "01") { strSelMemBankInfo = "EPC"; } else if (strSelMemBank == "10") { strSelMemBankInfo = "TID"; } else { strSelMemBankInfo = "User"; } infoGetSelParam = "Target=" + strSelTargetInfo + ", Action=" + strSelAction + ", Memory Bank=" + strSelMemBankInfo; infoGetSelParam = infoGetSelParam + ", Pointer=0x" + rxStrPkts.strParameters[1] + rxStrPkts.strParameters[2] + rxStrPkts.strParameters[3] + rxStrPkts.strParameters[4]; infoGetSelParam = infoGetSelParam + ", Length=0x" + rxStrPkts.strParameters[5]; string strTruncate = null; if (rxStrPkts.strParameters[6] == "00") { strTruncate = "Disable Truncation"; } else { strTruncate = "Enable Truncation"; } infoGetSelParam = infoGetSelParam + ", " + strTruncate; this.txtGetSelLength.Text = rxStrPkts.strParameters[5]; string strGetSelMask = null; int intGetSelMaskByte = Convert.ToInt32(rxStrPkts.strParameters[5], 16) / 8; int intGetSelMaskBit = Convert.ToInt32(rxStrPkts.strParameters[5], 16) - intGetSelMaskByte * 8; if (intGetSelMaskBit == 0) { for (int i = 0; i < intGetSelMaskByte; i++) { strGetSelMask = strGetSelMask + rxStrPkts.strParameters[7 + i]; } } else { for (int i = 0; i < intGetSelMaskByte + 1; i++) { strGetSelMask = strGetSelMask + rxStrPkts.strParameters[7 + i]; } } this.txtGetSelMask.Text = Commands.AutoAddSpace(strGetSelMask); MessageBox.Show(infoGetSelParam, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (rxStrPkts.strCmdH == ConstCode.CMD_SET_REGION) { curRegion = GetRegionValueFromUI(cbxRegion.SelectedIndex); ChangedRFchannelTableFromFreqRegion(cbxRegion.SelectedIndex); setToolStripStatusMessage1("Set RF Region Successed!", Color.Purple); } else if (rxStrPkts.strCmdH == ConstCode.CMD_GET_REGION) { //2019-04-18 /*cbxRegion.SelectedIndex = Convert.ToInt32(rxStrPkts.strParameters[0], 16); curRegion = GetRegionValueFromUI(cbxRegion.SelectedIndex); ChangedRFchannelTableFromFreqRegion(cbxRegion.SelectedIndex); setToolStripStatusMessage1("Get RF Region Successed!", Color.Purple);*/ string strRegion = ""; int iRFregionIndex = Convert.ToInt32(rxStrPkts.strParameters[0], 16); //curRegion = GetRegionValueFromUI(iRFregionIndex); BUG!!!! curRegion = rxStrPkts.strParameters[0]; switch (iRFregionIndex) { case 1: // China 2 cbxRegion.SelectedIndex = 0; strRegion = "China2"; break; case 4: // China 1 cbxRegion.SelectedIndex = 1; //2019-04-18 strRegion = "China1"; break; case 2: // US cbxRegion.SelectedIndex = 2; strRegion = "US"; break; case 3: // Europe cbxRegion.SelectedIndex = 3; strRegion = "Europe"; break; case 6: // Korea cbxRegion.SelectedIndex = 4; strRegion = "Korea"; break; default: cbxRegion.SelectedIndex = 0; strRegion = "Unknow"; break; } //OR switch (rxStrPkts.strParameters[0]) { case ConstCode.REGION_CODE_CHN2: // China 2 cbxRegion.SelectedIndex = 0; strRegion = "China2"; break; case ConstCode.REGION_CODE_CHN1: // China 1 cbxRegion.SelectedIndex = 1; //2019-04-18 strRegion = "China1"; break; case ConstCode.REGION_CODE_US: // US cbxRegion.SelectedIndex = 2; strRegion = "US"; break; case ConstCode.REGION_CODE_EUR: // Europe cbxRegion.SelectedIndex = 3; strRegion = "Europe"; break; case ConstCode.REGION_CODE_KOREA: // Korea cbxRegion.SelectedIndex = 4; strRegion = "Korea"; break; default: cbxRegion.SelectedIndex = 0; strRegion = "Unknow"; break; } ChangedRFchannelTableFromFreqRegion(cbxRegion.SelectedIndex); setToolStripStatusMessage1("Get RF Region Successed! {Index=" + rxStrPkts.strParameters[0] + "-" + strRegion + "}", Color.Purple); } else if (rxStrPkts.strCmdH == ConstCode.CMD_SET_RF_CHANNEL) { setToolStripStatusMessage1("Set RF Channel Successed!", Color.Purple); } else if (rxStrPkts.strCmdH == ConstCode.CMD_GET_RF_CHANNEL) { double curRfChIndex = Convert.ToInt32(rxStrPkts.strParameters[0], 16); double curRfCh; switch (curRegion) { case ConstCode.REGION_CODE_CHN2: // China 2 curRfCh = 920.125 + curRfChIndex * 0.25; break; case ConstCode.REGION_CODE_CHN1: // China 1 curRfCh = 840.125 + curRfChIndex * 0.25; break; case ConstCode.REGION_CODE_US: // US curRfCh = 902.25 + curRfChIndex * 0.5; break; case ConstCode.REGION_CODE_EUR: // Europe curRfCh = 865.1 + curRfChIndex * 0.2; break; case ConstCode.REGION_CODE_KOREA: // Korea curRfCh = 917.1 + curRfChIndex * 0.2; break; default: curRfCh = 0.0; break; } cbxChannel.SelectedIndex = (int)curRfChIndex; //MessageBox.Show("Current RF Channel is " + curRfCh + " MHz", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); setToolStripStatusMessage1("Current RF Channel is " + curRfCh + " MHz", Color.Purple); } else if (rxStrPkts.strCmdH == ConstCode.CMD_SET_FHSS) { //2019-01-26 string strFh; if (rxStrPkts.strCmdL == "00") { if (rxStrPkts.strParameters[0] == ConstCode.SET_OFF) setToolStripStatusMessage1("Set RF FHSS On/Off Successed! (FHSS Off)", Color.Purple); else setToolStripStatusMessage1("Set RF FHSS On/Off Successed! (FHSS On)", Color.Purple); } else if (rxStrPkts.strCmdL == "01") { if (rxStrPkts.strParameters[0] == ConstCode.SET_OFF) { setToolStripStatusMessage1("Get RF FHSS On/Off Successed! (FHSS Off)", Color.Purple); cbxFHSS.SelectedIndex = 0; } else { setToolStripStatusMessage1("Get RF FHSS On/Off Successed! (FHSS On)", Color.Purple); cbxFHSS.SelectedIndex = 1; } } else if (rxStrPkts.strCmdL == "02") { //Set Freqency Hopping Period strFh = rxStrPkts.strParameters[0] + rxStrPkts.strParameters[1]; uint nFh = Convert.ToUInt16(strFh, 16); cbxFhssHopPeriod.SelectedIndex = (int)(nFh / 100)-1; //100mS strFh = string.Format("{0:D}mS", nFh); setToolStripStatusMessage1("Set RF FHSS Period Successed! " + strFh, Color.Purple); } else if (rxStrPkts.strCmdL == "03") { //Get Freqency Hopping Period strFh = rxStrPkts.strParameters[0] + rxStrPkts.strParameters[1]; uint nFh = Convert.ToUInt16(strFh, 16); cbxFhssHopPeriod.SelectedIndex = (int)(nFh / 100) - 1; //100mS strFh = string.Format("{0:D}mS", nFh); setToolStripStatusMessage1("Get RF FHSS Period Successed! " + strFh, Color.Purple); } } else if (rxStrPkts.strCmdH == ConstCode.CMD_INSERT_FHSS_CHANNEL) { //setToolStripStatusMessage1("Set Current RF Power is OK!", Color.Purple); if (rxStrPkts.strCmdL == "00") { setToolStripStatusMessage1("Insert RF channel in the current range of RF region is OK! ", Color.Purple); } else if (rxStrPkts.strCmdL == "01") { uint RFchnlInrNum = Convert.ToUInt16(rxStrPkts.strParameters[0], 16); uint RFchnlBegin = Convert.ToUInt16(rxStrPkts.strParameters[1], 16); uint RFchnlEnd = RFchnlBegin + RFchnlInrNum - 1; txtChIndexBegin.Text = RFchnlBegin.ToString(); txtChIndexEnd.Text = RFchnlEnd.ToString(); string strInformation = "Get Insert RF Channel frome: " + txtChIndexBegin.Text + " To " + txtChIndexEnd.Text + " !"; //strInformation = strInformation + " (Set 'RF Region' will cancel this funciton!)"; setToolStripStatusMessage1(strInformation, Color.Purple); } } else if (rxStrPkts.strCmdH == ConstCode.CMD_SET_POWER) { setToolStripStatusMessage1("Set Current RF Power is OK!", Color.Purple); } else if (rxStrPkts.strCmdH == ConstCode.CMD_GET_POWER) { int rfpwrSel; string curPower = rxStrPkts.strParameters[0] + rxStrPkts.strParameters[1]; //MessageBox.Show("Current Power is " + (Convert.ToInt16(curPower, 16) / 100.0) + "dBm", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); rfpwrSel = (int)(Convert.ToInt16(curPower, 16) / 100.0); cbxPaPower.SelectedIndex = 30 - rfpwrSel; setToolStripStatusMessage1("Current Power is " + (Convert.ToInt16(curPower, 16) / 100.0) + "dBm!", Color.Purple); } else if (rxStrPkts.strCmdH == ConstCode.CMD_ANT) { AntResponseMessageProcess(rxStrPkts); } /* else if (rxStrPkts.strCmdH == ConstCode.CMD_READ_MODEM_PARA) { int mixerGain = mixerGainTable[Convert.ToInt32(rxStrPkts.strParameters[0], 16)]; int IFAmpGain = IFAmpGainTable[Convert.ToInt32(rxStrPkts.strParameters[1], 16)]; string signalTh = rxStrPkts.strParameters[2] + rxStrPkts.strParameters[3]; MessageBox.Show("Mixer Gain is " + mixerGain + "dB, IF AMP Gain is " + IFAmpGain + "dB, Decode Threshold is 0x" + signalTh + ".", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (rxStrPkts.strCmdH == ConstCode.CMD_SCAN_JAMMER) { int startChannel = Convert.ToInt16(rxStrPkts.strParameters[0], 16); int stopChannel = Convert.ToInt16(rxStrPkts.strParameters[1], 16); hBarChartJammer.Items.Maximum = 40; hBarChartJammer.Items.Minimum = 0; hBarChartJammer.Items.Clear(); int[] allJammer = new int[(stopChannel - startChannel + 1)]; int maxJammer = -100; int minJammer = 20; for (int i = 0; i < (stopChannel - startChannel + 1); i++) { int jammer = Convert.ToInt16(rxStrPkts.strParameters[2 + i], 16); if (jammer > 127) { jammer = -((-jammer) & 0xFF); } allJammer[i] = jammer; if (jammer >= maxJammer) { maxJammer = jammer; } if (jammer <= minJammer) { minJammer = jammer; } } int offset = -minJammer + 3; for (int i = 0; i < (stopChannel - startChannel + 1); i++) { allJammer[i] = allJammer[i] + offset; hBarChartJammer.Items.Add(new HBarItem((double)(allJammer[i]), (double)offset, (i + startChannel).ToString(), Color.FromArgb(255, 190, 200, 255))); } hBarChartJammer.RedrawChart(); } else if (rxStrPkts.strCmdH == ConstCode.CMD_SCAN_RSSI) { int startChannel = Convert.ToInt16(rxStrPkts.strParameters[0], 16); int stopChannel = Convert.ToInt16(rxStrPkts.strParameters[1], 16); hBarChartRssi.Items.Maximum = 73; hBarChartRssi.Items.Minimum = 0; hBarChartRssi.Items.Clear(); int[] allRssi = new int[(stopChannel - startChannel + 1)]; int maxRssi = -100; int minRssi = 20; for (int i = 0; i < (stopChannel - startChannel + 1); i++) { int rssi = Convert.ToInt16(rxStrPkts.strParameters[2 + i], 16); if (rssi > 127) { rssi = -((-rssi) & 0xFF); } allRssi[i] = rssi; if (rssi >= maxRssi) { maxRssi = rssi; } if (rssi <= minRssi) { minRssi = rssi; } } int offset = -minRssi + 3; for (int i = 0; i < (stopChannel - startChannel + 1); i++) { allRssi[i] = allRssi[i] + offset; hBarChartRssi.Items.Add(new HBarItem((double)(allRssi[i]), (double)offset, (i + startChannel).ToString(), Color.FromArgb(255, 190, 200, 255))); } hBarChartRssi.RedrawChart(); }*/ else if (rxStrPkts.strCmdH == ConstCode.CMD_GET_MODULE_INFO) { if (checkingReaderAvailable) { if (rxStrPkts.strParameters[0] == ConstCode.MODULE_HARDWARE_VERSION_FIELD) { hardwareVersion = String.Empty; try { for (int i = 0; i < Convert.ToInt32(rxStrPkts.strLength, 16) - 1; i++) { hardwareVersion += (char)Convert.ToInt32(rxStrPkts.strParameters[1 + i], 16); } txtHardwareVersion.Text = hardwareVersion; //adjustUIcomponents(hardwareVersion); getFirmwareVersion(); } catch (System.Exception ex) { hardwareVersion = rxStrPkts.strParameters[1].Substring(1, 1) + "." + rxStrPkts.strParameters[2]; txtHardwareVersion.Text = hardwareVersion; Console.WriteLine(ex.Message); } } else if (rxStrPkts.strParameters[0] == ConstCode.MODULE_SOFTWARE_VERSION_FIELD) { String firmwareVersion = string.Empty; try { for (int i = 0; i < Convert.ToInt32(rxStrPkts.strLength, 16) - 1; i++) { firmwareVersion += (char)Convert.ToInt32(rxStrPkts.strParameters[1 + i], 16); } txtFirmwareVersion.Text = firmwareVersion; } catch (System.Exception ex) { txtFirmwareVersion.Text = ""; Console.WriteLine(ex.Message); } } } if (rxStrPkts.strCmdL == ConstCode.MODULE_FIRMWARE_VERSION_SUBCMD) { string HWMajorVer, HWMinorVer, SWMajorVer, SWMinorVer; HWMajorVer = rxStrPkts.strParameters[0]; HWMinorVer = rxStrPkts.strParameters[1]; SWMajorVer = rxStrPkts.strParameters[2]; SWMinorVer = rxStrPkts.strParameters[3]; setToolStripStatusMessage2("Module Firmware Version: " + HWMajorVer + "." + HWMinorVer + "." + SWMajorVer + "." + SWMinorVer + "!", Color.Purple); } } else if (rxStrPkts.strCmdH == ConstCode.CMD_READER_FIRMWARE) { string HWMajorVer, HWMinorVer, SWMajorVer, SWMinorVer; HWMajorVer = rxStrPkts.strParameters[0]; HWMinorVer = rxStrPkts.strParameters[1]; SWMajorVer = rxStrPkts.strParameters[2]; SWMinorVer = rxStrPkts.strParameters[3]; setToolStripStatusMessage1("Reader Firmware Version: " + HWMajorVer + "." + HWMinorVer + "." + SWMajorVer + "." + SWMinorVer + "!", Color.Purple); } else if (rxStrPkts.strCmdH == ConstCode.CMD_IO_CONTROL)//"1A") { /*if (rxStrPkts.strParameters[0] == "02") { MessageBox.Show("IO" + rxStrPkts.strParameters[1].Substring(1) + " is " + (rxStrPkts.strParameters[2] == "00" ? "Low" : "High"), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); }*/ byte IoStatus = 0, st; switch (rxStrPkts.strCmdL) { case ConstCode.READER_OPERATION_SET://"00": setToolStripStatusMessage1("GPO Set OK! " + rxStrPkts.strParameters[0], Color.Purple); break; case ConstCode.READER_OPERATION_GET://"01": IoStatus = Convert.ToByte(rxStrPkts.strParameters[0],16); st =(byte)( IoStatus & 0x01); if(st!=0) checkBox_GPO1.Checked =true; else checkBox_GPO1.Checked = false; st =(byte)( IoStatus>>1 & 0x01); if(st!=0) checkBox_GPO2.Checked =true; else checkBox_GPO2.Checked = false; st =(byte)( IoStatus>>2 & 0x01); if(st!=0) checkBox_GPO3.Checked =true; else checkBox_GPO3.Checked = false; st =(byte)( IoStatus>>3 & 0x01); if(st!=0) checkBox_GPO4.Checked =true; else checkBox_GPO4.Checked = false; setToolStripStatusMessage1("GPO Get status : " + rxStrPkts.strParameters[0], Color.Purple); break; case "03": IoStatus = Convert.ToByte(rxStrPkts.strParameters[0]); st =(byte)( IoStatus & 0x01); if(st!=0) checkBox_GPI1.Checked =true; else checkBox_GPI1.Checked = false; st =(byte)( IoStatus>>1 & 0x01); if(st!=0) checkBox_GPI2.Checked =true; else checkBox_GPI2.Checked = false; st =(byte)( IoStatus>>2 & 0x01); if(st!=0) checkBox_GPI3.Checked =true; else checkBox_GPI3.Checked = false; st =(byte)( IoStatus>>3 & 0x01); if(st!=0) checkBox_GPI4.Checked =true; else checkBox_GPI4.Checked = false; setToolStripStatusMessage1("GPI Get status : " + rxStrPkts.strParameters[0], Color.Purple); break; default: break; } } else if (rxStrPkts.strCmdH == ConstCode.CMD_READ_ADDR) //SureLion { string str10devAddr = DataConvert.HexToDec(rxStrPkts.strParameters[0]); int devAddr = Convert.ToInt32(str10devAddr); string strdevAddr = devAddr.ToString("D03"); if (rxStrPkts.strCmdL == ConstCode.READER_OPERATION_SET) { cbxDeviceAddr.SelectedIndex = devAddr; ReaderDeviceAddress = (byte)devAddr;// Set to the Reader's Device 锛燂紵锛? MessageBox.Show("Set Reader to new Device Address: " + strdevAddr, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); setToolStripStatusMessage1("Set new Reader's Device Address: " + strdevAddr, Color.MediumSeaGreen); } else if (rxStrPkts.strCmdL == ConstCode.READER_OPERATION_GET) { cbxDeviceAddr.SelectedIndex = devAddr; ReaderDeviceAddress = (byte)devAddr;// Set to the Reader's Device //ReaderDeviceAddress = (byte)cbxDeviceAddr.SelectedIndex; Commands.ReaderDeviceAddr = ReaderDeviceAddress; //MessageBox.Show("Get Reader's Device Address: " + strdevAddr, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); setToolStripStatusMessage1("Get Reader's Device Address: " + strdevAddr, Color.MediumSeaGreen); } } } #region rp_PacketFail private string ParseErrCode(int errorCode) { switch (errorCode & 0x0F) { case ConstCode.ERROR_CODE_OTHER_ERROR: return "Other Error"; case ConstCode.ERROR_CODE_MEM_OVERRUN: return "Memory Overrun"; case ConstCode.ERROR_CODE_MEM_LOCKED: return "Memory Locked"; case ConstCode.ERROR_CODE_INSUFFICIENT_POWER: return "Insufficient Power"; case ConstCode.ERROR_CODE_NON_SPEC_ERROR: return "Non-specific Error"; default: return "Non-specific Error"; } } private void rp_PacketFail(string FailCode, string rxstrLen, string[] strParam) { int failType = Convert.ToInt32(FailCode, 16); int rxlen = Convert.ToInt32(rxstrLen, 16); /*if (rxlen > 7) // has PC+EPC field { txtOperateEpc.Text = ""; int pcEpcLen = Convert.ToInt32(strParam[0], 16); for (int i = 0; i < pcEpcLen; i++) { txtOperateEpc.Text += strParam[i + 1] + " "; } } else { txtOperateEpc.Text = ""; }*/ if (FailCode == ConstCode.FAIL_INVENTORY_TAG_TIMEOUT) { FailEPCNum = FailEPCNum + 1; db_errEPCNum = FailEPCNum; db_LoopNum_cnt = db_LoopNum_cnt + 1; errnum = (db_errEPCNum / db_LoopNum_cnt) * 100; per = string.Format("{0:0.000}", errnum); //GetEPC(pc, epc, crc, rssi_i, rssi_q, per); pbx_Inv_Indicator.Visible = false; } else if (FailCode == ConstCode.FAIL_FHSS_FAIL) { //MessageBox.Show("FHSS Failed.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("FHSS Failed", Color.Red); } else if (FailCode == ConstCode.FAIL_ANT_NOT_AVAILABLE) { //MessageBox.Show("FHSS Failed.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("Switch Antenna Port Failed! Please check the Antenna Setting.", Color.Red); } else if (FailCode == ConstCode.FAIL_ACCESS_PWD_ERROR) { //MessageBox.Show("Access Failed, Please Check the Access Password!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("Access Failed, Please Check the Access Password", Color.Red); } else if (FailCode == ConstCode.FAIL_READ_MEMORY_NO_TAG) { setStatus("No Tag Response, Fail to Read Tag Memory", Color.Red); } else if (FailCode.Substring(0, 1) == ConstCode.FAIL_READ_ERROR_CODE_BASE.Substring(0, 1)) { //MessageBox.Show("Read Failed. Error Code: " + ParseErrCode(failType), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("Read Failed. Error Code: " + ParseErrCode(failType), Color.Red); } else if (FailCode == ConstCode.FAIL_WRITE_MEMORY_NO_TAG) { //MessageBox.Show("No Tag Response, Fail to Write Tag Memory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("No Tag Response, Fail to Write Tag Memory", Color.Red); } else if (FailCode.Substring(0, 1) == ConstCode.FAIL_WRITE_ERROR_CODE_BASE.Substring(0, 1)) { //MessageBox.Show("Write Failed. Error Code: " + ParseErrCode(failType), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("Write Failed. Error Code: " + ParseErrCode(failType), Color.Red); } else if (FailCode == ConstCode.FAIL_LOCK_NO_TAG) { //MessageBox.Show("No Tag Response, Lock Operation Failed", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("No Tag Response, Lock Operation Failed", Color.Red); } else if (FailCode.Substring(0, 1) == ConstCode.FAIL_LOCK_ERROR_CODE_BASE.Substring(0, 1)) { //MessageBox.Show("Lock Failed. Error Code: " + ParseErrCode(failType), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("Lock Failed. Error Code: " + ParseErrCode(failType), Color.Red); } else if (FailCode == ConstCode.FAIL_KILL_NO_TAG) { //MessageBox.Show("No Tag Response, Kill Operation Failed", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("No Tag Response, Kill Operation Failed", Color.Red); } else if (FailCode.Substring(0, 1) == ConstCode.FAIL_KILL_ERROR_CODE_BASE.Substring(0, 1)) { //MessageBox.Show("Kill Failed. Error Code: " + ParseErrCode(failType), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("Kill Failed. Error Code: " + ParseErrCode(failType), Color.Red); } else if (FailCode == ConstCode.FAIL_NXP_CHANGE_CONFIG_NO_TAG) { //MessageBox.Show("No Tag Response, NXP Change Config Failed!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("No Tag Response, NXP Change Config Failed", Color.Red); } else if (FailCode == ConstCode.FAIL_NXP_CHANGE_EAS_NO_TAG) { //MessageBox.Show("No Tag Response, NXP Change EAS Failed!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("No Tag Response, NXP Change EAS Failed", Color.Red); } else if (FailCode == ConstCode.FAIL_NXP_CHANGE_EAS_NOT_SECURE) { //MessageBox.Show("Tag is not in Secure State, NXP Change EAS Failed!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("Tag is not in Secure State, NXP Change EAS Failed", Color.Red); } else if (FailCode == ConstCode.FAIL_NXP_EAS_ALARM_NO_TAG) { //MessageBox.Show("No Tag Response, NXP EAS Alarm Operation Failed!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); //txtOperateEpc.Text = ""; setStatus("No Tag Response, NXP EAS Alarm Operation Failed", Color.Red); } else if (FailCode == ConstCode.FAIL_NXP_READPROTECT_NO_TAG) { //MessageBox.Show("No Tag Response, NXP ReadProtect Failed!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("No Tag Response, NXP ReadProtect Failed", Color.Red); } else if (FailCode == ConstCode.FAIL_NXP_RESET_READPROTECT_NO_TAG) { //MessageBox.Show("No Tag Response, NXP Reset ReadProtect Failed!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("No Tag Response, NXP Reset ReadProtect Failed", Color.Red); } else if (FailCode == "2E") // QT Read/Write Failed { setStatus("No Tag Response, QT Command Failed", Color.Red); } else if (FailCode.Substring(0, 1) == ConstCode.FAIL_CUSTOM_CMD_BASE.Substring(0, 1)) { //MessageBox.Show("Command Executed Failed. Error Code: " + ParseErrCode(failType), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); setStatus("Command Executed Failed. Error Code: " + ParseErrCode(failType), Color.Red); } else if (FailCode == ConstCode.FAIL_INVALID_PARA) { MessageBox.Show("Invalid Parameters", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (FailCode == ConstCode.FAIL_INVALID_CMD) { MessageBox.Show("Invalid Command!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (FailCode == ConstCode.FAIL_SUBCMD_UNDEF) { MessageBox.Show("Invalid Sub Command!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (FailCode == ConstCode.FAIL_MAINCMD_UNDEF) { MessageBox.Show("Invalid Main Command!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (FailCode == ConstCode.FAIL_COMMAND_CRC)//2019-05-10 { setStatus("API command Crc is Error!", Color.Red); } else if (FailCode == ConstCode.FAIL_PARAMETER_FAIL)//2019-05-10 { setStatus("Set or Get Reader Parameter is failed!", Color.Red); } else if (FailCode == ConstCode.FAIL_READER_FAIL)//2019-05-10 { setStatus("Set Reader operation is failed1", Color.Red); } else if (FailCode == ConstCode.FAIL_TAG_FAIL)//2019-05-10 { setStatus("Access Tag operation is failed!", Color.Red); } } #endregion #endregion /// <summary> /// ////////////////////////////////////////////////////////////////////////Send Command Proc /// </summary> #region Send Command Proc public void NetSendCommand(string strCommandFrame) { if (bConnectToServerFlag == true) { rpClient.Send(txtSend.Text); } else { MessageBox.Show("Server has not been connected!!!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } #endregion /// <summary> /// ////////////////////////////////////////////////////////////////////////Interface Operation /// </summary> #region interface operation private void getFirmwareVersion() { //string sendApiString = Commands.RFID_Q_GetModuleInfo(ConstCode.READER_DEVICEADDR_BROADCAST,ConstCode.MODULE_SOFTWARE_VERSION_FIELD); txtSend.Text = Commands.RFID_Q_GetModuleInfo(ReaderDeviceAddress, ConstCode.MODULE_SOFTWARE_VERSION_FIELD); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); Thread.Sleep(5); txtSend.Text = Commands.RFID_Q_GetModuleFirmWare(ReaderDeviceAddress); NetSendCommand(txtSend.Text); //NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); Thread.Sleep(5); txtSend.Text = Commands.RFID_Q_GetReaderFirmWare(ReaderDeviceAddress); NetSendCommand(txtSend.Text); //NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private void GetReaderDeviceAddr() {// If we do not know the current Reader's Device Address, we can use the Broadcast Device Address to get it. txtSend.Text = Commands.RFID_Q_ReaderDeviceAddr(ConstCode.READER_DEVICEADDR_BROADCAST, ConstCode.READER_OPERATION_GET, 0); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private string hardwareVersion; private bool checkingReaderAvailable = false; private bool readerConnected; public void checkReaderAvailable() { if (bConnectToServerFlag==true) { //GetReaderDeviceAddr(); hardwareVersion = ""; checkingReaderAvailable = true; readerConnected = false; //Sp.GetInstance().Send(Commands.RFID_Q_GetModuleInfo(ReaderDeviceAddress,ConstCode.MODULE_HARDWARE_VERSION_FIELD)); txtSend.Text = Commands.RFID_Q_GetModuleInfo(ReaderDeviceAddress, ConstCode.MODULE_HARDWARE_VERSION_FIELD); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); //Sp.GetInstance().Send(Commands.RFID_Q_GetModuleInfo(ConstCode.READER_DEVICEADDR_BROADCAST, ConstCode.MODULE_HARDWARE_VERSION_FIELD)); timerCheckReader.Enabled = true;//if executed System.Timers.Timer.Elapsed Event } } private void timerCheckReader_Tick(object sender, EventArgs e) { timerCheckReader.Enabled = false; if (hardwareVersion == "") { MessageBox.Show("Connect Reader Failed, Please Check if the Com port and the power is OK!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); readerConnected = false; } else { //MessageBox.Show("Connect Success! Hardware version: " + hardwareVersion, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); readerConnected = true; } } private bool bConnectToServerFlag = false; private void button_Connect_Click(object sender, EventArgs e) { rpClient.Connect(textBox_IP.Text, int.Parse(textBox_Port.Text.Trim())); bConnectToServerFlag = true; threadClient = new Thread(ClientRecvMsgThread); threadClient.IsBackground = true; threadClient.Start(); threadFramePaser = new Thread(ClientFramePaserThread); threadFramePaser.IsBackground = true; threadFramePaser.Start(); this.button_Connect.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); button_Connect.Enabled = false; button_Close.Enabled = true; checkReaderAvailable(); } private void button_Close_Click(object sender, EventArgs e) { if (bConnectToServerFlag == true) { rpClient.SocketClose(); bConnectToServerFlag = false; } this.button_Connect.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128))))); button_Connect.Enabled = true; button_Close.Enabled = false; } private void Reset_FW_Click(object sender, EventArgs e) { txtSend.Text = Commands.RFID_Q_ResetReader(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); Thread.Sleep(100); button_Close_Click(null, null); } private void ReaderDeviceAddr_Inital() { int i; for (i = 0; i < 255; i++) { cbxDeviceAddr.Items.Add(i.ToString("D03")); cbxNewDeviceAddr.Items.Add(i.ToString("D03")); } i = 255; cbxDeviceAddr.Items.Add(i.ToString("D03") + " Broadcast"); cbxDeviceAddr.SelectedIndex = 255;//Default to use Broadcast Address to conncect the Reader, if we do not know the Reader's device address. cbxNewDeviceAddr.SelectedIndex = 0; ReaderDeviceAddress = (byte)cbxDeviceAddr.SelectedIndex; Commands.ReaderDeviceAddr = ReaderDeviceAddress; } private void btn_GetReaderDeviceAddr_Click(object sender, EventArgs e) { txtSend.Text = Commands.RFID_Q_ReaderDeviceAddr(ReaderDeviceAddress, ConstCode.READER_OPERATION_GET, cbxDeviceAddr.SelectedIndex); NetSendCommand(txtSend.Text);// Sp.GetInstance().Send(txtSend.Text); } private void btn_SetReaderDeviceAddr_Click(object sender, EventArgs e) { txtSend.Text = Commands.RFID_Q_ReaderDeviceAddr(ReaderDeviceAddress, ConstCode.READER_OPERATION_SET, cbxDeviceAddr.SelectedIndex); NetSendCommand(txtSend.Text);// Sp.GetInstance().Send(txtSend.Text); } private void btnSend_Click(object sender, EventArgs e) { NetSendCommand(txtSend.Text); } #endregion #region Tag Operation private void ReadTagInital() { this.cbx_MTR_Algorithm.SelectedIndex = 2; this.cbx_MTR_Qvalue.SelectedIndex = 5; this.txtRDMultiNum.Text = "0";// "188";//"65535"; } private bool bInventoryGoing = false;// doing the inventory multi-tag... private void btnInvtMulti_Click(object sender, EventArgs e) { bSensorTag_InventoryFlag = false; ulClientRecvByteCounter = 0; ulClientRecvEnqueueCounter = 0; ulClientRecvQueueCounter = 0; ulClientRecvDequeueCounter = 0; //bSensorTag_InventoryFlag = false; int loopCnt = Convert.ToInt32(txtRDMultiNum.Text); txtSend.Text = Commands.RFID_Q_ReadMulti(ReaderDeviceAddress, (byte)cbx_MTR_Algorithm.SelectedIndex, (byte)cbx_MTR_Qvalue.SelectedIndex, loopCnt); NetSendCommand(txtSend.Text);// NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); tmrCheckEpc.Enabled = true; bInventoryGoing = true; this.btnInvtMulti.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128)))));//2019-04-18 ClientRecvByteCounter = 0; textBox_RecvByteCounter.Text = ClientRecvByteCounter.ToString(); } private void btnStopRD_Click(object sender, EventArgs e) { txtSend.Text = Commands.RFID_Q_StopRead(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); Thread.Sleep(200); txtSend.Text = Commands.RFID_Q_StopRead(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); tmrCheckEpc.Enabled = false; bInventoryGoing = false; //this.btnInvtMulti.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); //this.btnInvtMulti.BackColor=SystemColors.Control; this.btnInvtMulti.UseVisualStyleBackColor = true;//2019-04-18 } private void btn_clear_epc1_Click(object sender, EventArgs e) { basic_table.Clear(); advanced_table.Clear(); //LoopNum_cnt = 0; FailEPCNum = 0; SucessEPCNum = 0; db_LoopNum_cnt = 0; for (int i = 0; i <= initDataTableLen - 1; i++) { basic_table.Rows.Add(new object[] { null }); } basic_table.AcceptChanges(); for (int i = 0; i <= initDataTableLen - 1; i++) { advanced_table.Rows.Add(new object[] { null }); } advanced_table.AcceptChanges(); rowIndex = 0; textBox_EPC_TagCounter.Text = "0"; textBox_EPC_Tag_Total.Text = "0"; } private void btn_clear_rx_Click(object sender, EventArgs e) { txtReceive.Text = ""; } private void cbxDeviceAddr_SelectedIndexChanged(object sender, EventArgs e) { ReaderDeviceAddress = (byte)cbxDeviceAddr.SelectedIndex; Commands.ReaderDeviceAddr = ReaderDeviceAddress; } private void button_GPIO_Get_Click(object sender, EventArgs e) { byte IoGpioSt=0; txtSend.Text = Commands.RFID_Q_GPIO_GPO(ReaderDeviceAddress, 0x01, IoGpioSt); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); Thread.Sleep(50); txtSend.Text = Commands.RFID_Q_GPIO_GPI(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private void button_GPIO_Set_Click(object sender, EventArgs e) { byte IoGpioSt = 0; bool gpo1= checkBox_GPO1.Checked; bool gpo2 = checkBox_GPO2.Checked; bool gpo3 = checkBox_GPO3.Checked; bool gpo4 = checkBox_GPO4.Checked; if (gpo1 == true) { IoGpioSt = (byte)(IoGpioSt | (byte)((byte)0x01 << 0)); } if (gpo2 == true) { IoGpioSt = (byte)(IoGpioSt | (byte)((byte)0x01 << 1)); } if (gpo3 == true) { IoGpioSt = (byte)(IoGpioSt | (byte)((byte)0x01 << 2)); } if (gpo4 == true) { IoGpioSt = (byte)(IoGpioSt | (byte)((byte)0x01 << 3)); } txtSend.Text = Commands.RFID_Q_GPIO_GPO(ReaderDeviceAddress, 0x00, IoGpioSt); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } #endregion int lastRecCnt = 0; private void tmrCheckEpc_Tick(object sender, EventArgs e) { if (lastRecCnt == Convert.ToInt32(txtCOMRxCnt.Text)) // no data received during last Tick, it may mean the Read Continue stoped { tmrCheckEpc.Enabled = false; return; } lastRecCnt = Convert.ToInt32(txtCOMRxCnt.Text); DateTime now = System.DateTime.Now; DateTime dt; DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo(); dtFormat.LongDatePattern = timeFormat; int timeout = (10 * tmrCheckEpc.Interval); for (int i = 0; i < this.dgvEpcBasic.Rows.Count; i++) { string time = this.dgvEpcBasic.Rows[i].Cells[7].Value.ToString(); if (null != time && !"".Equals(time)) { //dt = Convert.ToDateTime(time, dtFormat); //dt = DateTime.ParseExact(time, timeFormat, CultureInfo.InvariantCulture); if (DateTime.TryParse(time, out dt)) { TimeSpan sub = now.Subtract(dt); if (sub.TotalMilliseconds > timeout) { this.dgvEpcBasic.Rows[i].DefaultCellStyle.BackColor = Color.Red; } //else if ((sub.TotalMilliseconds > (tmrCheckEpc.Interval + 100))) //{ // this.dgvEpcBasic.Rows[i].DefaultCellStyle.BackColor = Color.Pink; //} else { int r = 0xFF & (int)(sub.TotalMilliseconds / timeout * 255); //this.dgvEpcBasic.Rows[i].DefaultCellStyle.BackColor = Color.White; this.dgvEpcBasic.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(0xff, 255 - r, 255 - r); } } } } } private void timer1_Tick(object sender, EventArgs e) { this.toolStripStatusLabel3.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); } private void btnClearCnt_Click(object sender, EventArgs e) { txtCOMRxCnt.Text = "0"; txtCOMTxCnt.Text = "0"; } #region System Setting private void SystemSettingInital() { this.cbxMode.SelectedIndex = 0; this.cbxRegion.SelectedIndex = 0; this.cbxChannel.SelectedIndex = 0; //------------------------------------ this.cbxPaPower.Items.Clear(); for (int i = 30; i >= 0; i--) { this.cbxPaPower.Items.Add(i.ToString() + "dBm"); } this.cbxPaPower.SelectedIndex = 0; //------------------------------------ this.comboBox_RF_AntPort_Quantity.SelectedIndex = 0; Ant_Inital(); } private const int _ANT_Max_Quantity_ = 8; private Commands.AntWorkParamStruct Ant = new Commands.AntWorkParamStruct(true); private CheckBox[] AntEnableBitCheck = new CheckBox[_ANT_Max_Quantity_]; private RadioButton[] AntPortRb = new RadioButton[_ANT_Max_Quantity_]; private ComboBox[] AntRfPowerCmb = new ComboBox[_ANT_Max_Quantity_]; private TextBox[] AntPollingCountTxt = new TextBox[_ANT_Max_Quantity_]; private bool bAnt_InitalFlag = false; private void Ant_Inital() { this.comboBoxRF_AntPort_Port1.SelectedIndex = 0; this.comboBoxRF_AntPort_Port2.SelectedIndex = 0; this.comboBoxRF_AntPort_Port3.SelectedIndex = 0; this.comboBoxRF_AntPort_Port4.SelectedIndex = 0; this.radioButton_AntPort1.Checked = true; this.checkBox_RF_Ant_Enable1.Checked = true; this.comboBox_RF_AntPort_Quantity.SelectedIndex = 0; AntEnableBitCheck[0] = checkBox_RF_Ant_Enable1; AntEnableBitCheck[1] = checkBox_RF_Ant_Enable2; AntEnableBitCheck[2] = checkBox_RF_Ant_Enable3; AntEnableBitCheck[3] = checkBox_RF_Ant_Enable4; AntEnableBitCheck[4] = checkBox_RF_Ant_Enable5; AntEnableBitCheck[5] = checkBox_RF_Ant_Enable6; AntEnableBitCheck[6] = checkBox_RF_Ant_Enable7; AntEnableBitCheck[7] = checkBox_RF_Ant_Enable8; AntPortRb[0] = radioButton_AntPort1; AntPortRb[1] = radioButton_AntPort2; AntPortRb[2] = radioButton_AntPort3; AntPortRb[3] = radioButton_AntPort4; AntPortRb[4] = radioButton_AntPort5; AntPortRb[5] = radioButton_AntPort6; AntPortRb[6] = radioButton_AntPort7; AntPortRb[7] = radioButton_AntPort8; AntRfPowerCmb[0] = comboBoxRF_AntPort_Port1; AntRfPowerCmb[1] = comboBoxRF_AntPort_Port2; AntRfPowerCmb[2] = comboBoxRF_AntPort_Port3; AntRfPowerCmb[3] = comboBoxRF_AntPort_Port4; AntRfPowerCmb[4] = comboBoxRF_AntPort_Port5; AntRfPowerCmb[5] = comboBoxRF_AntPort_Port6; AntRfPowerCmb[6] = comboBoxRF_AntPort_Port7; AntRfPowerCmb[7] = comboBoxRF_AntPort_Port8; AntPollingCountTxt[0] = textBox_RF_AntPort_InvCnter1; AntPollingCountTxt[1] = textBox_RF_AntPort_InvCnter2; AntPollingCountTxt[2] = textBox_RF_AntPort_InvCnter3; AntPollingCountTxt[3] = textBox_RF_AntPort_InvCnter4; AntPollingCountTxt[4] = textBox_RF_AntPort_InvCnter5; AntPollingCountTxt[5] = textBox_RF_AntPort_InvCnter6; AntPollingCountTxt[6] = textBox_RF_AntPort_InvCnter7; AntPollingCountTxt[7] = textBox_RF_AntPort_InvCnter8; bAnt_InitalFlag = true; } private void btnSetIoDirection_Click(object sender, EventArgs e) { } private void btnSetIO_Click(object sender, EventArgs e) { } private void btnGetIO_Click(object sender, EventArgs e) { } //----------------------------------------------------- private void btnSetModuleSleep_Click(object sender, EventArgs e) { txtSend.Text = Commands.RFID_Q_SetModuleSleep(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private void btnSaveConfigToNv_Click(object sender, EventArgs e) { byte NV_enable = cbxSaveNvConfig.Checked ? (byte)0x01 : (byte)0x00; txtSend.Text = Commands.RFID_Q_SaveConfigToNv(ReaderDeviceAddress, NV_enable); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private void btnSetMode_Click(object sender, EventArgs e) { txtSend.Text = Commands.RFID_Q_SetReaderEnvMode(ReaderDeviceAddress, (byte)cbxMode.SelectedIndex); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private void btnSetCW_Click(object sender, EventArgs e) { if (bInventoryGoing == true) { MessageBox.Show("Please Stop Continuous Inventory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (btnSetCW.Text == "CW ON") { //txtSend.Text = Commands.RFID_Q_SetCW(ReaderDeviceAddressConstCode.SET_ON); txtSend.Text = Commands.RFID_Q_SetCW(ReaderDeviceAddress, ConstCode.SET_ON); } else { //txtSend.Text = Commands.RFID_Q_SetCW(ReaderDeviceAddressConstCode.SET_OFF); txtSend.Text = Commands.RFID_Q_SetCW(ReaderDeviceAddress, ConstCode.SET_OFF); } NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); if (btnSetCW.Text == "CW ON") { btnSetCW.Text = "CW OFF"; } else { btnSetCW.Text = "CW ON"; } } private void btnGetPaPower_Click(object sender, EventArgs e) { if (bInventoryGoing == true) { MessageBox.Show("Please Stop Continuous Inventory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } txtSend.Text = Commands.RFID_Q_GetPaPower(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private void btnSetPaPower_Click(object sender, EventArgs e) { if (bInventoryGoing == true) { MessageBox.Show("Please Stop Continuous Inventory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } int powerDBm = 0; float powerFloat = 0; try { powerFloat = float.Parse(cbxPaPower.SelectedItem.ToString().Replace("dBm", "")); powerDBm = (int)(powerFloat * 100); } catch (Exception formatException) { Console.WriteLine(formatException.ToString()); switch (cbxPaPower.SelectedIndex) { case 5: powerDBm = 1250; break; case 4: powerDBm = 1400; break; case 3: powerDBm = 1550; break; case 2: powerDBm = 1700; break; case 1: powerDBm = 1850; break; case 0: powerDBm = 2000; break; default: powerDBm = 2000; break; } } txtSend.Text = Commands.RFID_Q_SetPaPower(ReaderDeviceAddress, (Int16)powerDBm); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private void btnInsertRfCh_Click(object sender, EventArgs e) { byte[] channelList; int chIndexBegin = Convert.ToInt32(txtChIndexBegin.Text); int chIndexEnd = Convert.ToInt32(txtChIndexEnd.Text); byte channelNum = (byte)(chIndexEnd - chIndexBegin + 1); channelList = new byte[channelNum]; for (int i = chIndexBegin; i <= chIndexEnd; i++) { channelList[i - chIndexBegin] = (byte)i; } txtSend.Text = Commands.RFID_Q_InsertRfCh(ReaderDeviceAddress, channelNum, channelList); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private void btnInsertRfCh_Get_Click(object sender, EventArgs e) { txtSend.Text = Commands.RFID_Q_GetInrRfCh(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private void btnInsertRfCh_Help_Click(object sender, EventArgs e) { MessageBox.Show("1. \"Set Region\" to Cancel the Insert RF Channel!\r\n2. FHSS=\"ON\"!", "Help", MessageBoxButtons.OK, MessageBoxIcon.Question); } private void btnGetChannel_Click(object sender, EventArgs e) { if (bInventoryGoing == true) { MessageBox.Show("Please Stop Continuous Inventory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } txtSend.Text = Commands.RFID_Q_GetRfChannel(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private string curRegion = ConstCode.REGION_CODE_CHN2; private string GetRegionValueFromUI(int IndexRegeion) { string strRegion; switch (IndexRegeion) { case 0: // China 2 strRegion = ConstCode.REGION_CODE_CHN2; break; case 1: // China 1 strRegion = ConstCode.REGION_CODE_CHN1; break; case 2: // US strRegion = ConstCode.REGION_CODE_US; break; case 3: // Europe strRegion = ConstCode.REGION_CODE_EUR; break; case 4: // Korea strRegion = ConstCode.REGION_CODE_KOREA; break; default: strRegion = ConstCode.REGION_CODE_CHN2; break; } return strRegion; } private void btnSetRegion_Click(object sender, EventArgs e) { if (bInventoryGoing == true) { MessageBox.Show("Please Stop Continuous Inventory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } /*string frame = string.Empty; if (cbxRegion.SelectedIndex == 0) // China 2 { frame = Commands.RFID_Q_SetRegion(ReaderDeviceAddress, ConstCode.REGION_CODE_CHN2); curRegion = ConstCode.REGION_CODE_CHN2; } else if (cbxRegion.SelectedIndex == 1) // China 1 { frame = Commands.RFID_Q_SetRegion(ReaderDeviceAddress, ConstCode.REGION_CODE_CHN1); curRegion = ConstCode.REGION_CODE_CHN1; } else if (cbxRegion.SelectedIndex == 2) // US { frame = Commands.RFID_Q_SetRegion(ReaderDeviceAddress, ConstCode.REGION_CODE_US); curRegion = ConstCode.REGION_CODE_US; } else if (cbxRegion.SelectedIndex == 3) // Europe { frame = Commands.RFID_Q_SetRegion(ReaderDeviceAddress, ConstCode.REGION_CODE_EUR); curRegion = ConstCode.REGION_CODE_EUR; } else if (cbxRegion.SelectedIndex == 4) // Korea { frame = Commands.RFID_Q_SetRegion(ReaderDeviceAddress, ConstCode.REGION_CODE_KOREA); curRegion = ConstCode.REGION_CODE_KOREA; } txtSend.Text = frame; NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); cbxChannel.SelectedIndex = 0;*/ curRegion = GetRegionValueFromUI(cbxRegion.SelectedIndex); txtSend.Text = Commands.RFID_Q_SetRegion(ReaderDeviceAddress, curRegion); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); cbxChannel.SelectedIndex = 0; } private void btnGetRegion_Click(object sender, EventArgs e) { txtSend.Text = Commands.RFID_Q_GetRegion(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private void btnSetFhss_Click(object sender, EventArgs e) { if (bInventoryGoing == true) { MessageBox.Show("Please Stop Continuous Inventory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } /*if (btnSetFhss.Text == "FHSS ON") { txtSend.Text = Commands.RFID_Q_SetFhss(ReaderDeviceAddress, ConstCode.SET_ON); } else { txtSend.Text = Commands.RFID_Q_SetFhss(ReaderDeviceAddress, ConstCode.SET_OFF); } NetSendCommand(txtSend.Text);//NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); if (btnSetFhss.Text == "FHSS ON") { btnSetFhss.Text = "FHSS OFF"; } else { btnSetFhss.Text = "FHSS ON"; }*/ if (cbxFHSS.SelectedIndex != 0) { txtSend.Text = Commands.RFID_Q_SetFhss(ReaderDeviceAddress, ConstCode.SET_ON); } else { txtSend.Text = Commands.RFID_Q_SetFhss(ReaderDeviceAddress, ConstCode.SET_OFF); } NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private void btnGetFhss_Click(object sender, EventArgs e) { //2019-01-26 txtSend.Text = Commands.RFID_Q_GetFhss(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private void cbxFhssHopPeriod_SelectedIndexChanged(object sender, EventArgs e) { } private void btnSetFreqHopPeriod_Click(object sender, EventArgs e) { ushort FhssPeriod = (ushort)((cbxFhssHopPeriod.SelectedIndex + 1) * 100); txtSend.Text = Commands.RFID_Q_SetFhssPeriod(ReaderDeviceAddress, FhssPeriod); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private void btnGetFreqHopPeriod_Click(object sender, EventArgs e) { txtSend.Text = Commands.RFID_Q_GetFhssPeriod(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private void cbxFHSS_SelectedIndexChanged(object sender, EventArgs e) { } //------------------------------------------------------------- private void ChangedRFchannelTableFromFreqRegion(int IndexFreqRegion) {//2019-01-26 string strIndex; cbxChannel.Items.Clear(); switch (IndexFreqRegion) { case 0: // China 2 for (int i = 0; i < 20; i++) { strIndex = i.ToString("D2") + "-"; this.cbxChannel.Items.Add(strIndex + (920.125 + i * 0.25).ToString() + "MHz"); } break; case 1: // China 1 for (int i = 0; i < 20; i++) { strIndex = i.ToString("D2") + "-"; this.cbxChannel.Items.Add(strIndex + (840.125 + i * 0.25).ToString() + "MHz"); } break; case 2: // US for (int i = 0; i < 52; i++) { strIndex = i.ToString("D2") + "-"; this.cbxChannel.Items.Add(strIndex + (902.25 + i * 0.5).ToString() + "MHz"); } break; case 3: // Europe for (int i = 0; i < 15; i++) { strIndex = i.ToString("D2") + "-"; this.cbxChannel.Items.Add(strIndex + (865.1 + i * 0.2).ToString() + "MHz"); } break; case 4: // Korea for (int i = 0; i < 32; i++) { strIndex = i.ToString("D2") + "-"; this.cbxChannel.Items.Add(strIndex + (917.1 + i * 0.2).ToString() + "MHz"); } break; default: break; } cbxChannel.SelectedIndex = 0; } private void cbxRegion_SelectedIndexChanged(object sender, EventArgs e) { /*cbxChannel.Items.Clear(); switch (cbxRegion.SelectedIndex) { case 0: // China 2 for (int i = 0; i < 20; i++) { this.cbxChannel.Items.Add((920.125 + i * 0.25).ToString() + "MHz"); } break; case 1: // China 1 for (int i = 0; i < 20; i++) { this.cbxChannel.Items.Add((840.125 + i * 0.25).ToString() + "MHz"); } break; case 2: // US for (int i = 0; i < 52; i++) { this.cbxChannel.Items.Add((902.25 + i * 0.5).ToString() + "MHz"); } break; case 3: // Europe for (int i = 0; i < 15; i++) { this.cbxChannel.Items.Add((865.1 + i * 0.2).ToString() + "MHz"); } break; case 4: // Korea for (int i = 0; i < 32; i++) { this.cbxChannel.Items.Add((917.1 + i * 0.2).ToString() + "MHz"); } break; default: break; } cbxChannel.SelectedIndex = 0; */ ChangedRFchannelTableFromFreqRegion(cbxRegion.SelectedIndex); cbxChannel.SelectedIndex = 0; } private void btnSetFreq_Click(object sender, EventArgs e) { if (bInventoryGoing == true) { MessageBox.Show("Please Stop Continuous Inventory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } txtSend.Text = Commands.RFID_Q_SetRfChannel(ReaderDeviceAddress, cbxChannel.SelectedIndex.ToString("X2")); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } //-------------------------------------------Antenna private void AntResponseMessageProcess(Commands.ReaderResponseFrameString rxStrPkts) //string strCmdL) { bool bParamError = false; string sstr; int i, k = 0; if (rxStrPkts.strStatus != ConstCode.FAIL_OK) { setToolStripStatusMessage1("Error Code: 0x" + rxStrPkts.strStatus, Color.Red); return; } switch (rxStrPkts.strCmdL) { case "00": if (rxStrPkts.strParameters[0] != Ant.Quantity.ToString("X2")) bParamError = true; if (rxStrPkts.strParameters[1] != Ant.Enable[0].ToString("X2")) bParamError = true; if (rxStrPkts.strParameters[2] != Ant.Enable[1].ToString("X2")) bParamError = true; if (rxStrPkts.strParameters[3] != Ant.Enable[2].ToString("X2")) bParamError = true; if (rxStrPkts.strParameters[4] != Ant.Enable[3].ToString("X2")) bParamError = true; if (rxStrPkts.strParameters[5] != Ant.PollingCycle.ToString("X2")) bParamError = true; k = 6; for (i = 0; i < Ant.Quantity; i++) { sstr = rxStrPkts.strParameters[k] + rxStrPkts.strParameters[k + 1]; if (sstr != Ant.AntRFPower[i].ToString("X4")) bParamError = true; sstr = rxStrPkts.strParameters[k + 2] + rxStrPkts.strParameters[k + 3]; if (sstr != Ant.PollingNumber[i].ToString("X4")) bParamError = true; k = k + 4; } if (bParamError == false) setToolStripStatusMessage1("Set Antenna Parameters Successed!", Color.Purple); else setToolStripStatusMessage1("Set Antenna Parameters Failed!", Color.Red); break; case "01": try { Ant.Quantity = byte.Parse(rxStrPkts.strParameters[0]);// Convert.ToByte(rxStrPkts.strParameters[0]) comboBox_RF_AntPort_Quantity.Text = Ant.Quantity.ToString(); Ant.Enable[0] = Convert.ToByte(rxStrPkts.strParameters[1], 16); //byte.Parse(rxStrPkts.strParameters[1]); for (i = 0; i < _ANT_Max_Quantity_; i++) ///!!! { if (((Ant.Enable[0] >> i) & 0x01) != 0x00) { AntEnableBitCheck[i].Checked = true; } else { AntEnableBitCheck[i].Checked = false; } } Ant.PollingCycle = byte.Parse(rxStrPkts.strParameters[5]); if (Ant.PollingCycle != 0) checkBox_RF_AntPort_AutoPolling.Checked = true; else checkBox_RF_AntPort_AutoPolling.Checked = false; k = 6; for (i = 0; i < Ant.Quantity; i++) { sstr = rxStrPkts.strParameters[k] + rxStrPkts.strParameters[k + 1]; Ant.AntRFPower[i] = Convert.ToUInt16(sstr, 16); //i = (Ant.AntRFPower[i] / 100) - 30; AntRfPowerCmb[i].SelectedIndex = 30 - (Ant.AntRFPower[i] / 100); sstr = rxStrPkts.strParameters[k + 2] + rxStrPkts.strParameters[k + 3]; Ant.PollingNumber[i] = Convert.ToUInt16(sstr, 16); AntPollingCountTxt[i].Text = Ant.PollingNumber[i].ToString(); k = k + 4; } setToolStripStatusMessage1("Get Antenna Parameters Successed!", Color.Purple); } catch (System.Exception ex) { Console.WriteLine(ex.Message); setToolStripStatusMessage1("Exception:" + ex.Message, Color.Red); } break; case "02": k = Convert.ToInt16(rxStrPkts.strParameters[0], 16); k = k + 1; setToolStripStatusMessage1("Switch to Antenna Port: Ant" + k.ToString(), Color.MediumSeaGreen); break; case "03": try { k = Convert.ToInt16(rxStrPkts.strParameters[0], 16); for (i = 0; i < _ANT_Max_Quantity_; i++) { AntPortRb[i].Checked = false; } AntPortRb[k].Checked = true; k = k + 1; setToolStripStatusMessage1("Get Current Antenna Port: Ant" + k.ToString(), Color.Purple); } catch (System.Exception ex) { Console.WriteLine(ex.Message); setToolStripStatusMessage1("Exception:" + ex.Message, Color.Red); } break; } } private ulong AntGetEnableSetting() { ulong EnSet = 0, t; for (int i = 0; i < 8; i++) { if (AntEnableBitCheck[i].Checked) { t = 1; t = t << i; EnSet = EnSet | t; } } return EnSet; } private void AntSetEnableSetting(ulong EnbSet) { ulong EnbSet1 = EnbSet; for (int i = 0; i < 8; i++) { if ((EnbSet1 & 0x00000001) != 0) AntEnableBitCheck[i].Checked = true; else AntEnableBitCheck[i].Checked = false; EnbSet1 = EnbSet1 >> 1; } } private void button_RF_Ant_Get_Click(object sender, EventArgs e) { txtSend.Text = Commands.RFID_Q_AntWorkParamters(ReaderDeviceAddress, ConstCode.READER_OPERATION_GET, Ant); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private void button_RF_Ant_Set_Click(object sender, EventArgs e) { byte i; Ant.Quantity = byte.Parse(comboBox_RF_AntPort_Quantity.SelectedItem.ToString()); for (i = 0; i < 4; i++) Ant.Enable[i] = 0; ulong lEnbleBits = AntGetEnableSetting(); Ant.Enable[0] = (byte)(lEnbleBits & 0x000000FF); Ant.Enable[1] = (byte)(lEnbleBits >> 8 & 0x000000FF); Ant.Enable[2] = (byte)(lEnbleBits >> 16 & 0x000000FF); Ant.Enable[3] = (byte)(lEnbleBits >> 32 & 0x000000FF); //------------------ float powerFloat = 0; int powerDBm = 0; try { for (i = 0; i < Ant.Quantity; i++) { powerFloat = float.Parse(AntRfPowerCmb[i].SelectedItem.ToString().Replace("dBm", "")); powerDBm = (int)(powerFloat * 100); Ant.AntRFPower[i] = (ushort)powerDBm; Ant.PollingNumber[i] = ushort.Parse(AntPollingCountTxt[i].Text); } } catch (Exception formatException) { Console.WriteLine(formatException.ToString()); } if (checkBox_RF_AntPort_AutoPolling.Checked) Ant.PollingCycle = 1; else Ant.PollingCycle = 0; txtSend.Text = Commands.RFID_Q_AntWorkParamters(ReaderDeviceAddress, ConstCode.READER_OPERATION_SET, Ant); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } //----------------------------------------- private void button_RF_Ant_GetCurrentAntPort_Click(object sender, EventArgs e) { byte AntPort = 0; txtSend.Text = Commands.RFID_Q_AntCurrentAntPort(ReaderDeviceAddress, ConstCode.READER_OPERATION_GET, AntPort); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private void SwitchAntennaPort(byte AntNo) { txtSend.Text = Commands.RFID_Q_SetAntCurrentAntPort(ReaderDeviceAddress, AntNo); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(frame); } private void radioButton_AntPort8_Click(object sender, EventArgs e) { SwitchAntennaPort(7); } private void radioButton_AntPort7_Click(object sender, EventArgs e) { SwitchAntennaPort(6); } private void radioButton_AntPort6_Click(object sender, EventArgs e) { SwitchAntennaPort(5); } private void radioButton_AntPort5_Click(object sender, EventArgs e) { SwitchAntennaPort(4); } private void radioButton_AntPort4_Click(object sender, EventArgs e) { SwitchAntennaPort(3); } private void radioButton_AntPort3_Click(object sender, EventArgs e) { SwitchAntennaPort(2); } private void radioButton_AntPort2_Click(object sender, EventArgs e) { SwitchAntennaPort(1); } private void radioButton_AntPort1_Click(object sender, EventArgs e) { SwitchAntennaPort(0); } private void comboBox_RF_AntPort_Quantity_SelectedIndexChanged(object sender, EventArgs e) { if (bAnt_InitalFlag == false) return; int i; for (i = 0; i < _ANT_Max_Quantity_; i++) { AntEnableBitCheck[i].Enabled = false; AntPortRb[i].Enabled = false; AntRfPowerCmb[i].Enabled = false; AntPollingCountTxt[i].Enabled = false; } Ant.Quantity = byte.Parse(comboBox_RF_AntPort_Quantity.SelectedItem.ToString()); for (i = 0; i < Ant.Quantity; i++) { AntEnableBitCheck[i].Enabled = true; AntPortRb[i].Enabled = true; AntRfPowerCmb[i].Enabled = true; AntPollingCountTxt[i].Enabled = true; } if (Ant.Quantity == 1) { AntEnableBitCheck[0].Checked = true; radioButton_AntPort1_Click(sender, e); } } #endregion #region Tag Access private void TagAccessInital() { //------------------------------------ this.cbxSelTarget.SelectedIndex = 0; this.cbxAction.SelectedIndex = 0; this.cbxSelMemBank.SelectedIndex = 1; //------------------------------------ this.cbxMemBank.SelectedIndex = 3; //------------------------------------ this.cbxLockKillAction.SelectedIndex = 0; this.cbxLockAccessAction.SelectedIndex = 0; this.cbxLockEPCAction.SelectedIndex = 0; this.cbxLockTIDAction.SelectedIndex = 0; this.cbxLockUserAction.SelectedIndex = 0; } private void btnInvtAdv_Click(object sender, EventArgs e) { bSensorTag_InventoryFlag = false; //LoopNum_cnt = LoopNum_cnt + 1; txtSend.Text = Commands.RFID_Q_ReadSingle(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private void btn_clear_epc2_Click(object sender, EventArgs e) { txtReceive.Text = ""; basic_table.Clear(); advanced_table.Clear(); //LoopNum_cnt = 0; FailEPCNum = 0; SucessEPCNum = 0; db_LoopNum_cnt = 0; for (int i = 0; i <= initDataTableLen - 1; i++) { basic_table.Rows.Add(new object[] { null }); } basic_table.AcceptChanges(); for (int i = 0; i <= initDataTableLen - 1; i++) { advanced_table.Rows.Add(new object[] { null }); } advanced_table.AcceptChanges(); rowIndex = 0; } private void btnSetSelect_Click(object sender, EventArgs e) { if (bAutoSend == true) { MessageBox.Show("Please Stop Continuous Inventory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } int intSelTarget = this.cbxSelTarget.SelectedIndex; int intAction = this.cbxAction.SelectedIndex; int intSelMemBank = this.cbxSelMemBank.SelectedIndex; int intSelPointer = Convert.ToInt32((txtSelPrt3.Text + txtSelPrt2.Text + txtSelPrt1.Text + txtSelPrt0.Text), 16); int intMaskLen = Convert.ToInt32(txtSelLength.Text, 16); int intSelDataMSB = intSelMemBank + intAction * 4 + intSelTarget * 32; int intTruncate = 0; if (this.ckxTruncated.Checked == true) { intTruncate = 0x80; } txtSend.Text = Commands.RFID_Q_SetSelect(ReaderDeviceAddress, intSelTarget, intAction, intSelMemBank, intSelPointer, intMaskLen, intTruncate, txtSelMask.Text); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); //inv_mode.Checked = true; } private void btnGetSelect_Click(object sender, EventArgs e) { txtSend.Text = Commands.RFID_Q_GetSelect(ReaderDeviceAddress); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private void select() { if (bConnectToServerFlag == false) { return; } int intSelTarget = this.cbxSelTarget.SelectedIndex; int intAction = this.cbxAction.SelectedIndex; int intSelMemBank = this.cbxSelMemBank.SelectedIndex; int intSelPointer = Convert.ToInt32((txtSelPrt3.Text + txtSelPrt2.Text + txtSelPrt1.Text + txtSelPrt0.Text), 16); int intMaskLen = Convert.ToInt32(txtSelLength.Text, 16); int intSelDataMSB = intSelMemBank + intAction * 4 + intSelTarget * 32; int intTruncate = 0; txtSend.Text = Commands.RFID_Q_SetSelect(ReaderDeviceAddress, intSelTarget, intAction, intSelMemBank, intSelPointer, intMaskLen, intTruncate, txtSelMask.Text); NetSendCommand(txtSend.Text);////Sp.GetInstance().Send(txtSend.Text); Thread.Sleep(20); } private int getSuccessTagEpc(string[] packetRx) { txtOperateEpc.Text = ""; if (packetRx.Length < 9) { return 0; } int pcEpcLen = Convert.ToInt32(packetRx[0], 16); for (int i = 0; i < pcEpcLen; i++) { txtOperateEpc.Text += packetRx[i + 1] + " "; } return pcEpcLen; } private void btn_invtread_Click(object sender, EventArgs e) { if (bAutoSend == true) { MessageBox.Show("Please Stop Continuous Inventory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string strAccessPasswd = txtRwAccPassWord.Text.Replace(" ", ""); if (strAccessPasswd.Length != 8) { MessageBox.Show("Access password should be two words!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } int wordPtr = Convert.ToInt32((txtWordPtr1.Text.Replace(" ", "") + txtWordPtr0.Text.Replace(" ", "")), 16); int wordCnt = Convert.ToInt32((txtWordCnt1.Text.Replace(" ", "") + txtWordCnt0.Text.Replace(" ", "")), 16); int intMemBank = cbxMemBank.SelectedIndex; select(); txtSend.Text = Commands.RFID_Q_ReadData(ReaderDeviceAddress, strAccessPasswd, intMemBank, wordPtr, wordCnt); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private void btnInvtWrtie_Click(object sender, EventArgs e) { if (bAutoSend == true) { MessageBox.Show("Please Stop Continuous Inventory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string strAccessPasswd = txtRwAccPassWord.Text.Replace(" ", ""); if (strAccessPasswd.Length != 8) { MessageBox.Show("Access password should be two words!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string strDate4Write = txtInvtRWData.Text.Replace(" ", ""); int intMemBank = cbxMemBank.SelectedIndex; int wordPtr = Convert.ToInt32((txtWordPtr1.Text.Replace(" ", "") + txtWordPtr0.Text.Replace(" ", "")), 16); int wordCnt = strDate4Write.Length / 4; // in word! if (strDate4Write.Length % 4 != 0) { MessageBox.Show("The Write Data's Length Should Be Integer Multiples Words", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } //if (strDate4Write.Length > 16 * 4) //{ // MessageBox.Show("Write Data Length Limit is 16 Words", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); // return; //} select(); txtSend.Text = Commands.RFID_Q_WriteData(ReaderDeviceAddress, strAccessPasswd, intMemBank, wordPtr, wordCnt, strDate4Write); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private void buttonLock_Click(object sender, EventArgs e) { if (textBoxLockAccessPwd.Text.Length == 0) return; if (bAutoSend == true) { MessageBox.Show("Please Stop Continuous Inventory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } select(); int lockPayload = buildLockPayload(); txtSend.Text = Commands.RFID_Q_Lock(ReaderDeviceAddress, textBoxLockAccessPwd.Text, lockPayload); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private int buildLockPayload() { int ld = 0; Commands.lock_payload_type payload; if (checkBoxKillPwd.Checked) { payload = Commands.genLockPayload((byte)cbxLockKillAction.SelectedIndex, 0x00); ld |= (payload.byte0 << 16) | (payload.byte1 << 8) | (payload.byte2); } if (checkBoxAccessPwd.Checked) { payload = Commands.genLockPayload((byte)cbxLockAccessAction.SelectedIndex, 0x01); ld |= (payload.byte0 << 16) | (payload.byte1 << 8) | (payload.byte2); } if (checkBoxEPC.Checked) { payload = Commands.genLockPayload((byte)cbxLockEPCAction.SelectedIndex, 0x02); ld |= (payload.byte0 << 16) | (payload.byte1 << 8) | (payload.byte2); } if (checkBoxTID.Checked) { payload = Commands.genLockPayload((byte)cbxLockTIDAction.SelectedIndex, 0x03); ld |= (payload.byte0 << 16) | (payload.byte1 << 8) | (payload.byte2); } if (checkBoxUser.Checked) { payload = Commands.genLockPayload((byte)cbxLockUserAction.SelectedIndex, 0x04); ld |= (payload.byte0 << 16) | (payload.byte1 << 8) | (payload.byte2); } return ld; } private void buttonKill_Click(object sender, EventArgs e) { if (textBoxKillPwd.Text.Length == 0) return; if (bAutoSend == true) { MessageBox.Show("Please Stop Continuous Inventory", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string strKillPasswd = textBoxKillPwd.Text.Replace(" ", ""); if (strKillPasswd.Length != 8) { MessageBox.Show("Kill password should be two words!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } int killRfu = 0; string strKillRfu = textBoxKillRFU.Text.Replace(" ", ""); if (strKillRfu.Length == 0) { killRfu = 0; } else if (strKillRfu.Length != 3) { MessageBox.Show("Kill RFU/Recom should be 3 bits!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else { try { killRfu = Convert.ToInt32(strKillRfu, 2); } catch (System.Exception ex) { Console.WriteLine("Convert Kill RFU fail." + ex.Message); MessageBox.Show("Kill RFU/Recom should be 3 bits!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } select(); txtSend.Text = Commands.RFID_Q_Kill(ReaderDeviceAddress, strKillPasswd, killRfu); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private void inv_mode_CheckedChanged(object sender, EventArgs e) { if (inv_mode.Checked) { txtSend.Text = Commands.RFID_Q_SetInventoryMode(ReaderDeviceAddress, ConstCode.INVENTORY_MODE0); //INVENTORY_MODE0 } else { txtSend.Text = Commands.RFID_Q_SetInventoryMode(ReaderDeviceAddress, ConstCode.INVENTORY_MODE1); //INVENTORY_MODE1 } NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private void ckxTruncated_CheckedChanged(object sender, EventArgs e) { if (ckxTruncated.Checked) { int intSelTarget = this.cbxSelTarget.SelectedIndex; int intSelMemBank = this.cbxSelMemBank.SelectedIndex; if (intSelTarget != 4 || intSelMemBank != 1) { MessageBox.Show("Select Target should be 100 and MemBank should be EPC", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); ckxTruncated.Checked = false; } } } #endregion private void dgv_epc2_MouseUp(object sender, MouseEventArgs e) { int rowIndex = dgv_epc2.CurrentRow.Index; if (dgv_epc2.Rows[rowIndex].Cells[2].Value.ToString() != null) { txtSelMask.Text = dgv_epc2.Rows[rowIndex].Cells[2].Value.ToString(); } txtSelLength.Text = (txtSelMask.Text.Replace(" ", "").Length * 4).ToString("X2"); } private void txtSelMask_DoubleClick(object sender, EventArgs e) { txtSelMask.SelectAll(); } private void cbxMemBank_SelectedIndexChanged(object sender, EventArgs e) { switch (cbxMemBank.SelectedIndex) { case 0: setToolStripStatusMessage1("RFU Bank is reserve for future!", Color.DeepPink); break; case 1: { txtWordPtr0.Text = "02"; txtWordPtr1.Text = "00"; txtWordCnt0.Text = "06"; txtWordCnt1.Text = "00"; setToolStripStatusMessage1("EPC ID Data is start from word pointer 0x02 with 0x06 word length normally!", Color.DeepPink); setToolStripStatusMessage2("0x00=CRC,0x01=PC,0x02~0x07=EPC", Color.DeepSkyBlue); } break; case 2: { txtWordPtr0.Text = "00"; txtWordPtr1.Text = "00"; txtWordCnt0.Text = "04"; txtWordCnt1.Text = "00"; setToolStripStatusMessage1("TID Bank is 4 word length normally!", Color.DeepPink); } break; case 3: { txtWordPtr0.Text = "00"; txtWordPtr1.Text = "00"; txtWordCnt0.Text = "08"; txtWordCnt1.Text = "00"; setToolStripStatusMessage1("Some Tag has no USER Bank!", Color.DeepPink); } break; } } #region Sensor Tag Process DataTable SensorTag_table = new DataTable(); DataSet ds_SensorTag = null; string SensorTag_Temperature = string.Empty; string SensorTag_SensorRssi = string.Empty; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SensorTag_MessageParam { public SensorTag_MessageParam(bool init) { UL = string.Empty; Pc = string.Empty; Epc = string.Empty; AntNo = string.Empty; Temperture = string.Empty; SensorRssi = string.Empty; TemprAverage = string.Empty; } public string UL; public string Pc; public string Epc; public string AntNo; //Pc+Epc Length; public string Temperture; public string SensorRssi; public string TemprAverage; } private SensorTag_MessageParam SensorTagMsg = new SensorTag_MessageParam(true); private void SensorTag_Inital() { //--------------------------------------------------- this.dgv_SensorTag.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dgv_SensorTag_DataBindingComplete); ds_SensorTag = new DataSet(); SensorTag_table = SensorTag_GetEPCHead(); ds_SensorTag.Tables.Add(SensorTag_table); DataView SensorTagDataViewEpc = ds_SensorTag.Tables[0].DefaultView; this.dgv_SensorTag.DataSource = SensorTagDataViewEpc; SensorTag_DGV_ColumnsWidth(this.dgv_SensorTag); this.cbx_SensorTag_ReadNumber.SelectedIndex = 9; this.cbx_SensorTag_SensorTagType.SelectedIndex = 0;// 2; } private DataTable SensorTag_GetEPCHead() { SensorTag_table.TableName = "SensorEPC";//2018-02-01 SensorTag_table.Columns.Add("No.", typeof(string)); //0 SensorTag_table.Columns.Add("PC", typeof(string)); //1 SensorTag_table.Columns.Add("EPC", typeof(string)); //2 SensorTag_table.Columns.Add("CRC", typeof(string)); //3 SensorTag_table.Columns.Add("CNT", typeof(string)); SensorTag_table.Columns.Add("Ant", typeof(string)); SensorTag_table.Columns.Add("Tempr(°C)", typeof(string)); //4 SensorTag_table.Columns.Add("SerRssi", typeof(string)); //4//4 SensorTag_table.Columns.Add("Average(°C)", typeof(string)); for (int i = 0; i <= initDataTableLen - 1; i++) { SensorTag_table.Rows.Add(new object[] { null }); } SensorTag_table.AcceptChanges(); return SensorTag_table; } private const int _SensorTag_DGV_ColumnsIndex_No = 0; private const int _SensorTag_DGV_ColumnsIndex_PC = 1; private const int _SensorTag_DGV_ColumnsIndex_Epc = 2; private const int _SensorTag_DGV_ColumnsIndex_Crc = 3; private const int _SensorTag_DGV_ColumnsIndex_Cnt = 4; private const int _SensorTag_DGV_ColumnsIndex_Ant = 5; private const int _SensorTag_DGV_ColumnsIndex_Temperature = 6; private const int _SensorTag_DGV_ColumnsIndex_SensorRssi = 7; private const int _SensorTag_DGV_ColumnsIndex_TemperAverage = 8; private void SensorTag_DGV_ColumnsWidth(DataGridView dataGridView1) { //dataGridView1.Columns[6].SortMode = DataGridViewColumnSortMode.Programmatic; dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.ColumnHeadersHeight = 40; //dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_No].Width = 40; //dataGridView1.Columns[0].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_No].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_No].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_PC].Width = 60; //dataGridView1.Columns[1].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_PC].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_PC].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Epc].Width = 230; //dataGridView1.Columns[2].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Epc].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Epc].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Crc].Width = 60; //dataGridView1.Columns[3].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Crc].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Crc].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Cnt].Width = 70; //dataGridView1.Columns[6].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Cnt].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Cnt].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Ant].Width = 35; //dataGridView1.Columns[6].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Ant].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Ant].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Temperature].Width = 70; //dataGridView1.Columns[6].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Temperature].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_Temperature].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_SensorRssi].Width = 65; //dataGridView1.Columns[6].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_SensorRssi].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_SensorRssi].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_TemperAverage].Width = 100; //dataGridView1.Columns[6].DefaultCellStyle.Font = new Font("Lucida Console", 10); dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_TemperAverage].Resizable = DataGridViewTriState.False; dataGridView1.Columns[_SensorTag_DGV_ColumnsIndex_TemperAverage].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;// .;MiddleLeft //Some Error , No Work! DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn(); checkBoxColumn.Name = "SelectAll"; checkBoxColumn.HeaderText = "Select"; checkBoxColumn.Width = 45; dataGridView1.Columns.Insert(0, checkBoxColumn); //dataGridView1.Columns.Add(checkBoxColumn); //2018-02-01 } private void dgv_SensorTag_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { //if (e.ListChangedType == ListChangedType.ItemChanged || e.ListChangedType == ListChangedType.ItemAdded) { for (int i = 0; i < this.dgv_SensorTag.Rows.Count; i++) { if (i % 2 == 0) { this.dgv_SensorTag.Rows[i].DefaultCellStyle.BackColor = Color.AliceBlue; } } } } private void dgv_SensorTag_ContentClick(object sender, DataGridViewCellEventArgs e) {//dgv_SensorTag CheckBox Setting.... if (e.RowIndex >= 0 && e.ColumnIndex == 0) { //if (this.dgv_SensorTag.Rows[e.RowIndex].Cells["SelectAll"].Value.ToString() == "1") if ((bool)this.dgv_SensorTag.Rows[e.RowIndex].Cells[0].EditedFormattedValue == true) {// if Checked, unselect. //this.dgv_SensorTag.Rows[e.RowIndex].Cells["SelectAll"].Value = 0; this.dgv_SensorTag.Rows[e.RowIndex].Cells[0].Value = 0; } else {// if no Checked, selected. //this.dgv_SensorTag.Rows[e.RowIndex].Cells["SelectAll"].Value = 1; this.dgv_SensorTag.Rows[e.RowIndex].Cells[0].Value = 1; } } } private void btn_SelectAllSensorTag_Click(object sender, EventArgs e) { dgv_SensorTag.EndEdit(); for (int i = 0; i < dgv_SensorTag.Rows.Count; i++) { //this.dgv_SensorTag.Rows[i].Cells["SelectAll"].Value = 1; this.dgv_SensorTag.Rows[i].Cells[0].Value = 1; } } private int iTemperatureValueErrCounter = 0; private decimal dTemperaturePrev = 0; private int TmpPrevIndex = 0; private decimal[] dgTemperaturePrev = new decimal[100]; private void SensorTag_MessageProcessOK(Commands.ReaderResponseFrameString rxStrPkts) // °C { //rxStrPkts.strCmdH == ConstCode.CMD_SENSORTAG_READ SensorTagMsg.UL = rxStrPkts.strParameters[0]; int PCEPCLength = ((Convert.ToInt32((rxStrPkts.strParameters[1]), 16)) / 8 + 1) * 2; SensorTagMsg.Pc = rxStrPkts.strParameters[1] + " " + rxStrPkts.strParameters[2]; SensorTagMsg.Epc = string.Empty; int i; for (i = 0; i < PCEPCLength - 2; i++) { SensorTagMsg.Epc = SensorTagMsg.Epc + rxStrPkts.strParameters[3 + i]; } SensorTagMsg.Epc = Commands.AutoAddSpace(SensorTagMsg.Epc); //crc = rxStrPkts.strParameters[1 + PCEPCLength] + " " + rxStrPkts.strParameters[2 + PCEPCLength]; i = i + 3; SensorTagMsg.AntNo = rxStrPkts.strParameters[i++]; //Get Temperature SensorTagMsg.Temperture = rxStrPkts.strParameters[i] + rxStrPkts.strParameters[i + 1]; short rTemperature = Convert.ToInt16(SensorTagMsg.Temperture, 16); decimal dTemperature = (decimal)rTemperature; dTemperature = dTemperature / 10; dgTemperaturePrev[TmpPrevIndex++] = dTemperature; TmpPrevIndex = TmpPrevIndex % 100; if (dTemperature > (decimal)120.0 || dTemperaturePrev < (decimal)(-60.0)) { iTemperatureValueErrCounter++; setToolStripStatusMessage2(iTemperatureValueErrCounter.ToString(), Color.Red); return;//Temperature Is Error. } //Get Sensor Rssi SensorTagMsg.Temperture = dTemperature.ToString("F1"); i = i + 2; SensorTagMsg.SensorRssi = DataConvert.HexToDec(rxStrPkts.strParameters[i]); SensorTag_GetEPCx(ref SensorTagMsg); Zed_AddTagTmprRssiInfor((double)dTemperature, Convert.ToDouble(SensorTagMsg.SensorRssi)); Zedgraph_ScrollToRightSide(); SensorTag_ReadTemprCounter++; if (SensorTag_ReadTemprCounter >= SensorTag_ReadTemprMaxNum) { SensorTag_ReadTemprCounter = 0; this.SensorTag_ReadTemprEveWaitHandle.Set();// Release the Block } string strShowMessage = string.Empty; strShowMessage = "Sensor Tag: " + SensorTagMsg.Epc + " [ " + SensorTagMsg.Temperture + "°C ]-{" + SensorTagMsg.SensorRssi + "}"; setToolStripStatusMessage1(strShowMessage, Color.MediumSeaGreen); } private void SensorTag_MessageProcessFailed(Commands.ReaderResponseFrameString rxStrPkts) {//2019-04-28 int PCEPCLength = ((Convert.ToInt32((rxStrPkts.strParameters[1]), 16)) / 8 + 1) * 2; pc = rxStrPkts.strParameters[1] + " " + rxStrPkts.strParameters[2]; epc = string.Empty; for (int i = 0; i < PCEPCLength - 2; i++) { epc = epc + rxStrPkts.strParameters[3 + i]; } epc = Commands.AutoAddSpace(epc); SensorTagMsg.Epc = epc; SensorTag_ReadTemprCounter++; if (SensorTag_ReadTemprCounter >= SensorTag_ReadTemprMaxNum) { SensorTag_ReadTemprCounter = 0; this.SensorTag_ReadTemprEveWaitHandle.Set();// Release the Block } string strShowMessage = string.Empty; strShowMessage = "Sensor Tag: " + SensorTagMsg.Epc + "- No Sensor Tag Found!" + SensorTag_ReadTemprCounter.ToString(); setToolStripStatusMessage1(strShowMessage, Color.Red); } private void SensorTag_GetEPCx(ref SensorTag_MessageParam StagMsg) { this.dgv_SensorTag.ClearSelection(); bool isFoundEpc = false; string newEpcItemCnt; int indexEpc = 0; int EpcItemCnt; if (rowIndex <= initDataTableLen) { EpcItemCnt = rowIndex; } else { EpcItemCnt = SensorTag_table.Rows.Count; } for (int j = 0; j < EpcItemCnt; j++) { if (SensorTag_table.Rows[j][_SensorTag_DGV_ColumnsIndex_Epc].ToString() == StagMsg.Epc && SensorTag_table.Rows[j][_SensorTag_DGV_ColumnsIndex_PC].ToString() == StagMsg.Pc) { indexEpc = j; isFoundEpc = true; break; } } if (EpcItemCnt < initDataTableLen) //basic_table.Rows[EpcItemCnt][0].ToString() == "" { if (!isFoundEpc || EpcItemCnt == 0) { if (EpcItemCnt + 1 < 10) { newEpcItemCnt = "0" + Convert.ToString(EpcItemCnt + 1); } else { newEpcItemCnt = Convert.ToString(EpcItemCnt + 1); } SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_No] = newEpcItemCnt; // EpcItemCnt + 1; SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_PC] = StagMsg.Pc; SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_Epc] = StagMsg.Epc; //SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_Crc] = crc; SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_Cnt] = 1; SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_Ant] = StagMsg.AntNo; SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_Temperature] = StagMsg.Temperture; SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_SensorRssi] = StagMsg.SensorRssi; SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_TemperAverage] = StagMsg.TemprAverage; rowIndex++; } else { if (indexEpc + 1 < 10) { newEpcItemCnt = "0" + Convert.ToString(indexEpc + 1); } else { newEpcItemCnt = Convert.ToString(indexEpc + 1); } SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_No] = newEpcItemCnt; // indexEpc + 1; SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_Cnt] = Convert.ToInt32(SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_Cnt].ToString()) + 1; SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_Ant] = StagMsg.AntNo; SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_Temperature] = StagMsg.Temperture; SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_SensorRssi] = StagMsg.SensorRssi; SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_TemperAverage] = StagMsg.TemprAverage; } } else { if (!isFoundEpc || EpcItemCnt == 0) { if (EpcItemCnt + 1 < 10) { newEpcItemCnt = "0" + Convert.ToString(EpcItemCnt + 1); } else { newEpcItemCnt = Convert.ToString(EpcItemCnt + 1); } SensorTag_table.Rows.Add(new object[] { newEpcItemCnt, StagMsg.Pc, StagMsg.Epc, crc, "1", StagMsg.AntNo, StagMsg.Temperture, StagMsg.SensorRssi }); rowIndex++; } else { if (indexEpc + 1 < 10) { newEpcItemCnt = "0" + Convert.ToString(indexEpc + 1); } else { newEpcItemCnt = Convert.ToString(indexEpc + 1); } SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_No] = newEpcItemCnt; // indexEpc + 1; SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_Cnt] = Convert.ToInt32(SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_Cnt].ToString()) + 1; SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_Ant] = StagMsg.AntNo; SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_Temperature] = StagMsg.Temperture; SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_SensorRssi] = StagMsg.SensorRssi; SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_TemperAverage] = StagMsg.TemprAverage; } } } private void SensorTag_GetEPC(string pc, string epc, string crc, string rssi, string per) { this.dgv_epc2.ClearSelection(); bool isFoundEpc = false; string newEpcItemCnt; int indexEpc = 0; int EpcItemCnt; if (rowIndex <= initDataTableLen) { EpcItemCnt = rowIndex; } else { EpcItemCnt = SensorTag_table.Rows.Count; } for (int j = 0; j < EpcItemCnt; j++) { if (SensorTag_table.Rows[j][_SensorTag_DGV_ColumnsIndex_Epc].ToString() == epc && SensorTag_table.Rows[j][_SensorTag_DGV_ColumnsIndex_PC].ToString() == pc) { indexEpc = j; isFoundEpc = true; break; } } if (EpcItemCnt < initDataTableLen) //SensorTag_table.Rows[EpcItemCnt][0].ToString() == "" { if (!isFoundEpc || EpcItemCnt == 0) { if (EpcItemCnt + 1 < 10) { newEpcItemCnt = "0" + Convert.ToString(EpcItemCnt + 1); } else { newEpcItemCnt = Convert.ToString(EpcItemCnt + 1); } SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_No] = newEpcItemCnt; // EpcItemCnt + 1; SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_PC] = pc; SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_Epc] = epc; SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_Crc] = crc; SensorTag_table.Rows[EpcItemCnt][_SensorTag_DGV_ColumnsIndex_Cnt] = 1; rowIndex++; } else { if (indexEpc + 1 < 10) { newEpcItemCnt = "0" + Convert.ToString(indexEpc + 1); } else { newEpcItemCnt = Convert.ToString(indexEpc + 1); } SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_No] = newEpcItemCnt; // indexEpc + 1; SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_Cnt] = Convert.ToInt32(SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_Cnt].ToString()) + 1; } } else { if (!isFoundEpc || EpcItemCnt == 0) { if (EpcItemCnt + 1 < 10) { newEpcItemCnt = "0" + Convert.ToString(EpcItemCnt + 1); } else { newEpcItemCnt = Convert.ToString(EpcItemCnt + 1); } SensorTag_table.Rows.Add(new object[] { newEpcItemCnt, pc, epc, crc, "1" }); rowIndex++; } else { if (indexEpc + 1 < 10) { newEpcItemCnt = "0" + Convert.ToString(indexEpc + 1); } else { newEpcItemCnt = Convert.ToString(indexEpc + 1); } SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_No] = newEpcItemCnt; // indexEpc + 1; SensorTag_table.Rows[indexEpc][_SensorTag_DGV_ColumnsIndex_Cnt] = Convert.ToInt32(SensorTag_table.Rows[indexEpc][4].ToString()) + 1; } } } private void btn_Clear_SensorTag_Click(object sender, EventArgs e) { txtReceive.Text = ""; SensorTag_table.Clear(); LoopNum_cnt = 0; FailEPCNum = 0; SucessEPCNum = 0; db_LoopNum_cnt = 0; for (int i = 0; i <= initDataTableLen - 1; i++) { SensorTag_table.Rows.Add(new object[] { null }); } SensorTag_table.AcceptChanges(); rowIndex = 0; } private bool bSensorTag_InventoryFlag = false; private void btn_SensorTag_InventoryOne_Click(object sender, EventArgs e) { if (bInventoryGoing == true) { MessageBox.Show("Please Stop Inventory Multi-tag before read sensor tag!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } bSensorTag_InventoryFlag = true; //LoopNum_cnt = LoopNum_cnt + 1; string strCmdFrame = Commands.RFID_Q_ReadSingle(ReaderDeviceAddress); setTextBoxInvoke(txtSend, strCmdFrame); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); } private string[] strSelMaskBuffer = new string[256]; private int iSelMaskBufCounter = 0; private int SensorTag_ReadTemprCounter = 0;// Count the read tempr times. private byte SensorTag_SensorTagType = (byte)ConstCode.SensorTagAccessFlag._SensorTagAccessFlag_YEH_Temperature; private int SensorTag_ReadTemprMaxNum = 1;// Count the read tempr times. Commands.TagSensorAccessParamStruct ReadParam = new Commands.TagSensorAccessParamStruct(true); private void SensorTag_GetAllTagEpcInfor() { ReadParam.ReadMaxNumber = (byte)SensorTag_ReadTemprMaxNum; string strAccessPasswd = txt_SensorTag_AccPassWord.Text.Replace(" ", ""); ReadParam.AccessPswd[0] = Convert.ToByte(strAccessPasswd.Substring(0, 2), 16); ReadParam.AccessPswd[1] = Convert.ToByte(strAccessPasswd.Substring(2, 2), 16); ReadParam.AccessPswd[2] = Convert.ToByte(strAccessPasswd.Substring(4, 2), 16); ReadParam.AccessPswd[3] = Convert.ToByte(strAccessPasswd.Substring(6, 2), 16); string strSelMask;//=txtSelMask.Text.Replace(" ", ""); iSelMaskBufCounter = 0; for (int k = 0; k < this.dgv_SensorTag.Rows.Count; k++) { //strSelMask = dgv_SensorTag.Rows[k].Cells[_SensorTag_DGV_ColumnsIndex_Epc].Value.ToString(); strSelMask = SensorTag_table.Rows[k][_SensorTag_DGV_ColumnsIndex_Epc].ToString(); strSelMask = strSelMask.Replace(" ", ""); strSelMaskBuffer[k] = string.Empty; strSelMaskBuffer[k] = strSelMask; iSelMaskBufCounter++; } } private void btn_SensorTag_GetTmpOne_Click(object sender, EventArgs e) { btn_Zed_Clear_Click(null, null); //SensorTag_GetAllTagEpcInfor(); SensorTag_ReadTemprMaxNum = (byte)(this.cbx_SensorTag_ReadNumber.SelectedIndex + 1); switch (this.cbx_SensorTag_SensorTagType.SelectedIndex) { case 0: SensorTag_SensorTagType = (byte)ConstCode.SensorTagAccessFlag._SensorTagAccessFlag_Rfm_Temperature; break; case 1: MessageBox.Show("Not support this Tag Type Currently!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; //break; case 2: SensorTag_SensorTagType = (byte)ConstCode.SensorTagAccessFlag._SensorTagAccessFlag_YEH_Temperature; break; case 3://2019-03-05 SensorTag_SensorTagType = (byte)ConstCode.SensorTagAccessFlag._SensorTagAccessFlag_YEH_Temperature3G; break; case 4:// SensorTag_SensorTagType = (byte)ConstCode.SensorTagAccessFlag._SensorTagAccessFlag_YEH_Temperature3GSL; //txtSend.Text = Commands.RFID_Q_ReadSensorTag_YEH3GSL(Commands.ReaderDeviceAddr, SensorTag_SensorTagType); //txtSend.Text = Commands.RFID_Q_ReadSensorTag(Commands.ReaderDeviceAddr, SensorTag_SensorTagType, ReadParam); //AA AA FF 06 CA 10 12 0D A5 txtSend.Text = Commands.RFID_Q_ReadSensorTagMTR_YEH3(Commands.ReaderDeviceAddr); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); return; //break; default: break; } SensorTag_GetAllTagEpcInfor(); SensorTag_ReadTemprCounter = 0;//2018-02-01 bSensorTag_ReadThreadExit = false; if (iSelMaskBufCounter != 0) { SensorTag_StartTemperatureOneThread(); } } //----------------------------------------------------- private delegate void txtSendDelegate(string strtext); private void set_txtSend(string strtext) { if (this.txtSend.InvokeRequired) { txtSendDelegate md = new txtSendDelegate(this.set_txtSend); this.Invoke(md, new object[] { strtext }); } else this.txtSend.Text = strtext; } //------------------------------------------------- //public EventWaitHandle SensorTag_ReadTemprEveWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); private AutoResetEvent SensorTag_ReadTemprEveWaitHandle = new AutoResetEvent(false); private void SensorTag_StartTemperatureOneThread() { Thread thread = new Thread(new ThreadStart(this.SensorTag_TemperatureThreadOneProc)); thread.IsBackground = true; thread.Start(); //this.SensorTag_ReadTemprEveWaitHandle.WaitOne(5000, false); } static bool bSensorTag_ReadThreadExit = false; //private AutoResetEvent exitEvent = new AutoResetEvent(false); private void SensorTag_TemperatureThreadOneProc() { string strCmdFrame; string strSelPC, strSelEpcMask; for (int k = 0; k < iSelMaskBufCounter; k++) { if ((bool)this.dgv_SensorTag.Rows[k].Cells[0].EditedFormattedValue == true) {//Read the Sensor Tag has been Checked. dgv_SensorTag.Rows[k].Selected = true; strSelPC = SensorTag_table.Rows[k][_SensorTag_DGV_ColumnsIndex_PC].ToString(); strSelPC = strSelPC.Replace(" ", ""); strSelEpcMask = SensorTag_table.Rows[k][_SensorTag_DGV_ColumnsIndex_Epc].ToString(); strSelEpcMask = strSelEpcMask.Replace(" ", ""); ReadParam.EpcLen = (byte)(strSelEpcMask.Length / 2); ushort PcVaule = Convert.ToUInt16(strSelPC, 16); ReadParam.EpcLen = (byte)(PcVaule >> 11); ReadParam.EpcLen = (byte)(ReadParam.EpcLen * 2); for (byte i = 0; i < ReadParam.EpcLen; i++) ReadParam.EPC[i] = Convert.ToByte(strSelEpcMask.Substring(i * 2, 2), 16); //strCmdFrame = Commands.RFID_Q_ReadSensorTag(Commands.ReaderDeviceAddr, (byte)ConstCode.SensorTagAccessFlag._SensorTagAccessFlag_Rfm_Temperature, ReadParam); strCmdFrame = Commands.RFID_Q_ReadSensorTag(Commands.ReaderDeviceAddr, SensorTag_SensorTagType, ReadParam); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); set_txtSend(strCmdFrame); SensorTag_ReadTemprEveWaitHandle.WaitOne();//5000, false); dgv_SensorTag.Rows[k].Selected = false; } if (bSensorTag_ReadThreadExit) { break; } } /*string strTagEpc; for (int k = 0; k < dgv_SensorTag.Rows.Count; k++) { if ((bool)this.dgv_SensorTag.Rows[k].Cells[0].EditedFormattedValue == true) {// if Checked, dgv_SensorTag.Rows[k].Selected = true;// strTagEpc = dgv_SensorTag.Rows[k].Cells[_SensorTag_DGV_ColumnsIndex_Epc].Value.ToString(); strTagEpc = strTagEpc.Replace(" ", ""); strSelMaskBuffer[k] = string.Empty; //strSelMaskBuffer[k] = strSelMask; } }*/ } //---------------------------------------------------------------------------------- private bool bSensorTagTmprAutoThreadFlag = false; private void btn_SensorTag_GetTmpAuto_Click(object sender, EventArgs e) { if (btn_SensorTag_GetTmpAuto.Text == "Get Temperature Auto") { btn_SensorTag_GetTmpAuto.Text = "Stop Auto"; SensorTag_ReadTemprMaxNum = (byte)(this.cbx_SensorTag_ReadNumber.SelectedIndex + 1); SensorTag_StartTemperatureAutoThread(); } else { btn_SensorTag_GetTmpAuto.Text = "Get Temperature Auto"; bSensorTagTmprAutoThreadFlag = false; } } private void SensorTag_StartTemperatureAutoThread() { btn_Clear_SensorTag_Click(null, null); bSensorTagTmprAutoThreadFlag = true; Thread thread = new Thread(new ThreadStart(this.SensorTag_TemperatureThreadAutoProc)); //Thread thread = new Thread(new ThreadStart(this.SensorTag_TemperatureThreadAutoProcInvoke)); thread.IsBackground = true; thread.Start(); //this.SensorTag_ReadTemprEveWaitHandle.WaitOne(5000, false); } public int SensorTag_TmprThreadFsmState = 0; private void SensorTag_TemperatureThreadAutoProc() { //btn_Clear_SensorTag_Click(null, null); SensorTag_TmprThreadFsmState = 0; while (bSensorTagTmprAutoThreadFlag) { SensorTag_TmprThreadFsmState++; switch (SensorTag_TmprThreadFsmState) { case 1: btn_SensorTag_InventoryOne_Click(null, null); Thread.Sleep(1000); break; case 2: SensorTag_GetAllTagEpcInfor(); break; case 3: SensorTag_TemperatureThreadOneProc(); break; default: SensorTag_TmprThreadFsmState = 0; break; } } } delegate void SensorTag_TemperatureThreadCallback(); private void SensorTag_TemperatureThreadAutoProcInvoke() { if (this.InvokeRequired) { SensorTag_TemperatureThreadCallback dg = new SensorTag_TemperatureThreadCallback(SensorTag_TemperatureThreadAutoProc); this.Invoke(dg, new object[] { }); } else { SensorTag_TemperatureThreadAutoProc(); } } private void SensorTag_dgv_MouseUp(object sender, MouseEventArgs e) { } private void btn_SensorTag_StopRead_Click(object sender, EventArgs e) { bSensorTag_ReadThreadExit = true; txtSend.Text = Commands.RFID_Q_StopSensorTag(Commands.ReaderDeviceAddr); NetSendCommand(txtSend.Text);//Sp.GetInstance().Send(txtSend.Text); //exitEvent.Set(); this.SensorTag_ReadTemprEveWaitHandle.Set(); } private void btn_SensorTag_Test_Click(object sender, EventArgs e) { } #endregion #region ZedGraph Display private PointPairList ZedList_Temperature = new PointPairList(); private PointPairList ZedList_SensorRSSI = new PointPairList(); private GraphPane myPane;// private const double _zedgraph_x_step_ = 1.0; private const double _zedgraph_x_max_ = 52.0; private void Zed_Inital() { myPane = this.zg1.GraphPane;// Get a reference to the GraphPane instance in the ZedGraphControl // Set the titles and axis labels myPane.Title.Text = "Temperature & Sensor RSSI"; myPane.XAxis.Title.Text = "Time Point"; myPane.YAxis.Title.Text = "Temperature"; myPane.Y2Axis.Title.Text = "Sensor RSSI"; //myPane.Title.FontSpec.IsItalic = true; myPane.Title.FontSpec.Size = 20f; myPane.YAxis.Title.FontSpec.Size = 18f; myPane.Y2Axis.Title.FontSpec.Size = 18f; // Make up some data points based on the Sine function //PointPairList ZedList_Temperature = new PointPairList(); //PointPairList ZedList_SensorRSSI = new PointPairList(); /*for ( int i = 0; i < 36; i++ ) { double x = (double)i * 5.0; double y = Math.Sin( (double)i * Math.PI / 15.0 ) * 16.0; double y2 = y * 2;//13.5; ZedList_Temperature.Add( x, y ); ZedList_SensorRSSI.Add( x, y2 ); }*/ // Generate a red curve with diamond symbols, and "Temperature" in the legend LineItem myCurve = myPane.AddCurve("Temperature(°C)", ZedList_Temperature, Color.Red, SymbolType.Diamond); // Fill the symbols with white myCurve.Symbol.Fill = new Fill(Color.White); // Generate a blue curve with circle symbols, and "RSSI" in the legend myCurve = myPane.AddCurve("RSSI", ZedList_SensorRSSI, Color.Blue, SymbolType.Circle); // Fill the symbols with white myCurve.Symbol.Fill = new Fill(Color.White); // Associate this curve with the Y2 axis myCurve.IsY2Axis = true; // Show the x axis grid myPane.XAxis.MajorGrid.IsVisible = true; myPane.XAxis.Scale.Min = -1; myPane.XAxis.Scale.Max = _zedgraph_x_max_; //myPane.XAxis.Scale.MinGrace = true; //myPane.XAxis.Scale.MaxGrace = true; myPane.XAxis.Scale.MinorStep = 1; myPane.XAxis.Scale.MajorStep = 5; //myPane.XAxis.Type = ZedGraph.AxisType.LinearAsOrdinal; // Make the Y axis scale red myPane.YAxis.Scale.FontSpec.FontColor = Color.Red; myPane.YAxis.Title.FontSpec.FontColor = Color.Red; // turn off the opposite tics so the Y tics don't show up on the Y2 axis myPane.YAxis.MajorTic.IsOpposite = false; myPane.YAxis.MinorTic.IsOpposite = false; // Don't display the Y zero line myPane.YAxis.MajorGrid.IsZeroLine = false; // Align the Y axis labels so they are flush to the axis myPane.YAxis.Scale.Align = AlignP.Inside; // Manually set the axis range myPane.YAxis.Scale.Min = -20; myPane.YAxis.Scale.Max = 50; // Enable the Y2 axis display myPane.Y2Axis.IsVisible = true; // Make the Y2 axis scale blue myPane.Y2Axis.Scale.FontSpec.FontColor = Color.Blue; myPane.Y2Axis.Title.FontSpec.FontColor = Color.Blue; // turn off the opposite tics so the Y2 tics don't show up on the Y axis myPane.Y2Axis.MajorTic.IsOpposite = false; myPane.Y2Axis.MinorTic.IsOpposite = false; // Display the Y2 axis grid lines myPane.Y2Axis.MajorGrid.IsVisible = true; // Align the Y2 axis labels so they are flush to the axis myPane.Y2Axis.Scale.Align = AlignP.Inside; // Manually set the axis range myPane.Y2Axis.Scale.Min = -1; myPane.Y2Axis.Scale.Max = 33; // Fill the axis background with a gradient //myPane.Chart.Fill = new Fill( Color.White, Color.LightGray, 45.0f ); // Fill the axis background with a gradient myPane.Chart.Fill = new Fill(Color.White, Color.LightGoldenrodYellow, 45.0f); // Add a text box with instructions //TextObj text = new TextObj( // "Zoom: left mouse & drag\nPan: middle mouse & drag\nContext Menu: right mouse", // 0.05f, 0.95f, CoordType.ChartFraction, AlignH.Left, AlignV.Bottom ); //text.FontSpec.StringAlignment = StringAlignment.Near; //myPane.GraphObjList.Add( text ); // Enable scrollbars if needed zg1.IsShowHScrollBar = true; zg1.IsShowVScrollBar = true; zg1.IsAutoScrollRange = true; zg1.IsScrollY2 = true; // OPTIONAL: Show tooltips when the mouse hovers over a point zg1.IsShowPointValues = true; zg1.PointValueEvent += new ZedGraphControl.PointValueHandler(Zed_PointValueHandler); // OPTIONAL: Add a custom context menu item zg1.ContextMenuBuilder += new ZedGraphControl.ContextMenuBuilderEventHandler( Zed_ContextMenuBuilder); // OPTIONAL: Handle the Zoom Event zg1.ZoomEvent += new ZedGraphControl.ZoomEventHandler(Zed_ZoomEvent); // Size the control to fit the window //Zed_SetSize(); // Tell ZedGraph to calculate the axis ranges // Note that you MUST call this after enabling IsAutoScrollRange, since AxisChange() sets // up the proper scrolling parameters zg1.AxisChange(); // Make sure the Graph gets redrawn zg1.Invalidate(); } private void Zed_SetSize() { zg1.Location = new Point(10, 10); // Leave a small margin around the outside of the control zg1.Size = new Size(this.ClientRectangle.Width - 20, this.ClientRectangle.Height - 20); } /// <summary> /// Display customized tooltips when the mouse hovers over a point /// </summary> private string Zed_PointValueHandler(ZedGraphControl control, GraphPane pane, CurveItem curve, int iPt) { // Get the PointPair that is under the mouse PointPair pt = curve[iPt]; return curve.Label.Text + " is " + pt.Y.ToString("f2") + " units at " + pt.X.ToString("f1") + "."; } /// <summary> /// Customize the context menu by adding a new item to the end of the menu /// </summary> private void Zed_ContextMenuBuilder(ZedGraphControl control, ContextMenuStrip menuStrip, Point mousePt, ZedGraphControl.ContextMenuObjectState objState) { ToolStripMenuItem item = new ToolStripMenuItem(); item.Name = "add-Temperature"; item.Tag = "add-Temperature"; item.Text = "Add a new Temperature Point"; item.Click += new System.EventHandler(Zed_AddBetaPoint); menuStrip.Items.Add(item); } /// <summary> /// Handle the "Add New Beta Point" context menu item. This finds the curve with /// the CurveItem.Label = "Beta", and adds a new point to it. /// </summary> private void Zed_AddBetaPoint(object sender, EventArgs args) { // Get a reference to the "Beta" curve IPointListEdit IPointListEdit ip = zg1.GraphPane.CurveList["Beta"].Points as IPointListEdit; if (ip != null) { double x = ip.Count * 5.0; double y = Math.Sin(ip.Count * Math.PI / 15.0) * 16.0 * 13.5; ip.Add(x, y); zg1.AxisChange(); zg1.Refresh(); } } // Respond to a Zoom Event private void Zed_ZoomEvent(ZedGraphControl control, ZoomState oldState, ZoomState newState) { // Here we get notification everytime the user zooms } delegate void Zedgraph_RefreshCallback(); private void Zedgraph_Refresh() { this.zg1.AxisChange(); this.zg1.Refresh(); } private void Zedgraph_RefreshInThread() { if (this.zg1.InvokeRequired) { // It's on a different thread, so use Invoke. Zedgraph_RefreshCallback dg = new Zedgraph_RefreshCallback(Zedgraph_Refresh); this.Invoke(dg, new object[] { }); } else { // It's on the same thread, no need for Invoke this.zg1.AxisChange(); this.zg1.Refresh(); } } private void Zedgraph_ScrollToRightSide() { if (Zed_Xpoint_Index >= _zedgraph_x_max_) { this.zg1.GraphPane.XAxis.Scale.Max += 1; this.zg1.GraphPane.XAxis.Scale.Min += 1; this.zg1.ScrollMaxX = this.zg1.GraphPane.XAxis.Scale.Max + 1; } } private double Zed_Xpoint_Index = 0; //private const double _zedgraph_x_step_ = 1.0; private void Zed_AddPoint_Temperature(double X, double Yp) { ZedList_Temperature.Add(X * _zedgraph_x_step_, Yp); } private void Zed_AddPoint_SensorRssi(double X, double Yp) { ZedList_SensorRSSI.Add(X * _zedgraph_x_step_, Yp); } private void Zed_AddTagTmprRssiInfor(double dTmprV, double dSnrRssi) { Zed_AddPoint_Temperature(Zed_Xpoint_Index, dTmprV); Zed_AddPoint_SensorRssi(Zed_Xpoint_Index, dSnrRssi); Zedgraph_Refresh(); Zed_Xpoint_Index++; } //-------------------------------------------------------------------- private void btn_Zed_Clear_Click(object sender, EventArgs e) { Zed_Xpoint_Index = 0; ZedList_Temperature.Clear(); ZedList_SensorRSSI.Clear(); //Zed_Inital(); Zedgraph_Refresh(); } #endregion } } <file_sep>/2560/main/pinout.h #ifndef PINOUT #define PINOUT #define UUID_LEN 37 #define LED 4 #define LED_WIFI 2 #define BUTTON_RESET 22 /*encode reading: SW -> The push button, when push go to low. DT -> delay between CLK CLK -> The interrupt pin*/ #define ENCODER_SW 25 #define ENCODER_DT 32 #define ENCODER_CLK 33 #define DEBOUNCED_TIME 300 volatile bool isr_encoder_flag; void IRAM_ATTR isr() { isr_encoder_flag = true; } typedef struct { char uuid_[UUID_LEN]; } Entity; typedef struct //If I recevived a stop command in the web I have to know what to stop { bool valves[128]; bool programs[6]; } active_to_stop; typedef struct { bool manual_web; bool active[10]; uint8_t number_timers; uint8_t valve_number[10]; uint32_t millix[10]; uint32_t times[10]; } stopManualWeb; Entity sys; active_to_stop active; stopManualWeb stop_man_web; //MAX 10 valves open at the same time #endif <file_sep>/2560/main/periodic_task.h #define TIME_INTERRUPT 30 //SECONDS volatile uint32_t isrCounter = 0; volatile uint32_t lastIsrAt = 0; hw_timer_t *timer = NULL; volatile SemaphoreHandle_t timer_mqtt; portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED; void IRAM_ATTR onTimer() { // Increment the counter and set the time of ISR portENTER_CRITICAL_ISR(&timerMux); isrCounter++; lastIsrAt = millis(); portEXIT_CRITICAL_ISR(&timerMux); // Give a semaphore that we can check in the loop xSemaphoreGiveFromISR(timer_mqtt, NULL); } void config_timer() { // Create mqtt timer to reconnect broker timer_mqtt = xSemaphoreCreateBinary(); // Use 1st timer of 4 (counted from zero). // Set 80 divider for prescaler timer = timerBegin(0, 80, true); // Attach onTimer function to our timer. timerAttachInterrupt(timer, &onTimer, true); // Set alarm to call onTimer function every second (value in microseconds). // Repeat the alarm (third parameter) timerAlarmWrite(timer, TIME_INTERRUPT * 1000000, true); //30 seconds // Start an alarm timerAlarmEnable(timer); } <file_sep>/RFID_UHF/SYSIoT_UHF_Reader_SDK/SYSIoT_UHF_Reader_SDK/SDK/SourceCode/c#/NetReaderGA/NetReader/xSocketDLL.cs using System; using System.Collections.Generic; using System.Text; using System.IO; using System.IO.Ports; using System.Threading; using System.Net; using System.Net.Sockets; namespace xSocketDLL { public class xServer { Socket listenSocket; IPEndPoint endp; byte[] RecvBytes = new byte[1024]; int bytes; public void server(string serverIP, int port) { IPAddress serverIp; string host = serverIP; int sport = port; //Console.WriteLine("1/创建套接字."); listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverIp = IPAddress.Parse(host); endp = new IPEndPoint(serverIp, sport); //Console.WriteLine("2/绑定套接字."); listenSocket.Bind(endp); //Console.WriteLine("3/开始监听."); listenSocket.Listen(20); //Console.WriteLine("4/接受客户端连接等待(Waiting)...."); } public Socket Accept() { Socket AcceptSocket = listenSocket.Accept(); return AcceptSocket; } public string Receive(Socket AcceptSocket)//不能用static { try { //阻塞直到发送返回 bytes = AcceptSocket.Receive(RecvBytes, SocketFlags.None); string str1 = Encoding.UTF8.GetString(RecvBytes, 0, bytes); if (bytes > 0) { //Console.WriteLine("已接收:\n{0}", str1); return str1; } return null; } catch (SocketException e) { Console.WriteLine("Server Receive -{0} Error code:{1}.", e.Message, e.ErrorCode); return null; } } public void Send(Socket AcceptSocket, String msg) { // Console.WriteLine("请输入:"); byte[] message = Encoding.UTF8.GetBytes(msg); try { int byteCount = AcceptSocket.Send(message, SocketFlags.None); } catch (SocketException e) { Console.WriteLine("Server Send -{0} Error code:{1}.", e.Message, e.ErrorCode); ; } } public void SocketClose() { this.listenSocket.Shutdown(SocketShutdown.Both); this.listenSocket.Close(); } } //============================================================================================ public class xClient { IPEndPoint endpoint; Socket socketClient=null; byte[] recvBytes = new byte[4096]; int bytesNum; public void Connect(string serverIP, int port) { socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipAddr = IPAddress.Parse(serverIP.Trim()); endpoint = new IPEndPoint(ipAddr, port);//网络节点 try { socketClient.Connect(endpoint); } catch (SocketException e) { Console.WriteLine("Client Connect -{0} Error code:{1}.", e.Message, e.ErrorCode); } } public string ReceiveStr() { try { string recvStr = ""; bytesNum = socketClient.Receive(recvBytes, recvBytes.Length, 0); recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytesNum); //Console.WriteLine("接受到的消息为:{0}", recvStr); return recvStr; //阻塞直到发送返回 } catch (SocketException e) { Console.WriteLine("Client Receive -{0} Error code:{1}.", e.Message, e.ErrorCode); return null; } } public int ReceiveBytes(ref byte[] bytesRecv) { try { bytesNum = socketClient.Receive(bytesRecv); return bytesNum; } catch (SocketException e) { Console.WriteLine("Client Receive -{0} Error code:{1}.", e.Message, e.ErrorCode); return 0; } } public void Send(string CommandMessge) { //string cmdmsg; byte[] byteArray = new byte[512]; //cmdmsg = msg.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", ""); //Clear the ilegal string:' ', try { //byte[] message = Encoding.ASCII.GetBytes(msg); byteArray = HexStringToBinary(CommandMessge); socketClient.Send(byteArray, SocketFlags.None); } catch (SocketException e) { Console.WriteLine("Client Send -{0} Error code:{1}.", e.Message, e.ErrorCode); } } public void SocketClose() { socketClient.Close(); socketClient = null; } public byte[] HexStringToBinary(string hexstring) { string[] tmpary = hexstring.Trim().Split(' '); byte[] buff = new byte[tmpary.Length]; for (int i = 0; i < buff.Length; i++) { buff[i] = Convert.ToByte(tmpary[i], 16); } return buff; } } //========================================== public class Net { public void GetLocalIP() { string name = Dns.GetHostName(); IPAddress[] ipadrlist = Dns.GetHostAddresses(name); foreach (IPAddress ipa in ipadrlist) { if (ipa.AddressFamily == AddressFamily.InterNetwork) { //Console.Writeline(ipa.ToString()); } } } } } <file_sep>/2560/main/wifi_config.h #include <WiFi.h> #include <WiFiClient.h> #include <WiFiAP.h> #include "esp_system.h" #include <EEPROM.h> #include "pinout.h" char web_compleat[] = "<!DOCTYPE html>\ <html <head>\ <meta name=\"viewport \" content=\"width=device-width, initial-scale=1\">\ <style>\ html {\ font-family: Helvetica;\ display: inline-block;\ margin: 0px auto;\ background-color: #ffffec;\ text-align: center;\ color: #052f0e;\ }\ h4 {\ color: #005cfa;\ }\ input {\ padding: 12px 20px;\ margin: 8px 0;\ box-sizing: border-box;\ } \ input[type=text] {\ border: 2px solid rgb(70, 9, 9);\ border-radius: 4px;\ }\ input[type=button], input[type=submit], input[type=reset]{\ background-color: #4CAF50;\ border: none;\ color: rgb(255, 255, 255);\ padding: 16px 32px;\ text-decoration: none;\ margin: 4px 2px;\ cursor: pointer;\ border: 2px solid rgb(70, 9, 9);\ border-radius: 8px;\ }\ </style>\ </head>\ <body>\ <h1>6025 Controller</h1>\ <img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAGQCAYAAACAvzbMAAAgAElEQVR4Xu3dbahd1Z3H8XOvgjLtaIaCbeNo9IXRQsdYrfaViU5r35iSpESw4BAFA31QYiwpZQYaFVqK0kaZ2hlQ0KCgoDSG2jeTPiT2lenUqh1oGwtqirYKnSZqhwY0d<KEY>/sKcFByQ8u1wAAAABJRU5ErkJggg==\">\ <h3>___________________ </h3>\ <span style=\"display:block; height: 40px; \"></span>\ <h4> Insert your house Wifi Credentials </h4>\ <form action=\"action_page.php\"> Wifi Name: <input type=\"text\" name=\"wifi_name\"><br>\ Password: <input type=\"text\" name=\"wifi_pass\"><br>\ <input type=\"submit\">\ </form>\ <h3>___________________ </h3>\ <h3> Configuration web page</h3>\ <h5> March - 2021</h5>\ </body>\ </html>"; WiFiServer server(80); typedef struct { char wifi_name[80]; char wifi_pass[80]; } AP_data_user; String header; AP_data_user AP_data; void get_url_info(char *data, uint16_t index); bool get_credentials(); void auto_wifi_connect(); void get_url_info(char *data, uint16_t index) { for (uint8_t i = 0; i < 30; i++) { //I save the info in the struct if (header.charAt(index + i) == '&' || header.charAt(index + i) == ' ') break; else data[i] = header.charAt(index + i); if (data[i] == '+') data[i] = ' '; LOGW(data[i]); } } bool get_credentials() { WiFiClient client = server.available(); // listen for incoming clients if (client) { // if you get a client, LOGLN("New Client."); // print a message out the serial port String currentLine = ""; // make a String to hold incoming data from the client while (client.connected()) { // loop while the client's connected if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then header += c; if (c == '\n') { if (currentLine.length() == 0) { client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println(); LOGLN("________________________________"); LOGLN(header); //GET /action_page.php?wifi_name=JoseLuis&wifi_pass=<PASSWORD> HTTP/1.1 if (header.indexOf("/action_page.php?wifi_name=") >= 0) { //GET /action_page.php?wifi_name=asd&wifi_pass=Fgh HTTP/1.1 LOGLN("__________START"); LOGLN(" "); LOG("USER: "); uint16_t index = header.indexOf("&wifi_name=") + 32; get_url_info(AP_data.wifi_name, index); LOGLN(" "); LOG("PASS:"); index = header.indexOf("&wifi_pass=") + 11; get_url_info(AP_data.wifi_pass, index); LOGLN(" "); LOGLN("__________END"); return true; } // the content of the HTTP response follows the header: client.println(web_compleat); // The HTTP response ends with another blank line: client.println(); // break out of the while loop: break; } else // if you got a newline, then clear currentLine: currentLine = ""; } else if (c != '\r') // if you got anything else but a carriage return character, currentLine += c; } } header = ""; // close the connection: client.stop(); // LOGLN("Client Disconnected."); } return false; } void auto_wifi_connect() { const char *ssid = "WIFI-6025"; const char *password = "<PASSWORD>"; int attemps = 0; LOGLN("Configuring access point"); //I alocate the eeprom memmory: EEPROMClass eeprom; eeprom.begin(100); // if (digitalRead(BUTTON_RESET) == LOW) // { // LOGLN("MANUAL RESET"); // eeprom.writeString(0, "nop"); // eeprom.writeString(80, "nop"); // eeprom.commit(); // digitalWrite(LED, HIGH); // delay(2000); // digitalWrite(LED, LOW); // } LOGLN("----Alocated on EEPROM:"); String wifi_flash_memmory_user = eeprom.readString(0); String wifi_flash_memmory_pass = eeprom.readString(80); delay(100); LOGLN(wifi_flash_memmory_user); LOGLN(wifi_flash_memmory_pass); //I try to connect to wifi if not: bool valid_credentials = true; // WiFi.begin(a, b); WiFi.begin(wifi_flash_memmory_user.c_str(), wifi_flash_memmory_pass.c_str()); delay(50); while (WiFi.status() != WL_CONNECTED) { delay(500); LOG("."); if (attemps++ > 30) { LOGLN("not valid credentials"); valid_credentials = false; break; } } if (valid_credentials) { randomSeed(micros()); LOGLN(""); LOGLN("WiFi connected"); LOGLN("IP address: "); LOGLN(WiFi.localIP()); } else { LOGLN("Fail on connected with store flash data, genetate access point"); WiFi.softAP(ssid, password); IPAddress myIP = WiFi.softAPIP(); LOG("AP IP address: "); LOGLN(myIP); server.begin(); uint32_t blink_interval = millis(); bool blink_status = true; //todo: blink to better knowlwedge of waitting introduuice while (!get_credentials()) if (millis() - blink_interval >= 500) { digitalWrite(LED_WIFI, blink_status); blink_status = !blink_status; blink_interval = millis(); } LOGLN("i get the user:"); for (int i = 0; i < sizeof(AP_data.wifi_name); i++) LOGW(AP_data.wifi_name[i]); LOGLN(""); LOGLN("i get the pass:"); for (int i = 0; i < sizeof(AP_data.wifi_pass); i++) LOGW(AP_data.wifi_pass[i]); LOGLN(""); WiFi.softAPdisconnect(true); // We start by connecting to a WiFi network LOGLN(); LOG("Connecting to "); LOGLN(AP_data.wifi_name); WiFi.begin(AP_data.wifi_name, AP_data.wifi_pass); attemps = 0; while (WiFi.status() != WL_CONNECTED) { delay(500); LOG("."); if (attemps++ > 25) esp_restart(); } //I save on the flash of the device: eeprom.writeString(0, AP_data.wifi_name); eeprom.writeString(80, AP_data.wifi_pass); eeprom.commit(); LOGLN(""); LOGLN("WiFi connected"); LOGLN("IP address: "); LOGLN(WiFi.localIP()); digitalWrite(LED_WIFI, HIGH); } } int getStrength(int points) { long rssi = 0; long quality = 0; long averageRSSI = 0; for (int i = 0; i < points; i++) { rssi += WiFi.RSSI(); delay(20); } averageRSSI = rssi / points; if (averageRSSI <= -100) quality = 0; else if (averageRSSI >= -50) quality = 100; else quality = 2 * (averageRSSI + 100); return quality; } <file_sep>/MQTT_auto_replay/mqtt.py #!/usr/bin/python import paho.mqtt.client as mqtt # get the credentials of the devises from not_show import intro_json, UPDATE_TOPICS, MQTT_CREDENTIALS import sys import os import json import zlib import hashlib import multiprocessing import time import base64 import ssl """ For converting to windows: pip install pyinstaller Go to your program’s directory and run: pyinstaller yourprogram.py """ # The parameters introduce by the user: business = "" # The name of the enterprise to make the update devise = "" # The model, or ESP32 or ATMEGA update_file_name = "" # The file direction of the update # Check if the update is possible: if (len(sys.argv) != 4): print("Invalid number of parameters !!") sys.exit() else: business = str(sys.argv[1]).lower() devise = str(sys.argv[2]).lower() update_file_name = str(sys.argv[3]) # print(update_file_name) # Check if it makes sense the words introduce: if (business == 'infrico' or business == 'solidy'): if (devise == 'esp32' or devise == 'atmega'): print("Comienza el proceso de update...") else: print("Invalid parameters!!") else: print("Invalid parameters!!") sys.exit() # First I open the file: file = open(update_file_name, "rb") update_bin = file.read() # Obtein the md5 checksum: md5_value = hashlib.md5(update_bin).hexdigest() # I create the string file and compress to zlib: update_zlib = zlib.compress(update_bin, level=9) update_zlib_encoded = base64.b64encode(update_zlib) # and close the file file.close() # and close the file def received_message(mqttc, obj, msg): # I get the version of the firmware in order to increase when I finish the update intro_info = str(msg.payload) offset = intro_info.find('firmware') + len('firmware": "') version = '' for i in range(0, 8): version += intro_info[offset + i] version = int(version[5:]) # Copy the current version and increase 1 time intro_json['firmware'] =intro_json['firmware'][:5] + str(version + 1) # Fill the json correctly: intro_json['md5'] = md5_value intro_json['model'] = devise topic_to_update = UPDATE_TOPICS['esp32_intro'].replace('x', business) json_msg = json.dumps(intro_json) mqttc.unsubscribe(topic_to_update, 0) # I publish the new version json and then the version print('Increase the version') mqttc.publish(UPDATE_TOPICS['esp32_bin'].replace('x', business), update_zlib_encoded, 0, True) print('Publish the firmware in /bin ') mqttc.publish(topic_to_update, json_msg, 0, True) # Configure the mqtt client: mqttc = mqtt.Client() mqttc.on_message = received_message # I connect to broker and set all the permisions: mqttc.tls_set('C:/Users/Asus/Desktop/ESP_32_noob/MQTT_auto_replay/ca.crt', tls_version=ssl.PROTOCOL_TLSv1_2) mqttc.tls_insecure_set(True) mqttc.username_pw_set(MQTT_CREDENTIALS['USER'],MQTT_CREDENTIALS['PASS']) mqttc.connect(MQTT_CREDENTIALS['HOST'], 8883, 60) mqttc.publish('Start', '{"Start_ALL":1}', 0, False) # I generate the first update json: mqttc.subscribe(UPDATE_TOPICS['esp32_intro'].replace('x', business), 0) mqttc.loop_forever() <file_sep>/2560/main/mqtt_interections.h #ifndef MQTT_INTERACTIONS #define MQTT_INTERACTIONS #include "secrets.h" #include "pinout.h" #include <PubSubClient.h> #include <ArduinoJson.h> WiFiClient wifiClient; PubSubClient client(wifiClient); uint32_t publish_counter = 0; void reconnect(); void init_mqtt(); void callback(char *topic, byte *payload, unsigned int length); void refresh_msg(uint32_t isrTime); void refresh_msg(uint32_t isrTime) { publish_counter++; char json[100]; DynamicJsonBuffer jsonBuffer(32); JsonObject &root = jsonBuffer.createObject(); root.set("publish", publish_counter); root.set("heap", esp_get_free_heap_size()); root.set("heap_min", esp_get_minimum_free_heap_size()); root.set("uptime", isrTime); root.printTo(json); client.publish((String(sys.uuid_) + "/uptime").c_str(), (const uint8_t *)json, strlen(json), false); LOGLN("Publish"); } void callback(char *topic, byte *payload, unsigned int length) { //Create the json buffer: DynamicJsonBuffer jsonBuffer(8084); //Parse the huge topic JsonObject &parsed = jsonBuffer.parseObject(payload); LOGLN(esp_get_free_heap_size()); LOGLN(esp_get_minimum_free_heap_size()); int identifier = parsed["id"].as<int>(); // This is for the sendding function app // Obtein the topic String sTopic = String(topic); } void init_mqtt() { client.setServer(mqtt_server, MQTT_PORT); client.setCallback(callback); reconnect(); } void reconnect() { int restart = 0; while (!client.connected()) { LOG("Attempting MQTT connection..."); // Create a random client ID String clientId = "Rarced-"; clientId += String(random(0xffff), HEX); // Attempt to connect if (client.connect(clientId.c_str(), MQTT_USER, MQTT_PASSWORD)) { LOGLN("connected"); String topic = String(sys.uuid_) + "/+/app"; client.subscribe(topic.c_str()); LOGLN(topic); digitalWrite(LED_WIFI, HIGH); } else { digitalWrite(LED_WIFI, LOW); LOG("failed, rc="); LOG(client.state()); LOGLN(" try again in 5 seconds"); if (restart > 10) esp_restart(); else restart++; delay(3000); } } } #endif <file_sep>/Access_Point/AP.h //This is just for testing the struct manipulation: #include <stdio.h> #include <stdint.h> #define MAX_INFO_AP 20 typedef struct { uint8_t starts[MAX_INFO_AP]; uint8_t time[MAX_INFO_AP]; uint8_t week_day[MAX_INFO_AP]; } light_open_info; void modified_struct(light_open_info *lamp, uint8_t hola); <file_sep>/2560/screen_works/screens.h #ifndef SCREENS #define SCREENS #include "SPI.h" #include "Adafruit_GFX.h" #include "Adafruit_ILI9341.h" #include "logos.h" #define _cs 5 // 3 goes to TFT CS #define _dc 2 // 4 goes to TFT DC #define _mosi 23 // 5 goes to TFT MOSI #define _sclk 18 // 6 goes to TFT SCK/CLK #define _rst 4 // ESP RST to TFT RESET #define _miso // Not connected// // 3.3V // Goes to TFT LED // 5v // Goes to TFT Vcc // Gnd // Goes to TFT Gnd void write_numbers(uint8_t number, uint8_t pos_x, uint8_t pos_y); void init_windows(); void main_window(); void config_window(); /* - Main - Manual - Program - Valve - Program - - Config - TIME */ //Define the screen: Adafruit_ILI9341 tft = Adafruit_ILI9341(_cs, _dc, _mosi, _sclk, _rst); void init_windows() { tft.begin(); tft.setRotation(45); tft.fillScreen(ILI9341_WHITE); } void main_window() { tft.fillScreen(ILI9341_WHITE); int h = 240, w = 240, row, col, buffidx = 0; for (row = 0; row < h; row++) for (col = 0; col < w; col++) tft.drawPixel(col + 40, row, pgm_read_word(color_image + buffidx++)); } void config_window() { // tft.fillScreen(ILI9341_WHITE); tft.setRotation(45); tft.setTextColor(ILI9341_BLACK); tft.setTextSize(4); const char *config_text[] = { "MANUAL", "PROGRAM", "CONFIG", }; int ofset = 20; static int value = 0; for (int i = 0; i < 3; i++) { tft.setCursor(60, ofset += 50); tft.println(config_text[i]); } write_numbers(value++, 60, ofset + 40); } void config_window_2(uint8_t input) { // tft.fillScreen(ILI9341_BLACK); tft.drawBitmap(100, 100, back, 25, 25, ILI9341_YELLOW); tft.drawBitmap(20, 50, sprinkler, 100, 100, ILI9341_NAVY); tft.drawBitmap(10, 10, back, 25, 25, ILI9341_BLUE); tft.setRotation(45); tft.setTextColor(ILI9341_WHITE); tft.setTextSize(4); const char *config_text[] = { "MANUAL", "PROGRAM", "CONFIG", }; int ofset_letters = 5; int ofset_box = 0; for (int i = 0; i < 3; i++) { uint8_t h = 20, l = 15; tft.drawRect(50, ofset_box += 50, 220, 40, ILI9341_WHITE); tft.drawRect(10 + h, ofset_box + l, 10, 10, ILI9341_BLACK); tft.drawRect(10 + 1 + h, ofset_box + 1 + l, 10 - 2, 10 - 2, ILI9341_BLACK); if (input == i) { tft.drawRect(10 + h, ofset_box + l, 10, 10, ILI9341_YELLOW); tft.drawRect(10 + 1 + h, ofset_box + 1 + l, 10 - 2, 10 - 2, ILI9341_YELLOW); } tft.setCursor(60, ofset_letters += 50); tft.println(config_text[i]); } } void write_numbers(uint8_t number, uint8_t pos_x, uint8_t pos_y) { // Fill clear the screen with white: tft.setTextColor(ILI9341_WHITE); int letters_clean[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; for (int i = 0; i < 10; i++) { tft.setCursor(pos_x, pos_y); tft.print(String(letters_clean[i]) + String(letters_clean[i])); } tft.setTextColor(ILI9341_BLACK); //Write the real number tft.setCursor(pos_x, pos_y); tft.print(number); } #endif <file_sep>/BLE_2560/gatt_server/components/irrigarion_controller/irrigation_controller.h #ifndef IRRIGATION_CONTROLLER #define IRRIGATION_CONTROLLER #include <stdint.h> #define MAX_NUMBER_PROGRAM 4 #define MAX_NUMBER_VALVES 8 typedef struct { uint8_t water_percentage; //0 - 10 -20 - 400% uint8_t start_hour[MAX_NUMBER_PROGRAM]; //0-24 h uint8_t start_min[MAX_NUMBER_PROGRAM]; //0-59 min uint8_t time_hour[MAX_NUMBER_VALVES]; //0 min a 12 min uint8_t time_min[MAX_NUMBER_VALVES]; //0 min a 60 min } Irrigation_program; void irrig_controller_init_data(); void irrig_controller_save_data(); #endif <file_sep>/BLE_2560/gatt_server/README.md ESP-IDF Gatt Server ======================== Set up the config file <file_sep>/Access_Point/AP_and_images/wifi_ap.ino #include <WiFi.h> #include <WiFiClient.h> #include <WiFiAP.h> #include "esp_system.h" #include <EEPROM.h> #include "SPIFFS.h" #define LED_BUILTIN 2 #define EEPROM_SIZE 1 #define BUTTON_RESET 4 WiFiServer server(80); typedef struct { char wifi_name[80]; char wifi_pass[80]; } AP_data_user; String header; AP_data_user AP_data; void get_url_info(char *data, uint16_t index); bool get_credentials(); char web_compleat[] = "<!DOCTYPE html>\ <html <head>\ <meta name=\"viewport \" content=\"width=device-width, initial-scale=1\">\ <style>\ html {\ font-family: Helvetica;\ display: inline-block;\ margin: 0px auto;\ background-color: #ffffec;\ text-align: center;\ color: #052f0e;\ }\ h4 {\ color: #005cfa;\ }\ input {\ padding: 12px 20px;\ margin: 8px 0;\ box-sizing: border-box;\ } \ input[type=text] {\ border: 2px solid rgb(70, 9, 9);\ border-radius: 4px;\ }\ input[type=button], input[type=submit], input[type=reset]{\ background-color: #4CAF50;\ border: none;\ color: rgb(255, 255, 255);\ padding: 16px 32px;\ text-decoration: none;\ margin: 4px 2px;\ cursor: pointer;\ border: 2px solid rgb(70, 9, 9);\ border-radius: 8px;\ }\ </style>\ </head>\ <body>\ <h1> - </h1>\ <img src=\"data:image/png;base64,iVBORw0KGgoAAAAN<KEY>\">\ <h3>___________________ </h3>\ <span style=\"display:block; height: 40px; \"></span>\ <h4> Insert your house Wifi Credentials </h4>\ <form action=\"action_page.php\"> Wifi Name: <input type=\"text\" name=\"wifi_name\"><br>\ Password: <input type=\"text\" name=\"wifi_pass\"><br>\ <input type=\"submit\">\ </form>\ <h3>___________________ </h3>\ <h3> Configuration web page</h3>\ <h5> November - 2020</h5>\ </body>\ </html>"; void setup() { pinMode(LED_BUILTIN, OUTPUT); pinMode(BUTTON_RESET, INPUT); const char *ssid = "-AQUAMONIX"; const char *password = "h"; int attemps = 0; Serial.begin(115200); Serial.println(); Serial.println("Configuring access point"); //I alocate the eeprom memmory: EEPROMClass eeprom; eeprom.begin(100); if (digitalRead(BUTTON_RESET) == HIGH) { eeprom.writeString(0, "nop"); eeprom.writeString(80, "nop"); eeprom.commit(); digitalWrite(LED_BUILTIN, HIGH); delay(2000); digitalWrite(LED_BUILTIN, LOW); } Serial.println("----Alocated on flash:"); String wifi_flash_memmory_user = eeprom.readString(0); String wifi_flash_memmory_pass = eeprom.readString(80); delay(1000); Serial.println(wifi_flash_memmory_user); Serial.println(wifi_flash_memmory_pass); //I try to connect to wifi if not: bool valid_credentials = true; WiFi.begin(wifi_flash_memmory_user.c_str(), wifi_flash_memmory_pass.c_str()); delay(200); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); if (attemps++ > 20) { Serial.println("not valid credentials"); valid_credentials = false; break; } } if (valid_credentials) { randomSeed(micros()); Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } else { Serial.println("Fail on connected with store flash data, genetate access point"); WiFi.softAP(ssid, password); IPAddress myIP = WiFi.softAPIP(); Serial.print("AP IP address: "); Serial.println(myIP); server.begin(); while (!get_credentials()) { } Serial.println("i get the user:"); for (int i = 0; i < sizeof(AP_data.wifi_name); i++) Serial.write(AP_data.wifi_name[i]); Serial.println(""); Serial.println("i get the pass:"); for (int i = 0; i < sizeof(AP_data.wifi_pass); i++) Serial.write(AP_data.wifi_pass[i]); Serial.println(""); WiFi.softAPdisconnect(true); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(AP_data.wifi_name); WiFi.begin(AP_data.wifi_name, AP_data.wifi_pass); attemps = 0; while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); if (attemps++ > 15) esp_restart(); } //I save on the flash of the device: eeprom.writeString(0, AP_data.wifi_name); eeprom.writeString(80, AP_data.wifi_pass); eeprom.commit(); Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } } void loop() { digitalWrite(LED_BUILTIN, HIGH); delay(2000); digitalWrite(LED_BUILTIN, LOW); delay(2000); } void get_url_info(char *data, uint16_t index) { for (uint8_t i = 0; i < 30; i++) { //I save the info in the struct if (header.charAt(index + i) == '&' || header.charAt(index + i) == ' ') break; else data[i] = header.charAt(index + i); if (data[i] == '+') data[i] = ' '; Serial.write(data[i]); } } bool get_credentials() { WiFiClient client = server.available(); // listen for incoming clients if (client) { // if you get a client, Serial.println("New Client."); // print a message out the serial port String currentLine = ""; // make a String to hold incoming data from the client while (client.connected()) { // loop while the client's connected if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then header += c; if (c == '\n') { if (currentLine.length() == 0) { client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println(); Serial.println("________________________________"); Serial.println(header); //GET /action_page.php?wifi_name=JoseLuis&wifi_pass=<PASSWORD> HTTP/1.1 if (header.indexOf("/action_page.php?wifi_name=") >= 0) { //GET /action_page.php?wifi_name=asd&wifi_pass=Fgh HTTP/1.1 Serial.println("__________START"); Serial.println(" "); Serial.print("USER: "); uint16_t index = header.indexOf("&wifi_name=") + 32; get_url_info(AP_data.wifi_name, index); Serial.println(" "); Serial.print("PASS:"); index = header.indexOf("&wifi_pass=") + 11; get_url_info(AP_data.wifi_pass, index); Serial.println(" "); Serial.println("__________END"); return true; } // the content of the HTTP response follows the header: client.println(web_compleat); // The HTTP response ends with another blank line: client.println(); // break out of the while loop: break; } else { // if you got a newline, then clear currentLine: currentLine = ""; } } else if (c != '\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } // Check to see if the client request was "GET /H" or "GET /L": if (currentLine.endsWith("GET /H")) { digitalWrite(LED_BUILTIN, HIGH); // GET /H turns the LED on } if (currentLine.endsWith("GET /L")) { digitalWrite(LED_BUILTIN, LOW); // GET /L turns the LED off } } } header = ""; // close the connection: client.stop(); // Serial.println("Client Disconnected."); } return false; }<file_sep>/Access_Point/AP/AP.ino <<<<<<< HEAD ======= const char *ssid = "Hotel_Config_Lamp"; const char *password = "<PASSWORD>"; WiFiServer server(80); // Set web server port number to 80 String header; // Variable to store the HTTP request typedef struct { char wifi_name[40]; char wifi_pass[40]; char week_day[7]; char hours_start[10]; } AP_data_user; AP_data_user AP_data; char web_compleat[] = "<!DOCTYPE html>\ <html <head>\ <meta name=\"viewport \" content=\"width=device-width, initial-scale=1\">\ <style>\ html {\ font-family: Helvetica;\ display: inline-block;\ margin: 0px auto;\ background-color: #131e48;\ text-align: center;\ color: #7dbedc;\ }\ h4 {\ color: #d0ca17;\ }\ </style>\ </head>\ <body>\ <h1>Hotel Credentials</h1>\ <h3>___________________ </h3>\ <span style=\"display:block; height: 40px; \"></span>\ <form action=\"action_page.php\"> Wifi Name: <input type=\"text \" name=\"wifi_name\"><br>\ Password: <input type=\"text\" name=\"wifi_pass\"><br>\ <h3>___________________ </h3>\ <h4>Select week day: </h4>\ Week (LMXJVSD): <input type=\"text\" name=\"week\">\ <h4>Select start time: </h4>\ Hour 1: <input type=\"text\" name=\"hours1\">\ <h6> </h6>\ Hour 2: <input type=\"text\" name=\"hours2\">\ <h6> </h6>\ Hour 3: <input type=\"text\" name=\"hours3\">\ <h6> </h6>\ Hour 4: <input type=\"text\" name=\"hours4\">\ <h3> </h3>\ <input type=\"Submit\">\ <h3>___________________ </h3>\ </form>\ <h3> Hotel setup web page</h3>\ <h5> August - 2020</h5>\ </body>\ </html>"; // <span style=\"display:block; height: 100px; \"></span> >>>>>>> 17773aa33e47a1d34c3b5d67b58ae68011f91fd1 void setup() { Serial.begin(115200); Serial.print("Access point in: "); } void loop() { if (Serial.available()) { int a = Serial.read(); if (a ==96) Serial.println("Hola"); <<<<<<< HEAD } delay(2220); Serial.println("hola"); delay(2220); ======= bool obtein_credentials() { WiFiClient client = server.available(); // Listen for incoming clients if (client) { // If a new client connects, Serial.println("New Client"); // print a message out in the serial port String currentLine = ""; // make a String to hold incoming data from the client while (client.connected()) { // loop while the client's connected if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then //Serial.write(c); // print it out the serial monitor header += c; if (c == '\n') { // if the byte is a newline character // if the current line is blank, you got two newline characters in a row. // that's the end of the client HTTP request, so send a response: if (currentLine.length() == 0) { // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) // and a content-type so the client knows what's coming, then a blank line: client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println("Connection: close"); client.println(); if (header.indexOf("GET /action_page.php?wifi_name=") >= 0) { //GET /action_page.php?wifi_name=asd&wifi_pass=Fgh HTTP/1.1 Serial.println(" "); Serial.print("USER: "); uint16_t index = header.indexOf("&wifi_name=") + 32; get_url_info(AP_data.wifi_name, index); Serial.println(" "); Serial.print("PASS:"); index = header.indexOf("&wifi_pass=") + 11; get_url_info(AP_data.wifi_pass, index); Serial.println(" "); Serial.print("WEEK DAY: "); index = header.indexOf("&week=") + 6; get_url_info(AP_data.week_day, index); Serial.println(" "); //TODO: DO NOT REPEAT THIS CODE Serial.print("TIME 1: "); index = header.indexOf("&hours1=") + 8; get_time_url(AP_data.hours_start, index); Serial.println(" "); Serial.print("TIME 2: "); index = header.indexOf("&hours2=") + 8; get_time_url(AP_data.hours_start, index); Serial.println(" "); Serial.print("TIME 3: "); index = header.indexOf("&hours3=") + 8; get_time_url(AP_data.hours_start, index); Serial.println(" "); Serial.print("TIME 4: "); index = header.indexOf("&hours4=") + 8; get_time_url(AP_data.hours_start, index); Serial.println(" "); } // Display the HTML web page client.println(web_compleat); break; } else currentLine = ""; } else if (c != '\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } } } // Clear the header variable header = ""; // Close the connection client.stop(); // Serial.println("Client disconnected"); // Serial.println(""); } return false; >>>>>>> 17773aa33e47a1d34c3b5d67b58ae68011f91fd1 } void get_url_info(char *data, uint16_t index) { for (uint8_t i = 0; i < 30; i++) { //I save the info in the struct if (header.charAt(index + i) == '&') break; else data[i] = header.charAt(index + i); if (data[i] == '+') data[i] = ' '; Serial.write(data[i]); } } void get_time_url(char *data, uint16_t index) { data[0] = header.charAt(index); data[1] = header.charAt(index + 1); data[2] = header.charAt(index + 5); data[3] = header.charAt(index + 6); Serial.write(data[0]); Serial.write(data[1]); Serial.print(":"); Serial.write(data[2]); Serial.write(data[3]); }
7d78929f800642a497d8b5a668819e61cea7cba1
[ "CMake", "Markdown", "C#", "Python", "C", "C++" ]
21
C
RarceD/ESP_32_noob
93c817405ff045c6336715460c1572b137c2e071
5374b1b673099a348891b1bbcf14656331fe4105
refs/heads/master
<file_sep>#!/usr/bin/env python import socket import sys import logging import contextlib import threading import os from datetime import datetime host = 'localhost' port = 8989 if len(sys.argv) > 1: port = int(sys.argv[1]) if "-v" in sys.argv: log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) else: log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.NOTSET) class Server: def __init__(self, h, p): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) log.debug("Socket opened") self.socket.bind((h, p)) log.debug("Listening on {}:{}".format(h, p)) self.socket.listen(5) def __stop_server(self): self.socket.close() log.debug("Socket closed") def run(self): while True: conn, addr = self.socket.accept() handler = ConnectionHandler(conn, addr) thread = threading.Thread(target=handler.run) thread.start() self.__stop_server() class ConnectionHandler: def __init__(self, conn, addr): self.__conn = conn log.debug("Thread started for: {}".format(addr)) def run(self): with contextlib.closing(self.__conn.makefile()) as f: smtp = SMTP() smtp, msg_headers = smtp.verify(f) if smtp: log.debug("SMTP verified") m = Message() save_state = m.save_message(f, msg_headers) if save_state: log.info("Mail saved") else: log.warn("Mail not saved") log.debug("Closing thread / connection") self.__conn.close() class SMTP: def __init__(self): """""" def verify(self, f): log.debug("Starting SMTP verification") message_headers = {'helo': "", 'mail from': "", 'rcpt to': "",} helo = [str(x).lower() for x in f.readline().strip().split(" ")] if len(helo) == 2: message_headers['helo'] = helo[1] log.debug("Got HELO {}".format(helo[1])) else: return False mail_from = [str(x).lower() for x in f.readline().strip().split(": ")] if len(mail_from) == 2 and "mail from" in mail_from: message_headers['mail from'] = mail_from[1] log.debug("Got MAIL FROM {}".format(mail_from[1])) else: return False rcpt_to = [str(x).lower() for x in f.readline().strip().split(": ")] if len(rcpt_to) == 2 and "rcpt to" in rcpt_to: message_headers['rcpt to'] = rcpt_to[1] log.debug("Got RCPT TO {}".format(rcpt_to[1])) elif len(rcpt_to) >= 2: return False data = str(f.readline()).lower() if "data" in data: log.debug("Got DATA") return True, message_headers else: return False class Message: def __init__(self): """""" def save_message(self, f, msg_headers): user = str(msg_headers['rcpt to']).split("@")[0] sender = str(msg_headers['mail from']) maildir = "/home/{}/maildir".format(user) now = datetime.now() if os.path.isdir(maildir): file_name = "{}_{}{}{}_{}_{}_{}".format(sender, str(now.year), str(now.month), str(now.day), str(now.hour), str(now.minute), str(now.second)) file_path = "{}/{}.eml".format(maildir, file_name) log.debug("Starting message save at: {}".format(file_path)) line = f.readline() line_nr = 1 try: with open(file_path, "a") as f2: while line: if line == ".\n": return True f2.write(line) log.debug("--wrote line {}".format(line_nr)) line = f.readline() line_nr += 1 except IOError: return False def main(): s = Server(host, port) s.run() if __name__ == "__main__": main() <file_sep>A personal smtp server development project in Python 3.4 Not finished and solely for personal educational purposes.
e072a6dadfaf30aabfb60b1ff2e094b0e2039bd4
[ "Markdown", "Python" ]
2
Python
hplar/smtpServer
7f302c20e621a33040906d2bf695fc594b2d6e36
ad81b81ffee7eb2a3fe70fc8e3e9be734af3c73b
refs/heads/master
<repo_name>longfeiXie/rpc_xielf<file_sep>/rpc/src/main/java/com/epower/rpc/service/ServiceDiscovery.java package com.epower.rpc.service; import com.epower.rpc.entity.Request; import com.epower.rpc.util.seralizable.RemoteMethodInfo; public abstract class ServiceDiscovery { public abstract RemoteMethodInfo discover(Request request); }<file_sep>/rpc/src/main/java/com/epower/rpc/server/test/Hello.java package com.epower.rpc.server.test; public interface Hello { public String hello(String str); } <file_sep>/rpc/src/main/java/com/epower/rpc/util/seralizable/RemoteMethodInfo.java package com.epower.rpc.util.seralizable; public class RemoteMethodInfo { private String address; private int port; private String methodName; private Class<?> resultType; private Class<?>[] parametersType; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public Class<?> getResultType() { return resultType; } public void setResultType(Class<?> resultType) { this.resultType = resultType; } public Class<?>[] getParametersType() { return parametersType; } public void setParametersType(Class<?>[] parametersType) { this.parametersType = parametersType; } } <file_sep>/rpc/src/main/java/com/epower/rpc/client/test/Client.java package com.epower.rpc.client.test; public interface Client { public String helloServer(String name); } <file_sep>/rpc/src/main/java/com/epower/rpc/client/test/ClientImpl.java package com.epower.rpc.client.test; import org.springframework.stereotype.Repository; import com.epower.rpc.annotation.client.RpcConsumer; @Repository public class ClientImpl implements Client{ @RpcConsumer("hello") Hello hello; public String helloServer(String name) { return hello.hello(name); } } <file_sep>/rpc/src/main/java/com/epower/rpc/server/test/HelloImp.java package com.epower.rpc.server.test; import com.epower.rpc.annotation.server.RpcService; @RpcService("hello") public class HelloImp implements Hello{ public String hello(String str) { return "hello;;;;;;;;;;;;" + str; } } <file_sep>/rpc/src/main/java/com/epower/rpc/util/seralizable/kryo/netty/codec/KryoDecoder.java package com.epower.rpc.util.seralizable.kryo.netty.codec; import com.epower.rpc.util.seralizable.kryo.KryoUtils; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; /** * 请求对象反序列化 * @author xielf * */ public class KryoDecoder extends LengthFieldBasedFrameDecoder { public KryoDecoder() { super(1024*1024, 0, 4, 0, 4); } @Override protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf frame = (ByteBuf) super.decode(ctx, in); if (frame == null) { return null; } try { return KryoUtils.decode(frame); } finally { if (null != frame) { frame.release(); } } } } <file_sep>/rpc/src/main/java/com/epower/rpc/annotation/client/RpcConsumer.java package com.epower.rpc.annotation.client; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface RpcConsumer { String value() default ""; } <file_sep>/rpc/target/classes/META-INF/maven/com.epower/rpc/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.epower</groupId> <artifactId>rpc</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>rpc Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring-version>4.1.7.RELEASE</spring-version> </properties> <repositories> <repository> <id>repo.spring.io</id> <url>http://repo.spring.io/libs-release-remote</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-runtime</artifactId> <version>1.0.12</version> </dependency> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-core</artifactId> <version>1.0.12</version> </dependency> <dependency> <groupId>com.esotericsoftware.kryo</groupId> <artifactId>kryo</artifactId> <version>2.24.0</version> </dependency> <dependency> <groupId>de.javakaffee</groupId> <artifactId>kryo-serializers</artifactId> <version>0.37</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.4.2</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>5.0.0.Alpha2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc-portlet</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-version}</version> </dependency> </dependencies> <build> <finalName>rpc</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.1</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> <configuration> <archive> <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile> </archive> </configuration> </plugin> </plugins> </build> </project> <file_sep>/rpc/src/main/java/com/epower/rpc/client/InitializeConsumer.java package com.epower.rpc.client; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Map; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import com.epower.rpc.annotation.client.RpcConsumer; import com.epower.rpc.entity.Request; import com.epower.rpc.entity.Response; import com.epower.rpc.service.ServiceDiscovery; import com.epower.rpc.service.impl.ZkServiceDiscoveryImpl; import com.epower.rpc.util.seralizable.RemoteMethodInfo; /** * 初始化服务器 * * @author xielf * */ @SuppressWarnings("unchecked") public class InitializeConsumer implements ApplicationContextAware, InitializingBean { private static final Logger LOG = LoggerFactory.getLogger(InitializeConsumer.class); private String registryAddress; private ServiceDiscovery discovery; private ApplicationContext applicationContext; public String getRegistryAddress() { return registryAddress; } public void setRegistryAddress(String registryAddress) { this.registryAddress = registryAddress; } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } private <T> T create(final Class<T> clazz, final String beanName) { return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Request request = new Request(); String methodName = method.getName(); Class<?>[] clazz = method.getParameterTypes(); Class<?> resultType = method.getReturnType(); request.setArgs(args); request.setMethodName(methodName); request.setParameterTypes(clazz); request.setServiceBeanName(beanName); request.setResultType(resultType); // 目前只有zookeeper if (discovery == null) { discovery = new ZkServiceDiscoveryImpl(registryAddress); } RemoteMethodInfo remoteMethodInfo = discovery.discover(request); String address = remoteMethodInfo.getAddress(); int port = remoteMethodInfo.getPort(); Response response = RpcClient.getInstance().remoteInvoke(address, port, request); if (response.getError() != null) { throw response.getError(); } else { return response.getResult(); } } }); } @Override public void afterPropertiesSet() throws Exception { if (!StringUtils.isEmpty(registryAddress)) { Map<String, Object> rpcServiceBeanMap = applicationContext.getBeansWithAnnotation(Component.class); for (Object serviceBean : rpcServiceBeanMap.values()) { LOG.info("class name: " + serviceBean.getClass().getName()); Field[] fields = serviceBean.getClass().getDeclaredFields(); for (Field field : fields) { LOG.info("field name: " + field.getName()); if (field.getType().isInterface()) { RpcConsumer rpcConsumer = field.getAnnotation(RpcConsumer.class); if (rpcConsumer != null) { String value = rpcConsumer.value(); value = StringUtils.isEmpty(value) ? field.getType().getSimpleName() : value; try { LOG.info("consumer name: " + value); field.setAccessible(true); field.set(serviceBean, create(field.getType(), value)); } catch (Exception e) { e.printStackTrace(); } } } } } LOG.info("initalize rpc client success"); } } public static void main(String[] args) throws IOException { Properties properties = new Properties(); properties.load(InitializeConsumer.class.getClassLoader().getResourceAsStream("com/epower/rpc/client/file.properties")); System.out.println(InitializeConsumer.class.getClassLoader().getResource("").getPath()); System.out.println(properties.get("a")); } }
14ae92e8466bd278c2b27433b17b55feed5e4e39
[ "Java", "Maven POM" ]
10
Java
longfeiXie/rpc_xielf
9281498ed49317ee00468ace22ece964c5aceeb2
964e8742750cac46fa820fd64666068c9aa56ec6
refs/heads/master
<repo_name>jensengbg-jakob-reesalu/nodejs-read-write-files-boilerplate<file_sep>/app.js const fs = require("fs"); // let newQuote = "" // fs.readFile("quote.txt", "utf8", (error, contents) => { // newQuote += contents; // }); // let readFile = fs.createReadStream("OscarWilde.txt"); // let writeFile = fs.createWriteStream("quote.txt"); // readFile.pipe(writeFile); // const file = fs.createWriteStream("OscarWilde.txt"); // let quote = "Be yourself. Everyone else is already taken."; //fs.readFile("quote.txt", "utf8", (error, contents) => { // console.log(contents); //}); // fs.writeFile("quote.txt", quote, (err) => { // console.log("Quote saved!"); // }); // for(let i=0; i < 5; i++) { // console.log("iteration:", i); // file.write("You can never be overdressed or overeducated.\n"); // } // file.end(); let newQuote = ""; fs.readFile("OscarWilde.txt", "utf8", (error, contents) => { newQuote = contents; console.log("newQuote is now: ", newQuote); }); fs.readFile("quote.txt", "utf8", (error, contents) => { newQuote += contents; console.log("newQuote is now: ", newQuote); fs.writeFile("quote.txt", newQuote, (err) => { console.log("newQuote saved!"); }); }); <file_sep>/resetQuote.js const fs = require("fs"); let quote = "Be yourself. Everyone else is already taken."; fs.writeFile("quote.txt", quote, (err) => { console.log("quote.txt restored!"); });
548b90ce7bb2a815adb0c200a4046fcaef9f2755
[ "JavaScript" ]
2
JavaScript
jensengbg-jakob-reesalu/nodejs-read-write-files-boilerplate
7f1bc653c67d5d5c06bb8631446a18660d5bdff5
a0fd526796afe08d2b25fa4ebd8582d4b5056039
refs/heads/master
<repo_name>buzz1274/simple_budget<file_sep>/simple_budget/models/budget/budget_category.py from __future__ import unicode_literals from django.db import models from simple_budget.helper.sql import SQL from sqlalchemy import func, desc, asc from budget_type import BudgetType class BudgetCategory(models.Model): """ budget category model """ budget_category_id = models.AutoField(primary_key=True) budget_category = models.TextField(blank=True) budget_type = models.ForeignKey(BudgetType, blank=True, null=True) class Meta: db_table = 'budget_category' app_label = 'simple_budget' @staticmethod def budget_categories(sort): """ retrieves a dict of all budget categories :return: """ sql = SQL() sort_order = {0: [sql.budget_category.c.budget_category], 2: [sql.budget_type.c.budget_type], 4: ['tc_count'],} try: sort = int(sort) sort_lookup = sort - (sort % 2) sort_order[sort_lookup] except (ValueError, IndexError, TypeError): sort = 0 sort_lookup = 0 transaction_categories = sql.db_session.query( sql.transaction_category.c.budget_category_id, func.COUNT(sql.transaction_category.c.budget_category_id).\ label('tc_count')).\ group_by(sql.transaction_category.c.budget_category_id).subquery() budget_categories = sql.db_session.query( sql.budget_category.c.budget_category_id, sql.budget_type.c.budget_type, transaction_categories.c.tc_count, sql.budget_category.c.budget_category). \ filter(sql.budget_type.c.budget_type_id== sql.budget_category.c.budget_type_id). \ filter(sql.budget_type.c.budget_type_id== sql.budget_category.c.budget_type_id). \ outerjoin(transaction_categories, transaction_categories.c.budget_category_id== sql.budget_category.c.budget_category_id) if sort % 2: budget_categories = \ budget_categories.order_by(desc(sort_order[sort_lookup][0])) else: budget_categories = \ budget_categories.order_by(asc(sort_order[sort_lookup][0])) return [sort, budget_categories]<file_sep>/simple_budget/views/budget/budget.py from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.http import HttpResponseRedirect from django.db import DatabaseError from django.contrib.auth.decorators import login_required, user_passes_test from simple_budget.models.transaction.transaction_category import \ TransactionCategory from simple_budget.models.budget.budget_category import BudgetCategory from simple_budget.helper.date_calculation import DateCalculation from simple_budget.helper.helper import clean_message_from_url from simple_budget.forms.budget.add_edit_budget_form import \ AddEditBudgetForm from simple_budget.forms.budget.delete_budget_form import \ DeleteBudgetForm from simple_budget.forms.budget.clone_budget_form import \ CloneBudgetForm from simple_budget.forms.budget.add_edit_budget_category_form import \ AddEditBudgetCategoryForm from simple_budget.forms.budget.delete_budget_category_form import \ DeleteBudgetCategoryForm from simple_budget.models.budget.budget import Budget from simple_budget.models.budget.budget_type import BudgetType @login_required def summary(request): """ index """ year, next_year, prev_year = \ DateCalculation.calculate_years(request.GET.get('year', None)) total_spending, average_spending, spending_by_budget_type = \ BudgetType().spending_by_budget_type(year) return render_to_response('budget/summary.html', {'year': year, 'next_year': next_year, 'prev_year': prev_year, 'total_spending': total_spending, 'average_spending': average_spending, 'spending_by_budget_type': spending_by_budget_type}, context_instance=RequestContext(request)) @login_required def budget(request): """ index """ prev_month, next_month, start_date, end_date, display_date = \ DateCalculation.calculate_dates(request.GET.get('date', None)) if not start_date or not end_date: return HttpResponseRedirect('/budget/') transactions, totals, grand_total = \ Budget().get_budget(start_date, end_date) return render_to_response('budget/budget.html', {'transactions': transactions, 'totals': totals, 'grand_total': grand_total, 'date': display_date, 'next_month': next_month, 'prev_month': prev_month}, context_instance=RequestContext(request)) @login_required @user_passes_test(lambda u: u.is_superuser, login_url='/?message=no_permissions_error', redirect_field_name=None) def add_edit_budgets(request, action=None, budget_id=None): budget_value_error_found = False referer = \ clean_message_from_url(request.META.get('HTTP_REFERER', None)) prev_month, next_month, start_date, end_date, today = \ DateCalculation().calculate_dates() transactions, totals, grand_total = \ Budget().get_budget(start_date, end_date, budget_id) if request.method == 'POST': if request.POST.get('submit', None) != 'Submit': return HttpResponseRedirect(request.POST.get('referer', '/')) if action == 'edit': edit_budget = True else: edit_budget = False form = AddEditBudgetForm(request.POST, transactions=transactions, edit_budget=edit_budget) if form.is_valid(): if Budget().add_edit_budget(action, request.POST): message = 'success' else: message = 'failure' return HttpResponseRedirect( '/budgets/?message=budget_%s_%s' % (action, message,)) else: for transaction in transactions: if form['budget_category_%s' % (transaction.budget_category_id,)].errors: transaction.has_error = True budget_value_error_found = True else: if action == 'edit' and budget_id: edit_budget = get_object_or_404(Budget, pk=budget_id) form = \ AddEditBudgetForm(transactions=transactions, edit_budget=True, initial={'referer': referer, 'budget_id': edit_budget.budget_id, 'budget_name': edit_budget.budget_name, 'budget_description': edit_budget.budget_description, 'budget_master': edit_budget.budget_master}) else: form = AddEditBudgetForm(transactions=transactions, initial={'referer': referer}) return render_to_response('budget/add_edit_budget.html', {'form': form, 'action': action, 'budget_value_error_found': budget_value_error_found, 'totals': totals, 'grand_total': grand_total, 'transactions': transactions}, context_instance=RequestContext(request)) @login_required @user_passes_test(lambda u: u.is_superuser, login_url='/?message=no_permissions_error', redirect_field_name=None) def clone_budgets(request, budget_id=None): """ deletes the supplied budget category :param request: :return: """ budget_to_clone = get_object_or_404(Budget, pk=budget_id) referrer = \ clean_message_from_url(request.META.get('HTTP_REFERER', None)) if request.method == 'POST': if request.POST.get('submit', None) == 'Cancel': return HttpResponseRedirect(request.POST.get('referrer', '/')) form = CloneBudgetForm(request.POST) if form.is_valid(): if budget_to_clone.clone_budget(form.cleaned_data): return HttpResponseRedirect( '/budgets/?message=budget_clone_success') else: return HttpResponseRedirect( '/budgets/?message=budget_clone_failure') else: form = CloneBudgetForm(initial={'budget_id': budget_to_clone.pk, 'referrer': referrer}) return render_to_response('budget/add_edit_budget.html', {'form': form, 'action': "clone", 'referrer': referrer}, context_instance=RequestContext(request)) @login_required @user_passes_test(lambda u: u.is_superuser, login_url='/?message=no_permissions_error', redirect_field_name=None) def delete_budgets(request, budget_id=None): """ deletes the supplied budget category :param request: :return: """ budget_to_delete = get_object_or_404(Budget, pk=budget_id) referer = \ clean_message_from_url(request.META.get('HTTP_REFERER', None)) if request.method == 'POST': if request.POST.get('submit', None) == 'Cancel': return HttpResponseRedirect(request.POST.get('referer', '/')) form = DeleteBudgetForm(request.POST) if form.is_valid(): if budget_to_delete.delete_budget(): return HttpResponseRedirect( '/budgets/?message=budget_delete_success') else: return HttpResponseRedirect( '/budgets/?message=budget_delete_failure') else: form = DeleteBudgetForm(initial={'budget_id': budget_to_delete.pk, 'referer': referer}) return render_to_response('budget/budget_delete.html', {'form': form, 'budget_is_master': budget_to_delete.budget_master, 'refer': referer}, context_instance=RequestContext(request)) @login_required def budgets(request, budget_id=None): """ index """ if budget_id: budget_to_view = Budget.objects.get(pk=budget_id) else: budget_to_view = None if not budget_id or not budget_to_view: return render_to_response('budget/budgets.html', {'budgets': Budget.objects.all(). order_by('-budget_master')}, context_instance=RequestContext(request)) else: prev_month, next_month, start_date, end_date, today = \ DateCalculation().calculate_dates() transactions, totals, grand_total = \ Budget().get_budget(start_date, end_date, budget_id) return render_to_response('budget/budget_detail.html', {'budget': budget_to_view, 'view_type': 'view', 'totals': totals, 'grand_total': grand_total, 'transactions': transactions}, context_instance=RequestContext(request)) @login_required def category(request): """ budget categories :param request: :return: """ sort, budget_categories = \ BudgetCategory.budget_categories(request.GET.get('sort', None)) return render_to_response('budget/category.html', {'budget_categories': budget_categories, 'sort': sort}, context_instance=RequestContext(request)) @login_required @user_passes_test(lambda u: u.is_superuser, login_url='/?message=no_permissions_error', redirect_field_name=None) def add_edit_budget_category(request, action, budget_category_id): """ add edit budget categories :param request: :return: """ referer = \ clean_message_from_url(request.META.get('HTTP_REFERER', None)) if request.method == 'POST': if request.POST.get('submit', None) != 'Submit': return HttpResponseRedirect(request.POST.get('referer', '/')) form = AddEditBudgetCategoryForm(request.POST) if form.is_valid(): try: if form.cleaned_data['budget_category_id']: budget_category = \ BudgetCategory( budget_category_id= form.cleaned_data['budget_category_id'], budget_type_id= form.cleaned_data['budget_type_id'], budget_category= form.cleaned_data['budget_category']) else: budget_category = \ BudgetCategory( budget_type_id= form.cleaned_data['budget_type_id'], budget_category= form.cleaned_data['budget_category']) budget_category.save() if budget_category.pk: message = 'success' else: message = 'failure' except DatabaseError: message = 'failure' return HttpResponseRedirect('/budget/category/?' 'message=budget_category_%s_%s' % (action, message,)) else: if action == 'edit': budget_category = get_object_or_404(BudgetCategory, pk=budget_category_id) form = AddEditBudgetCategoryForm( initial={'referer': referer, 'budget_category_id': budget_category.budget_category_id, 'budget_category': budget_category.budget_category, 'budget_type_id': budget_category.budget_type_id}) else: form = AddEditBudgetCategoryForm(initial={'referer': referer}) return render_to_response('budget/add_edit_budget_category.html', {'referer': referer, 'form': form, 'action': action}, context_instance=RequestContext(request)) @login_required @user_passes_test(lambda u: u.is_superuser, login_url='/?message=no_permissions_error', redirect_field_name=None) def delete_budget_category(request, budget_category_id): """ deletes the supplied budget category :param request: :return: """ budget_category = get_object_or_404(BudgetCategory, pk=budget_category_id) referer = \ clean_message_from_url(request.META.get('HTTP_REFERER', None)) transaction_categories = \ TransactionCategory.objects.filter(budget_category_id= budget_category_id).count() if request.method == 'POST': if request.POST.get('submit', None) == 'Cancel': return HttpResponseRedirect(request.POST.get('referer', '/')) form = \ DeleteBudgetCategoryForm( request.POST, current_budget_category_id=budget_category_id, select_new_category=bool(transaction_categories)) if form.is_valid(): try: if form.cleaned_data['transfer_budget_category_id']: TransactionCategory.objects.filter(budget_category_id= budget_category_id). \ update(budget_category_id= form.cleaned_data['transfer_budget_category_id']) budget_category.delete() return HttpResponseRedirect( '/budget/category/?' 'message=budget_category_delete_success') except DatabaseError: return HttpResponseRedirect( '/budget/category/?' 'message=budget_category_delete_failure') else: form = DeleteBudgetCategoryForm( current_budget_category_id=budget_category_id, initial={'budget_category_id': budget_category.pk, 'referer': referer}) return render_to_response('budget/delete_budget_category.html', {'form': form, 'transaction_categories': transaction_categories, 'refer': referer}, context_instance=RequestContext(request))<file_sep>/simple_budget/migrations/0013_auto_20150217_1414.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('simple_budget', '0012_auto_20150217_1350'), ] operations = [ migrations.AddField( model_name='account', name='account_starting_balance', field=models.DecimalField(default=0, max_digits=7, decimal_places=2), preserve_default=True, ), migrations.AlterField( model_name='accountbalance', name='account_balance', field=models.DecimalField(default=0, max_digits=7, decimal_places=2), preserve_default=False, ), ] <file_sep>/simple_budget/forms/budget/delete_budget_form.py from django import forms class DeleteBudgetForm(forms.Form): budget_id = forms.CharField(widget=forms.HiddenInput(), required=True) referer = forms.CharField(widget=forms.HiddenInput(), required=False)<file_sep>/simple_budget/models/budget/budget_amount.py from __future__ import unicode_literals from django.db import models from simple_budget.models.budget.budget_category import BudgetCategory class BudgetAmount(models.Model): """ budget category model """ budget_amount_id = models.AutoField(primary_key=True) budget = models.ForeignKey('Budget', blank=False, null=True) budget_category = models.ForeignKey(BudgetCategory, blank=False, null=True) budget_amount = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) start_date = models.DateField(null=False, blank=False) end_date = models.DateField(null=True, blank=True) class Meta: db_table = 'budget_amount'<file_sep>/simple_budget/models/transaction/transaction_category.py from __future__ import unicode_literals from django.db import models from simple_budget.helper.sql import SQL from sqlalchemy.orm import aliased from sqlalchemy import func, case, desc, asc from simple_budget.models.budget.budget_category import BudgetCategory class TransactionCategory(models.Model): """ transaction category model """ transaction_category_id = models.AutoField(primary_key=True) transaction_category_parent = models.ForeignKey('self', blank=True, null=True) budget_category = models.ForeignKey(BudgetCategory, blank=True, null=True) transaction_category = models.TextField(blank=True) class Meta: db_table = 'transaction_category' @staticmethod def transaction_category_mapping(sort, budget_category_id): """ returns budget/transaction category mapping :return: """ sql = SQL() parent_transaction_category = aliased(sql.transaction_category) sort_order = {0: ['category'], 2: [sql.budget_category.c.budget_category], 4: [sql.budget_type.c.budget_type]} try: sort = int(sort) sort_lookup = sort - (sort % 2) sort_order[sort_lookup] except (ValueError, IndexError, TypeError): sort = 0 sort_lookup = 0 transaction_categories = \ sql.db_session.query( sql.transaction_category.c.transaction_category_id, sql.budget_type.c.budget_type, sql.budget_category.c.budget_category_id, sql.budget_category.c.budget_category, case([(parent_transaction_category.c.transaction_category.isnot(None), func.CONCAT(parent_transaction_category.c.transaction_category, ' >> ', sql.transaction_category.c.transaction_category)) ], else_=sql.transaction_category.c.transaction_category). \ label('category'), sql.transaction_category.c.budget_category_id). \ outerjoin(sql.budget_category, sql.transaction_category.c.budget_category_id == sql.budget_category.c.budget_category_id). \ outerjoin(parent_transaction_category, sql.transaction_category.c.transaction_category_parent_id == parent_transaction_category.c.transaction_category_id). \ outerjoin(sql.budget_type, sql.budget_type.c.budget_type_id == sql.budget_category.c.budget_type_id) if budget_category_id: if budget_category_id == '0': budget_category_id = None else: budget_category_id = int(budget_category_id) transaction_categories = \ transaction_categories.filter( sql.budget_category.c.budget_category_id==budget_category_id) if sort % 2: transaction_categories = \ transaction_categories.order_by(desc(sort_order[sort_lookup][0])) else: transaction_categories = \ transaction_categories.order_by(asc(sort_order[sort_lookup][0])) return [sort, transaction_categories] <file_sep>/simple_budget/settings.py """ Django settings for simple_budget project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ ... """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import yaml BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<KEY>' ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'simple_budget', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "simple_budget.context_processors.quicken_import_active", "simple_budget.context_processors.get_message", "simple_budget.context_processors.unassigned_transaction_categories", ) TEMPLATE_DIRS = ( BASE_DIR + '/budget/templates/', ) STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) ROOT_URLCONF = 'simple_budget.urls' WSGI_APPLICATION = 'simple_budget.wsgi.application' with open(BASE_DIR + '/simple_budget/config.yaml') as f: config = yaml.load(f) if 'server_type' in config and config['server_type'] == 'LIVE': DB_HOST = os.environ['POSTGRES_PORT_5432_TCP_ADDR'] TEMPLATE_DEBUG = False DEBUG = False else: DB_HOST = os.environ['POSTGRES_PORT_5432_TCP_ADDR'] TEMPLATE_DEBUG = True DEBUG = True if 'python_path' in config: PYTHON_PATH = config['python_path'] else: PYTHON_PATH = None if 'backup_path' in config: BACKUP_PATH = config['backup_path'] else: BACKUP_PATH = None if 'backup_files_to_keep' in config: BACKUP_FILES_TO_KEEP = config['backup_files_to_keep'] else: BACKUP_FILES_TO_KEEP = None if 'start_date' in config: START_DATE = config['start_date'] else: START_DATE = None # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'accounts', 'USER': 'accounts', 'HOST': DB_HOST, 'PORT': 5432, 'PASSWORD': '<PASSWORD>' } } # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LOGIN_URL = '/login' LANGUAGE_CODE = 'en-gb' TIME_ZONE = 'Europe/London' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' TEMP_SAVE_PATH = '/tmp/' QUICKEN_IMPORT_ACTIVE = True SESSION_SAVE_EVERY_REQUEST = True <file_sep>/simple_budget/models/transaction/transaction.py from __future__ import unicode_literals from django.db import models from simple_budget.models.transaction.transaction_line import TransactionLine from simple_budget.models.account.account import Account from django.conf import settings from django.db import transaction as db_transaction from django.db import DatabaseError import os import subprocess import time class Transaction(models.Model): """ transaction model """ transaction_id = models.AutoField(primary_key=True) transaction_date = models.DateField(null=False, blank=False) account = models.ForeignKey(Account, blank=True, null=True) class Meta: db_table = 'transaction' @db_transaction.atomic def add_edit_transaction(self, action, data): """ :param action: add|edit :param data: transaction data :return: boolean """ if action == 'edit': self.delete_transaction(data) new_transaction = Transaction(transaction_date=data['transaction_date'], account_id=data['account_id'],) new_transaction.save() if not new_transaction.pk: raise DatabaseError('Unable to save transaction') if (new_transaction.pk and data['transaction_category_id'] and data['amount']): transaction_line = \ TransactionLine(transaction_id= new_transaction.pk, transaction_category_id= data['transaction_category_id'], amount= data['amount']) transaction_line.save() if not transaction_line.pk: raise DatabaseError('Unable to save transaction line') @db_transaction.atomic def delete_transaction(self, data): """ delete a transaction and all associated transaction lines :param data: transaction data :return: boolean """ try: transaction_line = \ TransactionLine.objects.filter( pk=data['transaction_line_id'])[0] except (IndexError, KeyError): raise DatabaseError('invalid transaction line') TransactionLine.objects.filter( transaction_id=transaction_line.transaction_id).delete() Transaction.objects.filter( transaction_id=transaction_line.transaction_id).delete() @staticmethod def process_upload_quicken_file(quicken_file): """ saves and process the uploaded quicken file :param quicken_file: :return: boolean """ filename = settings.TEMP_SAVE_PATH + quicken_file.name.lower() with open(filename, 'w+') as destination: for chunk in quicken_file.chunks(): destination.write(chunk) if not os.path.isfile(filename): return False else: subprocess.Popen([settings.PYTHON_PATH, '%s/simple_budget/scripts/qif_file_parser.py' % (settings.BASE_DIR,), '-p', filename]) time.sleep(5) return True <file_sep>/static/assets/js/main.js $(document).ready(function() { "use strict"; if(['login'].indexOf(window.location.pathname.replace(/\//g, '')) == -1) { setInterval(function() { $.ajax( "/check_auth", function() { }).fail(function() { window.location.href = '/login'; }); }, (17 * 60 * 1000)); } });<file_sep>/simple_budget/helper/helper.py from urlparse import urlparse, parse_qs def clean_message_from_url(url): """ strip message parameter from url :param url: :return: string """ if not url: return None o = urlparse(url) if not o.query: return url query_string = '' for key, value in parse_qs(o.query).iteritems(): if key != 'message': query_string = '%s%s=%s&' % (query_string, key, value[0],) url = '%s://%s%s' % (o.scheme, o.netloc, o.path,) if query_string: url = '%s?%s' % (url, query_string.strip('&'),) return url<file_sep>/simple_budget/forms/budget/clone_budget_form.py from django import forms from simple_budget.models.budget import Budget class CloneBudgetForm(forms.Form): budget_id = forms.CharField(widget=forms.HiddenInput(), required=False) referrer = forms.CharField(widget=forms.HiddenInput(), required=False) budget_name = \ forms.CharField( max_length=200, required=True, label="Name", widget=forms.TextInput(attrs={'class': 'form-control', 'autocomplete': 'off'})) budget_description = \ forms.CharField( max_length=200, required=True, label="Description", widget=forms.TextInput(attrs={'class': 'form-control', 'autocomplete': 'off'})) def clean_budget_name(self): """ ensure only one budget is flagged as master :return: """ if Budget.objects.filter(budget_name=self.cleaned_data['budget_name']): raise forms.ValidationError( "Budget with this name already exists.") return self.cleaned_data['budget_name'] <file_sep>/simple_budget/models/transaction/transaction_line.py from __future__ import unicode_literals from django.db import models from sqlalchemy.sql.expression import between from sqlalchemy import desc, asc, func, case from sqlalchemy.orm import aliased from simple_budget.models.transaction.transaction_category import \ TransactionCategory from simple_budget.helper.sql import SQL class TransactionLine(models.Model): """ transaction line model """ transaction_line_id = models.AutoField(primary_key=True) transaction = models.ForeignKey("Transaction", blank=True, null=True) transaction_category = \ models.ForeignKey(TransactionCategory, blank=True, null=True) amount = \ models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) class Meta: db_table = 'transaction_line' @staticmethod def transaction_lines(start_date, end_date, sort): """ retrieves a list of transaction lines for the specified dates :return: """ sql = SQL() sort_order = {0: [sql.transaction.c.transaction_date], 2: ['category'], 4: [sql.budget_category.c.budget_category], 6: [sql.transaction_line.c.amount], 8: [sql.account.c.account_name], 10: [sql.budget_type.c.budget_type]} try: sort = int(sort) sort_lookup = sort - (sort % 2) sort_order[sort_lookup] except (ValueError, IndexError, TypeError): sort = 0 sort_lookup = 0 parent_transaction_category = aliased(sql.transaction_category) transaction_lines = sql.db_session.query( sql.transaction_line.c.transaction_line_id.label('id'), sql.account.c.account_name, sql.account.c.account_id, sql.budget_category.c.budget_category, sql.budget_type.c.budget_type, sql.transaction.c.transaction_date, sql.transaction_line.c.amount, case([(parent_transaction_category.c.transaction_category.isnot(None), func.CONCAT(parent_transaction_category.c.transaction_category, ' >> ', sql.transaction_category.c.transaction_category)) ], else_=sql.transaction_category.c.transaction_category). \ label('category')).\ join(sql.transaction, sql.transaction.c.transaction_id== sql.transaction_line.c.transaction_id). \ filter(sql.budget_category.c.budget_category_id== sql.transaction_category.c.budget_category_id). \ filter(between(sql.transaction.c.transaction_date, start_date, end_date)). \ join(sql.transaction_category, sql.transaction_category.c.transaction_category_id== sql.transaction_line.c.transaction_category_id). \ join(sql.budget_category, sql.budget_category.c.budget_category_id== sql.transaction_category.c.budget_category_id). \ join(sql.budget_type, sql.budget_category.c.budget_type_id== sql.budget_type.c.budget_type_id). \ join(sql.account, sql.account.c.account_id== sql.transaction.c.account_id). \ outerjoin(parent_transaction_category, sql.transaction_category.c.transaction_category_parent_id == parent_transaction_category.c.transaction_category_id).\ filter(sql.transaction_category.c.transaction_category != 'Holding') if sort % 2: transaction_lines = \ transaction_lines.order_by(desc(sort_order[sort_lookup][0])) else: transaction_lines = \ transaction_lines.order_by(asc(sort_order[sort_lookup][0])) return [sort, transaction_lines] <file_sep>/simple_budget/migrations/0014_auto_20150217_1415.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('simple_budget', '0013_auto_20150217_1414'), ] operations = [ migrations.RemoveField( model_name='accountbalance', name='account', ), migrations.DeleteModel( name='AccountBalance', ), ] <file_sep>/simple_budget/forms/transaction/upload_quicken_file_form.py from django import forms class UploadQuickenFileForm(forms.Form): file = forms.FileField() referer = forms.CharField(widget=forms.HiddenInput(), required=False)<file_sep>/simple_budget/forms/transaction/add_edit_transaction_form.py # -*- coding: utf-8 -*- from django import forms from simple_budget.models.transaction.transaction_category import \ TransactionCategory from simple_budget.models.account.account import Account import re class AddEditTransactionForm(forms.Form): def __init__(self, *args, **kwargs): super(AddEditTransactionForm, self).__init__(*args, **kwargs) self.fields['transaction_category_id'].choices = \ [('', 'Please select a transaction category')] + \ [(o.transaction_category_id, str(o.category)) for o in TransactionCategory. transaction_category_mapping(sort=None, budget_category_id=None)[1]] self.fields['account_id'].choices = \ [('', 'Please select an account')] + \ [(o.account_id, str(o.account_name)) for o in Account.objects.filter(account_hidden=False). order_by('account_name')] transaction_line_id = forms.CharField(widget=forms.HiddenInput(), required=False) account_id = \ forms.ChoiceField( required=True, label='Account', widget=forms.Select(attrs={'class': 'form-control form-large'})) transaction_category_id = \ forms.ChoiceField( required=True, label='Transaction Category', widget=forms.Select(attrs={'class': 'form-control form-large'})) referer = forms.CharField(widget=forms.HiddenInput(), required=False) transaction_date = \ forms.DateField( required=True, input_formats=['%d %B, %Y'], label='Transaction Date', widget=forms.DateInput(format="%d %B, %Y", attrs={'class': 'form-control form-medium', 'readonly': 'readonly', 'autocomplete': 'off'})) amount = forms.CharField( max_length=200, required=True, label="Amount(£)", widget=forms.TextInput(attrs={'class': 'form-control form-medium', 'autocomplete': 'off'})) def is_valid(self): """ custom validation add transaction line """ invalid_float_error_message = 'Please enter a valid decimal' valid = super(AddEditTransactionForm, self).is_valid() if 'amount' in self.cleaned_data and self.cleaned_data['amount']: try: float(self.cleaned_data['amount']) if (re.search(r'\.', self.cleaned_data['amount']) and len(self.cleaned_data['amount'].rsplit('.')[-1]) != 2): self._errors['amount'] = \ self.error_class([invalid_float_error_message]) valid = False except ValueError: self._errors['amount'] = \ self.error_class([invalid_float_error_message]) valid = False return valid<file_sep>/simple_budget/views/views.py from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth import (authenticate, login as auth_login, logout as auth_logout) from django.contrib.auth.decorators import login_required from simple_budget.forms.login_form import LoginForm from django.http import HttpResponseRedirect from django.http import HttpResponse @login_required def index(request): """ index """ return render_to_response('index.html', {}, context_instance=RequestContext(request)) def logout(request): """ login view @author <NAME> <<EMAIL>> """ auth_logout(request) return HttpResponseRedirect('/login/?message=logged_out') def check_auth(request): """ determine if a user is authenticated """ if request.user.is_authenticated(): status = 200 else: status = 401 return HttpResponse(None, content_type='text/plain', status=status) def login(request): """ login form """ invalid_credentials = False if request.user.is_authenticated(): return HttpResponseRedirect('/') if request.method == 'POST': user = authenticate(username=request.POST.get('username', None), password=request.POST.get('password', None)) if user is not None and user.is_active: auth_login(request, user) request.session.set_expiry(900) return HttpResponseRedirect(request.POST.get('next', '/')) else: invalid_credentials = True form = LoginForm(request.POST) else: form = LoginForm(initial={'next': request.GET.get('next', '/')}) return render_to_response('login.html', {'form': form, 'invalid_credentials': invalid_credentials}, context_instance=RequestContext(request)) <file_sep>/simple_budget/forms/transaction/delete_transaction_form.py from django import forms class DeleteTransactionForm(forms.Form): transaction_line_id = forms.CharField(widget=forms.HiddenInput(), required=True) referer = forms.CharField(widget=forms.HiddenInput(), required=False)<file_sep>/simple_budget/models/budget/budget_type.py from __future__ import unicode_literals from django.db import models from datetime import datetime, date from simple_budget.helper.sql import SQL from simple_budget.settings import START_DATE from sqlalchemy import func from dateutil.relativedelta import relativedelta import decimal import calendar import re import collections class BudgetType(models.Model): """ budget type model """ budget_type_id = models.AutoField(primary_key=True) budget_type = models.TextField(blank=False, null=False) ordering = models.PositiveIntegerField(blank=False, null=False) class Meta: db_table = 'budget_type' def __unicode__(self): return self.budget_type @staticmethod def spending_by_budget_type(year=None): """ retrieves spending by budget type for the last 12 months """ simple_budget_start_date = datetime.strptime(START_DATE, '%Y-%m-%d') end_of_this_month = date(datetime.now().year, datetime.now().month, calendar.monthrange(datetime.now().year, datetime.now().month)[1]) if not year: date_trunc = 'YEAR' else: date_trunc = 'MONTH' simple_budget_start_date_previous_month = \ date(simple_budget_start_date.year, simple_budget_start_date.month, 1) - relativedelta(months=1) start_of_year = date(year, 1, 1) end_of_year = date(year, 12, 31) sql = SQL() spend = \ sql.db_session.query( sql.budget_type.c.budget_type, func.SUM(sql.transaction_line.c.amount).label('amount'), func.DATE_TRUNC(date_trunc, sql.transaction.c.transaction_date).\ label('date')).\ join(sql.budget_category, sql.budget_category.c.budget_type_id == sql.budget_type.c.budget_type_id).\ join(sql.transaction_category, sql.transaction_category.c.budget_category_id == sql.budget_category.c.budget_category_id).\ join(sql.transaction_line, sql.transaction_line.c.transaction_category_id == sql.transaction_category.c.transaction_category_id).\ join(sql.transaction, sql.transaction.c.transaction_id == sql.transaction_line.c.transaction_id).\ filter(sql.transaction.c.transaction_date >= simple_budget_start_date). \ filter(sql.transaction.c.transaction_date <= end_of_this_month) if year: spend = \ spend.filter(sql.transaction.c.transaction_date >= simple_budget_start_date_previous_month). \ filter(sql.transaction.c.transaction_date >= start_of_year). \ filter(sql.transaction.c.transaction_date <= end_of_year) spend = \ spend.group_by(sql.budget_type.c.budget_type, func.DATE_TRUNC(date_trunc, sql.transaction.c.transaction_date)). \ order_by(func.DATE_TRUNC(date_trunc, sql.transaction.c.transaction_date)) spend = spend.all() spending = {} average_spending = {} total_spending = {'income': 0, 'expense': 0, 'savings': 0, 'debt_repayment': 0, 'total': 0} if not spend: return [False, False, False] else: for s in spend: if not year: key = s.date.year else: key = str(date(s.date.year, s.date.month, s.date.day)) if not key in spending: spending[key] = {'date': s.date} category_key = re.sub(' ', '_', s.budget_type.lower()) if s.budget_type.lower() != 'income': spending[key][category_key] = s.amount * -1 else: spending[key][category_key] = abs(s.amount) if not year: if date.today().year == s.date.year: average_divisor = date.today().month else: if simple_budget_start_date.year == s.date.year: average_divisor = \ (12 - simple_budget_start_date.month) + 1 else: average_divisor = 12 spending[key][category_key+'_average'] = \ spending[key][category_key] / average_divisor for key, item in spending.iteritems(): item['debt_repayment'] = \ item['income'] - \ item['expense'] - \ item['savings'] if not year: if date.today().year == key: average_divisor = date.today().month else: if simple_budget_start_date.year == key: average_divisor = \ (12 - simple_budget_start_date.month) + 1 else: average_divisor = 12 item['debt_repayment_average'] = item['debt_repayment'] / average_divisor spending = collections.OrderedDict(sorted(spending.items(), reverse=True)) for key, item in spending.iteritems(): for item_key, value in item.iteritems(): if item_key != 'date' and not item_key in total_spending: total_spending[item_key] = value elif item_key != 'date': total_spending[item_key] += value for key, value in total_spending.iteritems(): average_spending[key] = decimal.Decimal(value) / \ decimal.Decimal(len(spending)) return [total_spending, average_spending, spending]<file_sep>/simple_budget/migrations/0004_remove_budgetcategory_budget_amount.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('simple_budget', '0003_budgetcategory_budget_amount'), ] operations = [ migrations.RemoveField( model_name='budgetcategory', name='budget_amount', ), ] <file_sep>/simple_budget/models/budget/budget.py from __future__ import unicode_literals from django.db import models, transaction, DatabaseError from django.db.models import Q from simple_budget.settings import START_DATE from simple_budget.models.budget.budget_amount import BudgetAmount from simple_budget.models.budget.budget_category import BudgetCategory from simple_budget.helper.sql import SQL from dateutil.relativedelta import relativedelta from datetime import datetime, date, timedelta from sqlalchemy import func, or_, and_, case, Table, MetaData from decimal import Decimal import re import calendar class Budget(models.Model): """ budget category model """ budget_id = models.AutoField(primary_key=True) budget_name = models.TextField(blank=False, null=False) budget_description = models.TextField(blank=False, null=False) budget_master = models.BooleanField(blank=False, null=False, default=False) class Meta: db_table = 'budget' def get_budget(self, start_date, end_date, budget_id=None): """ retrieves spending by budget category between the specified dates :return: dict """ if not start_date or not end_date: return [None, None, None] if not budget_id: budget = Budget.objects.filter(budget_master=True) if not budget: budget_id = None else: budget_id = budget[0].budget_id end_date_income = date(start_date.year, start_date.month, calendar.monthrange(start_date.year, start_date.month)[1]) start_date_income = date(end_date_income.year, end_date_income.month, 1) annual_start_date = date(start_date.year, start_date.month, 1) - \ relativedelta(years=1) annual_end_date = date(start_date.year, start_date.month, 1) - \ relativedelta(months=1) annual_end_date = date(annual_end_date.year, annual_end_date.month, calendar.monthrange(annual_end_date.year, annual_end_date.month)[1]) next_month_start_date = date(start_date.year, start_date.month, 1) + \ relativedelta(months=1) next_month_end_date = \ date(next_month_start_date.year, next_month_start_date.month, calendar.monthrange(next_month_start_date.year, next_month_start_date.month)[1]) quicken_start_date = datetime.strptime(START_DATE, '%Y-%m-%d').date() if annual_start_date < quicken_start_date: annual_divisor = \ ((annual_end_date.year - quicken_start_date.year) * 12 + \ annual_end_date.month - quicken_start_date.month) + 1 else: annual_divisor = 12 sql = SQL() budget_amount_future =\ Table('budget_amount', MetaData(), autoload=True, autoload_with=sql.db).alias('budget_amount_future') spend = sql.db_session.query( sql.budget_category.c.budget_category_id.label('id'), sql.budget_amount.c.budget_amount, budget_amount_future.c.budget_amount.label('budget_amount_future'), func.SUM(sql.transaction_line.c.amount).label('amount'), case([(sql.budget_type.c.budget_type == 'Expense', case([(func.SUM(sql.transaction_line.c.amount) < 0, sql.budget_amount.c.budget_amount - func.ABS(func.SUM(sql.transaction_line.c.amount)))], else_=sql.budget_amount.c.budget_amount + func.ABS(func.SUM(sql.transaction_line.c.amount)) )), (sql.budget_type.c.budget_type == 'Savings', case([(func.SUM(sql.transaction_line.c.amount) > 0, (sql.budget_amount.c.budget_amount + func.SUM(sql.transaction_line.c.amount)) * -1)], else_=func.ABS(func.SUM(sql.transaction_line.c.amount)) - sql.budget_amount.c.budget_amount )), (sql.budget_type.c.budget_type != 'Expense', func.ABS(func.SUM(sql.transaction_line.c.amount)) - sql.budget_amount.c.budget_amount ) ]).label('difference')).\ join(sql.budget_type, sql.budget_type.c.budget_type_id==sql.budget_category.c.budget_type_id). \ filter(sql.budget_type.c.budget_type != 'N/A').\ outerjoin(sql.transaction_category, sql.transaction_category.c.budget_category_id== sql.budget_category.c.budget_category_id). \ outerjoin(sql.budget, and_(sql.budget.c.budget_id == budget_id)). \ outerjoin(sql.budget_amount, and_(sql.budget.c.budget_id==sql.budget_amount.c.budget_id, sql.budget_amount.c.budget_category_id== sql.budget_category.c.budget_category_id, sql.budget_amount.c.start_date <= start_date, or_(sql.budget_amount.c.end_date == None, sql.budget_amount.c.end_date >= end_date))). \ outerjoin(budget_amount_future, and_(sql.budget.c.budget_id==budget_amount_future.c.budget_id, budget_amount_future.c.budget_category_id== sql.budget_category.c.budget_category_id, budget_amount_future.c.start_date <= next_month_start_date, or_(budget_amount_future.c.end_date == None, budget_amount_future.c.end_date >= next_month_end_date))). \ outerjoin(sql.transaction, or_(and_(sql.transaction.c.transaction_date.between(start_date, end_date), sql.budget_type.c.budget_type != 'Income').self_group(), and_(sql.transaction.c.transaction_date.between( start_date_income, end_date_income), sql.budget_type.c.budget_type == 'Income').self_group())). \ outerjoin(sql.transaction_line, and_(sql.transaction_line.c.transaction_id== sql.transaction.c.transaction_id, sql.transaction_category.c.transaction_category_id == sql.transaction_line.c.transaction_category_id)). \ group_by(sql.budget_category.c.budget_category_id, sql.budget_category.c.budget_category, sql.budget_amount.c.budget_amount, budget_amount_future.c.budget_amount, sql.budget_type.c.budget_type).subquery() annual_spend = sql.db_session.query( sql.transaction_category.c.budget_category_id.label('id'), case([(sql.budget_type.c.budget_type == 'Income', func.ROUND(func.ABS( func.SUM(sql.transaction_line.c.amount) / annual_divisor), 2)), ], else_= func.ROUND( (func.SUM(sql.transaction_line.c.amount * -1) / annual_divisor), 2)). label('amount')).\ filter(sql.transaction_line.c.transaction_category_id== sql.transaction_category.c.transaction_category_id). \ filter(sql.transaction.c.transaction_id== sql.transaction_line.c.transaction_id). \ filter(sql.budget_category.c.budget_category_id== sql.transaction_category.c.budget_category_id). \ filter(sql.budget_type.c.budget_type_id== sql.budget_category.c.budget_type_id). \ filter(sql.transaction.c.transaction_date.between(annual_start_date, annual_end_date)). \ filter(sql.transaction.c.transaction_date >= quicken_start_date). \ group_by(sql.transaction_category.c.budget_category_id, sql.budget_type.c.budget_type, sql.budget_category.c.budget_category).subquery() budget = \ sql.db_session.query(sql.budget_category.c.budget_category_id, sql.budget_category.c.budget_category, sql.budget_type.c.ordering, sql.budget_type.c.budget_type_id, sql.budget_type.c.budget_type, spend.c.budget_amount, spend.c.budget_amount_future, spend.c.difference.label('difference'), func.COALESCE(spend.c.budget_amount, 0).label('budget_amount'), spend.c.amount.label('actual_spend'), case([(and_(spend.c.difference != 0, spend.c.budget_amount > 0), func.ROUND(func.ABS((spend.c.difference / spend.c.budget_amount) * 100),2)), ], else_=0).label('difference_percent'), annual_spend.c.amount.label('average_annual_spend')). \ join(sql.budget_type, sql.budget_type.c.budget_type_id == sql.budget_category.c.budget_type_id). \ filter(sql.budget_type.c.budget_type != 'N/A').\ outerjoin(spend, and_(spend.c.id== sql.budget_category.c.budget_category_id)). \ outerjoin(annual_spend, and_(annual_spend.c.id== sql.budget_category.c.budget_category_id)). \ order_by(sql.budget_type.c.ordering.asc()). \ order_by(sql.budget_category.c.budget_category.asc()) transactions = budget.all() transactions, sorted_totals, grand_total = \ self.calculate_totals(transactions) return [transactions, sorted_totals, grand_total] def add_edit_budget(self, action, data): """ :param action: :param data: :return: boolean """ if 'budget_master' in data.keys(): budget_master = True else: budget_master = False try: with transaction.atomic(): if action == 'add': return self.add_budget(data, budget_master) elif action == 'edit': return self.edit_budget(data, budget_master) else: return False except DatabaseError: return False def delete_budget(self): """ delete the current budget and associated budget amounts :return: boolean """ try: with transaction.atomic(): BudgetAmount.objects.filter(budget_id=self.budget_id).delete() Budget.objects.filter(budget_id=self.budget_id).delete() return True except DatabaseError: return False @staticmethod def calculate_totals(transactions): """ calculates total income, expense and remaining :param transactions: :return: dict """ if not transactions: return [False, False] else: totals = {} grand_total = {'budget': 0, 'actual': 0, 'average_annual': 0, 'budget_future': 0} sorted_totals = [] for transaction in transactions: if transaction.budget_type not in totals: totals[transaction.budget_type] = \ {'actual': 0, 'budget': 0, 'average_annual': 0, 'budget_future':0, 'budget_type': transaction.budget_type, 'budget_type_id': transaction.budget_type_id, 'ordering': transaction.ordering} if transaction.actual_spend: if (transaction.budget_type == 'Savings' or (transaction.budget_type == 'Expense' and transaction.actual_spend > 0.01)): transaction.actual_spend *= -1 else: transaction.actual_spend = abs(transaction.actual_spend) totals[transaction.budget_type]['actual'] += \ transaction.actual_spend if transaction.budget_amount: totals[transaction.budget_type]['budget'] += \ transaction.budget_amount if transaction.budget_amount_future: totals[transaction.budget_type]['budget_future'] += \ transaction.budget_amount_future if transaction.average_annual_spend: totals[transaction.budget_type]['average_annual'] += \ transaction.average_annual_spend for key, total in totals.iteritems(): if total['budget_type'] != 'Savings': total['actual'] = abs(total['actual']) if total['budget_type'] == 'Expense': total['difference'] = total['budget'] - total['actual'] else: total['difference'] = total['actual'] - total['budget'] if total['difference'] != 0 and total['budget'] != 0: total['difference_percent'] = \ Decimal(abs((total['difference'] / total['budget']) * 100)).\ quantize(Decimal('.01')) sorted_totals.append(total) if key == 'Income': grand_total['budget'] += total['budget'] grand_total['budget_future'] += total['budget_future'] grand_total['actual'] += total['actual'] grand_total['average_annual'] += total['average_annual'] else: grand_total['budget'] -= total['budget'] grand_total['budget_future'] -= total['budget_future'] grand_total['actual'] -= total['actual'] grand_total['average_annual'] -= total['average_annual'] grand_total['difference'] = grand_total['actual'] - \ grand_total['budget'] if grand_total['difference'] != 0 and grand_total['budget'] != 0: grand_total['difference_percent'] = \ Decimal(abs((grand_total['difference'] / grand_total['budget']) * 100)). \ quantize(Decimal('.01')) sorted_totals = sorted(sorted_totals, key=lambda k: k['ordering']) return [transactions, sorted_totals, grand_total] @staticmethod def add_budget(data, budget_master): """ add a new budget """ budget = Budget(budget_name=data['budget_name'], budget_description=data['budget_description'], budget_master=budget_master) budget.save() start_date = date(datetime.now().year, datetime.now().month, 1) for key, value in data.iteritems(): budget_category_id = re.match(r'budget_category_(\d+)', key) if budget_category_id and budget_category_id.group(1): budget_category = \ BudgetCategory.objects.get( budget_category_id=budget_category_id.group(1)) if budget_category: try: value = float(value) except ValueError: value = 0 budget_amount = \ BudgetAmount(budget=budget, budget_category=budget_category, budget_amount=float(value), start_date=start_date, end_date=None) budget_amount.save() return True def edit_budget(self, data, budget_master): """ start_date = date(datetime.now().year, datetime.now().month, 1) end_date = date(datetime.now().year, datetime.now().month, calendar.monthrange(datetime.now().year, datetime.now().month)[1]) """ budget_input_fields = [{'regex': r'^budget_category_(\d+)$', 'future': False}, {'regex': r'^budget_category_(\d+)_future$', 'future': True}] budget = Budget.objects.get(pk=data['budget_id']) if not budget: return False budget.budget_name = data['budget_name'] budget.budget_description = data['budget_description'] budget.budget_master = budget_master budget.save() for budget_input_field in budget_input_fields: for key, value in data.iteritems(): budget_category_id = re.match(budget_input_field['regex'], key) if budget_category_id and budget_category_id.group(1) and value: self.update_budget_amounts(data['budget_id'], budget_category_id.group(1), Decimal(value), budget_input_field['future']) return True def clone_budget(self, data): """ clone a budget """ budget = Budget(budget_name=data['budget_name'], budget_description=data['budget_description']) budget.save() budget_to_clone = BudgetAmount.objects.filter(budget_id=data['budget_id']) for row in budget_to_clone: self.update_budget_amounts(budget.budget_id, row.budget_category_id, Decimal(row.budget_amount), False) return True @staticmethod def update_budget_amounts(budget_id, budget_category_id, value, future_value): today = datetime.now() next_month = date(today.year, today.month, 1) + relativedelta(months=1) prev_month = date(today.year, today.month, 1) - relativedelta(months=1) if future_value: start_this_month = date(next_month.year, next_month.month, 1) end_this_month = date(next_month.year, next_month.month, calendar.monthrange(next_month.year, next_month.month)[1]) end_last_month = date(today.year, today.month, calendar.monthrange(today.year, today.month)[1]) else: start_this_month = date(today.year, today.month, 1) end_this_month = date(today.year, today.month, calendar.monthrange(today.year, today.month)[1]) end_last_month = date(prev_month.year, prev_month.month, calendar.monthrange(prev_month.year, prev_month.month)[1]) budget_amount = \ BudgetAmount.objects.filter( Q(budget_id=budget_id), Q(budget_category=budget_category_id), Q(start_date__lte=start_this_month), Q(Q(end_date__gte=end_this_month) | Q(end_date=None))) if budget_amount: budget_amount = budget_amount[0] if not budget_amount and value: budget_amount = \ BudgetAmount(budget_id=budget_id, budget_category_id=budget_category_id, budget_amount=value, start_date=start_this_month, end_date=None) budget_amount.save() if budget_amount and value != budget_amount.budget_amount: budget_amount.end_date = end_last_month budget_amount.save() if value: budget_amount = \ BudgetAmount(budget_id=budget_id, budget_category_id=budget_category_id, budget_amount=value, start_date=start_this_month, end_date=None) budget_amount.save() <file_sep>/simple_budget/forms/transaction/delete_transaction_category_form.py from django import forms from simple_budget.models.transaction.transaction_category import \ TransactionCategory class DeleteTransactionCategoryForm(forms.Form): def __init__(self, *args, **kwargs): try: current_tc_id = kwargs.pop('current_tc_id') except KeyError: current_tc_id = False try: select_new_category = kwargs.pop('select_new_category') except KeyError: select_new_category = False super(DeleteTransactionCategoryForm, self).__init__(*args, **kwargs) self.fields['transfer_transaction_category_id'].choices = \ [('', 'Please select a transaction category')] self.fields['transfer_transaction_category_id'].required = \ select_new_category for o in TransactionCategory.\ transaction_category_mapping(sort=None, budget_category_id=None)[1]: if (not current_tc_id or o.transaction_category_id != int(current_tc_id)): self.fields['transfer_transaction_category_id'].choices +=\ [(o.transaction_category_id, str(o.category))] transaction_category_id = forms.CharField(widget=forms.HiddenInput(), required=True) transfer_transaction_category_id = \ forms.ChoiceField( label='Transaction Category', widget=forms.Select(attrs={'class': 'form-control form-large'})) referer = forms.CharField(widget=forms.HiddenInput(), required=False)<file_sep>/simple_budget/templates/message.html {% if user.is_authenticated %} {% if unassigned_transaction_categories %} <p class="bg-danger message"> <strong class="text-danger"> Warning!!! Their are <a class="text-danger" style="text-decoration:underline;" href="/transaction/category/?bc=0">{{unassigned_transaction_categories}}</a> transaction categories that are not assigned to a budget category. </strong> </p> {% endif %} {% if message %} <p class="bg-{{message_type}} message"> <strong class="text-{{message_type}}">{{message}}</strong> </p> {% if message_key == 'in_progress_quicken_file' %} <script> function get_quicken_file_status() { $.getJSON("/transaction/upload_quicken_file_status/", function (data) { }).done(function(response) { if (response.status) { if(response.status == 'complete') { window.location = '/budget/?message=quicken_upload_complete'; } else if(response.status == 'failed') { window.location = '/budget/?message=quicken_upload_failed'; } else if(response.status != 'in_progress') { window.location = '/budget/'; } } } ); } setInterval(function () { get_quicken_file_status(); }, 10000); </script> {% endif %} {% endif %} {% endif %}<file_sep>/simple_budget/migrations/0005_accounttype.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('simple_budget', '0004_remove_budgetcategory_budget_amount'), ] operations = [ migrations.CreateModel( name='AccountType', fields=[ ('account_type_id', models.AutoField(serialize=False, primary_key=True)), ('account_type', models.TextField()), ('ordering', models.PositiveIntegerField()), ], options={ 'db_table': 'account_type', }, bases=(models.Model,), ), ] <file_sep>/README.md simple_budget ============= Simple budgeting tool using parsed quicken QIF data (Python(Django)) <file_sep>/simple_budget/templatetags/templatetags.py from datetime import datetime from django import template register = template.Library() @register.filter(name='in_the_future') def in_the_future(date): try: if datetime.strptime(str(date), '%Y-%m-%d') > datetime.now(): return True else: return False except ValueError: return False @register.filter(name='currency') def currency(value): if value: return "{:,.2f}".format(value) return '-' @register.filter(name='lookup') def lookup(value, arg): return value[arg]<file_sep>/simple_budget/templates/account/accounts.html {% extends "base.html" %} {% load templatetags %} {% block content %} {% if accounts %} <table id="budget" class="table table-condensed table-striped table-bordered"> <tr> <th id="table_header" colspan="6"> <div class="dropdown" style="float:right;"> <a class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown" href="#"> Actions&nbsp;<span class="caret"></span> </a> <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel"> {% if user.is_superuser %} <li> <a role="menuitem" href="/account/add"> Add Account </a> </li> {% endif %} <li> <a role="menuitem" href="/account/add"> Show inactive </a> </li> </ul> </div> <div id="title">Accounts</div> </th> </tr> <tr> <th style="width:55%;">Account</th> <th style="width:30%;">Type</th> <th style="width:15%;">Balance(£)</th> </tr> {% for account_type, balance in summary.items %} {% for account in accounts %} {% if account.account_type == account_type %} <tr> <td> <a href="/account/{{account.account_id}}/"> {{account.account_name}} </a> </td> <td>{{account.account_type}}</td> <td class="currency"> {{account.balance|currency}} </td> </tr> {% endif %} {% endfor %} <tr> <td colspan="6" class="seperator">&nbsp;</td> </tr> <tr> <td colspan="2"> <strong>Total {{account_type}}(£)</strong> </td> <td class="currency {% if balance > 0 %} success {% else %} warning {% endif %}"> {{balance|currency}} </td> </tr> <tr> <td colspan="6" class="seperator">&nbsp;</td> </tr> {% endfor %} <tr> <td colspan="2"><strong>Grand Total(£)</strong></td> <td class="currency {% if grand_total > 0 %} success {% else %} warning {% endif %}"> {{grand_total|currency}} </td> </tr> <tr> <td colspan="6" class="seperator">&nbsp;</td> </tr> </table> {% endif %} {% endblock %}<file_sep>/simple_budget/views/transaction/transaction.py from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse from django.template import RequestContext from django.db import DatabaseError from django.contrib.auth.decorators import login_required, user_passes_test from simple_budget.models.transaction.transaction_category import \ TransactionCategory from simple_budget.forms.transaction.add_edit_transaction_category_form import \ AddEditTransactionCategoryForm from simple_budget.forms.transaction.delete_transaction_category_form import \ DeleteTransactionCategoryForm from simple_budget.models.transaction.transaction import Transaction from simple_budget.models.transaction.transaction_line import TransactionLine from simple_budget.forms.transaction.upload_quicken_file_form import \ UploadQuickenFileForm from simple_budget.forms.transaction.add_edit_transaction_form import \ AddEditTransactionForm from simple_budget.forms.transaction.delete_transaction_form import \ DeleteTransactionForm from simple_budget.models.transaction.qif_parser import QIFParser from simple_budget.helper.date_calculation import DateCalculation from simple_budget.helper.helper import clean_message_from_url from django.conf import settings import json import re @login_required def transactions(request): """ display transaction log """ prev_month, next_month, start_date, end_date, today = \ DateCalculation.calculate_dates(request.GET.get('date', None)) sort, monthly_transactions = \ TransactionLine.transaction_lines(start_date, end_date, request.GET.get('sort', None)) return render_to_response('transaction/transactions.html', {'date': today, 'sort': sort, 'next_month': next_month, 'prev_month': prev_month, 'transactions': monthly_transactions}, context_instance=RequestContext(request)) @login_required @user_passes_test(lambda u: u.is_superuser, login_url='/?message=no_permissions_error', redirect_field_name=None) def add_edit_transaction(request, action, transaction_line_id): """ add/edit a transaction :param request: :return: """ if action == 'edit': message = 'transaction_edit' transaction_line = get_object_or_404(TransactionLine, pk=transaction_line_id) else: message = 'transaction_add' if request.method == 'POST': if request.POST.get('submit', None) != 'Submit': return HttpResponseRedirect(request.POST.get('referer', '/')) form = AddEditTransactionForm(request.POST) if form.is_valid(): referer = request.POST.get('referer', '/transactions/?date=') if re.search('\?', referer): sep = '&' else: sep = '?' try: Transaction().add_edit_transaction(action, form.cleaned_data) return HttpResponseRedirect( '%s%smessage=%s_success' % (referer, sep, message,)) except DatabaseError: return HttpResponseRedirect( '%s%smessage=%s_failure' % (referer, sep, message,)) else: referer = \ clean_message_from_url(request.META.get('HTTP_REFERER', None)) if action == 'edit': form = AddEditTransactionForm( initial={'referer': referer, 'transaction_line_id': transaction_line.pk, 'account_id': transaction_line.transaction.account_id, 'transaction_category_id': transaction_line.transaction_category_id, 'transaction_date': transaction_line.transaction.transaction_date, 'amount': transaction_line.amount}) else: form = AddEditTransactionForm( initial={'referer': referer}) return render_to_response('transaction/add_edit_transaction.html', {'form': form, 'action': action}, context_instance=RequestContext(request)) @login_required @user_passes_test(lambda u: u.is_superuser, login_url='/?message=no_permissions_error', redirect_field_name=None) def delete_transaction(request, transaction_line_id): """ deletes the supplied transaction :param request: :return: """ transaction_line = get_object_or_404(TransactionLine, pk=transaction_line_id) referer = \ clean_message_from_url(request.META.get('HTTP_REFERER', None)) if request.method == 'POST': if request.POST.get('submit', None) == 'Cancel': return HttpResponseRedirect(request.POST.get('referer', '/')) form = DeleteTransactionForm(request.POST) if form.is_valid(): try: Transaction().delete_transaction(form.cleaned_data) return HttpResponseRedirect( '/transactions/?message=transaction_delete_success') except DatabaseError: return HttpResponseRedirect( '/transactions/?message=transaction_delete_failure') form = DeleteTransactionForm( initial={'transaction_line_id': transaction_line.pk, 'referer': referer}) return render_to_response('transaction/delete_transaction.html', {'form': form, 'refer': referer}, context_instance=RequestContext(request)) @login_required def category(request): """ displays transaction category --> budget category mapping """ budget_category_id = request.GET.get('bc', None) sort, transaction_categories = \ TransactionCategory.transaction_category_mapping( request.GET.get('sort', None), budget_category_id) return render_to_response('transaction/category.html', {'sort': sort, 'budget_category_id': budget_category_id, 'transaction_categories': transaction_categories}, context_instance=RequestContext(request)) @login_required @user_passes_test(lambda u: u.is_superuser, login_url='/?message=no_permissions_error', redirect_field_name=None) def add_edit_transaction_category(request, action, transaction_category_id=None): """ adds/edits budget category :param request: :return: """ referer = \ clean_message_from_url(request.META.get('HTTP_REFERER', None)) if transaction_category_id: transaction_category_has_children = \ bool(TransactionCategory.objects.filter( transaction_category_parent_id=transaction_category_id)) else: transaction_category_has_children = None if request.method == 'POST': if request.POST.get('submit', None) == 'Cancel': return HttpResponseRedirect(request.POST.get('referer', '/')) form = AddEditTransactionCategoryForm(request.POST) if form.is_valid(): try: if form.cleaned_data['transaction_category_id']: transaction_category = \ TransactionCategory( transaction_category_id= form.cleaned_data['transaction_category_id'], transaction_category_parent_id= form.cleaned_data['transaction_category_parent_id'], budget_category_id= form.cleaned_data['budget_category'], transaction_category= form.cleaned_data['transaction_category']) else: transaction_category = \ TransactionCategory( transaction_category_parent_id= form.cleaned_data['transaction_category_parent_id'], budget_category_id= form.cleaned_data['budget_category'], transaction_category= form.cleaned_data['transaction_category']) transaction_category.save() if transaction_category.pk: message = 'success' else: message = 'failure' except DatabaseError: message = 'failure' return HttpResponseRedirect('/transaction/category/?' 'message=transaction_category_%s_%s' % (action, message,)) else: if action == 'edit' and transaction_category_id: transaction_category = get_object_or_404(TransactionCategory, pk=transaction_category_id) form = AddEditTransactionCategoryForm( initial={'referer': referer, 'transaction_category_id': transaction_category.transaction_category_id, 'transaction_category_parent_id': transaction_category.transaction_category_parent_id, 'transaction_category': transaction_category.transaction_category, 'budget_category': transaction_category.budget_category_id}) else: form = AddEditTransactionCategoryForm(initial={'referer': referer}) return render_to_response('transaction/add_edit_transaction_category.html', {'form': form, 'action': action, 'transaction_category_has_children': transaction_category_has_children}, context_instance=RequestContext(request)) @login_required @user_passes_test(lambda u: u.is_superuser, login_url='/?message=no_permissions_error', redirect_field_name=None) def delete_transaction_category(request, transaction_category_id): """ deletes the supplied transaction category :param request: :return: """ transaction_category = get_object_or_404(TransactionCategory, pk=transaction_category_id) referer = \ clean_message_from_url(request.META.get('HTTP_REFERER', None)) transaction_lines = \ TransactionLine.objects.filter(transaction_category_id= transaction_category_id).count() transaction_category_children = \ bool(TransactionCategory.objects.filter( transaction_category_parent_id=transaction_category_id).count()) if request.method == 'POST': if (request.POST.get('submit', None) == 'Cancel' or transaction_category_children): return HttpResponseRedirect(request.POST.get('referer', '/')) form = \ DeleteTransactionCategoryForm( request.POST, current_tc_id=transaction_category_id, select_new_category=bool(transaction_lines)) if form.is_valid(): try: if form.cleaned_data['transfer_transaction_category_id']: TransactionLine.objects.filter(transaction_category_id= transaction_category_id).\ update(transaction_category_id= form.cleaned_data['transfer_transaction_category_id']) transaction_category.delete() return HttpResponseRedirect( '/transaction/category/?' 'message=transaction_category_delete_success') except DatabaseError: return HttpResponseRedirect( '/transaction/category/?' 'message=transaction_category_delete_failure') else: form = DeleteTransactionCategoryForm( current_tc_id=transaction_category_id, initial={'transaction_category_id': transaction_category.pk, 'referer': referer}) return render_to_response('transaction/delete_transaction_category.html', {'form': form, 'transaction_lines': transaction_lines, 'transaction_category_children': transaction_category_children, 'refer': referer}, context_instance=RequestContext(request)) @login_required @user_passes_test(lambda u: u.is_superuser, login_url='/?message=no_permissions_error', redirect_field_name=None) def upload_quicken_file(request): """ processes an uploaded quicken file """ if not settings.QUICKEN_IMPORT_ACTIVE: return HttpResponseRedirect('/') if request.method == 'POST': if request.POST.get('submit', None) == 'Cancel': return HttpResponseRedirect(request.POST.get('referer', '/')) form = UploadQuickenFileForm(request.POST, request.FILES) if form.is_valid(): if Transaction.process_upload_quicken_file(request.FILES['file']): return HttpResponseRedirect('/budget/?message=upload_success') else: return HttpResponseRedirect('/budget/?message=upload_failure') else: referer = \ clean_message_from_url(request.META.get('HTTP_REFERER', None)) form = UploadQuickenFileForm(initial={'referer': referer}) return render_to_response('transaction/upload_quicken_file.html', {'form': form}, context_instance=RequestContext(request)) @login_required def upload_quicken_file_status(request): """ gets the status for the last uploaded qif file :return: """ return HttpResponse(json.dumps({'status': QIFParser.get_status()}), content_type='application/json')<file_sep>/simple_budget/helper/message.py class Message(object): MESSAGES = {'upload_success': {'message': 'Quicken QIF successfully uploaded.', 'type': 'success'}, 'quicken_upload_complete': {'message': 'Quicken QIF successfully processed.', 'type': 'success'}, 'quicken_upload_failed': {'message': 'An error occurred processing Quicken QIF file.', 'type': 'danger'}, 'transaction_edit_success': {'message': 'Transaction edited.', 'type': 'success'}, 'transaction_edit_failure': {'message': 'An error occurred editing the transaction.', 'type': 'danger'}, 'transaction_add_success': {'message': 'Transaction added.', 'type': 'success'}, 'transaction_add_failure': {'message': 'An error occurred adding a new transaction.', 'type': 'danger'}, 'budget_category_add_success': {'message': 'Budget category added.', 'type': 'success'}, 'budget_category_add_failure': {'message': 'An error occurred adding a new ' 'budget category.', 'type': 'danger'}, 'budget_category_edit_success': {'message': 'Budget category edited.', 'type': 'success'}, 'budget_category_edit_failure': {'message': 'An error occurred editing a ' 'budget category.', 'type': 'danger'}, 'transaction_category_add_success': {'message': 'Transaction category added.', 'type': 'success'}, 'transaction_category_add_failure': {'message': 'An error occurred adding a new ' 'transaction category.', 'type': 'danger'}, 'transaction_category_edit_success': {'message': 'Transaction category edited.', 'type': 'success'}, 'transaction_category_edit_failure': {'message': 'An error occurred editing a ' 'transaction category.', 'type': 'danger'}, 'transaction_category_delete_success': {'message': 'Transaction category deleted.', 'type': 'success'}, 'transaction_category_delete_failure': {'message': 'An error occurred deleting a ' 'transaction category.', 'type': 'danger'}, 'budget_add_success': {'message': 'Budget added.', 'type': 'success'}, 'budget_add_failure': {'message': 'An error occurred adding a budget.', 'type': 'danger'}, 'budget_edit_success': {'message': 'Budget edited.', 'type': 'success'}, 'budget_edit_failure': {'message': 'An error occurred editing a budget.', 'type': 'danger'}, 'budget_category_delete_success': {'message': 'Budget category deleted.', 'type': 'success'}, 'budget_category_delete_failure': {'message': 'An error occurred deleting a ' 'budget category.', 'type': 'danger'}, 'transaction_delete_success': {'message': 'Transaction deleted.', 'type': 'success'}, 'budget_delete_success': {'message': 'Budget deleted.', 'type': 'success'}, 'budget_delete_failure': {'message': 'An error occurred deleting the budget.', 'type': 'danger'}, 'budget_clone_success': {'message': 'Budget cloned.', 'type': 'success'}, 'budget_clone_failure': {'message': 'An error occurred cloning the budget.', 'type': 'danger'}, 'transaction_delete_failure': {'message': 'An error occurred deleting a transaction.', 'type': 'danger'}, 'no_permissions_error': {'message': 'You do no have permission to access the ' 'requested resource.', 'type': 'danger'}, 'logged_out': {'message': 'You have logged out.', 'type': 'success'}, 'in_progress_quicken_file': {'message': 'Quicken QIF file processing.', 'type': 'success'}} <file_sep>/simple_budget/scripts/qif_file_parser.py #!/usr/bin/python # -*- coding: utf-8 -*- """ quicken qif parser. File format details taken from http://en.wikipedia.org/wiki/Quicken_Interchange_Format """ from datetime import datetime from optparse import OptionParser import re import sys import os.path import yaml import django sys.path.append(os.path.join(os.path.dirname(__file__), '../../../simple_budget')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "simple_budget.settings") from simple_budget.helper.sql import SQL from simple_budget.models.transaction.qif_parser import QIFParser class QuickenException(Exception): pass class Quicken(object): CONFIG_PATH = os.path.dirname(os.path.realpath(__file__)) + '/../config.yaml' sql = None transfer_accounts = None references = None always_an_expense = None def __init__(self): """ init """ django.setup() self.sql = SQL() self.read_config() def main(self): """ entry point when running script from command line """ parser = OptionParser() parser.add_option("-p", "--path", dest="path", metavar="path", help="path to quicken file") (options, args) = parser.parse_args() if not options.path: parser.print_help() else: if not os.path.isfile(options.path): raise QuickenException("QIF file does not exist") if not self.sql.db: raise QuickenException("No Database Connection") try: qif_parser = QIFParser() qif_parser.parse_status = 'in_progress' qif_parser.save() self.clean_db() self.parse_quicken_file(options.path) self.clean_childless_transactions() self.delete_quicken_file(options.path) self.sql.db_session.commit() qif_parser.parse_status = 'complete' qif_parser.save() except Exception, ex: self.sql.db_session.rollback() qif_parser.parse_status = 'failed' qif_parser.save() raise Exception(ex) def read_config(self): """ reads config file, connects to DB and sets appropriate class variables """ with open(self.CONFIG_PATH) as f: config = yaml.load(f) if 'accounts' in config: self.transfer_accounts = config['accounts'] if 'references' in config: self.references = config['references'] if 'always_an_expense' in config: self.always_an_expense = config['always_an_expense'] def clean_db(self): """ truncates all table and resets all sequences """ self.sql.db_session.execute( "ALTER SEQUENCE transaction_id RESTART WITH 1") self.sql.db_session.execute( "ALTER SEQUENCE transaction_line_id RESTART WITH 1") self.sql.db_session.execute( "DELETE FROM transaction_line CASCADE") self.sql.db_session.execute( "DELETE FROM transaction CASCADE") def parse_quicken_file(self, quicken_file): """ parse quicken qif file for transactions """ with open(quicken_file, 'r') as f: transaction_found = False negate_amount = False account_found = False account_id = False transaction = {} for line in f: if line[0:8] == '!Account': account_found = True if line[0] == 'N' and not transaction_found and account_found: account_found = False account_id = self.get_account_id(line[1:].strip()) if line[0] == 'D': try: date = datetime.strptime(line[1:].strip(), '%d/%m/%y') transaction_found = True transaction = {'date': date.strftime('%Y-%m-%d'), 'split': [], 'category': None, 'reference': None, 'sub_category': None} except ValueError: transaction = {} transaction_found = False elif transaction_found and line[0] == 'T': transaction['amount'] = self.parse_amount(line[1:]) elif transaction_found and line[0] == 'L': transaction['category'], transaction['sub_category'] =\ self.split_category(line[1:]) elif transaction_found and line[0] == 'S': category, sub_category = self.split_category(line[1:]) elif transaction_found and (line[0] == 'N' or line[0] == 'M'): transaction['reference'] = line[1:].strip() if line.strip() == 'NXOut': negate_amount = True if (transaction['reference'].lower() == 'sipp contribution claim' or transaction['reference'] == 'emp_pen' or transaction['reference'] == 'shares_in'): if transaction['reference'] == 'emp_pen': self.add_transaction_to_holding_account(transaction, account_id, 'Pension', 'Employment') if transaction['reference'].lower() == 'sipp contribution claim': self.add_transaction_to_holding_account(transaction, account_id, 'Sipp Contribution Rebate', 'Pension') if transaction['reference'].lower() == 'shares_in': self.add_transaction_to_holding_account(transaction, account_id, 'Employee Shares', 'Employment') transaction['split'].append({'category': 'Holding', 'sub_category': None, 'amount': transaction['amount']}) elif transaction_found and line[0] == '$' and category: transaction['split'].append( {'category': category, 'sub_category': sub_category, 'amount': self.parse_amount(line[1:])}) category = None sub_category = None elif line[0] == '^': if transaction and account_id: if not transaction['split'] and 'amount' in transaction: transaction['split'].append( {'category': transaction['category'], 'sub_category': transaction['sub_category'], 'amount': transaction['amount']}) transaction_id = \ self.save_transaction(account_id, transaction['date']) for transaction_line in transaction['split']: if transaction_line['category']: if (transaction['reference'] in self.references and transaction['reference'] != 'xxx'): transaction_line['sub_category'] = \ self.references[transaction['reference']] if transaction_line['category'][0] == '[': transaction_line['category'] = \ re.sub(r"\[|\]", "", transaction_line['category']) self.get_account_id(transaction_line['category']) transaction_category_id = \ self.save_category( transaction_line['sub_category'], transaction_line['category']) if ((transaction_line['sub_category'] in self.always_an_expense or transaction_line['category'] in self.always_an_expense) and transaction_line['amount'] > 0): transaction_line['amount'] *= -1 if negate_amount: transaction_line['amount'] *= -1 self.save_transaction_line( transaction_id, transaction_category_id, transaction_line['amount']) transaction_found = False negate_amount = False transaction = {} def get_account_id(self, account_name): """ get the account_id for the named account @return integer """ account_name = re.sub(r"\[|\]", "", account_name) account_id = self.sql.db_session.query( self.sql.account.c.account_id).\ filter(account_name == self.sql.account.c.account_name).scalar() if not account_id: account_id = self.add_account(account_name) return account_id def add_account(self, account_name): """ add a new account :param account_name: @return integer """ account_name = re.sub(r"\[|\]", "", account_name) account_id = self.sql.db_session.execute( self.sql.account.insert().\ values(account_name=account_name, account_hidden=False).\ returning(self.sql.account.c.account_id)).scalar() if not self.get_category_id(account_name, None): budget_category_id = self.sql.db_session.query( self.sql.budget_category.c.budget_category_id). \ filter(self.sql.budget_category.c.budget_category == 'n/a'). \ scalar() self.sql.db_session.execute( self.sql.transaction_category.insert(). \ values(transaction_category=account_name, budget_category_id=budget_category_id, transaction_category_parent_id=None)) return account_id def save_transaction(self, account_id, transaction_date): """ saves the transaction """ return self.sql.db_session.execute( self.sql.transaction.insert(). \ values(transaction_date=transaction_date, account_id=account_id). \ returning(self.sql.transaction.c.transaction_id)).scalar() def save_transaction_line(self, transaction_id, transaction_category_id, amount): """ saves a transaction line @return integer transaction_line_id """ return self.sql.db_session.execute(self.sql.transaction_line.insert(). \ values(transaction_id=transaction_id, transaction_category_id=transaction_category_id, amount=amount). \ returning(self.sql.transaction_line.c.transaction_line_id)).scalar() def save_category(self, transaction_category, parent_transaction_category): """ saves the supplied transaction_category @return integer transaction_category_id """ if transaction_category: transaction_category = \ re.sub(r"\[|\]", "", transaction_category) if parent_transaction_category: parent_transaction_category = \ re.sub(r"\[|\]", "", parent_transaction_category) if not transaction_category: transaction_category = parent_transaction_category transaction_category_parent_id = None else: transaction_category_parent_id = \ self.get_category_id(parent_transaction_category, None) if not transaction_category_parent_id: self.sql.db_session.execute( self.sql.transaction_category.insert(). \ values(transaction_category=parent_transaction_category, transaction_category_parent_id=None)) transaction_category_parent_id = \ self.get_category_id(parent_transaction_category, None) transaction_category_id = self.get_category_id( transaction_category, transaction_category_parent_id) if transaction_category_id: return transaction_category_id else: self.sql.db_session.execute(self.sql.transaction_category.insert().\ values(transaction_category=transaction_category, transaction_category_parent_id= transaction_category_parent_id)) return self.get_category_id(transaction_category, transaction_category_parent_id) def get_account_name(self, account_id): """ gets account name :param acount_id: :return: """ return self.sql.db_session.query(self.sql.account.c.account_name). \ filter(account_id == self.sql.account.c.account_id).scalar() def get_category_id(self, transaction_category, transaction_category_parent_id): """ gets the category id for the supplied category will return false if no matching category found. @return integer """ return self.sql.db_session.query( self.sql.transaction_category.c.transaction_category_id).\ filter(transaction_category == self.sql.transaction_category.c.transaction_category).\ filter(transaction_category_parent_id == self.sql.transaction_category.c.transaction_category_parent_id).\ scalar() def clean_childless_transactions(self): """ deletes all transaction that have no transaction lines @todo determine why calling delete() on result throws an exception because this is pretty damn inefficient. """ result = self.sql.db_session.query(self.sql.transaction). \ outerjoin(self.sql.transaction_line, self.sql.transaction.c.transaction_id== self.sql.transaction_line.c.transaction_id). \ filter(self.sql.transaction_line.c.transaction_line_id is None) for row in result: self.sql.db_session.execute( self.sql.transaction.delete(). \ where(self.sql.transaction.c.transaction_id== row.transaction_id)) def add_transaction_to_holding_account(self, transaction, account_id, transaction_parent_category, transaction_category): """" puts a transaction through holding account """ transaction_id = \ self.save_transaction(self.get_account_id('Holding'), transaction['date']) transaction_category_id = \ self.save_category(transaction_parent_category, transaction_category) self.save_transaction_line(transaction_id, transaction_category_id, transaction['amount']) transaction_id = \ self.save_transaction(self.get_account_id('Holding'), transaction['date']) transaction_category_id = \ self.save_category(None, self.get_account_name(account_id)) self.save_transaction_line(transaction_id, transaction_category_id, transaction['amount'] * -1) @staticmethod def split_category(category): """ splits category into category & sub category @return string """ try: category = category.strip().split(':') sub_category = category[1].strip() except IndexError: sub_category = None category = category[0].strip() return category, sub_category @staticmethod def delete_quicken_file(quicken_file): """ deletes the processed quicken file """ try: os.remove(quicken_file) except OSError: pass @staticmethod def parse_amount(amount): """ strips invalid chars from amount @return float """ return float(re.sub('[^0-9\-\.]', '', amount)) @staticmethod def display_message(message, message_type="normal"): """ displays the passed message with colour control characters """ if message_type == 'error': #red control_char = '\033[91m' else: #white control_char = '\033[0m' end_control_char = '\033[0m' print "%s%s%s" % (control_char, message, end_control_char) if __name__ == '__main__': try: Quicken().main() except Exception, e: Quicken.display_message(e, 'error') <file_sep>/simple_budget/models/account/account_type.py from __future__ import unicode_literals from django.db import models class AccountType(models.Model): """ account type model """ account_type_id = models.AutoField(primary_key=True) account_type = models.TextField(blank=False, null=False) ordering = models.PositiveIntegerField(blank=False, null=False) class Meta: db_table = 'account_type'<file_sep>/simple_budget/scripts/backup.py import os import sys import datetime sys.path.append(os.path.join(os.path.dirname(__file__), '../../../simple_budget')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "simple_budget.settings") from simple_budget.settings import (BACKUP_PATH, DATABASES) if not BACKUP_PATH or not os.path.isdir(BACKUP_PATH): print "Backup Path does not exist" sys.exit() sql_dump_file = 'accounts.zz50.co.uk.sql' os.popen('export PGPASSWORD="%s";' 'psql -U%s -h%s %s -c "VACUUM ANALYZE;" > /dev/null 2>&1' % (DATABASES['default']['PASSWORD'], DATABASES['default']['USER'], DATABASES['default']['HOST'], DATABASES['default']['NAME'],)) os.popen('export PGPASSWORD="%s";pg_dump -U%s -h%s %s ' '--inserts --clean > %s/%s' % (DATABASES['default']['PASSWORD'], DATABASES['default']['USER'], DATABASES['default']['HOST'], DATABASES['default']['NAME'], BACKUP_PATH, sql_dump_file)) if not os.path.isfile(BACKUP_PATH + '/' + sql_dump_file): print "Error Dumping DB" sys.exit() backup_file = 'accounts.zz50.co.uk_%s.tar.gz' % (datetime.date.today()) os.popen('cd %s;tar -czf %s %s' % (BACKUP_PATH, backup_file, sql_dump_file)) os.popen('rm %s/%s' % (BACKUP_PATH, sql_dump_file))<file_sep>/simple_budget/forms/login_form.py from django import forms class LoginForm(forms.Form): next = forms.CharField(widget=forms.HiddenInput(), required=True) username = forms.CharField( required=True, widget=forms.TextInput(attrs={'class': 'form-control form-large', 'autocomplete': 'off'})) password = forms.CharField( required=True, widget=forms.PasswordInput(attrs={'class': 'form-control form-large', 'autocomplete': 'off'}))<file_sep>/simple_budget/helper/sql.py from sqlalchemy import create_engine, Table, MetaData from sqlalchemy.dialects import postgresql from sqlalchemy.orm import sessionmaker from sqlalchemy.exc import DatabaseError from simple_budget.settings import DATABASES class SQL(object): db = None db_session = None budget_category = None transaction = None transaction_line = None connection_active = False def __init__(self): """ creates a db connecton using sqlalchemy :return: """ try: self.db = create_engine('postgresql://%s:%s@%s:%s/%s' % (DATABASES['default']['USER'], DATABASES['default']['PASSWORD'], DATABASES['default']['HOST'], DATABASES['default']['PORT'], DATABASES['default']['NAME'],)) session = sessionmaker() session.configure(bind=self.db) self.db_session = session() self.budget = Table('budget', MetaData(), autoload=True, autoload_with=self.db) self.budget_category = Table('budget_category', MetaData(), autoload=True, autoload_with=self.db) self.budget_type = Table('budget_type', MetaData(), autoload=True, autoload_with=self.db) self.budget_amount = Table('budget_amount', MetaData(), autoload=True, autoload_with=self.db) self.transaction = Table('transaction', MetaData(), autoload=True, autoload_with=self.db) self.transaction_category = Table('transaction_category', MetaData(), autoload=True, autoload_with=self.db) self.transaction_line = Table('transaction_line', MetaData(), autoload=True, autoload_with=self.db) self.account = Table('account', MetaData(), autoload=True, autoload_with=self.db) self.account_type = Table('account_type', MetaData(), autoload=True, autoload_with=self.db) except DatabaseError: self.db = False <file_sep>/simple_budget/urls.py from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^$', 'simple_budget.views.views.index', name='index'), url(r'^login/?$', 'simple_budget.views.views.login', name='login'), url(r'^logout/?$', 'simple_budget.views.views.logout', name='logout'), url(r'^check_auth/?$', 'simple_budget.views.views.check_auth', name='check_auth'), url(r'^accounts/?$', 'simple_budget.views.account.account.accounts', name='accounts'), url(r'^account/debt/?$', 'simple_budget.views.account.account.debt', name='debt'), url(r'^account/debt/summary/?$', 'simple_budget.views.account.account.debt_summary', name='debt_summary'), url(r'^budget/?$', 'simple_budget.views.budget.budget.budget', name='budget'), url(r'^budget/summary/?$', 'simple_budget.views.budget.budget.summary', name='summary'), url(r'^budget/(add|edit)/?([0-9]+)?/?$', 'simple_budget.views.budget.budget.add_edit_budgets'), url(r'^budget/delete/([0-9]+)/?$', 'simple_budget.views.budget.budget.delete_budgets'), url(r'^budget/clone/([0-9]+)/?$', 'simple_budget.views.budget.budget.clone_budgets', name="clone budget"), url(r'^budgets/([0-9]+)?/?$', 'simple_budget.views.budget.budget.budgets', name='budgets'), url(r'^transactions/?$', 'simple_budget.views.transaction.transaction.transactions', name='index'), url(r'^transaction/(add|edit)/?([0-9]+)?/?$', 'simple_budget.views.transaction.transaction.add_edit_transaction', name='transaction'), url(r'^transaction/delete/([0-9]+)/?$', 'simple_budget.views.transaction.transaction.delete_transaction', name='transaction'), url(r'^transaction/upload_quicken_file/?$', 'simple_budget.views.transaction.transaction.upload_quicken_file', name='upload_quicken_file'), url(r'^transaction/upload_quicken_file_status/?$', 'simple_budget.views.transaction.transaction.upload_quicken_file_status', name='upload_quicken_file_status'), url(r'^transaction/category/(add|edit)/?([0-9]+)?/?$', 'simple_budget.views.transaction.transaction.add_edit_transaction_category', name='transaction_category'), url(r'^transaction/category/delete/([0-9]+)/?$', 'simple_budget.views.transaction.transaction.delete_transaction_category', name='transaction_category'), url(r'^budget/category/?$', 'simple_budget.views.budget.budget.category', name='transaction_category'), url(r'^budget/category/(add|edit)/?([0-9]+)?/?$', 'simple_budget.views.budget.budget.add_edit_budget_category', name='transaction_category'), url(r'^budget/category/delete/([0-9]+)/?$', 'simple_budget.views.budget.budget.delete_budget_category', name='transaction_category'), url(r'^transaction/category/?$', 'simple_budget.views.transaction.transaction.category', name='transaction_category'))<file_sep>/simple_budget/context_processors.py from django.conf import settings from simple_budget.helper.message import Message from simple_budget.models.transaction.qif_parser import QIFParser from simple_budget.models.transaction.transaction_category import \ TransactionCategory def quicken_import_active(request): """ Is quicken import functionality turned on :param request: :return: """ return {'QUICKEN_IMPORT_ACTIVE': settings.QUICKEN_IMPORT_ACTIVE} def unassigned_transaction_categories(request): """ display a message if a transaction category is not assigned to a budget category :param request: :return: """ unassigned_transaction_categories = \ TransactionCategory.objects.filter(budget_category=None).count() return {"unassigned_transaction_categories": unassigned_transaction_categories} def get_message(request): """ get error/success messages for displaying to user :param request: :return: dict """ message_key = request.GET.get('message', None) message = None message_type = None if ((not message_key or message_key == 'upload_success') and QIFParser.get_status() == 'in_progress'): message_key = 'in_progress_quicken_file' try: message = Message.MESSAGES[message_key] message_type = message['type'] message = message['message'] except KeyError: pass return {'message': message, 'message_key': message_key, 'message_type': message_type} <file_sep>/simple_budget/migrations/0008_auto_20150207_0922.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('simple_budget', '0007_auto_20150207_0920'), ] operations = [ migrations.AlterModelTable( name='account', table='account', ), migrations.AlterModelTable( name='accountbalance', table='account_balance', ), ] <file_sep>/simple_budget/forms/budget/add_edit_budget_form.py from django import forms from simple_budget.models.budget import Budget class AddEditBudgetForm(forms.Form): def __init__(self, *args, **kwargs): try: transactions = kwargs.pop('transactions') except KeyError: transactions = False try: edit_budget = kwargs.pop('edit_budget') except KeyError: edit_budget = False super(AddEditBudgetForm, self).__init__(*args, **kwargs) if transactions: for transaction in transactions: field_id = "budget_category_%s" % \ (transaction.budget_category_id,) self.fields[field_id] = \ forms.CharField( max_length=8, required=False, widget=forms.HiddenInput(attrs= {'id':field_id, 'class': 'budget_category_hidden'})) if edit_budget: self.fields[field_id].initial = transaction.budget_amount field_id = "budget_category_%s_future" % \ (transaction.budget_category_id,) self.fields[field_id] = \ forms.CharField( max_length=8, required=False, widget=forms.HiddenInput(attrs= {'id':field_id, 'class': 'budget_category_hidden'})) self.fields[field_id].initial = \ transaction.budget_amount_future budget_id = forms.CharField(widget=forms.HiddenInput(), required=False) referer = forms.CharField(widget=forms.HiddenInput(), required=False) budget_name = \ forms.CharField( max_length=200, required=True, label="Name", widget=forms.TextInput(attrs={'class': 'form-control', 'autocomplete': 'off'})) budget_description = \ forms.CharField( max_length=200, required=True, label="Description", widget=forms.TextInput(attrs={'class': 'form-control', 'autocomplete': 'off'})) budget_master = forms.BooleanField(label="Master", required=False) def clean_budget_master(self): """ ensure only one budget is flagged as master :return: """ budget_master = self.cleaned_data['budget_master'] budget_id = self.cleaned_data['budget_id'] if budget_master: master_budget = Budget.objects.filter(budget_master=True) if (master_budget and (not budget_id or int(budget_id) != master_budget[0].budget_id)): raise forms.ValidationError( "Another budget is already flagged as master.") <file_sep>/simple_budget/migrations/0001_initial.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Budget', fields=[ ('budget_id', models.AutoField(serialize=False, primary_key=True)), ('budget_name', models.TextField()), ('budget_description', models.TextField()), ('budget_master', models.BooleanField(default=False)), ], options={ 'db_table': 'budget', }, bases=(models.Model,), ), migrations.CreateModel( name='BudgetCategory', fields=[ ('budget_category_id', models.AutoField(serialize=False, primary_key=True)), ('budget_category', models.TextField(blank=True)), ('budget_amount', models.DecimalField(null=True, max_digits=7, decimal_places=2, blank=True)), ], options={ 'db_table': 'budget_category', }, bases=(models.Model,), ), migrations.CreateModel( name='BudgetType', fields=[ ('budget_type_id', models.AutoField(serialize=False, primary_key=True)), ('budget_type', models.TextField()), ('ordering', models.PositiveIntegerField()), ], options={ 'db_table': 'budget_type', }, bases=(models.Model,), ), migrations.CreateModel( name='QIFParser', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('parse_status', models.TextField(null=True, blank=True)), ('date_added', models.DateField(auto_now_add=True)), ], options={ 'db_table': 'qif_parser', }, bases=(models.Model,), ), migrations.CreateModel( name='Transaction', fields=[ ('transaction_id', models.AutoField(serialize=False, primary_key=True)), ('transaction_date', models.DateField()), ], options={ 'db_table': 'transaction', }, bases=(models.Model,), ), migrations.CreateModel( name='TransactionCategory', fields=[ ('transaction_category_id', models.AutoField(serialize=False, primary_key=True)), ('transaction_category', models.TextField(blank=True)), ('budget_category', models.ForeignKey(blank=True, to='simple_budget.BudgetCategory', null=True)), ('transaction_category_parent', models.ForeignKey(blank=True, to='simple_budget.TransactionCategory', null=True)), ], options={ 'db_table': 'transaction_category', }, bases=(models.Model,), ), migrations.CreateModel( name='TransactionLine', fields=[ ('transaction_line_id', models.AutoField(serialize=False, primary_key=True)), ('amount', models.DecimalField(null=True, max_digits=7, decimal_places=2, blank=True)), ('transaction', models.ForeignKey(blank=True, to='simple_budget.Transaction', null=True)), ('transaction_category', models.ForeignKey(blank=True, to='simple_budget.TransactionCategory', null=True)), ], options={ 'db_table': 'transaction_line', }, bases=(models.Model,), ), migrations.AddField( model_name='budgetcategory', name='budget_type', field=models.ForeignKey(blank=True, to='simple_budget.BudgetType', null=True), preserve_default=True, ), ] <file_sep>/simple_budget/forms/transaction/add_edit_transaction_category_form.py from django import forms from simple_budget.models.budget.budget_category import BudgetCategory from simple_budget.models.transaction.transaction_category import \ TransactionCategory class AddEditTransactionCategoryForm(forms.Form): def __init__(self, *args, **kwargs): super(AddEditTransactionCategoryForm, self).__init__(*args, **kwargs) self.fields['transaction_category_parent_id'].choices = \ [('', 'Please select a transaction category')] + \ [(str(o.transaction_category_id), str(o.transaction_category)) for o in TransactionCategory. objects.filter(transaction_category_parent=None). order_by("transaction_category")] self.fields['budget_category'].choices = \ [('', 'Please select a budget category')] + \ [(str(o.budget_category_id), str(o.budget_category + ' ['+str(o.budget_type)+']')) for o in BudgetCategory.objects.all().order_by('budget_category')] transaction_category_id = forms.CharField(widget=forms.HiddenInput(), required=False) referer = forms.CharField(widget=forms.HiddenInput(), required=False) transaction_category = \ forms.CharField( max_length=200, required=True, label='Transaction Category', widget=forms.TextInput(attrs={'class': 'form-control', 'autocomplete': 'off'})) transaction_category_parent_id = \ forms.ChoiceField( required=False, label='Transaction Parent Category', widget=forms.Select(attrs={'class': 'form-control form-large'})) budget_category = \ forms.ChoiceField( required=True, label='Budget Category', widget=forms.Select(attrs={'class': 'form-control'}))<file_sep>/_docs/sql/schema.sql -- -- PostgreSQL database dump -- SET statement_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SET check_function_bodies = false; SET client_min_messages = warning; -- -- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: -- CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog; -- -- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: -- COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language'; SET search_path = public, pg_catalog; SET default_tablespace = ''; SET default_with_oids = false; -- -- Name: auth_group; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE auth_group ( id integer NOT NULL, name character varying(80) NOT NULL ); ALTER TABLE public.auth_group OWNER TO accounts; -- -- Name: auth_group_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_group_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_group_id_seq OWNER TO accounts; -- -- Name: auth_group_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE auth_group_id_seq OWNED BY auth_group.id; -- -- Name: auth_group_permissions; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE auth_group_permissions ( id integer NOT NULL, group_id integer NOT NULL, permission_id integer NOT NULL ); ALTER TABLE public.auth_group_permissions OWNER TO accounts; -- -- Name: auth_group_permissions_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_group_permissions_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_group_permissions_id_seq OWNER TO accounts; -- -- Name: auth_group_permissions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE auth_group_permissions_id_seq OWNED BY auth_group_permissions.id; -- -- Name: auth_permission; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE auth_permission ( id integer NOT NULL, name character varying(50) NOT NULL, content_type_id integer NOT NULL, codename character varying(100) NOT NULL ); ALTER TABLE public.auth_permission OWNER TO accounts; -- -- Name: auth_permission_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_permission_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_permission_id_seq OWNER TO accounts; -- -- Name: auth_permission_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE auth_permission_id_seq OWNED BY auth_permission.id; -- -- Name: auth_user; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE auth_user ( id integer NOT NULL, password character varying(128) NOT NULL, last_login timestamp with time zone NOT NULL, is_superuser boolean NOT NULL, username character varying(30) NOT NULL, first_name character varying(30) NOT NULL, last_name character varying(30) NOT NULL, email character varying(75) NOT NULL, is_staff boolean NOT NULL, is_active boolean NOT NULL, date_joined timestamp with time zone NOT NULL ); ALTER TABLE public.auth_user OWNER TO accounts; -- -- Name: auth_user_groups; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE auth_user_groups ( id integer NOT NULL, user_id integer NOT NULL, group_id integer NOT NULL ); ALTER TABLE public.auth_user_groups OWNER TO accounts; -- -- Name: auth_user_groups_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_user_groups_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_user_groups_id_seq OWNER TO accounts; -- -- Name: auth_user_groups_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE auth_user_groups_id_seq OWNED BY auth_user_groups.id; -- -- Name: auth_user_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_user_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_user_id_seq OWNER TO accounts; -- -- Name: auth_user_id_seq1; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_user_id_seq1 START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_user_id_seq1 OWNER TO accounts; -- -- Name: auth_user_id_seq1; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE auth_user_id_seq1 OWNED BY auth_user.id; -- -- Name: auth_user_user_permissions; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE auth_user_user_permissions ( id integer NOT NULL, user_id integer NOT NULL, permission_id integer NOT NULL ); ALTER TABLE public.auth_user_user_permissions OWNER TO accounts; -- -- Name: auth_user_user_permissions_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_user_user_permissions_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_user_user_permissions_id_seq OWNER TO accounts; -- -- Name: auth_user_user_permissions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE auth_user_user_permissions_id_seq OWNED BY auth_user_user_permissions.id; -- -- Name: budget; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE budget ( budget_id integer NOT NULL, budget_name text NOT NULL, budget_description text NOT NULL, budget_master boolean NOT NULL ); ALTER TABLE public.budget OWNER TO accounts; -- -- Name: budget_amount; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE budget_amount ( budget_amount_id integer NOT NULL, budget_amount numeric(7,2), start_date date NOT NULL, end_date date, budget_id integer, budget_category_id integer ); ALTER TABLE public.budget_amount OWNER TO accounts; -- -- Name: budget_amount_budget_amount_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE budget_amount_budget_amount_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.budget_amount_budget_amount_id_seq OWNER TO accounts; -- -- Name: budget_amount_budget_amount_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE budget_amount_budget_amount_id_seq OWNED BY budget_amount.budget_amount_id; -- -- Name: budget_budget_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE budget_budget_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.budget_budget_id_seq OWNER TO accounts; -- -- Name: budget_budget_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE budget_budget_id_seq OWNED BY budget.budget_id; -- -- Name: budget_category_id; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE budget_category_id START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.budget_category_id OWNER TO accounts; -- -- Name: budget_category; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE budget_category ( budget_category_id integer DEFAULT nextval('budget_category_id'::regclass) NOT NULL, budget_category text, budget_type_id smallint NOT NULL ); ALTER TABLE public.budget_category OWNER TO accounts; -- -- Name: budget_type; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE budget_type ( budget_type_id smallint NOT NULL, budget_type character varying(15) NOT NULL, ordering smallint NOT NULL ); ALTER TABLE public.budget_type OWNER TO accounts; -- -- Name: django_admin_log; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE django_admin_log ( id integer NOT NULL, action_time timestamp with time zone NOT NULL, object_id text, object_repr character varying(200) NOT NULL, action_flag smallint NOT NULL, change_message text NOT NULL, content_type_id integer, user_id integer NOT NULL, CONSTRAINT django_admin_log_action_flag_check CHECK ((action_flag >= 0)) ); ALTER TABLE public.django_admin_log OWNER TO accounts; -- -- Name: django_admin_log_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE django_admin_log_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.django_admin_log_id_seq OWNER TO accounts; -- -- Name: django_admin_log_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE django_admin_log_id_seq OWNED BY django_admin_log.id; -- -- Name: django_content_type_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE django_content_type_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.django_content_type_id_seq OWNER TO accounts; -- -- Name: django_content_type; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE django_content_type ( id integer DEFAULT nextval('django_content_type_id_seq'::regclass) NOT NULL, name character varying(100) NOT NULL, app_label character varying(100) NOT NULL, model character varying(100) NOT NULL ); ALTER TABLE public.django_content_type OWNER TO accounts; -- -- Name: django_migrations; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE django_migrations ( id integer NOT NULL, app character varying(255) NOT NULL, name character varying(255) NOT NULL, applied timestamp with time zone NOT NULL ); ALTER TABLE public.django_migrations OWNER TO accounts; -- -- Name: django_migrations_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE django_migrations_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.django_migrations_id_seq OWNER TO accounts; -- -- Name: django_migrations_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE django_migrations_id_seq OWNED BY django_migrations.id; -- -- Name: django_session; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE django_session ( session_key character varying(40) NOT NULL, session_data text NOT NULL, expire_date timestamp(6) with time zone NOT NULL ); ALTER TABLE public.django_session OWNER TO accounts; -- -- Name: qif_parser_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE qif_parser_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.qif_parser_id_seq OWNER TO accounts; -- -- Name: qif_parser; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE qif_parser ( id integer DEFAULT nextval('qif_parser_id_seq'::regclass) NOT NULL, parse_status text, date_added date NOT NULL ); ALTER TABLE public.qif_parser OWNER TO accounts; -- -- Name: transaction_id; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE transaction_id START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.transaction_id OWNER TO accounts; -- -- Name: transaction; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE transaction ( transaction_id integer DEFAULT nextval('transaction_id'::regclass) NOT NULL, transaction_date date ); ALTER TABLE public.transaction OWNER TO accounts; -- -- Name: transaction_category_id; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE transaction_category_id START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.transaction_category_id OWNER TO accounts; -- -- Name: transaction_category; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE transaction_category ( transaction_category_id integer DEFAULT nextval('transaction_category_id'::regclass) NOT NULL, transaction_category_parent_id integer, budget_category_id integer, transaction_category text ); ALTER TABLE public.transaction_category OWNER TO accounts; -- -- Name: transaction_line_id; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE transaction_line_id START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.transaction_line_id OWNER TO accounts; -- -- Name: transaction_line; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE transaction_line ( transaction_line_id integer DEFAULT nextval('transaction_line_id'::regclass) NOT NULL, transaction_id integer, transaction_category_id integer, amount numeric(9,2) ); ALTER TABLE public.transaction_line OWNER TO accounts; -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_group ALTER COLUMN id SET DEFAULT nextval('auth_group_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_group_permissions ALTER COLUMN id SET DEFAULT nextval('auth_group_permissions_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_permission ALTER COLUMN id SET DEFAULT nextval('auth_permission_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user ALTER COLUMN id SET DEFAULT nextval('auth_user_id_seq1'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user_groups ALTER COLUMN id SET DEFAULT nextval('auth_user_groups_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user_user_permissions ALTER COLUMN id SET DEFAULT nextval('auth_user_user_permissions_id_seq'::regclass); -- -- Name: budget_id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY budget ALTER COLUMN budget_id SET DEFAULT nextval('budget_budget_id_seq'::regclass); -- -- Name: budget_amount_id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY budget_amount ALTER COLUMN budget_amount_id SET DEFAULT nextval('budget_amount_budget_amount_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY django_admin_log ALTER COLUMN id SET DEFAULT nextval('django_admin_log_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY django_migrations ALTER COLUMN id SET DEFAULT nextval('django_migrations_id_seq'::regclass); -- -- Name: auth_group_name_key; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_group ADD CONSTRAINT auth_group_name_key UNIQUE (name); -- -- Name: auth_group_permissions_group_id_permission_id_key; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_group_permissions ADD CONSTRAINT auth_group_permissions_group_id_permission_id_key UNIQUE (group_id, permission_id); -- -- Name: auth_group_permissions_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_group_permissions ADD CONSTRAINT auth_group_permissions_pkey PRIMARY KEY (id); -- -- Name: auth_group_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_group ADD CONSTRAINT auth_group_pkey PRIMARY KEY (id); -- -- Name: auth_permission_content_type_id_codename_key; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_permission ADD CONSTRAINT auth_permission_content_type_id_codename_key UNIQUE (content_type_id, codename); -- -- Name: auth_permission_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_permission ADD CONSTRAINT auth_permission_pkey PRIMARY KEY (id); -- -- Name: auth_user_groups_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_user_groups ADD CONSTRAINT auth_user_groups_pkey PRIMARY KEY (id); -- -- Name: auth_user_groups_user_id_group_id_key; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_user_groups ADD CONSTRAINT auth_user_groups_user_id_group_id_key UNIQUE (user_id, group_id); -- -- Name: auth_user_pkey1; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_user ADD CONSTRAINT auth_user_pkey1 PRIMARY KEY (id); -- -- Name: auth_user_user_permissions_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_user_user_permissions ADD CONSTRAINT auth_user_user_permissions_pkey PRIMARY KEY (id); -- -- Name: auth_user_user_permissions_user_id_permission_id_key; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_user_user_permissions ADD CONSTRAINT auth_user_user_permissions_user_id_permission_id_key UNIQUE (user_id, permission_id); -- -- Name: auth_user_username_key1; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_user ADD CONSTRAINT auth_user_username_key1 UNIQUE (username); -- -- Name: budget_amount_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY budget_amount ADD CONSTRAINT budget_amount_pkey PRIMARY KEY (budget_amount_id); -- -- Name: budget_category_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY budget_category ADD CONSTRAINT budget_category_pkey PRIMARY KEY (budget_category_id); -- -- Name: budget_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY budget ADD CONSTRAINT budget_pkey PRIMARY KEY (budget_id); -- -- Name: budget_type_ordering_key; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY budget_type ADD CONSTRAINT budget_type_ordering_key UNIQUE (ordering); -- -- Name: budget_type_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY budget_type ADD CONSTRAINT budget_type_pkey PRIMARY KEY (budget_type_id); -- -- Name: django_admin_log_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY django_admin_log ADD CONSTRAINT django_admin_log_pkey PRIMARY KEY (id); -- -- Name: django_content_type_app_label_45f3b1d93ec8c61c_uniq; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY django_content_type ADD CONSTRAINT django_content_type_app_label_45f3b1d93ec8c61c_uniq UNIQUE (app_label, model); -- -- Name: django_content_type_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY django_content_type ADD CONSTRAINT django_content_type_pkey PRIMARY KEY (id); -- -- Name: django_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY django_migrations ADD CONSTRAINT django_migrations_pkey PRIMARY KEY (id); -- -- Name: django_session_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY django_session ADD CONSTRAINT django_session_pkey PRIMARY KEY (session_key); -- -- Name: qif_parser_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY qif_parser ADD CONSTRAINT qif_parser_pkey PRIMARY KEY (id); -- -- Name: transaction_category_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY transaction_category ADD CONSTRAINT transaction_category_pkey PRIMARY KEY (transaction_category_id); -- -- Name: transaction_line_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY transaction_line ADD CONSTRAINT transaction_line_pkey PRIMARY KEY (transaction_line_id); -- -- Name: transaction_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY transaction ADD CONSTRAINT transaction_pkey PRIMARY KEY (transaction_id); -- -- Name: auth_group_permissions_0e939a4f; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_group_permissions_0e939a4f ON auth_group_permissions USING btree (group_id); -- -- Name: auth_group_permissions_8373b171; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_group_permissions_8373b171 ON auth_group_permissions USING btree (permission_id); -- -- Name: auth_permission_417f1b1c; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_permission_417f1b1c ON auth_permission USING btree (content_type_id); -- -- Name: auth_user_groups_0e939a4f; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_user_groups_0e939a4f ON auth_user_groups USING btree (group_id); -- -- Name: auth_user_groups_e8701ad4; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_user_groups_e8701ad4 ON auth_user_groups USING btree (user_id); -- -- Name: auth_user_user_permissions_8373b171; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_user_user_permissions_8373b171 ON auth_user_user_permissions USING btree (permission_id); -- -- Name: auth_user_user_permissions_e8701ad4; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_user_user_permissions_e8701ad4 ON auth_user_user_permissions USING btree (user_id); -- -- Name: budget_amount_7748a592; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX budget_amount_7748a592 ON budget_amount USING btree (budget_id); -- -- Name: budget_amount_90a63c7c; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX budget_amount_90a63c7c ON budget_amount USING btree (budget_category_id); -- -- Name: django_admin_log_417f1b1c; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX django_admin_log_417f1b1c ON django_admin_log USING btree (content_type_id); -- -- Name: django_admin_log_e8701ad4; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX django_admin_log_e8701ad4 ON django_admin_log USING btree (user_id); -- -- Name: django_session_expire_date; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX django_session_expire_date ON django_session USING btree (expire_date); -- -- Name: django_session_session_key_like; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX django_session_session_key_like ON django_session USING btree (session_key varchar_pattern_ops); -- -- Name: D3a8426412148d1e982adbbf5c808e03; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY budget_amount ADD CONSTRAINT "D3a8426412148d1e982adbbf5c808e03" FOREIGN KEY (budget_category_id) REFERENCES budget_category(budget_category_id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_content_type_id_508cf46651277a81_fk_django_content_type_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_permission ADD CONSTRAINT auth_content_type_id_508cf46651277a81_fk_django_content_type_id FOREIGN KEY (content_type_id) REFERENCES django_content_type(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_group_permissio_group_id_689710a9a73b7457_fk_auth_group_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_group_permissions ADD CONSTRAINT auth_group_permissio_group_id_689710a9a73b7457_fk_auth_group_id FOREIGN KEY (group_id) REFERENCES auth_group(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_group_permission_id_1f49ccbbdc69d2fc_fk_auth_permission_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_group_permissions ADD CONSTRAINT auth_group_permission_id_1f49ccbbdc69d2fc_fk_auth_permission_id FOREIGN KEY (permission_id) REFERENCES auth_permission(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_user__permission_id_384b62483d7071f0_fk_auth_permission_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user_user_permissions ADD CONSTRAINT auth_user__permission_id_384b62483d7071f0_fk_auth_permission_id FOREIGN KEY (permission_id) REFERENCES auth_permission(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_user_groups_group_id_33ac548dcf5f8e37_fk_auth_group_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user_groups ADD CONSTRAINT auth_user_groups_group_id_33ac548dcf5f8e37_fk_auth_group_id FOREIGN KEY (group_id) REFERENCES auth_group(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_user_groups_user_id_4b5ed4ffdb8fd9b0_fk_auth_user_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user_groups ADD CONSTRAINT auth_user_groups_user_id_4b5ed4ffdb8fd9b0_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_user_user_permiss_user_id_7f0938558328534a_fk_auth_user_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user_user_permissions ADD CONSTRAINT auth_user_user_permiss_user_id_7f0938558328534a_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: budget_amount_budget_id_3f19ce1f52908e8_fk_budget_budget_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY budget_amount ADD CONSTRAINT budget_amount_budget_id_3f19ce1f52908e8_fk_budget_budget_id FOREIGN KEY (budget_id) REFERENCES budget(budget_id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: budget_category_budget_type_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY budget_category ADD CONSTRAINT budget_category_budget_type_id_fkey FOREIGN KEY (budget_type_id) REFERENCES budget_type(budget_type_id) ON UPDATE CASCADE ON DELETE CASCADE; -- -- Name: djan_content_type_id_697914295151027a_fk_django_content_type_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY django_admin_log ADD CONSTRAINT djan_content_type_id_697914295151027a_fk_django_content_type_id FOREIGN KEY (content_type_id) REFERENCES django_content_type(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: django_admin_log_user_id_52fdd58701c5f563_fk_auth_user_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY django_admin_log ADD CONSTRAINT django_admin_log_user_id_52fdd58701c5f563_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: transaction_category_transaction_category_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY transaction_category ADD CONSTRAINT transaction_category_transaction_category_parent_id_fkey FOREIGN KEY (transaction_category_parent_id) REFERENCES transaction_category(transaction_category_id); -- -- Name: transaction_line_transaction_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY transaction_line ADD CONSTRAINT transaction_line_transaction_id_fkey FOREIGN KEY (transaction_id) REFERENCES transaction(transaction_id); -- -- Name: public; Type: ACL; Schema: -; Owner: postgres -- REVOKE ALL ON SCHEMA public FROM PUBLIC; REVOKE ALL ON SCHEMA public FROM postgres; GRANT ALL ON SCHEMA public TO postgres; GRANT ALL ON SCHEMA public TO PUBLIC; -- -- PostgreSQL database dump complete -- -- -- PostgreSQL database dump -- SET statement_timeout = 0; SET lock_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SET check_function_bodies = false; SET client_min_messages = warning; -- -- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: -- CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog; -- -- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: -- COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language'; SET search_path = public, pg_catalog; SET default_tablespace = ''; SET default_with_oids = false; -- -- Name: account; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE account ( account_id integer NOT NULL, account_name text NOT NULL, account_notes text, account_type_id integer, account_hidden boolean NOT NULL ); ALTER TABLE public.account OWNER TO accounts; -- -- Name: account_type; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE account_type ( account_type_id integer NOT NULL, account_type text NOT NULL, ordering integer NOT NULL, CONSTRAINT account_type_ordering_check CHECK ((ordering >= 0)) ); ALTER TABLE public.account_type OWNER TO accounts; -- -- Name: account_type_account_type_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE account_type_account_type_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.account_type_account_type_id_seq OWNER TO accounts; -- -- Name: account_type_account_type_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE account_type_account_type_id_seq OWNED BY account_type.account_type_id; -- -- Name: auth_group; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE auth_group ( id integer NOT NULL, name character varying(80) NOT NULL ); ALTER TABLE public.auth_group OWNER TO accounts; -- -- Name: auth_group_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_group_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_group_id_seq OWNER TO accounts; -- -- Name: auth_group_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE auth_group_id_seq OWNED BY auth_group.id; -- -- Name: auth_group_permissions; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE auth_group_permissions ( id integer NOT NULL, group_id integer NOT NULL, permission_id integer NOT NULL ); ALTER TABLE public.auth_group_permissions OWNER TO accounts; -- -- Name: auth_group_permissions_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_group_permissions_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_group_permissions_id_seq OWNER TO accounts; -- -- Name: auth_group_permissions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE auth_group_permissions_id_seq OWNED BY auth_group_permissions.id; -- -- Name: auth_permission; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE auth_permission ( id integer NOT NULL, name character varying(50) NOT NULL, content_type_id integer NOT NULL, codename character varying(100) NOT NULL ); ALTER TABLE public.auth_permission OWNER TO accounts; -- -- Name: auth_permission_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_permission_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_permission_id_seq OWNER TO accounts; -- -- Name: auth_permission_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE auth_permission_id_seq OWNED BY auth_permission.id; -- -- Name: auth_user; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE auth_user ( id integer NOT NULL, password character varying(128) NOT NULL, last_login timestamp with time zone NOT NULL, is_superuser boolean NOT NULL, username character varying(30) NOT NULL, first_name character varying(30) NOT NULL, last_name character varying(30) NOT NULL, email character varying(75) NOT NULL, is_staff boolean NOT NULL, is_active boolean NOT NULL, date_joined timestamp with time zone NOT NULL ); ALTER TABLE public.auth_user OWNER TO accounts; -- -- Name: auth_user_groups; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE auth_user_groups ( id integer NOT NULL, user_id integer NOT NULL, group_id integer NOT NULL ); ALTER TABLE public.auth_user_groups OWNER TO accounts; -- -- Name: auth_user_groups_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_user_groups_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_user_groups_id_seq OWNER TO accounts; -- -- Name: auth_user_groups_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE auth_user_groups_id_seq OWNED BY auth_user_groups.id; -- -- Name: auth_user_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_user_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_user_id_seq OWNER TO accounts; -- -- Name: auth_user_id_seq1; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_user_id_seq1 START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_user_id_seq1 OWNER TO accounts; -- -- Name: auth_user_id_seq1; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE auth_user_id_seq1 OWNED BY auth_user.id; -- -- Name: auth_user_user_permissions; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE auth_user_user_permissions ( id integer NOT NULL, user_id integer NOT NULL, permission_id integer NOT NULL ); ALTER TABLE public.auth_user_user_permissions OWNER TO accounts; -- -- Name: auth_user_user_permissions_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE auth_user_user_permissions_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.auth_user_user_permissions_id_seq OWNER TO accounts; -- -- Name: auth_user_user_permissions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE auth_user_user_permissions_id_seq OWNED BY auth_user_user_permissions.id; -- -- Name: budget; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE budget ( budget_id integer NOT NULL, budget_name text NOT NULL, budget_description text NOT NULL, budget_master boolean NOT NULL ); ALTER TABLE public.budget OWNER TO accounts; -- -- Name: budget_amount; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE budget_amount ( budget_amount_id integer NOT NULL, budget_amount numeric(7,2), start_date date NOT NULL, end_date date, budget_id integer, budget_category_id integer ); ALTER TABLE public.budget_amount OWNER TO accounts; -- -- Name: budget_amount_budget_amount_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE budget_amount_budget_amount_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.budget_amount_budget_amount_id_seq OWNER TO accounts; -- -- Name: budget_amount_budget_amount_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE budget_amount_budget_amount_id_seq OWNED BY budget_amount.budget_amount_id; -- -- Name: budget_budget_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE budget_budget_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.budget_budget_id_seq OWNER TO accounts; -- -- Name: budget_budget_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE budget_budget_id_seq OWNED BY budget.budget_id; -- -- Name: budget_category_id; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE budget_category_id START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.budget_category_id OWNER TO accounts; -- -- Name: budget_category; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE budget_category ( budget_category_id integer DEFAULT nextval('budget_category_id'::regclass) NOT NULL, budget_category text, budget_type_id smallint ); ALTER TABLE public.budget_category OWNER TO accounts; -- -- Name: budget_type; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE budget_type ( budget_type_id smallint NOT NULL, budget_type text NOT NULL, ordering smallint NOT NULL ); ALTER TABLE public.budget_type OWNER TO accounts; -- -- Name: django_admin_log; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE django_admin_log ( id integer NOT NULL, action_time timestamp with time zone NOT NULL, object_id text, object_repr character varying(200) NOT NULL, action_flag smallint NOT NULL, change_message text NOT NULL, content_type_id integer, user_id integer NOT NULL, CONSTRAINT django_admin_log_action_flag_check CHECK ((action_flag >= 0)) ); ALTER TABLE public.django_admin_log OWNER TO accounts; -- -- Name: django_admin_log_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE django_admin_log_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.django_admin_log_id_seq OWNER TO accounts; -- -- Name: django_admin_log_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE django_admin_log_id_seq OWNED BY django_admin_log.id; -- -- Name: django_content_type_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE django_content_type_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.django_content_type_id_seq OWNER TO accounts; -- -- Name: django_content_type; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE django_content_type ( id integer DEFAULT nextval('django_content_type_id_seq'::regclass) NOT NULL, name character varying(100) NOT NULL, app_label character varying(100) NOT NULL, model character varying(100) NOT NULL ); ALTER TABLE public.django_content_type OWNER TO accounts; -- -- Name: django_migrations; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE django_migrations ( id integer NOT NULL, app character varying(255) NOT NULL, name character varying(255) NOT NULL, applied timestamp with time zone NOT NULL ); ALTER TABLE public.django_migrations OWNER TO accounts; -- -- Name: django_migrations_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE django_migrations_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.django_migrations_id_seq OWNER TO accounts; -- -- Name: django_migrations_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE django_migrations_id_seq OWNED BY django_migrations.id; -- -- Name: django_session; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE django_session ( session_key character varying(40) NOT NULL, session_data text NOT NULL, expire_date timestamp(6) with time zone NOT NULL ); ALTER TABLE public.django_session OWNER TO accounts; -- -- Name: qif_parser_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE qif_parser_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.qif_parser_id_seq OWNER TO accounts; -- -- Name: qif_parser; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE qif_parser ( id integer DEFAULT nextval('qif_parser_id_seq'::regclass) NOT NULL, parse_status text, date_added date NOT NULL ); ALTER TABLE public.qif_parser OWNER TO accounts; -- -- Name: simple_budget_account_account_id_seq; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE simple_budget_account_account_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.simple_budget_account_account_id_seq OWNER TO accounts; -- -- Name: simple_budget_account_account_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: accounts -- ALTER SEQUENCE simple_budget_account_account_id_seq OWNED BY account.account_id; -- -- Name: transaction_id; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE transaction_id START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.transaction_id OWNER TO accounts; -- -- Name: transaction; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE transaction ( transaction_id integer DEFAULT nextval('transaction_id'::regclass) NOT NULL, transaction_date date, account_id integer ); ALTER TABLE public.transaction OWNER TO accounts; -- -- Name: transaction_category_id; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE transaction_category_id START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.transaction_category_id OWNER TO accounts; -- -- Name: transaction_category; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE transaction_category ( transaction_category_id integer DEFAULT nextval('transaction_category_id'::regclass) NOT NULL, transaction_category_parent_id integer, budget_category_id integer, transaction_category text ); ALTER TABLE public.transaction_category OWNER TO accounts; -- -- Name: transaction_line_id; Type: SEQUENCE; Schema: public; Owner: accounts -- CREATE SEQUENCE transaction_line_id START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.transaction_line_id OWNER TO accounts; -- -- Name: transaction_line; Type: TABLE; Schema: public; Owner: accounts; Tablespace: -- CREATE TABLE transaction_line ( transaction_line_id integer DEFAULT nextval('transaction_line_id'::regclass) NOT NULL, transaction_id integer, transaction_category_id integer, amount numeric(9,2) ); ALTER TABLE public.transaction_line OWNER TO accounts; -- -- Name: account_id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY account ALTER COLUMN account_id SET DEFAULT nextval('simple_budget_account_account_id_seq'::regclass); -- -- Name: account_type_id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY account_type ALTER COLUMN account_type_id SET DEFAULT nextval('account_type_account_type_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_group ALTER COLUMN id SET DEFAULT nextval('auth_group_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_group_permissions ALTER COLUMN id SET DEFAULT nextval('auth_group_permissions_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_permission ALTER COLUMN id SET DEFAULT nextval('auth_permission_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user ALTER COLUMN id SET DEFAULT nextval('auth_user_id_seq1'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user_groups ALTER COLUMN id SET DEFAULT nextval('auth_user_groups_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user_user_permissions ALTER COLUMN id SET DEFAULT nextval('auth_user_user_permissions_id_seq'::regclass); -- -- Name: budget_id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY budget ALTER COLUMN budget_id SET DEFAULT nextval('budget_budget_id_seq'::regclass); -- -- Name: budget_amount_id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY budget_amount ALTER COLUMN budget_amount_id SET DEFAULT nextval('budget_amount_budget_amount_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY django_admin_log ALTER COLUMN id SET DEFAULT nextval('django_admin_log_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: accounts -- ALTER TABLE ONLY django_migrations ALTER COLUMN id SET DEFAULT nextval('django_migrations_id_seq'::regclass); -- -- Name: account_type_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY account_type ADD CONSTRAINT account_type_pkey PRIMARY KEY (account_type_id); -- -- Name: auth_group_name_key; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_group ADD CONSTRAINT auth_group_name_key UNIQUE (name); -- -- Name: auth_group_permissions_group_id_permission_id_key; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_group_permissions ADD CONSTRAINT auth_group_permissions_group_id_permission_id_key UNIQUE (group_id, permission_id); -- -- Name: auth_group_permissions_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_group_permissions ADD CONSTRAINT auth_group_permissions_pkey PRIMARY KEY (id); -- -- Name: auth_group_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_group ADD CONSTRAINT auth_group_pkey PRIMARY KEY (id); -- -- Name: auth_permission_content_type_id_codename_key; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_permission ADD CONSTRAINT auth_permission_content_type_id_codename_key UNIQUE (content_type_id, codename); -- -- Name: auth_permission_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_permission ADD CONSTRAINT auth_permission_pkey PRIMARY KEY (id); -- -- Name: auth_user_groups_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_user_groups ADD CONSTRAINT auth_user_groups_pkey PRIMARY KEY (id); -- -- Name: auth_user_groups_user_id_group_id_key; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_user_groups ADD CONSTRAINT auth_user_groups_user_id_group_id_key UNIQUE (user_id, group_id); -- -- Name: auth_user_pkey1; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_user ADD CONSTRAINT auth_user_pkey1 PRIMARY KEY (id); -- -- Name: auth_user_user_permissions_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_user_user_permissions ADD CONSTRAINT auth_user_user_permissions_pkey PRIMARY KEY (id); -- -- Name: auth_user_user_permissions_user_id_permission_id_key; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_user_user_permissions ADD CONSTRAINT auth_user_user_permissions_user_id_permission_id_key UNIQUE (user_id, permission_id); -- -- Name: auth_user_username_key1; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY auth_user ADD CONSTRAINT auth_user_username_key1 UNIQUE (username); -- -- Name: budget_amount_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY budget_amount ADD CONSTRAINT budget_amount_pkey PRIMARY KEY (budget_amount_id); -- -- Name: budget_category_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY budget_category ADD CONSTRAINT budget_category_pkey PRIMARY KEY (budget_category_id); -- -- Name: budget_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY budget ADD CONSTRAINT budget_pkey PRIMARY KEY (budget_id); -- -- Name: budget_type_ordering_key; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY budget_type ADD CONSTRAINT budget_type_ordering_key UNIQUE (ordering); -- -- Name: budget_type_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY budget_type ADD CONSTRAINT budget_type_pkey PRIMARY KEY (budget_type_id); -- -- Name: django_admin_log_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY django_admin_log ADD CONSTRAINT django_admin_log_pkey PRIMARY KEY (id); -- -- Name: django_content_type_app_label_45f3b1d93ec8c61c_uniq; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY django_content_type ADD CONSTRAINT django_content_type_app_label_45f3b1d93ec8c61c_uniq UNIQUE (app_label, model); -- -- Name: django_content_type_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY django_content_type ADD CONSTRAINT django_content_type_pkey PRIMARY KEY (id); -- -- Name: django_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY django_migrations ADD CONSTRAINT django_migrations_pkey PRIMARY KEY (id); -- -- Name: django_session_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY django_session ADD CONSTRAINT django_session_pkey PRIMARY KEY (session_key); -- -- Name: qif_parser_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY qif_parser ADD CONSTRAINT qif_parser_pkey PRIMARY KEY (id); -- -- Name: simple_budget_account_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY account ADD CONSTRAINT simple_budget_account_pkey PRIMARY KEY (account_id); -- -- Name: transaction_category_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY transaction_category ADD CONSTRAINT transaction_category_pkey PRIMARY KEY (transaction_category_id); -- -- Name: transaction_line_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY transaction_line ADD CONSTRAINT transaction_line_pkey PRIMARY KEY (transaction_line_id); -- -- Name: transaction_pkey; Type: CONSTRAINT; Schema: public; Owner: accounts; Tablespace: -- ALTER TABLE ONLY transaction ADD CONSTRAINT transaction_pkey PRIMARY KEY (transaction_id); -- -- Name: auth_group_permissions_0e939a4f; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_group_permissions_0e939a4f ON auth_group_permissions USING btree (group_id); -- -- Name: auth_group_permissions_8373b171; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_group_permissions_8373b171 ON auth_group_permissions USING btree (permission_id); -- -- Name: auth_permission_417f1b1c; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_permission_417f1b1c ON auth_permission USING btree (content_type_id); -- -- Name: auth_user_groups_0e939a4f; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_user_groups_0e939a4f ON auth_user_groups USING btree (group_id); -- -- Name: auth_user_groups_e8701ad4; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_user_groups_e8701ad4 ON auth_user_groups USING btree (user_id); -- -- Name: auth_user_user_permissions_8373b171; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_user_user_permissions_8373b171 ON auth_user_user_permissions USING btree (permission_id); -- -- Name: auth_user_user_permissions_e8701ad4; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX auth_user_user_permissions_e8701ad4 ON auth_user_user_permissions USING btree (user_id); -- -- Name: budget_amount_7748a592; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX budget_amount_7748a592 ON budget_amount USING btree (budget_id); -- -- Name: budget_amount_90a63c7c; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX budget_amount_90a63c7c ON budget_amount USING btree (budget_category_id); -- -- Name: django_admin_log_417f1b1c; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX django_admin_log_417f1b1c ON django_admin_log USING btree (content_type_id); -- -- Name: django_admin_log_e8701ad4; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX django_admin_log_e8701ad4 ON django_admin_log USING btree (user_id); -- -- Name: django_session_expire_date; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX django_session_expire_date ON django_session USING btree (expire_date); -- -- Name: django_session_session_key_like; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX django_session_session_key_like ON django_session USING btree (session_key varchar_pattern_ops); -- -- Name: simple_budget_account_d18f477c; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX simple_budget_account_d18f477c ON account USING btree (account_type_id); -- -- Name: transaction_8a089c2a; Type: INDEX; Schema: public; Owner: accounts; Tablespace: -- CREATE INDEX transaction_8a089c2a ON transaction USING btree (account_id); -- -- Name: D38d78680061548b4f00986358fe8273; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY account ADD CONSTRAINT "D38d78680061548b4f00986358fe8273" FOREIGN KEY (account_type_id) REFERENCES account_type(account_type_id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: D3a8426412148d1e982adbbf5c808e03; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY budget_amount ADD CONSTRAINT "D3a8426412148d1e982adbbf5c808e03" FOREIGN KEY (budget_category_id) REFERENCES budget_category(budget_category_id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_content_type_id_508cf46651277a81_fk_django_content_type_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_permission ADD CONSTRAINT auth_content_type_id_508cf46651277a81_fk_django_content_type_id FOREIGN KEY (content_type_id) REFERENCES django_content_type(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_group_permissio_group_id_689710a9a73b7457_fk_auth_group_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_group_permissions ADD CONSTRAINT auth_group_permissio_group_id_689710a9a73b7457_fk_auth_group_id FOREIGN KEY (group_id) REFERENCES auth_group(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_group_permission_id_1f49ccbbdc69d2fc_fk_auth_permission_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_group_permissions ADD CONSTRAINT auth_group_permission_id_1f49ccbbdc69d2fc_fk_auth_permission_id FOREIGN KEY (permission_id) REFERENCES auth_permission(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_user__permission_id_384b62483d7071f0_fk_auth_permission_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user_user_permissions ADD CONSTRAINT auth_user__permission_id_384b62483d7071f0_fk_auth_permission_id FOREIGN KEY (permission_id) REFERENCES auth_permission(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_user_groups_group_id_33ac548dcf5f8e37_fk_auth_group_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user_groups ADD CONSTRAINT auth_user_groups_group_id_33ac548dcf5f8e37_fk_auth_group_id FOREIGN KEY (group_id) REFERENCES auth_group(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_user_groups_user_id_4b5ed4ffdb8fd9b0_fk_auth_user_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user_groups ADD CONSTRAINT auth_user_groups_user_id_4b5ed4ffdb8fd9b0_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: auth_user_user_permiss_user_id_7f0938558328534a_fk_auth_user_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY auth_user_user_permissions ADD CONSTRAINT auth_user_user_permiss_user_id_7f0938558328534a_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: b_budget_type_id_65393ad90ee5e4fa_fk_budget_type_budget_type_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY budget_category ADD CONSTRAINT b_budget_type_id_65393ad90ee5e4fa_fk_budget_type_budget_type_id FOREIGN KEY (budget_type_id) REFERENCES budget_type(budget_type_id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: budget_amount_budget_id_3f19ce1f52908e8_fk_budget_budget_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY budget_amount ADD CONSTRAINT budget_amount_budget_id_3f19ce1f52908e8_fk_budget_budget_id FOREIGN KEY (budget_id) REFERENCES budget(budget_id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: djan_content_type_id_697914295151027a_fk_django_content_type_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY django_admin_log ADD CONSTRAINT djan_content_type_id_697914295151027a_fk_django_content_type_id FOREIGN KEY (content_type_id) REFERENCES django_content_type(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: django_admin_log_user_id_52fdd58701c5f563_fk_auth_user_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY django_admin_log ADD CONSTRAINT django_admin_log_user_id_52fdd58701c5f563_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: transaction_account_id_dda320160b69401_fk_account_account_id; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY transaction ADD CONSTRAINT transaction_account_id_dda320160b69401_fk_account_account_id FOREIGN KEY (account_id) REFERENCES account(account_id) DEFERRABLE INITIALLY DEFERRED; -- -- Name: transaction_category_transaction_category_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY transaction_category ADD CONSTRAINT transaction_category_transaction_category_parent_id_fkey FOREIGN KEY (transaction_category_parent_id) REFERENCES transaction_category(transaction_category_id); -- -- Name: transaction_line_transaction_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: accounts -- ALTER TABLE ONLY transaction_line ADD CONSTRAINT transaction_line_transaction_id_fkey FOREIGN KEY (transaction_id) REFERENCES transaction(transaction_id); -- -- Name: public; Type: ACL; Schema: -; Owner: postgres -- REVOKE ALL ON SCHEMA public FROM PUBLIC; REVOKE ALL ON SCHEMA public FROM postgres; GRANT ALL ON SCHEMA public TO postgres; GRANT ALL ON SCHEMA public TO PUBLIC; -- -- PostgreSQL database dump complete -- <file_sep>/requirements.txt Django==1.7.1 psycopg2==2.5.4 python-dateutil==2.4.0 PyYAML==3.11 six==1.9.0 SQLAlchemy==0.9.8 <file_sep>/simple_budget/models/__init__.py from account.account_type import AccountType from account.account import Account from budget.budget import Budget from budget.budget_category import BudgetCategory from transaction.qif_parser import QIFParser from transaction.transaction import Transaction from transaction.transaction_category import TransactionCategory from transaction.transaction_line import TransactionLine<file_sep>/simple_budget/models/account/account.py from __future__ import unicode_literals from django.db import models from account_type import AccountType from simple_budget.helper.sql import SQL from sqlalchemy import func, asc, or_ from decimal import Decimal from datetime import datetime, date from dateutil.relativedelta import relativedelta import math class Account(models.Model): """ account model """ account_id = models.AutoField(primary_key=True) account_name = models.TextField(blank=True) account_notes = models.TextField(blank=True, null=True) account_hidden = models.BooleanField(blank=False, null=False, default=False) account_type = models.ForeignKey(AccountType, blank=True, null=True) class Meta: db_table = 'account' @staticmethod def accounts(account_type=None): """ get account balances of the supplied type :param type: :return: """ sql = SQL() end_of_month = date(datetime.now().year, datetime.now().month, datetime.now().day) accounts = sql.db_session.query( sql.account.c.account_id, sql.account.c.account_hidden, sql.account.c.account_name, sql.account.c.account_notes, func.sum(sql.transaction_line.c.amount). \ label('balance'), sql.account_type.c.account_type). \ join(sql.account_type, sql.account_type.c.account_type_id == sql.account.c.account_type_id). \ outerjoin(sql.transaction, sql.transaction.c.account_id == sql.account.c.account_id). \ outerjoin(sql.transaction_line, sql.transaction_line.c.transaction_id == sql.transaction.c.transaction_id). \ filter(sql.account.c.account_hidden == False).\ filter(sql.transaction.c.transaction_date <= end_of_month).\ group_by(sql.account.c.account_id, sql.account.c.account_name, sql.account_type.c.account_type, sql.account_type.c.ordering). \ order_by(sql.account_type.c.ordering.asc(), sql.account.c.account_name.asc()) if account_type == 'debt': accounts = accounts.filter( or_(sql.account_type.c.account_type=='Loan', sql.account_type.c.account_type=='Store & Credit Card')) return accounts @staticmethod def account_balance_summary(account_type=None, account_id=None): """ get a summary of all account balances :param account_type: :return: """ sql = SQL() account_balances = sql.db_session.query( func.date_trunc('month', sql.transaction.c.transaction_date).\ label('date'), func.sum(sql.transaction_line.c.amount).\ label('balance')).\ join(sql.transaction_line, sql.transaction_line.c.transaction_id == sql.transaction.c.transaction_id). \ join(sql.account, sql.account.c.account_id == sql.transaction.c.account_id). \ join(sql.account_type, sql.account_type.c.account_type_id == sql.account.c.account_type_id). \ group_by('date').\ order_by(asc('date')) if account_id: account_balances = account_balances.filter( sql.account.c.account_id == account_id) elif account_type == 'debt': account_balances = account_balances.filter( or_(sql.account_type.c.account_type=='Loan', sql.account_type.c.account_type=='Store & Credit Card')) #loop through all balances and fill in any gaps in the date #with the balance for the previous month return account_balances def debt_balance_summary(self): """ gets summary for last 12 months debt balances :return: """ debt_balances = [] balances = self.account_balance_summary(account_type='debt') if balances: current_balance = 0 start_this_month = date(datetime.now().year, datetime.now().month, 1) start_last_year = date(datetime.now().year, datetime.now().month, 1) - \ relativedelta(months=11) for balance in balances: current_balance = Decimal(current_balance - balance.balance).\ quantize(Decimal('.01')) if (str(start_last_year) <= str(balance.date.strftime('%Y-%m-%d')) <= str(start_this_month)): debt_balances.append( {'date': balance.date.strftime('%Y-%m-%d'), 'balance': str(current_balance)}) return debt_balances def debt(self): """ gets balance for all debt related account types :return: """ today = datetime.now() start_this_month = date(today.year, today.month, 1) start_last_month = date(today.year, today.month, 1) - \ relativedelta(months=1) start_last_year = date(start_this_month.year, start_this_month.month, 1) - \ relativedelta(months=11) accounts = self.accounts(account_type='debt') if not accounts: return [False, False] else: account_balances = [] totals = {'current_balance': 0, 'last_month_balance': 0, 'last_month_balance_diff': 0, 'today': today, 'last_month_date': start_last_month, 'last_year_date': start_last_year, 'last_year_balance': 0, 'last_year_balance_diff': 0, 'avg_debt_repayment': 0, 'last_month_debt_repayment': 0} for account in accounts: if not account.account_hidden: last_month_balance = 0 last_year_balance = 0 current_balance = 0 balances = \ self.account_balance_summary( account_id=account.account_id) if not balances: if current_balance: account_balances['current_balance'] = \ current_balance else: account_balances['current_balance'] = 0 else: for balance in balances: current_balance = \ Decimal(current_balance - balance.balance).\ quantize(Decimal('.01')) if (str(balance.date.strftime('%Y-%m-%d')) == str(start_this_month)): break if (str(balance.date.strftime('%Y-%m-%d')) == str(start_last_month)): last_month_balance = current_balance if (str(balance.date.strftime('%Y-%m-%d')) == str(start_last_year)): last_year_balance = current_balance account_balances.append( {'account_id': account.account_id, 'account_name': account.account_name, 'account_type': account.account_type, 'last_month_balance': last_month_balance, 'last_year_balance': last_year_balance, 'current_balance': current_balance}) if account_balances: for account_balance in account_balances: if account_balance['current_balance']: totals['current_balance'] += \ account_balance['current_balance'] if account_balance['last_month_balance']: totals['last_month_balance'] += \ account_balance['last_month_balance'] if account_balance['last_year_balance']: totals['last_year_balance'] += \ account_balance['last_year_balance'] totals['last_month_balance_diff'] = \ totals['last_month_balance'] - totals['current_balance'] totals['last_year_balance_diff'] = \ totals['last_year_balance'] - totals['current_balance'] if totals['last_year_balance_diff'] > 0: totals['avg_debt_repayment'] = \ abs(totals['last_year_balance_diff'] / 12). \ quantize(Decimal('.01')) totals['avg_debt_repayment_date'] = \ date(today.year, today.month, 1) + \ relativedelta(months=int(math.ceil(totals['current_balance'] / totals['avg_debt_repayment']))) if totals['last_month_balance_diff'] > 0: totals['last_month_debt_repayment'] = \ abs(totals['last_month_balance_diff']) totals['last_month_debt_repayment_date'] = \ date(today.year, today.month, 1) + \ relativedelta(months=int(math.ceil(totals['current_balance'] / totals['last_month_debt_repayment']))) return [account_balances, totals] <file_sep>/simple_budget/models/transaction/qif_parser.py from django.db import models class QIFParser(models.Model): """ budget type model """ parse_status = models.TextField(blank=True, null=True) date_added = models.DateField(auto_now_add=True) class Meta: db_table = 'qif_parser' @staticmethod def get_status(): """ gets status for last uploaded qif file :return: """ try: parsed_quicken_file_status = QIFParser.objects.all().order_by('-id')[:1] if parsed_quicken_file_status: return parsed_quicken_file_status[0].parse_status else: return False except IndexError: return False<file_sep>/simple_budget/helper/date_calculation.py from datetime import datetime, date from dateutil.relativedelta import relativedelta from simple_budget.settings import START_DATE import calendar class DateCalculation(object): """ date calculations used withing simple budget """ @staticmethod def calculate_years(year=None): try: year = int(year) except TypeError: year = None if not year: return [None, None, None] else: today = datetime.now() if year + 1 <= today.year: next_year = year + 1 else: next_year = None if year - 1 >= datetime.strptime(START_DATE, '%Y-%m-%d').year: prev_year = year - 1 else: prev_year = None return [year, next_year, prev_year] @staticmethod def calculate_dates(year_month=None): """ :param year_month: :return: prev_month, next_month, start_date, end_date """ today = datetime.now() start_date = date(datetime.now().year, datetime.now().month, 1) end_date = date(datetime.now().year, datetime.now().month, calendar.monthrange(datetime.now().year, datetime.now().month)[1]) next_month = date(today.year, today.month, 1) + \ relativedelta(months=1) prev_month = date(today.year, today.month, 1) - \ relativedelta(months=1) if year_month: try: year_month = datetime.strptime(year_month, '%Y-%m') except ValueError: year_month = None if year_month: start_date = date(year_month.year, year_month.month, 1) if (START_DATE and (datetime.strptime(str(start_date), '%Y-%m-%d') < datetime.strptime(START_DATE, '%Y-%m-%d')) or (datetime.strptime(str(start_date), '%Y-%m-%d') > datetime.now())): start_date = None else: today = start_date end_date = date(year_month.year, year_month.month, calendar.monthrange(year_month.year, year_month.month)[1]) next_month = date(year_month.year, year_month.month, 1) + \ relativedelta(months=1) prev_month = date(year_month.year, year_month.month, 1) - \ relativedelta(months=1) if (START_DATE and datetime.strptime(str(prev_month), '%Y-%m-%d') < datetime.strptime(START_DATE, '%Y-%m-%d')): prev_month = None if next_month > date(datetime.now().year, datetime.now().month, datetime.now().day): next_month = None return [prev_month, next_month, start_date, end_date, today]<file_sep>/simple_budget/forms/budget/add_edit_budget_category_form.py from django import forms from simple_budget.models.budget.budget_type import BudgetType class AddEditBudgetCategoryForm(forms.Form): def __init__(self, *args, **kwargs): super(AddEditBudgetCategoryForm, self).__init__(*args, **kwargs) self.fields['budget_type_id'].choices = \ [('', 'Please select a budget type')] + \ [(str(o.budget_type_id), str(o.budget_type)) for o in BudgetType.objects.all().order_by('ordering')] budget_category_id = forms.CharField(widget=forms.HiddenInput(), required=False) referer = forms.CharField(widget=forms.HiddenInput(), required=False) budget_category = \ forms.CharField( label="Budget Catgeory", max_length=200, required=True, widget=forms.TextInput(attrs={'class': 'form-control', 'autocomplete': 'off'})) budget_type_id = \ forms.ChoiceField( label="Budget Type", required=True, widget=forms.Select(attrs={'class': 'form-control'}))<file_sep>/simple_budget/views/account/account.py from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth.decorators import login_required from simple_budget.models.account.account import Account from django.http import HttpResponse import json import collections @login_required def accounts(request): """ summary of all accounts """ all_accounts = Account().accounts() summary = collections.OrderedDict() grand_total = 0 for account in all_accounts: if not account.balance: account.balance = 0 grand_total += account.balance if account.account_type not in summary: summary[account.account_type] = account.balance else: summary[account.account_type] += account.balance return render_to_response('account/accounts.html', {'accounts': all_accounts, 'grand_total': grand_total, 'summary': summary}, context_instance=RequestContext(request)) @login_required def debt(request): """ index """ debts, totals = Account().debt() return render_to_response('account/debt.html', {'debts': debts, 'totals': totals}, context_instance=RequestContext(request)) @login_required def debt_summary(request): """ index """ return HttpResponse(json.dumps(Account().debt_balance_summary()), content_type='application/json')<file_sep>/simple_budget/migrations/0007_auto_20150207_0920.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('simple_budget', '0006_delete_accounttype'), ] operations = [ migrations.CreateModel( name='Account', fields=[ ('account_id', models.AutoField(serialize=False, primary_key=True)), ('account_name', models.TextField(blank=True)), ('account_notes', models.TextField(blank=True)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='AccountBalance', fields=[ ('account_balance_id', models.AutoField(serialize=False, primary_key=True)), ('account_balance', models.DecimalField(null=True, max_digits=7, decimal_places=2, blank=True)), ('account_balance_date', models.DateField()), ('account', models.ForeignKey(to='simple_budget.Account')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='AccountType', fields=[ ('account_type_id', models.AutoField(serialize=False, primary_key=True)), ('account_type', models.TextField()), ('ordering', models.PositiveIntegerField()), ], options={ 'db_table': 'account_type', }, bases=(models.Model,), ), migrations.AddField( model_name='account', name='account_type', field=models.ForeignKey(blank=True, to='simple_budget.AccountType', null=True), preserve_default=True, ), ] <file_sep>/simple_budget/forms/budget/delete_budget_category_form.py from django import forms from simple_budget.models.budget.budget_category import BudgetCategory class DeleteBudgetCategoryForm(forms.Form): def __init__(self, *args, **kwargs): try: current_budget_category_id = kwargs.pop('current_budget_category_id') except KeyError: current_budget_category_id = False try: select_new_category = kwargs.pop('select_new_category') except KeyError: select_new_category = False super(DeleteBudgetCategoryForm, self).__init__(*args, **kwargs) self.fields['transfer_budget_category_id'].choices = \ [('', 'Please select a budget category')] self.fields['transfer_budget_category_id'].required = \ select_new_category for o in BudgetCategory.objects.exclude( budget_category_id=current_budget_category_id).\ order_by('budget_category'): if (not current_budget_category_id or o.budget_category_id != int(current_budget_category_id)): self.fields['transfer_budget_category_id'].choices +=\ [(o.budget_category_id, str(o.budget_category))] budget_category_id = forms.CharField(widget=forms.HiddenInput(), required=True) transfer_budget_category_id = \ forms.ChoiceField( label='Budget Category', widget=forms.Select(attrs={'class': 'form-control form-large'})) referer = forms.CharField(widget=forms.HiddenInput(), required=False)<file_sep>/static/assets/js/datepicker.js $(document).ready(function() { $("#id_transaction_date").datepicker({changeYear: true, showOn: "both", buttonImage: "/static/assets/img/calendar.gif", dateFormat: "d MM, yy", buttonImageOnly: true}); var position = $('#id_transaction_date').position(); var width = $('#id_transaction_date').outerWidth(); $('.ui-datepicker-trigger').css({'position': 'absolute', 'top': position.top + 7, 'left': position.left + width + 5}); });
76a2cd02c961463f06acec623936c3655df46d90
[ "SQL", "HTML", "JavaScript", "Markdown", "Python", "Text" ]
50
Python
buzz1274/simple_budget
283f0401d83cf14152ca7ea109377e62ba74f8d3
6f2a9f70ba38198abe78a5dd23662866ee8d8650
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Management.Automation; using System.Text; using System.Threading.Tasks; namespace PowerShellHelper.Models { /// <summary> /// Class for running powershell scripts /// </summary> internal class PowerShellScriptRunner { /// <summary> /// fileName pertaining to the scripts filename and extension /// <exampl>TestScript.ps1</exampl> /// </summary> private string fileName = ""; /// <summary> /// Constructor that creates the powershell script /// </summary> /// <param name="scriptName">Script file name with file extension</param> public PowerShellScriptRunner(string scriptName) { fileName = scriptName; } /// <summary> /// Gets and return the complete file path from the projects Scripts folder /// </summary> /// <param name="scriptName">Script filename with file extension</param> /// <returns></returns> private string getCompletePath(string scriptName) { string path = Path.Combine(Environment.CurrentDirectory, @"Scripts\", scriptName); return path; } /// <summary> /// Executes the powershell script that needs to be ran /// </summary> public void RunScript() { //Uses Powershell nuget pack from Microsoft, creates an instance of powershell using (PowerShell shell = PowerShell.Create()) { //get the script to run string scriptPathToRun = getCompletePath(fileName); //add the command to powershell to get content, which gets the scripts contents shell.AddCommand("Get-Content").AddArgument(scriptPathToRun); //Pipes the script from Get-Content and invokes it as a powershell script, allows getting around ExecutionPolicy Restricted shell.AddCommand("Invoke-Expression"); //Runs the powershell script shell.Invoke(); } } } } <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.Tasks; using System.Windows.Forms; using System.Management.Automation; using System.Collections.ObjectModel; using PowerShellHelper.Models; namespace PowerShellHelper { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void BtnRunScript_Click(object sender, EventArgs e) { PowerShellScriptRunner scriptRunner = new PowerShellScriptRunner("TestScript.ps1"); scriptRunner.RunScript(); //Get Powershell running with new assembly nuget pack //using (PowerShell shell = PowerShell.Create()) //{ // string fileName = "TestScript.ps1"; // string path = Path.Combine(Environment.CurrentDirectory, @"Scripts\", fileName); // //shell.AddCommand("Get-Content " + path + " | Invoke-Expression"); // shell.AddCommand("Get-Content").AddArgument(path); // shell.AddCommand("Invoke-Expression"); // shell.Invoke(); // Console.WriteLine("TEST"); // // use "AddParameter" to add a single parameter to the last command/script on the pipeline. // //shell.AddParameter("param1", "parameter 1 value!"); //} //Execute a powershell script //string finalPath = "Get-Content " + path + " | Invoke-Expression"; //System.Diagnostics.Process.Start("PowerShell.exe", finalPath); } } }
efd40d250808a973a67d9b7e6da841451f80cef3
[ "C#" ]
2
C#
mark-e-kibbe/PowerShellHelper
c235dfe618c539f6ccea00c4ad370d04618455ec
1e41008481a470176950e35f4c7f00f58ea87dbe
refs/heads/master
<file_sep>import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export const routerList = [ { path:'/menu', component:()=>import('../views/menu/menu.vue'), name:'菜单管理' }, { path:'/role', component:()=>import('../views/role/role.vue'), name:'角色管理' }, { path:'/manger', component:()=>import('../views/manger/manger.vue'), name:'用户管理' }, { path:'/cate', component:()=>import('../views/cate/cate.vue'), name:'商品分类' }, { path:"/specs", component:()=>import('../views/specs/specs.vue'), name:"商品规格" }, { path:"/goods", component:()=>import('../views/goods/goods.vue'), name:"商品管理" }, { path:"/banner", component:()=>import('../views/banner/banner.vue'), name:"轮播图管理" }, { path:"/member", component:()=>import('../views/member/member.vue'), name:"会员管理" },{ path:"/seck", component:()=>import('../views/seck/seck.vue'), name:"秒杀活动" }, ]; const router = new Router({ routes: [ { path:'/login', component:()=>import ('../pages/login.vue') }, { path:'*', redirect:'/login' }, { path:'/index', component:()=>import('../pages/index.vue'), children:[ { path:'/home', component:()=>import('../views/home.vue') }, ...routerList ] } ] }) //全局导航守卫之登录拦截 router.beforeEach((to, from, next) => { // ...如果去登录就next if(to.path=='/login'){ next() return } //如果有登录状态就next if(sessionStorage.getItem('loginInfo')){ next() return } //都没有就强制跳回登录页 next('/login') }) export default router<file_sep> import http from './axios' //封装获取菜单列表接口 export function getMenuList(){ return http.get('/api/menulist?istree=true') } //封装添加菜单接口 export function addInfo(data){ return http.post('/api/menuadd',data) } //封装删除菜单列表接口 export function delMenu(data){ return http.post('/api/menudelete',data) } //封装获取一条菜单数据的接口 export function menuInfo(params){ return http.get('/api/menuinfo', { params }) } //封装更新菜单数据接口 export function menuUpdate(data){ return http.post('/api/menuedit',data) } //================角色列表的接口==================== //封装获取角色列表接口 export function getRoleList(){ return http.get('/api/rolelist') } //封装添加角色接口 export function addRole(data){ return http.post('/api/roleadd',data) } //封装删除角色列表接口 export function delRole(data){ return http.post('/api/roledelete',data) } //封装获取一条角色数据的接口 export function roleInfo(params){ return http.get('/api/roleinfo', { params }) } //封装更新角色数据接口 export function roleUpdate(data){ return http.post('/api/roleedit',data) } //=================管理员列表的接口================= //封装获取管理员列表接口 export function getMangerList(params){ return http.get('/api/userlist',{ params }) } //封装添加管理员接口 export function addManger(data){ return http.post('/api/useradd',data) } //封装删除管理员列表接口 export function delManger(data){ return http.post('/api/userdelete',data) } //封装获取一条管理员数据的接口 export function mangerInfo(params){ return http.get('/api/userinfo', { params }) } //封装更新管理员数据接口 export function mangerUpdate(data){ return http.post('/api/useredit',data) } //封装管理员数据总数的接口 export function userCount(){ return http.get('/api/usercount') } //封装管理员登录的接口 export function mangerLogin(data){ return http.post('/api/userlogin',data) } //================商品管理接口================= //封装获取商品分类接口 export function getCateList(){ return http.get('/api/catelist?istree=true') } //封装添加商品分类接口 export function addCate(data){ return http.post('/api/cateadd',data) } //封装删除商品分类接口 export function delCate(data){ return http.post('/api/catedelete',data) } //封装获取一条商品分类的接口 export function cateInfo(params){ return http.get('/api/cateinfo', { params }) } //封装更新商品分类接口 export function cateUpdate(data){ return http.post('/api/cateedit',data) } //=================商品规格接口===================== //封装获取商品规格列表接口 export function getSpecsList(params){ return http.get('/api/specslist',{ params }) } //封装添加商品规格接口 export function addSpecs(data){ return http.post('/api/specsadd',data) } //封装删除商品规格列表接口 export function delSpecs(data){ return http.post('/api/specsdelete',data) } //封装获取一条商品规格数据的接口 export function specsInfo(params){ return http.get('/api/specsinfo', { params }) } //封装更新商品规格数据接口 export function specsUpdate(data){ return http.post('/api/specsedit',data) } //封装商品规格数据总数的接口 export function specsCount(){ return http.get('/api/specscount') } //==============商品管理接口================ //封装获取商品管理列表接口 export function getGoodsList(params){ return http.get('/api/goodslist',{ params }) } //封装添加商品管理接口 export function addGoods(data){ let file = new FormData(); //FormData 数据的添加只能用append ,获取值也只能用get方式获取 //循环添加 对象 转化成了 FormData这种格式 for (let i in data) { file.append(i, data[i]); } return http.post('/api/goodsadd',file) } //封装删除商品管理列表接口 export function delGoods(data){ return http.post('/api/goodsdelete',data) } //封装获取一条商品管理数据的接口 export function goodsInfo(params){ return http.get('/api/goodsinfo', { params }) } //封装更新商品管理数据接口 export function goodsUpdate(data){ let file = new FormData(); //FormData 数据的添加只能用append ,获取值也只能用get方式获取 //循环添加 对象 转化成了 FormData这种格式 for (let i in data) { file.append(i, data[i]); } return http.post('/api/goodsedit',file) } //封装商品管理数据总数的接口 export function goodsCount(){ return http.get('/api/goodscount') } //===============轮播图接口==================== //封装获取轮播图列表接口 export function getBannerList(){ return http.get('/api/bannerlist') } //封装添加轮播图接口 export function addBanner(data){ let file = new FormData(); //FormData 数据的添加只能用append ,获取值也只能用get方式获取 //循环添加 对象 转化成了 FormData这种格式 for (let i in data) { file.append(i, data[i]); } return http.post('/api/banneradd',file) } //封装删除轮播图列表接口 export function delBanner(data){ return http.post('/api/bannerdelete',data) } //封装获取一条轮播图数据的接口 export function bannerInfo(params){ return http.get('/api/bannerinfo', { params }) } //封装更新轮播图数据接口 export function bannerUpdate(data){ let file = new FormData(); //FormData 数据的添加只能用append ,获取值也只能用get方式获取 //循环添加 对象 转化成了 FormData这种格式 for (let i in data) { file.append(i, data[i]); } return http.post('/api/banneredit',file) } //===================秒杀活动接口=================== //封装秒杀活动添加接口 export function getSeckAdd(data) { return http.post('/api/seckadd', data) } //封装秒杀活动列表接口 export function getSeckList( params) { return http.get('/api/secklist', { params }) } //封装秒杀活动获取(一条)接口 export function getSeckInfo(params) { return http.get('/api/seckinfo', { params }) } //封装秒杀活动修改接口 export function getSeckEdit(data) { return http.post('/api/seckedit', data) } //封装秒杀活动删除接口 export function getSeckDelete(data) { return http.post('/api/seckdelete', data) } /* =============会员管理=========== */ //封装会员管理列表接口 export function getMemberList(){ return http.get('/api/memberlist') } //封装会员管理获取(一条)接口 export function getMemberInfo(params){ return http.get('/api/memberinfo',{ params }) } //封装会员管理修改接口 export function getMemberEdit(data){ return http.post('/api/memberedit',data) }<file_sep>import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) import menu from './modulse/menu' import role from './modulse/role' import manger from './modulse/manger' import cate from './modulse/cate' import specs from './modulse/specs' import goods from './modulse/goods' import banner from './modulse/banner' import member from './modulse/member' import seck from './modulse/seck' export default new Vuex.Store({ state: { loginInfo: sessionStorage.getItem('loginInfo') ? JSON.parse(sessionStorage.getItem('loginInfo')) : null //个人信息 }, getters: { getUserInfo(state) { return state.loginInfo } }, mutations: { CHANGE_USER(state, payload) { state.loginInfo = payload if (payload) { //设置本地存储 sessionStorage.setItem('loginInfo', JSON.stringify(payload)) } else { sessionStorage.removeItem('loginInfo') } } }, //actionsstate actions: { changeUserInfoAction(contxt, payload) { contxt.commit('CHANGE_USER', payload) } }, modules:{ menu, role, manger, cate, specs, goods, banner, member, seck } })<file_sep>import addBread from './addBread' export default { addBread, }<file_sep>//引入接口文件 import {getBannerList} from '../../../util/axios' //创造一个state模块 const state = { bannerList:[] } //创造一个getters模块 const getters = { getBannerlist(state){ return state.bannerList } } //创造一个mutations模块 const mutations = { REQ_ADDBanner(state,payload){ state.bannerList = payload } } //创造一个actions模块 const actions = { getBannerListAction({commit}){ getBannerList() .then(res=>{ if(res.data.code==200){ commit('REQ_ADDBanner',res.data.list) } }) } } export default { state, getters, mutations, actions, namespaced:true }
66581d6575227cde4df1add53010d199cf39a5b9
[ "JavaScript" ]
5
JavaScript
SLQLLLL/bgProject
56707a7d4f6fee61807da7f94d18399166d9d1bf
825dd984db1c985a181efc14855147f909ff197f
refs/heads/master
<file_sep>**Testing** _Zero to Mastery Course_ ``` <h1>Hello World!</h1> ``` <file_sep>//! Function Declaration // function checkDriverAge(age) { // var age = prompt("What is your age?"); // if (Number(age) < 18) { // alert("Sorry, you are too young to drive this car. Powering off"); // } else if (Number(age) > 18) { // alert("Powering On. Enjoy the ride!"); // } else if (Number(age) === 18) { // alert("Congratulations on your first year of driving. Enjoy the ride!"); // } // } // checkDriverAge(); //?====================================== //! Function Expression // let checkDriverAge2 = function(age) { // // var age = prompt("What is your age?"); // if (Number(age) < 18) { // alert("Sorry, you are too young to drive this car. Powering off"); // } else if (Number(age) > 18) { // alert("Powering On. Enjoy the ride!"); // } else if (Number(age) === 18) { // alert("Congratulations on your first year of driving. Enjoy the ride!"); // } // }; // checkDriverAge2(18); //?====================================== //! Arrays //* Exercise 6 // let array = ["Banana", "Apples", "Oranges", "Blueberries"]; // let banana = array.shift(); // console.log(banana); // array.sort(); // console.log(array); // array.push("kiwi"); // console.log(array); // let apples = array.splice(0, 1); // console.log(apples); // console.log(array); // array.reverse(); // console.log(array); // var array2 = ["Banana", ["Apples", ["Oranges"], "Blueberries"]]; // let oranges = array2[1][1][0]; // console.log(oranges); //?====================================== //! Objects // let user = { // //? Property: Value, // name: "Nathan", // age: 33, // hobby: "coding", // isMarried: false, // shout: () => { // console.log("Loud Noises!"); // } // }; // console.log(user); // console.log(user.name); // user.lastName = "Daniels"; // console.log(user); //* Run the arrow function inside user object //? this is called a Method // user.shout(); //* Change user name // user.name = "stan"; // console.log(user); //* if statement from Object Property Value // if (user.name === "Nathan" || user.lastName === "Daneils") { // console.log(`Welcome in, ${user.name} ${user.lastName}!`); // } else { // console.log(`You're Not Welcome Here`); // } //* Object inside Array // let list = [ // { // username: "Andy", // password: "<PASSWORD>" // }, // { // username: "Stan", // password: "123" // } // ]; //* pull username from 2nd object inside list array // console.log(list[1].username); //?====================================== //! Javascript Terminology //*function Declaration // function newFunction() {} //*function Expression // let newFunction = function() {}; //*expression //? an expression is anything that produces a value // 1 + 3; // let a = 2; // return true; //*calling (involking) a function // alert(); // newFunction(param1, param2); //*assign a variable // let b = true; //*function vs method // function thisIsAFunction() {} // var obj = { thisIsAMethod: function() {} }; //* calling function vs method // thisIsAFunction(0); // obj.thisIsAMethod(); //?====================================== //! LOOPS! // let todos = [ // "clean room", // "brush teeth", // "exercise", // "study javascript", // "eat healthy" // ]; // //* for loop // for (let i = 0; i < todos.length; i++) { // todos[i] = `${todos[i]}!`; // } // console.log(todos); // console.log("============================="); // //* forEach // todos.forEach(i => { // console.log(i); // }); // console.log("============================="); // //* while loop // let i = 0; // while (i < todos.length) { // console.log(todos[i]); // i++; // } // console.log("============================="); // //* do while loop // let counterTwo = 10; // do { // console.log(counterTwo); // counterTwo--; // } while (counterTwo > 0); // console.log("============================="); // //* forEach // todos.forEach(i => { // console.log(i); // }); //?====================================== //! Exercise 7 (Facebook App) // let database = [ // { // username: "Nathan", // password: "<PASSWORD>" // }, // { // username: "Stanley", // password: "<PASSWORD>" // } // ]; // let newsfeed = [ // { // username: "Bobby", // timeline: "So tired from all that learning!" // }, // { // username: "Sally", // timeline: "Javascript is sooooo cool!" // }, // { // username: "Mitch", // timeline: "Javascript is preeetyy cool!" // } // ]; // function isUserValid(username, password) { // for (let i = 0; i < database.length; i++) { // if ( // database[i].username === username && // database[i].password === <PASSWORD> // ) { // return true; // } // } // return false; // } // function signIn(username, password) { // if (isUserValid(username, password) === true) { // console.log(`Welcome, ${username}`); // console.log(newsfeed); // } else { // alert( // `Sorry ${username}, Your Username or Password seems to be Invalid. Please Try Again` // ); // } // } // var userNamePrompt = prompt("Enter Username Below:"); // var userPasswordPrompt = prompt("Enter Password Below:"); // signIn(userNamePrompt, userPasswordPrompt); // ?====================================== // ! DOM (Todo List Project) // const btn = document.getElementById("btn"); // const li = document.getElementsByTagName("li"); // const list = document.getElementById("list"); // const input = document.getElementsByTagName("input")[0]; // // console.log(li.length); // function addListAfterClick() { // if (input.value.length > 0) { // const newItem = document.createElement("li"); // newItem.style.width = "50px"; // let newText = input.value; // //add input.value to list item // newItem.innerText = newText; // list.append(newItem); // //remove innerText from input.value // input.value = ""; // } // // deleteItem(); // toggleDelete(); // } // function addListAfterKeypress(event) { // // Number 13 is the "Enter" key on the keyboard // if (event.keyCode === 13) { // // Cancel the default action, if needed // event.preventDefault(); // // Trigger the button element with a click // btn.click(); // } // } // btn.addEventListener("click", addListAfterClick); // input.addEventListener("keypress", addListAfterKeypress); // // function deleteItem() { // // for (let i = 0; i < li.length; i++) { // // li[i].addEventListener("click", () => { // // // li[i].remove(li[i]); // // li[i].parentNode.removeChild(li[i]); // // console.log("deleted"); // // }); // // } // // } // function toggleDelete() { // let delBtn = document.createElement("button"); // delBtn.innerText = "Delete"; // for (let i = 0; i < li.length; i++) { // li[i].addEventListener("click", () => { // li[i].append(delBtn); // li[i].classList.toggle("done"); // if (li[i].classList == "done") { // delBtn.classList = "done"; // delBtn.style.display = "block"; // } else { // delBtn.style.display = "none"; // } // }); // } // //* Click Delete Btn // delBtn.addEventListener("click", () => { // for (let i = 0; i < li.length; i++) { // // li[i].parentNode.removeChild(li[i]); // delBtn.parentNode.remove(); // console.log("deleted"); // // console.log(event.target); // } // }); // } // ?====================================== //! Advanced Control Flow // ! Ternary // function isUserValid(valid) { // return valid; // } // let answer = isUserValid(false) ? "You may enter" : "Access Denied"; // let automatedAnswer = // "Your Account # is " + (isUserValid(false) ? "1234" : "not available"); // let condition = () => { // if (isUserValid(true)) { // return "You may Enter"; // } else { // return "Access Denied"; // } // }; // let answer2 = condition(); // ! Switch Statement // function moveCommand(direction) { // let whatHappens; // switch (direction) { // case "forward": // whatHappens = "you encounter a monster"; // break; // case "back": // whatHappens = "you encounter a pathway"; // break; // case "left": // whatHappens = "you encounter a door"; // break; // case "right": // whatHappens = "you encounter a castle"; // break; // default: // whatHappens = "please enter a valid direction"; // } // return whatHappens; // } // moveCommand("left"); //* Built on my own // function newSwitch(direction) { // let movingdirection; // switch (direction) { // case "top": // movingdirection = "to the top"; // break; // case "bottom": // movingdirection = "to the bottom"; // break; // case "left": // movingdirection = "to the left"; // break; // case "right": // movingdirection = "to the right"; // break; // default: // movingdirection = "enter correct direction"; // break; // } // return movingdirection; // } // console.log(newSwitch("right")); // ?====================================== //! ECMAScript6 (ES6) //! Arrow Functions // let arrow = () => console.log("test"); // let arrow2 = function arrow2() { // console.log("test2"); // }; // const obj = { // player: "bobby", // experience: 100, // wizardLevel: false // }; // const player = obj.player; // const experience = obj.experience; // const wizardLevel = obj.wizardLevel; // const { player, experience } = obj; // let { wizardLevel } = obj; //! Object Properties (Dynamic) // const name = "<NAME>"; // const obj = { // [name]: "hello", // ["ray" + "smith"]: "hihi" // }; // console.log(obj); //============== // const a = "simon"; // const b = true; // const c = {}; // const obj = { // a, // b, // c // }; // console.log(obj); //============== //! Default Arguments // function greet(name = "", age = 30, pet = "cat") { // console.log(`name = ${name}, age = ${age}, pet = ${pet}`); // } // greet("billy", 24, "dog"); //============== //! Symbols // let sym1 = Symbol(); // let sym2 = Symbol("foo"); // let sym3 = Symbol("foo1"); // ?====================================== //! Advanced Functions // const first = () => { // const greet = "hi"; // const name = "nathan"; // const second = () => { // console.log(name); // alert(greet); // }; // return second; // }; // let newFunc = first(); // newFunc(); //? Closures = A function ran. the Function Executed. It's NEVER going to be Execute again. But, it's going to remember references to those variables, so the child scope always has access to parent scope //*Currying // const multiply = (a, b) => a * b; // const curriedMultiply = a => b => console.log(a * b); // const multiplyBy10 = curriedMultiply(10); // const one = a => { // const two = b => { // console.log(a * b); // }; // return two; // }; // let newOne = one(); // newOne(5)(2); //* Compose // const compose = (f, g) => a => f(g(a)); // const sum = num => num + 2; // let composed = compose( // sum, // sum // )(5); // console.log(composed); // Avoiding Side Effects, Functional Purity //? ===================================== //! Advanced Arrays // const array = [1, 2, 10, 16]; // const double = []; // const newArray = array.forEach(num => { // double.push(num * 2); // }); // console.log("forEach", double); //* MAP/ FILTER/ REDUCE //* Map // const mapArray = array.map(num => num * 2); //? Map -> Always Must use Return (unless shorthand like above) // console.log("Map", mapArray); //* Filter // const filterArray = array.filter(num => num < 5); //? Filter -> Just like Map, use Return (unless shorthand like above) // console.log("filter", filterArray); //* Reduce // const reduceArray = array.reduce((accumulator, num) => { // return accumulator + num; // }, 0); //? Accumulator is something that stores info thats happens in the body. It adds one to the next, so 1 + 2 = 3, 3 + 10 = 13, 13 + 16 = 29. So it reduces the array down to one number // console.log("reduce", reduceArray); //? ===================================== //! Advanced Objects //? reference type // let object1 = { value: 10 }; // let object2 = object1; // let object3 = { value: 10 }; //? context vs scope //* Scope is whats between the { Brackets } which can't be accessed outside of those brackets // function b() { // // scope // let a = 4; // } // console.log(a); //not defined //* Context tells you where we are inside an object // console.log(this); // inside window object // this refers to what object you are inside of // const object4 = { // a: () => { // console.log(this); // // this now refers to object4 // } // }; //? instantiation // class Player { // constructor(name, type) { // console.log("player: ", this); // this.name = name; // this.type = type; // } // introduce() { // console.log(`Hi I'm ${this.name}, I'm a ${this.type}`); // } // } // class Wizard extends Player { // constructor(name, type) { // super(name, type); // console.log("wizard: ", this); // //* anytime you run *extends*, you have to run super(), with properties passed to constructor // //* super takes us up to the constructor of Player // //* *This* Becomes wizard (wizard.name, wizard.type) // } // play() { // console.log(`Weeeee I'm a ${this.type}`); // } // } // const wizard1 = new Wizard("Shelly", "Healer"); // const wizard2 = new Wizard("Shawn", "Dark Magic"); // console.log("==========================="); // console.log(wizard1.introduce()); // console.log(wizard2.introduce()); // console.log(wizard2.play()); //?========================================== //! By Reference vs By Value //* Pass By Value // let a = 5; // let b = a; // b++; // console.log(b); //6 //No Longer Connected to a // console.log(a); //5 //========================= //* Pass By Reference // let obj1 = { name: "nate", password: "123" }; // let obj2 = obj1; // console.log(obj2); // { name: "nate", password: "123" }; // console.log("-----------------"); // obj2.password = "321"; // console.log(obj1); // { name: "nate", password: "321" }; // console.log(obj2); // { name: "nate", password: "321" }; // Stay the same //? pass by ref. also works on arrays // let c = [1, 2, 3, 4, 5]; // let d = c; // d.push(534343); // console.log(d); // console.log(c); //? To stop this behavior... //* let d = [].concat(c); //This clones c into a new array called d // let obj = { // a: "a", // b: "b", // c: "c" // }; //? How to assign Obj to a new place in memory (without reference) // run the object constructor and assign obj to a new object // let newObj = Object.assign({}, obj); // console.log("newObj", newObj); // obj.c = 5; // console.log("newObj", newObj); // console.log("obj", obj); //! This is the same as running Object.assign() // let clone2 = { ...newObj }; // newObj.b = 5; // console.log("newObj updated", newObj); // console.log("clone2/ no change", clone2); //? if you have a nested object // let obj2 = { // a: "a", // b: "b", // c: { c: "Old C" } // This is another place in memory // }; // console.log("original obj2", obj2); // object3 = { ...obj2 }; // console.log(object3); // obj2.c.c = "NEW"; // console.log("updated obj2", obj2); //!shadow cloning means you can only clone the first level inside an object. so when running the code from obj, even though we cloned everything like before, they would all show the nested object inside c. You need JSON to Clone multi levels // for some reason I can't get this to work //! IF this object is really deep, it could hurt performance. // let superClone = JSON.parse(JSON.stringify(obj2)); // console.log("superClone", superClone); //?========================================== //! Type Coercion // Known To make people pull out their hair in frustration //* Type Coercion is when you use two equal signs (==) to find if they are equal. If the types aren't equal, it tries to "Coerce" it to be the same. which is why (2 == "2" (True)) //* When using two equals signs for JavaScript equality testing, some funky conversions take place. //? Use 3 equal signs to find equal values without trying to Coerce. (2 === "2" (False)) //? When using three equals signs for JavaScript equality testing, everything is as is. Nothing gets converted before being evaluated. //* This also works with if statements (typically 1 and 0 being Coerced into True or False). // if (1) { // // 1 is True // console.log("1 is true"); // } //?========================================== //! ES7 //* Includes() //? Includes tells you if something is inside an element. Below, we check if the string "hello" includes the letter "o", which is True // let newHello = "hello".includes("o"); // console.log(newHello); //true //? Includes also works on Arrays // const pets = ["cat", "dog", "rabbit"]; // const cat = pets.includes("cat"); // console.log(cat); //true //* exponential operator (**) // const square = x => x ** 2; // (**) = to the power of // const cube = y => y ** 3; // console.log(square(2)); // console.log(cube(2)); //?========================================== //! ES8 //* padStart() //* padEnd() // These add padding?! // console.log("turtle".padStart(10)); // "__________turtle" //this adds 10 spaces in front of "turtle" //* =========================== // const fun = (a, b, c, d) => { // console.log(a); // }; // console.log(fun(1, 2, 3, 4)); //? Object values, entries and keys //* Object.values; //* Object.entries; //* Object.keys // let obj = { // username0: "santa", // username1: "Rudolf", // username2: "Mr. Grinch" // }; //? Turn Object into array with Object.keys() //* Keys are the "property values of an object (left of (:))" // let keys = Object.keys(obj); // Turns object into Array // console.log(keys); // [ username0, username1, username2 ] //? Iterate through objects // Object.keys(obj).forEach((key, index) => { // console.log(key, obj[key]); // }); //? Find the object Values (right of (:)) // Object.values(obj).forEach(value => { // console.log("values", value); // }); //? Full Object Entries (Prints both key and value in seperate arrays) // Object.entries(obj).forEach(value => { // console.log("entries", value); // }); //? Change key names // let newNames = Object.entries(obj).map(value => { // return value[1] + value[0].replace("username", ""); // }); // console.log(newNames); // console.log(Object.values(obj)); //?========================================== //! Advanced Loops! // const basket = ["apples", "oranges", "grapes"]; // const detailedBasket = { // apples: 5, // oranges: 10, // grames: 1000 // }; //? for loop // for (let i = 0; i < basket.length; i++) { // console.log("for loop: ", basket[i]); // } //? forEach // basket.forEach(item => { // console.log("forEach: ", item); // }); //? for of // Iterating - arrays, strings //! for of loops do NOT work with Objects - Objects are Not Iterable // for (item of basket) { // console.log("forOf loop", item); // } //? for in - object properties // enumerating (enumerable properties) - objects // for (item in detailedBasket) { // console.log("forIn: ", item); // } //?========================================== //! Debugging! // const flattened = [[0, 1], [2, 3], [4, 5]].reduce((accumulator, array) => { // console.log("array", array); // console.log("accumulator", accumulator); // return accumulator.concat(array); // }, []); //?========================================== //! How Javascript Works //? What is a program? //* Allocate Memory //* Parse and Execute scripts // const a = 1; // we just allocated memory // const b = 10; // const c = 100; //* memory leaks happen when you have unused variables taking up space. It fills up the "Memory Heap" //* Call stack is what reads and executes our scripts // const one = () => { // const two = () => { // console.log("4"); // }; // two(); // }; // one(); //Asynchronous // setTimeout() is part of a webAPI (DOM (Document), AJAX(XMLHttpRequest), Timeout (setTimout)) // console.log("1"); // setTimeout(() => { // console.log("2"); // }, 2000); // console.log("3"); //! What Happens when you run setTimeout? // console.log("1") goes into the CALL STACK. This gets executed so we console log "1" to browser // Then runs setTimeout() which goes into the WebAPI to be run. The WebAPI starts a 2 second timer (in this case). While this is happening, the CALL STACK is empty and ready to take the next input. // console.log("3") goes into the CALL STACK. This gets executed so we console log "3" to browser // After the 2 seconds is up, the function inside setTimeout is run, but since its a callback, it gets moved to CALLBACK QUEUE. Then the EVENT LOOP checks if there is anything left inside CALL STACK. IF CALL STACK is empty, the CALLBACK QUEUE moves the function into the CALL STACK to be executed, which in this case, console logs "2" // So "1" gets logged first, then "3" gets logged before "2" (1,3,2) //* Javascript Runtime Environment //====================================== // CALL STACK // WEB API // CALLBACK QUEUE // EVENT LOOP //====================================== // Asynchronous vs synchronous //?========================================== //! Modules // use browserify to reduce the number of script tags used in an html document. //?========================================== //! Git/Github // Don't work on Master, Always branch //? check status of branchs w/ "git status" //? start new git branch w/ "git branch 'name'" //? check branches w/ "git branch" //? switch branches w/ "git checkout 'name'" //? get the latest branch commit w/ "git pull" //? merge branches w/ "git merge master" //* Keep Fork Up To Date //? git remote -v (You'll see current config remote repos for your fork) //? type "git remote add upstream <clone url>" //? verify with "git remote -v". Url for fork as 'origin', url for original repo as 'upstream' //Now, you can keep your fork synced with the upstream repository with a few Git commands. //One simple way is to do the below command from the master of your forked repository: git pull upstream master //?========================================== //! React //? Components always start with a Capital Letter //? Always remember to import/Export components //? Always have to render() a class //?========================================== //! Promises //? A Promise is an object that may produce a single value some time in the future //? Either a resolved value, or a reson that it's not resolved (rejected) //* Promise's can be in 1 of 3 states (fullfilled (resolved), rejected, pending) // const promise = new Promise((resolve, reject) => { // if (true) { // resolve("suff Worked"); // } else { // reject("Error, it broke"); // } // }); // promise // .then(result => result + "!") // .then(result2 => { // throw Error; // console.log(result2); // }) // .catch(() => console.log("error!")); // //? .catch catches any errors between/inside .then //=============== // const urls = [ // "https://jsonplaceholder.typicode.com/users", // "https://jsonplaceholder.typicode.com/posts", // "https://jsonplaceholder.typicode.com/albums" // ]; // Promise.all( // urls.map(url => { // return fetch(url).then(resp => resp.json()); // }) // ) // .then(results => { // console.log(results[0]); // console.log(results[2]); // console.log(results[3]); // }) // .catch(console.log("error")); <file_sep>// Solve the below problems: // #1) Check if this array includes the name "John". // const dragons = ["Tim", "Johnathan", "Sandy", "Sarah"]; // let included = dragons.includes("john"); // console.log("is John in Dragons array?", included); // #2) Check if this array includes any name that has "John" inside of it. If it does, return that // name or names in an array. const dragons2 = ["Tim", "Johnathan", "Sandy", "Sarah"]; let news = dragons2.filter(name => name.includes("John")); console.log(news); // #3) Create a function that calulates the power of 100 of a number entered as a parameter const powerHundo = num => num ** 100; console.log(powerHundo(5)); // #4) Useing your function from #3, put in the paramter 10000. What is the result? // Research for yourself why you get this result if (powerHundo(10000) === Infinity) { console.log("Its Infinity!"); } else { console.log("Not infinity"); }
309a9cbe57025376a2bce7e32464cf994d9bf899
[ "Markdown", "JavaScript" ]
3
Markdown
NathanielDaniels/Zero-to-Mastery
3f5b249f908a1c794d6ca5920d94fa5db6064368
a96b79dd65bd31c5417379c5ed07f777c4d9cac4
refs/heads/master
<file_sep>//Java program to find quotient and remainder package javapractice; import java.util.*; public class QuotientRemainder { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); System.out.println("Enter the numbers to find quotient and remainder"); int n1=sc.nextInt(); int n2=sc.nextInt(); System.out.println("Quotient for "+n1+"/"+n2+" is "+n1/n2); //quotient System.out.println("Remainder for "+n1+"/"+n2+" is "+n1%n2); //remainder sc.close(); } } <file_sep>//Java program to check if a character is vowel or consonant package javapractice; import java.util.Scanner; public class Alphabet { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); System.out.println("Enter the alphabet"); char ch=sc.next().charAt(0); //@input ch to get character from the inut line in console if(Character.isAlphabetic(ch)) //@function isAlphabetic to check if the character is an alphabet { if(ch=='a'||ch=='A'||ch=='e'||ch=='E'||ch=='i'||ch=='I'||ch=='o'||ch=='O'||ch=='u'||ch=='U') //@if condition to check if character is vowel { System.out.println(ch+" is a vowel"); //@print statement prints if character is vowel } else System.out.println(ch+" is a consonant"); //@print statement prints if a character is consonant } else System.out.println("Enter an alphabet!!!!"); sc.close(); } } <file_sep>//Java program to find prime factors package javapractice; import java.util.*; public class Factors { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); System.out.println("Enter the number to find prime factor"); int n=sc.nextInt(); //@input n whose prime factor is tot be calculated System.out.println("Prime factors of "+n+" are"); for(int i=2;i<=n;i++) //@for loop to iterate through numbers between 2 and n { while(n%i==0) //to check if i is factor of n { System.out.print(i+" "); //@output gives the prime factors one by one n=n/i; //to get prime factors only } } sc.close(); } } <file_sep># basic core java and functional programming concepts. There are 15 questions <file_sep>package javapractice; import java.util.*; public class Quadratic { public static void roots(int a,int b,int c) { int delta=b*b-4*a*c; double root1=(-b+Math.sqrt(delta))/(2*a); //formula for calculating roots of a quadratic equations double root2=(-b-Math.sqrt(delta))/(2*a); System.out.println("The roots af the equaiton is "+root1+","+root2); } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); System.out.println("Enter the value of a,b,c"); int a=sc.nextInt(); //get input from console int b=sc.nextInt(); int c=sc.nextInt(); roots(a,b,c); // call the function to calculate roots sc.close(); } } <file_sep>package javapractice; import java.util.Scanner; public class SomOfThree { public static Scanner sc=new Scanner(System.in); public static int[] array=new int[10]; public static int n; public static int distinctTriplets() { int d=0; for(int i=0;i<n-2;i++) for(int j=i+1;j<n-1;j++) for(int k=j+1;k<n;k++) { if(array[i]+array[j]+array[k]==0) { d++; System.out.println("("+array[i]+","+array[j]+","+array[k]+")"); } } return d; } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Enter the number of elements:"); n=sc.nextInt(); System.out.println("Enter the elements:"); for(int i=0;i<n;i++) { array[i]=sc.nextInt(); } int d=0; System.out.println("The distinct triplets are:"); d=distinctTriplets(); System.out.println("Number of distinct triplets is "+d); } }
e86d8f7191f3f2537d227cc1d6eaeacdfa88cf2e
[ "Markdown", "Java" ]
6
Java
shraazp/java_basic_programs
12ed544886aeaff4b348670a10135b74f31c3180
eed96298b96e383642df99ddfb8b34ab7fbc4f45
refs/heads/master
<repo_name>Detravoir/Detradio<file_sep>/index.php <!--PROGRAM IN START MENU--> <!--<li class="dropdown-item launch" data-launch="LAUNCH CLASS" data-title="TITLE" data-icon="ICON" data-url="URL">NAAM</li>--> <!--PROGRAM ON DESKTOP--> <!--<div class="desktop-item launch desktop-icon" data-launch="LAUNCH ICON" data-title="TITLE" data-icon="ICON" data-url="URL"> <p class="desktop-icon-title">NAME</p> </div>--> <?php spl_autoload_register(function($class){ $directories = array('pages/radio-stations/module/'); foreach ($directories as $directory) { if (file_exists($directory . $class . ".php")) { require_once $directory . $class . ".php"; break; } else continue; } }); $modules = array( new Radiozora(), new PirateStation(), new RadiozoraChill(), new Psychedelik() ); $data = array(); foreach ($modules as $module){ $data[] = $module->getModuleData(); } ?> <!DOCTYPE html> <html content="application/x-www-form-urlencoded; charset=UTF-8"> <head> <script> function alertUser(msg) { alert(msg) } </script> <meta charset="UTF-8"> <title>Detradio</title> <link rel="stylesheet" href="css/style.css"> <link rel="shortcut icon" href="media/images/favicon.ico" type="image/x-icon" sizes="16x16"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body onload="alertUser('Welcome to Detradio, here you can listen to a lot of live radio broadcasts. You can also find information about me and some school projects that i\'ve worked on/created. ' + 'Also, check your volume before opening radio stations, it can be loud!! ')"> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css" type="text/css"/> <div class="startbar"> <div id="startbutton" class="startbutton-off"> <b>Start</b> </div> <div class="time launch" data-launch="time" data-title="time" data-icon="" data-url="pages\time\index.html"> </div> </div> <div id="menu"> <div class="sidebar"></div> <div class="headline"><b>Windows</b> 98 </div> <ul class="menu-content"> <!-- PROGRAMS--> <li class="item more" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990247/directory_program_group_small_fqw8rr.ico">Programs <ul class="dropdown-content dropdown-to-many"> <li class="dropdown-item-more more" data-icon="https://orig00.deviantart.net/60a0/f/2015/168/0/0/trippy_icon__free_to_use___by_candyprincessaryanna-d8xoqks.gif">Trippy <ul class="dropdown-content-2"> </ul> </li> <li class="dropdown-item" data-icon="https://res.cloudinary.com/penry/image/upload//w_65,h_65,c_lpad/v1474990266/msie2_ks3wek.png">Internet Explorer</li> <li class="dropdown-item launch" data-launch="notepad" data-title="Notepad" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico" data-url="pages\notepad.php">Notepad</li> <li class="dropdown-item launch" data-launch="paint" data-title="Paint" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico" data-url="https://sketch.io/sketchpad/">Paint</li> <li class="dropdown-item launch" data-launch="life" data-title="L I F E . E X E" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico" data-url="http://wormax.io/">L I F E . E X E</li> <li class="dropdown-item launch" data-launch="useless" data-title="Useless web" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico" data-url="http://www.theuselessweb.com/">Useless web</li> <li class="dropdown-item launch" data-launch="thomasboard" data-title="Thomas board" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico" data-url="https://kozie.github.io/thomasboard/">Thomas board</li> <li class="dropdown-item launch" data-launch="solarsystemexplorer" data-title="Solar System Explorer" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico" data-url="pages\solar-system-explorer\index.html">Solar System Explorer</li> </ul> </li> <!-- PHOTOS--> <li class="item more" data-icon="https://res.cloudinary.com/penry/image/upload/w_65,h_65,c_lpad/v1474990246/directory_pictures_ualddt.png">Photos <ul class="dropdown-content"> <li class="dropdown-item launch" data-launch="pepe" data-title="Rare Pepe.jpg" data-icon="https://res.cloudinary.com/penry/image/upload/q_100/v1474990272/pictures_bt9tfg.ico" data-url="http://penry.me/projects/windows98/rarepepe/">Rare Pepe.jpg</li> <li class="dropdown-item launch" data-launch="dank" data-title="Requiem for a meme.gif" data-icon="https://res.cloudinary.com/penry/image/upload/q_100/v1474990272/pictures_bt9tfg.ico" data-url="http://penry.me/projects/windows98/requiem/">Requiem for a meme.gif</li> <li class="dropdown-item launch" data-launch="igdetra" data-title="Detravoir's IG" data-icon="https://instagram-brand.com/wp-content/uploads/2016/11/app-icon2.png" data-url="http:///lightwidget.com/widgets/a0012b312121533d8364205c218beffe.html">Detravoir's IG</li> </ul> </li> <!-- MUSIC--> <li class="item more" data-icon="https://res.cloudinary.com/penry/image/upload//w_40,h_40,c_lpad/v1474990234/cd_audio_cd_mcloiq.png">Music <ul class="dropdown-content dropdown-music"> <!-- RADIO STATIONS FOLDER--> <li class="dropdown-item-more more" data-icon="http://cd.textfiles.com/winfiles/winfiles1/gifs/folder.gif"> Radio stations <ul class="dropdown-content-2 dropdown-to-many"> <li class="dropdown-item launch" data-launch="радиорекорд" data-title="радио рекорд" data-icon="media/images/radiorecord.jpg" data-url="http://www.radiorecord.ru/">радио рекорд</li> <li class="dropdown-item launch" data-launch="R" data-title="Radiozora | <?php echo $data['0']['0']; ?>" data-icon="<?php if ($data['0']['1'] != ""){echo $data['0']['1'];}else{echo "https://radiozora.fm/wp-content/themes/radiozora.fm/images/oo.png";} ?>" data-url="pages\radio-stations\radiozora.php">Radiozora</li> <li class="dropdown-item launch" data-launch="RC" data-title="RadiozoraChill | <?php echo $data['2']; ?>" data-icon="https://radiozora.fm/wp-content/themes/radiozora.fm/images/oo.png" data-url="pages\radio-stations\radiozoraChill.php">RadiozoraChill</li> <li class="dropdown-item launch" data-launch="PS" data-title="Pirate Station | <?php echo $data['1'][0]; ?>" data-icon="https://dnbfm.ru/wp-content/uploads/2015/11/ps1-200x200.jpg" data-url="pages\radio-stations\pirateStation.php">Pirate Station</li> <li class="dropdown-item launch" data-launch="NFM" data-title="Nashville FM" data-icon="http://www.nashvilletv.nl/wp-content/uploads/2016/08/logo-white-fm-2.png" data-url="pages\radio-stations\nashvilleFM.php">Nashville FM</li> <li class="dropdown-item launch" data-launch="p85" data-title="POWER85" data-icon="https://mixlr-assets.s3.amazonaws.com/users/8a39ebccbd35d2c85580fdda23035556/thumb.jpg?1369885137" data-url="pages\radio-stations\power85\index.php">POWER85</li> <li class="dropdown-item launch" data-launch="Plaza" data-title="Nightwave Plaza" data-icon="https://plaza.one/img/icons/favicon-32x32.png" data-url="https://plaza.one/">Nightwave Plaza</li> <li class="dropdown-item launch" data-launch="CC" data-title="Current Condition" data-icon="http://currentcondition.org/assets/favicon_large-f3bfed70454b264c28d154d6f8b3f821.jpg" data-url="http://currentcondition.org/">Current Condition</li> <li class="dropdown-item launch" data-launch="ГОПFM" data-title="ГОП FM" data-icon="http://radioportal.ru/sites/default/files/uploads/main_photo/4070.jpg" data-url="pages\radio-stations\ГОПFM.php">ГОП FM</li> <li class="dropdown-item launch" data-launch="Psychedelik" data-title="Psychedelik | <?php echo $data['3'][0]; ?>" data-icon="http://www.psychedelik.com/img/psytrance.jpg" data-url="pages\radio-stations\psychedelik\index.html">Psychedelik</li> <li class="dropdown-item launch" data-launch="EiloRadio" data-title="Eilo Radio" data-icon="https://static-media.streema.com/media/cache/ee/c5/eec58aa67bc37f4b2e4b5e950b210c6f.jpg" data-url="pages\radio-stations\eliorioadio\index.html">Eilo Radio</li> <li class="dropdown-item launch" data-launch="RecordHardBass" data-title="Record Hard Bass" data-icon="https://data.whicdn.com/images/300738126/superthumb.png" data-url="pages\radio-stations\recordHardBass.php">Record Hard Bass</li> <li class="dropdown-item launch" data-launch="TRR" data-title="Third Rock Radio" data-icon="http://player.streamguys.com/thirdrock/sgplayer/include/assets/img/ThirdRockRadio500x500.jpg" data-url="pages\radio-stations\thirdRockRadio.php">Third Rock Radio</li> <li class="dropdown-item launch" data-launch="amoris" data-title="Amoris Dub Techno" data-icon="http://geo-media.beatport.com/image_size/500x500/23f7a9b9-1c1b-433f-82f4-f1ae72229862.jpg" data-url="pages\radio-stations\amorisDubTechno.php">Amoris Dub Techno</li> </ul> </li> <!-- SAVANT FOLDER--> <li class="dropdown-item-more more" data-icon="http://cd.textfiles.com/winfiles/winfiles1/gifs/folder.gif">Savant <ul class="dropdown-content-2"> <li class="dropdown-item launch" data-launch="heartbreakers" data-title="Savant - Heartbreakers" data-icon="http://images.genius.com/efdc4b601e3713d1271d55f8480960fa.1000x1000x1.jpg" data-url="http://www.youtube.com/embed/JqUAD-FOJgY?&autoplay=1&loop=1&rel=0&disablekb=1&hd=1&color=white">Savant - Heartbreakers</li> <li class="dropdown-item launch" data-launch="highlander" data-title="Aleksander Vinter - Highlander" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/kg6JRilwc7I?&autoplay=1&loop=1&rel=0&disablekb=1&hd=11&color=white">Aleksander Vinter - Highlander</li> <li class="dropdown-item launch" data-launch="mortals" data-title="Savant - Mortals" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/ReEjRwDUU4A?&autoplay=1&loop=1&rel=0&disablekb=1&hd=11&color=white">Savant - Mortals</li> </ul> </li> <!-- DETRAVOIR FOLDER--> <li class="dropdown-item-more more" data-icon="http://cd.textfiles.com/winfiles/winfiles1/gifs/folder.gif">Detravoir <ul class="dropdown-content-2"> <li class="dropdown-item launch" data-launch="tingeling" data-title="Detravoir - TingeLing Ft. Demerkies" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/307138930&amp;color=%23ff5500&amp;auto_play=true&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;show_teaser=true&amp;visual=true">Detravoir - TingeLing Ft. Demerkies</li> <li class="dropdown-item launch" data-launch="glücklich" data-title="Demerkies - Glücklich Dorf Ft. Detravoir" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/329568332&amp;color=%23ff5500&amp;auto_play=true&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;show_teaser=true&amp;visual=true">Demerkies - Glücklich Dorf Ft. Detravoir</li> <li class="dropdown-item launch" data-launch="DD" data-title="Detravoir - Do Drugs" data-icon="https://lh3.googleusercontent.com/CNpLPsz5_CH1yu-qaS5eJZgURXMW-d8x0Kry41yVWSgS2883H3CeTvEdQNVke8ry3N7I=w170" data-url="http://www.youtube.com/embed/TvhQRrHwG0w?&autoplay=1&rel=0&disablekb=1&hd=1&color=white">Detravoir - Do Drugs</li> <li class="dropdown-item launch" data-launch="DDPT2" data-title="Detravoir - Do Drugs Part 2" data-icon="https://lh3.googleusercontent.com/CNpLPsz5_CH1yu-qaS5eJZgURXMW-d8x0Kry41yVWSgS2883H3CeTvEdQNVke8ry3N7I=w170" data-url="http://www.youtube.com/embed/inC7FAL2Xqw?&autoplay=1&loop=1&rel=0&disablekb=1&hd=1&color=white">Detravoir - Do Drugs Part 2</li> <li class="dropdown-item launch" data-launch="ScooboSnox" data-title="Detravoir - Scoobo Snox Ft. Demerkies" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/8ub6oBi9WjY?&autoplay=1&loop=1&rel=0&disablekb=1&hd=1&color=white">Detravoir - Scoobo Snox Ft. Demerkies</li> <li class="dropdown-item launch" data-launch="BreakMyStridRemix" data-title="Detravoir - Break My Stride (Psytrance Remix)" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/z4gkkuDSnz0?&autoplay=1&loop=1&rel=0&disablekb=1&hd=1&color=white">Detravoir - Break My Stride (Psytrance Remix)</li> <li class="dropdown-item launch" data-launch="SelfImprovement" data-title="Detravoir Ft. DuckRider - Self Improvement" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/IkbYwoZ6WI0?&autoplay=1&loop=1&rel=0&disablekb=1&hd=1&color=white">Detravoir Ft. DuckRider - Self Improvement</li> </ul> </li> <!-- PSYTRANCE FOLDER--> <li class="dropdown-item-more more" data-icon="http://cd.textfiles.com/winfiles/winfiles1/gifs/folder.gif"> Psytrance <ul class="dropdown-content-2"> <li class="dropdown-item launch" data-launch="IMSMAN" data-title="Infected Mushroom - Send Me an Angel" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="https://www.youtube.com/embed/4l8Wkrb5JNw">Infected Mushroom - Send Me an Angel</li> <li class="dropdown-item launch" data-launch="DJW" data-title="Astrix - Deep Jungle Walk" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/lIuEuJvKos4?&autoplay=1&rel=0&loop=1&showinfo=0&controls=0&hd=1&autohide=0&color=white&playlist=lIuEuJvKos4">Astrix - Deep Jungle Walk</li> <li class="dropdown-item launch" data-launch="genesis" data-title="UnderCover - Genesis [Full Album]" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/394368009&amp;color=%23ff5500&amp;auto_play=true&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;show_teaser=true&amp;visual=true">UnderCover - Genesis [Full Album]</li> <li class="dropdown-item launch" data-launch="BurningStones" data-title="Astrix - Burning Stones" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/368505449&amp;color=%23ff5500&amp;auto_play=true&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;show_teaser=true&amp;visual=true">Astrix - Burning Stones</li> <li class="dropdown-item launch" data-launch="Adhana" data-title="Vini Vici & Astrix - Adhana" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/366227183&amp;color=%23ff5500&amp;auto_play=true&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;show_teaser=true&amp;visual=true">Vini Vici & Astrix - Adhana</li> <li class="dropdown-item launch" data-launch="PsychedelicTrancemixNovember2017" data-title="Psychedelic Trance mix November 2017" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/geajCOmYRcw?&autoplay=1&loop=1&rel=0&disablekb=1&hd=1&color=white">Psychedelic Trance mix November 2017</li> <li class="dropdown-item launch" data-launch="xsprojectmushroomsforbitcoins" data-title="XS Project - Mushrooms for bitcoins" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/-EzkUmQovvM?&autoplay=1&loop=1&rel=0&disablekb=1&hd=1&color=white">XS Project - Mushrooms for bitcoins</li> <li class="dropdown-item launch" data-launch="RickandMorty" data-title="Rick and Morty (Rameses B 'Psytrance' Remix)" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/iMHVfCyElW0?&autoplay=1&loop=1&rel=0&disablekb=1&hd=1&color=white">Rick and Morty (Rameses B 'Psytrance' Remix)</li> </ul> </li> <li class="dropdown-item launch" data-launch="420" data-title="MACINTOSH PLUS - リサフランク420 / 現代のコンピュー.mp3" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/cU8HrO7XuiE?&autoplay=1&loop=1&rel=0&disablekb=1&hd=1&color=white">MACINTOSH PLUS 420.mp3</li> <li class="dropdown-item launch" data-launch="hype" data-title="Hard Bass School - hype 2k!8" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/p5Aa4UU2xT8?&autoplay=1&loop=1&rel=0&disablekb=1&hd=1&color=white">Hard Bass School - hype 2k!8</li> <li class="dropdown-item launch" data-launch="horsecock" data-title="No cock Like horse cock Pepper Coyote" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/h2dJ-JUzhVs?&autoplay=1&loop=1&rel=0&disablekb=1&hd=1&color=white">No cock Like horse cock Pepper Coyote</li> <li class="dropdown-item launch" data-launch="undertale" data-title="Undertale Orchestral" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="http://www.youtube.com/embed/MEsuE35uSvo?&autoplay=1&loop=1&rel=0&disablekb=1&hd=1&color=white">Undertale Orchestral</li> <li class="dropdown-item launch" data-launch="automatic" data-title="The Automatic" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="https://open.spotify.com/embed/user/detravoir/playlist/2bTlC2mmVn5wNruu00zP09">The Automatic</li> <li class="dropdown-item launch" data-launch="fairytale" data-title="Demerkies - 舞-HiME Fairy Tale" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990282/SoundYel_aunogm.ico" data-url="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/422107350&amp;color=%23ff5500&amp;auto_play=true&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;show_teaser=true&amp;visual=true">Demerkies - 舞-HiME Fairy Tale</li> </ul> </li> <!-- VIDEOS--> <li class="item more" data-icon="https://res.cloudinary.com/penry/image/upload/c_lpad,g_center,r_0,w_65/v1474990261/media_player_file_sqjlgm.png">Videos <ul class="dropdown-content"> <li class="dropdown-item launch" data-launch="sundaySchool" data-title="SUNDAY SCHOOL.mp4" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990261/media_player_file_sqjlgm.png" data-url="https://www.youtube.com/embed/rTfa-9aCTYg">SUNDAY SCHOOL.mp4</li> <li class="dropdown-item launch" data-launch="kungFury" data-title="KUNG FURY.mp4" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990261/media_player_file_sqjlgm.png" data-url="https://www.youtube.com/embed/bS5P_LAqiVg">KUNG FURY.mp4</li> <li class="dropdown-item launch" data-launch="ponyandboy" data-title="Pony & Boy" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990261/media_player_file_sqjlgm.png" data-url="https://www.youtube.com/embed/f-v-wIX9ggI">Pony & Boy</li> </ul> </li> <!-- OTHERS--> <li class="item settings" data-icon="https://res.cloudinary.com/penry/image/upload/q_100/v1474990280/settings_gear_zxd7tf.ico">Settings</li> <li class="item" data-launch="find" data-title="Find" data-icon="https://res.cloudinary.com/penry/image/upload/q_100/v1474990279/search_file_2_yy4muv.ico" data-url="">Find</li> <li class="item" data-launch="Help" data-title="Help" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990254/help_book_small_ra0uhc.ico" data-url="">Help</li> <li class="item" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990231/application_hourglass_small_yyhy5z.ico" data-url="">Run</li> <li class="item" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990258/key_win_anpnfo.ico">Log off</li> <li class="item" data-launch="Shutdown" data-title="Shutdown" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990281/shut_down_normal_t24or4.ico" data-url="pages/shutdown.html">Shutdown</li> </ul> </div> <div class="desktop"> <div class="columns"> <!-- ROW 1--> <div class="column"> <div class="desktop-item launch desktop-icon" data-launch="радиорекорд" data-title="радио рекорд" data-icon="media/images/radiorecord.jpg" data-url="https://www.radiorecord.ru/stations"> <p class="desktop-icon-title">радио рекорд</p> </div> <div class="desktop-item launch desktop-icon" data-launch="PS" data-title="Pirate Station | <?php echo $data['1'][0]; ?>" data-icon="https://dnbfm.ru/wp-content/uploads/2015/11/ps1-200x200.jpg" data-url="pages\radio-stations\pirateStation.php"> <p class="desktop-icon-title">Pirate Station</p> </div> <div class="desktop-item launch desktop-icon" data-launch="Psychedelik" data-title="Psychedelik | <?php echo $data['3'][0]; ?>" data-icon="http://www.psychedelik.com/img/psytrance.jpg" data-url="pages\radio-stations\psychedelik\index.html"> <p class="desktop-icon-title">Psychedelik</p> </div> <div class="desktop-item launch desktop-icon" data-launch="R" data-title="Radiozora | <?php echo $data['0']['0']; ?>" data-icon="<?php if ($data['0']['1'] != ""){echo $data['0']['1'];}else{echo "https://i1.sndcdn.com/artworks-000071098319-473rmc-t500x500.jpg";} ?>" data-url="pages\radio-stations\radiozora.php"> <p class="desktop-icon-title">Radiozora</p> </div> <div class="desktop-item launch desktop-icon" data-launch="RC" data-title="RadiozoraChill | <?php echo $data['2']; ?>" data-icon="https://i1.sndcdn.com/artworks-000071098319-473rmc-t500x500.jpg" data-url="pages\radio-stations\radiozoraChill.php"> <p class="desktop-icon-title">RadiozoraChill</p> </div> <div class="desktop-item launch desktop-icon" data-launch="Plaza" data-title="Nightwave Plaza" data-icon="https://plaza.one/img/icons/favicon-32x32.png" data-url="https://plaza.one/"> <p class="desktop-icon-title">Nightwave Plaza</p> </div> </div> <!-- ROW 2--> <div class="column"> <div class="desktop-item launch desktop-icon" data-launch="notepad" data-title="Notepad" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico" data-url="pages\notepad.php"> <p class="desktop-icon-title">Notedpad</p> </div> </div> <!-- ROW 3--> <div class="column"> </div> <!-- ROW 4--> <div class="column"> <div class="desktop-item launch desktop-icon" data-launch="mariteam" data-title="Mariteam" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico" data-url="pages/mariteam.html"> <p class="desktop-icon-title">Mariteam, virutal learning program</p> </div> <div class="desktop-item launch desktop-icon" data-launch="reserveringssysteem" data-title="Reserverings Systeem" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico" data-url="detra/school/periode2/CLE2/index.php"> <p class="desktop-icon-title">Back-End school project<br/>"Reserverings Systeem" <br/>(admin inlog is "test", "test")</p> </div> </div> <!-- ROW 5--> <div class="column"> <div class="desktop-item launch desktop-icon" data-launch="aboutme" data-title="About Me" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico" data-url="pages\aboutme.html"> <p class="desktop-icon-title">About Me</p> </div> <div class="desktop-item launch desktop-icon" data-launch="aboutdetradio" data-title="About Detradio" data-icon="https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico" data-url="pages\aboutdetradio.html"> <p class="desktop-icon-title">About Detradio</p> </div> </div> <!-- ROW 6--> <div class="column"> </div> <!-- ROW 7--> <div class="column"> </div> <!-- ROW 8--> <div class="column"> </div> <!-- ROW 9--> <div class="column"> </div> <!-- ROW 10--> <div class="column"> </div> <!-- ROW 11--> <div id="column_11" class="column"> </div> </div> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js'></script> <script type="text/javascript" src="js/jGravity-min.js"></script> <script src="js/index.js"></script> <!--Tumblr folder--> <script type="text/javascript"> $(document).ready(function() { $('.settings').on('click', function() { $('body').jGravity({ target: 'everything', ignoreClass: 'startbar', weight: 25, depth: 5, drag: true }); }); }); function getData(targetId, title, imgUrl, url){ if (!isWindowOpen(targetId)) { createProgram(targetId, title, imgUrl, url); $('#menu').hide(); $("#startbutton").removeClass("startbutton-on"); } else { openWindow(targetId); $('#menu').hide(); $("#startbutton").removeClass("startbutton-on"); console.log("program already exists... opening window") } } function savedFile(targetId){ console.log('Saving ' + targetId); $("#column_11").append( <?php $id = "targetId"?> "<div class='desktop-item launch desktop-icon' data-launch='targetId' data-title='" + <?php echo $id; ?> + "' data-icon='https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico' data-url='pages/notepad.php' style='background-image: url(\"https://res.cloudinary.com/penry/image/upload/v1474990270/notepad_file_kf9wqx.ico\");'>" + "<p class='desktop-icon-title'>" + <?php echo $id; ?> + "</p>" + "</div>" ); } </script> </body> </html> <file_sep>/pages/radio-stations/module/RadiozoraChill.php <?php class RadiozoraChill{ public function getModuleData(){ return $this->retrieveData(); } private function retrieveData() { $data = $this->retrieveApi(); $name = $data['name']; return $name; } function retrieveApi() { $url = "https://chill.airtime.pro/api/live-info"; $ch = curl_init(); // Disable SSL verification curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url); // Execute $result = curl_exec($ch); $radiozoraChill = json_decode($result, true); return $radiozoraChill['current']; } } <file_sep>/pages/radio-stations/module/Radiozora.php <?php class Radiozora{ public function getModuleData(){ return $this->retrieveData(); } private function retrieveData() { $data = $this->retrieveApi(); $name = $data['name']; $image = $data['album_artwork_image']; return array($name, $image); } function retrieveApi() { $url = "https://trance.airtime.pro/api/live-info"; $ch = curl_init(); // Disable SSL verification curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url); // Execute $result = curl_exec($ch); $radiozora = json_decode($result, true); return $radiozora['current']; } } <file_sep>/pages/radio-stations/module/PirateStation.php <?php class PirateStation{ public function getModuleData(){ return $this->retrieveData(); } private function retrieveData() { $data = $this->retrieveApi(); $name = $data['Pirate Station']; return $name; } function retrieveApi() { $url = "https://dnbfm.ru/stations.json?_=1509723057598"; $ch = curl_init(); // Disable SSL verification curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url); // Execute $result = curl_exec($ch); $pirateStation = json_decode($result, true); return $pirateStation; } } <file_sep>/pages/radio-stations/power85/power85.php <?php require_once '../module/Power85.php'; $module = new Power85(); $data = $module->getModuleData(); ?> <style> .wrapper { position: relative; width: 100%; height: 100%; } .bg { position: absolute; width: 100%; height: 100%; border: 2px solid #808080; /*border-radius: 5px;*/ z-index: 1; } </style> <div class="wrapper"> <?php echo $data; ?> <img onclick="playPower85()" class="bg" src="../../../media/images/power85.png"> <audio id="power85" autoplay="autoplay" src="http://listen1.mixlr.com/4adb41dcd4574330c802ba0c329430e1"></audio> </div> <script type="text/javascript"> var audio = document.getElementById("power85"); console.log(audio.volume); function playPower85(){ if (audio.paused) { audio.play(); } else { audio.pause(); } } </script><file_sep>/config.php <?php /** * User: thomas */ $servername = "localhost"; $username = "thomas"; $password = "<PASSWORD>"; $db = "thomas_windows98"; $conn = new mysqli($servername, $username, $password, $db);<file_sep>/pages/radio-stations/pirateStation.php <?php // require_once 'pirateStationClass.php'; // $module = new pirateStationClass(); // $data = $module->getModuleData(); // echo json_encode($data) //?> <style> .wrapper { position: relative; width: 100%; height: 100%; } .bg { position: absolute; width: 100%; height: 100%; border: 2px solid #808080; /*border-radius: 5px;*/ z-index: 1; } </style> <div style="border-bottom: 2px solid #808080; height: 45px; background-color: #afafaf; text-align: center"> <button onclick="setHalfVolume();" name="sethalf">Set Volume to half</button> <button onclick="setFullVolume();" name="setfull">Set Volume to full</button><br/> <button onclick="playPirateStation();" name="turn">pause</button> </div><br/> <div class="wrapper"> <img onclick="playPirateStation()" class="bg" src="../../media/images/piratestation.jpg"> <audio id="piratestation" autoplay="autoplay" src="http://air2.radiorecord.ru:805/ps_320?1509444610"></audio> </div> <script type="text/javascript"> let audio = document.getElementById("piratestation"); audio.volume = 0.2; audio.addEventListener('ended', function(){ audio.play(); }); function playPirateStation(){ if (audio.paused) { audio.play(); } else { audio.pause(); } } function setHalfVolume(){ audio.volume = 0.2; } function setFullVolume(){ audio.volume = 1; } </script><file_sep>/TODO.txt 1. Folders -> Style the folders so that it looks like a real windows 95 folder. 2. Radio Stations -> Get more radio stations on the website. (OPTIONAL) 3. Login system -> Make a login system with certain permissions. 4. Saved file -> If you open the saved file on the deskop it'll show the correct values (IF THIS STAYS IN). 5. Grid -> Make a grid for the draggable items on the desktop. <file_sep>/pages/notepad.php <?php ini_set('display_errors', 1); error_reporting(E_ALL); include '../config.php'; $nameSaved = ''; $valueSaved = ''; // Get name and open the file with that name if(isset($_POST['open'])) { $nameSaved = $_POST['nameSaved']; } $get = "SELECT * FROM notepad WHERE name='$nameSaved'"; $result = $conn->query($get); $row = $result->fetch_assoc(); $valueSaved = $row['value']; if (isset($_POST['submit'])){ if (strpos($_POST['name'], '.txt') == true){ $name = $_POST['name']; } else { $name = $_POST['name'] . ".txt"; } $value = $_POST['value']; $update = "SELECT * FROM notepad WHERE `name` = '$name'"; $result = $conn->query($update); if ($result->num_rows > 0){ $query = "UPDATE notepad SET value='$value' WHERE name='$name'"; } else { $query = "INSERT INTO notepad (name, value) VALUES ('$name', '$value')"; } $conn->query($query); } ?> <body style="margin: 0;"> <div style="border-bottom: 2px solid #808080; height: 25px; background-color: #afafaf;"> <form id="open" action="#" method="post"> <label for="nameSaved"><select name="nameSaved" id="nameSaved"> <option value="">Select a file</option> <?php $sql = "SELECT `name` FROM notepad"; $result = $conn->query($sql); while ($rowSelect = $result->fetch_assoc()){ echo "<option value='" . $rowSelect['name'] . "'>" . $rowSelect['name'] . "</option>"; } ?> </select> <button name="open" type="submit">Open</button> </form> </div> <br/> <div style="width: 100%; height: 100%"> <form id="form" name="notepad" action="#" method="post" style="font-family: Arial"> File name: <br/> <input placeholder="" id="fileName" name="name" type="text" value="<?php echo $nameSaved; ?>"><br/> <textarea placeholder="" name="value" maxlength="1000000" style="font-family: Arial; font-size: 12pt; width: 100%; height: 100vw; margin-top: 5px;"><?php echo $valueSaved; ?></textarea> <button onclick="saveFile();" name="submit" type="submit">Save</button> </form> </div> <script> function saveFile(){ var targetId = document.getElementById('fileName').value + ".txt"; parent.savedFile(targetId); } </script> </body><file_sep>/pages/radio-stations/module/Power85.php <?php class Power85{ public function getModuleData(){ return $this->retrieveData(); } private function retrieveData() { $data = $this->retrieveApi(); $audioSource = $data['broadcasts']{0}['streams']['progressive']['url']; return $audioSource; } function retrieveApi() { $url = "https://api.mixlr.com/users/159490?source=embed"; $ch = curl_init(); // Disable SSL verification curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url); // Execute $result = curl_exec($ch); $power85 = json_decode($result, true); return $power85; } } <file_sep>/pages/radio-stations/module/Psychedelik.php <?php class Psychedelik{ public function getModuleData(){ return $this->retrieveData(); } private function retrieveData() { $data = $this->retrieveApi(); $row = $data[0]; $name = $row['songtitle']; return array($name); } function retrieveApi() { $url = "http://www.psychedelik.com/stream-stats.php?port=8000"; $ch = curl_init(); // Disable SSL verification curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url); // Execute $result = curl_exec($ch); $psychedelik = json_decode($result, true); return $psychedelik['streams']; } } <file_sep>/pages/radio-stations/power85/index.php <?php require_once '../module/Power85.php'; $module = new Power85(); $data = $module->getModuleData(); ?> <!DOCTYPE html> <!-- This site was created in Webflow. http://www.webflow.com --> <!-- Last Published: Sat May 06 2017 15:45:02 GMT+0000 (UTC) --> <html data-wf-page="590a4d20c29c7411b413436e" data-wf-site="590a4d20c29c7411b413436d"> <head> <meta charset="utf-8"> <title>Computer illustration and animation built in Webflow</title> <meta content="I recreated a computer illustration by <NAME> in Webflow with HTML and CSS visually, without writing any code." name="description"> <meta content="Computer illustration and animation built in Webflow" property="og:title"> <meta content="I recreated a computer illustration by <NAME> in Webflow with HTML and CSS visually, without writing any code." property="og:description"> <meta content="https://daks2k3a4ib2z.cloudfront.net/590a4d20c29c7411b413436d/590a734275863b10c5040d35_computer-screen-animation-1200x600.gif" property="og:image"> <meta content="summary" name="twitter:card"> <meta content="width=device-width, initial-scale=1" name="viewport"> <meta content="Webflow" name="generator"> <link href="css/normalize.css" rel="stylesheet" type="text/css"> <link href="css/webflow.css" rel="stylesheet" type="text/css"> <link href="css/computer-illustration.webflow.css" rel="stylesheet" type="text/css"> <script src="https://ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js"></script> <script type="text/javascript"> WebFont.load({ google: { families: [ "Open Sans:300,300italic,400,400italic,600,600italic,700,700italic,800,800italic" ] } }); </script> <script src="js/modernizr.js" type="text/javascript"></script> <link href="../../media/images/favicon.png" rel="shortcut icon" type="image/x-icon"> <link href="https://daks2k3a4ib2z.cloudfront.net/img/webclip.png" rel="apple-touch-icon"> </head> <body onclick="playPower85()"> <div id="div"> <audio id="power85" autoplay="autoplay" src="<?php echo $data; ?>"></audio> </div> <div class="dark fs"> <div class="hold-illustration w-preserve-3d"> <div class="cs__parent w-preserve-3d"> <div class="cs__hero-section"> <div class="cs__top-bar w-clearfix"> <div class="green-button" data-ix="float-in-top-1"></div> <div class="green-button small" data-ix="float-in-top-4"></div> <div class="green-button small" data-ix="float-in-top-3"></div> <div class="green-button small" data-ix="float-in-top-2"></div> </div> <div class="cs__hero-text w-clearfix w-preserve-3d"> <div class="hold-letter" data-ix="show-letter-1"> <div>P</div> </div> <div class="hold-letter" data-ix="show-letter-2"> <div>O</div> </div> <div class="hold-letter" data-ix="show-letter-3"> <div>W</div> </div> <div class="hold-letter" data-ix="show-letter-4"> <div>E</div> </div> <div class="hold-letter" data-ix="show-letter-5"> <div>R</div> </div> <div class="hold-letter" data-ix="show-letter-7"> <div>8</div> </div> <div class="hold-letter" data-ix="show-letter-8"> <div>5</div> </div> <div class="cs__cursor-text-icon" data-ix="cursor-flash"></div> </div> <div class="cs__left-side" data-ix="float-out-from-left"></div> <div class="cs__right-block w-preserve-3d" data-ix="float-out-from-right"></div> </div> <div class="cs__content w-clearfix"> <div class="text-like-box"> <div class="overflow-hide w-clearfix"> <div class="text" data-ix="arrow-load">A</div> <div class="straight-line" data-ix="arrow-load"></div> <div class="straight-line-full" data-ix="loading-line-animation"></div> <div class="straight-line-full" data-ix="loading-line-animation-2"></div> <div class="straight-line-full" data-ix="loading-line-animation-4-shortened"></div> <div class="straight-line-full" data-ix="loading-line-animation-5"></div> <div class="shortened straight-line-full" data-ix="loading-line-animation-6shorted"></div> </div> </div> <div class="cs__hold-image"> <div class="mountain-photo__real-deal w-preserve-3d" data-ix="arrow-load"> <div class="mountain" data-ix="mountain-slide-in-from-left"></div> <div class="_2 mountain" data-ix="mountain-slide-in"></div> </div> </div> <div class="cs__bottom-block"></div> </div> </div> <div class="keyboard-parent w-clearfix"> <div class="keyboard__button" data-ix="type-letter-7"></div> <div class="_2 keyboard__button" data-ix="type-letter-2"></div> <div class="_3 keyboard__button" data-ix="type-letter-9"></div> <div class="_4 keyboard__button" data-ix="type-letter-8"></div> <div class="_5 keyboard__button" data-ix="type-letter-5"></div> <div class="_7 keyboard__button" data-ix="type-letter-3"></div> <div class="_8 keyboard__button"></div> <div class="_9 keyboard__button"></div> <div class="_10 keyboard__button"></div> <div class="_11 keyboard__button" data-ix="type-letter-10"></div> <div class="_12 keyboard__button"></div> <div class="_13 keyboard__button" data-ix="type-letter-1"></div> <div class="_14 keyboard__button"></div> <div class="_15 keyboard__button"></div> <div class="_16 keyboard__button"></div> <div class="_17 keyboard__button"></div> <div class="keyboard__button space-bar" data-ix="type-letter-6"></div> <div class="_18 keyboard__button"></div> <div class="_18 keyboard__button"></div> </div> </div> </div> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js'></script> <script src="js/webflow.js" type="text/javascript"></script> <!-- [if lte IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/placeholders/3.0.2/placeholders.min.js"></script><![endif] --> <script type="text/javascript"> var audio = document.getElementById("power85"); var url = "index.php"; audio.onended = function () { $('#div').load(url + '#power85'); }; function playPower85(){ if (audio.paused) { audio.play(); } else { audio.pause(); } } </script> </body> </html>
c2caab887c967db9c2d73a3276d62a5c50fd91b0
[ "Text", "PHP" ]
12
PHP
Detravoir/Detradio
43a50769908a9a505fa42765c372f960637e3f3d
8754e658c66895fda90020081a3ee695959e643b
refs/heads/master
<file_sep>#include <cmath> #include <string> #include <time.h> #include <iostream> using namespace std; class Car { //Основной класс private: string brand; //св-тво с брендом машины int coast; //св-тво с ценой машины //Car() { // Конструктор с параметрами по умолчанию // brand = "none"; // coast = 0; //}; //~Car() { // Диструктор с параметрами по умолчанию // cout<<"Bye!"; //}; protected: bool TryTo() // метод для попытки завести мотор { int t = rand() %5+1; //генерирует случайное число от 1 до 6 if (t % 2 == 0) //проверка числа на четность { return true;// если четное - машина завелась } else { return false; //нечетное - не завелась } } public: virtual void Transmission() // метод, выводящий информацию о коробке передач { cout<<"Механическая коробка передач!"<<endl; } void StartEngine() // метод завести мотор { if (TryTo()) //Вызываем метод попытки завестись { cout << "Sounds of motor"<<endl; //Если метод TryTo() вернул значение True - заводимся } else cout << "Something wrong, try again"<<endl; // или нет } // далее идут методы Get и Set для ввода получения данных, которые находятся в поле private void SetBrand(string brand) // ввести бренд { this->brand = brand; //присваеваем название бренда для объекта класса } void GetBrand() // получить бренд { cout <<"Brand: " << brand << endl; } void SetCoast(int coast) // ввести стоимость { this->coast = coast; } void GetCoast() // получить стоимость { cout <<"Coast: " << coast << endl; } }; class SportCar : public Car { // класс-наследник (Дочерний) класса Car private: string model; string type; public: void Transmission() override //Переоприделенный метод коробки передач для спорткаров { cout<<"Коробка-автомат!"<<endl; } void SetModel(string model) // ввести модель { this->model = model; } void GetModel() // получить модель { cout <<"Model: "<< model << endl; } void SetType(string type) // ввести тип { this->type = type; } void GetType(){ // получить тип cout <<"Type: " << type << endl; } }; int main() { srand(time(NULL)); // Функция для создания раномных чисел string brand = "Mersedess-Benz"; // переменные для передачи в класс int coast = 12000; SportCar car1; //создаем объект класса SportCar car1.SetBrand(brand); // передаем аргументы через метод(который наследуем из класса Car) car1.SetCoast(coast); car1.GetBrand(); // вызываем метод для просмотра информации по бренду car1.GetCoast(); string model = "CLS 550"; //еще одни переменные для передачи в класс string type = "Coupe"; car1.SetModel(model); // передаем аргументы через метод car1.SetType(type); car1.GetModel(); // вызываем метод для просмотра информации по Модели car1.GetType(); link_try: // ссылка для оператора goto cout << "Want to try start the engine? \n 1.Yes \n 2.No" << endl; int choice; // переменная для принятия данных о выборе пользователя cin >> choice; // Ввод данных switch (choice) // свич для обработки введенных данных { case 1: car1.StartEngine(); //пользователь согласился завести машину, вызываем метод "завести мотор" break; case 2: cout << "Bye!" << endl; //пользователь решил закончить, прощаемся break; default: cout << "What?" << endl; // пользователь ввел что-то не то goto link_try; // через оператора goto возвращаем его к моменту выбора действия break; } }
bc8e6c50851303892832d0348089b56ac9dc192d
[ "C++" ]
1
C++
Agetiv/I-and-E
1c1d9c5a6e31db26bfd83c8d3f841d091fe5c21b
17fe8571d8a2e8a7a5e60343606003603a186f82
refs/heads/master
<file_sep>var webpack = require("webpack"); module.exports = { devtool: 'sourcemap', output: { filename: 'ionic-modal-select.min.js' }, plugins : [ new webpack.optimize.UglifyJsPlugin({ minimize: true }) ], module: { loaders: [ { test: /\.js$/, exclude: [/app\/lib/, /node_modules/], loader: 'ng-annotate!babel' }, ], } };
7ba1212d3c22a6d8dd9da2f3dc3a8288ba046e95
[ "JavaScript" ]
1
JavaScript
vaishalipepr/ionic-modal-select
75a8ed1dcf16cbc7a00b30c1f692de0c8182906f
2a6c3c7b72421d0e3d6ae6c464b7603d7dd8fec0
refs/heads/master
<repo_name>calvinrahmat/Valley-eCommerce-prototype<file_sep>/src/main/java/com/piper/valley/ValleyApplication.java package com.piper.valley; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @EnableJpaRepositories(basePackages = "com.piper.valley.models.repository") @EnableJpaAuditing public class ValleyApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(ValleyApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(ValleyApplication.class); } }
25fc6dfc249cb11623b4642aae0aaca330a56288
[ "Java" ]
1
Java
calvinrahmat/Valley-eCommerce-prototype
007cd0518e8556b15983cc2d9618011f6afcaddc
f30537f0e39bc117dd70d899c87c77dd9952f264
refs/heads/master
<file_sep>module.exports = { /* Your site config here */ plugins: [ "gatsby-plugin-sass", "gatsby-plugin-image", "gatsby-plugin-sharp", "gatsby-transformer-sharp", "gatsby-plugin-react-helmet", { resolve: "gatsby-source-filesystem", options: { name: "images", path: `${__dirname}/src/images`, }, }, { resolve: "gatsby-plugin-react-svg", }, ], siteMetadata: { title: "Fiber", description: "Create your portfolio in minutes with Fiber's premade templates.", copyright: "This website is copyright 2021 <NAME>", contact: "<EMAIL>", url: "https://pensive-dijkstra-b20c0b.netlify.app", }, }; <file_sep>import React from "react"; import { Helmet } from "react-helmet"; import Layout from "../components/Layout"; import "../styles/normalize.css"; import "../styles/contact.scss"; const ContactFormPage = () => { return ( <Layout> <Helmet htmlAttributes={{ lang: "en", }} > <meta charSet="utf-8" /> <title>Contact Us | Fiber</title> <meta name="description" content="Get in touch with the team at Fiber to solve all your questions." /> <link rel="canonical" href="https://pensive-dijkstra-b20c0b.netlify.app/contact" /> </Helmet> <div className="content-container"> <h1>Contact Us</h1> <form name="Contact Form" method="POST" onSubmit="submit" netlify-honeypot="bot-field" data-netlify="true" action="/success" > <input type="hidden" name="form-name" value="Contact Form" /> <input type="hidden" name="subject" value="Fiber has a new contact message." /> <div className="form-section"> <label htmlFor="fullName">Full Name</label> <input type="text" name="fullName" id="fullName" placeholder="<NAME>" required={true} /> </div> <div className="form-section"> <label htmlFor="email">Your Email:</label> <input type="email" name="email" id="email" placeholder="<EMAIL>" required={true} /> </div> <div className="form-section"> <label htmlFor="message">Message:</label> <textarea name="message" id="message" placeholder="Type your message here..." required={true} /> </div> <button type="submit">Send</button> </form> </div> </Layout> ); }; export default ContactFormPage; <file_sep>import React from "react"; import { Link } from "gatsby"; import { Helmet } from "react-helmet"; import Layout from "../components/Layout"; import "../styles/contact.scss"; const SuccessPage = () => { return ( <Layout> <Helmet htmlAttributes={{ lang: "en", }} > <meta charSet="utf-8" /> <title>Thank you for contacting us | Fiber</title> <meta name="description" content="Thank you for submitting your contact details" /> <link rel="canonical" href="https://pensive-dijkstra-b20c0b.netlify.app/success" /> </Helmet> <div className="content-container"> <h1>Thank You!</h1> <p> Your form has been submitted and one of the team will be in touch soon. </p> <Link to="/" className="main-btn"> Return to home page </Link> </div> </Layout> ); }; export default SuccessPage; <file_sep>import React, { useState } from "react"; import { Link } from "gatsby"; import Hamburger from "../images/svg/hamburger-menu.svg"; import Close from "../images/svg/x.svg"; const MobileMenu = () => { const [showMenu, SetShowMenu] = useState(false); let menu; let menuBg; if (showMenu) { menu = ( <div className="mobile-menu"> <div className="mobile-menu-head"> <h2>Fiber</h2> <Close onClick={() => SetShowMenu(false)} /> </div> <ul className="mobile-ul"> <li> <Link to="/#" className="mobile-li" onClick={() => SetShowMenu(false)} > Community </Link> </li> <li> <Link to="/#" className="mobile-li" onClick={() => SetShowMenu(false)} > Pricing </Link> </li> <li> <Link to="/#" className="mobile-li" onClick={() => SetShowMenu(false)} > Features </Link> </li> </ul> </div> ); menuBg = ( <div className="mobile-menu-bg" onClick={() => SetShowMenu(false)}></div> ); } return ( <div> <Hamburger className="hamburger" onClick={() => SetShowMenu(!showMenu)} /> {menuBg} {menu} </div> ); }; export default MobileMenu; // Use state to initial it to false - this will determine if the visible class is applied // When the hamburger is clicked, then we run a function to update state in this component <file_sep>import React from "react"; import { Helmet } from "react-helmet"; import Diversify from "../components/Diversify"; import Layout from "../components/Layout"; import MainHeader from "../components/MainHeader"; import WhyFiber from "../components/WhyFiber"; import Portfolios from "../components/Portfolios"; export default function Home() { return ( <Layout> <Helmet htmlAttributes={{ lang: "en", }} > <meta charSet="utf-8" /> <title>Build Your Dream Portfolio | Fiber</title> <meta name="description" content="Create your portfolio in minutes with Fiber's premade templates." /> <link rel="canonical" href="https://pensive-dijkstra-b20c0b.netlify.app/" /> </Helmet> <MainHeader /> <WhyFiber /> <Diversify /> <Portfolios /> </Layout> ); } <file_sep>import React from "react"; import { Link } from "gatsby"; import { StaticImage } from "gatsby-plugin-image"; import Checkmark from "../images/svg/checkmark.svg"; import Star from "../images/svg/star.svg"; const MainHeader = () => { return ( <header className="main-header"> <div className="content-container"> <div className="header-grid"> <StaticImage src="../images/hero-Illustration.png" alt="Person using multimedia while wearing VR Glasses" className="header-img" placeholder="blurred" /> <div className="header-grid-content"> <div className="rating"> <Star className="star" /> <Star className="star" /> <Star className="star" /> <Star className="star" /> <Star className="star" /> <p>Rated 4.8/5 (243 reviews)</p> </div> <h1>Create your portfolio in minutes.</h1> <p> With Fiber, you can setup your own personal portfolio in minutes with dozens of premade, beautiful templates. </p> <div className="header-btns"> <Link to="/sign-up" className="main-btn"> Start Free Trial </Link> <Link to="/#portfolios" className="secondary-btn"> View Examples </Link> </div> <div className="checkmark-section"> <div className="checkmark-div"> <Checkmark className="checkmark" /> <p>No Credit Card Required</p> </div> <div className="checkmark-div"> <Checkmark className="checkmark" /> <p>10 Free Templates</p> </div> </div> </div> </div> </div> </header> ); }; export default MainHeader; <file_sep>import React, { useState } from "react"; import { Helmet } from "react-helmet"; import { Link } from "gatsby"; import { StaticImage } from "gatsby-plugin-image"; import HidePassword from "../images/svg/hide-password.svg"; import "../styles/normalize.css"; import "../styles/sign-up.scss"; const SignUp = () => { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [isRevealPwd, setIsRevealPwd] = useState(false); const [isChecked, setIsChecked] = useState(false); const handleSubmit = (e) => { e.preventDefault(); setName(""); setEmail(""); setPassword(""); setIsChecked(false); }; return ( <div className="sign-up-layout"> <Helmet htmlAttributes={{ lang: "en", }} > <meta charSet="utf-8" /> <title>Sign-up to Fiber | Fiber</title> <meta name="description" content="Sign-up to use the world's best portfolio builder." /> <link rel="canonical" href="https://pensive-dijkstra-b20c0b.netlify.app/sign-up" /> </Helmet> <div className="grid-left"> <h1> <Link to="/" className="link"> Fiber </Link> </h1> <h2>Create your Fiber account</h2> <form onSubmit={handleSubmit}> <label> Your Name <input type="text" value={name} placeholder="<NAME>" required={true} onChange={(e) => setName(e.target.value)} /> </label> <label> E-mail <input type="text" value={email} placeholder="<EMAIL>" required={true} onChange={(e) => setEmail(e.target.value)} /> </label> <label className="password"> Password <input type={isRevealPwd ? "text" : "password"} value={password} placeholder="At least 8 characters" onChange={(e) => setPassword(e.target.value)} minLength="8" required={true} className="password-input" /> <HidePassword className="password-svg" title={isRevealPwd ? "Hide password" : "Show password"} onClick={() => setIsRevealPwd((prevState) => !prevState)} /> </label> <label> <input type="checkbox" name="agree" checked={isChecked} required={true} onChange={() => setIsChecked((prevState) => !prevState)} /> <p className="terms"> By creating an account on Fiber, you agree to the{" "} <strong>Terms & Conditions.</strong> </p> </label> <button type="submit">Create Fiber Account</button> </form> <p className="sign-up-footer"> Already have an account?{" "} <Link to="#" className="emph-footer"> Sign in </Link> </p> </div> <div className="grid-right"> <StaticImage src="../images/sign-up-image.png" alt="Example of porfolio template" className="grid-right-img" placeholder="blurred" /> <h3>Unparalleled Templates</h3> <p> Crafted by a team of professional deisgners, our templates are unparalleled in the market. </p> <div className="circles"> <div className="circle-one"></div> <div className="circle-two"></div> <div className="circle-three"></div> <div className="circle-four"></div> </div> </div> </div> ); }; export default SignUp; <file_sep># Fiber Landing Page This is a solution to the [Fiber Landing Page challenge on Codewell](https://www.codewell.cc/challenges/608a7e639691700015db16d1). Codewell challenges help improve your HTML and CSS skills by practicing on real design templates. ## Table of contents - [Overview](#overview) - [The challenge](#the-challenge) - [Screenshot](#screenshot) - [Links](#links) - [My process](#my-process) - [Built with](#built-with) - [What I learned](#what-i-learned) - [Continued development](#continued-development) - [Local Development](#local-development) - [Author](#author) - [Acknowledgments](#acknowledgments) ## Overview ### The challenge Take the design and build a landing page for an online portfolio generator. Great to practice flex/grid layouts, absolute positioning and sliders. ### Screenshot ![](./Screenshot_README.png) ### Links - Github Repo: [Add solution URL here](https://github.com/IsaacArnold/fiber-landing-page-two) - Live Site: [Add live site URL here](https://fiberlandingpage123.netlify.app/) ## My process ### Built with - GatsbyJS - SCSS - Flexbox - CSS Grid - Mobile-first workflow - Netlify to host contact form ### What I learned This challenge was a great way to cement my Gatsby knowledge. Using pages to create the 'Sign Up' and 'Contact' pages, I was able to enable the user to easily navigate between pages. The biggest challenge in this project was getting the purple section to closely match the mockup files. In the end I settled on an empty div and used a background-image to insert the image. One particular aspect of this project I am proud of was my ability to quickly set up a Netlify contact form. This was my first time trying to implement a form and thanks to Netlify's easy integration with Gatsby, this couldn't have been easier. The form also features a honeypot field to prevent spam. Please see the form code below: ```jsx <form name="Contact Form" method="POST" onSubmit="submit" netlify-honeypot="bot-field" data-netlify="true" action="/success" > <input type="hidden" name="form-name" value="Contact Form" /> <input type="hidden" name="subject" value="Fiber has a new contact message." /> <div className="form-section"> <label htmlFor="fullName">Full Name</label> <input type="text" name="fullName" id="fullName" placeholder="<NAME>" required="{true}" /> </div> <div className="form-section"> <label htmlFor="email">Your Email:</label> <input type="email" name="email" id="email" placeholder="<EMAIL>" required="{true}" /> </div> <div className="form-section"> <label htmlFor="message">Message:</label> <textarea name="message" id="message" placeholder="Type your message here..." required="{true}" /> </div> <button type="submit">Send</button> </form> ``` ### Continued development I'd like to continue developing my Gatsby skills. Particularly in the areas of: - Layout - SEO implementation ## Local Development If you'd like to download or clone this project to develop locally on your own machine, just follow these steps: 1. Download or clone this repo 2. Ensure Gatsby is installed on your machine. You can find out more [here](https://www.gatsbyjs.com/docs/quick-start/) 3. In your terminal, navigate to the project directory 4. Once in the project directory, simply run `gatsby develop` 5. Open up [http://localhost:8000](http://localhost:8000) ## Author - Website - [<NAME>](https://isaacarnold.dev/) - Instagram - [@isaac.codes](https://www.instagram.com/isaac.codes/) - Twitter - [@isaac_codes](https://twitter.com/isaac_codes) ## Acknowledgments I'd particularly like to acknowledge Codewell for the high quality design mockups and collateral provided to complete this challenge. Go check them out [here](https://www.codewell.cc/). <file_sep>import React from "react"; import { Link } from "gatsby"; import { StaticImage } from "gatsby-plugin-image"; import "../styles/global.scss"; const NotFound = () => { return ( <div className="notFound"> <h1>404</h1> <p>Sorry, this page doesn't exist</p> <StaticImage src="../images/hero-Illustration.png" alt="Person wearing VR Glasses while looking at multimedia resources" className="notFound-img" /> <Link to="/" className="notFound-btn"> Return to the homepage </Link> </div> ); }; export default NotFound; <file_sep>import React from "react"; import { Link } from "gatsby"; import { StaticImage } from "gatsby-plugin-image"; const Portfolios = () => { return ( <section className="portfolios" id="portfolios"> <div className="content-container"> <div className="port-card"> <StaticImage src="../images/svg/user-avatar.svg" atl="Profile image of <NAME>" className="user-img" placeholder="blurred" /> <div className="user-info"> <p className="name"><NAME></p> <p className="revenue">$100k in revenue</p> </div> <p className="user-content"> Setting up my portfolio with Fiber too no more than 10 minutes. Since then, my portfolio has attracted a lot of clients and made me more than $100k. </p> <Link to="/#" className="user-btn"> View Sarah's Portfolio </Link> </div> <div className="port-card"> <StaticImage src="../images/svg/user-avatar-2.svg" atl="Profile image of <NAME>" className="user-img" placeholder="blurred" /> <div className="user-info"> <p className="name"><NAME></p> <p className="revenue">$20k in revenue</p> </div> <p className="user-content"> I have been getting A LOT of leads ever since I used Fiber's premade templates, now I just need to work on my case studies and I'll be ready to go! </p> <Link to="/#" className="user-btn"> View Mathew's Portfolio </Link> </div> <div className="port-card"> <StaticImage src="../images/svg/user-avatar-32.svg" atl="Profile image of <NAME>" className="user-img" placeholder="blurred" /> <div className="user-info"> <p className="name"><NAME></p> <p className="revenue">$30k in revenue</p> </div> <p className="user-content"> I only just started freelancing this year and I have already made more than I ever made in my full-time job. The templates are just so amazing. </p> <Link to="/#" className="user-btn"> View Janice's Portfolio </Link> </div> </div> </section> ); }; export default Portfolios;
8c893e7c0917fba994403f9058381dce72f4062c
[ "JavaScript", "Markdown" ]
10
JavaScript
IsaacArnold/fiber-landing-page-two
000e3c525b0ad7a2e3244888ed3c79eebbb7b099
a73453958498445dbfeee36c0bdf41d1ab52366c
refs/heads/master
<file_sep>package com.alian.testingmod.common.util; import com.alian.testingmod.common.init.TMBlocks; import com.alian.testingmod.common.init.TMItems; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; @Mod.EventBusSubscriber public class RegistryHandler { /** * Fires first to registerItems() method * @param event */ @SubscribeEvent public static void registerBlocks(RegistryEvent.Register<Block> event) { //Register all blocks event.getRegistry().registerAll(TMBlocks.Blocks.toArray(new Block[0]/*Needed to tell the method to use the Block class*/)); } /** * Fires seconds to registerBlocks() method * @param event */ @SubscribeEvent public static void registerItems(RegistryEvent.Register<Item> event) { //Register all items event.getRegistry().registerAll(TMItems.Items.toArray(new Item[0]/*Needed to tell the method to use the Item class*/)); } } <file_sep>package com.alian.testingmod; import com.alian.testingmod.common.command.CommandCheckUpdate; import com.alian.testingmod.common.command.CommandLightingStrike; import com.alian.testingmod.common.init.TMBlocks; import com.alian.testingmod.common.init.TMItems; import com.alian.testingmod.common.util.RegistryHandler; import net.minecraft.init.Blocks; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import org.apache.logging.log4j.Logger; @Mod(modid = TestingMod.MODID, name = TestingMod.NAME, version = TestingMod.VERSION, acceptedMinecraftVersions = TestingMod.ACCEPTED_MINECRAFT_VERSIONS/*, updateJSON = TestingMod.UPDATE_JSON*/) public class TestingMod { public static final String MODID = "testingmod"; public static final String NAME = "Testing Mod"; public static final String VERSION = "1.12.2-0.0.0.1"; public static final String ACCEPTED_MINECRAFT_VERSIONS = "[1.12.2]"; public static final String GUI_FACTORY = "toSet"; public static final String UPDATE_JSON = "https://raw.githubusercontent.com/Alian7911/TestingMod/master/changelog.json"; public static final String CERTIFICATE_FINGERPRINT = "notSet"; private static Logger logger; public static TestingMod instance; @EventHandler public void preInit(FMLPreInitializationEvent event) { logger = event.getModLog(); //initialization TMBlocks.init(); TMItems.init(); } @EventHandler public void init(FMLInitializationEvent event) { // some example code logger.info("DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName()); ForgeVersion.CheckResult checkResult = ForgeVersion.getResult(Loader.instance().activeModContainer()); logger.info(checkResult.status.toString()); //MinecraftForge.EVENT_BUS.register(new RegistryHandler()); } @EventHandler public void postInit(FMLPostInitializationEvent event) { logger.debug("post-initialization..."); } @EventHandler public static void serverInit(FMLServerStartingEvent event) { event.registerServerCommand(new CommandCheckUpdate()); event.registerServerCommand(new CommandLightingStrike()); } } <file_sep>package com.alian.testingmod.client; import com.alian.testingmod.api.proxy.IProxy; public class ClientProxy implements IProxy { } <file_sep>package com.alian.testingmod.common.util; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent; @Mod.EventBusSubscriber public class EventHandler { @SubscribeEvent public static void PlayerJoinEvent(PlayerEvent.PlayerLoggedInEvent event) { event.player.sendMessage(new TextComponentString(ForgeVersion.getResult(Loader.instance().activeModContainer()) .status.toString())); } } <file_sep># TestingMod Testing mod.
f10850be5945b96817c71d95a85046a9d96a5652
[ "Markdown", "Java" ]
5
Java
Alian7911/TestingMod
fa6e7c0b2535a613c4b608444a1758e4f73eb51c
d0188b0d197b8791c1eb0b9dd65dde9dd1514d2b
refs/heads/master
<repo_name>dhakle/nyc-pigeon-organizer-web-062617<file_sep>/nyc_pigeon_organizer.rb require "pry" def nyc_pigeon_organizer(data) # write your code here! pigeon_list = {} data.each do |key, val| val.each do |k, v| v.each do |bird| if pigeon_list[bird] if pigeon_list[bird].has_key?(key) pigeon_list[bird][key] = pigeon_list[bird][key] << k.to_s else pigeon_list[bird][key] = [k.to_s] end elsif !pigeon_list[bird] pigeon_list[bird] = {key => [k.to_s]} end end end # binding.pry end pigeon_list end
d3c72061857338e807bc325582127c598552b5de
[ "Ruby" ]
1
Ruby
dhakle/nyc-pigeon-organizer-web-062617
3d8bc82d610e5ef61eed3be0344c51eb7ed8589f
1442d3864f79650095157f9ce038b9093276bfb2
refs/heads/master
<repo_name>cr-gonzalez/browser-extension<file_sep>/README.md # browser_extension a simple browser extension/addon that adds a magenta border to all websites. <file_sep>/borderify.js document.body.style.border = "10px solid magenta";
9793ec190aa5010562f705e8be859aaf09c39ca5
[ "Markdown", "JavaScript" ]
2
Markdown
cr-gonzalez/browser-extension
2760508882270f261ccd56635eb81c167ff3158f
20c5a48d644af316aca76cbb4eff0fe3303bac8d
refs/heads/main
<file_sep>use clap::{App, Arg, SubCommand}; use mkplaylist::{error::Error, operation::Operation, operation::PlayList, run}; use std::path::Path; fn main() -> Result<(), Error> { let matches = App::new("mkplaylist") .subcommand( SubCommand::with_name("index").arg( Arg::with_name("path") .short("p") .long("path") .required(true) .takes_value(true), ), ) .subcommand( SubCommand::with_name("playlist") .arg( Arg::with_name("filter") .short("f") .long("filter") .required(false) .takes_value(true), ) .arg( Arg::with_name("shuffle") .short("s") .long("shuffle") .required(false) .takes_value(false), ), ) .subcommand( SubCommand::with_name("rate") .arg( Arg::with_name("music_id") .short("m") .long("music_id") .required(true) .takes_value(true), ) .arg( Arg::with_name("rating") .short("r") .long("rating") .required(true) .takes_value(true), ), ) .get_matches(); let operation = if let Some(matches) = matches.subcommand_matches("index") { let path = Path::new(matches.value_of("path").unwrap()).to_path_buf(); Operation::Index(path) } else if let Some(matches) = matches.subcommand_matches("playlist") { let playlist = if let Some(filter) = matches.value_of("filter") { if matches.is_present("shuffle") { PlayList::ShuffledFiltered(filter) } else { PlayList::Filtered(filter) } } else if matches.is_present("shuffle") { PlayList::Shuffled } else { PlayList::Standard }; Operation::Create(playlist) } else if let Some(matches) = matches.subcommand_matches("rate") { let music_id: i64 = matches.value_of("music_id").unwrap().parse().unwrap(); let rating: i64 = matches.value_of("rating").unwrap().parse().unwrap(); Operation::Rate(music_id, rating) } else { return Err(Error::Usage); }; run(operation) } <file_sep>use crate::rating::Rating; use std::path::PathBuf; #[derive(Debug)] pub enum PlayList<'a> { Standard, Filtered(&'a str), Rated(Rating), Shuffled, ShuffledFiltered(&'a str), } #[derive(Debug)] pub enum Operation<'a> { Create(PlayList<'a>), Index(PathBuf), Rate(i64, i64), } <file_sep>pub mod error; use error::Error; mod indexer; use indexer::index_directory; mod music; use music::Music; pub mod operation; use operation::{Operation, PlayList}; mod rating; mod store; use store::Store; use rand::{seq::SliceRandom, thread_rng}; use std::path::Path; pub fn display<'a, I>(iter: I) where I: Iterator<Item = &'a Music>, { for music in iter { println!("{}", music); } } pub fn run(operation: Operation) -> Result<(), Error> { let path = Path::new("test.sqlite"); let mut store = match path.is_file() { false => Store::create(path)?, true => Store::open(path)?, }; match operation { Operation::Create(playlist) => { let music = match playlist { PlayList::Standard | PlayList::Shuffled => store.select()?, PlayList::Filtered(filter) | PlayList::ShuffledFiltered(filter) => { store.select_filter(filter)? } PlayList::Rated(ref rating) => store.select_by_rating(rating.as_i64())?, }; if let Some(mut music) = music { match playlist { PlayList::Shuffled | PlayList::ShuffledFiltered(_) => { let mut rng = thread_rng(); music.shuffle(&mut rng); } _ => (), } display(music.iter()); } } Operation::Index(path) => { let music = index_directory(path)?; let _ = store.insert(music.into_iter()); } Operation::Rate(music_id, rating_value) => { let inserts = vec![(music_id, rating_value)]; let _ = store.insert_rating(inserts.into_iter())?; } } Ok(()) } <file_sep>use std::fmt; use std::path::PathBuf; pub enum Error { IndexerPathNotDir(PathBuf), IndexerIO(std::io::Error), IndexerSend(std::sync::mpsc::SendError<PathBuf>), IndexerThread, StoreOpenNoFile(PathBuf), StoreRusqlite(rusqlite::Error), Usage, } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let description = match self { Error::IndexerPathNotDir(pb) => { let maybe_utf8 = pb.to_str().unwrap_or("unknown path"); format!( "The provided directory ('{}') is not a directory, or is not readable.", maybe_utf8 ) } Error::IndexerIO(e) => format!("A IO Error '{}' occurred in the indexer thread.", e), Error::IndexerSend(e) => format!("A Send Error '{}' occured in the indexer thread.", e), Error::IndexerThread => "A panic occurred in the indexer thread.".to_string(), Error::StoreOpenNoFile(pb) => { let maybe_utf8 = pb.to_str().unwrap_or("unknown path"); format!( "The provided store path ('{}') is not a file, or is not readable.", maybe_utf8 ) } Error::StoreRusqlite(e) => format!("A rusqlite Error '{}') occured", e), Error::Usage => "Please use mkplaylist --help for example use.".to_string(), }; write!(f, "{}", description) } } impl From<std::io::Error> for Error { fn from(e: std::io::Error) -> Self { Error::IndexerIO(e) } } impl From<std::sync::mpsc::SendError<PathBuf>> for Error { fn from(e: std::sync::mpsc::SendError<PathBuf>) -> Self { Error::IndexerSend(e) } } impl From<rusqlite::Error> for Error { fn from(e: rusqlite::Error) -> Self { Error::StoreRusqlite(e) } } <file_sep>CREATE TABLE rating_value ( id INTEGER PRIMARY KEY, value INTEGER NOT NULL ); CREATE TABLE rating ( id INTEGER PRIMARY KEY, music_id INTEGER, rating_value_id INTEGER, FOREIGN KEY (music_id) REFERENCES music (id), FOREIGN KEY (rating_value_id) REFERENCES rating_value (id) ); INSERT INTO rating_value (value) VALUES (1), (2), (3), (4), (5); <file_sep>#[derive(Debug)] pub enum Rating { One, Two, Three, Four, Five, } impl Rating { pub fn as_i64(&self) -> i64 { match self { Rating::One => 1, Rating::Two => 2, Rating::Three => 3, Rating::Four => 4, Rating::Five => 5, } } } <file_sep>use crate::error::Error; use crate::music::Music; use rusqlite::{params, Connection}; use std::path::Path; #[derive(Debug)] pub struct Store { con: Connection, } impl Store { pub fn create(path: &Path) -> Result<Self, Error> { let con = Connection::open(path)?; let schema = r#" CREATE TABLE music ( id INTEGER PRIMARY KEY, path TEXT NOT NULL UNIQUE ) "#; let _ = con.execute(schema, params![])?; Ok(Store { con }) } pub fn open(path: &Path) -> Result<Self, Error> { if !path.is_file() { return Err(Error::StoreOpenNoFile(path.to_path_buf())); } let con = Connection::open(path)?; Ok(Store { con }) } pub fn insert<I>(&mut self, iter: I) -> Result<(), Error> where I: Iterator<Item = Music>, { let sql = r#" INSERT INTO music (path) VALUES (?1) "#; let tx = self.con.transaction()?; for item in iter { match tx.execute(sql, params![item.path]) { Ok(_) => (), Err(e) => match e { rusqlite::Error::SqliteFailure(ec, _) => match ec.code { rusqlite::ErrorCode::ConstraintViolation => { continue; } _ => return Err(Error::StoreRusqlite(e)), }, _ => return Err(Error::StoreRusqlite(e)), }, } } tx.commit()?; Ok(()) } pub fn insert_rating<I>(&mut self, iter: I) -> Result<(), Error> where I: Iterator<Item = (i64, i64)>, { let sql = r#" INSERT INTO rating (music_id, rating_value_id) VALUES (?1, ?2) "#; let tx = self.con.transaction()?; for item in iter { match tx.execute(sql, params![item.0, item.1]) { Ok(_) => (), Err(e) => match e { rusqlite::Error::SqliteFailure(ec, _) => match ec.code { rusqlite::ErrorCode::ConstraintViolation => { continue; } _ => return Err(Error::StoreRusqlite(e)), }, _ => return Err(Error::StoreRusqlite(e)), }, } } tx.commit()?; Ok(()) } pub fn select(&self) -> Result<Option<Vec<Music>>, Error> { let sql = r#" SELECT path FROM music "#; let mut statement = self.con.prepare(sql)?; let iter = statement.query_map(params![], |row| Ok(Music { path: row.get(0)? }))?; let mut music: Vec<Music> = Vec::new(); for item in iter { music.push(item?); } if music.is_empty() { return Ok(None); } Ok(Some(music)) } pub fn select_filter(&self, filter: &str) -> Result<Option<Vec<Music>>, Error> { let sql = r#" SELECT path FROM music WHERE LIKE(?1, path) "#; let mut statement = self.con.prepare(sql)?; // work around an issue with parameters and LIKE let filter = format!("%{}%", filter); let iter = statement.query_map(params![&filter], |row| Ok(Music { path: row.get(0)? }))?; let mut music: Vec<Music> = Vec::new(); for item in iter { music.push(item?); } if music.is_empty() { return Ok(None); } Ok(Some(music)) } pub fn select_by_rating(&self, rating: i64) -> Result<Option<Vec<Music>>, Error> { let sql = r#" SELECT music.path FROM rating INNER JOIN music ON rating.music_id = music.id INNER JOIN rating_value ON rating_value_id = rating_value.id WHERE rating_value.id = ?1 "#; let mut statement = self.con.prepare(sql)?; let iter = statement.query_map(params![rating], |row| Ok(Music { path: row.get(0)? }))?; let mut music: Vec<Music> = Vec::new(); for item in iter { music.push(item?); } if music.is_empty() { return Ok(None); } Ok(Some(music)) } } <file_sep>use crate::error::Error; use crate::music::Music; use std::fs::{self}; use std::path::{Path, PathBuf}; use std::sync::mpsc::{channel, Sender}; use std::thread; pub fn index_directory(path: PathBuf) -> Result<Vec<Music>, Error> { if !path.is_dir() { return Err(Error::IndexerPathNotDir(path)); } let (sender, receiver) = channel(); let visitor = thread::spawn(move || -> Result<(), Error> { visit_dirs(&path, &sender) }); let mut items: Vec<Music> = Vec::new(); for pb in receiver { if let Some(path) = pb.to_str() { items.push(Music { path: path.to_string(), }); } else { // using the debug formatter for pb is kind of yuck. eprintln!("Skipping path '{:?}' due to invalid UTF8", pb); } } // Has the child panicked? let maybe_err = match visitor.join() { Ok(maybe_err) => maybe_err, // we can't really do anything useful here.. just note that an error // occurred. Err(_) => return Err(Error::IndexerThread), }; // Was an error returned from the closure? match maybe_err { Ok(_) => Ok(items), Err(e) => Err(e), } } // borrowed/adapted from the rust docs fn visit_dirs(dir: &Path, sender: &Sender<PathBuf>) -> Result<(), Error> { if dir.is_dir() { for entry in fs::read_dir(dir)? { let entry = entry?; let pb = entry.path(); if pb.is_dir() { visit_dirs(&pb, sender)?; } else { sender.send(pb)?; } } } Ok(()) } <file_sep>CREATE TABLE music ( id INTEGER PRIMARY KEY, path TEXT NOT NULL UNIQUE ); <file_sep>use std::fmt; #[derive(Debug)] pub struct Music { pub path: String, } impl fmt::Display for Music { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.path) } }
5ae1f91b1f06791b164972acd27e476ae6f616c2
[ "Rust", "SQL" ]
10
Rust
amigo-rich/mkplaylist
bcdc9d08a4aa52c823259de2c1a2be96cdac9c0f
6c0d556869c51d7c8c2878eca3220a2aa9c41ddf
refs/heads/master
<repo_name>lazyker/studyDev<file_sep>/.svn/pristine/33/338d15e8e7a73ea5b98a97e8757dcbd8450f07aa.svn-base "# studyDev" <file_sep>/src/main/webapp/erd/tonysearch.sql SET SESSION FOREIGN_KEY_CHECKS=0; /* Drop Tables */ DROP TABLE IF EXISTS H_COMPANY_USER; DROP TABLE IF EXISTS H_RECRUIT; DROP TABLE IF EXISTS H_USER; DROP TABLE IF EXISTS I_ATTACH; DROP TABLE IF EXISTS I_BOARD; DROP TABLE IF EXISTS I_COMMENT; DROP TABLE IF EXISTS I_COMPANY; DROP TABLE IF EXISTS I_CONSULTANT; DROP TABLE IF EXISTS I_HOLIDAY; DROP TABLE IF EXISTS I_JOB_CD; DROP TABLE IF EXISTS I_KPI; DROP TABLE IF EXISTS I_LOGIN_INFO; DROP TABLE IF EXISTS I_MARK; DROP TABLE IF EXISTS I_PERSON; DROP TABLE IF EXISTS I_POSITION; DROP TABLE IF EXISTS I_PRO_STATUS; DROP TABLE IF EXISTS I_REC_PRESENT; DROP TABLE IF EXISTS I_SCHEDULE; DROP TABLE IF EXISTS I_USER; DROP TABLE IF EXISTS I_USER_ACADEMIC; DROP TABLE IF EXISTS MAIL_MANAGER; /* Create Tables */ -- 홈페이지-기업회원 CREATE TABLE H_COMPANY_USER ( COM_USR_ID varchar(11) COMMENT '기업회원 아이디', PASSWORD varchar(62) COMMENT '<PASSWORD>', COM_NM varchar(30) COMMENT '회사명', SALES varchar(40) COMMENT '매출액', PEOPLE varchar(20) COMMENT '인원', MAJOR varchar(100) COMMENT '주요사업', URL varchar(40) COMMENT '홈페이지 주소', HR_NM varchar(20) COMMENT '인사담당자 이름', HR_RANK varchar(20) COMMENT '인사담당자 직급', HR_PHONE varchar(128) COMMENT '인사담당자 전화번호', HR_MOBILE varchar(128) COMMENT '인사담당자 휴대폰', HR_EMAIL varchar(128) COMMENT '인사담당자 이메일', REG_DATE datetime COMMENT '가입일시', MOD_DATE datetime COMMENT '수정일시', DEL_DATE datetime COMMENT '탈퇴여부' ) COMMENT = '홈페이지-기업회원'; -- 홈페이지-채용의뢰 CREATE TABLE H_RECRUIT ( REC_ID int NOT NULL COMMENT '채용의뢰 아이디', COM_NM varchar(40) COMMENT '회사명', SALES varchar(40) COMMENT '매출액', PEOPLE varchar(10) COMMENT '인원', MAJOR varchar(100) COMMENT '주요사업', URL varchar(40) COMMENT '홈페이지 주소', HR_NM varchar(20) COMMENT '인사담당자 이름', HR_RANK varchar(20) COMMENT '인사담당자 직급', HR_PHONE varchar(128) COMMENT '인사담당자 전화번호', HR_MOBILE varchar(128) COMMENT '인사담당자 휴대폰', HR_EMAIL varchar(128) COMMENT '인사담당자 이메일', POS_NM varchar(20) COMMENT '포지션 이름', RANK varchar(20) COMMENT '직급', DUTY varchar(20) COMMENT '직책', DEPT_NM varchar(20) COMMENT '근무부서', DEPT_PLACE varchar(20) COMMENT '근무지', TASK varchar(20000) COMMENT '업무내용', REC_CONDITION varchar(20000) COMMENT '자격요건', SALARY varchar(20) COMMENT '연봉수준', WELFARE varchar(100) COMMENT '복리후생', ETC varchar(20000) COMMENT '기타', REG_DATE datetime COMMENT '등록일시', PRIMARY KEY (REC_ID) ) COMMENT = '홈페이지-채용의뢰'; -- 홈페이지-개인회원 CREATE TABLE H_USER ( USR_ID varchar(11) COMMENT '후보자 아이디', PASSWORD varchar(62) COMMENT '비밀번호', USER_NM varchar(20) COMMENT '성명', GENDER char COMMENT '성별', MOBILE varchar(128) COMMENT '휴대폰', PHONE varchar(128) COMMENT '전화번호', EMAIL varchar(128) COMMENT '이메일', REG_DATE datetime COMMENT '가입일시', DEL_DATE datetime COMMENT '탈퇴여부' ) COMMENT = '홈페이지-개인회원'; -- 파일첨부 CREATE TABLE I_ATTACH ( ATT_ID varchar(11) NOT NULL COMMENT '첨부파일 아이디', ORG_ID varchar(11) COMMENT '게시물 아이디', -- 1 : 후보자(iuser01) -- 2 : 공지사항, 업무자료(board) -- 3 : 일정관리(schedule) -- 4 : 컨설턴트(consultant) FILE_TYPE char(1) COMMENT '파일 구분 : 1 : 후보자(iuser01) 2 : 공지사항, 업무자료(board) 3 : 일정관리(schedule) 4 : 컨설턴트(consultant)', -- type 1인 경우 -- 1 : 국문이력서1 -- 2 : 국문이력서2 -- 3 : 영문이력서1 -- 4 : 영문이력서2 -- 5 : 추천서 -- 6 : 기타 FILE_ORDER char(1) COMMENT '파일 순서 : type 1인 경우 1 : 국문이력서1 2 : 국문이력서2 3 : 영문이력서1 4 : 영문이력서2 5 : 추천서 6 : 기타', ORIGINAL_FILE_NM varchar(200) COMMENT '원본 파일명', STORED_FILE_NM varchar(550) COMMENT '실제 저장된 파일명', FILE_PATH varchar(255) COMMENT '파일위치', FILE_SIZE int(11) COMMENT '파일크기', CON_ID varchar(20) COMMENT '작성자 아이디', REG_DATE datetime COMMENT '등록일시', DEL_DATE datetime COMMENT '삭제일시', PRIMARY KEY (ATT_ID) ) COMMENT = '파일첨부'; -- 게시판 CREATE TABLE I_BOARD ( BOD_ID int NOT NULL COMMENT '게시물 아이디', -- 1 : 공지사항 -- 2 : 업무자료 BOD_TYPE char(1) COMMENT '게시판 구분 : 1 : 공지사항 2 : 업무자료', TITLE varchar(50) COMMENT '제목', CONTENTS varchar(20000) COMMENT '내용', CON_ID varchar(20) COMMENT '컨설턴트 아이디', REG_DATE datetime COMMENT '등록일시', DEL_DATE datetime COMMENT '삭제일시', PRIMARY KEY (BOD_ID) ) COMMENT = '게시판'; -- 코멘트 CREATE TABLE I_COMMENT ( CMT_ID varchar(11) NOT NULL COMMENT '코멘트 아이디', -- 1 : 고객사 -- 2 : 포지션 -- 3 : 후보자 CMT_TYPE char(1) COMMENT '구분 : 1 : 고객사 2 : 포지션 3 : 후보자', ITEM_ID varchar(11) COMMENT '대상 아이디', CON_ID varchar(20) COMMENT '컨설턴트 아이디', CONTENTS varchar(10000) COMMENT '내용', REG_DATE datetime COMMENT '등록일시', DEL_DATE datetime COMMENT '삭제일시', PRIMARY KEY (CMT_ID) ) COMMENT = '코멘트'; -- 고객사 CREATE TABLE I_COMPANY ( COM_ID varchar(11) NOT NULL COMMENT '회사아이디', COM_NM varchar(40) COMMENT '회사명', -- A : 고객사, B : 마케팅 SECTION char(1) COMMENT '구분 : A : 고객사, B : 마케팅', -- A : 대기업, B : 중견기업, C : 중소기업, D : 외국계기업 COM_TYPE char(1) COMMENT '기업형태 : A : 대기업, B : 중견기업, C : 중소기업, D : 외국계기업', SALES varchar(20) COMMENT '매출 ', PEOPLE varchar(20) COMMENT '인원', INDUSTRY1 varchar(11) COMMENT '업종 1단계', INDUSTRY2 varchar(11) COMMENT '업종 2단계', PUBLIC_YN char(1) COMMENT '내부공개여부', SUMMARY varchar(20000) COMMENT '회사개요', ADDRESS varchar(100) COMMENT '주소', STANDARD varchar(50) COMMENT '처우수준', URL varchar(60) COMMENT '홈페이지', -- 1 : TM, 2 : EM, 3 : 방문, 4 : 지인소개, 5 : 인바운드, 6 : 기타 SOURCE char(1) COMMENT '등록경로 : 1 : TM, 2 : EM, 3 : 방문, 4 : 지인소개, 5 : 인바운드, 6 : 기타', COMMISSION varchar(50) COMMENT '수수료율', GUARANTEE varchar(2) COMMENT '개런티', USR_NM varchar(20) COMMENT '등록자 이름', USR_ID varchar(20) COMMENT '등록자 아이디', CON_ID varchar(20) COMMENT '컨설턴트 아이디', CON_NM varchar(20) COMMENT '컨설턴트 이름', REG_DATE datetime COMMENT '등록일시', MOD_DATE datetime COMMENT '수정일시', DEL_DATE datetime COMMENT '삭제일시', PRIMARY KEY (COM_ID) ) COMMENT = '고객사'; -- 컨설턴트 CREATE TABLE I_CONSULTANT ( CON_ID varchar(20) NOT NULL COMMENT '컨설턴트 아이디', PASSWORD varchar(62) COMMENT '암호', CON_NM varchar(20) COMMENT '컨설턴트 이름', RANK varchar(20) COMMENT '직급코드', RANK_NM varchar(20) COMMENT '직급명', CON_ORDER int(3) COMMENT '정렬순서', FIELD varchar(1000) COMMENT '전문분야', -- 홈페이지 공개여부 H_PUBLIC_YN char(1) DEFAULT 'Y' COMMENT '홈페이지 공개여부 : 홈페이지 공개여부', PHONE varchar(128) COMMENT '연락처', MOBILE varchar(128) COMMENT '휴대폰', EMAIL varchar(128) COMMENT '이메일', EDU varchar(20000) COMMENT '학력/경력', ADMIN_YN char(1) DEFAULT 'N' COMMENT '관리자지정', -- 1 : 권한있음 -- 0 : 권한없음 AUTH_PUBLIC char(1) COMMENT '등록자료 공개여부 : 1 : 권한있음 0 : 권한없음', -- 1 : 권한있음 -- 0 : 권한없음 AUTH_COMPANY char(1) COMMENT '고객사관리 조회 여부 : 1 : 권한있음 0 : 권한없음', -- 1 : 권한있음 -- 0 : 권한없음 AUTH_POSITION char(1) COMMENT '포지션관리 조회 여부 : 1 : 권한있음 0 : 권한없음', -- 1 : 권한있음 -- 0 : 권한없음 AUTH_USER char(1) COMMENT '후보자관리 조회 여부 : 1 : 권한있음 0 : 권한없음', -- 1 : 전체이력조회 -- 2 : 연락처를 제외한 이력조회 -- 3 : 이력서 조회 불가 AUTH_USER_TYPE char(1) COMMENT '후보자 이력서 조회 유형 : 1 : 전체이력조회 2 : 연락처를 제외한 이력조회 3 : 이력서 조회 불가', REG_DATE datetime COMMENT '등록일시', DEL_DATE datetime COMMENT '삭제일시', PRIMARY KEY (CON_ID) ) COMMENT = '컨설턴트'; -- 공휴일관리 CREATE TABLE I_HOLIDAY ( HLDY_YMD varchar(10) COMMENT '휴일날짜', HLDY_NM varchar(40) COMMENT '휴일 이름', REG_DATE datetime COMMENT '등록일시' ) COMMENT = '공휴일관리'; -- 업종,직무 코드 CREATE TABLE I_JOB_CD ( CD_ID varchar(11) COMMENT '코드 아이디', CD_TYPE char COMMENT '코드 구분', CD_LEVEL char COMMENT '코드 단계', PARENT_ID varchar(11) COMMENT '상위 코드 아이디', CD_NM varchar(50) COMMENT '코드 이름', CD_ORDER int(2) COMMENT '코드 순서' ) COMMENT = '업종,직무 코드'; -- KPI 현황 CREATE TABLE I_KPI ( CON_ID varchar(20) COMMENT '컨설턴트 아이디', SCON_ID varchar(20) COMMENT '부컨설턴트 아이디', POS_ID varchar(11) COMMENT '포지션 아이디', USR_ID varchar(11) COMMENT '후보자 아이디', COM_ID varchar(11) COMMENT '회사 아이디', REC_ID varchar(11) COMMENT '추천 아이디', STA_ID varchar(11) COMMENT '상태 아이디', ACTION varchar(12) COMMENT '액션 명칭', REG_DATE datetime COMMENT '등록일시', DEL_DATE datetime COMMENT '삭제일시' ) COMMENT = 'KPI 현황'; -- 로그인정보 CREATE TABLE I_LOGIN_INFO ( CON_ID varchar(20) COMMENT '컨설턴트 아이디', IP varchar(39) COMMENT '접속 IP', REG_DATE datetime COMMENT '접속일시', PASS_YN char(1) COMMENT '로그인 성공 여부' ) COMMENT = '로그인정보'; -- 관심DB CREATE TABLE I_MARK ( MARK_ID int COMMENT '관심DB 아이디', CON_ID varchar(11) COMMENT '컨설턴트 아이디', USR_ID varchar(11) COMMENT '후보자 아이디', REG_DATE datetime COMMENT '등록일시' ) COMMENT = '관심DB'; -- 고객사-담당자 : AUTO_INCREMENT CREATE TABLE I_PERSON ( PERSON_ID int NOT NULL COMMENT '고객사담당자 아이디', COM_ID varchar(11) NOT NULL COMMENT '회사 아이디', PERSON_NM varchar(20) COMMENT '담당자 이름', DEPT_NM varchar(40) COMMENT '담당자 부서', POS_NM varchar(20) COMMENT '담당자 직위', PHONE1 varchar(128) COMMENT '담당자 연락처1', PHONE2 varchar(128) COMMENT '담당자 연락처2', EMAIL varchar(128) COMMENT '담당자 이메일', ETC varchar(50) COMMENT '비고', SORT char COMMENT '정렬 순서', REG_DATE datetime COMMENT '등록일시', MOD_DATE datetime COMMENT '수정일시', DEL_DATE datetime COMMENT '삭제일시', PRIMARY KEY (PERSON_ID) ) COMMENT = '고객사-담당자 : AUTO_INCREMENT'; -- 포지션 CREATE TABLE I_POSITION ( POS_ID varchar(11) NOT NULL COMMENT '포지션 아이디', POS_NM varchar(100) COMMENT '포지션 이름', COM_ID varchar(11) COMMENT '회사 아이디', COM_NM varchar(40) COMMENT '회사명', RULE varchar(20) COMMENT '업무방식', H_PUBLIC_YN char(1) COMMENT '홈페이지공개여부', CON_ID varchar(20) COMMENT '주컨설턴트 아이디', CON_NM varchar(20) COMMENT '컨설턴트 이름', S_CON_ID varchar(20) COMMENT '부컨설턴트 아이디', S_CON_NM varchar(20) COMMENT '부 컨설턴트 이름', POS_STATUS char(1) COMMENT '진행상태', JOB1 varchar(11) COMMENT '직무 1단계', JOB2 varchar(11) COMMENT '직무 2단계', EDU char(1) COMMENT '학력', FROM_RANK char(1) COMMENT 'FROM 직급', TO_RANK char(1) COMMENT 'TO 직급', CAREER varchar(30) COMMENT '경력', LANG varchar(40) COMMENT '외국어', PLACE varchar(20) COMMENT '근무지', PUBLIC_YN char(1) COMMENT '인트라넷(내부)공개여부', TASK mediumtext COMMENT '업무내용', POS_CONDITION mediumtext COMMENT '자격요건', FROM_TARGET varchar(4) COMMENT 'FROM 타켓연령', TO_TARGET varchar(4) COMMENT 'TO 연령', T_COMPANY varchar(50) COMMENT '선호기업', GENDER char(1) COMMENT '성별', LICENSE varchar(50) COMMENT '자격증', BASE varchar(20) COMMENT '기본급', BONUS varchar(20) COMMENT '성과급', ETC mediumtext COMMENT '기타정보', REG_DATE datetime COMMENT '등록일시', MOD_DATE datetime COMMENT '수정일시', DEL_DATE datetime COMMENT '삭제일시', PRIMARY KEY (POS_ID) ) COMMENT = '포지션'; -- 추천 진행상태 CREATE TABLE I_PRO_STATUS ( STA_ID varchar(11) COMMENT '진행상태 아이디', REC_ID varchar(11) COMMENT '추천 아이디', CON_ID varchar(11) COMMENT '컨설턴트 아이디', STATE varchar(2) COMMENT '진행상태값', STATE_NM varchar(20) COMMENT '진행상태명', STATE_DATE varchar(10) COMMENT '진행상태날짜', REG_DATE datetime COMMENT '등록일시', DEL_DATE datetime COMMENT '삭제일시', -- 사용처가 어딘지 모르리 상황봐서 삭제 POS_CON_ID varchar(11) COMMENT '뭔지모름 : 사용처가 어딘지 모르리 상황봐서 삭제' ) COMMENT = '추천 진행상태'; -- 추천 진행현황 CREATE TABLE I_REC_PRESENT ( REC_ID varchar(11) NOT NULL COMMENT '추천 아이디', POS_ID varchar(11) NOT NULL COMMENT '포지션 아이디', USR_ID varchar(11) NOT NULL COMMENT '후보자 아이디', CON_ID varchar(20) COMMENT '컨설턴트 아이디', REG_DATE datetime COMMENT '추천일시', DEL_DATE datetime COMMENT '삭제일시', PRIMARY KEY (REC_ID, POS_ID, USR_ID) ) COMMENT = '추천 진행현황'; -- 일정관리 CREATE TABLE I_SCHEDULE ( SCH_ID varchar(11) NOT NULL COMMENT '스케줄 아이디', SCH_NM varchar(20) COMMENT '스케줄 이름', START_YMD varchar(10) COMMENT '시작일자', END_YMD varchar(10) COMMENT '종료일자', START_TM varchar(4) COMMENT '시작시간', END_TM varchar(4) COMMENT '종료시간', CON_ID varchar(11) COMMENT '컨설턴트 아이디', PLACE varchar(100) COMMENT '장소', -- 메모 MEMO varchar(1000) COMMENT '메모 : 메모', PUBLIC_YN char COMMENT '공개여부', REG_DATE datetime COMMENT '등록일시', DEL_DATE datetime COMMENT '삭제일시', PRIMARY KEY (SCH_ID) ) COMMENT = '일정관리'; -- 후보자 CREATE TABLE I_USER ( USR_ID varchar(11) NOT NULL COMMENT '후보자 아이디', USR_NM varchar(60) COMMENT '후보자 이름', INDUSTRY1 varchar(11) COMMENT '업종1', INDUSTRY2 varchar(11) COMMENT '업종2', JOB1 varchar(11) COMMENT '직무1', JOB1_NM varchar(30) COMMENT '직무명1', JOB2 varchar(11) COMMENT '직무2', JOB2_NM varchar(30) COMMENT '직무명2', YEAR varchar(4) COMMENT '출생년도', GENDER char COMMENT '성별', ADDRESS varchar(100) COMMENT '주소', PUBLIC_YN char COMMENT '인트라넷(내부)공개여부', LANG varchar(40) COMMENT '외국어', LICENSE varchar(50) COMMENT '자격증', BASE int COMMENT '기본급', BONUS int COMMENT '성과급', -- 학력1 ACADEMIC_1 varchar(380) COMMENT '학력1 : 학력1', -- 학력2 ACADEMIC_2 varchar(220) COMMENT '학력2 : 학력2', -- 학력3 ACADEMIC_3 varchar(200) COMMENT '학력3 : 학력3', -- 학력4 ACADEMIC_4 varchar(200) COMMENT '학력4 : 학력4', C_NAME varchar(260) COMMENT '경력회사', SUMMARY mediumtext COMMENT '경력요약', DETAIL mediumtext COMMENT '상세경력', SOURCES varchar(2) COMMENT '출처', CON_ID varchar(20) COMMENT '등록자 아이디', -- 등록자 이름 CON_NM varchar(20) COMMENT '등록자 이름 : 등록자 이름', PHONE varchar(128) COMMENT '연락처', MOBILE varchar(128) COMMENT '휴대폰', EMAIL varchar(128) COMMENT '이메일', REG_DATE datetime COMMENT '등록일시', MOD_DATE datetime COMMENT '수정일시', DEL_DATE datetime COMMENT '삭제일시', PRIMARY KEY (USR_ID) ) COMMENT = '후보자'; -- 후보자 학력 CREATE TABLE I_USER_ACADEMIC ( USR_ID varchar(20) COMMENT '후보자 아이디', USR_LEVEL varchar(20) COMMENT '후보자 학력', USR_SCHOOL varchar(20) COMMENT '후보자 학교', USR_MAJOR varchar(20) COMMENT '후보자 전공', USR_TYPE varchar(20) COMMENT '후보자 졸업구분', USR_ORDER varchar(20) COMMENT '순서' ) COMMENT = '후보자 학력'; -- 메일관리 CREATE TABLE MAIL_MANAGER ( MAIL_TO varchar(50) COMMENT '수신메일주소', MAIL_FROM varchar(50) COMMENT '발신메일주소', MAIL_TITLE varchar(100) COMMENT '메일제목' ) COMMENT = '메일관리';
bbb8eb892a4b4edbc31d9376098f0d6f6129f13b
[ "Markdown", "SQL" ]
2
Markdown
lazyker/studyDev
4c775cbeb170ab7ec5afd8e10da757f791309b51
07d9f31419a79a530cfa0eed5741d5b4d5f36ac6
refs/heads/master
<file_sep>package com.chaoliu1995.blog.entity; import java.io.Serializable; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import com.chaoliu1995.blog.util.Constant; import lombok.Data; /** * @ClassName: ArticleType * @Desc: TODO 文章类型表 * @author chao.Liu * @date 2017-06-15 08:38 */ @Data public class ArticleType implements Serializable { private static final long serialVersionUID = Constant.SERIAL_VERSION_UID; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String typeCode; private String name; private String parentCode; private Integer flag; } <file_sep>/** * 前端加密方法 */ //随机数 function s20(){ var data=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]; var result = ""; for(var i=0;i<8;i++){ r=Math.floor(Math.random()*62); result+=data[r]; } return result; } //加密 function Encrypt(word){ var ran = s20(); var key = CryptoJS.enc.Utf8.parse("1234567891234567"); //从服务器接收 var iv = CryptoJS.enc.Utf8.parse("0102030405060708"); //从服务器接收 srcs = CryptoJS.enc.Utf8.parse(ran + word); var encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode:CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7} ); //encrypted.toString()返回的是base64格式的密文 var str = Base64.encode(encrypted.toString()); return str; } //解密 function Decrypt(word){ var key = CryptoJS.enc.Utf8.parse("0102030405060708"); var iv = CryptoJS.enc.Utf8.parse('0102030405060708'); var decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv,mode:CryptoJS.mode.CBC}); return CryptoJS.enc.Utf8.stringify(encrypted).toString(); } <file_sep>package com.chaoliu1995.blog.service; import java.util.List; import com.chaoliu1995.blog.base.BaseService; import com.chaoliu1995.blog.entity.SysMenu; public interface SysMenuService extends BaseService<SysMenu>{ /** * 获取某节点的子节点 * @param parentId * @return */ List<SysMenu> listSysMenuByParentId(Integer parentId); } <file_sep>package com.chaoliu1995.blog.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Transient; import com.chaoliu1995.blog.util.Constant; import lombok.Data; /** * @ClassName: Article * @Desc: TODO 文章表 * @author chao.Liu * @date 2017-06-15 08:38 */ @Data public class Article implements Serializable { private static final long serialVersionUID = Constant.SERIAL_VERSION_UID; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; //ID private String articleCode; //文章的编号 private String fragment; //文章的摘要 private String keywords; private Integer contentId; //内容id @Transient private String content; //内容 private String title; //标题 private Date pubtime; //发表时间 private String typeCode; //类型code private Integer clickCount; //点击数量 private Integer commentCount; //评论数量 private Integer flag; //状态 } <file_sep>StaticFile.path=D:/temp/<file_sep>package com.chaoliu1995.blog.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.chaoliu1995.blog.base.BaseController; import com.chaoliu1995.blog.entity.User; import com.chaoliu1995.blog.service.impl.UserServiceImpl; import com.chaoliu1995.blog.util.StringUtils; import com.google.gson.Gson; @Controller @RequestMapping("/admin") public class LoginController extends BaseController{ @Autowired private UserServiceImpl userService; /** * 登录页面 * @return */ @RequestMapping(value="/login",method=RequestMethod.GET) public String loginPage(){ return "backend/login"; } /** * 登录 * @param user * @return */ @RequestMapping(value="/login",method=RequestMethod.POST) @ResponseBody public String login(User user){ Map<String,String> resultMap = new HashMap<String,String>(); resultMap.put("status", "error"); Gson gson = new Gson(); if(StringUtils.isEmpty(user.getUsername())){ resultMap.put("info", "账号不可以为空"); return gson.toJson(resultMap); }else if(StringUtils.isEmpty(user.getPassword())){ resultMap.put("info", "密码不可以为空"); return gson.toJson(resultMap); }else if(StringUtils.isEmpty(user.getValidCode())){ resultMap.put("info", "验证码不可以为空"); return gson.toJson(resultMap); } if(!validCodeIsEqual(user.getValidCode())){ resultMap.put("info", "验证码不匹配"); return gson.toJson(resultMap); } Map<String,String> serviceMap = userService.login(user); if(serviceMap.get("status").equals("success")){ session.setAttribute("session_user", user); resultMap.put("status", "success"); resultMap.put("url", "admin/index.do"); return gson.toJson(resultMap); }else{ resultMap.put("info", serviceMap.get("info")); return gson.toJson(resultMap); } } /** * 退出登录 * @return */ @RequestMapping("/loginOut") public String loginOut(){ if(session != null){ session.invalidate(); } return "backend/login"; } @RequestMapping("/index") public String getIndexPage(){ return "backend/index"; } } <file_sep>package com.chaoliu1995.blog.controller; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.chaoliu1995.blog.base.BaseController; import com.chaoliu1995.blog.entity.ArticleType; import com.chaoliu1995.blog.service.ArticleTypeService; import com.chaoliu1995.blog.util.Constant; import com.chaoliu1995.blog.util.StringUtils; import com.google.gson.Gson; @Controller @RequestMapping("/admin/articleType") public class ArticleTypeController extends BaseController { @Autowired private ArticleTypeService articleTypeService; @RequestMapping("/listPage") public String listPage(){ return "backend/articleTypeList"; } /** * 获取文章类型的list JSON * @return */ @RequestMapping("/list") @ResponseBody public String list(){ List<ArticleType> list = articleTypeService.listAll(); if(list != null && list.size() > 0){ Gson gson = new Gson(); return gson.toJson(list); } return ""; } /** * 新增文章类型 * @param name * @param parentCode * @return */ /*@RequestMapping("/add") @ResponseBody public String addArticleType(@RequestParam("name")String name,String parentCode){ Map<String,String> resultMap = getInitResultMap(); if(StringUtils.isEmpty(name)){ resultMap.put("info", "类型名称不可以为空!"); return StringUtils.toJson(resultMap); } ArticleType articleType = new ArticleType(); articleType.setName(name); articleType.setParentCode(parentCode); articleType.setTypeCode(StringUtils.getRandomCode("AT")); try { articleTypeService.insert(articleType); resultMap.put("status", "success"); return StringUtils.toJson(resultMap); } catch (Exception e) { e.printStackTrace(); resultMap.put("info", "未知异常,请联系管理员!"); return StringUtils.toJson(resultMap); } }*/ @RequestMapping("/add") @ResponseBody public String add(@RequestParam("name")String name,@RequestParam("parentCode")String parentCode){ Map<String,String> resultMap = getInitResultMap(); if(StringUtils.isEmpty(name)){ resultMap.put(Constant.RESULT_INFO, "类型名称不可以为空!"); return StringUtils.toJson(resultMap); } ArticleType type = new ArticleType(); if(!StringUtils.isEmpty(parentCode)){ type.setTypeCode(parentCode); if(null == articleTypeService.getOne(type)){ resultMap.put(Constant.RESULT_INFO, "父类型不存在"); return StringUtils.toJson(resultMap); }else{ type.setParentCode(parentCode); } } type.setName(name); type.setTypeCode(StringUtils.getRandomCode("at")); try { articleTypeService.insert(type); resultMap.put(Constant.RESULT_STATUS, Constant.RESULT_STATUS_SUCCESS); return StringUtils.toJson(resultMap); } catch (Exception e) { e.printStackTrace(); resultMap.put(Constant.RESULT_INFO, Constant.RESULT_MESSAGE_UNKNOWN); return StringUtils.toJson(resultMap); } } } <file_sep>package com.chaoliu1995.blog.model; import java.io.Serializable; import com.chaoliu1995.blog.util.Constant; import lombok.Data; @Data public class ArticleTypeCount implements Serializable { private static final long serialVersionUID = Constant.SERIAL_VERSION_UID; private Integer id; private String name; private Integer total; private String typeCode; private Integer flag; } <file_sep>package com.chaoliu1995.blog.base; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import com.chaoliu1995.blog.util.StringUtils; /** * @ClassName: BaseController * @Desc: TODO 为Controller提供公用的属性 * @author chao.Liu * @date 2017-06-15 12:38 */ public class BaseController { protected HttpServletResponse response; protected HttpServletRequest request; protected HttpSession session; protected Model model; protected String basePath; @ModelAttribute public void setReqAndRes(HttpServletRequest request, HttpServletResponse response,Model model){ this.request = request; this.response = response; this.session = request.getSession(); this.model = model; if(StringUtils.isEmpty(basePath)){ this.basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; } model.addAttribute("basePath", basePath); } /** * 验证码是否正确 * @param str * @return */ public boolean validCodeIsEqual(String str){ String validCode = (String)session.getAttribute("verifyCode"); return str.equalsIgnoreCase(validCode); } /** * 返回一个初始化的Map * @return */ public Map<String,String> getInitResultMap(){ Map<String,String> resultMap = new HashMap<String,String>(); resultMap.put("status", "error"); return resultMap; } /** * 返回easyui数据表格所需的json格式 * @param total * @param objList * @return */ public <T> String getDatagridJSON(Integer total,List<T> objList){ Map<String,Object> resultMap = new HashMap<String,Object>(); resultMap.put("total", total); resultMap.put("rows", objList); return StringUtils.toJson(resultMap); } } <file_sep>package com.chaoliu1995.blog.service.impl; import java.io.File; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.chaoliu1995.blog.entity.Article; import com.chaoliu1995.blog.service.ArticleService; import com.chaoliu1995.blog.service.HtmlGeneratorService; import com.chaoliu1995.blog.util.Constant; import com.chaoliu1995.blog.util.FreeMarkerUtils; import com.chaoliu1995.blog.util.Pager; /** * Author: ChaoLiu * Description: * Email: <EMAIL> * CreateDate: 2017年9月24日 下午3:55:08 */ @Service("htmlGeneratorService") public class HtmlGeneratorServiceImpl implements HtmlGeneratorService { @Autowired private ArticleService articleService; @Override public void generatorIndexHtml() { } @Override public void generatorAllArticleHtml() { Article tempArticle = new Article(); Pager<Article> pager = articleService.listArticleContainContentForPager(Pager.DEFAULT_CURRENT_PAGE, Pager.DEFAULT_PAGE_SIZE, tempArticle); Map<String,Object> model = new HashMap<String,Object>(); while(pager.getCurrentPage() <= pager.getPageTotal()){ for(Article article : pager.getRecordList()){ model.put("article", article); FreeMarkerUtils.outputHtmlFileToPath(new File("G:/ftl/"), "article.html", Constant.ARTICLE_PATH, article.getArticleCode()+".html", model); model.clear(); } if(pager.getCurrentPage() < pager.getPageTotal()){ pager = articleService.listArticleContainContentForPager(pager.getNextPage(), Pager.DEFAULT_PAGE_SIZE, tempArticle); } } } @Override public void generatorIndexPageingHtml() { } @Override public void generatorAllArticleTypePagingHtml() { } @Override public boolean checkFilePath() { File blogPath = new File(Constant.BLOG_PATH); File articlePath = new File(Constant.ARTICLE_PATH); try { if(!blogPath.exists()){ blogPath.mkdir(); } if(!articlePath.exists()){ articlePath.mkdir(); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } } <file_sep>package com.chaoliu1995.blog.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.chaoliu1995.blog.base.BaseController; import com.chaoliu1995.blog.entity.Article; import com.chaoliu1995.blog.service.ArticleService; import com.chaoliu1995.blog.util.Pager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @Controller @RequestMapping("/front") public class FrontAriticleController extends BaseController { @Autowired private ArticleService articleService; /** * 主页 * @return */ @RequestMapping(value="/index") public String index(Integer currentPage){ Article article = new Article(); if(currentPage == null){ currentPage = Pager.DEFAULT_CURRENT_PAGE; } Pager<Article> pager = articleService.listArticleForPager(currentPage,Pager.DEFAULT_PAGE_SIZE,article); model.addAttribute("pager", pager); return "front/index"; } /** * 转到文章详情页 * @param request * @param articleCode * @return */ @RequestMapping(value="/articleShow",method=RequestMethod.GET) public String articleShow(@RequestParam("articleId")String articleId){ Article article = articleService.getArticle(Integer.parseInt(articleId)); model.addAttribute("article", article); return "front/article"; } /** * 获取一篇文章 * @return */ @ResponseBody @RequestMapping(value="/getArticle")//,method=RequestMethod.GET public String getArticle(String articleCode){ Article article = new Article(); article.setArticleCode(articleCode); article = articleService.getOne(article); Gson gson = new GsonBuilder().disableHtmlEscaping().create(); String json = gson.toJson(article,Article.class); System.out.println(json.toString()); return json.toString(); } /** * 获取博客列表(翻页) * @return */ @RequestMapping(value="/articleList") public String articleList(@RequestParam(value="currentPage",required = false, defaultValue = "1") Integer currentPage){ Article article = new Article(); article.setTypeCode("1"); try { Pager<Article> pager = articleService.listArticleForPager(currentPage, Pager.DEFAULT_PAGE_SIZE,article); model.addAttribute("pager", pager); } catch (Exception e) { e.printStackTrace(); } return "front/index"; } } <file_sep>package com.chaoliu1995.blog.dao; import com.chaoliu1995.blog.entity.ArticleContent; import tk.mybatis.mapper.common.Mapper; public interface ArticleContentMapper extends Mapper<ArticleContent> { } <file_sep>package com.chaoliu1995.blog.entity; import java.io.Serializable; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Transient; import com.chaoliu1995.blog.util.Constant; import lombok.Data; /** * @ClassName: User * @Desc: TODO 用户表 * @author chao.Liu * @date 2017-06-15 08:38 */ @Data public class User implements Serializable { private static final long serialVersionUID = Constant.SERIAL_VERSION_UID; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String username; private String password; private String nickname; private String email; private String website; @Transient private String validCode; } <file_sep>package com.chaoliu1995.blog.util; public class DateUtil { } <file_sep> /** * 清除form中的数据 * @param idStr * @returns */ function clearForm(idStr){ $(idStr).form('clear'); } /** * 判断字符串是否为空 * @param str * @returns */ function isEmpty(str){ if(str == null || str == "" || str == undefined || str.length == 0){ return true; } return false; }<file_sep>package com.chaoliu1995.blog.service; import java.util.Map; import com.chaoliu1995.blog.base.BaseService; import com.chaoliu1995.blog.entity.User; public interface UserService extends BaseService<User> { /** * 添加用户 * @param user * @throws Exception */ void insertUser(User user)throws Exception; /** * 登录 * @param user * @return */ Map<String,String> login(User user); } <file_sep>package com.chaoliu1995.blog.util.security; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class FullrichPassword { private static final String iv = "abcd123e456abdc9"; // 16位 // 服务器专用密钥 private static final String cryptKey = "8ig*lpk$=Fang5@P"; // 16位 private static final String ivv = "0102030405060708"; private static final String sKey = "1234567891234567"; public static String getIvv() { return ivv; } public static String getSkey() { return sKey; } /** * 模拟客户端密码加密 * @param encryptStr * @return 返回加密之后的字符串 * @throws NoSuchAlgorithmException */ public static String encryptMd5Hash(String encryptStr) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // 输入的字符串转换成字节数组 byte[] inputByteArray = encryptStr.getBytes(); // inputByteArray是输入字符串转换得到的字节数组 messageDigest.update(inputByteArray); // 转换并返回结果,也是字节数组,包含16个元素 byte[] resultByteArray = messageDigest.digest(); // 字符数组转换成字符串返回 . String pw = byteArrayToHex(resultByteArray); // 创建加密对象 并傳入加密類型 @SuppressWarnings("unused") MessageDigest messageDigest1 = MessageDigest.getInstance("SHA-512"); // 传入要加密的字符串 messageDigest.update(pw.getBytes()); // 得到 byte 類型结果 byte byteBuffer[] = messageDigest.digest(); // 將 byte 轉換爲 string StringBuffer strHexString = new StringBuffer(); // 遍歷 byte buffer for (int i = 0; i < byteBuffer.length; i++) { String hex = Integer.toHexString(0xff & byteBuffer[i]); if (hex.length() == 1) { strHexString.append('0'); } strHexString.append(hex); } // 得到返回結果 return strHexString.toString(); } public static String byteArrayToHex(byte[] byteArray) { // 首先初始化一个字符数组,用来存放每个16进制字符 char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方)) char[] resultCharArray = new char[byteArray.length * 2]; // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去 int index = 0; for (byte b : byteArray) { resultCharArray[index++] = hexDigits[b >>> 4 & 0xf]; resultCharArray[index++] = hexDigits[b & 0xf]; } // 字符数组组合成字符串返回 return new String(resultCharArray); } /** * 服务器加密方法 * @param encryptString 需加密的明文 * @param serverSalt 盐值 :随机8位字符 * @return 返回密文 * @throws Exception */ public static String encryptAES(String encryptString, String serverSalt) throws Exception { byte[] raw = cryptKey.getBytes(); // 最后一个参数 加密的方式 SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); // "算法/模式/补码方式" Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv1 = new IvParameterSpec(iv.getBytes()); // 使用CBC模式,需要一个向量iv,可增加加密算法的强度 cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv1); byte[] encrypted = cipher.doFinal((serverSalt + encryptString).getBytes()); // 此处使用BAES64做转码功能,同时能起到2次加密的作用。 return Base64s.encode(encrypted); } /** * 服务器解密方法 * @param decryptString 需解密的密文 * @return 返回明文 * @throws Exception */ public static String decryptAES(String decryptString) { try { byte[] raw = cryptKey.getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv1 = new IvParameterSpec(iv.getBytes()); // "0102030405060708".getBytes() cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv1); byte[] encrypted1 = Base64s.decode(decryptString); try { byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString.substring(8); } catch (Exception e) { System.out.println(e.toString()); return null; } } catch (Exception ex) { System.out.println(ex.toString()); return null; } } /** * 客户端密文解密方法 * @param decryptString 客户端传入的密文 * @param ivv 和客户端一致的iv * @param sKey 和客户端一致密钥 * @return 返回明文 * @throws Exception */ public static String decryptAES(String decryptString, String ivv, String sKey) throws Exception { try { byte[] raw = sKey.getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(ivv.getBytes()); // "0102030405060708".getBytes() cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); // decryptString接收的是前端的加密之后的密码,已经是base64格式的了,见前端注释 byte[] encrypted1 = Base64s.decode(decryptString); try { // cipher.doFinal(encrypted1)即可,如果前端对AES的结果又进行了二次base.encode操作,那么这里需要用Base64.decode解两次 byte[] original = cipher.doFinal(Base64s.decode(new String(encrypted1))); String originalString = new String(original); return originalString.substring(8); } catch (Exception e) { System.out.println(e.toString()); return null; } } catch (Exception ex) { System.out.println(ex.toString()); return null; } } } <file_sep>package com.chaoliu1995.blog.service; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import com.chaoliu1995.blog.base.BaseJunit4Test; import com.chaoliu1995.blog.entity.ArticleType; import com.chaoliu1995.blog.model.ArticleTypeCount; import com.chaoliu1995.blog.util.Constant; import com.chaoliu1995.blog.util.StringUtils; public class ArticleTypeServiceTest extends BaseJunit4Test { @Autowired private ArticleTypeService articleTypeService; @Autowired private Environment env; @Test public void testInsertArticleType(){ ArticleType type = new ArticleType(); type.setFlag(Constant.ARTICLE_TYPE_DEFAULT_FLAG); type.setName("test"); type.setTypeCode(StringUtils.getRandomCode("AT")); System.out.println("-------------------StaticFile.path: "+env.getProperty("StaticFile.path")); articleTypeService.insert(type); } @Test public void testListArticleTypeCount(){ ArticleType type = new ArticleType(); List<ArticleTypeCount> list = articleTypeService.listArticleTypeCount(type); System.out.println(list.size()); } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.chaoliu1995.blog</groupId> <artifactId>Blog</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Blog</name> <url>http://maven.apache.org</url> <properties> <jdk.version>1.8</jdk.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.3.8.RELEASE</spring.version> <mybatis.version>3.3.0</mybatis.version> <log4j.version>1.2.17</log4j.version> <freemarker-version>2.3.23</freemarker-version> <jdbc.driverClassName>com.mysql.jdbc.Driver</jdbc.driverClassName> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.8.47</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- servlet begin --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>${freemarker-version}</version> </dependency> <!-- spring-start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>provided</scope> </dependency> <!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> --> <!-- spring-end --> <!-- MyBtis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- currency mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0</version> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.0</version> </dependency> <!-- mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.33</version> </dependency> <dependency> <groupId>com.sun</groupId> <artifactId>tools</artifactId> <version>${jdk.version}</version> <scope>system</scope> <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> <scope>compile</scope> </dependency> </dependencies> <!-- 仓库配置 --> <repositories> <repository> <id>aliyun</id> <name>nexus aliyun</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>central</id> <name>Maven Repository Switchboard</name> <url>http://repo1.maven.org/maven2/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <build> <finalName>Blog</finalName> <plugins> <!-- 运行插件-start --> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>8.1.16.v20140903</version> </plugin> <!-- 运行插件-end --> <!-- 编译插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> <encoding>UTF-8</encoding> <meminitial>128m</meminitial> <maxmem>256m</maxmem> </configuration> </plugin> <!-- 资源文件处理插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.7</version> <configuration> <encoding>UTF-8</encoding> <useDefaultDelimiters>false</useDefaultDelimiters> <delimiters> <delimiter>${*}</delimiter> <delimiter>@{*}</delimiter> </delimiters> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> <!-- 包含的资源文件 --> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> <!-- 测试的资源文件 --> <testResources> <testResource> <directory>src/test/resources</directory> <filtering>true</filtering> </testResource> </testResources> </build> <profiles> <profile> <!-- 本地开发环境 --> <id>development</id> <properties> <log4j.logFilePath>E:/temp/Blog/log/Blog.log</log4j.logFilePath> <jdbc.username>blog_user</jdbc.username> <jdbc.password><PASSWORD>+.</jdbc.password> <!-- 生成的静态文件存放路径 --> <StaticFile.path></StaticFile.path> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <!-- 生产环境 --> <id>production</id> <properties> <log4j.logFilePath>/mnt/lc/program/apache-tomcat-7.0.73/logs/Blog.log</log4j.logFilePath> <jdbc.username>blog_user</jdbc.username> <jdbc.password><PASSWORD>+.</jdbc.<PASSWORD>> <StaticFile.path></StaticFile.path> </properties> </profile> </profiles> </project> <file_sep>package com.chaoliu1995.blog.service; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.chaoliu1995.blog.base.BaseService; import com.chaoliu1995.blog.entity.ArticleType; import com.chaoliu1995.blog.model.ArticleTypeCount; public interface ArticleTypeService extends BaseService<ArticleType> { /** * 获取每个文章类型的文章总数 * @param articleType * @return */ Map<Integer,Integer> listArticleTotalForArticleType(String flag); /** * 获取文章类型的统计信息 * @param articleType * @return */ List<ArticleTypeCount> listArticleTypeCount(@Param("articleType")ArticleType articleType); } <file_sep>package com.chaoliu1995.blog.service; import com.chaoliu1995.blog.base.BaseService; import com.chaoliu1995.blog.entity.Article; import com.chaoliu1995.blog.util.Pager; public interface ArticleService extends BaseService<Article> { /** * 添加文章,主键set到实体中 * @param article * @return */ void insertArticle(Article article); /** * 获取一条文章记录 * @param id * @return */ Article getArticle(Integer id); /** * 分页获取文章列表 * @param currentPage * @param pageSize * @return */ Pager<Article> listArticleForPager(Integer currentPage,Integer pageSize,Article article); /** * 分页获取文章列表,包含文章内容 * @param currentPage * @param pageSize * @param article * @return */ Pager<Article> listArticleContainContentForPager(Integer currentPage,Integer pageSize,Article article); /** * 根据实体属性,获取文章总数 * @param article * @return */ Integer getCountByAttr(Article article); } <file_sep>package com.chaoliu1995.blog.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.chaoliu1995.blog.entity.Article; import tk.mybatis.mapper.common.Mapper; public interface ArticleMapper extends Mapper<Article> { /** * 添加文章,返回主键 * @param article */ void insertArticle(Article article); /** * 根据实体属性,分页获取文章 * @param start_num * @param end_num * @param flag * @return */ List<Article> listArticle(@Param("article")Article article,@Param("startNum")Integer startNum,@Param("endNum")Integer endNum); /** * 根据实体属性,分页获取文章,包含文章内容 * @param article * @param startNum * @param endNum * @return */ List<Article> listArticleContainContent(@Param("article")Article article,@Param("startNum")Integer startNum,@Param("endNum")Integer endNum); /** * 根据实体属性,获取文章总数 * @param article * @return */ Integer getCountByAttr(Article article); }
b8ae21855197e7a8ebdef8f5797e287482be24f6
[ "JavaScript", "Java", "Maven POM", "INI" ]
22
Java
chaoliu1995/Blog
ed51b46a1b28ce6b04cab838fdf60fb1ffa1b655
01eb92abc756e8e631d3d5982619d64cdd966f80
refs/heads/master
<repo_name>krlvi/wc-rs<file_sep>/Cargo.toml [package] name = "wc-rs" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] edition = "2018" [dependencies] spmc = "0.2.2" hashbrown = "0.3.0" [profile.release] lto = true<file_sep>/README.md # wc-rs Counting words with Rust. This project is simply for learning purposes. ## Building ```sh $ cargo build --release ``` ## Usage ```sh $ target/release/wc-rs ~/path/to/words_dict.txt ~/path/to/input.txt <number_of_threads> the 27774997 to 20896481 a 17984751 of 14939545 and 13697946 is 11471216 that 10235401 in 9217977 for 7262176 you 7061003 ``` <file_sep>/src/main.rs use spmc::{Receiver, Sender}; use hashbrown::HashMap; use std::env; use std::fs::File; use std::io::{BufRead, BufReader}; use std::thread::JoinHandle; fn work( rx: Receiver<Option<String>>, mut dict: HashMap<String, i32>, n: usize, ) -> Vec<(String, i32)> { loop { for msg in rx.recv().iter() { match msg { Some(line) => { for word in line.split_whitespace() { if let Some(val) = dict.get(word) { dict.insert(String::from(word), *val + 1); } } } None => return top_n(dict, n), } } } } fn top_n(dict: HashMap<String, i32>, n: usize) -> Vec<(String, i32)> { let mut res: Vec<(&String, &i32)> = dict.iter().filter(|(_k, v)| v.is_positive()).collect(); res.sort_by(|(_, xv), (_, yv)| yv.cmp(xv)); res.truncate(n); let mut out = Vec::new(); for (k, v) in res { out.push((k.clone(), *v)); } out } fn setup_consumers( d: HashMap<String, i32>, rx: Receiver<Option<String>>, num_thrs: usize, n: usize, ) -> Vec<JoinHandle<Vec<(String, i32)>>> { let mut handles = Vec::new(); for _ in 0..num_thrs { let rx = rx.clone(); let dict = d.clone(); handles.push(std::thread::spawn(move || work(rx, dict, n))); } handles } fn merge_results(handles: Vec<JoinHandle<Vec<(String, i32)>>>) -> Vec<(String, i32)> { let mut re: HashMap<String, i32> = HashMap::new(); // Wait for consumers to finish and merge their results for handle in handles { let thr_res = handle.join().unwrap(); for (k, v) in thr_res { match re.get(&k) { Some(ev) => { re.insert(k, ev + v); } None => { re.insert(k, v); } } } } let mut res: Vec<(&String, &i32)> = re.iter().collect(); res.sort_by(|(_, xv), (_, yv)| yv.cmp(xv)); res.truncate(10); // There has to be a better way res.iter() .map(|(x, y)| (x.clone().clone(), y.clone().clone())) .collect() } fn load_dict(dict_file: &str) -> HashMap<String, i32> { let mut d = HashMap::new(); for line in BufReader::new(File::open(dict_file).expect("Coult not read file")).lines() { d.insert(line.expect("There was a problem reading a line"), 0); } d } fn load_file_into_channel(tx: Sender<Option<String>>, input_file: String, num_thrs: usize) { std::thread::spawn(move || { let input = File::open(&input_file).expect("Could not open input file"); for l in BufReader::new(input).lines() { let _ = tx.send(Option::from(l.expect("Could not read line"))); } // Send termination signal to threads for _ in 0..num_thrs { let _ = tx.send(Option::None); } }); } fn main() { let args: Vec<String> = env::args().collect(); let dict_file = &args[1]; let input_file = &args[2]; let num_thrs = &args[3] .parse::<usize>() .expect("Failed to parse number of threads"); let n = 10; let (tx, rx): (Sender<Option<String>>, Receiver<Option<String>>) = spmc::channel(); let dict = load_dict(dict_file); let handles = setup_consumers(dict, rx, *num_thrs, n); load_file_into_channel(tx, input_file.to_string(), *num_thrs); let res = merge_results(handles); for (k, v) in res { println!("{} {}", k, v); } }
ebd88db8cb66edd305e18cfd86dbf6a1e974442f
[ "TOML", "Rust", "Markdown" ]
3
TOML
krlvi/wc-rs
b89da8176c9215a7ec0ca69d1f418ca06808e901
01f56adcc4cc9f2eebf2586c1c585c8f01885cf0
refs/heads/master
<repo_name>balaji043/Billing-Angular<file_sep>/src/app/core/confirm-popup-box/confirm-popup-box.component.ts import { Component, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { ConfirmationPopup } from 'src/app/model/confirmation.model'; @Component({ selector: 'app-confirm-popup-box', templateUrl: './confirm-popup-box.component.html', styleUrls: ['./confirm-popup-box.component.css'] }) export class ConfirmPopupBoxComponent { constructor(public dialogRef: MatDialogRef<ConfirmPopupBoxComponent>, @Inject(MAT_DIALOG_DATA) public data: ConfirmationPopup) { } onNoClick(): void { this.dialogRef.close(); } } <file_sep>/src/app/components/bill-panel/bill-panel.component.ts import { Component, OnInit, ViewChild } from '@angular/core'; import { GridConfig } from 'src/app/model/generic-grid.config'; import { BillTableConfig } from 'src/app/config/generic-table-config/bill-table-config'; import { MatTableDataSource } from '@angular/material'; import { BillingService } from 'src/app/service/billing.service'; import { GenericGridComponent } from 'src/app/core/mat-generic-grid/mat-generic-grid.component'; import { Customer } from 'src/app/model/customer.model'; import { FormBuilder } from '@angular/forms'; import { debounceTime, tap, switchMap, finalize } from 'rxjs/operators'; import { CustomerService } from 'src/app/service/customer.service'; import { SearchBillRequest } from 'src/app/model/search-bill-request'; import { UtilityService } from 'src/app/service/utility.service'; @Component({ selector: 'app-bill-panel', templateUrl: './bill-panel.component.html', styleUrls: ['./bill-panel.component.css'] }) export class BillPanelComponent implements OnInit { @ViewChild(GenericGridComponent, { static: true }) genericGrid: GenericGridComponent; billTableConfig: GridConfig; billList: MatTableDataSource<any>; isFuzzyLoading: boolean; customerList: Customer[]; advanceSearchForm = this.fb.group({ customer: [], startDate: [], endDate: [] }); constructor( private fb: FormBuilder, private billService: BillingService, private customerService: CustomerService, private uService: UtilityService ) { this.billTableConfig = BillTableConfig(); this.makeSearchBillsAPICall(); } ngOnInit() { this.billList = new MatTableDataSource(); this.billList.paginator = this.genericGrid.paginator; this.initializeForCustomerFuzzySearch(); } public makeSearchBillsAPICall(): void { let searchRequest: SearchBillRequest; if (this.advanceSearchForm.touched && this.advanceSearchForm.valid) { searchRequest = this.advanceSearchForm.value as SearchBillRequest; searchRequest.startDate = this.uService.transformDate(searchRequest.startDate); searchRequest.endDate = this.uService.transformDate(searchRequest.endDate); searchRequest.isAllBillRequest = false; } else { searchRequest = { isAllBillRequest: true, startDate: null, endDate: null }; } this.billService.searchBills(searchRequest).subscribe(result => { this.billList.data = result.data; }); } public initializeForCustomerFuzzySearch(): void { this.advanceSearchForm .get('customer') .valueChanges .pipe( debounceTime(300), tap(() => this.isFuzzyLoading = true), switchMap(value => this.customerService.getCustomerFuzzy('%' + value + '%') .pipe( finalize(() => this.isFuzzyLoading = false), ) ) ) .subscribe(customerList => { this.customerList = customerList; }); } public displayFn(user: any): string { if (user) { return user.name; } } public onClickOfEditIconButton(element): void { console.log(element); } } <file_sep>/src/app/model/customer.model.ts export class Customer { id: number; name: string; phone: string; gstIn: string; streetAddress: string; city: string; state: string; zipCode: string; } <file_sep>/src/app/core/json-ignore/json-ignore.ts const IGNORE_FIELDS = new Map<string, string[]>(); function JsonIgnore(cls: any, name: string) { const clsName = cls.constructor.name; let list: string[]; if (IGNORE_FIELDS.has(clsName)) { list = IGNORE_FIELDS.get(clsName); } else { list = []; IGNORE_FIELDS.set(clsName, list); } list.push(name); } class Base { toJson(): { [name: string]: any } { const json = {}; const ignore = IGNORE_FIELDS.get(this.constructor.name); Object.getOwnPropertyNames(this).filter(name => ignore.indexOf(name) < 0).forEach(name => { json[name] = this[name]; }); return json; } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatNativeDateModule, MatSnackBarModule, MatIconModule, MatButtonModule, MatTableModule, MatPaginatorModule, MatSortModule, MatTabsModule, MatCheckboxModule, MatToolbarModule, MatCardModule, MatFormFieldModule, MatProgressSpinnerModule, MatInputModule, MatMenuModule, MatGridListModule, MatAutocompleteModule, MatTooltipModule, MatBadgeModule, MatExpansionModule, MatStepperModule, MatSlideToggleModule, } from '@angular/material'; import { MatDialogModule, MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { MatDatepickerModule } from '@angular/material/datepicker'; import { MatRadioModule } from '@angular/material/radio'; import { MatSelectModule } from '@angular/material/select'; import { MatSliderModule } from '@angular/material/slider'; import { MatDividerModule } from '@angular/material/divider'; import { LayoutModule } from '@angular/cdk/layout'; import { MatSidenavModule } from '@angular/material/sidenav'; import { MatListModule } from '@angular/material/list'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ScrollingModule } from '@angular/cdk/scrolling'; import { SingleProductComponent } from './components/single-product/single-product.component'; import { BillRegistrationComponent } from './components/bill-registration/bill-registration.component'; import { BillPanelComponent } from './components/bill-panel/bill-panel.component'; import { CustomerPanelComponent } from './components/customer-panel/customer-panel.component'; import { UserPanelComponent } from './components/user-panel/user-panel.component'; import { ConfirmPopupBoxComponent } from './core/confirm-popup-box/confirm-popup-box.component'; import { GenericGridComponent } from './core/mat-generic-grid/mat-generic-grid.component'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { CustomerRegistrationComponent } from './components/customer-registration/customer-registration.component'; import { AppMainNavComponent } from './components/app-main-nav/app-main-nav.component'; import { LoginComponent } from './components/login/login.component'; import { AuthInterceptor } from './config/auth.interceptor'; import { DisableControlDirective } from './core/directive/disale-control.directive'; import { InputDropdownComponent } from './core/input-dropdown/input-dropdown.component'; import { DatePipe } from '@angular/common'; import { UserRegistrationComponent } from './components/user-registration/user-registration.component'; import { GstInvoiceComponent } from './components/invoice-ui/gst-invoice/gst-invoice.component'; import { NonGstInvoiceComponent } from './components/invoice-ui/non-gst-invoice/non-gst-invoice.component'; import { IGstInvoiceComponent } from './components/invoice-ui/i-gst-invoice/i-gst-invoice.component'; @NgModule({ declarations: [ AppComponent, AppMainNavComponent, SingleProductComponent, BillPanelComponent, BillRegistrationComponent, ConfirmPopupBoxComponent, CustomerPanelComponent, UserPanelComponent, GenericGridComponent, CustomerRegistrationComponent, LoginComponent, DisableControlDirective, InputDropdownComponent, UserRegistrationComponent, GstInvoiceComponent, NonGstInvoiceComponent, IGstInvoiceComponent ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, MatNativeDateModule, MatSnackBarModule, MatIconModule, MatDialogModule, MatButtonModule, MatTableModule, MatPaginatorModule, MatSortModule, MatTabsModule, MatCheckboxModule, MatToolbarModule, MatCardModule, MatFormFieldModule, MatProgressSpinnerModule, MatInputModule, MatDatepickerModule, MatRadioModule, MatSelectModule, MatSliderModule, MatDividerModule, LayoutModule, MatSidenavModule, MatListModule, MatMenuModule, ReactiveFormsModule, MatGridListModule, MatAutocompleteModule, MatTooltipModule, ScrollingModule, MatBadgeModule, HttpClientModule, FormsModule, MatExpansionModule, MatStepperModule, MatSlideToggleModule ], providers: [ { provide: MatDialogRef, useValue: {} }, { provide: MAT_DIALOG_DATA, useValue: [] }, { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, }, DatePipe ], bootstrap: [AppComponent], entryComponents: [ ConfirmPopupBoxComponent, CustomerRegistrationComponent, UserRegistrationComponent ] }) export class AppModule { } <file_sep>/src/app/components/customer-panel/customer-panel.component.ts import { Component, OnInit, ViewChild } from '@angular/core'; import { MatDialog, MatTableDataSource } from '@angular/material'; import { CustomerTableConfig } from 'src/app/config/generic-table-config/customer-table-config'; import { CustomerRegistrationComponent } from '../customer-registration/customer-registration.component'; import { GridConfig } from 'src/app/model/generic-grid.config'; import { Customer } from 'src/app/model/customer.model'; import { CustomerRequest } from 'src/app/model/customer-request'; import { CustomerService } from 'src/app/service/customer.service'; import { CustomerType } from 'src/app/utils/billing-constants'; import { GenericGridComponent } from 'src/app/core/mat-generic-grid/mat-generic-grid.component'; @Component({ selector: 'app-cutomer-panel', templateUrl: './customer-panel.component.html', styleUrls: ['./customer-panel.component.css'] }) export class CustomerPanelComponent implements OnInit { @ViewChild(GenericGridComponent, { static: true }) genericGrid: GenericGridComponent; customerGridConfig: GridConfig; genericMatTabaleDataSource: MatTableDataSource<Customer>; customerSearchRequest: CustomerRequest; public CustomerType = CustomerType; constructor( public dialog: MatDialog, private customerService: CustomerService) { this.customerGridConfig = CustomerTableConfig(); this.customerSearchRequest = new CustomerRequest(); this.makeSearchCustomerCall(); } ngOnInit() { this.genericMatTabaleDataSource = new MatTableDataSource(); this.genericMatTabaleDataSource.paginator = this.genericGrid.paginator; } public openCustomerRegistrationDialog(): void { const dialogRef = this.dialog.open(CustomerRegistrationComponent, { width: '450px', data: {} }); dialogRef.afterClosed().subscribe(result => { if (result) { this.makeSearchCustomerCall(); } }); } public makeSearchCustomerCall(): void { this.customerService.getCustomers(this.customerSearchRequest) .subscribe( result => { this.genericMatTabaleDataSource.data = result; }, error => { console.error(error); } ); } } <file_sep>/src/app/components/user-panel/user-panel.component.ts import { Component, OnInit, ViewChild } from '@angular/core'; import { UserRole } from 'src/app/utils/billing-constants'; import { UserSearchRequest } from 'src/app/model/user-search-request'; import { UserService } from 'src/app/service/user.service'; import { GridConfig } from 'src/app/model/generic-grid.config'; import { User } from 'src/app/model/user.model'; import { MatTableDataSource, MatDialog } from '@angular/material'; import { UserTableConfig } from 'src/app/config/generic-table-config/user-table-config'; import { GenericGridComponent } from 'src/app/core/mat-generic-grid/mat-generic-grid.component'; import { error } from 'util'; import { UserRegistrationComponent } from '../user-registration/user-registration.component'; @Component({ selector: 'app-user-panel', templateUrl: './user-panel.component.html', styleUrls: ['./user-panel.component.css'] }) export class UserPanelComponent implements OnInit { @ViewChild(GenericGridComponent, { static: true }) genericGrid: GenericGridComponent; public userGridConfig: GridConfig; public genericMatTabaleDataSource: MatTableDataSource<User>; public UserRole = UserRole; public userSearchRequest: UserSearchRequest; constructor( public dialog: MatDialog, private userService: UserService ) { this.userGridConfig = UserTableConfig(); this.userSearchRequest = new UserSearchRequest(); this.userSearchRequest.userRole = UserRole.BOTH; this.makeSearchUserCall(); } ngOnInit() { this.genericMatTabaleDataSource = new MatTableDataSource(); this.genericMatTabaleDataSource.paginator = this.genericGrid.paginator; } public openUserRegistrationDialog(): void { const dialogRef = this.dialog.open(UserRegistrationComponent, { width: '450px', data: {} }); dialogRef.afterClosed().subscribe(result => { if (result) { this.makeSearchUserCall(); } }); } public makeSearchUserCall(): void { this.userService.getAllUsers(this.userSearchRequest) .subscribe( response => { this.genericMatTabaleDataSource.data = response; }, ex => { console.error(ex); } ); } } <file_sep>/src/app/components/invoice-ui/gst-invoice/gst-invoice.component.ts import { Component, OnInit } from '@angular/core'; import { Customer } from 'src/app/model/customer.model'; @Component({ selector: 'app-gst-invoice', templateUrl: './gst-invoice.component.html', styleUrls: ['./gst-invoice.component.css'] }) export class GstInvoiceComponent implements OnInit { bill: Bill; store: StoreDetails; constructor() { this.bill = { invoice: 'invoice', date: '04/03/1997', totalAmount: '123123', customer: { name: '<NAME>', city: 'City', gstIn: '123456789123456', phone: '9751776701', state: 'Tamil Nadu', streetAddress: 'street address', zipCode: '621212' }, gst12Half: '123', gst12Total: '123', gst18Half: '123', gst18Total: '123', gst28Half: '123', gst28Total: '123', totalTaxAmount: '1', halfTax: '123', gross: '123', time: '123', localDate: '12/12/1221', totalAmountBeforeRoundOff: '123', total: '12', roundedOff: '00.13', place: '12', tax12BeforeTotal: '12', tax18BeforeTotal: '12', tax28BeforeTotal: '12', userName: 'user name', products: [ { name: '13', gstAmount: '123', halfTaxAmt: '123', halfTaxPer: '132', hsn: '12', per: '123', qty: '123', rate: '123', ready: '123', singleOrg: '123', sl: '123', tax: '123', totalAmount: '123', totalOriginalAmount: '123', } ] } as Bill; this.store = { city: 'trichy', gstIn: '789456123456456', name: '<NAME>', phoneNumber: '123456789', street: 'muthu nagar', icon: 'icon', description: 'House Of Cards' } as StoreDetails; } ngOnInit() { } } class StoreDetails { description: string; name: string; street: string; city: string; phoneNumber: string; gstIn: string; icon: string; } class Bill { invoice: string; date: string; customer: Customer; products: Product[]; totalAmount: string; gst12Half: string; gst12Total: string; gst18Half: string; gst18Total: string; gst28Half: string; gst28Total: string; totalTaxAmount: string; halfTax: string; gross: string; userName: string; time: string; localDate: string; totalAmountBeforeRoundOff: string; total: string; roundedOff: string; place: string; tax12BeforeTotal: string; tax18BeforeTotal: string; tax28BeforeTotal: string; } class Product { sl: string; name: string; hsn: string; qty: string; tax: string; rate: string; per: string; halfTaxPer: string; halfTaxAmt: string; totalAmount: string; singleOrg: string; gstAmount: string; ready: string; totalOriginalAmount: string; } <file_sep>/src/app/config/generic-table-config/user-table-config.ts import { GridConfig } from 'src/app/model/generic-grid.config'; import { TableColumn } from 'src/app/model/table-column.config'; export function UserTableConfig(): GridConfig { const gridConfig = new GridConfig(); gridConfig.caption = 'User Details'; gridConfig.uniqueName = 'USER_TABLE_CONFIG'; gridConfig.isPaginationRequired = true; gridConfig.paginationOptions = [5, 10, 15, 20]; const taleColumns = []; const nameColumn = new TableColumn(); nameColumn.accessVariableName = 'name'; nameColumn.columnDisplayName = 'Name'; nameColumn.type = 'text'; nameColumn.searchType = 'text'; taleColumns.push(nameColumn); const userNameColumn = new TableColumn(); userNameColumn.accessVariableName = 'userName'; userNameColumn.columnDisplayName = 'User Name'; userNameColumn.type = 'text'; userNameColumn.searchType = 'text'; taleColumns.push(userNameColumn); const email = new TableColumn(); email.accessVariableName = 'emailId'; email.columnDisplayName = 'Email ID'; email.type = 'text'; email.searchType = 'text'; taleColumns.push(email); const role = new TableColumn(); role.accessVariableName = 'role'; role.columnDisplayName = 'Role'; role.type = 'text'; role.searchType = 'text'; taleColumns.push(role); gridConfig.columns = taleColumns; return gridConfig; } <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { BillRegistrationComponent } from './components/bill-registration/bill-registration.component'; import { BillPanelComponent } from './components/bill-panel/bill-panel.component'; import { UserPanelComponent } from './components/user-panel/user-panel.component'; import { CustomerPanelComponent } from './components/customer-panel/customer-panel.component'; import { LoginComponent } from './components/login/login.component'; import { GstInvoiceComponent } from './components/invoice-ui/gst-invoice/gst-invoice.component'; const routes: Routes = [ { path: 'bill-panel', component: BillPanelComponent }, { path: 'register-bill', component: BillRegistrationComponent }, { path: 'customer-panel', component: CustomerPanelComponent }, { path: 'user-panel', component: UserPanelComponent }, { path: 'login', component: LoginComponent }, { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'app-gst-invoice', component: GstInvoiceComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/environments/environtment-base.ts export class EnvirontmentBase { } export class Environment { env: string; dns: string; baseUrl: string; production: boolean; msPoints: MicroService[]; constructor(env: string, dns: string, baseUrl: string, production: boolean, endPoints: MicroService[]) { this.env = env; this.dns = dns; this.baseUrl = baseUrl; this.msPoints = endPoints; } } export class MicroService { msName: string; basePath: string; endPoints: EndPoint[]; constructor(msName: string, basePath: string, endPoints: EndPoint[]) { this.msName = msName; this.basePath = basePath; this.endPoints = endPoints; } } export class EndPoint { apiName: string; path: string; constructor(apiName: string, path: string) { this.apiName = apiName; this.path = path; } } <file_sep>/src/app/components/customer-registration/customer-registration.component.ts import { Component, Inject, OnInit } from '@angular/core'; import { Validators, FormBuilder } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { CustomerService } from 'src/app/service/customer.service'; import { SharedService } from 'src/app/service/shared.service'; import { CustomerType } from 'src/app/utils/billing-constants'; @Component({ selector: 'app-customer-registration', templateUrl: './customer-registration.component.html', styleUrls: ['./customer-registration.component.css'] }) export class CustomerRegistrationComponent implements OnInit { customerForm = this.fb.group( { name: [null, Validators.required], phoneNumber: [null, Validators.required], gstNo: [null, Validators.required], street: [null, Validators.required], city: [null, Validators.required], state: [null, Validators.required], zipCode: [null, Validators.required], customerType: [null, Validators.required] } ); constructor( public dialogRef: MatDialogRef<CustomerRegistrationComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private fb: FormBuilder, private customerService: CustomerService, private sharedService: SharedService ) { this.customerTypeControl.setValue(CustomerType.NON_GST); } ngOnInit(): void { this.customerTypeControl.setValue(CustomerType.NON_GST); } onSubmit(): void { if (this.customerForm.valid) { this.customerService.saveCustomer(this.customerForm.value).subscribe(result => { this.sharedService.openMatSnackBar('Customer ' + result.name + ' saved successfully'); this.dialogRef.close(true); }, error => { this.sharedService.openMatSnackBar('Error occured'); }); } else { this.customerForm.markAllAsTouched(); } } onNoClick(): void { this.sharedService.openMatSnackBar('Cancelled'); this.dialogRef.close(false); } get customerTypeControl() { return this.customerForm.get('customerType'); } onGSTToggle() { const customerType = this.customerTypeControl.value === CustomerType.GST ? CustomerType.NON_GST : CustomerType.GST; this.customerTypeControl.setValue(customerType); } } <file_sep>/src/app/service/utility.service.ts import { Injectable } from '@angular/core'; import { DatePipe } from '@angular/common'; @Injectable({ providedIn: 'root' }) export class UtilityService { constructor( private datePipe: DatePipe ) { } public isNullOrUndefined(obj: any): boolean { return typeof obj === 'undefined' || obj === null; } public isNullOrUndefinedOrEmpty(value: any): boolean { return this.isNullOrUndefined(value) || value.length === 0; } public cloneObject(value: any): any { return Object.assign({}, value); } public transformDate(date: any): string { if (this.isNullOrUndefined(date)) { return null; } try { return this.datePipe.transform(date, 'dd-MM-yyyy'); } catch (error) { return date; } } } <file_sep>/src/app/components/single-product/single-product.component.ts import { Component, Input, Output, EventEmitter } from '@angular/core'; import { FormBuilder, Validators, FormGroup } from '@angular/forms'; import { Product } from 'src/app/model/product.model'; @Component({ selector: 'app-single-product', templateUrl: './single-product.component.html', styleUrls: ['./single-product.component.css'] }) export class SingleProductComponent { /* #region component inputs */ @Input() singleProductForm: FormGroup; @Input() slNo: number; @Output() clickOfCheckBox = new EventEmitter(); /* #endregion */ /* #region variable declaration */ taxPercentages: number[]; descriptions: string[]; perValues: string[]; /* #endregion */ /* #region constructor */ constructor(private fb: FormBuilder) { /* #region to be replaced with api calls */ this.taxPercentages = [16, 18, 21]; this.descriptions = ['Pen', 'Pencil', 'Eraser', 'Sharpner', 'Scale']; this.perValues = ['PCS', 'DOZ', 'PKT', 'GRO', 'BOX', 'SET', 'ROL', 'BUN']; /* #endregion */ } /* #endregion */ /* #region on event functions */ onSubmit(): void { // console.log(this.); } onClickOfReset(): void { this.singleProductForm.reset(); this.clickOfCheckBox.emit(); } isValid(): boolean { this.singleProductForm.markAllAsTouched(); return this.singleProductForm.valid; } /* #endregion */ } <file_sep>/src/environments/environment-local.ts // This file can be replaced during build by using the `fileReplacements` array. // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. import { Environment, MicroService, EndPoint } from 'src/environments/environtment-base'; import { BillAPIName, CustomerAPIName, UserAPIName, AuthAPIName, MSName } from 'src/app/utils/billing-constants'; export const ENV_LOCAL = new Environment( 'local', 'http://localhost:8080', '/bam/bs', false, [ new MicroService(MSName.BILL_MS, '/bill', [ new EndPoint(BillAPIName.SAVE, ''), new EndPoint(BillAPIName.UPDATE, ''), new EndPoint(BillAPIName.SEARCH, '/search'), new EndPoint(BillAPIName.DELETE, '') ]), new MicroService(MSName.CUSTOMER_MS, '/customer', [ new EndPoint(CustomerAPIName.SAVE, ''), new EndPoint(CustomerAPIName.UPDATE, ''), new EndPoint(CustomerAPIName.SEARCH, '/search'), new EndPoint(CustomerAPIName.FUZZY, '/fuzzy'), new EndPoint(CustomerAPIName.DELETE, '') ]), new MicroService(MSName.USER_MS, '/user', [ new EndPoint(UserAPIName.SAVE, ''), new EndPoint(UserAPIName.UPDATE, ''), new EndPoint(UserAPIName.SEARCH, '/search'), new EndPoint(UserAPIName.DELETE, '') ]), new MicroService(MSName.API_AUTH, '/api/auth', [ new EndPoint(AuthAPIName.SIGN_IN, '/signin') ]) ] ); <file_sep>/src/app/components/bill-registration/bill-registration.component.ts import { Component, OnInit } from '@angular/core'; import { MatDialog } from '@angular/material'; import { ConfirmPopupBoxComponent } from 'src/app/core/confirm-popup-box/confirm-popup-box.component'; import { BillingService } from 'src/app/service/billing.service'; import { FormBuilder, FormArray, Validators } from '@angular/forms'; import { Customer } from 'src/app/model/customer.model'; import { UtilityService } from 'src/app/service/utility.service'; import { TokenStorageService } from 'src/app/service/token-storage.service'; import { BillType, URLS } from 'src/app/utils/billing-constants'; import { CustomerService } from 'src/app/service/customer.service'; import { Router } from '@angular/router'; import { SharedService } from 'src/app/service/shared.service'; import { switchMap, debounceTime, tap, finalize } from 'rxjs/operators'; import { DatePipe } from '@angular/common'; @Component({ selector: 'app-bill-registration', templateUrl: './bill-registration.component.html', styleUrls: ['./bill-registration.component.css'], providers: [DatePipe] }) export class BillRegistrationComponent implements OnInit { /* #region variable declaration */ selectedCustomer: Customer; totalAmount: number; isCheckAll: boolean; isFuzzyLoading: boolean; isCustomerSelected: boolean; checkBoxMatIcon: string; billForm = this.fb.group({ invoiceName: [], creationDate: [], user: [null, Validators.required], customer: [null, Validators.required], products: this.fb.array([]) }); customerList: Customer[]; customerName: string; /* #endregion */ /* #region constructor */ constructor( public dialog: MatDialog, private billingService: BillingService, private fb: FormBuilder, private customerService: CustomerService, private uService: UtilityService, private router: Router, private tokenStorageService: TokenStorageService, private sharedService: SharedService ) { this.billForm.get('user').setValue(this.tokenStorageService.getUser()); this.totalAmount = 0; this.isCheckAll = false; this.checkBoxMatIcon = 'check_box_outline_blank'; this.onClickOfAddProductButton(); this.isCustomerSelected = false; this.customerName = ''; } /* #endregion */ ngOnInit() { this.initializeForCustomerFuzzySearch(); } /* #region on click action methods */ public onClickOfAddProductButton() { if (this.products) { this.products.push(this.fb.group({ checkBox: [], description: [null, Validators.required], hsnCode: [null, Validators.required], quantity: [null, Validators.required], rate: [null, Validators.required], taxPercentage: [null, Validators.required], perValue: [null, Validators.required], discount: [null] })); } } public onClickOfOverallDeleteButton() { const dialogRef = this.dialog.open(ConfirmPopupBoxComponent, { width: 'max-content', data: { title: 'Confirm Delete', content: 'Do you want to delete the selected ' + this.getSelectedCount + ' product(s).' } }); dialogRef.afterClosed().subscribe(result => { console.log('The dialog was closed'); if (result) { this.products.controls = this.products.controls.filter( product => !product.get('checkBox').value ); this.onClickOfIndividualSelectButton(); } }); } public onClickOfOverAllSelectButton() { let isAnySelected = false; this.products.controls.forEach(product => { if (product.get('checkBox').value) { isAnySelected = true; return; } }); this.products.controls.forEach(product => product.get('checkBox').setValue(!isAnySelected)); this.isCheckAll = !this.isCheckAll && !isAnySelected; this.updateCheckBoxMatIcon(); } public onSubmit(): void { const isValid = this.billForm.valid; if (isValid) { console.log('valid products'); const bill = this.billForm.value; bill.billType = this.uService.isNullOrUndefined(this.selectedCustomer.gstIn) ? BillType.NON_GST : BillType.GST; bill.products.forEach(product => { delete product.checkbox; }); bill.customer = this.selectedCustomer; bill.creationDate = this.uService.transformDate(new Date()); this.billingService.saveBill(bill) .subscribe( result => { this.router.navigateByUrl(URLS.BILL_PANEL); this.sharedService.openMatSnackBar('Bill Saved Successfully'); }, error => { this.sharedService.openMatSnackBar(error); }); } else { console.log('invalid products'); } } /* #endregion */ /* #region emmited event functions */ public onClickOfIndividualSelectButton() { this.isCheckAll = this.getTotalCount !== 0 && this.getTotalCount === this.getSelectedCount; this.updateCheckBoxMatIcon(); } public onSelectConfirmOfCustomer() { if (this.billForm .get('customer').valid) { this.isCustomerSelected = true; this.selectedCustomer = this.billForm.get('customer').value; } else { this.billForm.get('customer').markAsTouched(); } } /* #endregion */ /* #region get counts methods */ get getTotalCount(): number { return this.products.length; } get getSelectedCount(): number { return this.products.controls.filter( product => product.get('checkBox').value ).length; } get products(): FormArray { return this.billForm.get('products') as FormArray; } /* #endregion */ /* #region enable and disable buttons */ public isAddButtonDisable(): boolean { return this.getTotalCount >= 20; } public isDeleteButtonDisable(): boolean { return this.getSelectedCount === 0; } public isSubmitAndSelectAllButtonDisable(): boolean { return this.getTotalCount === 0; } /* #endregion */ /* #region get the tool tip text */ public getDeleteProductButtonTooltip(): string { return 'Add Product'; } public getDeleteSelectedProductButtonTooltip(): string { return 'Delete Selected Product(s)'; } /* #endregion */ /* #region private methods */ private updateCheckBoxMatIcon(): void { if (this.isCheckAll) { this.checkBoxMatIcon = 'check_box'; } else { this.checkBoxMatIcon = 'check_box_outline_blank'; } } /* #endregion */ public initializeForCustomerFuzzySearch(): void { this.billForm .get('customer') .valueChanges .pipe( debounceTime(300), tap(() => this.isFuzzyLoading = true), switchMap(value => this.customerService.getCustomerFuzzy('%' + value + '%') .pipe( finalize(() => this.isFuzzyLoading = false), ) ) ) .subscribe(customerList => { this.customerList = customerList; }); } public displayFn(user: any): string { if (user) { return user.name; } return ''; } } <file_sep>/src/app/components/bill-panel/bill-panel.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { BillPanelComponent } from './bill-panel.component'; describe('BillPanelComponent', () => { let component: BillPanelComponent; let fixture: ComponentFixture<BillPanelComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ BillPanelComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(BillPanelComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/src/app/service/auth.service.ts import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { ApiService } from './api.service'; import { EnvironmentService } from './environment.service'; import { AuthAPIName, MSName } from '../utils/billing-constants'; @Injectable({ providedIn: 'root' }) export class AuthService { constructor( private apiService: ApiService, private environmentService: EnvironmentService) { } public login(credentials): Observable<any> { return this.apiService.post( this.environmentService.getUrl(MSName.API_AUTH, 'SignIn'), credentials); } } <file_sep>/src/app/service/customer.service.ts import { Injectable } from '@angular/core'; import { ApiService } from './api.service'; import { Observable } from 'rxjs'; import { EnvironmentService } from './environment.service'; import { MSName, CustomerAPIName } from '../utils/billing-constants'; import { CustomerRequest } from '../model/customer-request'; import { Customer } from '../model/customer.model'; @Injectable({ providedIn: 'root' }) export class CustomerService { constructor(private apiService: ApiService, private environmentService: EnvironmentService) { } public getCustomers(customerSearchRequest: CustomerRequest): Observable<Customer[]> { return this.apiService.post(this.getUrl(CustomerAPIName.SEARCH), customerSearchRequest); } public getCustomerFuzzy(customerName: string): Observable<Customer[]> { return this.apiService.post(this.getUrl(CustomerAPIName.FUZZY), customerName); } public saveCustomer(customer: Customer): Observable<Customer> { return this.apiService.post(this.getUrl(CustomerAPIName.SAVE), customer); } private getUrl(apiName: string): string { return this.environmentService.getUrl(MSName.CUSTOMER_MS, apiName); } } <file_sep>/src/app/service/shared.service.ts import { Injectable } from '@angular/core'; import { Customer } from '../model/customer.model'; import { MatSnackBar } from '@angular/material'; @Injectable({ providedIn: 'root' }) export class SharedService { constructor(private snackBar: MatSnackBar) { } public getCustomersList(): Customer[] { const cutomers = []; const customer = new Customer(); cutomers.push(customer); customer.name = 'not not'; for (let i = 1; i < 4; i++) { cutomers.push(new Customer()); } return cutomers; } public openMatSnackBar(msg: any): void { this.snackBar.open(msg, null, { duration: 2000, }); } } <file_sep>/src/app/components/user-registration/user-registration.component.ts import { Component, OnInit, Inject } from '@angular/core'; import { Validators, FormBuilder } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { CustomerRegistrationComponent } from '../customer-registration/customer-registration.component'; import { UserService } from 'src/app/service/user.service'; import { SharedService } from 'src/app/service/shared.service'; import { UserRole } from 'src/app/utils/billing-constants'; @Component({ selector: 'app-user-registration', templateUrl: './user-registration.component.html', styleUrls: ['./user-registration.component.css'] }) export class UserRegistrationComponent implements OnInit { userForm = this.fb.group( { name: [null, Validators.required], userName: [null, Validators.required], role: [null, Validators.required], password: [null, Validators.required] } ); public UserRole = UserRole; constructor( public dialogRef: MatDialogRef<CustomerRegistrationComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private fb: FormBuilder, private userService: UserService, private sharedService: SharedService ) { this.userRoleControl.setValue(UserRole.EMPLOYEE); } ngOnInit() { this.userRoleControl.setValue(UserRole.EMPLOYEE); } get userRoleControl() { return this.userForm.get('role'); } onSubmit(): void { if (this.userForm.valid) { this.userService.saveUser(this.userForm.value).subscribe(result => { this.sharedService.openMatSnackBar(result.message); this.dialogRef.close(true); }, error => { this.sharedService.openMatSnackBar('Error occured'); }); } else { this.userForm.markAllAsTouched(); } } onNoClick(): void { this.sharedService.openMatSnackBar('Cancelled'); this.dialogRef.close(false); } get customerTypeControl() { return this.userForm.get('customerType'); } onRoleToggle() { const customerType = this.customerTypeControl.value === UserRole.ADMIN ? UserRole.EMPLOYEE : UserRole.ADMIN; this.customerTypeControl.setValue(customerType); } } <file_sep>/src/app/model/table-column.config.ts export class TableColumn { accessVariableName: string; columnDisplayName: string; type: string; searchValue: string; searchType: string; searchData: string; icon: string; } <file_sep>/src/app/service/api.service.ts import { Injectable } from '@angular/core'; import { HttpHeaders, HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApiService { httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; constructor(private http: HttpClient) { } public post(postUrl: string, obj: any): Observable<any> { return this.http.post<any>(postUrl, obj); } public put(putUrl: string, obj: any): Observable<any> { return this.http.put<any>(putUrl, obj); } public get(getUrl: string): Observable<any> { return this.http.get<any>(getUrl); } public addRequestParam(url: string, key: string, value: string): string { return url + '?' + key + '=' + value; } } <file_sep>/src/app/core/mat-generic-grid/mat-generic-grid.component.ts import { Component, OnInit, Input, HostListener, AfterViewInit, ViewChild, Output, EventEmitter } from '@angular/core'; import { GridConfig } from 'src/app/model/generic-grid.config'; import { TableColumn } from 'src/app/model/table-column.config'; import { UtilityService } from 'src/app/service/utility.service'; import { MatTableDataSource, MatPaginator } from '@angular/material'; @Component({ selector: 'app-mat-generic-grid', templateUrl: './mat-generic-grid.component.html', styleUrls: ['./mat-generic-grid.component.css'] }) export class GenericGridComponent implements OnInit { @Input() gridConfig: GridConfig; @Input() dataSource: MatTableDataSource<any>; @Output() clickOfIconButton = new EventEmitter(); @Output() clickOfLinkButton = new EventEmitter(); @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator; displayedColumns: string[]; dSCopy: any[]; public isShowFormField: boolean; constructor(private utilityService: UtilityService) { } ngOnInit() { this.displayedColumns = []; this.gridConfig.columns.forEach(element => { this.displayedColumns.push(element.accessVariableName); }); this.onResize(null); } @HostListener('window:resize', ['$event']) onResize(event) { this.isShowFormField = window.innerWidth > 1330; } public onSearchOfFilter(column: TableColumn): void { const filterValue = (event.target as HTMLInputElement).value; this.dataSource.filter = filterValue.trim().toLowerCase(); if (this.dataSource.paginator) { this.dataSource.paginator.firstPage(); } } public onClickOfIconButton(column: TableColumn, value: any): void { this.clickOfIconButton.emit({ '{key}': column.accessVariableName, '{value}': value }); } public onClickOfLinknButton(column: TableColumn, value: any): void { this.clickOfLinkButton.emit({ '{key}': column.accessVariableName, '{value}': value }); } } <file_sep>/src/app/model/product.model.ts export class Product { description: string; hsnCode: string; quantity: number; rate: number; taxPercentage: number; discount: number; perValue: string; isSelected: boolean; } <file_sep>/src/app/model/generic-grid.config.ts import { TableColumn } from './table-column.config'; export class GridConfig { columns: TableColumn[]; caption: string; uniqueName: string; isPaginationRequired: boolean; paginationOptions: number[]; } <file_sep>/src/app/model/user-search-request.ts export class UserSearchRequest { userRole: string; } <file_sep>/src/app/components/app-main-nav/app-main-nav.component.ts import { Component } from '@angular/core'; import { TokenStorageService } from 'src/app/service/token-storage.service'; import { Router } from '@angular/router'; import { UserRole, URLS } from 'src/app/utils/billing-constants'; @Component({ selector: 'app-main-nav', templateUrl: './app-main-nav.component.html', styleUrls: ['./app-main-nav.component.css'] }) export class AppMainNavComponent { constructor( private tokenStorageService: TokenStorageService, private router: Router ) { if (!this.isLoggedIn) { this.router.navigateByUrl(URLS.LOGIN); } } logout() { this.tokenStorageService.signOut(); window.location.reload(); } get isLoggedIn() { return !!this.tokenStorageService.getToken(); } get isAdmin() { return this.tokenStorageService.getUser().role === UserRole.ADMIN; } } <file_sep>/src/app/model/customer-request.ts import { CustomerType } from '../utils/billing-constants'; export class CustomerRequest { customerType: string; constructor() { this.customerType = CustomerType.BOTH; } } <file_sep>/src/app/model/search-bill-response.ts export class SearchBillResponse { id: number; customerName: string; place: string; invoice: string; date: string; invoiceAmount: string; userName: string; } <file_sep>/src/app/core/input-dropdown/input-dropdown.component.ts import { Component, OnInit, Input, Output, HostListener, ElementRef } from '@angular/core'; import { EventEmitter } from '@angular/core'; import { ApiService } from 'src/app/service/api.service'; import { EnvironmentService } from 'src/app/service/environment.service'; @Component({ selector: 'app-input-dropdown', templateUrl: './input-dropdown.component.html', }) export class InputDropdownComponent implements OnInit { @Input() inputDropDownConfig: InputDropDownConfig; @Output() clickOnConfirm = new EventEmitter(); list = []; inputValue: string; valueToEmit: any; constructor( private apiService: ApiService, private environmentService: EnvironmentService, private elementRef: ElementRef ) { this.inputValue = ''; } ngOnInit() { } onClickOfItem(item) { this.inputValue = item[this.inputDropDownConfig.displayVariableName]; this.valueToEmit = item; this.list = []; } emit() { this.clickOnConfirm.emit(this.valueToEmit); } changeOnInputTextM() { this.apiService.post(this.environmentService .getUrl(this.inputDropDownConfig.msName, this.inputDropDownConfig.apiName) , this.inputValue).subscribe(e => { if (e && e.length !== 0) { this.list = e; } else { this.list = []; } }); } @HostListener('document:click', ['$event.target']) public onClick(target) { const clickedInside = this.elementRef.nativeElement.contains(target); if (!clickedInside) { this.list = []; } } } class InputDropDownConfig { placeHolder: string; displayVariableName: string; msName: string; apiName: string; constructor( placeHolder: string, displayVariableName: string, msName: string, apiName: string, ) { this.placeHolder = placeHolder; this.displayVariableName = displayVariableName; this.msName = msName; this.apiName = apiName; } } <file_sep>/src/app/service/user.service.ts import { Injectable } from '@angular/core'; import { EnvironmentService } from './environment.service'; import { ApiService } from './api.service'; import { Observable } from 'rxjs'; import { UserAPIName, MSName } from '../utils/billing-constants'; import { UserSearchRequest } from '../model/user-search-request'; import { User } from '../model/user.model'; @Injectable({ providedIn: 'root' }) export class UserService { constructor( private apiService: ApiService, private environmentService: EnvironmentService ) { } public saveUser(user: User) { return this.apiService.post(this.getUrl(UserAPIName.SAVE), user); } public getAllUsers(userRequest: UserSearchRequest): Observable<any> { return this.apiService.post(this.getUrl(UserAPIName.SEARCH), userRequest); } public getUrl(apiName: string): string { return this.environmentService.getUrl(MSName.USER_MS, apiName); } } <file_sep>/src/app/service/environment.service.ts import { Injectable } from '@angular/core'; import { ENV_LOCAL } from 'src/environments/environment-local'; import { Environment } from '../../environments/environtment-base'; @Injectable({ providedIn: 'root' }) export class EnvironmentService { env = 'local'; environments: Environment[]; environment: Environment; constructor() { this.environments = [ ENV_LOCAL ]; this.environment = this.environments.find(env => { return env.env === this.env; }); } public getUrl(msName: string, apiName: string): string { const microService = this.environment.msPoints.find(ms => ms.msName === msName); return this.environment.dns + this.environment.baseUrl + microService.basePath + microService.endPoints.find(endPoint => endPoint.apiName === apiName).path; } } <file_sep>/src/app/config/generic-table-config/bill-table-config.ts import { GridConfig } from 'src/app/model/generic-grid.config'; import { TableColumn } from 'src/app/model/table-column.config'; export function BillTableConfig(): GridConfig { const gridConfig = new GridConfig(); gridConfig.caption = 'View Bill'; gridConfig.uniqueName = 'BILL_TABLE_CONFIG'; gridConfig.isPaginationRequired = true; gridConfig.paginationOptions = [5, 10, 15, 20]; const taleColumns = []; const customerNameColumn = new TableColumn(); customerNameColumn.accessVariableName = 'customerName'; customerNameColumn.columnDisplayName = 'Customer Name'; customerNameColumn.type = 'text'; taleColumns.push(customerNameColumn); const placeColumn = new TableColumn(); placeColumn.accessVariableName = 'place'; placeColumn.columnDisplayName = 'Place'; placeColumn.type = 'text'; taleColumns.push(placeColumn); const invoiceColumn = new TableColumn(); invoiceColumn.accessVariableName = 'invoice'; invoiceColumn.columnDisplayName = 'Invoice'; invoiceColumn.type = 'text'; taleColumns.push(invoiceColumn); const dateColumn = new TableColumn(); dateColumn.accessVariableName = 'date'; dateColumn.columnDisplayName = 'Date'; dateColumn.type = 'text'; taleColumns.push(dateColumn); const invoiceAmountColumn = new TableColumn(); invoiceAmountColumn.accessVariableName = 'invoiceAmount'; invoiceAmountColumn.columnDisplayName = 'Invoice Amount'; invoiceAmountColumn.type = 'text'; invoiceAmountColumn.searchType = 'text'; taleColumns.push(invoiceAmountColumn); const userName = new TableColumn(); userName.accessVariableName = 'userName'; userName.columnDisplayName = '<NAME>'; userName.type = 'text'; taleColumns.push(userName); const editIcon = new TableColumn(); editIcon.accessVariableName = 'editIconButton'; editIcon.type = 'icon_button'; editIcon.icon = 'edit'; taleColumns.push(editIcon); gridConfig.columns = taleColumns; return gridConfig; } <file_sep>/src/app/utils/billing-constants.ts export class BillingConstants { public static get ADD_PRODUCT_BUTTON_TOOLTIP(): string { return 'Add Product'; } public static get DELETE_SELECTED_PRODUCT_BUTTON_TOOLTIP(): string { return 'Delete Selected Product(s)'; } } export class URLS { public static BILL_PANEL = 'bill-panel'; public static CUSTOMER_PANEL = 'customer-panel'; public static USER_PANEL = 'user-panel'; public static LOGIN = 'login'; } export class CustomerType { public static GST = 'GST'; public static NON_GST = 'NON_GST'; public static BOTH = 'BOTH'; } export class UserRole { public static ADMIN = 'ADMIN'; public static EMPLOYEE = 'EMPLOYEE'; public static BOTH = 'BOTH'; } export class BillType { public static GST = 'GST'; public static NON_GST = 'NON_GST'; } export class MSName { public static BILL_MS = 'Bill-MS'; public static CUSTOMER_MS = 'Customer-MS'; public static USER_MS = 'User-MS'; public static API_AUTH = 'API-AUTH'; } export class UserAPIName { public static SAVE = 'Save'; public static UPDATE = 'Update'; public static SEARCH = 'Search'; public static DELETE = 'Delete'; } export class AuthAPIName { public static SIGN_IN = 'SignIn'; public static LOGIN = 'Update'; } export class BillAPIName { public static SAVE = 'Save'; public static UPDATE = 'Update'; public static SEARCH = 'Search'; public static DELETE = 'Delete'; } export class CustomerAPIName { public static SAVE = 'Save'; public static UPDATE = 'Update'; public static SEARCH = 'Search'; public static DELETE = 'Delete'; public static FUZZY = 'Fuzzy'; } <file_sep>/src/app/config/generic-table-config/customer-table-config.ts import { GridConfig } from 'src/app/model/generic-grid.config'; import { TableColumn } from 'src/app/model/table-column.config'; export function CustomerTableConfig(): GridConfig { const gridConfig = new GridConfig(); gridConfig.caption = 'Customer Details'; gridConfig.uniqueName = 'CUSTOMER_TABLE_CONFIG'; gridConfig.isPaginationRequired = true; gridConfig.paginationOptions = [5, 10, 15, 20]; const taleColumns = []; const nameColumn = new TableColumn(); nameColumn.accessVariableName = 'name'; nameColumn.columnDisplayName = 'Name'; nameColumn.type = 'text'; nameColumn.searchType = 'text'; taleColumns.push(nameColumn); const phoneColumn = new TableColumn(); phoneColumn.accessVariableName = 'phoneNumber'; phoneColumn.columnDisplayName = 'Phone Number'; phoneColumn.type = 'text'; phoneColumn.searchType = 'text'; taleColumns.push(phoneColumn); const gstNo = new TableColumn(); gstNo.accessVariableName = 'gstNo'; gstNo.columnDisplayName = 'GST No.'; gstNo.type = 'text'; gstNo.searchType = 'text'; taleColumns.push(gstNo); const streetAddress = new TableColumn(); streetAddress.accessVariableName = 'street'; streetAddress.columnDisplayName = 'Street'; streetAddress.type = 'text'; streetAddress.searchType = 'text'; taleColumns.push(streetAddress); const city = new TableColumn(); city.accessVariableName = 'city'; city.columnDisplayName = 'City'; city.type = 'text'; city.searchType = 'text'; taleColumns.push(city); const state = new TableColumn(); state.accessVariableName = 'state'; state.columnDisplayName = 'State'; state.type = 'text'; state.searchType = 'text'; taleColumns.push(state); const zipCode = new TableColumn(); zipCode.accessVariableName = 'zipCode'; zipCode.columnDisplayName = 'ZIP Code'; zipCode.type = 'text'; zipCode.searchType = 'text'; taleColumns.push(zipCode); gridConfig.columns = taleColumns; return gridConfig; } <file_sep>/src/app/model/bill.model.ts import { Product } from './product.model'; export class Bill extends Base { id: number; @JsonIgnore checkBox: boolean; invoiceName: string; creationDate: string; products: Array<Product>; userId: number; customerId: number; billType: string; } <file_sep>/src/app/model/search-bill-request.ts export class SearchBillRequest { isAllBillRequest: boolean; startDate: string; endDate: string; } <file_sep>/src/app/components/login/login.component.ts import { Component, OnInit, HostListener, ElementRef } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { AuthService } from 'src/app/service/auth.service'; import { TokenStorageService } from 'src/app/service/token-storage.service'; import { MatSnackBar } from '@angular/material'; import { SharedService } from 'src/app/service/shared.service'; import { UtilityService } from 'src/app/service/utility.service'; import { LoginResponse } from 'src/app/model/LoginResponse'; import { URLS } from 'src/app/utils/billing-constants'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { loginForm = this.fb.group({ userName: [null, Validators.required], password: [null, Validators.required] }); isLoggedIn: boolean; constructor( private fb: FormBuilder, private router: Router, private authService: AuthService, private tokenStorage: TokenStorageService, private sharedService: SharedService, private utilityService: UtilityService) { if (!this.utilityService.isNullOrUndefined(this.tokenStorage.getUser())) { this.isLoggedIn = true; this.router.navigateByUrl(URLS.BILL_PANEL); } } ngOnInit(): void { this.loginForm.reset(); } onSubmit() { if (this.loginForm.invalid) { this.loginForm.markAllAsTouched(); } else { this.authService.login(this.loginForm.value).subscribe( (loginResponse: LoginResponse) => { this.tokenStorage.saveToken(loginResponse.token); this.tokenStorage.saveUser(loginResponse.user); this.isLoggedIn = true; this.sharedService.openMatSnackBar('Welcome ' + loginResponse.user.name + ' !!!'); this.reloadPage(); }, err => { this.sharedService.openMatSnackBar(err.error.message); } ); } } reloadPage() { this.router.navigateByUrl(URLS.BILL_PANEL); } } <file_sep>/src/app/service/billing.service.ts import { Injectable } from '@angular/core'; import { Bill } from '../model/bill.model'; import { Observable } from 'rxjs'; import { EnvironmentService } from './environment.service'; import { ApiService } from './api.service'; import { MSName, BillAPIName } from '../utils/billing-constants'; import { SearchBillRequest } from '../model/search-bill-request'; import { ApiResponse } from '../model/api-response'; @Injectable({ providedIn: 'root' }) export class BillingService { constructor( private apiService: ApiService, private environmentService: EnvironmentService ) { } public saveBill(bill: Bill): Observable<Bill> { return this.apiService.post(this.getUrl(BillAPIName.SAVE), bill); } public updateBill(bill: Bill): Observable<Bill> { return this.apiService.put(this.getUrl(BillAPIName.UPDATE), bill); } public searchBills(request: SearchBillRequest): Observable<ApiResponse> { return this.apiService.post(this.getUrl(BillAPIName.SEARCH), request); } private getUrl(apiName: string): string { return this.environmentService.getUrl(MSName.BILL_MS, apiName); } }
2ea50e663110d35f30164193f18a5c19ce7a6952
[ "TypeScript" ]
40
TypeScript
balaji043/Billing-Angular
f9672751a5292cfe3f95fbb3299b4aa53b51bdb3
62a7e2a90eeafb84e2e3bb2b71efd1e721bf6e65
refs/heads/master
<repo_name>MendozaWeb/CrudPHP<file_sep>/CrudPOO/controllers/controllerActions.php <?php declare (strict_types = 1); // Si no se ha enviado nada por el POST y se intenta acceder al archivo se retornará a la página de inicio if ($_POST) { require_once '../models/Personas.php'; $persona = new Personas(); $opcion = $_POST['opcion']; $id = intval($_POST['id']); $nombre = $_POST['nombre']; $pais = $_POST['pais']; $edad = $_POST['edad']; if (!empty($opcion)) { switch ($opcion) { case 'insertar': if (!empty($nombre) && !empty($pais) && !empty($edad)) { $persona->insert($nombre, $pais, $edad); } else { echo 'VACIO'; } break; case 'editar': if (!empty($id) && !empty($nombre) && !empty($pais) && !empty($edad)) { $persona->edit($id, $nombre, $pais, $edad); } else { echo 'VACIO'; } break; case 'eliminar': if (!empty($id)) { $persona->delete($id); } else { echo 'VACIO'; } break; } } else { echo $opcion; } } else { // Retornar header('Location:../'); } <file_sep>/CrudPOO/controllers/controllerList.php <?php declare (strict_types = 1); // Si no se ha enviado nada por el POST y se intenta acceder al archivo se retornará a la página de inicio if ($_POST) { require_once '../models/Personas.php'; $persona = new Personas(); $data = array(); // Paginación $paginacion = array(); // Para versiones de PHP inferiores a la 7 // $pagina = isset($_POST['pagina']) ? $_POST['pagina'] : 1; $pagina = $_POST['pagina'] ?? 1; // Para versiones de PHP inferiores a la 7 // $termino = isset($_POST['termino']) ? $_POST['termino'] : ''; $termino = $_POST['termino'] ?? ''; $paginacion = $persona->getPagination(); $filasTotal = $paginacion['filasTotal']; $filasPagina = $paginacion['filasPagina']; $empezarDesde = ($pagina - 1) * $filasPagina; if ($termino != '') { $data = $persona->getSearch($termino); } else { $data = $persona->getAll($empezarDesde, $filasPagina); } echo $persona->showTable($data); } else { // Retornar a inicio header('Location:../'); } <file_sep>/CrudPOO/script.sql /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Volcando estructura de base de datos para personas CREATE DATABASE IF NOT EXISTS `personas` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `personas`; -- Volcando estructura para tabla personas.informacion CREATE TABLE IF NOT EXISTS `informacion` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(50) NOT NULL DEFAULT '0', `pais` varchar(50) NOT NULL DEFAULT '0', `edad` varchar(50) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8; -- Volcando datos para la tabla personas.informacion: ~20 rows (aproximadamente) /*!40000 ALTER TABLE `informacion` DISABLE KEYS */; INSERT INTO `informacion` (`id`, `nombre`, `pais`, `edad`) VALUES (3, 'Esteban', 'Chile', '32'), (4, 'Carlos', 'Ecuador', '20'), (5, 'Manuel', 'Argentina', '18'), (6, 'María', 'Uruguay', '45'), (7, 'Mónica', 'Costa Rica', '19'), (8, 'Gabriela', 'Nicaragua', '28'), (9, '<NAME>', 'Colombia', '19'), (10, 'Viviana', 'Perú', '27'), (11, 'Julián', 'Colombia', '15'), (12, 'Natalia', 'Ecuador', '25'), (13, 'Eva', 'USA', '36'), (14, 'Sandra', 'Chile', '15'), (15, 'Luis', 'Panamá', '21'), (16, 'Mauro', 'Perú', '26'), (17, '<NAME>', 'Venezuela', '35'), (18, '<NAME>', 'México', '21'), (19, 'Joseling', 'Nicaragüa', '22'), (20, 'Bernardo', 'Colombia', '24'), (21, 'Ignacio', 'Panamá', '45'), (23, 'Paulina', 'Colombia', '24'); /*!40000 ALTER TABLE `informacion` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; <file_sep>/CrudPOO/js/main.js $(function() { var input_busqueda = $('#txt_busqueda'); listar(''); tipoListado(input_busqueda); crearPaginacion(); ejecutarAccion(); }); // Quitar la alerta del Modal var quitarAlerta = () => { $('#alerta').html(''); } // Limpiar el cuadro de búsqueda var limpiarBusqueda = () => { $('#txt_busqueda').val(''); } // Desbloquear el botón 'Guardar Cambios' var desbloquearBoton = () => { $('#btn_guardar_cambios').removeAttr('disabled'); } // Mostrar una alerta de acuerdo a la respuesta del servidor var alerta = (opcion, respuesta) => { let mensaje = ''; switch (opcion) { case 'insertar': mensaje = 'Usuario insertado correctamente.'; break; case 'editar': mensaje = 'Información de usuario modificada con exito.'; break; case 'eliminar': mensaje = 'Usuario eliminado exitosamente.'; break; } switch (respuesta) { case 'BIEN': $('#alerta').html('<div class="alert alert-success text-center"><strong>¡BIEN! </strong>' + mensaje + '</div>'); break; case 'ERROR': $('#alerta').html('<div class="alert alert-danger text-center"><strong>¡ERROR! </strong>Solicitud no procesada.</div>'); break; case 'IGUAL': $('#alerta').html('<div class="alert alert-info text-center"><strong>¡ADVERTENCIA! </strong>Ha enviado los mismos datos.</div>'); break; case 'VACIO': $('#alerta').html('<div class="alert alert-danger text-center"><strong>¡ERROR! </strong>No puede enviar datos vacíos.</div>'); break; } } // ----------------------------------------------------Ejecutar la acción seleccionada por el usuario---------------------------------------------------- var ejecutarAccion = () => { $('#btn_guardar_cambios').on('click', function() { let opcion = $('#opcion').val(); let id = $('#id').val(); let nombre = $('#txt_nombre').val(); let pais = $('#txt_pais').val(); let edad = $('#txt_edad').val(); $.ajax({ beforeSend: function() { $('#gif').toggleClass('d-none'); }, url: 'controllers/controllerActions.php', method: 'POST', data: { opcion: opcion, id: id, nombre: nombre, pais: pais, edad: edad }, }).done(function(data) { $('#gif').toggleClass('d-none'); alerta(opcion, data); listar(''); crearPaginacion(); if (opcion == 'eliminar' && data == 'BIEN') { $('#btn_guardar_cambios').attr('disabled', true); } if (opcion == 'insertar' && data == 'BIEN') { $('#id').val(''); $('#txt_nombre').val(''); $('#txt_pais').val(''); $('#txt_edad').val(''); } }); }); } // -------------------------------------------------------------------Preparar datos------------------------------------------------------------------- var prepararDatos = () => { let values = []; // Evento botón editar $('#table .editar').on('click', function() { values = ciclo($(this)); $('#opcion').val('editar'); $('#id').val(values[0]); $('#txt_nombre').val(values[1]).removeAttr('disabled'); $('#txt_pais').val(values[2]).removeAttr('disabled'); $('#txt_edad').val(values[3]).removeAttr('disabled'); cambiarTitulo('Editar información'); quitarAlerta(); limpiarBusqueda(); desbloquearBoton(); }); // Evento botón eliminar $('#table .eliminar').on('click', function() { values = ciclo($(this)); $('#opcion').val('eliminar'); $('#id').val(values[0]); $('#txt_nombre').val(values[1]).attr('disabled', true); $('#txt_pais').val(values[2]).attr('disabled', true); $('#txt_edad').val(values[3]).attr('disabled', true); cambiarTitulo('Eliminar usuario'); quitarAlerta(); limpiarBusqueda(); desbloquearBoton(); }); // Evento btotón insertar $('#btn_insertar').on('click', function() { $('#opcion').val('insertar'); $('#id').val(''); $('#txt_nombre').val('').removeAttr('disabled'); $('#txt_pais').val('').removeAttr('disabled'); $('#txt_edad').val('').removeAttr('disabled'); cambiarTitulo('Insertar usuario'); quitarAlerta(); limpiarBusqueda(); desbloquearBoton(); }); } var ciclo = (selector) => { let datos = []; $(selector).parents('tr').find('td').each(function(i) { if (i < 4) { datos[i] = $(this).text(); } else { return false; } }); return datos; } var cambiarTitulo = (titulo) => { $('.modal-header .modal-title').text(titulo); } // --------------------------------------------------------------------------Paginación-------------------------------------------------------------------------- var cambiarPagina = () => { $('.page-item>.page-link').on('click', function() { $.ajax({ url: 'controllers/controllerList.php', method: 'POST', data: { pagina: $(this).text() }, }).done(function(data) { $('#div_tabla').html(data); prepararDatos(); }); }); } var crearPaginacion = () => { $.ajax({ url: 'controllers/controllerPagination.php', method: 'POST' }).done(function(data) { $('#pagination li').remove(); for (var i = 1; i <= data; i++) { $('#pagination').append('<li class="page-item"><a class="page-link text-muted" href="#">' + i + '</a></li>'); } cambiarPagina(); }); } // ---------------------------------------------------Listar personas--------------------------------------------------- var listar = (param) => { $.ajax({ url: 'controllers/controllerList.php', method: 'POST', data: { termino: param } }).done(function(data) { $('#div_tabla').html(data); prepararDatos(); }); } var tipoListado = (input) => { $(input).on('keyup', function() { let termino = ''; if ($(this).val() != '') { termino = $(this).val(); } listar(termino); }); }<file_sep>/CrudPOO/controllers/controllerPagination.php <?php // Si no se ha enviado una petición mediante AJAX se retornará a página inicio if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { require_once '../models/Personas.php'; $persona = new Personas(); $paginacion = array(); $paginacion = $persona->getPagination(); echo ceil($paginacion['filasTotal'] / $paginacion['filasPagina']); } else { header('Location:../'); } <file_sep>/CrudPOO/models/Personas.php <?php declare (strict_types = 1); require_once 'Conexion.php'; class Personas extends Conexion { public function __construct() { parent::__construct(); } public function insert(string $nombre, string $pais, string $edad) { error_reporting(0); try { $query = "INSERT INTO informacion VALUES (null,:nombre,:pais,:edad) ;"; $result = $this->db->prepare($query); $result->execute(array(':nombre' => $nombre, ':pais' => $pais, ':edad' => $edad)); echo 'BIEN'; } catch (PDOException $e) { echo 'ERROR'; } } public function delete(int $id) { error_reporting(0); try { $query = "DELETE FROM informacion WHERE id=:id;"; $result = $this->db->prepare($query); $result->execute(array(':id' => $id)); echo 'BIEN'; } catch (PDOException $e) { echo 'ERROR'; } } public function edit(int $id, string $nombre, string $pais, string $edad) { error_reporting(0); try { $query = "UPDATE informacion SET nombre=:nombre,pais=:pais,edad=:edad WHERE id=:id;"; $result = $this->db->prepare($query); $result->execute(array(':id' => $id, ':nombre' => $nombre, ':pais' => $pais, ':edad' => $edad)); if ($result->rowCount()) { echo 'BIEN'; } else { echo 'IGUAL'; } } catch (PDOException $e) { echo 'ERROR'; } } public function getAll(int $desde, int $filas): array { $query = "SELECT * FROM informacion ORDER BY nombre LIMIT {$desde},{$filas}"; return $this->ConsultaSimple($query); } public function getSearch(string $termino): array { $where = "WHERE nombre LIKE :nombre || pais LIKE :pais ORDER BY nombre ASC"; $array = array(':nombre' => '%' . $termino . '%', ':pais' => '%' . $termino . '%'); return $this->ConsultaCompleja($where, $array); } public function getPagination(): array { $query = "SELECT COUNT(*) FROM informacion;"; return array( 'filasTotal' => intval($this->db->query($query)->fetch(PDO::FETCH_BOTH)[0]), 'filasPagina' => 5, ); } public function showTable(array $array): string { $html = ''; if (count($array)) { $html = ' <table class="table table-striped" id="table"> <thead> <th class="d-none"></th> <th>NOMBRE</th> <th>PAÍS</th> <th>EDAD</th> <th>OPCIONES</th> </thead> <tbody> '; foreach ($array as $value) { $html .= ' <tr> <td class="d-none">' . $value['id'] . '</td> <td>' . $value['nombre'] . '</td> <td>' . $value['pais'] . '</td> <td>' . $value['edad'] . '</td> <td class="text-center"> <button title="Editar este usuario" class="editar btn btn-secondary" data-toggle="modal" data-target="#ventanaModal"> <i class="fa fa-pencil-square-o"></i> </button> <button title="Eliminar este usuario" type="button" class="eliminar btn btn-danger" data-toggle="modal" data-target="#ventanaModal"> <i class="fa fa-trash-o"></i> </button> </td> </tr> '; } $html .= ' </tbody> </table>'; } else { $html = '<h4 class="text-center">No hay datos...</h4>'; } return $html; } }
19f8bbd79e6cc6ad5b2d0025cc530967d5564f33
[ "JavaScript", "SQL", "PHP" ]
6
PHP
MendozaWeb/CrudPHP
d6701e3b8c564a134afb38f038303d5314fbda45
b97104859d279441bc63d9adbaac270c6f4da03d
refs/heads/master
<repo_name>mystic-cg/LeetCode<file_sep>/easy/0013_roman2integer.py #!/usr/bin/env python # -*- coding: utf-8 -*- def roman2int(roman: str) -> int: """ roman to integer :param roman: :return: """ roman_dict_common = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } roman_dict_unique = { "IV": 4, "IX": 9, "XL": 40, "XC": 90, "CD": 400, "CM": 900 } result = 0 for key, value in roman_dict_unique.items(): result += roman.count(key) * value roman = roman.replace(key, "") for key, value in roman_dict_common.items(): result += roman.count(key) * value return result if __name__ == '__main__': print(roman2int("MCMXCIX")) <file_sep>/README.md # Exercise on LeetCode<file_sep>/easy/0014_longest_common_prefix.py #!/usr/bin/env python # -*- coding: utf-8 -*- from typing import List def longest_common_prefix(strs: List[str]) -> str: """ find the longest common prefix ['find', 'fire', 'five'] -> 'fi' ['dog', 'flow', 'car'] -> '' :param strs: :return: """ if len(strs) >= 1: count = len(strs[0]) if count > 0: for val in strs[1:]: if strs[0][:count] != val[:count]: count -= 1 return strs[0][:count] # if len(strs) >= 1: # count = len(strs[0]) # lst_size = 1 # while count > 0 and lst_size < len(strs): # if strs[0][:count] == strs[lst_size][:count]: # lst_size += 1 # continue # else: # count -= 1 # return strs[0][:count] return "" if __name__ == '__main__': print(longest_common_prefix(['dog', 'flow', 'car'])) <file_sep>/easy/0001_2sum.py #!/usr/bin/env python # -*- coding: utf-8 -*- from typing import List def two_sum(nums: List[int], target: int) -> List[int]: """ two sum :param nums: :param target: :return: """ # Solution1: time complexity is too large # arr_len = len(nums) # for i in range(arr_len): # for j in range(i+1, arr_len): # if nums[i] + nums[j] == target: # return [i, j] # return [] # Solution2: # deduplicate arr_len = len(nums) # arr_set = [] # [arr_set.append(i) for i in nums if i not in arr_set] # if arr_len != len(arr_set): # raise Exception("Please ensure each element in list is unique.") temp = {} for i in range(arr_len): minus = target - nums[i] if minus not in temp: temp[nums[i]] = i continue return [temp[minus], i] return [] <file_sep>/medium/0002_add2numbers.py #!/usr/bin/env python # -*- coding: utf-8 -*- # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: @staticmethod def add2numbers(l1: ListNode, l2: ListNode) -> ListNode: root = ListNode((l1.val + l2.val) % 10) carry = (l1.val + l2.val) // 10 node = root while l1.next or l2.next: s = (l1.next.val if l1.next else 0) + (l2.next.val if l2.next else 0) + carry node.next = ListNode(s % 10) if l1.next: l1 = l1.next if l2.next: l2 = l2.next node = node.next carry = s // 10 if carry: node.next = ListNode(carry) return root if __name__ == '__main__': ln1 = ListNode(2) ln2 = ListNode(4) ln3 = ListNode(3) ln1.next = ln2 ln2.next = ln3 ln4 = ListNode(5) ln5 = ListNode(6) ln6 = ListNode(4) ln4.next = ln5 ln5.next = ln6 print(Solution().add2numbers(ln1, ln4))
f5067c942e7cf8bc6c97f5b4536dc1e98e4752bb
[ "Markdown", "Python" ]
5
Python
mystic-cg/LeetCode
1bc7be69012bd9233e5b3242f172c67ab44ebd52
350657e8d2adc96a85508cf0df48f32784771d61
refs/heads/master
<repo_name>Romankhom/goit-react-hw-05-phonebook<file_sep>/src/components/ContactForm/ContactForm.jsx import React, { PureComponent } from "react"; import InputTelMask from "react-input-mask"; import PropTypes from "prop-types"; import styles from "./ContactForm.module.css"; export default class ContactForm extends PureComponent { static propTypes = { onAddContact: PropTypes.func.isRequired }; state = { name: "", number: "" }; handleInput = e => { this.setState({ [e.target.name]: e.target.value }); }; handleSubmit = e => { e.preventDefault(); this.props.onAddContact({ ...this.state }); this.setState({ name: "", number: "" }); }; render() { const { name, number } = this.state; return ( <form className={styles.contactForm} onSubmit={this.handleSubmit}> <label>Name</label> <input type="text" className={styles.contactInput} name="name" value={name} onChange={this.handleInput} required /> <label>Phone number</label> <InputTelMask mask="999-99-99" type="tel" className={styles.contactInput} name="number" value={number} onChange={this.handleInput} placeholder="only numbers" required /> <input type="submit" className={styles.addButton} value="Add contact" /> </form> ); } } <file_sep>/src/components/App/App.js import React, { Component } from 'react'; import { CSSTransition } from 'react-transition-group'; import FormContacts from '../FormContacts/FormContacts'; import ContactsList from '../ContactsList/ContactsList'; import FilterContacts from '../FilterContacts/FilterContacts'; import styles from './App.module.css'; import slideTransition from '../../transitions/slide-500.module.css'; const filterContacts = (contacts, filter) => { return contacts.filter(contact => contact.name.toLowerCase().includes(filter.toLowerCase()), ); }; export default class App extends Component { state = { contacts: [ { id: 'id-1', name: '<NAME>', number: '459-12-56' }, { id: 'id-2', name: '<NAME>', number: '443-89-12' }, { id: 'id-3', name: '<NAME>', number: '645-17-79' }, { id: 'id-4', name: '<NAME>', number: '227-91-26' }, ], filter: '', isLoad: false, }; componentDidMount() { try { const localContacts = JSON.parse(localStorage.getItem('contacts')); if (localContacts) { this.setState({ contacts: localContacts, isLoad: true }); } } catch (err) { console.log(err); } } componentDidUpdate(prevProps, prevState) { const { contacts } = this.state; if (prevState.contacts !== contacts) { try { localStorage.setItem('contacts', JSON.stringify(contacts)); } catch (err) { console.log(err); } } } addNewContact = newContact => { this.setState(state => ({ contacts: [newContact, ...state.contacts] })); }; handleFilter = e => { this.setState({ filter: e.target.value }); }; handleDeleteContact = id => { const { contacts } = this.state; const filteredContacts = contacts.filter(contact => contact.id !== id); this.setState({ contacts: filteredContacts }); }; render() { const { contacts, filter, isLoad } = this.state; const filtredContacts = filterContacts(contacts, filter); return ( <div className={styles.main_wrapper}> <CSSTransition in={isLoad} timeout={500} classNames={slideTransition} unmountOnExit > <h1>Phonebook</h1> </CSSTransition> <FormContacts addNewContact={this.addNewContact} contacts={contacts} /> <h2>Contacts</h2> <FilterContacts filter={filter} handleFilter={this.handleFilter} /> <ContactsList contacts={filtredContacts} handleDeleteContact={this.handleDeleteContact} /> </div> ); } } <file_sep>/src/components/FilterContacts/FilterContacts.js import React from 'react'; import PropTypes from 'prop-types'; import styles from './FilterContacts.module.css'; const FilterContacts = ({ filter, handleFilter }) => ( <input type="text" value={filter} onChange={handleFilter} placeholder="Filter..." className={styles.contacts__filter} /> ); FilterContacts.propTypes = { filter: PropTypes.string.isRequired, handleFilter: PropTypes.func.isRequired, }; export default FilterContacts; <file_sep>/src/components/Title/Title.jsx import React from "react"; const Title = () => ( <div> <h1>Phonebook</h1> </div> ); export default Title; <file_sep>/src/components/Contact/Contact.js import React from 'react'; import PropTypes from 'prop-types'; import styles from './Contact.module.css'; const Contact = ({ name, number, handleDeleteContact }) => ( <> <p className={styles.item__name}>{name}</p> <div className={styles.item__right}> <p>{number}</p> <button type="button" onClick={handleDeleteContact} className={styles.item__button} /> </div> </> ); Contact.propTypes = { name: PropTypes.string.isRequired, number: PropTypes.string.isRequired, handleDeleteContact: PropTypes.func.isRequired, }; export default Contact; <file_sep>/src/components/ContactsList/ContactsList.js import React from 'react'; import PropTypes from 'prop-types'; import { CSSTransition, TransitionGroup } from 'react-transition-group'; import Contact from '../Contact/Contact'; import styles from './ContactsList.module.css'; import slideTransition from '../../transitions/slide-250.module.css'; const ContactsList = ({ contacts, handleDeleteContact }) => ( <TransitionGroup component="ul" className={styles.contacts__list}> {contacts.map(contact => ( <CSSTransition key={contact.id} timeout={250} classNames={slideTransition} > <li className={styles.list__items}> <Contact name={contact.name} number={contact.number} handleDeleteContact={() => handleDeleteContact(contact.id)} /> </li> </CSSTransition> ))} </TransitionGroup> ); ContactsList.propTypes = { contacts: PropTypes.arrayOf(PropTypes.shape().isRequired).isRequired, handleDeleteContact: PropTypes.func.isRequired, }; export default ContactsList; <file_sep>/src/components/FormContacts/FormContacts.js import React, { Component } from 'react'; import { CSSTransition } from 'react-transition-group'; import PropTypes from 'prop-types'; import shortid from 'shortid'; import styles from './FormContacts.module.css'; import slideTransition from '../../transitions/slide-250.module.css'; import Message from '../Message/Message'; export default class FormContacts extends Component { static propTypes = { addNewContact: PropTypes.func.isRequired, contacts: PropTypes.arrayOf(PropTypes.shape().isRequired).isRequired, }; state = { name: '', number: '', showError: false, }; handleChangeName = e => { this.setState({ name: e.target.value }); }; handleChangeNumber = e => { this.setState({ number: e.target.value }); }; reset = () => { this.setState({ name: '', number: '' }); }; handleSubmit = e => { e.preventDefault(); const { name, number } = this.state; if (!name || !number) return; const sameContact = this.props.contacts.find( contact => contact.name === name, ); if (sameContact) { this.setState( prevState => ({ showError: !prevState.showError, }), () => setTimeout(() => { this.setState(prevState => ({ showError: !prevState.showError })); }, 2000), ); this.reset(); return; } const newContact = { name, number, id: shortid.generate(), }; this.props.addNewContact(newContact); this.reset(); }; render() { const { name, number, showError } = this.state; return ( <> <CSSTransition in={showError} timeout={250} classNames={slideTransition} unmountOnExit > <Message /> </CSSTransition> <form onSubmit={this.handleSubmit} className={styles.contacts__form}> <label htmlFor={shortid.generate()} className={styles.contacts__label} > Name <input type="text" value={name} onChange={this.handleChangeName} className={styles.contacts__input} /> </label> <label htmlFor={shortid.generate()} className={styles.contacts__label} > Number <input type="tel" value={number} onChange={this.handleChangeNumber} className={styles.contacts__input} /> </label> <button type="submit" className={styles.contacts__button}> Add contact </button> </form> </> ); } }
a49df8493623fe2d715d440e8e52c2fb7f473ba6
[ "JavaScript" ]
7
JavaScript
Romankhom/goit-react-hw-05-phonebook
00ae4bd69d78ebc049d1a819b66ba19687378d3a
870d2e87dc643f1541ef0449ee0a3b9a9a077c3e
refs/heads/teads
<file_sep>import {expect} from 'chai'; import {createElementWithAttributes} from '#core/dom'; import '../../../amp-story/1.0/amp-story'; import '../../../amp-story/1.0/amp-story-page'; import '../amp-story-shopping'; import '../../../amp-story-page-attachment/0.1/amp-story-page-attachment'; import {registerServiceBuilder} from '../../../../src/service-helpers'; import { Action, getStoreService, } from '../../../amp-story/1.0/amp-story-store-service'; describes.realWin( 'amp-story-shopping-attachment-v0.1', { amp: { runtimeOn: true, extensions: [ 'amp-story:1.0', 'amp-story-shopping:0.1', 'amp-story-page-attachment:0.1', ], }, }, (env) => { let win; let pageEl; let shoppingEl; let shoppingImpl; let storeService; beforeEach(async () => { win = env.win; storeService = getStoreService(win); registerServiceBuilder(win, 'performance', function () { return { isPerformanceTrackingOn: () => false, }; }); registerServiceBuilder(win, 'story-store', function () { return storeService; }); env.sandbox.stub(win.history, 'replaceState'); const story = win.document.createElement('amp-story'); win.document.body.appendChild(story); pageEl = win.document.createElement('amp-story-page'); pageEl.id = 'page1'; story.appendChild(pageEl); const tagEl = createElementWithAttributes( win.document, 'amp-story-shopping-tag', { 'layout': 'container', 'data-product-id': 'lamp', } ); pageEl.appendChild(tagEl); shoppingEl = win.document.createElement('amp-story-shopping-attachment'); pageEl.appendChild(shoppingEl); shoppingImpl = await shoppingEl.getImpl(); }); async function dispatchTestShoppingData() { const shoppingData = { 'lamp': { 'productId': 'lamp', 'productTitle': 'Brass Lamp', 'productBrand': 'Lamp Co', 'productPrice': 799.0, 'productPriceCurrency': 'USD', 'productImages': ['https://source.unsplash.com/Ry9WBo3qmoc/500x500'], }, }; storeService.dispatch(Action.CHANGE_PAGE, { id: 'page1', index: 1, }); storeService.dispatch(Action.ADD_SHOPPING_DATA, shoppingData); storeService.dispatch(Action.TOGGLE_PAGE_ATTACHMENT_STATE, true); } it('should build shopping attachment component', () => { expect(() => shoppingImpl.layoutCallback()).to.not.throw(); }); it('should build CTA with i18n shopping label text', async () => { await dispatchTestShoppingData(); const attachmentChildEl = shoppingEl.querySelector( 'amp-story-page-attachment' ); expect(attachmentChildEl.getAttribute('cta-text')).to.equal('Shop Now'); }); it('should open attachment', async () => { await dispatchTestShoppingData(); const attachmentChildEl = shoppingEl.querySelector( 'amp-story-page-attachment' ); const attachmentChildImpl = await attachmentChildEl.getImpl(); env.sandbox.stub(attachmentChildImpl, 'mutateElement').callsFake(() => { expect(pageEl.querySelector('.i-amphtml-story-draggable-drawer-open')) .to.not.be.null; }); }); it('should build PLP on CTA click', async () => { await dispatchTestShoppingData(); const attachmentChildEl = shoppingEl.querySelector( 'amp-story-page-attachment' ); const attachmentChildImpl = await attachmentChildEl.getImpl(); env.sandbox.stub(attachmentChildImpl, 'mutateElement').callsFake(() => { expect(pageEl.querySelector('.amp-story-shopping-plp')).to.not.be.null; }); }); it('should build PLP with data from tag on page', async () => { await dispatchTestShoppingData(); const attachmentChildEl = shoppingEl.querySelector( 'amp-story-page-attachment' ); const attachmentChildImpl = await attachmentChildEl.getImpl(); env.sandbox.stub(attachmentChildImpl, 'mutateElement').callsFake(() => { expect( pageEl.querySelector( '.amp-story-shopping-plp-card .amp-story-shopping-plp-card-title' ).textContent ).to.equal('Spectacular Spectacles'); }); }); } ); <file_sep>import {loadScript, validateData} from '#3p/3p'; /** * @param {!Window} global * @param {!Object} data */ export function teads(global, data) { /*eslint "local/camelcase": 0*/ global._teads_amp = { allowed_data: ['pid', 'tag'], mandatory_data: ['pid'], mandatory_tag_data: ['tta', 'ttp'], data, }; validateData( data, global._teads_amp.mandatory_data, global._teads_amp.allowed_data ); const QueryString = function () { // This function is anonymous, is executed immediately and // the return value is assigned to QueryString! const query_string = {} const a = document.createElement('a') a.href = global.context.sourceUrl const query = a.search.substring(1) const vars = query.split("&") for (var i = 0; i < vars.length; i++) { const pair = vars[i].split("=") // If first entry with this name if (typeof query_string[pair[0]] === "undefined") { query_string[pair[0]] = decodeURIComponent(pair[1]) // If second entry with this name } else if (typeof query_string[pair[0]] === "string") { const arr = [query_string[pair[0]], decodeURIComponent(pair[1])] query_string[pair[0]] = arr // If third or later entry with this name } else { query_string[pair[0]].push(decodeURIComponent(pair[1])) } } return query_string }() if ( QueryString.js || QueryString.second_asset_url || QueryString.pid || QueryString.page || QueryString.content ) { if (QueryString.tracking) { (global.teads || (global.teads = {})).TRACKING_URL = QueryString.tracking } // FOR-3052: Split teads-format into 2 assets if (QueryString.second_asset_url) { (global.teads || (global.teads = {})).FORMAT_WITH_PLAYER_URL = QueryString.second_asset_url } const ttag = () => { global.teads .ad(QueryString.pid || 47405, { type: 'VastUrl', content: QueryString.content || 'https://a.teads.tv/vast/preview/50221', settings: { values: { pageId: QueryString.page || 42266, placementId: QueryString.pid || 47405, adType: QueryString.adtype || 'video' }, components: { progressBar: QueryString.pb || false } }, headerBiddingProvider: 'debugFormat' }) .page(QueryString.page || 42266) .placement(QueryString.pid || 47405, { format: 'inread', slot: { selector: 'body' } }) .serve() } loadScript(global, `//${QueryString.js || 'a.teads.tv/media/format/v3/teads-format.min.js'}`, ttag) } else if (data.tag) { validateData(data.tag, global._teads_amp.mandatory_tag_data); global._tta = data.tag.tta; global._ttp = data.tag.ttp; loadScript( global, 'https://a.teads.tv/media/format/' + encodeURI(data.tag.js || 'v3/teads-format.min.js') ); } else { loadScript( global, 'https://a.teads.tv/page/' + encodeURIComponent(data.pid) + '/tag' ); } } <file_sep>#!/usr/bin/env bash set -xe # Install local teads-central (documented @ https://confluence.teads.net/display/INFRA/teads-central+documentation) curl -sL http://dl.teads.net/teads-central/get.sh | sh - cleanup () { trap '' INT; ./teads-central docker clean-tagged; } trap cleanup EXIT TERM trap true INT # common changes above this line should be done upstream # ########################################################## HASH=$(./teads-central vars hash) IMAGE=$(./teads-central vars image) # Make sure build dir is accessible from host chmod g+s . # Update from main amp html repository # currently the result is not pushed because it will trigger the same job, infinite ci loop git remote add upstream <EMAIL>:ampproject/amphtml.git || echo 'upstream already present' git fetch upstream git rebase upstream/main git submodule init git submodule update git submodule foreach git pull origin master rm -rf ./.git # remove 1GB to the docker image size git init # need a git initialized directory for being able to run node ./build-system/task-runner/install-amp-task-runner.js in docker container # Build docker build -t "${IMAGE}":"${HASH}" . <file_sep>FROM node:16.14.0 MAINTAINER Format team <<EMAIL>> ADD . /var/www WORKDIR /var/www RUN npm i RUN node ./build-system/task-runner/install-amp-task-runner.js EXPOSE 8000 CMD amp --fortesting <file_sep>/** * Use logger for intentionally logging messages in production code. */ export const logger = { info: console.info.bind(console), warn: console.warn.bind(console), error: console.error.bind(console), }; <file_sep>import * as Preact from '#core/dom/jsx'; import {Services} from '#service'; import * as remoteConfig from '../../../../examples/amp-story/shopping/remote.json'; import {Action} from '../../../amp-story/1.0/amp-story-store-service'; import { getShoppingConfig, storeShoppingConfig, } from '../amp-story-shopping-config'; describes.realWin( 'amp-story-shopping-config-v0.1', { amp: { runtimeOn: true, extensions: ['amp-story-shopping:0.1'], }, }, (env) => { let pageElement; const defaultInlineConfig = { items: [ { 'productId': 'city-pop', 'productTitle': 'Plastic Love', 'productPrice': 19, 'productPriceCurrency': 'JPY', }, ], }; const keyedDefaultInlineConfig = { 'city-pop': defaultInlineConfig.items[0], }; beforeEach(async () => { pageElement = <amp-story-page id="page1"></amp-story-page>; env.win.document.body.appendChild(pageElement); }); async function createAmpStoryShoppingConfig( src = null, config = defaultInlineConfig ) { pageElement.appendChild( <amp-story-shopping-config layout="nodisplay" src={src}> <script type="application/json">{JSON.stringify(config)}</script> </amp-story-shopping-config> ); return getShoppingConfig(pageElement); } it('throws on no config', async () => { expectAsyncConsoleError(async () => { expect(() => { pageElement.appendChild(<amp-story-shopping-config />); return getShoppingConfig(pageElement); }).to.throw(/<script> tag with type=\"application\/json\"​​​/); }); }); it('does use inline config', async () => { const result = await createAmpStoryShoppingConfig(); expect(result).to.deep.eql(keyedDefaultInlineConfig); }); it('does use remote config when src attribute is provided', async () => { const remoteUrl = 'https://foo.example'; const expectedRemoteResult = // matches remote.json { 'art': { 'productUrl': 'https://www.google.com', 'productId': 'art', 'productTitle': 'Abstract Art', 'productBrand': 'V. Artsy', 'productPrice': 1200.0, 'productPriceCurrency': 'JPY', 'productImages': [ '/examples/visual-tests/amp-story/img/shopping/shopping-product.jpg', ], 'aggregateRating': { 'ratingValue': '4.4', 'reviewCount': '89', 'reviewUrl': 'https://www.google.com', }, }, }; env.sandbox.stub(Services, 'xhrFor').returns({ fetchJson(url) { if (url === remoteUrl) { return Promise.resolve({ ok: true, json: () => remoteConfig, }); } }, }); const result = await createAmpStoryShoppingConfig(remoteUrl); expect(result).to.deep.eql(expectedRemoteResult); }); it('does use inline config when remote src is invalid', async () => { env.sandbox.stub(Services, 'xhrFor').returns({ fetchJson() { throw new Error(); }, }); const result = await createAmpStoryShoppingConfig('invalidRemoteUrl'); expect(result).to.deep.eql(keyedDefaultInlineConfig); }); describe('storeShoppingConfig', () => { let storeService; beforeEach(async () => { storeService = {dispatch: env.sandbox.spy()}; env.sandbox .stub(Services, 'storyStoreServiceForOrNull') .resolves(storeService); }); it('dispatches ADD_SHOPPING_DATA', async () => { const config = {foo: {bar: true}}; await storeShoppingConfig(pageElement, config); expect(storeService.dispatch.withArgs(Action.ADD_SHOPPING_DATA, config)) .to.have.been.calledOnce; }); }); } ); <file_sep>#!/usr/bin/env bash set -xe # common changes above this line should be done upstream # ########################################################## IMAGE=$(./teads-central vars image) ./teads-central docker tag-and-push --branch-tag --image "${IMAGE}" <file_sep>import {useCallback, useState} from '#preact'; import {logger} from '#preact/logger'; /** * @param {string} key * @param {*=} defaultValue * @return {{ "0": any, "1": function(any): void }} */ export function useLocalStorage(key, defaultValue = null) { // Keep track of the state locally: const [value, setValue] = useState(() => { try { const json = self.localStorage?.getItem(key); return json ? JSON.parse(json) : defaultValue; } catch (err) { // warning: could not read from local storage return defaultValue; } }); const storeValue = useCallback( (/** @type {any} */ newValue) => { try { const json = JSON.stringify(newValue); self.localStorage?.setItem(key, json); } catch (err) { logger.warn( 'useLocalStorage', 'Could not write value to local storage', key, err ); } setValue(newValue); }, [key] ); return [value, storeValue]; } <file_sep>import {iterateCursor} from '#core/dom'; import * as Preact from '#core/dom/jsx'; import {Layout_Enum} from '#core/dom/layout'; import {Services} from '#service'; import {CSS} from '../../../build/amp-story-subscriptions-0.1.css'; import {StateProperty} from '../../amp-story/1.0/amp-story-store-service'; const TAG = 'amp-story-subscriptions'; /** * The attribute name used in amp-subscriptions to indicate the content is locked or not. * @const {string} */ const SUBSCRIPTIONS_SECTION = 'subscriptions-section'; /** * The index of the limited-content page, which is the page where the paywall would be triggered. * @const {number} */ const FIRST_PAYWALL_STORY_PAGE_INDEX = 2; export class AmpStorySubscriptions extends AMP.BaseElement { /** @param {!AmpElement} element */ constructor(element) { super(element); /** @private {?../../../extensions/amp-story/1.0/amp-story-store-service.AmpStoryStoreService} */ this.storeService_ = null; } /** @override */ buildCallback() { // Mark pages with required attributes to be treated as paywall protected pages. // 'limited-content' is for the paywall dialog page, where a paywall would trigger based on both time advance or click events. // 'content' is for all the remaining locked pages. iterateCursor( document.querySelectorAll('amp-story-page'), (pageEl, index) => { if (index == FIRST_PAYWALL_STORY_PAGE_INDEX) { pageEl.setAttribute(SUBSCRIPTIONS_SECTION, 'limited-content'); } else if (index > FIRST_PAYWALL_STORY_PAGE_INDEX) { pageEl.setAttribute(SUBSCRIPTIONS_SECTION, 'content'); } } ); // Create a paywall dialog element that have required attributes to be able to be // rendered by amp-subscriptions. // TODO(#37285): complete the rest of paywall dialog UI based on the publisher-provided attributes. const dialogEl = ( <div subscriptions-dialog subscriptions-display="NOT granted"></div> ); this.element.appendChild(dialogEl); return Services.storyStoreServiceForOrNull(this.win).then( (storeService) => { this.storeService_ = storeService; this.initializeListeners_(); } ); } /** @override */ isLayoutSupported(layout) { return layout == Layout_Enum.CONTAINER; } /** * @private */ initializeListeners_() { this.storeService_.subscribe( StateProperty.SUBSCRIPTIONS_DIALOG_STATE, (isDialogVisible) => this.onSubscriptionStateChange_(isDialogVisible) ); } /** * @param {boolean} isDialogVisible * @private */ onSubscriptionStateChange_(isDialogVisible) { this.mutateElement(() => this.element.classList.toggle( 'i-amphtml-story-subscriptions-visible', isDialogVisible ) ); } } AMP.extension(TAG, '0.1', (AMP) => { AMP.registerElement(TAG, AmpStorySubscriptions, CSS); }); <file_sep>import {Services} from '#service'; import {getElementConfig} from 'extensions/amp-story/1.0/request-utils'; import { Action, ShoppingConfigDataDef, } from '../../amp-story/1.0/amp-story-store-service'; /** * @typedef {{ * items: !Array<!ShoppingConfigDataDef>, * }} */ let ShoppingConfigResponseDef; /** @typedef {!Object<string, !ShoppingConfigDataDef> */ export let KeyedShoppingConfigDef; /** * Gets Shopping config from an <amp-story-page> element. * The config is validated and keyed by 'product-tag-id'. * @param {!Element} pageElement <amp-story-page> * @return {!Promise<!KeyedShoppingConfigDef>} */ export function getShoppingConfig(pageElement) { const element = pageElement.querySelector('amp-story-shopping-config'); return getElementConfig(element).then((config) => { //TODO(#36412): Add call to validate config here. return keyByProductTagId(config); }); } /** * @param {!ShoppingConfigResponseDef} config * @return {!KeyedShoppingConfigDef} */ function keyByProductTagId(config) { const keyed = {}; for (const item of config.items) { keyed[item.productId] = item; } return keyed; } /** * @param {!Element} pageElement * @param {!KeyedShoppingConfigDef} config * @return {!Promise<!ShoppingConfigResponseDef>} */ export function storeShoppingConfig(pageElement, config) { const win = pageElement.ownerDocument.defaultView; return Services.storyStoreServiceForOrNull(win).then((storeService) => { storeService?.dispatch(Action.ADD_SHOPPING_DATA, config); return config; }); } <file_sep>import '../amp-story-subscriptions'; import * as Preact from '#core/dom/jsx'; import {Services} from '#service'; import {afterRenderPromise} from '#testing/helpers'; import { Action, AmpStoryStoreService, } from '../../../amp-story/1.0/amp-story-store-service'; import {AmpStorySubscriptions} from '../amp-story-subscriptions'; describes.realWin( 'amp-story-subscriptions-v0.1', { amp: { runtimeOn: true, extensions: ['amp-story:1.0', 'amp-story-subscriptions:0.1'], }, }, (env) => { let win; let doc; let subscriptionsEl; let storeService; let storySubscriptions; const nextTick = () => new Promise((resolve) => win.setTimeout(resolve, 0)); beforeEach(() => { win = env.win; doc = win.document; storeService = new AmpStoryStoreService(win); env.sandbox .stub(Services, 'storyStoreServiceForOrNull') .returns(Promise.resolve(storeService)); subscriptionsEl = ( <amp-story-subscriptions layout="container"> </amp-story-subscriptions> ); const storyEl = doc.createElement('amp-story'); storyEl.appendChild(subscriptionsEl); doc.body.appendChild(storyEl); storySubscriptions = new AmpStorySubscriptions(subscriptionsEl); }); it('should contain amp-subscriptions attributes', async () => { await subscriptionsEl.whenBuilt(); expect( subscriptionsEl .querySelector('div') .hasAttribute('subscriptions-dialog') ).to.equal(true); expect( subscriptionsEl .querySelector('div') .getAttribute('subscriptions-display') ).to.equal('NOT granted'); }); it('should display the blocking paywall on state update', async () => { await storySubscriptions.buildCallback(); await nextTick(); storeService.dispatch(Action.TOGGLE_SUBSCRIPTIONS_DIALOG, true); await afterRenderPromise(win); expect(storySubscriptions.element).to.have.class( 'i-amphtml-story-subscriptions-visible' ); }); } );
2f58d9f288ea12aa80a2c845e03b8b18d95325b6
[ "JavaScript", "Dockerfile", "Shell" ]
11
JavaScript
ebuzzing/amphtml
ef4e1c4846d5b3ea975ada8f8bc256faaaf06687
339f0fd67189e7c7066f8b353b3109e2da3c7aa2
refs/heads/master
<repo_name>danyashorokh/tensorflow_cnn<file_sep>/main.py import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import cv2 # from tensorflow.examples.tutorials.mnist import input_data # mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) dir_input = 'input/' train_patches = np.load(dir_input + 'train_patches.npy') train_labels = np.load(dir_input + 'train_labels.npy') test_patches = np.load(dir_input + 'test_patches.npy') test_labels = np.load(dir_input + 'test_labels.npy') print(train_patches) print(train_labels) print(len(train_patches)) print(len(test_patches)) n_classes = 2 batch_size = 100 x = tf.placeholder('float', [None, 16*16]) y = tf.placeholder('float') keep_rate = 0.8 keep_prob = tf.placeholder(tf.float32) def conv2d(x, w): return tf.nn.conv2d(x, w, strides=[1, 1, 1, 6], padding='SAME') def maxpool2d(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def convolutional_neural_network(x): weights = {'w_conv1': tf.Variable(tf.random_normal([5, 5, 6, 32])), # 5, 5, 1, 32 'w_conv2': tf.Variable(tf.random_normal([5, 5, 32, 64])), 'w_fc': tf.Variable(tf.random_normal([4*4*64, 1024])), # 7*7 'out': tf.Variable(tf.random_normal([1024, n_classes]))} biases = {'b_conv1': tf.Variable(tf.random_normal([32])), 'b_conv2': tf.Variable(tf.random_normal([64])), 'b_fc': tf.Variable(tf.random_normal([1024])), 'out': tf.Variable(tf.random_normal([n_classes]))} x = tf.reshape(x, shape=[-1, 16, 16, 6]) conv1 = conv2d(x, weights['w_conv1']) conv1 = maxpool2d(conv1) conv2 = conv2d(conv1, weights['w_conv2']) conv2 = maxpool2d(conv2) fc = tf.reshape(conv2, [-1, 4*4*64]) # 7*7 fc = tf.nn.relu(tf.add(tf.matmul(fc, weights['w_fc']), biases['b_fc'])) fc = tf.nn.dropout(fc, keep_rate) output = tf.add(tf.matmul(fc, weights['out']), biases['out']) return output def train_neural_network(x): prediction = convolutional_neural_network(x) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) hm_epochs = 10 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(hm_epochs): epoch_loss = 0 for i in range(len(train_patches) // batch_size): feed_dict = {x: train_patches[i * batch_size:(i + 1) * batch_size], y: train_labels[i * batch_size:(i + 1) * batch_size]} _, c = sess.run([optimizer, cost], feed_dict=feed_dict) epoch_loss += c print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:', epoch_loss) correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) print('Accuracy:', accuracy.eval({x: test_patches, y: test_labels})) train_neural_network(x) <file_sep>/cnn_example_v2.py import tensorflow as tf import numpy as np from datetime import datetime, timedelta from sklearn import metrics dir_input = 'input/' train_patches = np.load(dir_input + 'train_patches.npy') train_labels = np.load(dir_input + 'train_labels.npy') test_patches = np.load(dir_input + 'test_patches.npy') test_labels = np.load(dir_input + 'test_labels.npy') # test t_size = 5000 train_patches = np.concatenate((train_patches[:t_size], train_patches[-t_size:])) train_labels = np.concatenate((train_labels[:t_size], train_labels[-t_size:])) test_patches = np.concatenate((test_patches[:t_size], test_patches[-t_size:])) test_labels = np.concatenate((test_labels[:t_size], test_labels[-t_size:])) np.save(dir_input + 'small_train_patches.npy', train_patches) np.save(dir_input + 'small_train_labels.npy', train_labels) np.save(dir_input + 'small_test_patches.npy', test_patches) np.save(dir_input + 'small_test_labels.npy', test_labels) exit() print(len(train_patches)) print(train_patches[0].shape) tf.set_random_seed(0) IMAGE_SIZE = 16 IMAGE_CHANNELS = 6 NUM_CLASSES = 2 BATCH_SIZE = 500 x = tf.placeholder('float', shape=[None, IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNELS]) y = tf.placeholder('int64', shape=[None]) def cnn(x): input_layer = tf.reshape(x, shape=[-1, IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNELS]) # Convolutional Layer #1 # Computes 32 features using a 5x5 filter with ReLU activation. # Padding is added to preserve width and height. # Input Tensor Shape: [batch_size, 28, 28, 1] # Output Tensor Shape: [batch_size, 28, 28, 32] conv1 = tf.layers.conv2d( inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) # Pooling Layer #1 # First max pooling layer with a 2x2 filter and stride of 2 # Input Tensor Shape: [batch_size, 16, 16, 32] # Output Tensor Shape: [batch_size, 8, 8, 32] pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) # Convolutional Layer #2 # Computes 64 features using a 5x5 filter. # Padding is added to preserve width and height. # Input Tensor Shape: [batch_size, 8, 8, 32] # Output Tensor Shape: [batch_size, 8, 8, 64] conv2 = tf.layers.conv2d( inputs=pool1, filters=64, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) # Pooling Layer #2 # Second max pooling layer with a 2x2 filter and stride of 2 # Input Tensor Shape: [batch_size, 8, 8, 64] # Output Tensor Shape: [batch_size, 4, 4, 64] pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) # Flatten tensor into a batch of vectors # Input Tensor Shape: [batch_size, 4, 4, 64] # Output Tensor Shape: [batch_size, 4 * 4 * 64] pool2_flat = tf.reshape(pool2, [-1, 4 * 4 * 64]) # Dense Layer # Densely connected layer with 1024 neurons # Input Tensor Shape: [batch_size, 4 * 4 * 64] # Output Tensor Shape: [batch_size, 1024] dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu) # Add dropout operation; 0.6 probability that element will be kept dropout = tf.layers.dropout(inputs=dense, rate=0.4) # Logits layer # Input Tensor Shape: [batch_size, 1024] # Output Tensor Shape: [batch_size, 2] output = tf.layers.dense(inputs=dropout, units=NUM_CLASSES) return output def train_cnn(x): prediction = cnn(x) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction, labels=tf.one_hot(y, NUM_CLASSES))) optimizer = tf.train.AdamOptimizer().minimize(cost) hm_epochs = 10 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) for epoch in range(hm_epochs): epoch_loss = 0 for i in range(len(train_patches) // BATCH_SIZE): feed_dict = {x: train_patches[i * BATCH_SIZE:(i + 1) * BATCH_SIZE], y: train_labels[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]} _, c = sess.run([optimizer, cost], feed_dict=feed_dict) epoch_loss += c print('%s Epoch %s completed out of %s loss: %s' % (datetime.now(), epoch + 1, hm_epochs, epoch_loss)) argmax_prediction = tf.argmax(prediction, 1) argmax_y = y correct = tf.equal(argmax_prediction, argmax_y) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) print('Accuracy:', accuracy.eval({x: test_patches, y: test_labels})) # TP = tf.count_nonzero(argmax_prediction * argmax_y, dtype=tf.float32) # TN = tf.count_nonzero((argmax_prediction - 1) * (argmax_y - 1), dtype=tf.float32) # FP = tf.count_nonzero(argmax_prediction * (argmax_y - 1), dtype=tf.float32) # FN = tf.count_nonzero((argmax_prediction - 1) * argmax_y, dtype=tf.float32) # # precision = TP / (TP + FP) # recall = TP / (TP + FN) # f11 = 2 * precision * recall / (precision + recall) # # # v.2 # _, recall = tf.metrics.recall(argmax_y, argmax_prediction) # _, precision = tf.metrics.precision(argmax_y, argmax_prediction) # # f12 = 2 * precision * recall / (precision + recall) t_start = datetime.now() print(t_start) train_cnn(x) t_finish = datetime.now() print('Training time = %s min' % str((t_finish - t_start)/timedelta(minutes=1))) # 2018-05-29 10:40:47.019255 # 2018-05-29 10:46:44.811883 Epoch 1 completed out of 10 loss: 5418.902016327147 # 2018-05-29 10:52:37.535540 Epoch 2 completed out of 10 loss: 544.2676258957363 # 2018-05-29 11:32:14.045132 Epoch 3 completed out of 10 loss: 292.21028113976354 # 2018-05-29 11:42:11.045421 Epoch 4 completed out of 10 loss: 264.3411089053261 # 2018-05-29 11:52:28.410208 Epoch 5 completed out of 10 loss: 228.79144700716643 # 2018-05-29 11:58:20.893716 Epoch 6 completed out of 10 loss: 347.66179316881124 # 2018-05-29 12:04:42.367687 Epoch 7 completed out of 10 loss: 544.5814690636653 # 2018-05-29 12:10:33.006995 Epoch 8 completed out of 10 loss: 289.0318987420178 # 2018-05-29 12:50:16.223302 Epoch 9 completed out of 10 loss: 257.2835987842991 # 2018-05-29 13:04:28.912487 Epoch 10 completed out of 10 loss: 267.65256672833493 # Process finished with exit code 137 (interrupted by signal 9: SIGKILL) # 2018-05-29 13:19:02.822745 Epoch 1 completed out of 10 loss: 6414.275468234842 # 2018-05-29 13:24:58.770487 Epoch 2 completed out of 10 loss: 416.25010985624976 # 2018-05-29 13:30:48.582920 Epoch 3 completed out of 10 loss: 226.82338501722552 # 2018-05-29 13:49:37.294407 Epoch 4 completed out of 10 loss: 228.31862263567746 # 2018-05-29 13:55:27.590219 Epoch 5 completed out of 10 loss: 151.67859579938158 # 2018-05-29 14:12:07.707235 Epoch 6 completed out of 10 loss: 176.13612923119217 # 2018-05-29 14:17:59.580634 Epoch 7 completed out of 10 loss: 174.3668554674132 # 2018-05-29 14:32:37.689864 Epoch 8 completed out of 10 loss: 200.4157704377867 # 2018-05-29 14:38:31.467441 Epoch 9 completed out of 10 loss: 169.84641691233583 # 2018-05-29 15:08:00.137249 Epoch 10 completed out of 10 loss: 4929.881377357835
e21f67dfd01ef407727cd75e7789948c8bd18a6e
[ "Python" ]
2
Python
danyashorokh/tensorflow_cnn
b45ae9fc5bb08e69287858f2c9db5f89a4f98289
61e46d388f119551b840455a51d411c4f0bc330b
refs/heads/master
<repo_name>OggYiu/GGJ2018<file_sep>/source/Assets/StageUI.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class StageUI : MonoBehaviour { public Image imageStageBegin; public Image imageStageClear; const float UI_INIT_POS_X = -350; private GameMgr gameMgr; // Use this for initialization void Start () { this.gameMgr = FindObjectOfType<GameMgr>(); } // Update is called once per frame void Update () { } public void ShowStageBegin() { Vector3 imagePos = imageStageBegin.transform.position; imageStageBegin.transform.position = new Vector3(UI_INIT_POS_X, imagePos.y, imagePos.z); iTween.MoveTo(imageStageBegin.gameObject, iTween.Hash("x", Screen.width/2, "easeType", "easeInOutExpo", "oncompletetarget", this.gameObject, "oncomplete", "onShowStageBeginPhase1Ended")); } public void onShowStageBeginPhase1Ended() { iTween.MoveTo(imageStageBegin.gameObject, iTween.Hash("x", Screen.width - UI_INIT_POS_X, "easeType", "easeInOutExpo", "oncompletetarget", this.gameObject, "oncomplete", "onShowStageBeginPhase2Ended")); } public void onShowStageBeginPhase2Ended() { this.gameMgr.OnLevelStarted(); } public void ShowStageClear() { Vector3 imagePos = imageStageClear.transform.position; imageStageClear.transform.position = new Vector3(UI_INIT_POS_X, imagePos.y, imagePos.z); iTween.MoveTo(imageStageClear.gameObject, iTween.Hash("x", Screen.width / 2, "easeType", "easeInOutExpo", "oncompletetarget", this.gameObject, "oncomplete", "onShowStageClearPhase1Ended")); } public void onShowStageClearPhase1Ended() { iTween.MoveTo(imageStageClear.gameObject, iTween.Hash("x", Screen.width - UI_INIT_POS_X, "easeType", "easeInOutExpo", "oncompletetarget", this.gameObject, "oncomplete", "onShowStageClearPhase2Ended")); } public void onShowStageClearPhase2Ended() { this.gameMgr.OnLevelEnded(); } } <file_sep>/source/Assets/DebugController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DebugController : MonoBehaviour { public float speed = 20f; private Parcel parcel; Dictionary<KeyCode, bool> keyDownChecker = new Dictionary<KeyCode, bool>(); // Use this for initialization void Start() { parcel = FindObjectOfType<Parcel>(); parcel.GetComponent<Rigidbody>().isKinematic = true; KeyCode targetKeyCode; targetKeyCode = KeyCode.W; keyDownChecker[targetKeyCode] = false; targetKeyCode = KeyCode.S; keyDownChecker[targetKeyCode] = false; targetKeyCode = KeyCode.A; keyDownChecker[targetKeyCode] = false; targetKeyCode = KeyCode.D; keyDownChecker[targetKeyCode] = false; } // Update is called once per frame void Update () { KeyCode targetKeyCode; // Keycode W { targetKeyCode = KeyCode.W; if (Input.GetKeyUp(targetKeyCode)) { keyDownChecker[targetKeyCode] = false; } if (Input.GetKeyDown(targetKeyCode)) { keyDownChecker[targetKeyCode] = true; } if (keyDownChecker[targetKeyCode]) { Vector3 parcelPos = parcel.transform.position; parcel.transform.position = new Vector3(parcelPos.x, parcelPos.y + speed * Time.deltaTime, parcelPos.z); } } // Keycode S { targetKeyCode = KeyCode.S; if (Input.GetKeyUp(targetKeyCode)) { keyDownChecker[targetKeyCode] = false; } if (Input.GetKeyDown(targetKeyCode)) { keyDownChecker[targetKeyCode] = true; } if (keyDownChecker[targetKeyCode]) { Vector3 parcelPos = parcel.transform.position; parcel.transform.position = new Vector3(parcelPos.x, parcelPos.y - speed * Time.deltaTime, parcelPos.z); } } // Keycode A { targetKeyCode = KeyCode.A; if (Input.GetKeyUp(targetKeyCode)) { keyDownChecker[targetKeyCode] = false; } if (Input.GetKeyDown(targetKeyCode)) { keyDownChecker[targetKeyCode] = true; } if (keyDownChecker[targetKeyCode]) { Vector3 parcelPos = parcel.transform.position; parcel.transform.position = new Vector3(parcelPos.x - speed * Time.deltaTime, parcelPos.y, parcelPos.z); } } // Keycode D { targetKeyCode = KeyCode.D; if (Input.GetKeyUp(targetKeyCode)) { keyDownChecker[targetKeyCode] = false; } if (Input.GetKeyDown(targetKeyCode)) { keyDownChecker[targetKeyCode] = true; } if (keyDownChecker[targetKeyCode]) { Vector3 parcelPos = parcel.transform.position; parcel.transform.position = new Vector3(parcelPos.x + speed * Time.deltaTime, parcelPos.y, parcelPos.z); } } } } <file_sep>/source/Assets/GameMgr.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameMgr : MonoBehaviour { public enum GunType { HAND_GUN, MACHINE_GUN, SHORT_GUN, ROCKET_LAUNCHER, } public bool showGameStart = false; public string nextLevel; public GunType initGunType; public Gun[] guns; public bool isGameStarted = false; public bool isGameEnded = false; public SpriteRenderer fadeInOutSpirteRenderer; public AudioSource audioChangeGun; private StageUI stageUI; private GameUIMgr gameUIMgr; private Gun myGun; private Parcel parcel; protected GameMgr() { } public void FadeIn() { this.fadeInOutSpirteRenderer.gameObject.SetActive(true); this.fadeInOutSpirteRenderer.color = new Color(1.0f, 1.0f, 1.0f, 1.0f); Hashtable tweenParams = new Hashtable(); tweenParams.Add("from", this.fadeInOutSpirteRenderer.color); tweenParams.Add("to", new Color(1.0f, 1.0f, 1.0f, 0f)); tweenParams.Add("time", 3.0); tweenParams.Add("onupdate", "OnColorUpdated"); tweenParams.Add("oncomplete", "OnFadeInEnded"); iTween.ValueTo(this.gameObject, tweenParams); } private void OnFadeInEnded() { //this.fadeInOutSpirteRenderer.gameObject.SetActive(false); } private void OnFadeOutEnded() { SceneManager.LoadScene(this.nextLevel); } private void OnColorUpdated(Color color) { this.fadeInOutSpirteRenderer.color = color; } public void FadeOut() { this.fadeInOutSpirteRenderer.gameObject.SetActive(true); this.fadeInOutSpirteRenderer.color = new Color(1.0f, 1.0f, 1.0f, 0.0f); Hashtable tweenParams = new Hashtable(); tweenParams.Add("from", this.fadeInOutSpirteRenderer.color); tweenParams.Add("to", new Color(1.0f, 1.0f, 1.0f, 1.0f)); tweenParams.Add("time", 3.0); tweenParams.Add("onupdate", "OnColorUpdated"); tweenParams.Add("oncomplete", "OnFadeOutEnded"); iTween.ValueTo(this.gameObject, tweenParams); } // Use this for initialization void Start() { this.gameUIMgr = FindObjectOfType<GameUIMgr>(); this.stageUI = FindObjectOfType<StageUI>(); this.FadeIn(); this.parcel = FindObjectOfType<Parcel>(); if (this.showGameStart) { Rigidbody body = this.parcel.GetComponent<Rigidbody>(); body.isKinematic = true; body.useGravity = false; this.stageUI.ShowStageBegin(); } else { OnLevelStarted(); } foreach (Gun gun in guns) { gun.gameObject.SetActive(false); } ChangeWeapon(initGunType); } // Update is called once per frame void Update() { } public void ChangeWeapon(GunType gunType) { Gun gun = guns[(int)gunType]; if (myGun != null) { myGun.gameObject.SetActive(false); } myGun = gun; if (myGun != null) { myGun.gameObject.SetActive(true); } audioChangeGun.Play(); } public void OnLevelStarted() { isGameStarted = true; Rigidbody body = this.parcel.GetComponent<Rigidbody>(); body.isKinematic = false; body.useGravity = true; } public void OnLevelEnded() { Rigidbody body = this.parcel.GetComponent<Rigidbody>(); body.isKinematic = true; body.useGravity = false; isGameEnded = true; FadeOut(); } public void OnGotHit(GameUIMgr.GotHitType type) { this.gameUIMgr.ShowGotHit(type); } public void OnGotScore(GameUIMgr.GotScoreType type, GameObject target) { this.gameUIMgr.ShowGotScore(type, target); } public void GetItem(GunType gunType) { ChangeWeapon(gunType); } } <file_sep>/source/Assets/Bullet.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { public Vector3 fromPosition; public Vector3 targetPosition; public Gun gun; public GameObject prefabGunFire; public float speed = 20f; private float lifeCountDown = 0; private bool bulletHoleCreated = false; private float life = 0; // Use this for initialization void Start () { this.transform.position = fromPosition; Vector3 diffPosition = (targetPosition - fromPosition); float distance = diffPosition.magnitude; this.life = distance / this.speed; Rigidbody2D body = this.gameObject.GetComponent<Rigidbody2D>(); diffPosition.Normalize(); body.velocity = diffPosition * speed; //Debug.Log("start!"); this.lifeCountDown = this.life; } // Update is called once per frame void Update () { this.lifeCountDown -= Time.deltaTime; if(!bulletHoleCreated) { if (this.lifeCountDown <= 0) { // create gunFire GameObject gunFire = GameObject.Instantiate(prefabGunFire); gunFire.transform.position = new Vector3(targetPosition.x, targetPosition.y, -1); GameObject.DestroyObject(gunFire, 1.0f); bulletHoleCreated = true; this.gun.OnBulletHitPosition(this.targetPosition); GameObject.DestroyObject(this.gameObject); } } } } <file_sep>/source/Assets/ChansHand.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChansHand : MonoBehaviour { private StageUI stageUI; // Use this for initialization void Start () { this.stageUI = FindObjectOfType<StageUI>(); } // Update is called once per frame void Update () { } private void OnTriggerEnter(Collider other) { Parcel parcel = other.gameObject.GetComponent<Parcel>(); if(parcel != null) { Rigidbody body = parcel.GetComponent<Rigidbody>(); body.useGravity = false; body.isKinematic = true; this.stageUI.ShowStageClear(); } } } <file_sep>/source/Assets/Script/BirdMoving.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BirdMoving : MonoBehaviour { public bool Flip = false; public bool IsUFO = false; public float Speed = 10f; private Transform Bird; private bool StartFly = false; private float VerticalSpeed = 5; private float IniticalY; private float vertical = 0; // Use this for initialization void Start () { Bird = this.gameObject.transform; if (IsUFO) { IniticalY = Bird.localPosition.y; vertical = VerticalSpeed; } if (Flip) { Speed *= -1; } } // Update is called once per frame void Update () { if (IsUFO) { if (Bird.localPosition.y > IniticalY + 3 || Bird.localPosition.y < IniticalY - 3) { vertical *= -1; } } if (StartFly) { Bird.localPosition = new Vector3 (Bird.localPosition.x + (Speed * Time.deltaTime), Bird.localPosition.y + (vertical * Time.deltaTime), Bird.localPosition.z); } if (Bird.localPosition.x < -30 || Bird.localPosition.x > 30) { DestroyObject(this.gameObject); StartFly = false; } } private void OnTriggerEnter(Collider other) { StartFly = true; } } <file_sep>/source/Assets/GameUIMgr.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameUIMgr : MonoBehaviour { public enum GotHitType { MINUS_10, MINUS_20, MINUS_30, } public enum GotScoreType { SCORE_10, SCORE_20, SCORE_30, } public GameObject[] prefabGotHitImages; public GameObject[] prefabGotScoreImages; public Image[] currentHeightImages; public Image[] targetHeightImages; public Sprite[] heightSprites; private Parcel parcel; // Use this for initialization void Start () { parcel = FindObjectOfType<Parcel>(); } // Update is called once per frame void Update () { } public void ShowGotHit(GotHitType type) { GameObject targetImage = GameObject.Instantiate(prefabGotHitImages[(int)type]); iTween.MoveBy(targetImage, iTween.Hash("y", 1, "easeType", "easeInOutExpo", "oncompletetarget", this.gameObject)); targetImage.transform.position = new Vector3(this.parcel.transform.position.x, this.parcel.transform.position.y, -9); DestroyObject(targetImage, 1.0f); } public void ShowGotScore(GotScoreType type, GameObject target) { GameObject targetImage = GameObject.Instantiate(prefabGotScoreImages[(int)type]); iTween.MoveBy(targetImage, iTween.Hash("y", 1, "easeType", "easeInOutExpo", "oncompletetarget", this.gameObject)); targetImage.transform.position = new Vector3(target.transform.position.x, target.transform.position.y, -9); DestroyObject(targetImage, 1.0f); } public void SetCurrentHeight(int height) { Image image10000 = currentHeightImages[4]; Image image1000 = currentHeightImages[3]; Image image100 = currentHeightImages[2]; Image image10 = currentHeightImages[1]; Image image1 = currentHeightImages[0]; int digit1 = height % 10; int digit2 = (int)((height % 100) / 10); int digit3 = (int)((height % 1000) / 100); int digit4 = (int)((height % 10000) / 1000); int digit5 = (int)((height % 100000) / 10000); if (digit1 >= 0 && digit2 >= 0 && digit3 >= 0 && digit4 >= 0) { image10000.sprite = heightSprites[digit5]; image1000.sprite = heightSprites[digit4]; image100.sprite = heightSprites[digit3]; image10.sprite = heightSprites[digit2]; image1.sprite = heightSprites[digit1]; } } public void SetTargetHeight(int height) { Image image10000 = targetHeightImages[4]; Image image1000 = targetHeightImages[3]; Image image100 = targetHeightImages[2]; Image image10 = targetHeightImages[1]; Image image1 = targetHeightImages[0]; int digit1 = height % 10; int digit2 = (int)((height % 100) / 10); int digit3 = (int)((height % 1000) / 100); int digit4 = (int)((height % 10000) / 1000); int digit5 = (int)((height % 100000) / 10000); if (digit1 >= 0 && digit2 >= 0 && digit3 >= 0 && digit4 >= 0) { image10000.sprite = heightSprites[digit5]; image1000.sprite = heightSprites[digit4]; image100.sprite = heightSprites[digit3]; image10.sprite = heightSprites[digit2]; image1.sprite = heightSprites[digit1]; } } } <file_sep>/source/Assets/DestroyableObject.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DestroyableObject : MonoBehaviour { public AudioSource destroySound; private Rigidbody body; private BoxCollider boxCollider; private Vector3 backupPos; private bool isSelfDestroyStarted = false; const float SELF_DESTROY_TIME = 4.0f; private float lifeTimeAfterSelfDestroyStarted = SELF_DESTROY_TIME; private bool isDead = false; private SpriteRenderer spriteRenderer; private GameMgr gameMgr; private CameraShake cameraShake; //private Vector3 backupPos; // Use this for initialization void Start () { this.body = this.gameObject.GetComponent<Rigidbody>(); this.spriteRenderer = this.gameObject.GetComponent<SpriteRenderer>(); this.boxCollider = this.gameObject.GetComponent<BoxCollider>(); this.backupPos = this.transform.position; this.gameMgr = FindObjectOfType<GameMgr>(); this.cameraShake = FindObjectOfType<CameraShake>(); } // Update is called once per frame void Update () { if(this.isDead) { return; } if(isSelfDestroyStarted) { this.lifeTimeAfterSelfDestroyStarted -= Time.deltaTime; this.spriteRenderer.color = new Color(this.spriteRenderer.color.r, this.spriteRenderer.color.g, this.spriteRenderer.color.b, this.lifeTimeAfterSelfDestroyStarted / SELF_DESTROY_TIME); if (this.lifeTimeAfterSelfDestroyStarted <= 0) { DestroyObject(this.gameObject); this.isDead = true; } } } private void OnCollisionEnter(Collision collision) { Parcel parcel = collision.gameObject.GetComponent<Parcel>(); if (parcel != null) { this.body.useGravity = true; this.gameMgr.OnGotHit(GameUIMgr.GotHitType.MINUS_10); this.cameraShake.ShakeCamera(0.2f, 0.1f); StartSelfDestroy(); } } public void StartSelfDestroy() { isSelfDestroyStarted = true; this.boxCollider.enabled = false; destroySound.Play(); } } <file_sep>/source/Assets/Gun.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Gun : MonoBehaviour { public float radius = 0; public float power = 0; public float coolDown = 0; public float upward = 0; public bool isAutoWeapon = false; public Bullet prefabBullet; public int numberOfBulletsFire = 1; public float gunFireLife = 0.5f; public AudioSource fireSound; private float shortGunRadius = 1f; private float coolDownBK = 0; private bool isMouseJustDown = false; private bool isMouseUp = true; private bool isMouseDown = false; private GameMgr gameMgr; // Use this for initialization void Start() { coolDownBK = coolDown; this.gameMgr = FindObjectOfType<GameMgr>(); } // Update is called once per frame void Update() { if (this.gameMgr.isGameEnded || !this.gameMgr.isGameStarted) { return; } if (Input.GetMouseButtonUp(0)) { isMouseUp = true; isMouseDown = false; } if (Input.GetMouseButtonDown(0)) { isMouseJustDown = true; isMouseUp = false; isMouseDown = true; } if ((isMouseJustDown || (isAutoWeapon && isMouseDown)) && isCoolDownFinished()) { fireSound.Play(); Vector3 mouseScreenPos = Input.mousePosition; Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(mouseScreenPos); mouseWorldPos = new Vector3(mouseWorldPos.x, mouseWorldPos.y, 0); // create bullet { float screenHeight = Camera.main.orthographicSize * 2.0f; Vector3 bulletPos = new Vector3(mouseWorldPos.x, Camera.main.transform.position.y - screenHeight / 2, -1); prefabBullet.fromPosition = bulletPos; prefabBullet.targetPosition = mouseWorldPos; prefabBullet.gun = this; Bullet bullet = GameObject.Instantiate(prefabBullet); } if(this.numberOfBulletsFire > 1) { for(int i = 0; i < this.numberOfBulletsFire-1; ++i) { // create bullet float screenHeight = Camera.main.orthographicSize * 2.0f; Vector3 bulletPos = new Vector3(mouseWorldPos.x, Camera.main.transform.position.y - screenHeight / 2, -1); Vector3 targetPos = mouseWorldPos; targetPos += new Vector3(Random.Range(-this.shortGunRadius, this.shortGunRadius), Random.Range(-this.shortGunRadius, this.shortGunRadius), -1); prefabBullet.fromPosition = bulletPos; prefabBullet.targetPosition = targetPos; prefabBullet.gun = this; Bullet bullet = GameObject.Instantiate(prefabBullet); } } coolDown = coolDownBK; } if(coolDown > 0) { coolDown -= Time.deltaTime; if(coolDown <= 0) { coolDown = 0; } } isMouseJustDown = false; } public bool isCoolDownFinished() { return coolDown <= 0; } public void OnBulletHitPosition(Vector3 pos) { Vector3 explosionPos = pos; explosionPos = new Vector3(explosionPos.x, explosionPos.y, -0.001f); Collider[] colliders = Physics.OverlapSphere(explosionPos, radius); foreach (Collider hit in colliders) { Rigidbody rb = hit.GetComponent<Rigidbody>(); if (rb != null) { //rb.velocity = Vector3.zero; //rb.angularVelocity = Vector3.zero; rb.AddExplosionForce(power, explosionPos, radius, upward); DestroyableObject destroyableObject = rb.GetComponent<DestroyableObject>(); if(destroyableObject != null) { rb.useGravity = true; destroyableObject.StartSelfDestroy(); this.gameMgr.OnGotScore(GameUIMgr.GotScoreType.SCORE_10, destroyableObject.gameObject); } //Debug.Log("hit " + rb.gameObject.name); } } } } <file_sep>/source/Assets/GunItem.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class GunItem : MonoBehaviour { public GameMgr.GunType gunType; public GameMgr gameMgr; // Use this for initialization void Start () { this.gameMgr = FindObjectOfType<GameMgr>(); } // Update is called once per frame void Update () { } private void OnTriggerEnter(Collider other) { Parcel parcel = other.GetComponent<Parcel>(); if(parcel != null) { GetItem(); } } public void GetItem() { this.gameMgr.GetItem(this.gunType); GameObject.DestroyObject(this.gameObject); } } <file_sep>/source/Assets/ParcelCamera.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ParcelCamera : MonoBehaviour { private Parcel parcel; public float offsetY = 0; public float targetHeight = 0; public GameUIMgr gameUIMgr; private float lastUpdatedHeight = 0; private bool currentHeightSet = false; // Use this for initialization void Start () { parcel = FindObjectOfType<Parcel>(); } // Update is called once per frame void Update () { Vector3 parcelPos = parcel.transform.position; Vector3 camPos = Camera.main.transform.position; float currentHeight = parcelPos.y; if (!currentHeightSet) { lastUpdatedHeight = currentHeight; currentHeightSet = true; } float diffHeight = currentHeight - lastUpdatedHeight; Camera.main.transform.position = new Vector3(camPos.x, lastUpdatedHeight - this.offsetY + diffHeight, camPos.z); this.gameUIMgr.SetCurrentHeight((int)currentHeight); this.gameUIMgr.SetTargetHeight((int)(this.targetHeight - currentHeight)); lastUpdatedHeight = currentHeight; } } <file_sep>/source/Assets/Script/Target.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Target : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { iTween.MoveBy(gameObject, iTween.Hash("y", 0.5, "easeType", "easeInOutExpo", "loopType", "pingPong")); } } <file_sep>/source/Assets/Script/SkyScroll.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SkyScroll : MonoBehaviour { public Transform Background1; public Transform Background2; public Transform Background3; public int MaxFloor; private int CurrentBackground = 1; public Transform cam; private const float Height = 10.5f; private const float StartHeight = 120 + Height; private float CurrentHeight = StartHeight; private float BackgroundHeight = Height; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (cam.position.y >= CurrentHeight + 5) { if (CurrentHeight / Height <= MaxFloor + 0.01) { if (CurrentBackground == 1) { Background1.localPosition = new Vector3 (0, Background1.localPosition.y + BackgroundHeight * 3, 0); } else if (CurrentBackground == 2) { Background2.localPosition = new Vector3 (0, Background2.localPosition.y + BackgroundHeight * 3, 0); } else if (CurrentBackground == 3) { Background3.localPosition = new Vector3 (0, Background3.localPosition.y + BackgroundHeight * 3, 0); } CurrentHeight += Height; CurrentBackground += 1; if (CurrentBackground == 4) { CurrentBackground = 1; } } } else if (cam.position.y + Height < CurrentHeight + 5 && cam.position.y > StartHeight - 5) { CurrentHeight -= Height; CurrentBackground -= 1; if (CurrentBackground == 0) { CurrentBackground = 3; } if (CurrentBackground == 1) { Background1.localPosition = new Vector3 (0, Background1.localPosition.y - BackgroundHeight * 3, 0); } else if (CurrentBackground == 2) { Background2.localPosition = new Vector3 (0, Background2.localPosition.y - BackgroundHeight * 3, 0); } else if (CurrentBackground == 3) { Background3.localPosition = new Vector3 (0, Background3.localPosition.y - BackgroundHeight * 3, 0); } } } } <file_sep>/source/Assets/Script/DebugCamera.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DebugCamera : MonoBehaviour { bool isDownPressed = false; bool isUpPressed = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKeyUp (KeyCode.W)) { isUpPressed = true; isDownPressed = false; } if (Input.GetKeyDown (KeyCode.S)) { isDownPressed = true; isUpPressed = false; } if(isDownPressed) { Camera.main.transform.position = new Vector3 (Camera.main.transform.position.x, Camera.main.transform.position.y - 0.2f, Camera.main.transform.position.z); } if(isUpPressed) { Camera.main.transform.position = new Vector3 (Camera.main.transform.position.x, Camera.main.transform.position.y + 0.2f, Camera.main.transform.position.z); } } } <file_sep>/source/Assets/JesusTrigger.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class JesusTrigger : MonoBehaviour { public GameObject prefabSpineAnimation; public AudioSource bgMusic; public AudioSource bgHoly; private bool showed = false; private Parcel parcel; private GameMgr gameMgr; // Use this for initialization void Start () { this.parcel = FindObjectOfType<Parcel>(); this.gameMgr = FindObjectOfType<GameMgr>(); } // Update is called once per frame void Update () { } private void OnTriggerEnter(Collider other) { Parcel parcel = other.GetComponent<Parcel>(); if(parcel != null && !showed) { showed = true; GameObject spineAnim = GameObject.Instantiate(prefabSpineAnimation); Camera camera = Camera.main; spineAnim.transform.localPosition = new Vector3(0, 1f, 1); spineAnim.transform.parent = camera.transform; spineAnim.transform.localPosition = new Vector3(0, 1f, 1); this.parcel.enabled = false; this.gameMgr.isGameEnded = true; bgMusic.Stop(); bgHoly.Play(); } } } <file_sep>/source/Assets/Script/Background.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Background : MonoBehaviour { public Transform Background1; public Transform cam; // Use this for initialization void Start () { } // Update is called once per frame void Update () { Background1.localPosition = new Vector3 (Background1.localPosition.x, cam.position.y, Background1.localPosition.z); } } <file_sep>/source/Assets/Walls.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Walls : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { Vector3 camPos = Camera.main.transform.position; this.transform.position = new Vector3(camPos.x, camPos.y, 0); } }
18b55cf07760e8d82ac2728582417d3ff2446f4a
[ "C#" ]
17
C#
OggYiu/GGJ2018
1bd1e751c75411ab6f8efe7c2487a6d2f68749e0
e46a068d09678b6f1af8f8804bf78c5c2202ce0a
refs/heads/master
<repo_name>neerajgoyal12/QuickChat<file_sep>/Podfile platform :ios, '7.0' xcodeproj '/Users/systology/Documents/play/Obj-C/QuickChat/QuickChat.xcodeproj' pod 'QMChatViewController', '~> 0.1' pod 'TTTAttributedLabel' pod 'QuickBlox' pod 'QMServices'
bff88008159773e25bf23a1d1db9eec160403d89
[ "Ruby" ]
1
Ruby
neerajgoyal12/QuickChat
a7ae97a0cfc1a916e0d94074f7814a8ea9891653
5c4a18d1063ed27ab9ceed281fcc09cbbe966f17
refs/heads/master
<repo_name>shacowgit/iot9608-com<file_sep>/main.c #include "netclient.h" #include "fileoperator.h" #include "dealana.h" #include <pthread.h> pthread_t rev_thread; //receive thread pthread_mutex_t revtex; //the signal for receive buffer operator char revdata[1500]; //net receive buffer void *revthread_f(void *arg) //net receive thread { int revnum,i,res; char databuf[MAXLINE + 1]; res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); //set cancel enable if (res != 0) { perror("Thread setcancelstate failed!"); exit(EXIT_FAILURE); } res = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); //set cancel asy, cancel immediately if (res != 0) { perror("Thread setcanceltype failed!"); exit(EXIT_FAILURE); } while(1) { revnum = netclient_recv(databuf); if(revnum > 0) { pthread_mutex_lock(&revtex); if(revnum > 1500) revnum = 1500; if(revdata[0] != 0xff) //flag changed,already work for it,update receive buffer { revdata[0] = 0xff; printf("receive command from the remote server:"); for(i=0;i<revnum;i++) { revdata[i+1] = databuf[i]; printf("%d,",databuf[i]); } printf("\n"); } else { printf("the last message is not answer yet! \n"); } pthread_mutex_unlock(&revtex); } } } void test_revthread() { int pthread_kill_err; int res; pthread_kill_err = pthread_kill(rev_thread,0); if(pthread_kill_err == ESRCH) { printf("rev thread is not alive !\n"); res = pthread_create(&rev_thread, NULL, revthread_f, NULL); if (res != 0) { perror("Thread create failed"); exit(EXIT_FAILURE); } wdt_feed(); } else if(pthread_kill_err == EINVAL) { printf("rev thread has error! \n"); res = pthread_cancel(rev_thread); if(res != 0) { perror("Thread cancel failed"); exit(EXIT_FAILURE); } } else { printf("rev thread is alive\n"); } } void init_revthread() { int res; res = pthread_mutex_init(&revtex, NULL); //create signal for thread operator if (res != 0) { perror("Mutex init failed!"); exit(EXIT_FAILURE); } res = pthread_create(&rev_thread, NULL, revthread_f, NULL); if (res != 0) { perror("Thread create failed"); exit(EXIT_FAILURE); } } int setinfo_check() { int res,i; char setinfo[111]; char inbuf[10]; char su[5]; res = fgetsetdata(setinfo); for(i=0;i<110;i++) { setinfo[i] = 0; } if(res != 110) { loop: fflush(stdin); printf("pleas input collector name: ... \n"); scanf("%s",&inbuf); for(i=0;i<10;i++) { setinfo[10 + i] = inbuf[i]; } fflush(stdin); printf("the collector name is : %s\n",inbuf); printf("are you sure ? [y/n] \n"); scanf("%s",&su); if(su[0] == 'y') { res = fsetsetdata(setinfo); if(res < 0) exit(EXIT_FAILURE); } else goto loop; } } int senddatatoserver() { int i,j,res; char setinfo[F_SETFILE_LENGTH]; int chnum[8]; char fname[] = {'.','.','/','d','s','m','/','1','1','\0'}; if(res = fgetsetdata(setinfo) != F_SETFILE_LENGTH) { return -1; } printf("send data to server!\n"); chnum[0] = chartoi(setinfo,30,2); chnum[1] = chartoi(setinfo,40,2); chnum[2] = chartoi(setinfo,50,2); chnum[3] = chartoi(setinfo,60,2); chnum[4] = chartoi(setinfo,70,2); chnum[5] = chartoi(setinfo,80,2); chnum[6] = chartoi(setinfo,90,2); chnum[7] = chartoi(setinfo,100,2); for(i=0;i<8;i++) { if(chnum[i] > 0) { printf("the chanel %d has %d elecs !\n",i+1,chnum[i]); for(j=0;j<chnum[i];j++) { fname[7] = i+0x31; fname[8] = j+0x31; deal_sendrtdata(fname); } } } return 0; } void revdataana() { pthread_mutex_lock(&revtex); //check the receive buffer if(revdata[0] == 0xff) { deal_revbufana(revdata); revdata[0] = 0x00; } pthread_mutex_unlock(&revtex); } void datacommunicate(time_t *lasttime) { int worktype; int sendspan,timespan; time_t nowtime; worktype = fgetworktype(); //check work type if(worktype == 1) { sendspan = fgetsendspan(); if(sendspan > 0) { time(&nowtime); timespan = difftime(nowtime,*lasttime); if(timespan > sendspan) { *lasttime = nowtime; senddatatoserver(); } } else senddatatoserver(); } } int main(int argc,char* argv[]) { int i,res; time_t lasttime; chdir((char *)dirname(argv[0])); setinfo_check(); netclient_init(); //net connection init_revthread(); wdt_init(60); //start watch dog time(&lasttime); //get now time while(1) { test_revthread(); //rev thread state check revdataana(); //rev data analysis if(netclient_serverstate == 0) datacommunicate(&lasttime); else netclient_init(); wdt_feed(); sleep(1); } return 0; } <file_sep>/dealana.h #include "netclient.h" #include "fileoperator.h" #define FIXED_FRAME_LENGTH 18 #define FIXED_FRAME_HEDA 0x10 #define FIXED_FRAME_FOOT 0x16 #define FIXED_CONTROL 1 #define FIXED_ADDRESS 3 #define FIXED_DATA 11 #define ACT_FRAME_SEG 0x68 #define ACT_CONTROL 4 #define ACT_ADDRESS 6 #define ACT_DATA 14 extern int deal_revbufana(char databuf[]); extern int deal_sendrtdata(char fname[]); extern int deal_setcolinfo(char databuf[]); <file_sep>/dealana.c #include "dealana.h" int deal_revbufana(char databuf[]) //receive buffer analysis { int type; type = frametypecharge(databuf); if(type < 0) { printf("receive nothing!\n"); } if(type > 0) { printf("there is a active frame:"); switch(databuf[18]) { case 0x04: printf("it is a set collector info cmd!\n"); deal_setcolinfo(databuf); break; default: printf("i can't understand now!"); break; } } else { printf("it is a fixed frame!"); switch(databuf[15]) //the first byte is a flag { case 0x03: printf("it is query elec head cmd!\n"); sendelechisinfo(databuf); break; case 0x04: printf("it is query collector info cmd!\n"); sendsetinfo(); break; case 0x05: printf("it is query history data cmd!\n"); sendhisdata(databuf); break; default: printf("i can't understand now!"); break; } } } int deal_sendrtdata(char fname[]) //send realtime data to remote server { char elecdata[RECORDDATALEN],senddata[RECORDDATALEN + 21]; int datanum,i,len; datanum = fgetrtdata(fname,elecdata); len = RECORDDATALEN + 10 + 4; if(datanum > 0) { senddata[0] = 0x68; senddata[1] = len >> 8; senddata[2] = len; senddata[3] = 0x68; senddata[4] = 0x00; senddata[5] = 0x03; senddata[6] = 0x00; senddata[7] = 0x00; senddata[8] = 0x00; senddata[9] = 0x00; senddata[10] = 0x00; senddata[11] = 0x00; senddata[12] = 0x00; senddata[13] = 0x00; senddata[14] = 0x01; senddata[15] = 0x01; senddata[16] = 0x00; senddata[17] = 0x10; senddata[RECORDDATALEN + 18] = 0x00; senddata[RECORDDATALEN + 19] = 0x00; senddata[RECORDDATALEN + 20] = 0x68; for(i = 0;i<RECORDDATALEN;i++) { senddata[i+18] = elecdata[i]; } netclient_send(senddata,RECORDDATALEN + 21); } } int frametypecharge(char databuf[]) // charge the frame type { int i; printf("command type charge ! \n"); for(i=0;i<1500;i++) { if(databuf[i] == 0x10) { if((i+17) < 1500 && databuf[i+17] == 0x16) return 0; } if(databuf[i] == 0x68) { if((i+3) < 1500 && databuf[i + 3] == 0x68) return 1; } } return -1; } int sendelechisinfo(char databuf[]) { int datanum,i; char data[301]; char buf[71]; char fname[] = {'.','.','/','d','s','m','/','1','1','\0'}; fname[7] = databuf[12] + 0x30; fname[8] = databuf[13] + 0x30; datanum = fgethddata(fname,data); if(datanum > 0){ for(i=0;i<54;i++){ buf[i+18] = data[i]; } buf[0] = 0x68; buf[1] = 0x00; buf[2] = 0x40; buf[3] = 0x68; buf[4] = 0x00; buf[5] = 0x03; buf[6] = 0x00; buf[7] = 0x00; buf[8] = 0x00; buf[9] = 0x00; buf[10] = 0x00; buf[11] = 0x00; buf[12] = 0x00; buf[13] = 0x00; buf[14] = databuf[12]; buf[15] = databuf[13]; buf[16] = 0x00; buf[17] = 0x03; buf[68] = 0x00; buf[69] = 0x00; buf[70] = 0x68; netclient_send(buf,71); } } int sendhisdata(char databuf[]) { int datanum,dataindex,i; char data[RECORDLEN + 10]; char buf[1451]; char fname[] = {'.','.','/','d','s','m','/','1','1','\0'}; fname[7] = databuf[12] + 0x30; fname[8] = databuf[13] + 0x30; dataindex = chartoi(databuf,4,4); printf("it is query history data cmd!the data number is : %d\n",dataindex); datanum = fgethisdata(fname,dataindex,data); if(datanum > 0){ for(i=0;i<RECORDLEN;i++){ buf[i+18] = data[i]; } buf[0] = 0x68; buf[1] = (datanum + 10 + 3) >> 8; buf[2] = (datanum + 10 + 3); buf[3] = 0x68; buf[4] = 0x00; buf[5] = 0x05; buf[6] = 0x00; buf[7] = 0x00; buf[8] = 0x00; buf[9] = 0x00; buf[10] = 0x00; buf[11] = 0x00; buf[12] = 0x00; buf[13] = 0x00; buf[14] = databuf[12]; buf[15] = databuf[13]; buf[16] = 0x00; buf[17] = 0x05; buf[1448] = 0x00; buf[1449] = 0x00; buf[1450] = 0x68; netclient_send(buf,1451); printf("send history data to server\n"); } } int sendsetinfo() { int datanum,i; char fdata[120]; char sdata[131]; for(i=0;i<131;i++) { sdata[i] = 0; } datanum = fgetsetdata(fdata); if(datanum > 0) { for(i=0;i<110;i++){ sdata[i+18] = fdata[i]; } sdata[0] = 0x68; sdata[1] = 0x00; sdata[2] = 0x7C; sdata[3] = 0x68; sdata[4] = 0x00; sdata[5] = 0x03; sdata[6] = 0x00; sdata[7] = 0x00; sdata[8] = 0x00; sdata[9] = 0x00; sdata[10] = 0x00; sdata[11] = 0x00; sdata[12] = 0x00; sdata[13] = 0x00; sdata[14] = 0x01; sdata[15] = 0x01; sdata[16] = 0x00; sdata[17] = 0x04; sdata[128] = 0x00; sdata[129] = 0x00; sdata[130] = 0x68; netclient_send(sdata,131); } else netclient_send(sdata,131); } int deal_setcolinfo(char databuf[]) { int i; char wrbuf[111]; for(i=0;i<110;i++) { wrbuf[i] = databuf[i + 19]; printf("%d",wrbuf[i]); } printf("\n"); fsetsetdata(wrbuf); } <file_sep>/netclient.c #include "netclient.h" int sockfd; int netclient_serverstate; void connectserver() { int res; struct sockaddr_in servaddr; close(sockfd); sleep(1); //创建socket描述符 if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){ printf("create socket error: %s(errno: %d)\n", strerror(errno),errno); netclient_serverstate = -1; close(sockfd); return; } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); if( inet_pton(AF_INET, SERVERIP, &servaddr.sin_addr) <= 0){ printf("inet_pton error for %s\n",SERVERIP); netclient_serverstate = -1; close(sockfd); return; } printf("connect to the server : %s:%d ... \n",SERVERIP,PORT); if(res = connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){ printf("connect error: %s(errno: %d)\n",strerror(errno),errno); netclient_serverstate = -1; close(sockfd); wdt_feed(); return; } netclient_serverstate = 0; printf("connect remote server done ! the file number is %d\n",sockfd); } void netclient_init() { char devname[15]; char senddata[15]; int res; connectserver(); if(netclient_serverstate == 0){ usleep(100000); res = fgetcolname(devname); senddata[0] = 0x05; senddata[1] = 0x03; for(res = 0;res < 10; res ++) { senddata[res+2] = devname[res]; } senddata[12] = 0x03; senddata[13] = 0x05; senddata[14] = '\0'; printf("the device name is:%s!\n",devname); netclient_send(senddata,15); } } int netclient_send(char data[],int len) { int res; if(netclient_serverstate == -1) { printf("send msg error : the network is broken!\n"); return -1; } signal(SIGPIPE, SIG_IGN); res = send(sockfd, data, len, 0); if( res == -1 && errno == EPIPE) { printf("send msg error: %s(errno: %d)\n", strerror(errno), errno); shutdown(sockfd,2); netclient_serverstate = -1; return -1; } else return 0; } int netclient_recv(char data[]) { int rec_len; int res; if(netclient_serverstate == -1) { printf("rev msg error : the network is broken !\n"); sleep(1); return -1; } if((rec_len = recv(sockfd, data, MAXLINE,0)) == -1){ //表示读取失败 perror("socket recv error"); netclient_serverstate = -1; sleep(1); return -1; } data[rec_len] = '\0'; return rec_len; } <file_sep>/netclient.h #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #include <signal.h> #include "wdt.h" #include "fileoperator.h" #define PORT 51230 // The port which is communicate with server #define MAXLINE 4096 //#define SERVERIP "172.16.113.88" #define SERVERIP "172.16.2.10" extern int netclient_serverstate; extern void netclient_init(); extern int netclient_send(char data[],int len); extern int netclient_recv(char data[]);
cacac8507816976fe50b860adb337861f33c1e7f
[ "C" ]
5
C
shacowgit/iot9608-com
6499cb52e77a2a7a97df6cf196f979f358646a21
770cde3dcfa37484a5f56db7ac57f2759acc540a
refs/heads/master
<file_sep><?php $access_token = '<KEY>'; $baseUrl = "xxxxx"; ?>
a19e026456e6beee32e22e0795f7265e060031a3
[ "PHP" ]
1
PHP
Champy8/Line--Messaging-API
7f5c517e2ec2be7220317f85c1bf356593323fab
a85abd3498ae49a05617e38dfa8edf345e4861f7
refs/heads/master
<file_sep>import { Routes } from '@angular/router'; import { resourceRoutes } from '@app/resource/resource-routing.module'; export const appRoutes: Routes = [ ...resourceRoutes, ]; <file_sep>import { Injectable } from '@angular/core'; import { Model, ModelCollection, models } from '@model/index'; @Injectable() export class ModelService { models: ModelCollection = models; get(id: string): Model { return this.models.get(id); } getAll(): Model[] { return Array.from(this.models.getAll()); } getIds(): string[] { return Array.from(this.models.getIds()); } iterAll(): Iterable<Model> { return this.models.getAll(); } iterIds(): Iterable<string> { return this.models.getIds(); } } <file_sep>import { Model } from '@model/model'; export class ModelCollection { private collection: Map<string, Model> = new Map(); add(model: Model) { this.collection.set(model.id, model); } get(id: string): Model { return this.collection.get(id); } getAll(): Iterable<Model> { return this.collection.values(); } getIds(): Iterable<string> { return this.collection.keys(); } } <file_sep>export * from '@model/model'; export * from '@model/model.collection'; import { ModelCollection } from '@model/model.collection'; import { userModel } from '@model/user.model'; import { sampleModel } from '@model/sample.model'; export const models = new ModelCollection(); models.add(userModel); models.add(sampleModel); <file_sep>import { Injectable } from '@angular/core'; import { IConfig } from 'model/config.interface'; import { Config } from 'model/config'; @Injectable() export class ConfigService { cfg: IConfig; constructor() { this.cfg = new Config(); } } <file_sep>import { IConfig } from '@model/config.interface'; export class Config implements IConfig { title = 'Rest Api Admin'; } <file_sep>import { Component } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Params } from '@angular/router/src/shared'; @Component({ selector: 'app-list', templateUrl: './list.component.html', styleUrls: ['./list.component.scss'] }) export class ListComponent { resource: string; constructor(private route: ActivatedRoute) { this.route.params.subscribe(params => this.init(params)); } private init({ resource }: Params) { this.resource = resource; } } <file_sep>import { Routes } from '@angular/router'; import { ResourceComponent } from './resource.component'; import { ListComponent } from './list/list.component'; export const resourceRoutes: Routes = [ { path: '', component: ResourceComponent }, { path: ':resource', component: ListComponent }, ]; <file_sep>import { Component } from '@angular/core'; import { ConfigService } from './core/services/config.service'; import { ModelService } from './core/services/model.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { apiResources; constructor(public meta: ConfigService, private models: ModelService) { this.apiResources = models.getIds(); } } <file_sep>import { Model } from '@model/model'; export const userModel = new Model('User'); <file_sep>import { Model } from '@model/model'; export const sampleModel = new Model('Sample');
df59ddb831d6e230916bfc4c5ff2766248fa7d34
[ "TypeScript" ]
11
TypeScript
DawnAngel/rest-api-admin
3fe19c92debb671167ecf9159784d9d794d63434
d10314db1ec704480f13a223d56730b6413e197a
refs/heads/master
<repo_name>mthiesen/jonathan_converter<file_sep>/src/lib.rs use eyre::bail; use eyre::Result; use eyre::WrapErr; use rayon::prelude::*; use std::{ fs::{read_dir, DirBuilder, File, OpenOptions}, io::{BufWriter, Read, Write}, path::{Path, PathBuf}, }; // ------------------------------------------------------------------------------------------------- const GFX_INPUT_DIR: &str = "GRAFIK"; const GFX_OUTPUT_DIR: &str = "GRAFIK_PNG"; const TEXT_INPUT_DIR: &str = "TEXT"; const TEXT_OUTPUT_DIR: &str = "TEXT_TXT"; #[cfg(windows)] const LINE_ENDING: &str = "\r\n"; #[cfg(not(windows))] const LINE_ENDING: &str = "\n"; // ------------------------------------------------------------------------------------------------- fn is_file_with_extension(path: &Path, extension_upper: &str) -> bool { if path.is_file() { path.extension().map_or(false, |e| { e.to_str() .map_or(false, |e| e.to_uppercase() == extension_upper) }) } else { false } } fn create_output_file(path: &Path) -> Result<File> { let file = OpenOptions::new() .write(true) .truncate(true) .create(true) .open(&path) .wrap_err_with(|| { format!( "Unable to create '{}'. Is the path writable?", path.display() ) })?; Ok(file) } fn to_output_filename( input_path: &Path, output_path: &Path, output_extension: &str, ) -> Result<PathBuf> { let stem = match input_path.file_stem() { Some(stem) => stem, None => bail!( "Input path '{}' does not have a stem.", input_path.display() ), }; let mut output_filename = PathBuf::new(); output_filename.push(output_path); output_filename.push(stem); output_filename.set_extension(output_extension); Ok(output_filename) } fn read_file_contents(filename: &Path) -> Result<Vec<u8>> { let mut input_file = OpenOptions::new() .read(true) .open(filename) .wrap_err_with(|| format!("Unable to open input file '{}'.", filename.display()))?; let mut contents = Vec::new(); let _ = input_file .read_to_end(&mut contents) .wrap_err_with(|| format!("Unable to read input file '{}'.", filename.display()))?; Ok(contents) } fn convert_pcx(input_filename: &Path, output_filename: &Path) -> Result<()> { let input_file_contents = { let mut input_file_contents = read_file_contents(input_filename)?; if input_file_contents.len() < 4 { bail!( "'{}' is too small to be a valid PCX file.", input_filename.display() ); } input_file_contents[0] = 0x0a; input_file_contents[1] = 0x05; input_file_contents[2] = 0x01; input_file_contents[3] = 0x08; input_file_contents }; let mut pcx_file = pcx::Reader::new(input_file_contents.as_slice()).wrap_err_with(|| { format!( "Unable to read contents of '{}' as PCX file.", input_filename.display() ) })?; if !pcx_file.is_paletted() || pcx_file.palette_length().unwrap_or(0) != 256 { bail!( "'{}' does not contain a 256 color PCX palette.", input_filename.display() ); } let width = pcx_file.width() as usize; let height = pcx_file.height() as usize; let image_data = { let mut image_data = vec![0u8; width * height]; for y in 0..height { let begin = width * y; let end = begin + width; pcx_file .next_row_paletted(&mut image_data[begin..end]) .wrap_err_with(|| { format!( "Error occurred while decoding '{}'.", input_filename.display() ) })?; } image_data }; let palette_data = { let mut palette_data = vec![0u8; 256 * 3]; let _ = pcx_file.read_palette(&mut palette_data).wrap_err_with(|| { format!( "Error occurred while decoding palette of '{}'.", input_filename.display() ) })?; palette_data }; let writer = BufWriter::new(create_output_file(output_filename)?); let mut png_encoder = png::Encoder::new(writer, width as u32, height as u32); png_encoder.set_color(png::ColorType::Indexed); png_encoder.set_depth(png::BitDepth::Eight); png_encoder.set_palette(palette_data); let mut png_writer = png_encoder .write_header() .wrap_err_with(|| format!("Unable to write to '{}'.", output_filename.display()))?; png_writer .write_image_data(&image_data) .wrap_err_with(|| format!("Unable to write to '{}'.", output_filename.display()))?; Ok(()) } fn convert_dir( input_path: &Path, input_extension: &str, output_path: &Path, output_extension: &str, conversion_fn: &(dyn Fn(&Path, &Path) -> Result<()> + Sync), ) -> Result<()> { let dir_reader = read_dir(&input_path).wrap_err_with(|| { format!( "Unable to read directory '{}'. Is the provided path correct?", input_path.display() ) })?; let _ = DirBuilder::new().create(&output_path); let files_to_convert = { let mut files_to_convert = Vec::new(); for entry in dir_reader { let entry = entry.wrap_err_with(|| { format!( "Unable to read directory entry in '{}'.", input_path.display() ) })?; let input_filename = entry.path(); if is_file_with_extension(&input_filename, input_extension) { let output_filename = to_output_filename(&input_filename, output_path, output_extension) .wrap_err_with(|| { format!( "Unable to create output filename for input file '{}'.", input_filename.display() ) })?; files_to_convert.push((input_filename.to_owned(), output_filename)); } } files_to_convert }; files_to_convert .par_iter() .for_each(|(input_filename, output_filename)| { println!( "Converting '{}' to '{}' ...", input_filename.display(), output_filename.display() ); let conversion_result = conversion_fn(input_filename, output_filename).wrap_err_with(|| { format!( "Unable to convert '{}' to '{}'.", input_filename.display(), output_filename.display() ) }); if let Err(err) = conversion_result { println!("{:#}", err); } }); Ok(()) } fn convert_graphics(root_dir: &str) -> Result<()> { let gfx_input_path: PathBuf = [root_dir, GFX_INPUT_DIR].iter().collect(); let gfx_output_path: PathBuf = [root_dir, GFX_OUTPUT_DIR].iter().collect(); convert_dir( &gfx_input_path, "PCX", &gfx_output_path, "PNG", &convert_pcx, ) } fn convert_txt(input_filename: &Path, output_filename: &Path) -> Result<()> { let file_contents = read_file_contents(input_filename)?; let converted_file_contents = { let mut s = String::with_capacity(file_contents.len()); s.push('\u{feff}'); for &c in &file_contents { match c { 10 => s.push_str(LINE_ENDING), 11..=136 => s.push((c - 10) as char), 139 => s.push('ü'), 164 => s.push('Ü'), 142 => s.push('ä'), 152 => s.push('Ä'), 158 => s.push('ö'), 163 => s.push('Ö'), 183 => s.push('ô'), 235 => s.push('ß'), _ => bail!( "'{}' contains illegal character {}", input_filename.display(), c ), }; } s }; let mut file = create_output_file(output_filename)?; file.write_all(converted_file_contents.as_bytes()) .wrap_err_with(|| format!("Unable to write to '{}'.", output_filename.display()))?; Ok(()) } fn convert_texts(root_dir: &str) -> Result<()> { let txt_input_path: PathBuf = [root_dir, TEXT_INPUT_DIR].iter().collect(); let txt_output_path: PathBuf = [root_dir, TEXT_OUTPUT_DIR].iter().collect(); convert_dir( &txt_input_path, "TCT", &txt_output_path, "TXT", &convert_txt, ) } pub fn run(root_dir: &str) -> Result<()> { println!("Converting graphics ..."); convert_graphics(root_dir)?; println!(); println!("Converting texts ..."); convert_texts(root_dir)?; Ok(()) } <file_sep>/README.md ## Usage: ``` jonathan_converter 1.0.0 <NAME> <<EMAIL>> Converts the graphics and text resources of the classic adventure game 'Jonathan' to regular PNG and TXT files USAGE: jonathan_converter.exe [DIRECTORY] FLAGS: -h, --help Prints help information -V, --version Prints version information ARGS: <DIRECTORY> The root directory of the 'Jonathan' game The PCX files in the GRAFIK directory are converted to PNG files and written to the new directory GRAFIK_PNG. The TCT files in the TEXT directory are converted to UTF-8 text files and written to the new directory TEXT_TXT. ``` <file_sep>/Cargo.toml [package] name = "jonathan_converter" version = "1.0.0" edition = "2018" description = "Converts the graphics and text resources of the classic adventure game 'Jonathan' to regular PNG and text files" authors = ["<NAME> <<EMAIL>>"] [dependencies] clap = "4.0.18" eyre = "0.6.8" pcx = "0.2" png = "0.17.7" rayon = "1.5.3" [dev-dependencies] data-encoding = "2.3.2" fs_extra = "1.2.0" ring = "0.16.20" tempfile = "3.3.0" <file_sep>/src/main.rs use clap::{Arg, Command}; use std::io::prelude::*; fn pause() { let mut stdin = std::io::stdin(); let mut stdout = std::io::stdout(); write!(stdout, "Press return to continue...").unwrap(); stdout.flush().unwrap(); let _ = stdin.read(&mut [0u8]).unwrap(); } fn main() { let matches = Command::new(env!("CARGO_PKG_NAME")) .author(env!("CARGO_PKG_AUTHORS")) .version(env!("CARGO_PKG_VERSION")) .about(env!("CARGO_PKG_DESCRIPTION")) .arg(Arg::new("DIRECTORY") .help("The root directory of the 'Jonathan' game. By default the current directory is used.") .index(1)) .after_help("The PCX files in the GRAFIK directory are converted to PNG files and written to the new directory GRAFIK_PNG.\n\ The TCT files in the TEXT directory are converted to UTF-8 text files and written to the new directory TEXT_TXT.") .get_matches(); println!(concat!( env!("CARGO_PKG_NAME"), " ", env!("CARGO_PKG_VERSION") )); println!(env!("CARGO_PKG_AUTHORS")); println!(); if let Err(ref err) = jonathan_converter::run(matches.get_one::<String>("DIRECTORY").unwrap_or(&".".to_string())) { eprintln!("{err:#}"); pause(); std::process::exit(1); } else { pause(); } }
9c52ebd90681bb7970cf25a116ff59bcfb870302
[ "Markdown", "Rust", "TOML" ]
4
Rust
mthiesen/jonathan_converter
7ed74abdfe526c5f5c58140a8e54b901a6b239a4
12f43ef059d81bf0f336c523999f64e331e5ce7f
refs/heads/main
<file_sep>package com.test; interface ICalculator{ public int add(int x, int y); } public class Sp02_Lambda { public static void main(String[] args) { ICalculator calc = new ICalculator() { public int add(int a, int b) { return a + b; } }; int c = calc.add(30, 50); System.out.println(c); ICalculator calc2 = (x, y) -> { return x + y; }; int f = calc2.add(30, 100); System.out.println(f); } } <file_sep># JavaWorkshop01 #Kel Kel Kelthaas
6599efcd5fd853ec5c045f1e3bce2146208353e8
[ "Markdown", "Java" ]
2
Java
Gamaspin/JavaWorkshop01
409057fac721520a9f1de99e80f9b2547d80d278
efe48b0c021de287191cb874c8a435be3aaaf28a
refs/heads/master
<repo_name>devsubhajit/devsubhajit.github.io<file_sep>/finescroll/js/scrollbar.js (function ($) { $.fn.finescroll = function (options) { var defaults = { alignment: "right", value:'0px', width:'10px', bgColor:'rgba(0,0,0,0.4)', fgColor:'rgba(0,0,0,0.7)' }; var settings = $.extend({}, defaults, options); return this.each(function () { var isdrag = false; var $obj = $(this); $($obj).css({ width: 'calc(100% + 20px)', overflowY: 'auto', overflowX: 'hidden', position: 'relative', height: '100%' }); var $objHeight = $($obj).innerHeight(); var $objMargins = parseInt($($obj).find('ul').css('margin-top')) + parseInt($($obj).find('ul').css('margin-bottom')); var $objInnerHeight = $($obj).children().innerHeight(); $($obj).wrap("<div class='scrollCont' style='height:" + $objHeight + "px; position:relative;'></div>"); $($obj).parent(".scrollCont").append("<div class='scroll-line'><div class='scroll-backbar'></div><div class='scroll-bar'></div><div class='scrollup'></div><div class='scrolldown'></div></div>"); $($obj).parent(".scrollCont").find(".scroll-line").css({ position:'absolute', top:'0', width:settings.width, backgroundColor:settings.bgColor, height: $objHeight - ($objMargins / 2) + 'px' }); if(settings.alignment === 'right'){ $($obj).parent(".scrollCont").find(".scroll-line").css({ right:settings.value, left:'auto' }) }else if(settings.alignment === 'left'){ $($obj).parent(".scrollCont").find(".scroll-line").css({ left:settings.value, right:'auto' }) }else{ return false; } $($obj).parent(".scrollCont").find(".scroll-bar").css({ position:'absolute', top:'0', left:'0', width:settings.width, backgroundColor:settings.fgColor, height: $objInnerHeight - ($objHeight - ($objMargins / 2)) + 'px' }); $($obj).parent(".scrollCont").find(".scroll-backbar").css({ position:'absolute', top:'0', left:'0', width:'100%', backgroundColor:'transparent', height: '100%' }); var lst = $objInnerHeight - $objHeight; var visibleDiff = ($objHeight - ($objMargins / 2)) - ($objInnerHeight - ($objHeight - ($objMargins / 2))); console.log(visibleDiff); /* The Math for custom scrollBar * latestscrollTop => lst = (height of scroll element) - (height of container) * visible scrolling area on bar => vsab => visibleDiff = (height of scroll line) - (height of scroll bar); * * suppose currnet scrollTop = x; * ans : (x * vsab)/ latestscrollTop => ((st * visibleDiff)/lst) */ $($obj).scroll(function () { if (isdrag === false) { var st = $(this).scrollTop(); $($obj).parent(".scrollCont").find(".scroll-bar").css({ top: ((st * visibleDiff) / lst) + 'px' }); } else { return false; } }); $($obj).parent(".scrollCont").find(".scroll-bar ").draggable({ containment: "parent", axis: "y", drag: function () { isdrag = true; var $thistop = $(this).css('top'); var newScrollTop = (parseInt($thistop) * lst) / visibleDiff; $($obj).scrollTop(newScrollTop); }, stop: function () { isdrag = false; } }); $($obj).parent(".scrollCont").find(".scroll-backbar").click(function(e){ var scrollBar = $($obj).parent(".scrollCont").find(".scroll-bar "); // scroll bar var offTop = $(scrollBar).offset().top - $($obj).offset().top; // scroll bars offset top var posY = $(this).offset().top; var actualClickValue = e.pageY - posY; // position of clicked point var cst = $($obj).scrollTop(); if(actualClickValue > offTop){ var scrollYvalue = actualClickValue - (offTop + $(scrollBar).height()); var moreScroll = ((offTop +scrollYvalue) * lst) / visibleDiff; $($obj).scrollTop(moreScroll); }else{ var scrollYvalueless = offTop - actualClickValue; var lessScroll = ((offTop - scrollYvalueless) * lst) / visibleDiff; $($obj).scrollTop(lessScroll); } }); }); }; }(jQuery));<file_sep>/README.md # devsubhajit.github.io MEAN / UI Developer <file_sep>/js/easyUI-effects.js /* * 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. */ var screenWidth = window.innerWidth; var screenHeight = window.innerHeight; function bubbleEffect() { var mainCanvas = document.getElementById("myCanvas"); var themeColor = mainCanvas.getAttribute('data-theme'); mainCanvas.setAttribute('width', screenWidth); mainCanvas.setAttribute('height', screenHeight); var mainContext = mainCanvas.getContext('2d'); var circles = new Array(); var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; function Circle(radius, speed, width, xPos, yPos) { this.radius = radius; this.speed = speed; this.width = width; this.xPos = xPos; this.yPos = yPos; this.opacity = .05 + Math.random() * .5; this.counter = 0; var signHelper = Math.floor(Math.random() * 2); if (signHelper == 1) { this.sign = -1; } else { this.sign = 1; } } Circle.prototype.update = function () { this.counter += this.sign * this.speed; mainContext.beginPath(); mainContext.arc(this.xPos + Math.cos(this.counter / 100) * this.radius, this.yPos + Math.sin(this.counter / 100) * this.radius, this.width, 0, Math.PI * 2, false); mainContext.closePath(); mainContext.fillStyle = 'rgba(' + themeColor + ',' + this.opacity + ')'; mainContext.fill(); }; function drawCircles() { for (var i = 0; i < 100; i++) { var randomX = Math.round(-200 + Math.random() * screenWidth + 100); var randomY = Math.round(-200 + Math.random() * screenHeight + 200); var speed = .2 + Math.random() * 3; var size = 5 + Math.random() * 5; var circle = new Circle(25, speed, size, randomX, randomY); circles.push(circle); } draw(); } drawCircles(); function draw() { mainContext.clearRect(0, 0, screenWidth, screenHeight); for (var i = 0; i < circles.length; i++) { var myCircle = circles[i]; myCircle.update(); } requestAnimationFrame(draw); } } // ------------- particle effects -------------- function particleEffect() { var NUM_PARTICLES = ((ROWS = 60) * (COLS = 600)), THICKNESS = Math.pow(50, 2), SPACING = 3, MARGIN = 100, COLOR = 000, DRAG = 0.95, EASE = 0.25, container, particle, canvas, mouse, stats, list, ctx, tog, man, dx, dy, mx, my, d, t, f, a, b, i, n, w, h, p, s, r, c; particle = { vx: 0, vy: 0, x: 0, y: 0 }; function init() { container = document.getElementById('container'); canvas = document.createElement('canvas'); ctx = canvas.getContext('2d'); man = false; tog = true; list = []; w = canvas.width = COLS * SPACING + MARGIN * 2; h = canvas.height = ROWS * SPACING + MARGIN * 2; container.style.marginLeft = Math.round(w * -0.5) + 'px'; container.style.marginTop = Math.round(h * -0.5) + 'px'; container.style.opacity = 0.7; for (i = 0; i < NUM_PARTICLES; i++) { p = Object.create(particle); p.x = p.ox = MARGIN + SPACING * (i % COLS); p.y = p.oy = MARGIN + SPACING * Math.floor(i / COLS); list[i] = p; } container.addEventListener('mousemove', function (e) { bounds = container.getBoundingClientRect(); mx = e.clientX - bounds.left; my = e.clientY - bounds.top; man = true; }); if (typeof Stats === 'function') { document.body.appendChild((stats = new Stats()).domElement); } container.appendChild(canvas); } function step() { if (stats) stats.begin(); if (tog = !tog) { if (!man) { t = +new Date() * 0.001; mx = w * 0.5 + (Math.cos(t * 2.1) * Math.cos(t * 0.9) * w * 0.45); my = h * 0.5 + (Math.sin(t * 3.2) * Math.tan(Math.sin(t * 0.8)) * h * 0.45); } for (i = 0; i < NUM_PARTICLES; i++) { p = list[i]; d = (dx = mx - p.x) * dx + (dy = my - p.y) * dy; f = -THICKNESS / d; if (d < THICKNESS) { t = Math.atan2(dy, dx); p.vx += f * Math.cos(t); p.vy += f * Math.sin(t); } p.x += (p.vx *= DRAG) + (p.ox - p.x) * EASE; p.y += (p.vy *= DRAG) + (p.oy - p.y) * EASE; } } else { b = (a = ctx.createImageData(w, h)).data; for (i = 0; i < NUM_PARTICLES; i++) { p = list[i]; b[n = (~~p.x + (~~p.y * w)) * 4] = b[n + 1] = b[n + 2] = COLOR, b[n + 3] = 255; } ctx.putImageData(a, 0, 0); } if (stats) stats.end(); requestAnimationFrame(step); } init(); step(); } //window.onload = function(){ // var mainBody = document.getElementsByTagName('body')[0]; // var effect = mainBody.getAttribute('data-effect'); // if(effect === 'bubble'){ // bubbleEffect(); // } //};<file_sep>/js/easyUI-js.js /* * 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. */ var w = window.innerWidth; var h = window.innerHeight; var screenWidth = window.innerWidth; var screenHeight = window.innerHeight; function bubbleEffect() { var mainCanvas = document.getElementById("myCanvas"); var themeColor = mainCanvas.getAttribute('data-theme'); mainCanvas.setAttribute('width', screenWidth); mainCanvas.setAttribute('height', screenHeight); var mainContext = mainCanvas.getContext('2d'); var circles = new Array(); var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; function Circle(radius, speed, width, xPos, yPos) { this.radius = radius; this.speed = speed; this.width = width; this.xPos = xPos; this.yPos = yPos; this.opacity = .05 + Math.random() * .5; this.counter = 0; var signHelper = Math.floor(Math.random() * 2); if (signHelper == 1) { this.sign = -1; } else { this.sign = 1; } } Circle.prototype.update = function () { this.counter += this.sign * this.speed; mainContext.beginPath(); mainContext.arc(this.xPos + Math.cos(this.counter / 100) * this.radius, this.yPos + Math.sin(this.counter / 100) * this.radius, this.width, 0, Math.PI * 2, false); mainContext.closePath(); mainContext.fillStyle = 'rgba(' + themeColor + ',' + this.opacity + ')'; mainContext.fill(); }; function drawCircles() { for (var i = 0; i < 100; i++) { var randomX = Math.round(-200 + Math.random() * screenWidth + 100); var randomY = Math.round(-200 + Math.random() * screenHeight + 200); var speed = .2 + Math.random() * 3; var size = 5 + Math.random() * 5; var circle = new Circle(25, speed, size, randomX, randomY); circles.push(circle); } draw(); } drawCircles(); function draw() { mainContext.clearRect(0, 0, screenWidth, screenHeight); for (var i = 0; i < circles.length; i++) { var myCircle = circles[i]; myCircle.update(); } requestAnimationFrame(draw); } } //window.onload = function(){ // var mainBody = document.getElementsByTagName('body')[0]; // var effect = mainBody.getAttribute('data-effect'); // if(effect === 'bubble'){ // bubbleEffect(); // } //}; function globalFunctions() { var souzi = document.getElementById('souzi'); // var souziPulse = souzi.getElementsByClassName('easyui-puller-effect')[0]; var souzimsg = souzi.getElementsByClassName('souzi-messageBox')[0]; var souziexp = souzi.getElementsByClassName('souzi-expressions')[0]; var uilogo = document.getElementsByClassName('easyui-logo')[0]; var uinav = uilogo.getElementsByClassName('easyui-navigation')[0]; var followMebuble = document.getElementsByClassName('easyui-pullbox'); var aboutUI = document.getElementById('easyui-about'); var menuList = uinav.getElementsByTagName('li'); window.onmousedown = function () { uinav.style.opacity = 0; setTimeout(function () { uinav.style.display = 'none'; }, 600); }; uilogo.onmousedown = function (event) { event = event || window.event // cross-browser event if (event.stopPropagation) { event.stopPropagation() } else { event.cancelBubble = true } uinav.style.display = 'block'; setTimeout(function () { uinav.style.opacity = 1; }, 10); }; for (liNumber = 0; liNumber < menuList.length; liNumber++) { menuList[liNumber].onmouseover = function () { var subnav = this.getElementsByTagName('ul')[0]; if (subnav !== undefined) { subnav.style.display = 'block'; } }; menuList[liNumber].onmouseout = function () { var subnav = this.getElementsByTagName('ul')[0]; if (subnav !== undefined) { subnav.style.display = 'none'; } }; } for (followLi = 0; followLi < followMebuble.length; followLi++) { var clicks = 0; followMebuble[followLi].onmousedown = function () { clicks += 1; if (clicks === 1) { souzi.style.left = (5 + Math.random() * 50) + '%'; souzi.style.top = (5 + Math.random() * 30) + '%'; souzi.classList.add('active'); souzimsg.style.opacity = 1; souzimsg.innerHTML = 'hello, I am friend of Subhajit, your guide for this website'; souziexp.innerHTML = ': D'; setTimeout(function () { souzimsg.innerHTML = 'follow me'; souziexp.innerHTML = ': )'; }, 4000); setTimeout(function () { souzimsg.innerHTML = ''; souzimsg.style.opacity = 0; souzimsg.style.padding = 0 + 'px'; // -------- animating souzi to left ----- var souzileft = souzi.offsetLeft; function frame() { souzileft++; souzi.style.left = souzileft + 'px'; // show frame if (souzileft === (w - 60)) { // check finish condition clearInterval(souziid); aboutUI.style.left = 98 + '%'; souzimsg.innerHTML = 'pull me left'; souzimsg.style.left = 'auto'; souzimsg.style.right = '30px'; souzimsg.style.opacity = '1'; souzimsg.style.textAlign = 'right'; } } var souziid = setInterval(frame, 2); // draw every 2ms souzi.onmousedown = function () { var auiLef = aboutUI.offsetWidth; var souziLeft = souzi.offsetLeft; document.onmousemove = function (e) { souzi.classList.remove('easyui-commonTrans'); aboutUI.classList.remove('easyui-commonTrans'); e = e || event; souzi.style.left = e.pageX - 25 + 'px'; souzi.style.top = e.pageY - 25 + 'px'; // // ------ opening the about element var souziLeft2 = souzi.offsetLeft; if (souziLeft >= (w - 100)) { souzimsg.innerHTML = ''; souziexp.innerHTML = ': x'; aboutUI.style.left = (e.pageX + 10) + 'px'; var aboutUIleft = aboutUI.offsetLeft; if (aboutUIleft <= (w - (auiLef - 20))) { souzi.style.left = e.pageX - 25 + 'px'; document.onmousemove = null; souzimsg.innerHTML = 'Done'; souziexp.innerHTML = ': )'; setTimeout(function () { souziexp.innerHTML = ''; souzimsg.innerHTML = ''; souzi.classList.remove('active'); document.getElementById('blackOverlay').style.display = 'block'; aboutUI.style.backgroundColor = 'rgba(255,255,255,1)'; aboutUI.getElementsByTagName('header')[0].style.opacity = 1;// setTimeout(function () { document.getElementById('closeAboutUI-easyui').style.bottom = 0; }, 500); }, 1000); } this.onmouseup = function () { document.onmousemove = null; if (aboutUIleft > (w - (auiLef - 30))) { souzi.classList.add('easyui-commonTrans'); aboutUI.classList.add('easyui-commonTrans'); souzimsg.innerHTML = 'pul for about'; souziexp.innerHTML = ': o'; setTimeout(function () { aboutUI.style.left = (w - 10) + 'px'; souzi.style.left = w - 50 + 'px'; }, 100); // } }; } if (souziLeft2 >= (w - 60)) { aboutUI.style.left = 99 + '%'; souzimsg.innerHTML = 'Ready to go'; souziexp.innerHTML = ': o'; } }; this.onmouseup = function () { document.onmousemove = null; }; }; document.getElementById('closeAboutUI-easyui').onclick = function () { this.setAttribute("style", " "); setTimeout(function () { aboutUI.classList.add('easyui-commonTrans'); aboutUI.getElementsByTagName('header')[0].style.opacity = 0; aboutUI.style.backgroundColor = 'rgba(0,0,0,0.5)'; setTimeout(function () { aboutUI.style.left = 100 + '%'; document.getElementById('blackOverlay').setAttribute("style", " "); }, 100); }, 500); setTimeout(function () { souzi.classList.add('active'); souzi.style.left = (5 + Math.random() * 50) + '%'; souziexp.innerHTML = ': ?'; aboutUI.getElementsByTagName('header')[0].setAttribute("style", " "); aboutUI.setAttribute("style", " "); }, 800); }; souzi.ondragstart = function () { return false; }; }, 6000); } if (clicks >= 2) { souzimsg.innerHTML = 'to view this, move me to the left'; souziexp.innerHTML = ': {o'; setTimeout(function () { souzimsg.innerHTML = ''; souziexp.innerHTML = ': |'; }, 7000); } }; } } function showCoords(event) { var movespeed = 50; var canmovespeed = 3.5; var uilogo = document.getElementsByClassName('easyui-logo')[0]; var mainCanvas = document.getElementById("myCanvas"); var docx = event.clientX; var docy = event.clientY; var xcenter = window.innerWidth / 2; var ycenter = window.innerHeight / 2; var dx = xcenter - docx; var dy = ycenter - docy; uilogo.style.left = -dx * movespeed / 100 + 'px'; uilogo.style.top = -dy * movespeed / 100 + 'px'; mainCanvas.style.left = -dx * canmovespeed / 100 + 'px'; mainCanvas.style.top = -dy * canmovespeed / 100 + 'px'; } function productGlobals() { var aboutProduct = document.getElementsByClassName('easyui-product-about-switch')[0]; var overlayBlack = document.getElementById('blackOverlay'); var allUi = document.getElementById('alui'); aboutProduct.onclick = function () { if (this.innerHTML === '||||') { this.innerHTML = 'X'; this.style.color = '#fff'; this.style.transform = 'rotate(0deg)'; overlayBlack.style.display = 'block'; document.getElementsByClassName('about-product-info')[0].style.right = 0 + 'px'; }else if(this.innerHTML === 'X') { this.innerHTML = '||||'; this.removeAttribute('style'); overlayBlack.style.display = 'none'; document.getElementsByClassName('about-product-info')[0].style.right = -502 + 'px'; } }; allUi.onclick = function(){ if(this.innerHTML === 'All UI'){ this.innerHTML = 'close'; document.getElementById('uilist').style.left = 0+'px'; }else if(this.innerHTML === 'close') { this.innerHTML = 'All UI'; document.getElementById('uilist').style.left = -200+'px'; } }; } function touchHandler(event) { var touch = event.changedTouches[0]; var simulatedEvent = document.createEvent("MouseEvent"); simulatedEvent.initMouseEvent({ touchstart: "mousedown", touchmove: "mousemove", touchend: "mouseup" }[event.type], true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null); touch.target.dispatchEvent(simulatedEvent); event.preventDefault(); } function init() { document.addEventListener("touchstart", touchHandler, true); document.addEventListener("touchmove", touchHandler, true); document.addEventListener("touchend", touchHandler, true); document.addEventListener("touchcancel", touchHandler, true); } // -- call **init()** in document.ready function // ---------------- canvas ------------- effect ------------- window.onload = function () { init(); var mainBody = document.getElementsByTagName('body')[0]; var pagename = mainBody.getAttribute('data-page'); if (pagename === 'index') { globalFunctions(); } if (pagename === 'product') { productGlobals(); } var effect = mainBody.getAttribute('data-effect'); if (effect === 'bubble') { bubbleEffect(); } if(effect === 'particle'){ particleEffect(); } }; window.onmousemove = function (event) { var mainBody = document.getElementsByTagName('body')[0]; var pagename = mainBody.getAttribute('data-page'); if (pagename === 'index') { showCoords(event); } };
d9bc1370ddc8e429e6e4316f24bbe29d508759f9
[ "JavaScript", "Markdown" ]
4
JavaScript
devsubhajit/devsubhajit.github.io
3a8bd973a4a8f71e9a11484a7494fba02b7974c8
2b8370dba8dc07f984dd874835bf91e6b562b739
refs/heads/master
<file_sep>package Eliza; public class Main { /** * @param args */ public static void main(String[] args) { ElizaMain e = new ElizaMain(); e.readScript(false, "/script"); String name = ""; String room_address = ""; try { name = args[0].toString(); room_address = args[1].toString(); System.out.println(args[0].toString()); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.runProgram("what's up?", null); e.runProgram("hello", null); e.runProgram("bye", null); } }
2222d0da3a047e00f3ae6c1fa066159243059486
[ "Java" ]
1
Java
luppittegui/chat
afdcbbde4275a3dc224e1641b483c71b32869b8e
6e8bf6c80ebd09f576e4699106856f5f6b1f0628
refs/heads/master
<repo_name>alfdahlman/sw-react<file_sep>/src/components/SingleMovie/SingleMovie.js import React from 'react'; import './SingleMovie.css'; const singleMovie = (props) => { let content = ( <div className="no-content"> <p>No movie selected</p> </div> ) if(props.singleMovie?.fields){ content = ( <div className="content"> <h2>{ props.singleMovie?.fields?.title }</h2> <p>{ props.singleMovie?.fields?.opening_crawl }</p> <p>Directed by: { props.singleMovie?.fields?.director }</p> </div> ) } return ( <div className="single"> { content } </div> ); }; export default singleMovie; <file_sep>/src/App.js import React, { useEffect, useState } from 'react'; import axios from 'axios'; import Cockpit from './components/Cockpit/Cockpit'; import List from './components/List/List'; import SingleMovie from './components/SingleMovie/SingleMovie'; import './App.css'; const App = () => { const [movieList, setMovieList] = useState([]); const [displayedList, setDisplayedList] = useState([]); const [selectedMovie, setSelectedMovie] = useState({}); const [query, setQuery] = useState(''); useEffect(() => { axios.get('https://star-wars-api.herokuapp.com/films') .then( res => { setMovieList(res.data); setDisplayedList(res.data); }) .catch(err => console.log('Failed to fetch data', err)) }, []); const selectMovieHandler = (id) => { const selected = movieList.filter( mov => mov.id === id ); return setSelectedMovie({ ...selected[0] }); } const sortList = (property) => { const sortedList = movieList.sort((a, b) => { if (a.fields[property] < b.fields[property]) { return -1; } if (a.fields[property] > b.fields[property]) { return 1; } return 0; }); setMovieList([...sortedList]); if( query ){ return setDisplayedList( sortedList.filter(mov => mov.fields.title.toLowerCase().includes( query ) ) ); } return setDisplayedList([...sortedList]); } const searchList = (e) => { const searchQuery = e.currentTarget.value.toLowerCase(); const resultList = movieList.filter(mov => mov.fields.title.toLowerCase().includes( searchQuery )); setQuery(searchQuery); return setDisplayedList([...resultList]); } return ( <div className="App"> <Cockpit searchList={searchList} sortList={sortList}/> <List movies={displayedList} selectMovie={selectMovieHandler}/> <SingleMovie singleMovie={selectedMovie} /> </div> ); } export default App;
ef61eb7b11714e6059881b05a1c8f07d8029edaf
[ "JavaScript" ]
2
JavaScript
alfdahlman/sw-react
33d8bde6a67e7ce34aeffc3ee426245e4f0ec5b0
7a00a35131e4b899617d6fd81f0851a30a4ae416
refs/heads/main
<file_sep><?php namespace OguzhanUmutlu\AntiAuraBot; use pocketmine\entity\Entity; use pocketmine\event\entity\EntityDamageByEntityEvent; use pocketmine\event\entity\EntityDamageEvent; use pocketmine\event\Listener; use pocketmine\nbt\tag\ByteArrayTag; use pocketmine\nbt\tag\CompoundTag; use pocketmine\nbt\tag\StringTag; use pocketmine\Player; class EventListener implements Listener { /*** @var int[][] */ public $aps = []; /*** @var string[] */ public static $report = []; public function onDamage(EntityDamageEvent $event) { $player = $event->getEntity(); if(!$player instanceof Player || !$event instanceof EntityDamageByEntityEvent) return; $damage = $event->getDamager(); if(!$damage instanceof Player) return; if(!isset($this->aps[$damage->getName()]) || $this->aps[$damage->getName()][1] < time()) $this->aps[$damage->getName()] = [0, time()]; $this->aps[$damage->getName()][0]++; if(isset(self::$report[$damage->getName()])) return; if((in_array($damage->getName(), AntiAuraBot::$reports) && $this->aps[$damage->getName()][0] > 4) || (AntiAuraBot::$config->getNested("auto-report.enabled") && $this->aps[$damage->getName()][0] > AntiAuraBot::$config->getNested("auto-report.warns"))) { self::$report[$damage->getName()] = true; if(in_array($damage->getName(), AntiAuraBot::$reports)) unset(AntiAuraBot::$reports[array_search($damage->getName(), AntiAuraBot::$reports)]); $nbt = Entity::createBaseNBT($damage->add($damage->getDirectionVector()->multiply(-1))); $nbt->setTag(new CompoundTag("Skin", [ new StringTag("Name", $player->getSkin()->getSkinId()), new ByteArrayTag("Data", $player->getSkin()->getSkinData()), new StringTag("GeometryName", $player->getSkin()->getGeometryName()), new ByteArrayTag("GeometryData", $player->getSkin()->getGeometryData()) ])); $bot = Entity::createEntity("AntiAuraBotEntity", $damage->level, $nbt); if(!$bot instanceof BotEntity) return; $bot->hacker = $damage; $bot->hackerName = $damage->getName(); $bot->setNameTag($player->getNameTag()); $bot->setNameTagVisible(); $bot->setNameTagAlwaysVisible(); $bot->setScale($player->getScale()); $bot->setHealth($player->getHealth()); $bot->setMaxHealth($player->getMaxHealth()); $bot->setScoreTag($player->getScoreTag() ?? ""); $bot->lookAt($damage); $bot->spawnTo($damage); } } }<file_sep><?php namespace OguzhanUmutlu\AntiAuraBot; use pocketmine\command\ConsoleCommandSender; use pocketmine\entity\Human; use pocketmine\event\entity\EntityDamageByEntityEvent; use pocketmine\event\entity\EntityDamageEvent; use pocketmine\math\Vector3; use pocketmine\Player; use pocketmine\Server; class BotEntity extends Human { /*** @var Player|null */ public $hacker; public $hackerName = ""; public $teleportTick = 0; public $fullTicks = 0; public function onUpdate(int $currentTick): bool { $this->fullTicks++; if(!$this->hacker instanceof Player || $this->hacker->isClosed() || !$this->level || $this->fullTicks >= AntiAuraBot::$config->getNested("de"."spawn-seconds")*20) { $this->flagForDespawn(); return false; } switch(AntiAuraBot::$config->getNested("teleport.type")) { case "turn": $this->teleport( $this->hacker->add( $this->getCustomVector()->multiply( -AntiAuraBot::$config->getNested("teleport.back-multiplier")[array_rand(AntiAuraBot::$config->getNested("teleport.back-multiplier"))] ) )->add( 0, AntiAuraBot::$config->getNested("teleport.turn-y")[array_rand(AntiAuraBot::$config->getNested("teleport.turn-y"))] ), $this->yaw, $this->pitch ); $this->yaw+=AntiAuraBot::$config->getNested("teleport.turn-speed")[array_rand(AntiAuraBot::$config->getNested("teleport.turn-speed"))]; if($this->yaw > 360) $this->yaw-=360; break; case "fast-teleport": case "fastTeleport": if($this->teleportTick >= AntiAuraBot::$config->getNested("teleport.teleport-speed")) { $expand = AntiAuraBot::$config->getNested("teleport.teleport-range"); $expand = $expand[array_rand($expand)]; $airs = array_filter($this->getNearBlocks($this->hacker, $expand), function($block){ $similarity = abs($this->calculateLookHitBox($this->hacker, $block)-(($this->hacker->yaw+$this->hacker->pitch)/2)); return $block->getId() == 0 && $similarity > 80; }); if(empty($airs)) break; $this->teleportTick = 0; $this->teleport($airs[array_rand($airs)]); $this->lookAt($this->hacker); } else $this->teleportTick++; break; case "back-side": case "backside": case "backSide": $this->lookAt($this->hacker); $this->teleport($this->hacker->add($this->getCustomHackerVector()->multiply(-AntiAuraBot::$config->getNested("teleport.back-multiplier")[array_rand(AntiAuraBot::$config->getNested("teleport.back-multiplier"))]))); break; } return true; } public function getCustomVector(): Vector3 { $y = -sin(deg2rad(0)); $xz = cos(deg2rad(0)); $x = -$xz * sin(deg2rad($this->yaw)); $z = $xz * cos(deg2rad($this->yaw)); return $this->temporalVector->setComponents($x, $y, $z)->normalize(); } public function getCustomHackerVector(): Vector3 { $y = -sin(deg2rad(0)); $xz = cos(deg2rad(0)); $x = -$xz * sin(deg2rad($this->hacker->yaw)); $z = $xz * cos(deg2rad($this->hacker->yaw)); return $this->temporalVector->setComponents($x, $y, $z)->normalize(); } public function calculateLookHitBox(Player $player, Vector3 $target) { $horizontal = sqrt(($target->x - $player->x) ** 2 + ($target->z - $player->z) ** 2); $vertical = $target->y - $player->y; $pitch = -atan2($vertical, $horizontal) / M_PI * 180; $xDist = $target->x - $player->x; $zDist = $target->z - $player->z; $yaw = atan2($zDist, $xDist) / M_PI * 180 - 90; if($yaw < 0) $yaw += 360.0; return ($yaw+$pitch)/2; } public function getNearBlocks(Player $player, int $length) : array{ $blocks = []; for($x=$player->x-$length;$x<=$player->x+$length;$x++) for($y=$player->y-$length;$y<=$player->y+$length;$y++) for($z=$player->z-$length;$z<=$player->z+$length;$z++) $blocks[] = $player->level->getBlock(new Vector3($x, $y, $z)); return $blocks; } public $warns = 0; public function attack(EntityDamageEvent $source): void { if($source instanceof EntityDamageByEntityEvent && $source->getDamager()->id == $this->hacker->id) $this->warns++; if($this->hacker instanceof Player && $this->hacker->isOnline() && $this->warns >= AntiAuraBot::$config->getNested("warns")) switch(AntiAuraBot::$config->getNested("punishment")) { case "kick": $this->hacker->kick(AntiAuraBot::$config->getNested("reason"), false); break; case "ban": $this->server->getNameBans()->addBan($this->getName(), AntiAuraBot::$config->getNested("reason"), null, "AntiAuraBot AC"); $this->hacker->kick(AntiAuraBot::$config->getNested("reason"), false); break; default: $cmd = AntiAuraBot::$config->getNested("punishment"); if(is_array($cmd)) foreach($cmd as $c) { Server::getInstance()->dispatchCommand(new ConsoleCommandSender(), $c); } else Server::getInstance()->dispatchCommand(new ConsoleCommandSender(), $cmd); break; } parent::attack($source); } public function kill(): void {$this->setHealth(20);} public function flagForDespawn(): void { unset(EventListener::$report[$this->hackerName]); parent::flagForDespawn(); } } <file_sep><?php namespace OguzhanUmutlu\AntiAuraBot; use pocketmine\command\Command; use pocketmine\command\CommandSender; use pocketmine\command\PluginIdentifiableCommand; use pocketmine\Player; use pocketmine\plugin\Plugin; use pocketmine\Server; class ReportCommand extends Command implements PluginIdentifiableCommand { public function __construct() { parent::__construct(AntiAuraBot::$config->getNested("report-command.name"), AntiAuraBot::$config->getNested("report-command.description"), null, []); } public function execute(CommandSender $sender, string $commandLabel, array $args) { if(!isset($args[0])) { $sender->sendMessage("§c> Usage: /".$this->getName()." <player".">"); return; } $player = Server::getInstance()->getPlayerExact($args[0]); if(!$player instanceof Player) { $sender->sendMessage("§c> Player not found!"); return; } if($player->getName() == $sender->getName()) { $sender->sendMessage("§c> You cannot report yourself!"); return; } if(isset(AntiAuraBot::$reports[$sender->getName()])) { $sender->sendMessage("§c> You already reported someone!"); return; } if(!in_array($player->getName(), AntiAuraBot::$reports)) AntiAuraBot::$reports[$sender->getName()] = $player->getName(); foreach(Server::getInstance()->getOnlinePlayers() as $p) if($p->hasPermission("anti"."aura"."bot.staff")) $p->sendMessage("§e> Player " .$sender->getName()." reported ".$player->getName()."!"); $sender->sendMessage("§a> Player reported!"); } public function getPlugin(): Plugin { return AntiAuraBot::$instance; } } <file_sep><?php namespace OguzhanUmutlu\AntiAuraBot; use pocketmine\entity\Entity; use pocketmine\plugin\PluginBase; use pocketmine\utils\Config; class AntiAuraBot extends PluginBase { /*** @var Config */ public static $config; public static $reports = []; /*** @var AntiAuraBot */ public static $instance; public function onEnable() { self::$instance = $this; $this->saveDefaultConfig(); self::$config = $this->getConfig(); Entity::registerEntity(BotEntity::class, true, ["AntiAuraBotEntity"]); if(self::$config->getNested("report-command.enabled")) $this->getServer()->getCommandMap()->register($this->getName(), new ReportCommand()); $this->getServer()->getPluginManager()->registerEvents(new EventListener(), $this); } }<file_sep># AntiAuraBot Perfect Anti Kill Aura for PocketMine-MP! # What it does? - It punishes kill aura hackers with bot! # TODO - idk. Discord: Oğuzhan#6561 for suggestions # Help/Suggestion/Bug Report - They can get help, suggest something or report some bugs here: https://github.com/OguzhanUmutlu/AntiAuraBot/issues - Also they can contact me on Discord: `Oğuzhan#6561`
f76717ffeee7f98fd2f1518163cc297809d61967
[ "Markdown", "PHP" ]
5
PHP
CoreDaDev/AntiAuraBot
b420d48214ff9003171d25c27d10283ce55cdf4e
06eeb3295900db083a0718866ced6e15c8351f00
refs/heads/master
<repo_name>deng565430/remotebranchmanagement<file_sep>/server/routers/home.js /* 子路由 */ const router = require('koa-router')(); const index = require('../controllers/index'); module.exports = router .get('/',index.index()) .get('getBranchInfo', index.getBranchInfo()) .get('createBranch', index.createBranch())
097b4ceffe23b2a918eed419e382d3a5b0af41ef
[ "JavaScript" ]
1
JavaScript
deng565430/remotebranchmanagement
2956d9ba4f6b9b55afe8c57b9832e096e23e3687
86e57d24c6603ac77a062692a3a25029fbd99e2b
refs/heads/master
<file_sep>const Discord = require('discord.js'); const moment = require('moment'); const { prefix, token } = require('./config.json') const client = new Discord.Client(); client.once('ready', () => { console.log('ready') }) client.on('message', message => { console.log(message.content); if(message.content.startsWith(`${prefix}time`)){ message.channel.send(moment().format('MMMM Do YYYY, h:mm:ss a')); } if(message.content.startsWith(`${prefix}beep`)){ message.channel.send('boop'); } if(message.content.startsWith(`${prefix}pic`)){ message.channel.send({files: ["./images/" + (getRandomInt(3) + 1) + ".png"]}); } if(message.content.startsWith(`${prefix}random`)){ message.channel.send(getRandomInt(10) + 1); } }) function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } client.login(token);
4488d428d61401b8a5ab30d8f088b41599aa6420
[ "JavaScript" ]
1
JavaScript
lolitsozzie/Simple-discord-bot
9abb9e0061b375f41932c95dbc079d674b522335
d4ea9a7bb1e0fb84c8c7ec2c38ae544182d0201d
refs/heads/master
<repo_name>virajnilakh/Part0<file_sep>/src/gash/router/client/WriteChannel.java package gash.router.client; import java.util.concurrent.Callable; import io.netty.channel.Channel; import routing.Pipe.CommandMessage; public class WriteChannel implements Callable<Long>{ //long id=0; //ArrayList<CommandMessage> messages= new ArrayList<CommandMessage>(); CommandMessage message; Channel channel; public WriteChannel(CommandMessage msg,Channel ch){ message=msg; channel=ch; } /*Needs refactoring*/ @Override public Long call(){ channel.writeAndFlush(message); return (long)1; } }<file_sep>/src/gash/router/client/Constants.java package gash.router.client; public class Constants { public static int sizeOfChunk=1024*1024*1; } <file_sep>/src/gash/router/app/DemoApp.java /** * Copyright 2016 Gash. * * This file and intellectual content is protected 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. */ package gash.router.app; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.logging.Logger; import com.google.protobuf.ByteString; import gash.router.client.CommConnection; import gash.router.client.CommListener; import gash.router.client.MessageClient; import gash.router.client.WriteChannel; import gash.router.server.CommandInit; import gash.router.server.WorkInit; import global.Constants; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import redis.clients.jedis.Jedis; import routing.Pipe.CommandMessage; public class DemoApp implements CommListener { private static MessageClient mc; public static Channel channel = null; private static Jedis jedisHandler1=new Jedis("169.254.214.175",6379); private static Jedis jedisHandler2=new Jedis("169.254.56.202",6379); private static Jedis jedisHandler3=new Jedis("169.254.80.87",6379); public static Jedis getJedisHandler1() { return jedisHandler1; } public static Jedis getJedisHandler2() { return jedisHandler2; } public static Jedis getJedisHandler3() { return jedisHandler3; } public DemoApp(MessageClient mc) { init(mc); } private void init(MessageClient mc) { this.mc = mc; this.mc.addListener(this); } private void ping(int N) { // test round-trip overhead (note overhead for initial connection) final int maxN = 10; long[] dt = new long[N]; long st = System.currentTimeMillis(), ft = 0; for (int n = 0; n < N; n++) { mc.ping(); ft = System.currentTimeMillis(); dt[n] = ft - st; st = ft; } System.out.println("Round-trip ping times (msec)"); for (int n = 0; n < N; n++) System.out.print(dt[n] + " "); System.out.println(""); } @Override public String getListenerID() { return "demo"; } @Override public void onMessage(CommandMessage msg) { System.out.println("---> " + msg); } /** * sample application (client) use of our messaging service * * @param args */ public static void main(String[] args) { String host = "127.0.0.1"; int port = 4568; Boolean affirm = true; Boolean mainAffirm = true; try { // MessageClient mc = new MessageClient(host, port); // DemoApp da = new DemoApp(mc); // do stuff w/ the connection // da.ping(2); // Logger.info("trying to connect to node " + ); if(jedisHandler1.ping().equals("PONG")){ host = jedisHandler1.get("1").split(":")[0]; port = Integer.parseInt(jedisHandler1.get("1").split(":")[1]); }else if(jedisHandler2.ping().equals("PONG")){ host = jedisHandler2.get("1").split(":")[0]; port = Integer.parseInt(jedisHandler2.get("1").split(":")[1]); }else if(jedisHandler3.ping().equals("PONG")){ host = jedisHandler3.get("1").split(":")[0]; port = Integer.parseInt(jedisHandler3.get("1").split(":")[1]); } EventLoopGroup workerGroup = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); // (1) b.group(workerGroup); // (2) b.channel(NioSocketChannel.class); // (3) b.option(ChannelOption.SO_KEEPALIVE, true); // (4) b.handler(new CommandInit(null, false)); // Start the client. System.out.println("Connect to a node."); ChannelFuture f = b.connect(host, port).sync(); // (5) channel = f.channel(); Scanner reader = new Scanner(System.in); try { int option = 0; System.out.println("Welcome to Gossamer Distributed"); System.out.println("Please choose an option to continue: "); System.out.println("1. Read a file"); System.out.println("2. Write a file"); System.out.println("0. Exit"); option = reader.nextInt(); // option = 2; // reader.nextLine(); System.out.println("You entered " + option); System.out.println("Press Y to continue or any other key to cancel"); String ans = ""; // ans=reader.nextLine(); // ans = "Y"; if (ans.equals("Y")) { mainAffirm = false; } String path = ""; switch (option) { case 1: break; case 2: // For testing writes // String path = runWriteTest(); System.out.println("Please enter directory (path) to upload:"); // path = reader.nextLine(); // path = "C:\\Songs\\1.mp4"; System.in.read(); System.out.println("You entered" + path); System.out.println("Press Y to continue or any other key to cancel"); affirm = false; String ans1 = ""; ans1 = reader.next(); // ans1 = "Y"; if (ans1.equals("Y")) { affirm = true; } reader.close(); File file = new File(path); long begin = System.currentTimeMillis(); System.out.println("Begin time"); System.out.println(begin); sendFile(file); System.out.println("File sent"); System.out.flush(); break; } } catch (Exception e) { // TODO Auto-generated catch block System.out.println("Error occurred..."); Thread.sleep(10 * 1000); e.printStackTrace(); } finally { System.out.println("Exiting..."); // Thread.sleep(10 * 1000); } // System.out.println("\n** exiting in 10 seconds. **"); // System.out.flush(); // Thread.sleep(10 * 1000); } catch ( Exception e) { e.printStackTrace(); } finally { // CommConnection.getInstance().release(); } } private static String runWriteTest() { String path = "C:\\1\\Natrang.avi"; return path; } private static void sendFile(File file) { // TODO Auto-generated method stub /* * Task 1: Send Read Command Task 2: Receive Ack Task 3: Split into * chunks Task 4: Send chunks Task 5: Recv Ack Task 6: Resend chunks not * ack */ sendReadCommand(file); } private static void sendReadCommand(File file) { // TODO Auto-generated method stub ArrayList<ByteString> chunksFile = new ArrayList<ByteString>(); ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); List<WriteChannel> futuresList = new ArrayList<WriteChannel>(); int sizeChunks = Constants.sizeOfChunk; int numChunks = 0; byte[] buffer = new byte[sizeChunks]; try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); String name = file.getName(); String hash = getHashFileName(name); int tmp = 0; while ((tmp = bis.read(buffer)) > 0) { try { ByteString bs = ByteString.copyFrom(buffer, 0, tmp); chunksFile.add(bs); numChunks++; } catch (Exception ex) { ex.printStackTrace(); } } for (int i = 0; i < chunksFile.size(); i++) { CommandMessage commMsg = MessageClient.sendWriteRequest(chunksFile.get(i), hash, name, numChunks, i + 1); WriteChannel myCallable = new WriteChannel(commMsg, channel); futuresList.add(myCallable); } System.out.println("No. of chunks: " + futuresList.size()); long start = System.currentTimeMillis(); System.out.print(start); System.out.println("Start send"); List<Future<Long>> futures = service.invokeAll(futuresList); System.out.println("Completed tasks"); service.shutdown(); } catch (Exception ex) { ex.printStackTrace(); } } private static String getHashFileName(String name) { // TODO Auto-generated method stub MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } digest.reset(); digest.update(name.getBytes()); byte[] bs = digest.digest(); BigInteger bigInt = new BigInteger(1, bs); String hashText = bigInt.toString(16); // Zero pad until 32 chars while (hashText.length() < 32) { hashText = "0" + hashText; } return hashText; } } <file_sep>/.metadata/version.ini #Mon Apr 03 03:13:14 PDT 2017 org.eclipse.core.runtime=2 org.eclipse.platform=4.6.1.v20160907-1200 <file_sep>/src/global/Constants.java package global; public class Constants { public static int sizeOfChunk = 1024 * 1024 * 1; public static String dataDir = "C:\\Gossamer\\"; }
ee52f96bf1df49b8425ec963e3d9a80cd7be6758
[ "Java", "INI" ]
5
Java
virajnilakh/Part0
93c1c0ef6bf9764983e4a63cd821c58b5de75c74
8cd82502304e908b4e6e54184dc3359fe8d3586e
refs/heads/master
<repo_name>phoenixTW/medly-components<file_sep>/packages/utils/src/hooks/useSWRAxios/types.ts import { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'; import { SWRConfiguration, SWRResponse } from 'swr'; export type AxiosConfig = AxiosRequestConfig & { url: string }; export type Return<Data = unknown, Error = unknown> = Omit<SWRResponse<AxiosResponse<Data>, AxiosError<Error>>, 'data' | 'error'> & { data?: Data; response?: AxiosResponse<Data>; error?: AxiosResponse<Error>; }; export type SWRConfig<Data = unknown, Error = unknown> = Omit<SWRConfiguration<AxiosResponse<Data>, AxiosError<Error>>, 'initialData'> & { initialData?: Data; }; <file_sep>/packages/core/src/components/Accordion/types.ts import { WithStyle } from '@medly-components/utils'; import type { Context, Dispatch, FC, SetStateAction } from 'react'; export type StaticProps = { Header: FC<HeaderProps> & WithStyle; Content: FC & WithStyle; Context: Context<AccordionContextType>; }; export type AccordionContextType = [ boolean /** Current active state */, Dispatch<SetStateAction<boolean>> /** Function to be called to toggle the active state */ ]; export type AccordionProps = { defaultActive?: boolean; active?: boolean; onChange?: Dispatch<SetStateAction<boolean>>; iconColor?: string; }; export type HeaderProps = { iconColor?: string; }; <file_sep>/packages/core/src/components/Breadcrumb/types.ts import { HTMLProps } from '@medly-components/utils'; import type { FC, ReactNode } from 'react'; export type BreadcrumbProps = Omit<HTMLProps<HTMLOListElement>, 'type'> & { /** You can pass any separator which you can use between the links */ separator?: string | ReactNode; }; export type BreadcrumbStaticProps = { Item: FC<HTMLProps<HTMLLIElement>>; Back: FC<HTMLProps<HTMLLIElement>>; }; <file_sep>/packages/utils/src/hooks/useSWRAxios/useSWRAxios.ts import axios, { AxiosError, AxiosResponse } from 'axios'; import useSWR from 'swr'; import { AxiosConfig, Return, SWRConfig } from './types'; const defaultSWRConfig = { revalidateOnMount: true, errorRetryCount: 5 }; /** * This react hook can be used to call the api using SWR and axios. SWR helps to cache the data. With SWR, components will get a stream of data updates constantly and automatically. And the UI will be always fast and reactive. * * @param {string | AxiosConfig} config can be either url or AxiosRequestConfig * @param {SWRConfig<Data, Error>} SWRConfig SWR config * * @returns {Return<Data, Error>} An object with data, response, request, isLoading and error */ export const useSWRAxios = <Data = unknown, Error = unknown>( config: string | AxiosConfig, { initialData, ...swrConfig }: SWRConfig<Data, Error> = {} ): Return<Data, Error> => { const axiosConfig = typeof config === 'string' ? { url: config } : config; const { data: axiosSuccessResponse, error: axiosErrorResponse, ...swrResponse } = useSWR<AxiosResponse<Data>, AxiosError<Error>>(axiosConfig.url, () => axios(axiosConfig), { ...defaultSWRConfig, ...swrConfig, initialData: initialData && { status: 200, statusText: 'InitialData', config: axiosConfig, headers: {}, data: initialData } }); return { data: axiosSuccessResponse?.data, response: axiosSuccessResponse, error: axiosErrorResponse?.response, ...swrResponse }; }; <file_sep>/packages/core/src/components/Breadcrumb/Breadcrumb.stories.mdx import { Breadcrumb } from './Breadcrumb.tsx'; import { Preview, Story, Meta, Props } from '@storybook/addon-docs/blocks'; import * as stories from './Breadcrumb.stories'; import { action } from '@storybook/addon-actions'; import Text from '../Text'; <Meta title="Core" component={Breadcrumb} /> # Breadcrumb A `Breadcrumb` is a list of links that help you visualize the location of the page within an application or website by showing the hierarchical structure. <Preview withToolbar> <Story name="Breadcrumb"> <Breadcrumb> <Breadcrumb.Item onClick={action('Home')}>Home</Breadcrumb.Item> <Breadcrumb.Item onClick={action('Article')}>Article</Breadcrumb.Item> <Breadcrumb.Item disabled onClick={action('Section')}> Section </Breadcrumb.Item> </Breadcrumb> </Story> </Preview> To perform on click action on any item, pass the `onClick` prop, and to disable any item, pass the `disabled` prop. Additionally, to use the back button, call `<Breadcrumb.Back />`. <Preview withToolbar> <Breadcrumb.Back onClick={action('Back')} /> </Preview> ## Props This component offers the following props mentioned in the table below: <Props of={Breadcrumb} /> ## BreadcrumbTheme This component offers the following themes mentioned in the table below: <Props of={stories.ThemeInterface} /> <file_sep>/rollup.config.js import babel from '@rollup/plugin-babel'; import commonjs from '@rollup/plugin-commonjs'; import resolve from '@rollup/plugin-node-resolve'; import typescript from '@rollup/plugin-typescript'; import svgr from '@svgr/rollup'; import path from 'path'; import { terser } from 'rollup-plugin-terser'; const PACKAGE_ROOT_PATH = process.cwd(), SRC = path.join(PACKAGE_ROOT_PATH, 'src'), INPUT = path.join(PACKAGE_ROOT_PATH, 'src/index.ts'), BABEL_CONFIG = path.join(PACKAGE_ROOT_PATH, '../../babel.config.js'), TS_CONFIG = path.join(PACKAGE_ROOT_PATH, '../../tsconfig.json'), PKG_JSON = require(path.join(PACKAGE_ROOT_PATH, 'package.json')); const extensions = ['.ts', '.tsx', '.js', '.jsx']; export default ['es', 'cjs'].map(format => ({ input: INPUT, preserveModules: true, external: [ ...Object.keys(PKG_JSON.peerDependencies || {}), ...Object.keys(PKG_JSON.dependencies || {}), 'date-fns', /@babel\/runtime/, 'react/jsx-runtime', 'react/jsx-dev-runtime' ], plugins: [ commonjs({ namedExports: { 'react/jsx-runtime': ['jsx', 'jsxs', 'Fragment'], 'react/jsx-dev-runtime': ['jsx', 'jsxs', 'jsxDEV'] } }), resolve({ extensions, customResolveOptions: { preserveSymlinks: false }, mainFields: ['module', 'main'] }), babel({ configFile: BABEL_CONFIG, extensions, include: ['src/**/*'], babelHelpers: 'runtime' }), typescript({ tsconfig: TS_CONFIG, rootDir: SRC, baseUrl: PACKAGE_ROOT_PATH, declaration: true, outDir: `dist/${format}`, exclude: ['**/test-utils.tsx', '**/*.test.tsx', '**/*.test.ts', '**/*.stories.tsx', '**/*.stories.mdx', '**/docs/**'], include: ['src/**/*', 'module.d.ts'] }), terser(), svgr({ native: true }) ], output: { format, exports: 'auto', dir: `dist/${format}` } }));
f8fe266a40fe2d1167dacaa4737c1519ee8fc8d1
[ "Markdown", "TypeScript", "JavaScript" ]
6
TypeScript
phoenixTW/medly-components
6ec538b80ec1c59a0ed44da0c1e6886c2d1288d0
eae6947ba018f72818fbc165c88b45317e2dcc08
refs/heads/master
<repo_name>CHOISEONGJU/mbticombi<file_sep>/js/mbticb.js var arr = []; //영역지정 for (var i = 0; i <= 15; i++) { arr[i] = []; for (var j = 0; j <= 15; j++) { arr[i][j] = 0; } } //오른쪽 아래 큰부분 for (var i = 4; i <= 15; i++) { for (var j = 4; j <= 15; j++) { arr[i][j] = 5; } } //왼쪽 위 for (var i = 0; i <= 7; i++) { for (var j = 0; j <= 7; j++) { arr[i][j] = 7; } } //오른쪽 아래 작은부분 for (var i = 12; i <= 15; i++) { for (var j = 12; j <= 15; j++) { arr[i][j] = 7; } } //왼쪽 위 for (var i = 0; i <= 3; i++) { for (var j = 8; j <= 15; j++) { arr[i][j] = 1; } } //왼쪽 아래 for (var i = 8; i <= 15; i++) { for (var j = 0; j <= 3; j++) { arr[i][j] = 1; } } //노란부분 for (var i = 8; i <= 11; i++) { for (var j = 8; j <= 11; j++) { arr[i][j] = 3; } } (arr[0][3] = 9), (arr[3][0] = 9); (arr[0][5] = 9), (arr[5][0] = 9); (arr[1][2] = 9), (arr[2][1] = 9); (arr[1][4] = 9), (arr[4][1] = 9); (arr[2][7] = 9), (arr[7][2] = 9); (arr[3][8] = 9), (arr[8][3] = 9); (arr[4][7] = 9), (arr[7][4] = 9); (arr[4][12] = 3), (arr[12][4] = 3); (arr[4][13] = 3), (arr[13][4] = 3); (arr[4][14] = 3), (arr[14][4] = 3); (arr[4][15] = 3), (arr[15][4] = 3); (arr[5][6] = 9), (arr[6][5] = 9); (arr[6][12] = 3), (arr[12][6] = 3); (arr[6][13] = 3), (arr[13][6] = 3); (arr[6][14] = 3), (arr[14][6] = 3); (arr[6][15] = 9), (arr[15][6] = 9); (arr[7][12] = 3), (arr[12][7] = 3); (arr[7][13] = 3), (arr[13][7] = 3); (arr[7][14] = 3), (arr[14][7] = 3); (arr[7][15] = 3), (arr[15][7] = 3); (arr[8][13] = 9), (arr[13][8] = 9); (arr[8][15] = 9), (arr[15][8] = 9); (arr[9][12] = 9), (arr[12][9] = 9); (arr[9][14] = 9), (arr[14][9] = 9); (arr[10][13] = 9), (arr[13][10] = 9); (arr[10][15] = 9), (arr[15][10] = 9); (arr[11][12] = 9), (arr[12][11] = 9); (arr[11][14] = 9), (arr[14][11] = 9); var arr2 = []; (arr2[0] = "INFP"), (arr2[1] = "ENFP"); (arr2[2] = "INFJ"), (arr2[3] = "ENFJ"); (arr2[4] = "INTJ"), (arr2[5] = "ENTJ"); (arr2[6] = "INTP"), (arr2[7] = "ENTP"); (arr2[8] = "ISFP"), (arr2[9] = "ESFP"); (arr2[10] = "ISTP"), (arr2[11] = "ESTP"); (arr2[12] = "ISFJ"), (arr2[13] = "ESFJ"); (arr2[14] = "ISTJ"), (arr2[15] = "ESTJ"); function show() { let number = document.getElementById('num').value; for (var i = 1; i <= 5; i++) { document.getElementById('f' + i).style.display = 'none'; } $('#howmany').hide(); for (var i = 1; i <= number; i++) { $('#f' + i).show(); } $('#friend').show(); $('#but').show(); } function regist() { let number2 = document.getElementById('num').value; if (number2 == 2) { let mbti_1 = document.getElementById('mbti1').value; let mbti_2 = document.getElementById('mbti2').value; let score_max = 0; let arrValues = []; for (var mbti_3 = 0; mbti_3 <= 15; mbti_3++) { let score1 = arr[mbti_1]; let score2 = score1[mbti_2]; let score3 = arr[mbti_1]; let score4 = score3[mbti_3]; let score5 = arr[mbti_2]; let score6 = score5[mbti_3]; let score = ((score2 + score4 + score6) / 27) * 100; let mbti_max = arr2[mbti_3]; if (score > score_max) { score_max = score; arrValues = []; arrValues.push(mbti_max); } else if (score == score_max) { arrValues.push(mbti_max); } } $('#friend').hide(); $('.reset').show(); var myString1 = arrValues.toString(); document.getElementById('result').innerText = myString1 + '\n' +Math.ceil(score_max)+"점!!"; } else if (number2 == 3) { let mbti_1 = document.getElementById('mbti1').value; let mbti_2 = document.getElementById('mbti2').value; let mbti_3 = document.getElementById('mbti3').value; let score_max = 0; let arrValues = []; for (var mbti_4 = 0; mbti_4 <= 15; mbti_4++) { var array = [mbti_1, mbti_2, mbti_3, mbti_4]; let score3 = 0; for (var i = 0, item; (item = array[i]); i++) { let score1 = arr[item]; for (var j = i + 1, item2; (item2 = array[j]); j++) { let item2 = array[j]; let score2 = score1[item2]; score3 = score3 + score2; } } let score = (score3 / 54) * 100; let mbti_max = arr2[mbti_4]; if (score > score_max) { score_max = score; arrValues = []; arrValues.push(mbti_max); } else if (score == score_max) { arrValues.push(mbti_max); } } $('#friend').hide(); $('.reset').show(); var myString1 = arrValues.toString(); document.getElementById('result').innerText = myString1 + '\n' +Math.ceil(score_max)+"점!!"; } else if (number2 == 4) { let mbti_1 = document.getElementById('mbti1').value; let mbti_2 = document.getElementById('mbti2').value; let mbti_3 = document.getElementById('mbti3').value; let mbti_4 = document.getElementById('mbti4').value; let score_max = 0; let arrValues = []; for (var mbti_5 = 0; mbti_5 <= 15; mbti_5++) { var array = [mbti_1, mbti_2, mbti_3, mbti_4, mbti_5]; let score3 = 0; for (var i = 0, item; (item = array[i]); i++) { let score1 = arr[item]; for (var j = i + 1, item2; (item2 = array[j]); j++) { let item2 = array[j]; let score2 = score1[item2]; score3 = score3 + score2; } } let score = (score3 / 90) * 100; let mbti_max = arr2[mbti_5]; if (score > score_max) { score_max = score; arrValues = []; arrValues.push(mbti_max); } else if (score == score_max) { arrValues.push(mbti_max); } } $('#friend').hide(); $('.reset').show(); var myString1 = arrValues.toString(); document.getElementById('result').innerText = myString1 + '\n' +Math.ceil(score_max)+"점!!"; } else { let mbti_1 = document.getElementById('mbti1').value; let mbti_2 = document.getElementById('mbti2').value; let mbti_3 = document.getElementById('mbti3').value; let mbti_4 = document.getElementById('mbti4').value; let mbti_5 = document.getElementById('mbti5').value; let score_max = 0; let arrValues = []; for (var mbti_6 = 0; mbti_6 <= 15; mbti_6++) { var array = [mbti_1, mbti_2, mbti_3, mbti_4, mbti_5, mbti_6]; let score3 = 0; for (var i = 0, item; (item = array[i]); i++) { let score1 = arr[item]; for (var j = i + 1, item2; (item2 = array[j]); j++) { let item2 = array[j]; let score2 = score1[item2]; score3 = score3 + score2; } } let score = (score3 / 135) * 100; let mbti_max = arr2[mbti_6]; if (score > score_max) { score_max = score; arrValues = []; arrValues.push(mbti_max); } else if (score == score_max) { arrValues.push(mbti_max); } } $('#friend').hide(); $('.reset').show(); var myString1 = arrValues.toString(); document.getElementById('result').innerText = myString1 + '\n' +Math.ceil(score_max)+"점!!"; } $('.reset').click(function (e) { e.preventDefault(); //$("#layer").css("display","block"); //$("#layer").show(); //$("#layer").fadeIn(); $('#layer').slideDown(); }); $('#layer .close').click(function (e) { e.preventDefault(); //$("#layer").css("display","none"); //$("#layer").hide(); //$("#layer").fadeOut(); location.reload(); }); }
ced1606268032720a02ef39294bf3a71e9c480b4
[ "JavaScript" ]
1
JavaScript
CHOISEONGJU/mbticombi
723edbed9f76219e81efec76607c9d15f070b8eb
448231f162b3cd85c1dcf97b893c3e1263eb8d50
refs/heads/master
<file_sep>package com.fxpgy.fetch; public class Constant { public static String ONLINE_USER_LIST="online_user_list"; //在线用户列表 public static String CUREN_USER = "curen_user"; //当前用户 public static String SESSION_COLLECTION = "session_collection"; //会话集合 public static String DISTANCE_LOGIN = "distance login"; //异地登录 private static final String CQWZQ_LIST_URL="http://www.cqjg.gov.cn/netcar/FindOne1.aspx"; private static final String CQWZQ_INFO_URL="http://www.cqjg.gov.cn/netcar/wfxw.aspx"; } <file_sep>package com.fxpgy.fetch.service; import java.io.File; import java.io.FileOutputStream; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.fxpgy.fetch.util.DataBaseConnection; import com.fxpgy.fetch.util.HttpClientUtil; import com.fxpgy.fetch.util.XmlLoad; /** * @author paul * @version 创建时间:2013-5-21 上午11:51:22 * 类说明 */ public class CarConfigService { public StringBuffer carConfigSqlBuffer() throws Exception{ List<Map<String,Integer>> typeMaps = XmlLoad.typeMaps; StringBuffer sb = new StringBuffer("insert into bsd_auto_setting_value (carId,paramValue,typeId) values \n"); DataBaseConnection conn = new DataBaseConnection(DataBaseConnection.MYSQL_DRIVER,"jdbc:mysql://10.89.100.250:3306/BSD", "root", "123456"); List<Map<String,Object>> carList = conn.queryForList("select car.id,car.xcarid from bsd_auto_car car ", null); List<Long> existCarIds = existCarValue(conn); for(Map<String,Object> car : carList){ Long carId = (Long)car.get("id"); if(!existCarIds.contains(carId)){ System.out.println("汽车Id"+carId); String xcar_web = "http://newcar.xcar.com.cn/m"; String xcarId = String.valueOf(car.get("xcarId")); xcar_web = xcar_web+xcarId+"/config.htm"; String html = HttpClientUtil.httpRequest(xcar_web, null, "GET", "gb2312"); Map<String,String> map = HtmlParserHandler.excuteParser(new CarConfigHtmlParser(), html); for(Map<String,Integer> typeMap:typeMaps){ for(Entry<String,Integer> entry :typeMap.entrySet()){ String paramValue = map.get(entry.getKey()); if( paramValue == null){ paramValue = ""; System.out.println(entry.getKey()); } sb.append(" ("+carId+",'"+ paramValue +"',"+entry.getValue()+"),\n"); } } } } return sb; } public List<Long> existCarValue(DataBaseConnection conn) throws SQLException{ ResultSet resultSet = conn.query("select v.carId from bsd_auto_setting_value v group by v.carId", null); List<Long> ids = new ArrayList<Long>(); while(resultSet.next()){ ids.add(resultSet.getLong(1)); } return ids; } public static void main(String[] args) throws Exception{ CarConfigService carService = new CarConfigService(); StringBuffer sb = carService.carConfigSqlBuffer(); File file = new File("F://carConfigSql.sql"); FileOutputStream fos = new FileOutputStream(file); fos.write(sb.toString().getBytes()); System.out.println("生成汽车配置sql成功"); // List<Long> ids = new ArrayList<Long>(); // ids.add(new Long(100)); // ids.add(new Long(200)); // System.out.println(ids.contains(new Long(100))); } } <file_sep>package com.fxpgy.fetch.vo; /** * @author paul * @version 创建时间:2013-5-8 下午4:51:08 * 类说明 */ public class OilVo { private String city; private String price90; private String price93; private String price97; private String price0; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getPrice90() { return price90; } public void setPrice90(String price90) { this.price90 = price90; } public String getPrice93() { return price93; } public void setPrice93(String price93) { this.price93 = price93; } public String getPrice97() { return price97; } public void setPrice97(String price97) { this.price97 = price97; } public String getPrice0() { return price0; } public void setPrice0(String price0) { this.price0 = price0; } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.fxpgy</groupId> <artifactId>fetchData</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>fetchData</name> <url>http://maven.apache.org</url> <distributionManagement> <repository> <id>releases</id> <name>releases</name> <url>http://localhost:8081/nexus/content/repositories/releases/</url> </repository> <snapshotRepository> <id>Snapshots</id> <name>Snapshots</name> <url>http://localhost:8081/nexus/content/repositories/snapshots/</url> </snapshotRepository> </distributionManagement> <build> <finalName>bsdweb</finalName> <plugins> <plugin> <artifactId>maven-scm-plugin</artifactId> <version>1.7</version> <configuration> <scmVersionType>branch</scmVersionType> <scmVersion>master</scmVersion> </configuration> </plugin> <plugin> <artifactId>maven-release-plugin</artifactId> <version>2.3.2</version> <configuration> <autoVersionSubmodules>true</autoVersionSubmodules> <scmCommentPrefix></scmCommentPrefix> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.2</version> <configuration> <attach>true</attach> </configuration> <executions> <execution> <phase>install</phase> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit-dep</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>${jsoup.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> <exclusions> <exclusion> <artifactId>mail</artifactId> <groupId>javax.mail</groupId> </exclusion> <exclusion> <artifactId>jms</artifactId> <groupId>javax.jms</groupId> </exclusion> <exclusion> <artifactId>jmxtools</artifactId> <groupId>com.sun.jdmk</groupId> </exclusion> <exclusion> <artifactId>jmxri</artifactId> <groupId>com.sun.jmx</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>${jsp.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.easymock</groupId> <artifactId>easymock</artifactId> <version>${easymock.version}</version> <scope>test</scope> </dependency> </dependencies> <scm> <url>scm:git:https://github.com/cbpaul/test.git</url> <connection>scm:git:ssh://git@github.com:cbpaul/test.git</connection> <developerConnection>scm:git:ssh://git@github.com:cbpaul/test.git</developerConnection> </scm> <properties> <junit.version>4.9</junit.version> <log4j.version>1.2.17</log4j.version> <jsp.version>2.1</jsp.version> <servlet.version>2.5</servlet.version> <jsoup.version>1.7.2</jsoup.version> <easymock.version>3.1</easymock.version> <jdom.version>2.0.2</jdom.version> </properties> </project> <file_sep>package com.fxpgy.fetch.servlet; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public abstract class BaseServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected HttpServletRequest request; protected HttpServletResponse response; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String methodName = req.getParameter("method"); this.setRequest(req); this.setResponse(resp); @SuppressWarnings("rawtypes") Class clazz = getCurrenServlet().getClass(); try { @SuppressWarnings("unchecked") Method method = clazz.getMethod(methodName); try { method.invoke(getCurrenServlet()); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } public abstract BaseServlet getCurrenServlet(); public HttpServletResponse getResponse() { return response; } public void setResponse(HttpServletResponse response) { this.response = response; } public void setRequest(HttpServletRequest request) { this.request = request; } public HttpServletRequest getRequest() { return request; } } <file_sep>package com.fxpgy.fetch.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.easymock.EasyMock; import org.junit.Test; /** * @author paul * @version 创建时间:2013-5-8 下午6:35:58 * 类说明 */ public class OilServletTest { private HttpServletRequest request; private HttpServletResponse response; // @Test // public void testOilPriceQuery() { // request = EasyMock.createMock(HttpServletRequest.class); // response = EasyMock.createMock(HttpServletResponse.class); // EasyMock.expect(request.getParameter("method")).andReturn("oilPriceQuery").times(1); // EasyMock.expect(request.getParameter("city")).andReturn("chengdu").times(1); // EasyMock.replay(request,response); // OilServlet os = new OilServlet(); // try { // os.doGet(request, response); // } catch (ServletException e) { // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } } <file_sep>package com.fxpgy.fetch.service; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @author paul * @version 创建时间:2013-5-13 下午5:45:22 类说明 */ public class XmlParser { private static final String WEB_URL = "PicLib"; private static int oneClassId = 0; private static int twoClassId = 0; private static int seriesId = 0; public static XPath xpath; private static StringBuffer oneClassBrand = new StringBuffer(); private static StringBuffer towClassBrand = new StringBuffer(); private static StringBuffer series = new StringBuffer(); public static void main(String[] args) throws Exception { int i = 0; oneClassBrand.append("insert into bsd_auto_brand (id,name,letter,icon) values "); towClassBrand.append("insert into bsd_auto_brand (id,name,parentId)"); series.append("insert into bsd_auto_series (id,brandId,name,icon,parentId,price) "); DocumentBuilderFactory domFactory = DocumentBuilderFactory .newInstance(); domFactory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse("src/main/java/Brand_Info.plist"); XPathFactory factory = XPathFactory.newInstance(); xpath = factory.newXPath(); NodeList letterNodes = (NodeList) xpath.compile("//plist/array/dict/array/dict/string").evaluate(doc,XPathConstants.NODESET); NodeList oneclassBrandNodes = (NodeList) xpath.compile("//plist/array/dict/array/dict/array/dict").evaluate(doc,XPathConstants.NODESET); System.out.println(oneclassBrandNodes.getLength()); twoClassId = oneclassBrandNodes.getLength(); for (i = 0; i < letterNodes.getLength(); i++) { Node node = letterNodes.item(i).getParentNode(); NodeList list = (NodeList) xpath.compile("array/dict").evaluate(node, XPathConstants.NODESET); NodeList strList = (NodeList) xpath.compile("array/dict/string").evaluate(node, XPathConstants.NODESET); if (strList.getLength() >= 3) { int b = strList.getLength() / 3; for (int j = 1; j <= b; j++) { oneClassId++; oneClassBrand.append("("+oneClassId+",'"+ strList.item(j * 3 - 1).getTextContent() + "','"+ letterNodes.item(i).getTextContent() + "','"+ urlSub(strList.item(j * 3 - 2).getTextContent())+ "'),\n"); NodeList towClassNodes = (NodeList) xpath.compile("array/dict").evaluate(list.item(j - 1),XPathConstants.NODESET); twoClassSqlStr(towClassNodes); } } } System.out.println(oneClassBrand.substring(0,oneClassBrand.lastIndexOf(","))); System.out.println(towClassBrand.substring(0,towClassBrand.lastIndexOf(","))); System.out.println(series.substring(0,series.lastIndexOf(","))); } private static String urlSub(String url) { return url.substring(url.indexOf(WEB_URL), url.length()); } public static void twoClassSqlStr(NodeList towClassNodes) throws Exception { for (int i = 0; i < towClassNodes.getLength(); i++) { twoClassId++; NodeList nodes = (NodeList)xpath.compile("string").evaluate(towClassNodes.item(i), XPathConstants.NODESET); towClassBrand.append("("+twoClassId+",'" + nodes.item(1).getTextContent() + "',"+oneClassId + ") ,\n"); NodeList seriesNodes = (NodeList)xpath.compile("array/dict").evaluate(towClassNodes.item(i), XPathConstants.NODESET); seriesSqlStr(seriesNodes); } } public static void seriesSqlStr(NodeList seriesNodes) throws Exception{ for(int i=0;i<seriesNodes.getLength();i++){ seriesId++; Node seriesNode = seriesNodes.item(i); NodeList seriesValue = (NodeList)xpath.compile("string").evaluate(seriesNode, XPathConstants.NODESET); series.append("("+seriesId+","+twoClassId+",'"+seriesValue.item(1).getTextContent()+"','"+urlSub(seriesValue.item(0).getTextContent())+"',null,'"+seriesValue.item(2).getTextContent()+"'),\n"); } } } <file_sep>package com.fxpgy.fetch.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 该工具类用于数据库连接,返回一个Statement对象,用户可以根据此对象执行sql语句获取结果 */ public class DataBaseConnection { public static final String ACCESS_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver"; public static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver"; public static final String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver"; public static final String SQLSERVER_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; private Connection connection = null; @SuppressWarnings("unused") private DataBaseConnection(){ } public DataBaseConnection(String driver, String url, String user, String password) { try { // 1、加载驱动程序 Class.forName(driver); // 2、通过url建立连接,连接到数据库 if(connection == null){ connection = DriverManager.getConnection(url, user, password); } // 3、创建语句,connection可以看出缆道,Statement可以看出缆车 } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public static void excute(Statement st,String sql){ try { st.execute(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 查询返回listMap * @param sql * @param params * @return * @throws Exception */ public List<Map<String,Object>> queryForList(String sql ,Object...params) throws Exception{ ResultSet rs = query(sql,params); List<Map<String,Object>> rsList = new ArrayList<Map<String,Object>>(); ResultSetMetaData data=rs.getMetaData(); while(rs.next()){ Map<String,Object> rsMap = new HashMap<String, Object>(); for(int i = 1 ; i<= data.getColumnCount() ; i++){ rsMap.put(data.getColumnName(i), rs.getObject(i)); } rsList.add(rsMap); } return rsList; } /** * @param sql * @param params * @return * @throws SQLException */ public ResultSet query(String sql ,Object...params) throws SQLException{ PreparedStatement statement = connection.prepareStatement(sql); if(params != null){ for(Object param : params){ if(param instanceof String){ statement.setObject(0, param); } } } ResultSet rs = statement.executeQuery(sql); return rs; } public void close(Statement st) { try { if (st != null) st.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args){ // getStatement(MYSQL_DRIVER,"jdbc:mysql://localhost:3306/bsd","root",""); } } <file_sep>package com.fxpgy.fetch.service; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.fxpgy.fetch.util.HttpClientUtil; import com.fxpgy.fetch.vo.IllegalVo; public abstract class IllegalHTMLParser { private static final String CQWZ_WEB_URL="http://www.cqjg.gov.cn/netcar/"; /** * 车辆违章列表 * * @param html * @return */ public static List<IllegalVo> illegalList(String html, String appUrl) { List<IllegalVo> obs = new ArrayList<IllegalVo>(); Document doc = Jsoup.parse(html); Elements elements = doc.select("table tr"); for (int i = 1; i < elements.size(); i++) { Element element = elements.get(i); IllegalVo vio = new IllegalVo(); Elements es = element.children(); if (es.size() >= 7) { vio.setCarType(es.get(0).text()); vio.setTime(es.get(1).text()); vio.setPlace(es.get(2).text()); vio.setFineMoney(es.get(3).text()); vio.setScore(es.get(4).text()); vio.setParty(es.get(5).text()); String href = es.get(6).children().get(0).attr("href"); vio.setInfoParamStr(appUrl + href.substring(href.indexOf("?") + 1, href.length())); obs.add(vio); } } return obs; } /** * 车辆违章详情 * * @param html * @return */ public static IllegalVo illegalInfo(String html) { IllegalVo vio = new IllegalVo(); Document doc = Jsoup.parse(html); Elements elements = doc.select("tr td"); if (elements.size() > 13) { vio.setCarType(elements.get(1).text()); vio.setTime(elements.get(3).text()); vio.setPlace(elements.get(5).text()); vio.setEnforcementUnit(elements.get(7).text()); vio.setScore(elements.get(9).text()); vio.setFineMoney(elements.get(11).text()); vio.setBehavior(elements.get(13).text()); } return vio; } /** * 得到违章时间与请求url对应列表 * @param html * @return */ public static Map<String,String> illegalTimeUrlMaps(String html){ Document doc = Jsoup.parse(html); Elements elements = doc.select("table tr"); Map<String,String> resultMap = new HashMap<String,String>(); if(elements.size()>0){ for (int i = 1; i < elements.size(); i++) { String timeStr = elements.get(i).children().get(1).text(); String href = elements.get(i).children().get(6).children().get(0).attr("href"); String regex="([\u4e00-\u9fa5]+)"; Matcher matcher = Pattern.compile(regex).matcher(href); StringBuffer sb = new StringBuffer(); while(matcher.find()){ try { System.out.println(URLEncoder.encode(matcher.group(), "gb2312")); matcher.appendReplacement(sb, URLEncoder.encode(matcher.group(), "gb2312")); System.out.println(sb.toString()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } resultMap.put(timeStr, CQWZ_WEB_URL+matcher.appendTail(sb)); } return resultMap; } return null; } /** * 返回违章详情列表 * @param timeUrlMap 时间与详情url对应(illegalTimeUrlMaps方法可以返回) * @param illegalVos 存取违章vo列表 * @return * @throws Exception */ public synchronized static List<IllegalVo> illegalInfos(Map<String,String> timeUrlMap,List<IllegalVo> illegalVos) throws Exception{ if(illegalVos == null){ illegalVos = new ArrayList<IllegalVo>(); } for(Entry<String, String> entry : timeUrlMap.entrySet()){ String html = HttpClientUtil.httpRequest(entry.getValue(), "", "GET", "gb2312"); if(null != html){ IllegalVo illegalVo = illegalInfo(html); illegalVos.add(illegalVo); } } return illegalVos; } }
6ab8d21fd79e81b34f2c79b9239d3b861b2c9fae
[ "Java", "Maven POM" ]
9
Java
cbpaul/test
d5dae758fdcc242c42dbd9cbb1115ce96e79bdf3
0ad1a3eef5bbcc246b55a30afb1e55bbb4e877d2
refs/heads/master
<repo_name>hanrufan/week3<file_sep>/src/app/components/content/content.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-content', templateUrl: './content.component.html', styleUrls: ['./content.component.scss'] }) export class ContentComponent implements OnInit { titleArr = [ {'title':'TOTAL REVENUE', 'num': '54,540', 'color': 'text-success'}, {'title':'TOTAL COST', 'num': '12,660', 'color': 'text-danger'}, {'title':'NET INCOME', 'num': '41,880', 'color': 'text-primary'} ]; firstArr = [ {'icon': 'fab fa-facebook','url':'www.facebook.com', 'num':'45,836','grow':'up','grow_num':'20'}, {'icon': 'fab fa-google','url':'www.google.com', 'num':'23,582','grow':'up','grow_num':'12'}, {'icon': 'fas fa-shopping-cart','url':'www.shopify.com', 'num':'2,489','grow':'down','grow_num':'15'}, {'icon': 'fab fa-wordpress','url':'www.wordpress.com', 'num':'10,57','grow':'down','grow_num':'30'} ]; // {'title':'Latest Orders', 'list':[ // ]} // ]; constructor() { } ngOnInit() { } }
c5988d5194dfbe1c565bcb90b7afad0ba6cda94a
[ "TypeScript" ]
1
TypeScript
hanrufan/week3
73d7f21ca1383472b47b1d36ad3c70a4940a4a14
070b9128735e973a65d9c01db267d86049d1100d
refs/heads/master
<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); ?><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Welcome to Yearbook</title> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <!-- Generic page styles --> <link rel="stylesheet" href="css/style.css"> <style type="text/css"> ::selection { background-color: #E13300; color: white; } ::-moz-selection { background-color: #E13300; color: white; } </style> </head> <body> <div class = "container"> <div style="float:right;position:relative;top:20px;"> <form class="form-inline" method="post" role="form"> <div class="form-group"> <input type="email" class="form-control" id="email1" name="email1" placeholder="Enter Your Email" /> </div> <div class="form-group"> <input type="<PASSWORD>" class="form-control" id="pwd" name="pwd" placeholder="Enter Your Password" /> </div> <button type="submit" class="btn btn-success">Submit</button> </form> </div> <div class="jumbotron"> <h1 style="text-align:center" >Welcome to Yearbook 2015 </h1> </div> <div class="row"> <h2 style="text-align:center" >Register to Yearbook 2015 </h2><br/><br/> <form action="/member_area.php" class="form-horizontal" role="form" method="post"> <div class="form-group"> <label class="control-label col-sm-2" for="roll">Roll No.</label> <div class="col-sm-5"> <input type="text" class="form-control" id="roll" name="roll" placeholder="Enter Your Roll" /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="dep">Department</label> <div class="col-sm-5"> <input type="text" class="form-control" id="dep" name="dep" placeholder="Your Department" /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="dob">Date-of-Birth</label> <div class="col-sm-5"> <input type="text" class="form-control" id="dob" name="dob" placeholder="Enter Your Date Of Birth" /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="perf">Email ID</label> <div class="col-sm-5"> <input type="text" class="form-control" id="pref" name="pref" placeholder="Enter Your Prefferd Email Id" /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="pass">Password</label> <div class="col-sm-5"> <input type="text" class="form-control" id="pass" name="pass" placeholder="Enter Your Prefferd Password" /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" ></label> <div class="col-sm-5"> <button class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </body> </html>
417254b3f01739c2d66a42fbfb3aa96f245b2864
[ "PHP" ]
1
PHP
uagarwal744/yearbook
89417e6764092a530e6f696cdd1d00cbf621e94c
0861f32d877f122a97a9538126ac34e12023fdca
refs/heads/master
<file_sep>import random DESC_FIELD = False class Field: """Finite Field representation. A finite field of prime (or prime power) size. Attributes: char (int): Characteristic dim (int): Dimension size (int): Number of elements in field irr (Polynomial): Irreducible polynomial (if `dim > 1`) inverses (dict): Inverses of constants in the field indeterminate (str): Indeterminate symbol for polynomials """ def __init__(self, p, n, f, ind="x"): """Constructor: Args: p (int): characteristic n (int): dimension f (Polynomial): irreducible polynomial ind (str): indeterminate symbol (default: "x") Returns: A Field: * If `n == 1`: The field of `p` elements `Fp` * If `n > 1`: The field of polynomials in the ring `Fp[x]` mudulu the irreducible polynomial `f`: `Fp[x] % <f>` """ self.irr = None if n > 1: self.irr = f self.char = p self.dim = n self.size = p**n self.inverses = inverses(p) self.indeterminate = ind def zero(self): """Returns the zero element of the field """ return Polynomial([0], self) def one(self): """Returns the identity element of the field """ return Polynomial([1], self) def __repr__(self): """Text representation. Args: self (Field): field Returns: A description: * If `n == 1`: describe field size * If `n > 1`: describe field size, characteristic and irreducible polynomial """ if self.dim == 1: return "Field of size " + str(self.size) poly = str(self.irr) st = "Field of size " + str(self.size) st += ", Characteristic " + str(self.char) st += ", with irreducible polynomial " + poly return st class Polynomial: def __init__(self, coefs, field): if not any(coefs): coefs = [0] else: for i in range(len(coefs) - 1, -1, -1): if coefs[i] != 0: coefs = coefs[:i + 1] break for coef in coefs: pass # TODO: assert coef in field self.coefs = coefs if field.char: self.coefs = [coef % field.char for coef in self.coefs] self.dim = len(self.coefs) - 1 self.field = field def __repr__(self): poly = "" for i in range(len(self.coefs) - 1, -1, -1): if self.coefs[i] != 0: c, x, exp = "", "", "" ind = self.field.indeterminate if self.coefs[i] != 1 or i == 0: c = str(self.coefs[i]) if i != 0: x = ind if (ind != "x" and self.coefs[i] != 1 and not isinstance(self.coefs[i], int)): c = "(" + c + ")" if i > 1: exp = str(i) x += "^" poly += c + x + exp + "+" if poly == "": poly = "00" return poly[:-1] def __add__(self, other): if isinstance(other, int): return self + Polynomial([other], self.field) assert self.field.char == other.field.char selfcoefs, othercoefs, length = pad_lists(self.coefs, other.coefs) new_coefs = [(selfcoefs[i] + othercoefs[i]) for i in range(length)] if self.field.char: new_coefs = [coef % self.field.char for coef in new_coefs] return Polynomial(new_coefs, self.field) def __radd__(self, other): return self + other def __neg__(self): negs = [-coef for coef in self.coefs] if self.field.char: negs = [coef % self.field.char for coef in negs] return Polynomial(negs, self.field) def __sub__(self, other): return self + (-other) def __pow__(self, num): assert isinstance(num, int) new = Polynomial([1], self.field) for i in range(num): new = new * self return new def __truediv__(self, other): if isinstance(other, int): inv = inverses(self.field.char)[other] return self * Polynomial([inv], self.field) return self.poly_div_mod(other)[0] def __rtruediv__(self, other): if isinstance(other, int): nom = Polynomial([other], self.field) return nom / self def __mod__(self, other): if isinstance(other, int): return Polynomial([c % other for c in self.coefs], self.field) if isinstance(other, Element): return self % other.poly if other.is_const() and not other.is_zero(): coefs = [coef % other.coefs[0] for coef in self.coefs] return Polynomial(coefs, self.field) else: return self.poly_div_mod(other)[1] def poly_div_mod(self, other): assert not other.is_zero(), "Divide by zero" err = "Can't divide polynomials from fields of different chars." assert self.field.char == other.field.char, err char = self.field.char if char: invs = inverses(char) q = Polynomial([0], self.field) r = Polynomial([coef for coef in self.coefs], self.field) while not r.is_zero() and r.deg() >= other.deg(): if char: # print("OTHER", other, type(other), other.coefs, other.deg()) # print("INVS", invs[1], type(other.coefs[other.deg()])) key = other.coefs[other.deg()] while isinstance(key, Element): key = key.poly.coefs[0] t = r.coefs[r.deg()] * invs[key] else: t = r.coefs[r.deg()] / other.coefs[other.deg()] new_poly_coefs = [0 for i in range(r.deg() + 1)] new_poly_coefs[r.deg() - other.deg()] = t new_poly = Polynomial(new_poly_coefs, self.field) q = q + new_poly r = r - (new_poly * other) return (q, r) def __eq__(self, other): if isinstance(other, int): return self.coefs[0] == other and len(self.coefs) == 1 selfcoefs, othercoefs, _ = pad_lists(self.coefs, other.coefs) return selfcoefs == othercoefs and self.field == other.field def is_zero(self): return self == 0 or self.coefs == [0 for i in range(len(self.coefs))] def deg(self): if self.is_zero(): return 0 n = len(self.coefs) for i in range(n - 1, -1, -1): if self.coefs[i] != 0: return i return 0 def __rmul__(self, other): if isinstance(other, int): return self * other def is_const(self): return len(self.coefs) == 1 def __mul__(self, other): if isinstance(other, int): return self * Polynomial([other], self.field) err = "Field characteristics must agree when multiplying polynomials" assert self.field.char == other.field.char, err selfcoefs, othercoefs, length = pad_lists(self.coefs, other.coefs) # Do the actual work mult_coefs = [0 for i in range(2 * length - 1)] for i in range(length): for j in range(length): mult_coefs[i + j] += selfcoefs[i] * othercoefs[j] # Take mod field characteristic if self.field.char: mult_coefs = [coef % self.field.char for coef in mult_coefs] return Polynomial(mult_coefs, self.field) # TODO: evaluation should be in the field. # i.e. take every coef and convert to field element and then multiply def __call__(self, val): exp = 1 ret = Element(Polynomial([0], self.field), self.field) for coef in self.coefs: t = Element(Polynomial([coef * exp], self.field), self.field) ret += t exp = exp * val ret = ret % self.field.char return ret def inv(self, irr): char = self.field.char t = Polynomial([0], self.field) newt = Polynomial([1], self.field) r = Polynomial([1], self.field) if irr: r = Polynomial([coef for coef in irr.coefs], self.field) newr = Polynomial([coef for coef in self.coefs], self.field) while not newr.is_zero(): q = r.poly_div_mod(newr)[0] r, newr = newr, r - (q * newr) t, newt = newt, t - (q * newt) err = "Either field.irr is not irreducible " err += "or polynomial is multiple of field.irr" assert r.deg() == 0, err key = r.coefs[0] while isinstance(key, Element): key = key.poly.coefs[0] return t * inverses(char)[key] @staticmethod def one(field): return field.one() class Element(): def __init__(self, poly, field): assert len(poly.coefs) <= field.dim self.poly = poly self.field = field self.coef_field = poly.field def __repr__(self): field_desc = "" if DESC_FIELD: field_desc = " in the " + str(self.field).lower() return str(self.poly) + field_desc def __add__(self, other): if isinstance(other, int): pol = Polynomial([other], self.coef_field) return self + Element(pol, self.field) assert self.field == other.field p = self.field.char new_poly = (self.poly + other.poly) % p return Element(new_poly, self.field) def __radd__(self, other): return self + other def __neg__(self): return Element((-self.poly) % self.field.char, self.field) def __sub__(self, other): return self + (-other) def __eq__(self, other): if isinstance(other, int): return self.poly == Polynomial([other], self.field) return self.poly == other.poly and self.field == other.field def is_zero(self): return self.poly.is_zero() def deg(self): return self.poly.deg() def __pow__(self, num): return Element((self.poly**num) % self.field.irr, self.field) def __mul__(self, other): if isinstance(other, int): pol = Polynomial([other], self.coef_field) return self * Element(pol, self.field) assert self.field == other.field mod = self.field.char if self.field.irr: mod = self.field.irr return Element((self.poly * other.poly) % mod, self.field) def __rmul__(self, other): return self * other def __truediv__(self, other): if isinstance(other, int): pol = Polynomial([other], self.coef_field) return self / Element(pol, self.field) assert self.field == other.field other_inv = other.inv() el1 = Element(self.poly, self.field) el2 = Element(other_inv.poly, self.field) return el1 * el2 def __rtruediv__(self, other): if isinstance(other, int): return Element(Polynomial([other], self.field), self.field) / self def inv(self): return Element(self.poly.inv(self.field.irr), self.field) def __hash__(self): return hash((tuple(self.poly.coefs), self.field.size)) def is_gen(self, verbose=False): generated = self.generated_subgroup() if verbose: for gen in generated: print(gen) return len(generated) == self.field.size - 1 def generated_subgroup(self): generated = set() cand = Element(Polynomial([1], self.coef_field), self.field) * self while True: if cand in generated: break generated.add(cand) cand = cand * self return generated def __mod__(self, other): # if isinstance(other, int): # other_pol = Polynomial([other], self.coef_field) # other_el = Element(other_pol, self.field) # return self % other_el return Element(self.poly % other, self.field) @staticmethod def random(field): p = field.char elems = [i for i in range(p)] n = field.dim coefs = [random.choice(elems) for i in range(n)] return Element(Polynomial(coefs, field), field) @staticmethod def draw_generator(field, halt=-1): while halt != 0: cand = Element.random(field) gen = cand.generated_subgroup() if len(gen) == field.size - 1: return cand halt -= 1 return None def pad_lists(l1, l2): length = max(len(l1), len(l2)) l1_pad = l1 + [0 for i in range(length - len(l1))] l2_pad = l2 + [0 for i in range(length - len(l2))] return l1_pad, l2_pad, length def inverses(p): dic = {} for i in range(p): for j in range(p): if (i * j) % p == 1: dic[i] = j break return dic <file_sep># Finite Field Arithmetic A simple Python module for performing finite field arithmetic. ![GIF demo](media/demo.gif) ## Usage This module implements three algebraic elements: * Fields * Polynomials * Field elements In order to load the module simple import it: ```python from finite_field_arith import * ``` ### Fields The general syntax for creating a field is: ```python F = Field(p, dim, irr) ``` This is the construction of the field of size `p^dim` where `p` is some prime and `dim` is a positive integer. If `dim > 1` then `irr` is an irreducible polynomial in `F_p[x]` of degree `n`. For example, to construct `F_2`: ```python F2 = Field(2, 1, None) ``` Given an irreducible polynomial of degree `3` over `F_2`, say `irr = x^3 + x + 1` one can construct `F_8` simply by calling: ```python F8 = Field(2, 3, irr) ``` ### Polynomials A polynomial `f` of degree `k` is determined by: * Its underlying field `F` * Its list of coefficients `alpha_0, ... , alpha_k`, all elements of `F` Given a field `F` and a list of coefficients `coefs` from list we can construct the polynomial: ```python f = Polynomial(coefs, F) ``` ### Field Elements A field element `alpha` in `F = G[x] % irr` is determined by the polynomial representation `f_alpha` and its respective field `F`. Note that while `f_alpha` is an element in `G[x]` (i.e., the coefficient are element from `G`) the field element `alpha` is an element of `F` and therefore is defined as follows: <!-- since the polynomial representation of `alpha` already encapsulates `F` the construction of `alpha` is dependent on the polynomial alone. --> <!-- That is, if `f` is a polynomial in some field `F` then: --> ```python f = Polynomial(coefs, G) alpha = Element(f, F) ``` Constructs the appropriate field element `f % F.irr` ### Full example The following snippet constructs `F_2, F_8 = F_2[x] % x^3 + x + 1`, the polynomial `f = 1 + x^2` over `F_2[x]` and the field element `alpha_f = 1 + x^2 % (x^3 + x + 1)`: ```python F2 = Field(2, 1, None) irr = Polynomial([1, 1, 0, 1], F2) F8 = Field(2, 3, irr) f = Polynomial([1, 0, 1], F2) f_in_field = Element(f, F8) ``` ## Functionality In what follows, let `F` be a field, `f, g, h` polynomials and `a, b` field elements. Things you can do with this module include: ### Polynomial arithmetic: ```python t = f * g #product t = f + g #addition (and subtraction) t = f / g #quotient t = f % g #remainder ``` ### Field operations: ```python a_gen = a.generated_subgroup() #set of elements generated by powers of a g = Element.draw_generator(F, halt = k) #draw random element in F and return it if it generates the entire field. Give up after k attempts (by default halt is unbounded) ``` ## Todo The following is a list of features to be implemented in the future: * Complete docstrings: very partial atm. * Extension fields: in the current implementation a field of size `p^k` for `k > 1` must be constructed as a degree `k` extension of `F_p`. Future implementation should allow, for example, creating `G = F_p[x] % irr_1` and `H = G[y] % irr_2` where `irr_1` is in `F_p[x]` and `irr_2` is in `G[y]`. ## License This project is distributed under the Apache license version 2.0 (see the LICENSE file in the project root). <file_sep>from finite_field_arith import * F = Field(7, 1, None) f = Polynomial([0, 3, 6, 8, 3],F) g = Polynomial([3, 3, 2], F) #f+f F2 = Field(2,1,None) F13 = Field(13, 1, None) Elems13 = [Element(Polynomial([i], F13), F13) for i in range(13)] E0 = Element(Polynomial([0], F2), F2) E1 = Element(Polynomial([1], F2), F2) irr = Polynomial([E1, E1, E0, E1], F2) F8 = Field(2, 3, irr) a = Element(Polynomial([E0, E1, E1], F2), F8) print(a.inv(),a) f_x = Polynomial([Elems13[4], Elems13[7], Elems13[9]], F13) #print(Elems13[6].inv()) #print(f_x, f_x(4), Elems13[7] % Elems13[4]) exit() irr = Polynomial([1, 1, 0, 1], F2) print("eval", irr(1)) G = Field(2, 3, irr, ind="y") gener = Element.draw_generator(G) print("generator:",gener) f = Polynomial([0,1,0],F2) f_el = Element(f, G) print("TEST", f_el + f_el) field4 = list(f_el.generated_subgroup()) print("el2",field4[2]) print("el3",field4[3]) poly_f = Polynomial([field4[2], field4[3], field4[3]], G) print(poly_f) #print(poly_f(field4[2])) print("f1 int",f(1)) print("f1 elem",f(Element(Polynomial([1], F2), F2))) exit() F7 = Field(7, 1, None) g = Polynomial([2, 3, 3, 1], F7) k = Element(Polynomial([3], F7), F7) print("g:",g) print(g(k)) print(g(3)) r = Polynomial([1],F2) # print(G) # print(r) t = Element(r,G) q = Element(Polynomial([1], F2), G) print("t:",t / t) print("tinv:", t.inv()) F7 = Field(7, 1, None) pol3 = Polynomial([3], F7) el3 = Element(pol3, F7) print("Final") print(el3*3) # print(-t) # print(t+2) # #t = Element(Polynomial([1], G)) # print(t**2) # print(r/r) # print(r.field) # print(t.poly == r) # print((r.inv()*r)%r.field.irr) # print(t.inv()) # print(1/t * t) # print(Element(Polynomial([1], G))) field = t.generated_subgroup() for x in field: print(x.is_gen()) field = list(field) print(field[5].inv()+1) print(Element(Polynomial([1],field[0].field))) K = Field(7, 1, None) R = Field(2,1,None) a = Element(Polynomial([1],R)) z = Element(Polynomial([0], K)) print("z,a:", z,a) print("z inv:",z.inv(),z.inv().field.indeterminate) GT = Field(2,3,None,ind="y") T = Polynomial([field[5].poly,field[2].poly,field[4].poly],GT) One = Polynomial.one(GT) print("One:",One) print("T:",T) print("T**2:",T*T) F31 = Field(31,1,None) irr31 = Polynomial([1, 12, 7, 1], F31) G = Field(31, 3, irr31) x = Element.random(G) print(x, x.inv(), x*x.inv()) # print(x) # print(len(x.generated_subgroup())) #import time #t0 = time.perf_counter() #y = Element.draw_generator(G, halt = 100) #print(y) #print("Found in:", time.perf_counter() - t0) ''' f = Polynomial([1, 1, 0, 1], 2) F = Field(2, 3, f) a = Element(Polynomial([1, 0, 1], 2), F) b = Element(Polynomial([1, 0, 0], 2), F) G = Field(5, 3, f) c = Element(Polynomial([2, 0, 1], 5), G) g = Polynomial([1,1,0,1,1], 2) H = Field(5, 1, Polynomial([1],5)) '''
5f462330aeab5b1aa82e0785934e75d9ea99d47b
[ "Markdown", "Python" ]
3
Python
nparzan/finite_field_arithmetic
5de30240efe9e9bdffa80172d7fe60c8bca8c39c
814d4dfbe528671545ddfe32b02a2deea320f8c5
refs/heads/master
<repo_name>chaidongnzh/lsyncd<file_sep>/init.sh #!/bin/sh cat <<EOF > /etc/supervisord.conf [supervisord] nodaemon=true EOF if [[ $sshd_enable ]];then cat <<EOF >> /etc/supervisord.conf [program:sshd] command=/usr/sbin/sshd -D user=root autostart=true autorestart=unexpected numprocs=1 startsecs = 0 stdout_logfile=/dev/fd/1 stdout_logfile_maxbytes=0 EOF fi if [[ $lsyncd_enable ]];then cat <<EOF >> /etc/supervisord.conf [program:lsyncd] command=/usr/bin/lsyncd -nodaemon /etc/lsyncd.conf user=root autostart=true autorestart=unexpected numprocs=1 startsecs = 0 stdout_logfile=/dev/fd/1 stdout_logfile_maxbytes=0 EOF fi if [[ $crontab_enable ]];then cat <<EOF >> /etc/supervisord.conf [program:crontab] command=/usr/sbin/crond -f -c /etc/crontabs user=root autostart=true autorestart=unexpected numprocs=1 startsecs = 0 stdout_logfile=/dev/fd/1 stdout_logfile_maxbytes=0 EOF fi if [[ $rsync_enable ]];then cat <<EOF >> /etc/supervisord.conf [program:rsync] command=/usr/bin/rsync --daemon --no-detach -v --config=/etc/rsyncd.conf user=root autostart=true autorestart=unexpected numprocs=1 startsecs = 0 stdout_logfile=/dev/fd/1 stdout_logfile_maxbytes=0 EOF fi /usr/bin/supervisord -c /etc/supervisord.conf <file_sep>/myrsyncssh.lua settings { logfile = "/var/log/lsyncd.log", statusFile = "/var/log/lsyncd-status.log", insist = true, statusInterval = 1, --状态文件写入最短时间 maxDelays = 1 --最大延迟 } sync { default.rsync, source = "/root/src", target = "rsync://rsync@172.16.31.10:5432/test", delete = true, -- excludeFrom = "/etc/rsyncd.d/rsync_exclude.lst", rsync = { binary = "/usr/bin/rsync", acls = true, archive = true, compress = true, owner = true, perms = true, verbose = true, password_file = "/etc/rsyncd.secrets" } } <file_sep>/backup.sh #!/bin/sh echo "chaidong" DATE=`date +%Y%m%d` SEC=`date +%Y%m%d%H%M%S` DIR=/root/backup NAME=backup SOURCE=/root/src DAYS=5 if [ ! -f $DIR/$NAME_$DATE.tar.gz ];then find $DIR -mtime +$DAYS -name $NAME"_"*.tar.gz|xargs rm -f /bin/rm -f $DIR/snapshot /bin/tar -g $DIR/snapshot -zcpPf $DIR/$NAME"_"$DATE.tar.gz $SOURCE else /bin/tar -g $DIR/snapshot -zcpPf $DIR/$NAME"_incremental_"$SEC.tar.gz $SOURCE fi
668d5e74123f5d7e3369fc66185bad93ca6bad93
[ "Shell", "Lua" ]
3
Shell
chaidongnzh/lsyncd
d59f4909b1fc41a6d323a2a0e73c32a418c1f78c
4db9cccd75e78df130585c091047a5818336fcbf
refs/heads/master
<file_sep>const casesForVentilatorsByRequestedTime = (infectionsByRequestedTime) => { const percent = 2 / 100; const casesForVents = infectionsByRequestedTime * percent; // return casesForVents; }; export default casesForVentilatorsByRequestedTime; <file_sep>const infectionsByRequestedTime = (currentlyInfected, periodType, inputPeriod) => { // let factor = 0; let period = 0; // if (periodType === 'months') { period = inputPeriod * 30; } else if (periodType === 'weeks') { period = inputPeriod * 7; } else if (periodType === 'days') { period = inputPeriod; } // factor = Math.trunc(period / 3); const result = currentlyInfected * (2 ** factor); // return result; }; export default infectionsByRequestedTime; <file_sep>frontend.url = https://bankymono.github.io/covid-19-frontend/ backend.rest = https://jsonplaceholder.typicode.com/todos
15ba02f009cab4d0f4fcd528a79e6fc693dd8fa0
[ "JavaScript", "INI" ]
3
JavaScript
bankymono/covid-19-estimator-js
1a61be799dc19a84aa04a8164bff8a97e581e21c
5b62eed72503f107b215647e579501640f461620
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Cryptography; using System.Text; using System.Windows; namespace WPFLoginWindow { class ListInstance { #region Instance public static ListInstance Instance = new ListInstance(); #endregion #region Variables public ObservableCollection<UserViewModel> users=new ObservableCollection<UserViewModel>(); private string FilePath = "8999TM.bin"; #endregion #region Constructor public ListInstance() { LoadDatabase(); } #endregion #region Methods /// <summary> /// Load database from file /// </summary> public void LoadDatabase() { if (File.Exists(FilePath)) { using (var stream = File.Open(FilePath, FileMode.Open, FileAccess.Read)) { if (stream.Length > 0) { var bin = new BinaryFormatter(); users = (ObservableCollection<UserViewModel>)bin.Deserialize(stream); } else { users = new ObservableCollection<UserViewModel>(); } } } else { NewUser("Mateusz", "Trybula", StatusTypes.admin); } } /// <summary> /// Save database to file /// </summary> public void SaveDatabase() { using (var stream = File.Open(FilePath, FileMode.OpenOrCreate)) { var bin = new BinaryFormatter(); bin.Serialize(stream, this.users); } } /// <summary> /// Add new user /// </summary> /// <param name="login"></param> /// <param name="password"></param> /// <param name="status">Available(user,moderator,admin)</param> /// <returns></returns> public void NewUser(string login,string password,StatusTypes status) { UserViewModel user = new UserViewModel(); user.id = CheckAvailableId(); user.login = login; user.password = <PASSWORD>(<PASSWORD>); user.status = status; user.registered = DateTime.Now; user.lastModified = DateTime.Now; user.lastLogged = Convert.ToDateTime(null); bool tmp = false; foreach(UserViewModel us in users) { if (us.login == login) tmp = true; } if (!tmp) { users.Add(user); } else { MessageBox.Show("Login is already taken!"); } RefreshList(); } /// <summary> /// Check for available id /// </summary> /// <returns>First available id</returns> private int CheckAvailableId() { int id = 0; List<int> ids = users.Select(x => x.id).ToList(); for (int i = 0; ; i++) { if (!ids.Contains(i)) { id = i; break; } } return id; } /// <summary> /// Remove user from list /// </summary> /// <param name="id">Id of user to delete</param> public void RemoveUser(int id) { if (users.Count > 1) users.RemoveAt(id); else MessageBox.Show("I can't remove last user"); RefreshList(); } /// <summary> /// Edit user data /// </summary> /// <param name="param">Array of variables</param> public void EditUser(object[] param) { UserViewModel user = users[(int)param[0]]; user.login = param[1].ToString(); user.password = param[2].ToString() != String.Empty ? CodePass((int)param[0], param[2].ToString()) : user.password; user.status = (StatusTypes)((int)param[3]); user.lastModified = DateTime.Now; users[(int)param[0]] = user; } /// <summary> /// Code password /// </summary> /// <param name="id">User id</param> /// <param name="password">Uncrypted password</param> /// <returns>Crypted password</returns> public string CodePass(int id,string password) { byte[] salt = Encoding.ASCII.GetBytes(id.ToString() + "8999Trybula"); Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, salt); return Encoding.ASCII.GetString(rfc.GetBytes(salt.Length)); } /// <summary> /// Check if user exists and if password is correct /// </summary> /// <param name="login"></param> /// <param name="password"></param> /// <returns>Array of variables</returns> public object[] CheckForUser(string login,string password) { foreach(UserViewModel user in users) { if (user.login == login) { if (user.password == <PASSWORD>(user.id, password)) return new object[] { true, user }; else return new object[] { false, "Wrong password!" }; } } return new object[] { false, "User not found!" }; } /// <summary> /// Refreshing list and sort it /// </summary> private void RefreshList() { users = new ObservableCollection<UserViewModel>(users.OrderBy(i => i.id)); } #endregion } } <file_sep>using System; namespace WPFLoginWindow { [Serializable()] class UserModel { public int id; public string login; public string password; public StatusTypes status; public DateTime registered; public DateTime lastModified; public DateTime lastLogged; } } <file_sep>using System; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace WPFLoginWindow { [Serializable()] class LoggedViewModel:BaseViewModel { #region Commands public ICommand Close { get; set; } public ICommand Minimize { get; set; } public ICommand WindowClosing { get; set; } public ICommand WindowLoaded { get; set; } public ICommand AddUser { get; set; } public ICommand RemoveUser { get; set; } public ICommand EditUser { get; set; } #endregion #region Fields and properties public ObservableCollection<UserViewModel> users { get { return ListInstance.Instance.users; } } private UserViewModel User; public UserViewModel user { get { return User; } set { if (value != null) User = value; OnPropertyChange("user"); } } private int index; public int Index { get { return index; } set { index = value; OnPropertyChange("Index"); } } #endregion #region Constructor public LoggedViewModel(UserViewModel user) { this.user = user; Close = new RelayCommand<Window>(_Close); Minimize = new RelayCommand<Window>(_Minimize); WindowClosing = new NormalCommand(Closing); WindowLoaded = new RelayCommand<WrapPanel>(windowLoaded); AddUser = new NormalCommand(addUser); RemoveUser = new RelayCommand<ListBox>(removeUser); EditUser = new NormalCommand(editUser); this.Index = -1; } #endregion #region Methods /// <summary> /// Closing window /// </summary> /// <param name="window"></param> private void _Close(Window window) { MainWindow main = new MainWindow(); main.Show(); window?.Close(); } /// <summary> /// Changing window state to minimize /// </summary> /// <param name="window"></param> private void _Minimize(Window window) { if (window != null) window.WindowState = WindowState.Minimized; } /// <summary> /// Save database to file when window is closing /// </summary> private void Closing() { ListInstance.Instance.SaveDatabase(); } /// <summary> /// Set button to enable when window is loaded /// </summary> /// <param name="panel">Panel to do operation</param> private void windowLoaded(WrapPanel panel) { if (user.status == StatusTypes.admin) { foreach(Button btn in panel.Children) { btn.IsEnabled = true; } } else if (user.status == StatusTypes.moderator) { foreach (Button btn in panel.Children) { if (btn.Tag.ToString() == "Moderator") { btn.IsEnabled = true; } } } } /// <summary> /// Remove user from collection /// </summary> private void removeUser(ListBox box) { if (box.SelectedIndex > -1) { if (ListInstance.Instance.users[box.SelectedIndex].id != user.id) ListInstance.Instance.RemoveUser(Index); else MessageBox.Show("Cannot remove already logged user!"); } } /// <summary> /// Open window for edit user /// </summary> private void editUser() { if (Index > -1) { ManageUserWindow window = new ManageUserWindow(ListInstance.Instance.users[Index], this.user.status); window.ShowDialog(); } } /// <summary> /// Open window for add user /// </summary> private void addUser() { ManageUserWindow window = new ManageUserWindow(null, this.user.status); window.ShowDialog(); } #endregion } } <file_sep>using System; namespace WPFLoginWindow { [Serializable()] public class UserViewModel:BaseViewModel, IComparable { private UserModel user = new UserModel(); #region Fields public int id { get { return user.id; } set { user.id = value; OnPropertyChange("id"); } } public string login { get { return user.login; } set { if (value != null) user.login = value; OnPropertyChange("login"); } } public string password { get { return user.password; } set { if (value != null) user.password = value; OnPropertyChange("password"); } } public StatusTypes status { get { return user.status; } set { user.status = value; OnPropertyChange("status"); } } public DateTime registered { get { return user.registered; } set { if (value != null) user.registered = value; OnPropertyChange("value"); } } public DateTime lastModified { get { return user.lastModified; } set { if (value != null) user.lastModified = value; OnPropertyChange("lastModified"); } } public DateTime lastLogged { get { return user.lastLogged; } set { user.lastLogged = value; OnPropertyChange("lastLogged"); } } public string TimeString { get { return "Registered: " + registered.ToString() + " Last modified: " + lastModified.ToString() + " Last logged: " + lastLogged.ToString(); } } public int CompareTo(object obj) { return id.CompareTo(obj); } #endregion } } <file_sep>namespace WPFLoginWindow { public enum StatusTypes { user,moderator,admin } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace WPFLoginWindow { class ManageUserViewModel:BaseViewModel { #region Commands public ICommand Close { get; set; } public ICommand WindowClosing { get; set; } public ICommand WindowLoaded { get; set; } public ICommand Confirm { get; set; } #endregion #region Fields and Properties private UserViewModel User; public UserViewModel user { get { return User; } set { User = value; OnPropertyChange("user"); } } private StatusTypes status; #endregion #region Constructor public ManageUserViewModel(UserViewModel user,StatusTypes status) { this.user = user; this.status = status; Close = new RelayCommand<Window>(_Close); WindowClosing = new NormalCommand(Closing); WindowLoaded = new RelayCommand<object[]>(windowLoaded); Confirm = new RelayCommand<object[]>(confirm); } #endregion #region Methods /// <summary> /// Closing window /// </summary> /// <param name="window"></param> private void _Close(Window window) { window?.Close(); } /// <summary> /// Save database to file when window is closing /// </summary> private void Closing() { ListInstance.Instance.SaveDatabase(); } /// <summary> /// Set button to enable when window is loaded /// </summary> /// <param name="panel">Panel to do operation</param> private void windowLoaded(object[] box) { if (user != null) { ((TextBox)box[0]).IsEnabled = status == StatusTypes.admin ? true : false; ((TextBox)box[0]).Text = user.login; ((ComboBox)box[1]).SelectedIndex = (int)user.status; ((ComboBox)box[1]).IsEnabled = status == StatusTypes.admin ? true : false; } } /// <summary> /// Add or edit user /// </summary> /// <param name="box">Parameters to add or edit user</param> private void confirm(object[] box) { if (user == null) { bool canAdd = true; foreach(var item in box) { if(item is PasswordBox) canAdd = ((PasswordBox)item).Password.Length > 0 ? true : false; else if(item is TextBox) canAdd = ((TextBox)item).Text.Length > 0 ? true : false; } canAdd = ((PasswordBox)box[1]).Password == ((PasswordBox)box[2]).Password ? true : false; if (canAdd) { ListInstance.Instance.NewUser(((TextBox)box[0]).Text, ((PasswordBox)box[1]).Password, (StatusTypes)((ComboBox)box[3]).SelectedIndex); } else { MessageBox.Show("Wrong data"); } } else { if(this.status==StatusTypes.moderator) ListInstance.Instance.EditUser(new object[]{user.id, ((TextBox)box[0]).Text, ((PasswordBox)box[1]).Password, ((ComboBox)box[3]).SelectedIndex }); else { bool canAdd = true; foreach (var item in box) { if (item is TextBox) canAdd = ((TextBox)item).Text.Length > 0 ? true : false; } canAdd = ((PasswordBox)box[1]).Password == ((PasswordBox)box[2]).Password ? true : false; if (canAdd) { ListInstance.Instance.EditUser(new object[]{user.id, ((TextBox)box[0]).Text, ((PasswordBox)box[1]).Password, ((ComboBox)box[3]).SelectedIndex }); } else { MessageBox.Show("Wrong data"); } } } ((Window)box[4]).Close(); } #endregion } } <file_sep>using System; using System.Windows; using System.Windows.Input; namespace WPFLoginWindow { class MainViewModel:BaseViewModel { #region Fields private string loginText; public string LoginText { get { return loginText; } set { loginText = value; OnPropertyChange("LoginText"); } } private string passwordText; public string PasswordText { get { return passwordText; } set { passwordText = value; OnPropertyChange("PasswordText"); } } #endregion #region Commands public ICommand Close { get; set; } public ICommand Minimize { get; set; } public ICommand Login { get; set; } #endregion #region Constructor public MainViewModel() { Close = new RelayCommand<Window>(_Close); Minimize = new RelayCommand<Window>(_Minimize); Login = new RelayCommand<Window>(_Login); } #endregion #region Methods /// <summary> /// Closing window /// </summary> /// <param name="window"></param> private void _Close(Window window) { Environment.Exit(1); } /// <summary> /// Changing window state to minimize /// </summary> /// <param name="window"></param> private void _Minimize(Window window) { if (window != null) window.WindowState = WindowState.Minimized; } /// <summary> /// Perform login to application /// </summary> /// <param name="param">Needed variables</param> private void _Login(Window win) { object[] param = ListInstance.Instance.CheckForUser(LoginText, PasswordText); if ((bool)param[0]) { LoggedWindow window = new LoggedWindow((UserViewModel)param[1]); window.Show(); win.Close(); } else { MessageBox.Show(param[1].ToString(), "There was a problem!", MessageBoxButton.OK, MessageBoxImage.Error); LoginText = String.Empty; PasswordText = String.Empty; } } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace WPFLoginWindow { [Serializable()] public class BaseViewModel : INotifyPropertyChanged { [field: NonSerialized()] public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChange(string v) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(v)); } } }
fed6823128e8817f15c4eab2ad389ede051d3ed8
[ "C#" ]
8
C#
zerq98/WPFLoginWindow
a27ffba786f19a6b1aa1e639217d7408eb76e8ac
602592f47261dee40e0b9b4bc9c86acbf0591eec
refs/heads/master
<repo_name>bibekaryal/paradise-youtubesubs<file_sep>/js/main.js console.log('PYTS Loaded...');<file_sep>/paradise_youtubesubs.php <?php /* Plugin Name: Paradise Nepal Youtube Subs Description: Display YouTube sub button and count Version: 1.0.0 Author: <NAME> Author URI: https://homea.sgedu.site/colibri-wp/ */ // Exit if accessed directly if(!defined('ABSPATH')){ exit; } // Load Scripts require_once(plugin_dir_path(__FILE__).'/includes/paradise_youtubesubs-scripts.php'); // Load Class require_once(plugin_dir_path(__FILE__).'/includes/paradise_youtubesubs-class.php'); // Register Widget function register_paradise_youtubesubs(){ register_widget('Paradise_Youtube_Subs_Widget'); } // Hook in function add_action('widgets_init', 'register_paradise_youtubesubs');<file_sep>/includes/paradise_youtubesubs-scripts.php <?php // Add Scripts function pyts_add_scripts(){ // Add Main CSS wp_enqueue_style('yts-main-style', plugins_url(). '/paradise_youtubesubs/css/style.css'); // Add Main JS wp_enqueue_script('yts-main-script', plugins_url(). '/paradise_youtubesubs/js/main.js'); // Add Google Script wp_register_script('google', 'https://apis.google.com/js/platform.js'); wp_enqueue_script('google'); } add_action('wp_enqueue_scripts', 'pyts_add_scripts');<file_sep>/README.md # paradise-youtubesubs: Paradise-youtubesubs plugin is used to subscribe the youtube videos and channel. You can subscribe to channels which you like to see more content from those channels. You can find a Subscribe button under any YouTube video or on a channel's page. Once you subscribe to a channel, any new videos it publishes will show up in your Subscriptions feed. When you want to explore more videos you can subscribe from the subscription button which are in all the blog pages. #Installation: Installation is very easy. After you active your plugin then go to the widget and you will see the Paradise-youtubesubs button. You have to add that button into widget and select the place where you want to place. It is so flexible to place the plugin as your desire. #Demo: As a demo i have use the homea.sgedu.site website. If you click on any inner page or blog, you can find the youtube subscribe button on the left side. Thankyou!!! Author: <NAME>
9e535189a63bd3ef4a42cb5d9ba69e7df152b9d4
[ "JavaScript", "Markdown", "PHP" ]
4
JavaScript
bibekaryal/paradise-youtubesubs
fb5f015fdd673ce5adb7d803d26b55d98c58fc96
157786dc66e421bec866884bdfefd29380945327
refs/heads/main
<file_sep>Editorial Statistics ==================== This plugin allows editors to view total content published with the following available settings: 1) Start Date and End Date: Set the start and end dates for the report or choose from one of four predefined date ranges. 2) Report Columns: You must choose at least one of the three columns for Author, Content Type and/or Term. If you choose more than one, the report will break down more granularly. 3) Choose Taxonomies (optional): If you choose Term as a column, you must specify which taxonomies you wish to include in the report. Once submitted, the report will appear in an HTML table below the form. You can click the Export to CSV link to download a copy for further manipulation in Excel. <file_sep><?php /* Plugin Name: Editorial Statistics Description: Allows editors to generate reports in HTML or CSV format for posts published per author, content type, and/or taxonomy term within a specified date range. Compatible with Co-Authors Plus. Author: Al<NAME> (<NAME>) Version: 0.1 Author URI: http://alleyinteractive.com */ require_once( dirname( __FILE__ ) . '/php/class-plugin-dependency.php' ); class Editorial_Statistics { /** * @var Editorial_Statistics * @access private * @static * Static instance of the class */ private static $__instance = NULL; /** * @var string * @access private * Prefix to use for all plugin fields and settings */ private $prefix = 'editorial_statistics_'; /** * @var string * @access private * Plugin name */ private $plugin_name = 'Editorial Statistics'; /** * @var string * @access private * Capability required to use this plugin */ private $capability = 'edit_theme_options'; /** * @var array * @access public * Errors generated by the plugin */ public $errors = array(); /** * @var array * @access public * Available report columns */ public $report_columns = array( 'author', 'content_type', 'term' ); /** * @var array * @access public * Available report columns */ public $filtered_post_types = array( 'attachment', 'guest-author' ); /** * @var string * @access public * Default date format to use for reports and date fields */ public $default_date_format = 'm/d/Y'; /** * @var array * @access public * Predefined date ranges */ public $date_ranges = array(); /** * @var string * @access private * Screen ID */ private $screen_id = 'tools_page_editorial-statistics'; /** * @var object * @access private * Dependency check on Co-Authors Plus */ private $coauthors_plus; /** * Constructor * * @access public */ function __construct() {} /** * Init function * * @access public * @static */ public static function init() { self::instance()->prepare(); } /** * Return singleton instance for this class. * * @access public * @static * @return object Singleton instance for this class */ public static function instance() { if ( self::$__instance == NULL ) { self::$__instance = new Editorial_Statistics; } return self::$__instance; } /** * Prepare settings, variables and hooks. * * @access public */ public function prepare() { add_action( 'init', array( &$this, 'setup_plugin' ) ); add_action( 'wp_loaded', array( &$this, 'check_csv_export' ) ); } /** * Initialize menus and scripts. * * @access public */ public function setup_plugin() { // Allow filtering of the default capability $this->capability = apply_filters( 'editorial_statistics_capability', $this->capability ); // Add action hooks to display the report interface and to handle exports add_action( 'admin_menu', array( &$this, 'register_management_page' ) ); add_action( 'admin_enqueue_scripts', array( &$this, 'enqueue_scripts' ) ); // Add the date ranges $this->date_ranges = array( array( 'name' => 'Yesterday', 'start_date' => date( $this->default_date_format, strtotime( 'yesterday' ) ), 'end_date' => date( $this->default_date_format, strtotime( 'yesterday' ) ) ), array( 'name' => 'Week to Date', 'start_date' => date( $this->default_date_format, strtotime( 'last monday' ) ), 'end_date' => date( $this->default_date_format ) ), array( 'name' => 'This Month', 'start_date' => date( $this->default_date_format, strtotime( 'first day of this month' ) ), 'end_date' => date( $this->default_date_format, strtotime( 'last day of this month' ) ) ), array( 'name' => 'Last Month', 'start_date' => date( $this->default_date_format, strtotime( 'first day of last month' ) ), 'end_date' => date( $this->default_date_format, strtotime( 'last day of last month' ) ) ) ); // Add the dependency check used later to check if Co-Authors Plus is active $this->coauthors_plus = new Plugin_Dependency( $this->plugin_name, 'Co-Authors Plus', 'http://wordpress.org/extend/plugins/co-authors-plus/' ); } /** * Enqueue required scripts. * * @access public */ public function enqueue_scripts() { // Only enqueue the scripts for the Editorial Statistics report screen $screen = get_current_screen(); if ( $screen->id == $this->screen_id ) { $plugin_url = apply_filters( 'editorial_statistics_plugin_url', plugin_dir_url( __FILE__ ) ); // Enqueue the plugin script wp_enqueue_script( $this->prefix . 'js', $plugin_url . 'js/editorial-statistics.js', false, '1.0', true ); // Add chosen.js for the taxonomy selection field wp_enqueue_script( 'chosen', $plugin_url . 'js/chosen/chosen.jquery.min.js', false, '1.0', true ); wp_enqueue_style( 'chosen_css', $plugin_url . 'js/chosen/chosen.css', false, '1.0' ); // Add form validation wp_enqueue_script( 'jquery-validate', $plugin_url . 'js/jquery.validate.min.js', false, '1.0', true ); // Enqueue the plugin styles wp_enqueue_style( $this->prefix . 'css', $plugin_url . 'css/editorial-statistics.css', false, '1.0' ); wp_enqueue_style( 'jquery.ui.theme', $plugin_url . 'css/jquery-ui/jquery-ui-1.10.3.custom.css', false, '1.10.3' ); // Include the jquery datepicker for the report date range wp_enqueue_script( 'jquery-ui-datepicker' ); } } /** * Create the tools menu item for running editorial statistics reports. * * @access public */ public function register_management_page() { add_management_page( $this->plugin_name, $this->plugin_name, $this->capability, 'editorial-statistics', array( &$this, 'management_page' ) ); } /** * Output the management page for running editorial statistics reports. * * @access public */ public function management_page() { ?> <div class="wrap"> <?php screen_icon(); ?> <h2><?php esc_html_e( $this->plugin_name, 'editorial-statistics' ) ?></h2> <form id="editorial_statistics_form" method="post" action=""> <input type="hidden" name="<?php echo $this->prefix ?>output_format" id="<?php echo $this->prefix ?>output_format" value="<?php echo ( isset( $_POST[$this->prefix . 'output_format'] ) ) ? esc_attr( $_POST[$this->prefix . 'output_format'] ) : 'html' ?>" /> <h3><?php esc_html_e( 'Report Settings', 'editorial-statistics' ) ?></h3> <?php wp_nonce_field( $this->prefix . 'nonce' ) ?> <table class="form-table"> <tr valign="top"> <th scope="row"> <label for="<?php echo $this->prefix ?>start_date"> <div> <b><?php esc_html_e( 'Start Date', 'editorial-statistics' ) ?></b> </div> <p><?php esc_html_e( 'Set the start date for the report.', 'editorial-statistics' ) ?></p> </label> </th> <td> <input type="text" name="<?php echo $this->prefix ?>start_date" id="<?php echo $this->prefix ?>start_date" value="<?php echo ( isset( $_POST[$this->prefix . 'start_date'] ) ) ? esc_attr( $_POST[$this->prefix . 'start_date'] ) : '' ?>" /> <div class="error-message"></div> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo $this->prefix ?>end_date"> <div> <b><?php esc_html_e( 'End Date', 'editorial-statistics' ) ?></b> </div> <p><?php esc_html_e( 'Set the end date for the report.', 'editorial-statistics' ) ?></p> </label> </th> <td> <input type="text" name="<?php echo $this->prefix ?>end_date" id="<?php echo $this->prefix ?>end_date" value="<?php echo ( isset( $_POST[$this->prefix . 'end_date'] ) ) ? esc_attr( $_POST[$this->prefix . 'end_date'] ) : '' ?>" /> <div class="error-message"></div> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo $this->prefix ?>predefined_date_ranges"> <div> <b><?php esc_html_e( 'Predefined Date Ranges', 'editorial-statistics' ) ?></b> </div> <p><?php esc_html_e( 'Choose a predefined date range to set the start and end dates for the report.', 'editorial-statistics' ) ?></p> </label> </th> <td> <?php $date_range_output = array(); foreach( $this->date_ranges as $date_range ) { $date_range_output[] = sprintf( '<a href="#" class="editorial-statistics-date-range" data-start-date="%s" data-end-date="%s">%s</a>', $date_range['start_date'], $date_range['end_date'], $date_range['name'] ); } echo implode( '&nbsp;&nbsp;|&nbsp;&nbsp;', $date_range_output ); ?> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo $this->prefix ?>report_columns"> <div> <b><?php esc_html_e( 'Report Columns', 'editorial-statistics' ) ?></b> </div> <p><?php esc_html_e( 'Choose the columns to display in the report (at least one is required).', 'editorial-statistics' ) ?></p> </label> </th> <td> <?php foreach( $this->report_columns as $report_column ): ?> <?php echo sprintf( '<input type="checkbox" value="%s" name="%sreport_columns[]" id="%sreport_columns_%s" class="editorial-statistics-report-column" %s />', esc_attr( $report_column ), esc_attr( $this->prefix ), esc_attr( $this->prefix ), esc_attr( $report_column ), ( isset( $_POST[$this->prefix . 'report_columns'] ) && in_array( $report_column, $_POST[$this->prefix . 'report_columns'] ) ) ? ' checked="checked"' : '' ); ?> <?php esc_html_e( ucwords( str_replace( '_', ' ', $report_column ) ), 'editorial-statistics' ) ?><br /> <?php endforeach; ?> <div class="error-message"></div> </td> </tr> <tr valign="top" id="<?php echo $this->prefix ?>terms_wrapper" class="editorial-statistics-filter" > <th scope="row"> <label for="<?php echo $this->prefix ?>terms"> <div> <b><?php esc_html_e( 'Choose Taxonomies', 'editorial-statistics' ) ?></b> </div> <p><?php esc_html_e( 'Choose which taxonomies should be included in the term column (at least one is required).', 'editorial-statistics' ) ?></p> </label> </th> <td> <?php echo sprintf( '<select multiple="multiple" class="chzn-select" name="%s" id="%s" data-placeholder="%s">%s</select>', esc_attr( $this->prefix . 'terms[]' ), esc_attr( $this->prefix . 'terms' ), esc_html__( 'Select Taxonomies', 'editorial-statistics' ), strip_tags( $this->get_taxonomy_options(), '<option>' ) ); ?> <div class="error-message"></div> </td> </tr> </table> <p class="submit"> <?php submit_button( __( 'Create Report', 'editorial-statistics' ), 'primary', $this->prefix . 'submit', false ); ?> <input type="button" name="editorial_statistics_reset" id="editorial_statistics_reset" class="button delete" value="<?php esc_attr_e( 'Reset Options', 'editorial-statistics' ) ?>" /> </p> </form> <?php // If the form was submitted, display the report in HTML format. $this->create_report(); ?> </div> <?php } /** * Builds the list of options for the taxonomy selection field. * * @access private * @return string */ private function get_taxonomy_options() { // Initialize the container for the taxonomy options list $taxonomy_options = ''; // Get the list of available taxonomies. // Just return an empty string if this blank for some reason. $taxonomies = $this->get_taxonomies(); if ( empty( $taxonomies ) || ! is_array( $taxonomies ) ) { return $taxonomy_options; } foreach( $taxonomies as $taxonomy ) { $taxonomy_options .= sprintf( '<option value="%s" %s>%s</option>', esc_attr( $taxonomy->name ), ( isset( $_POST[ $this->prefix . 'terms' ] ) && in_array( $taxonomy->name, $_POST[ $this->prefix . 'terms' ] ) ) ? ' selected="selected"' : '', esc_html( $taxonomy->label ) ); } return $taxonomy_options; } /** * Get the list of taxonomies for use in filtering reports * * @access private * @return array */ private function get_taxonomies() { // Only return taxonomies that are shown in the admin interface. // Otherwise, the list could be confusing to editors or provide invalid options. return get_taxonomies( array( 'public' => true, 'show_ui' => true ), 'objects' ); } /** * Get the list of post types for use in filtering reports. * * @access private * @return array */ private function get_post_types() { // Only return post types that are shown in the admin interface. // Otherwise, the list could be confusing to editors or provide invalid options. $post_types = get_post_types( array( 'public' => true, 'show_ui' => true ), 'names' ); // Also remove unwanted post types from this list $post_types = array_filter( $post_types, array( &$this, 'filter_post_types' ) ); // Return the post types to be used for the report return $post_types; } /** * Filters unwanted post types for the report * * @access private * @param string $post_type * @return array */ private function filter_post_types( $post_type ) { // Apply filters to allow the list of filtered post types to be editable $post_types_to_filter = apply_filters( $this->prefix . 'filtered_post_types', $this->filtered_post_types ); return ! in_array( $post_type, $post_types_to_filter ); } /** * Create the output for the editorial statistics report. * * @access private * @param string $mode */ private function create_report( $mode = 'html' ) { // Check if the report form was submitted. If not, just return. if ( ! isset( $_POST['editorial_statistics_output_format'] ) || empty( $_POST['editorial_statistics_output_format'] ) ) { return; } // Capability check if ( ! current_user_can( $this->capability ) ) { wp_die( __( 'You do not have access to perform this action', 'editorial-statistics' ) ); } // Form nonce check check_admin_referer( $this->prefix . 'nonce' ); // If the output format does not match the mode, exit // This is important to prevent HTML reports from being output during the init action reserved for CSV reports if ( $mode != $_POST[$this->prefix . 'output_format'] ) { return; } // Query for all posts for public post types in the specified date range add_filter( 'posts_where', array( &$this, 'report_date_filter' ) ); $args = array( 'post_type' => $this->get_post_types(), 'posts_per_page' => -1 ); $posts_query = new WP_Query( $args ); $posts = $posts_query->get_posts(); remove_filter( 'posts_where', array( &$this, 'report_date_filter' ) ); if ( count( $posts ) > 0 && isset( $_POST[$this->prefix . 'report_columns'] ) ) { // Create an array to hold the final data $report_data = array(); // Now we will iterate over each post. // The available report columns are author, content type, and tag in that order. // Based on which were selected, we will group counts for each into a multidimensional array // that will later serve as the final output of the report. foreach( $posts as $post ) { // Build the array keys that will be used to classify and count this post // Report granularity should always be displayed as author, then content type and then term for the specified taxonomies $keys = array(); if ( in_array( 'author', $_POST[$this->prefix . 'report_columns'] ) ) { $authors = array(); if ( $this->coauthors_plus->verify() ) { foreach( get_coauthors( $post->ID ) as $coauthor ) { $authors[] = $coauthor->display_name; } } else { $authors[] = $post->post_author; } $keys[] = $authors; } if ( in_array( 'content_type', $_POST[$this->prefix . 'report_columns'] ) ) { // Use an array here to be consistent with authors and terms and simplify the recursive function that adds totals $keys[] = array( get_post_type_object( $post->post_type )->labels->singular_name ); } if ( in_array( 'term', $_POST[$this->prefix . 'report_columns'] ) ) { $taxonomy_terms = array(); foreach( wp_get_post_terms( $post->ID, $_POST[$this->prefix . 'terms'] ) as $term ) { $taxonomy_terms[] = $term->name; } // If there are no terms, just use 'None' if ( empty( $taxonomy_terms ) ) { $taxonomy_terms[] = __( 'None', 'editorial-statistics' ); } $keys[] = $taxonomy_terms; } // Add this story to the totals for the appropriate rows in the final report $report_data = $this->add_report_totals( $report_data, $keys ); } // Sort the data for the report $this->sort_report_data( $report_data ); // Output the data $this->output_report_data( $report_data, $_POST[$this->prefix . 'output_format'], $_POST[ $this->prefix . 'report_columns' ] ); } else if ( ( 0 == count( $posts ) || ! isset( $_POST[$this->prefix . 'report_columns'] ) ) && 'html' == $_POST[ $this->prefix . 'output_format' ] ) { ?> <h4><?php esc_html_e( 'No results were returned for the current report settings.', 'editorial-statistics' ) ?></h4> <?php } } /** * Adds a date filter for the report * * @access public * @param string $where * @return string */ public function report_date_filter( $where = '' ) { // Ensure the date parameters are set. Otherwise invalidate the query. if ( isset( $_POST[$this->prefix . 'start_date'] ) && isset( $_POST[ $this->prefix . 'end_date' ] ) ) { $where .= " AND post_date >= '" . date( 'Y-m-d', intval( strtotime( $_POST[ $this->prefix . 'start_date' ] ) ) ) . "' AND post_date < '" . date( 'Y-m-d', intval( strtotime( $_POST[ $this->prefix . 'end_date' ] ) ) + ( 60*60*24 ) ) . "'"; } else { $where .= " AND 1=2"; } return $where; } /** * Recursive function to add to the totals for the final report. * Adds one to the lowest level of the indexes provided. * * @access private * @param array $report_data * @param array $keys * @return string */ private function add_report_totals( $report_data, $keys ) { // Get the keys used for this level and shift them off the array of keys $lvl_keys = array_shift( $keys ); // Iterate through the keys for this level of the report foreach( $lvl_keys as $lvl_key ) { // If the keys array is now empty, we have reached the lowest level and add one to the key // Otherwise, recurse with the trimmed keys array and set this index equal to the result if ( empty( $keys ) ) { if ( empty( $report_data[ $lvl_key ] ) ) { $report_data[ $lvl_key ] = 0; } $report_data[ $lvl_key ]++; } else { // If this key does not yet exist, initialize it as an empty array if ( ! array_key_exists( $lvl_key, $report_data ) ) { $report_data[ $lvl_key ] = array(); } // Recurse with the newly trimmed keys array to get down to the final level to add totals $report_data[ $lvl_key ] = $this->add_report_totals( $report_data[ $lvl_key ], $keys ); } } // Return the final report data return $report_data; } /** * Outputs the final data for the report. * Uses a simple HTML table or CSV format. * * @access private * @param array $report_data * @param string $report_format * @param string $report_columns * @return string */ private function output_report_data( $report_data, $report_format = 'html', $report_columns ) { // Generate the data for the report $this->generate_report_data( $output_data, $report_data, sanitize_text_field( $_POST[ $this->prefix . 'output_format' ] ) ); // Output based on the format specified if( 'csv' == $report_format ) { // Set the filename for the report $filename = 'report.csv'; // Output the headers required for CSV export header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' ); header( 'Content-Description: File Transfer' ); header( 'Content-type: text/csv' ); header( "Content-Disposition: attachment; filename={$filename}" ); header( 'Expires: 0' ); header( 'Pragma: public' ); // Open the file handle for streaming output $fh = @fopen( 'php://output', 'w' ); // Write the headers $report_columns = array_map( array( &$this, 'format_report_column' ), $report_columns ); $report_columns[] = __( 'Total Stories', 'editorial-statistics' ); $header_row = sprintf( "\"%s\"\n", implode( '","', $report_columns ) ); fwrite( $fh, $header_row ); // Write the data fwrite( $fh, $output_data ); // Close the file handle fclose( $fh ); // Exit at this point because we don't want to display anything further in the popup window exit; } else { ?> <h3><?php esc_html_e( 'Report', 'editorial-statistics' ) ?></h3> <div><a href="#" id="<?php echo esc_attr( $this->prefix ); ?>export_to_csv"><?php esc_html_e( 'Export to CSV', 'editorial-statistics' ) ?></a></div> <table id="report_table"> <tr> <?php foreach( $report_columns as $report_column ) { echo sprintf( '<td class="header">%s</td>', esc_html( $this->format_report_column( $report_column ) ) ); } ?> <td class="header"><?php esc_html_e( 'Total Stories', 'editorial-statistics' ) ?></td> </tr> <?php echo wp_kses_post( $output_data ) ?> </table> <?php } } /** * Generates the data for the report in either HTML or CSV format. * * @access private * @param string $output_data * @param array $report_data * @param string $report_format * @param array $row_values * @return string */ private function generate_report_data( &$output_data, $report_data, $report_format = 'html', $row_values = array() ) { // Determine if we are still building a row of data or if it is ready to be output if ( is_array( $report_data ) ) { // This is still an array of data so get the keys for the current level // Add it to the row values as the next column of data to be output and pass its value to this function recursively $keys = array_keys( $report_data ); foreach( $keys as $key ) { // Add this key as a column in the report $row_values[] = $key; // Recursively call this function until we reach the total (i.e. final column) $this->generate_report_data( $output_data, $report_data[$key], $report_format, $row_values ); // Pop this column off the output data before we iterate to the next one array_pop( $row_values ); } } else { // If report data is not an array, we've reached the lowest level of the report data and should output the row // Set the row start, end and separators based on the output format switch( $report_format ) { case 'csv': $row_start = '"'; $row_end = "\"\n"; $separator = '","'; break; case 'html': default: $row_start = '<tr><td>'; $row_end = '</td></tr>'; $separator = '</td><td>'; break; } // Start the row $output_data .= $row_start; // Output the row data after adding the final column, which is the total $row_values[] = $report_data; $output_data .= implode( $separator, $row_values ); // End the row $output_data .= $row_end; } } /** * Recursive function to sort the data before displaying it. * * @access private * @param array $report_data * @return string */ private function sort_report_data( &$report_data ) { foreach( $report_data as $column ) { if ( is_array( $column ) ) { $this->sort_report_data( $column ); } } ksort( $report_data ); } /** * Format a report column type for output in a report * * @access private * @param string $report_column */ public function format_report_column( $report_column ) { return ucwords( str_replace( '_', ' ', $report_column ) ); } /** * Check if a CSV export was requested. * * @access public */ public function check_csv_export() { // Check if the report form was submitted for CSV export // If so, intercept it here and output the required headers to stream a CSV to the browser $this->create_report( 'csv' ); } /** * Log an error. * * @param string $message * @return bool false */ private function error( $message ) { $this->errors[] = $message; return false; } /** * Display any errors on the site, */ public function display_errors() { if ( count( $this->errors ) ) : ?> <div id="message" class="error"> <p> <?php echo esc_html( _n( 'There was an issue retrieving your user account: ', 'There were issues retrieving your user account: ', count( $this->errors ), 'editorial-statistics' ) ) ?> <br /> &bull; <?php echo wp_kses_post( implode( "\n\t\t\t\t<br /> &bull; ", $this->errors ) ) ?> </p> </div> <?php endif; } } Editorial_Statistics::init();
673290a53451457eaa981580a975a41f6d635c9c
[ "Markdown", "PHP" ]
2
Markdown
isabella232/editorial-statistics
0423cea10345dc4a07796e474912031ca34b55ca
27118c1c8076e9bdbb090984000b9940e5184c68
refs/heads/main
<repo_name>iMyGirl/spyder_stadiumgoods<file_sep>/code.py from bs4 import BeautifulSoup from urllib.request import urlopen import re import requests import urllib.request import json import pandas as pd import csv # 利用colab云上编译 # 保存文件 # from pydrive.auth import GoogleAuth # from pydrive.drive import GoogleDrive # from google.colab import auth # from oauth2client.client import GoogleCredentials # 爬取所有搜索页面的url def url_load(url): print(url) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(url,None,headers = headers) #print(req) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, features='lxml') centent = soup.find('div', {"class": "category-products"}) b = centent.find_all('li') url_all = [] name_all = [] size_all = [] prize_all = [] # 爬取各搜索页中各详情页的url for a in b: all_href = a.find_all('a',{"class":"product-image"}) #print(all_href) # 进入详情页,爬取各页面的详情参数 for l in all_href: #print(l['href']) #list[] = l['href'] e = l['href'] u = printurl(e) url_all.append(u) #print(u) n = printname(e) name_all.append(n) s = printsize(e) size_all.append(s) p = printprize(e) prize_all.append(p) #print(au) data = { 'url' : url_all, 'name' : name_all, 'size' : size_all, 'prize' : prize_all } #print(data) #data_csv = pd.DataFrame(data) return data #data_csv.to_csv("data.csv",index=False,sep=',') #print(u) # 爬取详情页链接 def printurl(url): print(url) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(url,None,headers = headers) #print(req) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, features='lxml') url_single = [] #for i in range(1,24): url_single.append(url) #print(url_single) return url_single # 爬取详情页产品名称 def printname(url): #print(url) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(url,None,headers = headers) #print(req) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, features='lxml') #<h1 class="product-name" itemprop="name"> h = soup.find('h1',{"class":"product-name"}) #print(h.get_text()) name_single = [] #for i in range(1,24): name_single.append(h.get_text()) return name_single # 爬取详情页产品的鞋码 def printsize(url): #print(url) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(url,None,headers = headers) #print(req) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, features='lxml') #<span class="product-sizes__size">7*</span> s = soup.find_all('span',{"class":"product-sizes__size"}) size_single = [] for size in s: #print(size.get_text()) size_single.append(size.get_text()) return size_single # 爬取详情页产品的价格 def printprize(url): #print(url) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(url,None,headers = headers) #print(req) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, features='lxml') #<span class="product-sizes__price" data-selected-price>CN¥5,296.00</span> p = soup.find_all('span',{"class":"product-sizes__price"}) #print(p.get_text()) prize_single = [] for prize in p: #print(prize.get_text()) prize_single.append(prize.get_text()) return prize_single #def write_csv(content): if __name__ == '__main__': # 以Air Jordan 1 为例 url = 'https://www.stadiumgoods.com/air-jordan/air-jordan-1' # 开始爬取 x = url_load(url) # 分页面保存 data_csv = pd.DataFrame(x) data_csv.to_csv("data/data01.csv",index=False,sep=',') <file_sep>/result.md ### colab平台试验记录-20190919 ```python 代码单元格 <UoWyxPyQ9frz> #%% [code] from bs4 import BeautifulSoup from urllib.request import urlopen import re import requests import urllib.request import json import pandas as pd import csv #保存文件 from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials def url_load(url): print(url) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(url,None,headers = headers) #print(req) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, features='lxml') centent = soup.find('div', {"class": "category-products"}) b = centent.find_all('li') url_all = [] name_all = [] size_all = [] prize_all = [] for a in b: all_href = a.find_all('a',{"class":"product-image"}) #print(all_href) for l in all_href: #print(l['href']) #list[] = l['href'] e = l['href'] #u = printurl(e) print(e) url_single = [] url_single.append(e) u = url_single url_all.append(u) #print(u) n = printname(e) name_all.append(n) s = printsize(e) size_all.append(s) p = printprize(e) prize_all.append(p) #print(au) data = { 'url' : url_all, 'name' : name_all, 'size' : size_all, 'prize' : prize_all } #print(data) #data_csv = pd.DataFrame(data) return data #data_csv.to_csv("data.csv",index=False,sep=',') #print(u) def printurl(url): print(url) # headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} # req = urllib.request.Request(url,None,headers = headers) # #print(req) # html = urllib.request.urlopen(req).read() # soup = BeautifulSoup(html, features='lxml') url_single = [] #for i in range(1,24): url_single.append(url) #print(url_single) return url_single def printname(url): #print(url) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(url,None,headers = headers) #print(req) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, features='lxml') #<h1 class="product-name" itemprop="name"> h = soup.find('h1',{"class":"product-name"}) #print(h.get_text()) name_single = [] #for i in range(1,24): name_single.append(h.get_text()) return name_single def printsize(url): #print(url) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(url,None,headers = headers) #print(req) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, features='lxml') #<span class="product-sizes__size">7*</span> s = soup.find_all('span',{"class":"product-sizes__size"}) size_single = [] for size in s: #print(size.get_text()) size_single.append(size.get_text()) return size_single def printprize(url): #print(url) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(url,None,headers = headers) #print(req) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, features='lxml') #<span class="product-sizes__price" data-selected-price>CN¥5,296.00</span> p = soup.find_all('span',{"class":"product-sizes__price"}) #print(p.get_text()) prize_single = [] for prize in p: #print(prize.get_text()) prize_single.append(prize.get_text()) return prize_single #def write_csv(content): def url_page(url,beginPage,endPage): for p in range(beginPage,endPage+1): fullurl = url + "/page/" + str(p) #print(fullurl) x = url_load(fullurl) data_csv = pd.DataFrame(x) #file_name = "data" + str(p) + ".csv" data_csv.to_csv('data.csv',index=False,sep=',') # Authenticate and create the PyDrive client. # This only needs to be done once in a notebook. auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) # Create & upload a text file. #你想要导出的文件的名字 uploaded = drive.CreateFile({'title': 'OK.csv'}) #改为之前生成文件的名字 uploaded.SetContentFile('data.csv') uploaded.Upload() print('Uploaded file with ID {}'.format(uploaded.get('id'))) #url_2 = "https://www.stadiumgoods.com/air-jordan/air-jordan-1/page/1" if __name__ == '__main__': url = "https://www.stadiumgoods.com/air-jordan/air-jordan-1/page/1" #url_page(url,1,7) x = {} x = url_load(url) xyz = pd.DataFrame(x) xyz.to_csv('over.csv') # Authenticate and create the PyDrive client. # This only needs to be done once in a notebook. auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) # Create & upload a text file. #你想要导出的文件的名字 uploaded = drive.CreateFile({'title': 'OK.csv'}) #改为之前生成文件的名字 uploaded.SetContentFile('over.csv') uploaded.Upload() print('Uploaded file with ID {}'.format(uploaded.get('id'))) ``` ### 运行结果 ``` 2019年9月19日 下午9:30的执行输出 Stream https://www.stadiumgoods.com/air-jordan/air-jordan-1/page/1 https://www.stadiumgoods.com/air-jordan-1-low-travis-scott-cq4277-001 https://www.stadiumgoods.com/air-jordan-1-high-og-wmns-satin-black-toe-cd0461-016 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-obsidian-university-blue-555088-140 https://www.stadiumgoods.com/air-jordan-1-retro-high-obsidian-university-blue-og-gs-575441-140 https://www.stadiumgoods.com/air-jordan-1-high-og-defiant-yellow-cd6579-071 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-travis-scott-cd4487-100 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-defiant-couture-bq6682-006 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-la-to-chicago-court-purple-cd6578-507 https://www.stadiumgoods.com/air-jordan-1-mid-gs-554725-058-black-starfish-starfish-white https://www.stadiumgoods.com/air-jordan-1-low-black-toe-553558-116 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-gym-red-555088-061 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-gs-turbo-green-575441-311 https://www.stadiumgoods.com/air-jordan-1-mid-yellow-toe-852542-071 https://www.stadiumgoods.com/air-jordan-1-low-shattered-backboard-553558-128 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-555088-311-turbo-green-sail-white https://www.stadiumgoods.com/air-jordan-1-mid-obsidian-554724-174 https://www.stadiumgoods.com/air-jordan-1-mid-gs-554725-174-white-metallic-gold-obsidian https://www.stadiumgoods.com/air-jordan-1-retro-high-og-phantom-555088-160 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-rookie-of-the-year-555088-700 https://www.stadiumgoods.com/air-jordan-1-low-royal-toe-cq9446-400 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-neutral-grey-hyper-crimson-555088-018 https://www.stadiumgoods.com/air-jordan-1-mid-black-gold-patent-leather-852542-007 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-271466 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-crimson-tint-555088-081 https://www.stadiumgoods.com/air-jordan-1-sb-retro-high-og-nyc-to-paris-light-bone-cd6578-006 https://www.stadiumgoods.com/air-jordan-1-mid-shattered-backboard-554724-058 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-sports-illustrated-555088-015 https://www.stadiumgoods.com/air-jordan-1-mid-554724-050-black-dark-grey-black https://www.stadiumgoods.com/air-jordan-1-mid-gs-554725-125-white-university-red-black https://www.stadiumgoods.com/air-jordan-1-low-gold-toe-cq94478-700 https://www.stadiumgoods.com/air-jordan-1-retro-high-off-white-unc-aq0818-148 https://www.stadiumgoods.com/air-jordan-1-low-gs-cq9487-700-metallic-gold-black-white https://www.stadiumgoods.com/air-jordan-1-retro-high-og-royale-2017-555088-007 https://www.stadiumgoods.com/air-jordan-1-low-mystic-green-553558-113 https://www.stadiumgoods.com/air-jordan-1-mid-gs-555112-190-white-rose-gold-black https://www.stadiumgoods.com/air-jordan-1-retro-high-og-gs-unc-patent-leather-cd0461-401 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-nrg-256843 https://www.stadiumgoods.com/air-jordan-1-mid-554724-062-black-cone-light-bone https://www.stadiumgoods.com/air-jordan-1-mid-554724-051-black-dark-concord-white https://www.stadiumgoods.com/air-jordan-1-low-cj9216-051-black-field-purple-white https://www.stadiumgoods.com/air-jordan-1-retro-high-og-gym-red-gs-575441-061 https://www.stadiumgoods.com/air-jordan-1-mid-554724-061-black-infrared-23-white https://www.stadiumgoods.com/air-jordan-1-low-gs-553560-116-white-black-gym-red https://www.stadiumgoods.com/air-jordan-1-retro-high-og-nrg-861428-061-black-university-red-white https://www.stadiumgoods.com/air-jordan-1-retro-high-og-gs-crimson-tint-575441-081 https://www.stadiumgoods.com/air-jordan-1-mid-se-gs-bq6931-007-black-metallic-gold-white https://www.stadiumgoods.com/air-jordan-1-retro-high-og-gs-575441-602-gym-red-black-white-photo-blue https://www.stadiumgoods.com/air-jordan-1-low-royal-toe-gs-cq9486-400 https://www.stadiumgoods.com/air-jordan-1-mid-white-black-bq6472-101 https://www.stadiumgoods.com/air-jordan-1-low-gs-553560-128-white-black-starfish https://www.stadiumgoods.com/air-jordan-1-low-university-gold-553558-127 https://www.stadiumgoods.com/wmns-air-jordan-1-retro-low-ns-ah7232-100-white-metallic-gold-white https://www.stadiumgoods.com/air-jordan-1-retro-high-og-gs-575441-401-hyper-royal-sail-hyper-royal https://www.stadiumgoods.com/air-jordan-1-mid-lakers-2019-852542-700 https://www.stadiumgoods.com/nike-air-jordan-1-low-sb-eric-koston-cj7891-401 https://www.stadiumgoods.com/air-jordan-1-mid-554724-125-white-university-red-black https://www.stadiumgoods.com/air-jordan-1-mid-554724-121-white-metallic-silver-black https://www.stadiumgoods.com/jordan-1-mid-554724-116-white-black-gym-red https://www.stadiumgoods.com/air-jordan-1-retro-high-og-gs-575441-015-black-varsity-red-sail https://www.stadiumgoods.com/air-jordan-1-mid-top-3-gs-bq6931-005 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-bg-248848 https://www.stadiumgoods.com/jordan-1-retro-high-555088-610-red-black-white https://www.stadiumgoods.com/air-jordan-1-mid-554724-124-white-black-hyper-royal https://www.stadiumgoods.com/air-jordan-1-mid-554724-113-white-black-white https://www.stadiumgoods.com/air-jordan-1-retro-high-og-nigel-sylvester-bv1803-106 https://www.stadiumgoods.com/air-jordan-1-retro-high-off-white-white-aq0818-100 https://www.stadiumgoods.com/air-jordan-1-retro-high-pine-green-555088-302 https://www.stadiumgoods.com/wmns-air-jordan-1-retro-low-ns-ah7232-011-black-metallic-gold-white https://www.stadiumgoods.com/air-jordan-1-mid-se-852542-306-turbo-green-black-hyper-pink https://www.stadiumgoods.com/air-jordan-1-mid-se-852542-301-pine-green-black-sail https://www.stadiumgoods.com/air-jordan-1-low-hyper-pink-553558-119 https://www.stadiumgoods.com/air-jordan-1-retro-court-purple-555088-501 https://www.stadiumgoods.com/air-jordan-1-mid-se-852542-801-crimson-tint-hyper-pink-black https://www.stadiumgoods.com/air-jordan-1-retro-high-og-gs-575441-160-sail-black-phantom-gym-red https://www.stadiumgoods.com/air-jordan-mid-1-all-over-logos-gs-554725-143 https://www.stadiumgoods.com/air-jordan-1-mid-gs-bv7446-400-blue-void-clear-team-royal https://www.stadiumgoods.com/air-jordan-1-retro-high-og-555088-801-guava-ice-sail https://www.stadiumgoods.com/air-jordan-1-mid-gs-554725-116-white-black-gym-red https://www.stadiumgoods.com/air-jordan-1-mid-554724-115-white-black-wolf-grey https://www.stadiumgoods.com/air-jordan-1-retro-high-og-555088-401-hyper-royal-sail https://www.stadiumgoods.com/air-jordan-1-mid-gs-555112-300-green-abyss-frosted-spruce https://www.stadiumgoods.com/air-jordan-1-retro-high-union-storm-blue-bv1300-146 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-271456 https://www.stadiumgoods.com/air-jordan-1-mid-bq6578-001-black-university-red-white https://www.stadiumgoods.com/air-jordan-1-retro-high-og-twist-panda-cd0461-007 https://www.stadiumgoods.com/air-jordan-1-mid-se-852542-400-deep-royal-blue-black https://www.stadiumgoods.com/air-jordan-1-retro-high-union-black-toe-bv1300-106 https://www.stadiumgoods.com/air-jordan-1-mid-bq6578-100-white https://www.stadiumgoods.com/air-jordan-1-retro-high-og-bg-248850 https://www.stadiumgoods.com/air-jordan-1-mid-se-852542-010-black-black-sail-wolf-grey https://www.stadiumgoods.com/air-jordan-1-mid-gs-ice-blue-555112-104 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-spider-man-origin-story-555088-602 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-bg-248849 https://www.stadiumgoods.com/air-jordan-1-retro-high-og-clay-green-555088-135 https://www.stadiumgoods.com/wmns-air-jordan-1-high-og-nrg-bv2613-600-bordeaux-lt-armory-blue https://www.stadiumgoods.com/air-jordan-1-mid-gs-554725-061-black-infrared-23-white Uploaded file with ID 19Yw-fgKevLDNFQOWFeALZU8ZuweQ9_sv ``` <file_sep>/README.md # spyder_stadiumgoods # 爬取国外一球鞋网站<https://www.stadiumgoods.com> ## 写在前面 >该项目是于2019年于某鱼平台上接单,帮助开发的一个爬取球鞋网站<https://www.stadiumgoods.com>各商品数据的一个脚本 > >感兴趣可联系<<EMAIL>> > >我的主页<https://imygirl.github.io/> ## 说明: 0. result.md中记录了colab平台上的运行结果,可参考; 1. 在主程序中添加 url 即可运行 code.py 文件; 2. 运行 code.py 文件生成的csv文件为分页爬取结果; 3. 可通过其他脚本将分页爬取结果汇总至一个文件中; 4. 主要通过<kbd>BeautifulSoup</kbd>数据包单线程爬取,分析**url**指向页面,伪装**header**爬取,主体程序架构如下: ``` --># 爬取所有搜索页面的url --># 爬取各搜索页中各详情页的url for i in 所有搜索页面的url: --># 进入详情页,爬取各页面的详情参数 for j in 各搜索页中各详情页的url: ... ``` ## 爬取结果 >data01.csv <img src="https://github.com/iMyGirl/spyder_stadiumgoods/blob/main/data/data01.png" width="100%">
5609ada09e80702e2ace1f4354dec194cb924f97
[ "Markdown", "Python" ]
3
Python
iMyGirl/spyder_stadiumgoods
4d98cc53b4f81a73c968720a8da0ff404e4da002
77578321c9255dde13572a3f17e2f7b0cd05b090
refs/heads/master
<file_sep>package com.example.sphinxassignment.ui import android.annotation.SuppressLint import android.os.Bundle import android.view.Menu import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.menu.MenuBuilder import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import com.denzcoskun.imageslider.constants.ScaleTypes import com.denzcoskun.imageslider.models.SlideModel import com.example.sphinxassignment.R import com.example.sphinxassignment.network.responses.LoginResponse import dagger.hilt.android.AndroidEntryPoint import kotlinx.android.synthetic.main.activity_dashboard.* import java.util.* @AndroidEntryPoint class DashboardActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_dashboard) setSupportActionBar(toolbar) setSliderImages() setMostUsedRecycler() } private fun setMostUsedRecycler() { val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) rv1.layoutManager = linearLayoutManager rv1.itemAnimator = DefaultItemAnimator() rv1.setHasFixedSize(true) val linearLayoutManager1 = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) rv2.layoutManager = linearLayoutManager1 rv2.itemAnimator = DefaultItemAnimator() rv2.setHasFixedSize(true) val linearLayoutManager2 = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) rv3.layoutManager = linearLayoutManager2 rv3.itemAnimator = DefaultItemAnimator() rv3.setHasFixedSize(true) val list = ArrayList<LoginResponse>() val list1 = ArrayList<LoginResponse>() val list2 = ArrayList<LoginResponse>() for (i in 0..2) { val data = LoginResponse().apply { foodname = "Veg-Food !!" } list.add(data) } for (i in 0..1) { val data = LoginResponse().apply { foodname = "Cleaning !!" } list1.add(data) } val data = LoginResponse().apply { foodname = "Resto !!" } list2.add(data) val adapterFood = AdapterFood(this) rv1.adapter = adapterFood adapterFood.refresh(list) val adapterFood1 = AdapterFood(this) rv2.adapter = adapterFood1 adapterFood1.refresh(list1) val adapterFood2 = AdapterFood(this) rv3.adapter = adapterFood2 adapterFood2.refresh(list2) } private fun setSliderImages() { val imageList = ArrayList<SlideModel>() imageList.add(SlideModel(R.drawable.img1, ScaleTypes.FIT)) imageList.add(SlideModel(R.drawable.img2, ScaleTypes.FIT)) banner_slider.setImageList(imageList) } @SuppressLint("RestrictedApi") override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.app_menu, menu) return true } }<file_sep>rootProject.name = "Sphinx Assignment" include ':app' <file_sep>package com.example.sphinxassignment.network.api.apihelper import com.example.sphinxassignment.network.responses.LoginResponse import retrofit2.Response import retrofit2.http.Body interface ApiHelper { suspend fun authenticate(@Body loginResponse: LoginResponse): Response<LoginResponse> suspend fun signUp(@Body loginResponse: LoginResponse): Response<LoginResponse> suspend fun getCityList(): Response<LoginResponse> }<file_sep>package com.example.sphinxassignment.network.responses import com.google.gson.annotations.SerializedName data class LoginResponse( @field:SerializedName("access_token") var access_token: String? = null, var status: String? = null, var email: String? = null, var password: String? = null, @field:SerializedName("social_id") var social_id: String? = null, @field:SerializedName("user_type") var user_type: String? = null, @field:SerializedName("address") var address: String? = null, @field:SerializedName("social_type") var social_type: String? = null, @field:SerializedName("contact") var contact: String? = null, var foodname: String? = null, @field:SerializedName("latitude") var latitude: Double? = null, @field:SerializedName("username") var username: String? = null, @field:SerializedName("longitude") var longitude: Double? = null, @field:SerializedName("city_id") var city_id: Int? = null, @field:SerializedName("list") var getCityList: List<CityList>? = null, ) data class CityList( @field:SerializedName("latitude") var latitude: String? = null, @field:SerializedName("name") val name: String? = null, @field:SerializedName("id") var id: Int? = null, @field:SerializedName("country_id") var countryId: Int? = null, @field:SerializedName("status") var status: String? = null, @field:SerializedName("longitude") var longitude: String? = null )<file_sep>package com.example.sphinxassignment.ui.auth import android.content.Context import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.sphinxassignment.network.responses.LoginResponse import com.example.sphinxassignment.Utils import com.example.sphinxassignment.network.api.repository.ApiRepository import com.example.sphinxassignment.network.responses.CityList import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.launch class LoginViewModel @ViewModelInject constructor( @ApplicationContext val context: Context, private val apiRepository: ApiRepository, ) : ViewModel() { var isSuccessful: MutableLiveData<Boolean> = MutableLiveData() var cityList: MutableLiveData<List<CityList>> = MutableLiveData() fun doSignIn( emailID: String, pass: String ) { viewModelScope.launch { val loginResponse = LoginResponse().apply { email = emailID password = <PASSWORD> } apiRepository.authenticate(loginResponse).let { try { if (it.isSuccessful && it.body()?.status.equals("success")) { isSuccessful.value = true } else { if (it.errorBody() != null) { Utils.showToast( context, it.errorBody()?.string() ?.split(",")!![1].removeSuffix("}") ) } isSuccessful.value = false } } catch (e: Exception) { e.printStackTrace() isSuccessful.value = false } } } } fun doSignUp( emailId: String, userName: String, mobile: String, user_Type: String, add: String, lat: String, lon: String, pass: String, so_id: String, so_type: String, cityId: Int, ) { viewModelScope.launch { val loginResponse = LoginResponse().apply { email = emailId username = userName contact = mobile user_type = user_Type address = add latitude = lat.toDouble() longitude = lon.toDouble() password = <PASSWORD> social_id = so_id social_type = so_type city_id = cityId } apiRepository.signUp(loginResponse).let { try { if (it.isSuccessful && it.code() == 200) { isSuccessful.value = true Utils.showToast(context, "User Registered Successfully .") } else { if (it.errorBody() != null) { Utils.showToast( context, it.errorBody()?.string() ?.split(",")!![1].removeSuffix("}") ) } isSuccessful.value = false } } catch (e: Exception) { e.printStackTrace() isSuccessful.value = false } } } } fun getCityList() { viewModelScope.launch { apiRepository.getCityList().let { try { if (it.isSuccessful && it.body()?.status.equals("success")) { if (it.body()?.getCityList?.isNotEmpty() == true) { cityList.value = it.body()?.getCityList } } else { if (it.errorBody() != null) { Utils.showToast( context, it.errorBody()?.string() ?.split(",")!![1].removeSuffix("}") ) } } } catch (e: Exception) { e.printStackTrace() isSuccessful.value = false } } } } }<file_sep>package com.example.ridecellassignment import android.widget.EditText import java.util.regex.Matcher import java.util.regex.Pattern object Validations { fun edtValidation(editText: EditText, error: String?): Boolean { if (editText.text.toString().isEmpty()) { editText.requestFocus() editText.error = error return false } else editText.error = null return true } fun mobileValidation(editText: EditText): Boolean { if (editText.text.toString().isEmpty()) { editText.requestFocus() editText.error = "Enter mobile number" return false } else if (!isMobileValid(editText.text.toString().trim { it <= ' ' })) { editText.requestFocus() editText.error = "Enter valid mobile number" return false } else editText.error = null return true } fun isMobileValid(mobile: String?): Boolean { // boolean isValid = false; val pattern = Pattern.compile("^([7-9]{1})([0-9]{9})$") val matcher = pattern.matcher(mobile) // Check if pattern matches // Check if pattern matches return if (matcher.matches()) true else false } fun emailValidation(editText: EditText): Boolean { if (editText.text.toString().isEmpty()) { editText.requestFocus() editText.error = "Enter Email Id" return false } else if (!isEmailValid(editText.text.toString().trim { it <= ' ' })) { editText.requestFocus() editText.error = "Enter valid email address" return false } else editText.error = null return true } fun isEmailValid(email: String): Boolean { var isValid = false val expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$" val inputStr: CharSequence = email val pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE) val matcher = pattern.matcher(inputStr) if (matcher.matches()) { isValid = true } return isValid } fun passwordValidation(editText: EditText): Boolean { if (editText.text.toString().isEmpty()) { editText.requestFocus() editText.error = "Enter password" return false } else if (!isValidPassword(editText.text.toString())) { editText.requestFocus() editText.error = "Your password must be at least 5 characters long, contain at least one number, special character and have a mixture of uppercase and lowercase letters." return false } else editText.error = null return true } fun isValidPassword(password: String?): Boolean { // final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[A-Z])(?=.*[@#$%^&+=!])(?=\\S+$).{4,}$"; val PASSWORD_PATTERN = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@\$%^&*-]).{5,20}\$" val pattern: Pattern = Pattern.compile(PASSWORD_PATTERN) val matcher: Matcher = pattern.matcher(password) return matcher.matches() } }<file_sep>package com.example.sphinxassignment.ui.auth import android.app.Dialog import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.activity.viewModels import androidx.databinding.DataBindingUtil import com.example.ridecellassignment.Validations import com.example.sphinxassignment.R import com.example.sphinxassignment.Utils import com.example.sphinxassignment.databinding.ActivityLoginBinding import com.example.sphinxassignment.databinding.ActivitySignupBinding import com.example.sphinxassignment.network.responses.CityList import com.example.sphinxassignment.ui.DashboardActivity import dagger.hilt.android.AndroidEntryPoint import kotlinx.android.synthetic.main.activity_login.* import kotlinx.android.synthetic.main.activity_signup.* @AndroidEntryPoint class SignUpActivity : AppCompatActivity() { lateinit var binding: ActivitySignupBinding val viewModel: LoginViewModel by viewModels() lateinit var pDialog: Dialog val listname = ArrayList<String>() val listCity = ArrayList<CityList>() var lat = "" var lon = "" var city_id = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_signup) binding.executePendingBindings() binding.viewModel = viewModel setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar!!.setDisplayShowHomeEnabled(true) toolbar.setNavigationIcon(R.drawable.back) toolbar.setNavigationOnClickListener { finish() } pDialog = Utils.generateProgressDialog(this)!! observeCityList() onSignUp() getCityList() binding.btnRegister.setOnClickListener { if (!Validations.edtValidation(edit_username, "Enter Username")) return@setOnClickListener else if (!Validations.emailValidation(edit_emailId)) return@setOnClickListener else if (!Validations.mobileValidation(edit_mobile)) return@setOnClickListener else if (!Validations.edtValidation(edit_password, "Enter Password")) return@setOnClickListener else if (sp_city.selectedItem.toString().equals("City", true)) { Utils.showToast(this, "Select City") } else signUpUser() } binding.spCity.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, id: Long ) { if (sp_city.selectedItem.toString() != "City") { for (list in listCity) { if (sp_city.selectedItem.toString() == list.name) { city_id = list.id!! lat = list.latitude!! lon = list.longitude!! } } } } override fun onNothingSelected(parent: AdapterView<*>?) { } } } private fun onSignUp() { viewModel.isSuccessful.observe(this, androidx.lifecycle.Observer { isSuccess -> if (isSuccess) { startActivity(Intent(this, DashboardActivity::class.java)) finish() } pDialog.dismiss() }) } private fun observeCityList() { viewModel.cityList.observe(this, androidx.lifecycle.Observer { list -> listname.clear() listCity.clear() listCity.addAll(list) for (cityList in list) { if (cityList.name != null) { listname.add(cityList.name) } } if (listname.isNotEmpty()) { listname[0] = "City" binding.spCity.adapter = Utils.arrayAdpter(applicationContext, listname) } pDialog.dismiss() }) } private fun getCityList() { if (Utils.isDataConnected(this)) { viewModel.getCityList() pDialog.show() } else { Utils.showSNACK_BAR_NO_INTERNET(this, localClassName) } } private fun signUpUser() { if (Utils.isDataConnected(this)) { viewModel.doSignUp( edit_emailId.text.toString(), edit_username.text.toString(), edit_mobile.text.toString(), "BIDDER", sp_city.selectedItem.toString(), lat, lon, edit_password.text.toString(), "", "", city_id ) pDialog.show() } else { Utils.showSNACK_BAR_NO_INTERNET(this, localClassName) } } }<file_sep>package com.example.sphinxassignment.ui import android.content.Context import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.RecyclerView import com.example.sphinxassignment.R import com.example.sphinxassignment.databinding.RvItemBinding import com.example.sphinxassignment.network.responses.CityList import com.example.sphinxassignment.network.responses.LoginResponse class AdapterFood constructor( private val context: Context, private val layoutInflater: LayoutInflater = LayoutInflater.from(context), ) : RecyclerView.Adapter<AdapterFood.ViewHolder>() { private lateinit var list: List<LoginResponse> class ViewHolder(val rvItemBinding: RvItemBinding) : RecyclerView.ViewHolder(rvItemBinding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( DataBindingUtil.inflate( layoutInflater, R.layout.rv_item, parent, false ) ) } fun refresh(list: List<LoginResponse>) { this.list = list notifyDataSetChanged() } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val response = list[position].also { holder.rvItemBinding.response = it } } override fun getItemCount(): Int { return list.size } }<file_sep>package com.example.sphinxassignment.network.api.apiservice import com.example.sphinxassignment.network.responses.LoginResponse import retrofit2.Response import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST interface ApiService { @POST("login-user") suspend fun authenticate( @Body loginResponse: LoginResponse ): Response<LoginResponse> @POST("signup") suspend fun signUp( @Body loginResponse: LoginResponse ): Response<LoginResponse> @GET("city-list") suspend fun getCityList(): Response<LoginResponse> }<file_sep>package com.example.sphinxassignment.network.api.apihelperimpl import com.example.sphinxassignment.network.responses.LoginResponse import com.example.sphinxassignment.network.api.apihelper.ApiHelper import com.example.sphinxassignment.network.api.apiservice.ApiService import retrofit2.Response import retrofit2.http.Body import javax.inject.Inject class ApiHelperImpl @Inject constructor(private val apiService: ApiService) : ApiHelper { override suspend fun authenticate(@Body loginResponse: LoginResponse): Response<LoginResponse> = apiService.authenticate(loginResponse) override suspend fun signUp(@Body loginResponse: LoginResponse): Response<LoginResponse> = apiService.signUp(loginResponse) override suspend fun getCityList(): Response<LoginResponse> = apiService.getCityList() }<file_sep>package com.example.sphinxassignment.network.api.repository import com.example.sphinxassignment.network.responses.LoginResponse import com.example.sphinxassignment.network.api.apihelper.ApiHelper import retrofit2.http.Body import javax.inject.Inject class ApiRepository @Inject constructor(private val apiHelper: ApiHelper) { suspend fun authenticate(@Body loginResponse: LoginResponse) = apiHelper.authenticate(loginResponse) suspend fun signUp(@Body loginResponse: LoginResponse) = apiHelper.signUp(loginResponse) suspend fun getCityList() = apiHelper.getCityList() }<file_sep>package com.example.sphinxassignment.ui.auth import android.app.Dialog import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.activity.viewModels import androidx.databinding.DataBindingUtil import com.example.ridecellassignment.Validations import com.example.sphinxassignment.R import com.example.sphinxassignment.Utils import com.example.sphinxassignment.databinding.ActivityLoginBinding import com.example.sphinxassignment.ui.DashboardActivity import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.WithFragmentBindings import kotlinx.android.synthetic.main.activity_login.* import kotlinx.android.synthetic.main.activity_signup.* @AndroidEntryPoint class LoginActivity : AppCompatActivity() { lateinit var binding: ActivityLoginBinding val viewModel: LoginViewModel by viewModels() lateinit var pDialog: Dialog override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_login) binding.executePendingBindings() binding.viewModel = viewModel pDialog = Utils.generateProgressDialog(this)!! onSignIn() binding.textSignup.setOnClickListener { startActivity(Intent(this, SignUpActivity::class.java)) } binding.btnLogin.setOnClickListener { if (!Validations.emailValidation(edit_email)) return@setOnClickListener else if (!Validations.edtValidation(edit_pass, "Enter Password")) return@setOnClickListener else signInUser() } } private fun signInUser() { if (Utils.isDataConnected(this)) { viewModel.doSignIn(edit_email.text.toString(), edit_pass.text.toString()) pDialog.show() } else { Utils.showSNACK_BAR_NO_INTERNET(this, localClassName) } } private fun onSignIn() { viewModel.isSuccessful.observe(this, androidx.lifecycle.Observer { isSuccess -> if (isSuccess) { startActivity(Intent(this, DashboardActivity::class.java)) finish() } pDialog.dismiss() }) } }
f5b016e77d2326f703c96f5f69f6b0b4277244ed
[ "Kotlin", "Gradle" ]
12
Kotlin
ganii001/Sphinx-Assignment
4a768ae324c1919903d04cc97b8ae1a2f99e2dea
f2df52c5c115a798e911372b438713cf2e92ff00
refs/heads/master
<file_sep>package ru.newsagregator.App.controller; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/auth") public class AuthController { @GetMapping("/login") public String loginPage() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); boolean hasUserRole = authentication.getAuthorities().stream() .anyMatch(r -> r.getAuthority().equals("user:read")); if (hasUserRole) return "redirect:/meduza/news"; else return "login"; } @GetMapping("/logout") public String logoutPage() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication.getPrincipal().equals("anonymousUser")) return "redirect:/meduza/news"; else return "logout"; } } <file_sep>package ru.newsagregator.App.model; public enum Permission { USER_READ("user:read"), USER_WRITE("user:write"); private final String permission; Permission(String permission) { this.permission=permission; } public String getPermission() {return permission;} } <file_sep>package ru.newsagregator.App.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JSR310Module; import lombok.SneakyThrows; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.function.client.WebClient; import ru.newsagregator.App.mapper.ContentMapper; import ru.newsagregator.App.model.ContentList; import ru.newsagregator.App.model.MeduzaNews; import ru.newsagregator.App.model.NewsContent; import java.util.List; @RestController public class RestNewsApiController { // добавить value private String urlPartOne; private String urlPartTwo; private final ContentMapper contentMapper; public RestNewsApiController(ContentMapper contentMapper) { this.contentMapper = contentMapper; } @GetMapping(value = "/news", produces = MediaType.APPLICATION_JSON_VALUE) public ContentList news(@RequestParam(value = "page", required = false, defaultValue = "0") String page) { String url = createUrl(urlPartOne, urlPartTwo, page); String responseJson = getContentJsonFromMeduzaApi(url); MeduzaNews meduzaNews = stringToJsonMeduza(responseJson); List<NewsContent> content = contentMapper.toDTO(meduzaNews); return new ContentList(content); } private String createUrl(String urlPartOne, String urlPartTwo, String page) { return new StringBuilder() .append("https://meduza.io/api/v3/search?chrono=news&locale=ru&page=") .append(page) .append("&per_page=24").toString(); } private String getContentJsonFromMeduzaApi(String url) { return WebClient.create().get() .uri(url) .exchange() .block() .bodyToMono(String.class) .block(); } @SneakyThrows private MeduzaNews stringToJsonMeduza(String text) { ObjectMapper objectMapper = new ObjectMapper(); //new JodaModule() objectMapper.registerModule(new JSR310Module()); return objectMapper.readValue(text, MeduzaNews.class); } } <file_sep>package ru.newsagregator.App.mapper; import org.springframework.stereotype.Component; import ru.newsagregator.App.model.MeduzaNews; import ru.newsagregator.App.model.NewsContent; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Map; @Component public class ContentMapper implements ModelMapper<MeduzaNews, List<NewsContent>> { @Override public List<NewsContent> toDTO(MeduzaNews meduzaNews) { List<NewsContent> list = new ArrayList<>(); for (Map.Entry<String, Map<Object, Object>> entry : meduzaNews.getDocuments().entrySet()) { Map<Object, Object> map = entry.getValue(); NewsContent content = new NewsContent(); for (Map.Entry<Object, Object> obj: map.entrySet()) { switch ((String) obj.getKey()) { case "url": content.setUrl((String) obj.getValue()); break; case "title": content.setTitle((String) obj.getValue()); break; case "share_image_url": content.setShareImageUrl((String) obj.getValue()); break; case "pub_date": content.setPubDate(LocalDate.parse((String) obj.getValue())); break; } } list.add(content); } return list; } @Override public MeduzaNews toModel(List<NewsContent> newsContents) { return null; } }
6235d490d70e438ca95e8d5397c5bd447160e4cc
[ "Java" ]
4
Java
AnBlag/TrainingProject-Aggregator
24079d1921087a6efc30ead4dd9f1f185ef6fde8
cb2ba9b3759970131e1fec9f4051a5154a907e5e
refs/heads/master
<repo_name>darkarty/cards<file_sep>/cards.js function card(name, suit, value){ this.name = name; this.suit= suit; this.value = value; //value is ranked from 2 to 14, from 2 to A. (Suits don't determine rank in poker) } function deck(){ this.cards=[]; this.create = function(){ names = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']; //ordered in order of value suits = ['Diamonds','Clubs','Hearts','Spades']; // ordered in order of value var value=1; for (var i=0; i<names.length;i++){ //for each name.. for (var j =0; j<suits.length;j++){ //for each suit.. //push new card into deck if(names[i]=='J'){ value=11; } else if(names[i]=='Q'){ value=12; } else if(names[i]=='K'){ value=13; } else if(names[i]=='A'){ value=14; } else{ value=parseInt(names[i]); } this.cards.push(new card(names[i],suits[j],value)); } } }; this.shuffle = function(){ for (var k=0;k<100;k++){ //shuffle x times to shuffle var newOrder=[]; var numberOfCards = this.cards.length; for(var i=0;i<52;i++){ //find random number between 51 and 0 var randomNumber = Math.floor((Math.random() * (numberOfCards-1) + 0)); //place this.cards[randomNumber] into first of newOrder; newOrder.push(this.cards[randomNumber]); //remove this.cards[randomNumber] from this.cards this.cards.splice(randomNumber,1); numberOfCards--; } newOrder.reverse(); //reverse array as part of shuffling this.cards=newOrder; } } } function hand(){ this.cards=[] this.draw = function(deck){ this.cards.push(deck.cards.pop()); } } function isValueInArray(value,array){ //check if value is in array if(array.indexOf(value) > -1){ return true; } else{ return false; } } function findMaxInArray(array){ return Math.max.apply(null, array); } function isHandRoyalFlush(valueArray,suitArray,nameArray){ //check for royal flush var sortedValueArray=valueArray.slice(); sortedValueArray.sort(sortNumber); var sortedNameArray=nameArray.slice(); sortedNameArray.sort(); //will be 5 highest values for 10,J,Q,K,A, can be ANY SUIT(but same within a hand) if((isValueInArray(10,valueArray) && isValueInArray(11,valueArray) && isValueInArray(12,valueArray) && isValueInArray(13,valueArray) && isValueInArray(14,valueArray)) && (suitArray[0]==suitArray[1] && suitArray[0]==suitArray[2] && suitArray[0]==suitArray[3] && suitArray[0]==suitArray[4])){ return true; } else{ return false; } } function isHandStraightFlush(valueArray,suitArray,nameArray){ //check for straight flush var sortedValueArray=valueArray.slice(); sortedValueArray.sort(sortNumber); var sortedNameArray=nameArray.slice(); sortedNameArray.sort(); //sort by value, it will have to be +1 between each one, and need same suit if((sortedValueArray[0] == sortedValueArray[0] && sortedValueArray[1]==sortedValueArray[0]+1 && sortedValueArray[2]==sortedValueArray[0]+2 && sortedValueArray[3]==sortedValueArray[0]+3 && sortedValueArray[4]==sortedValueArray[0]+4) && (suitArray[0]==suitArray[1] && suitArray[1]==suitArray[2] && suitArray[2]==suitArray[3] && suitArray[3]==suitArray[4])){ return true; } //for straight flush, need to also check A-1-2-3-4-5 if(sortedNameArray[0]=="2" && sortedNameArray[1]=="3" && sortedNameArray[2]=="4" && sortedNameArray[3]=="5" && sortedNameArray[4]=="A"){ if(suitArray[0]==suitArray[1] && suitArray[1]==suitArray[2] && suitArray[2]==suitArray[3] && suitArray[3]==suitArray[4]){ //if suits are same, then straight flush, if not, straight return true; } } else{ return false; } } function isHandForOfAKind(valueArray,suitArray,nameArray){ //check for four of a kind var sortedValueArray=valueArray.slice(); sortedValueArray.sort(sortNumber); var sortedNameArray=nameArray.slice(); sortedNameArray.sort(); //can sort by name and check first 4, or last 4 are the same if((sortedNameArray[0]==sortedNameArray[1] && sortedNameArray[0]==sortedNameArray[2] && sortedNameArray[0]==sortedNameArray[3]) || (sortedNameArray[4]==sortedNameArray[3] && sortedNameArray[4]==sortedNameArray[2] && sortedNameArray[4]==sortedNameArray[1])){ return true; } else{ return false } } function isHandFullHouse(valueArray,suitArray,nameArray){ //check for full house var sortedValueArray=valueArray.slice(); sortedValueArray.sort(sortNumber); var sortedNameArray=nameArray.slice(); sortedNameArray.sort(); //sort, and check first three are same, and last 2 are same OR first two are same, and last three are same if((sortedNameArray[0]==sortedNameArray[1] && sortedNameArray[1]==sortedNameArray[2] && sortedNameArray[3]==sortedNameArray[4]) || (sortedNameArray[2]==sortedNameArray[3] && sortedNameArray[3]==sortedNameArray[4] && sortedNameArray[1]==sortedNameArray[0])){ return true; } else{ return false; } } function isHandFlush(valueArray,suitArray,nameArray){ //check for flush //check all suits are the same if(suitArray[0]==suitArray[1] && suitArray[0]==suitArray[2] && suitArray[0]==suitArray[3] && suitArray[0]==suitArray[4]){ return true; } else{ return false; } } function isHandStraight(valueArray,suitArray,nameArray){ //check for straight var sortedValueArray=valueArray.slice(); sortedValueArray.sort(sortNumber); var sortedNameArray=nameArray.slice(); sortedNameArray.sort(); //this checks 2,3,4,5,6 up to 6,7,8,9,10 if(parseInt(sortedNameArray[0])==parseInt(sortedNameArray[0]) && parseInt(sortedNameArray[0])==parseInt(sortedNameArray[0])+1 && parseInt(sortedNameArray[0])==parseInt(sortedNameArray[0])+2 && parseInt(sortedNameArray[0])==parseInt(sortedNameArray[0])+3 && parseInt(sortedNameArray[0])==parseInt(sortedNameArray[0])+4){ return true; } //a-1-2-3-4-5 if(sortedNameArray[0]=="2" && sortedNameArray[1]=="3" && sortedNameArray[2]=="4" && sortedNameArray[3]=="5" && sortedNameArray[4]=="A"){ if(suitArray[0]==suitArray[1] && suitArray[1]==suitArray[2] && suitArray[2]==suitArray[3] && suitArray[3]==suitArray[4]){ //if suits are same, then straight flush, if not, straight return false; } else{ return true; } } //we need edge cases for 7,8,9,10,J 8,9,10,J,Q 9,10,J,Q,K 10,J,Q,K,A if(sortedNameArray[0]=="7" && sortedNameArray[1]=="8" && sortedNameArray[2]=="9" && sortedNameArray[3]=="10" && sortedNameArray[4]=="J"){ return true; } if(sortedNameArray[0]=="8" && sortedNameArray[1]=="9" && sortedNameArray[2]=="10" && sortedNameArray[3]=="J" && sortedNameArray[4]=="Q"){ return true; } if(sortedNameArray[0]=="9" && sortedNameArray[1]=="10" && sortedNameArray[2]=="J" && sortedNameArray[3]=="K" && sortedNameArray[4]=="Q"){ return true; } if(sortedNameArray[0]=="10" && sortedNameArray[1]=="A" && sortedNameArray[2]=="J" && sortedNameArray[3]=="K" && sortedNameArray[4]=="Q"){ return true; } return false; } function isHandThreeOfAKind(valueArray,suitArray,nameArray){ //check for three of a kind var sortedValueArray=valueArray.slice(); sortedValueArray.sort(sortNumber); var sortedNameArray=nameArray.slice(); sortedNameArray.sort(); //check every 3 cards in succession for sorted name array if((sortedNameArray[0]==sortedNameArray[1] && sortedNameArray[1]==sortedNameArray[2]) || (sortedNameArray[1]==sortedNameArray[2] && sortedNameArray[2]==sortedNameArray[3]) || (sortedNameArray[2]==sortedNameArray[3] && sortedNameArray[3]==sortedNameArray[4])){ return true; } else{ return false; } } function isHandTwoPair(valueArray,suitArray,nameArray, handFourOfAKind, handThreeOfAKind){ //check for two pairs var sortedValueArray=valueArray.slice(); sortedValueArray.sort(sortNumber); var sortedNameArray=nameArray.slice(); sortedNameArray.sort(); var pairCounter=0; //check every pair, and add 1 to counter for pair if(sortedNameArray[0]==sortedNameArray[1]){ pairCounter+=1; } if(sortedNameArray[1]==sortedNameArray[2]){ pairCounter+=1; } if(sortedNameArray[2]==sortedNameArray[3]){ pairCounter+=1; } if(sortedNameArray[3]==sortedNameArray[4]){ pairCounter+=1; } if(pairCounter>=2 && !handFourOfAKind && !handThreeOfAKind){ //if it has matches and it is not four of a kind, then it is 2 pair return true; } else{ return false; } } function isHandPair(valueArray,suitArray,nameArray){ //check for single pair var sortedValueArray=valueArray.slice(); sortedValueArray.sort(sortNumber); var sortedNameArray=nameArray.slice(); sortedNameArray.sort(); var pairCounter=0; if(sortedNameArray[0]==sortedNameArray[1]){ pairCounter+=1; } if(sortedNameArray[1]==sortedNameArray[2]){ pairCounter+=1; } if(sortedNameArray[2]==sortedNameArray[3]){ pairCounter+=1; } if(sortedNameArray[3]==sortedNameArray[4]){ pairCounter+=1; } if(pairCounter==1){ return true; } else{ return false; } } function handHighestValue(hand){ //return highest value of a hand //set values for each var handRoyalFlush=false; //value 10 var handStraightFlush=false; //value 9 var handFourOfAKind=false; //value 8 var handFullHouse=false; //value 7 var handFlush=false; //value 5 var handStraight=false; //value 4 var handTwoPair=false; //value 3 var handThreeOfAKind=false; //value 3 var handPair=false; //value 2 var valueArray=[]; var suitArray=[]; var nameArray=[]; console.log(hand.cards); for(i=0;i<5;i++){ valueArray.push(hand.cards[i].value); suitArray.push(hand.cards[i].suit); nameArray.push(hand.cards[i].name); } handRoyalFlush=isHandRoyalFlush(valueArray, suitArray, nameArray); handStraightFlush=isHandStraightFlush(valueArray, suitArray, nameArray); handFourOfAKind=isHandForOfAKind(valueArray, suitArray, nameArray); handFullHouse=isHandFullHouse(valueArray, suitArray, nameArray); handFlush=isHandFlush(valueArray, suitArray, nameArray); handStraight=isHandStraight(valueArray, suitArray, nameArray); handThreeOfAKind=isHandThreeOfAKind(valueArray, suitArray, nameArray); handTwoPair=isHandTwoPair(valueArray, suitArray, nameArray, handFourOfAKind, handThreeOfAKind); handPair=isHandPair(valueArray, suitArray, nameArray); /* //print true/false for checks console.log("royal flush "+ handRoyalFlush); console.log("straight flush "+ handStraightFlush); console.log("four of a kind "+ handFourOfAKind); console.log("full house "+ handFullHouse); console.log("flush "+ handFlush); console.log("straight "+ handStraight); console.log("three of a kind "+ handThreeOfAKind); console.log("two pair "+ handTwoPair); console.log("pair "+ handPair); */ if(handRoyalFlush){ return 10; } else if(handStraightFlush){ return 9; } else if(handFourOfAKind){ return 8; } else if(handFullHouse){ return 7 } else if(handFlush){ return 6; } else if(handStraight){ return 5; } else if(handTwoPair){ return 4; } else if(handThreeOfAKind){ return 3; } else if(handPair){ return 2; } else{ //nothing return 1; } } function sortNumber(a,b){ return b-a; } function tieBreakerHighCard(sortedValueArrayForHand1, sortedValueArrayForHand2){ //compare max value between arrays, if they are equal compare next highest card //return 1 if hand1 wins, return -1 if hand2 wins, return 0 if tie for(i=0;i<sortedValueArrayForHand1.length;i++){ if(sortedValueArrayForHand1[i]>sortedValueArrayForHand2[i]){ return 1; } if(sortedValueArrayForHand1[i]<sortedValueArrayForHand2[i]){ return -1; } } return 0; } function tieBreakerPair(sortedValueArrayForHand1, sortedValueArrayForHand2){ //make a var for the pair value //make array for the non pair values, to check high card if the pair values are equal //make copy of sortedValueArrays so that we can splice them later var sortedValueArrayForHand1Copy=sortedValueArrayForHand1.slice(); var sortedValueArrayForHand2Copy=sortedValueArrayForHand2.slice(); var pairForHand1; var nonPairArrayForHand1=[]; var pairForHand2; var nonPairArrayForHand2=[]; for(i=0;i<sortedValueArrayForHand1.length - 1;i++){ if(sortedValueArrayForHand1[i]==sortedValueArrayForHand1[i+1]){ //this is a pair pairForHand1=sortedValueArrayForHand1[i]; //remove this pair from the copy sortedValueArrayForHand1Copy.splice(i,1); sortedValueArrayForHand1Copy.splice(i,1); } if(sortedValueArrayForHand2[i]==sortedValueArrayForHand2[i+1]){ //this is a pair pairForHand2=sortedValueArrayForHand2[i]; //remove this pair from the copy sortedValueArrayForHand2Copy.splice(i,1); sortedValueArrayForHand2Copy.splice(i,1); } } //see which value in pairArray is bigger, if equal, then we used sortedValueArrayForHandXCopy to find next high card if(pairForHand1>pairForHand2){ return 1; } if(pairForHand1<pairForHand2){ return -1; } if(pairForHand1==pairForHand2){ return tieBreakerHighCard(sortedValueArrayForHand1Copy, sortedValueArrayForHand2Copy); } } function tieBreakerThreeOfAKind(sortedValueArrayForHand1, sortedValueArrayForHand2){ var sortedValueArrayForHand1Copy=sortedValueArrayForHand1.slice(); var sortedValueArrayForHand2Copy=sortedValueArrayForHand2.slice(); var tripleForHand1; var nonPairArrayForHand1=[]; var tripleForHand2; var nonPairArrayForHand2=[]; for(i=0;i<sortedValueArrayForHand1.length - 1;i++){ if(sortedValueArrayForHand1[i]==sortedValueArrayForHand1[i+1] && sortedValueArrayForHand1[i]==sortedValueArrayForHand1[i+3]){ //this is a triple tripleForHand1=sortedValueArrayForHand1[i]; //remove this pair from the copy sortedValueArrayForHand1Copy.splice(i,1); sortedValueArrayForHand1Copy.splice(i,1); sortedValueArrayForHand1Copy.splice(i,1); } if(sortedValueArrayForHand2[i]==sortedValueArrayForHand2[i+1] && sortedValueArrayForHand1[i]==sortedValueArrayForHand1[i+3]){ //this is a triple tripleForHand2=sortedValueArrayForHand2[i]; //remove this pair from the copy sortedValueArrayForHand2Copy.splice(i,1); sortedValueArrayForHand2Copy.splice(i,1); sortedValueArrayForHand1Copy.splice(i,1); } } //see which value in tripleForHand is bigger, if equal, then we used sortedValueArrayForHandXCopy to find next high card if(tripleForHand1>tripleForHand2){ return 1; } if(tripleForHand1<tripleForHand2){ return -1; } if(tripleForHand1==tripleForHand2){ return tieBreakerHighCard(sortedValueArrayForHand1Copy, sortedValueArrayForHand2Copy); } } function tieBreakerTwoPair(sortedValueArrayForHand1, sortedValueArrayForHand2){ //make copy of sortedValueArrays so that we can splice them later var sortedValueArrayForHand1Copy=sortedValueArrayForHand1.slice(); var sortedValueArrayForHand2Copy=sortedValueArrayForHand2.slice(); var pairsForHand1=[0,0]; var nonPairArrayForHand1; var pairsForHand2=[0,0]; var nonPairArrayForHand2; for(i=0;i<sortedValueArrayForHand1.length - 1;i++){ if(sortedValueArrayForHand1[i]==sortedValueArrayForHand1[i+1]){ //this is a pair if(pairsForHand1[0]==0){ pairForHand1[0]=sortedValueArrayForHand1[i]; } else{ pairForHand1[1]=sortedValueArrayForHand1[i]; } //remove this pair from the copy sortedValueArrayForHand1Copy.splice(i,1); sortedValueArrayForHand1Copy.splice(i,1); } if(sortedValueArrayForHand2[i]==sortedValueArrayForHand2[i+1]){ //this is a pair if(pairsForHand2[0]==0){ pairForHand2[0]=sortedValueArrayForHand2[i]; } else{ pairForHand2[1]=sortedValueArrayForHand2[i]; } //remove this pair from the copy sortedValueArrayForHand2Copy.splice(i,1); sortedValueArrayForHand2Copy.splice(i,1); } } if((pairsForHand1[0]>pairsForHand2[0] && pairsForHand1[0]>pairsForHand2[1]) || (pairsForHand1[1]>pairsForHand2[0] && pairsForHand1[1]>pairsForHand2[1])){ return 1; } else if((pairsForHand2[0]>pairsForHand1[0] && pairsForHand2[0]>pairsForHand1[1]) || (pairsForHand2[1]>pairsForHand1[0] && pairsForHand2[1]>pairsForHand1[1])){ return -1; } else{ return tieBreakerHighCard(sortedValueArrayForHand1Copy, sortedValueArrayForHand2Copy); } function tieBreakerStraight(sortedValueArrayForHand1, sortedValueArrayForHand2){ var sortedValueArrayForHand1Copy=sortedValueArrayForHand1.slice(); var sortedValueArrayForHand2Copy=sortedValueArrayForHand2.slice(); return tieBreakerHighCard(sortedValueArrayForHand1Copy, sortedValueArrayForHand2Copy); } function tieBreakerFlush(sortedValueArrayForHand1, sortedValueArrayForHand2){ var sortedValueArrayForHand1Copy=sortedValueArrayForHand1.slice(); var sortedValueArrayForHand2Copy=sortedValueArrayForHand2.slice(); return tieBreakerHighCard(sortedValueArrayForHand1Copy, sortedValueArrayForHand2Copy); } function tieBreakerFullHouse(sortedValueArrayForHand1, sortedValueArrayForHand2){ return tieBreakerThreeOfAKind(sortedValueArrayForHand1, sortedValueArrayForHand2); } function tieBreakerFourOfAKind(sortedValueArrayForHand1, sortedValueArrayForHand2){ //compare first and last from sorted Array var fourHand1; var singleHand1; var fourHand2; var singleHand2 if(sortedValueArrayForHand1[0]==sortedValueArrayForHand1[1]){ fourHand1=sortedValueArrayForHand1[0]; singleHand1=sortedValueArrayForHand1[4]; } else{ fourHand1=sortedValueArrayForHand1[4]; singleHand1=sortedValueArrayForHand1[0]; } if(sortedValueArrayForHand2[0]==sortedValueArrayForHand2[1]){ fourHand2=sortedValueArrayForHand2[0]; singleHand2=sortedValueArrayForHand2[4]; } else{ fourHand2=sortedValueArrayForHand2[4]; singleHand2=sortedValueArrayForHand2[0]; } if(fourHand1>fourHand2){ return 1; } else if(fourHand2>fourHand1){ return -1; } else if(singleHand1>singleHand2){ return 1 } else if(singlehand2>singleHand1){ return -1; } else{ return 0; } } function tieBreakerStraightFlush(sortedValueArrayForHand1, sortedValueArrayForHand2){ if(sortedValueArrayForHand1[4]>sortedValueArrayForHand2[4]){ return 1; } else if(sortedValueArrayForHand1[4]<sortedValueArrayForHand2[4]){ return -1; } else{ return 0; } } } function printPokerHandName(handValue){ var output="" if(handValue==10){ output+="royal flush"; return output; } if(handValue==9){ output+="straight flush"; return output; } if(handValue==8){ output+="four of a kind"; return output; } if(handValue==7){ output+="full house"; return output; } if(handValue==6){ output+="flush"; return output; } if(handValue==5){ output+="straight"; return output; } if(handValue==4){ output+="two pair"; return output; } if(handValue==3){ output+="three of a kind"; return output; } if(handValue==2){ output+="pair"; return output; } if(handValue==1){ output+="high card"; return output; } } function tieBreaker(hand1, hand2, handValue){ //return 1 if hand1 wins, return -1 if hand2 wins, return 0 if tie console.log("tie breaker"); var valueArrayForHand1=[]; var suitArrayForHand1=[]; var nameArrayForHand1=[]; var valueArrayForHand2=[]; var suitArrayForHand2=[]; var nameArrayForHand2=[]; for(i=0;i<5;i++){ valueArrayForHand1.push(hand1.cards[i].value); suitArrayForHand1.push(hand1.cards[i].suit); nameArrayForHand1.push(hand1.cards[i].name); } for(i=0;i<5;i++){ valueArrayForHand2.push(hand2.cards[i].value); suitArrayForHand2.push(hand2.cards[i].suit); nameArrayForHand2.push(hand2.cards[i].name); } var sortedValueArrayForHand1=valueArrayForHand1.slice(); sortedValueArrayForHand1.sort(sortNumber); var sortedNameArrayForHand1=nameArrayForHand1.slice(); sortedNameArrayForHand1.sort(); var sortedValueArrayForHand2=valueArrayForHand2.slice(); sortedValueArrayForHand2.sort(sortNumber); var sortedNameArrayForHand2=nameArrayForHand2.slice(); sortedNameArrayForHand2.sort(); if(handValue==10){ // both royal flush console.log("both royal flush, tie") return 0; } if(handValue==9){ //for straight flush, highest top card wins (A can be used in A-2-3-4-5, but then 5 is the top card) return tieBreakerStraightFlush(sortedValueArrayForHand1, sortedValueArrayForHand2); } if(handValue==8){ //for four of a kind, highest name of the four cards wins, and then kicker return tieBreakerFourOfAKind(sortedValueArrayForHand1, sortedValueArrayForHand2); } if(handValue==7){ //for full house, highest name of the three cards wins, if equal, rank of pair decides return tieBreakerFullHouse(sortedValueArrayForHand1, sortedValueArrayForHand2); } if(handValue==6){ //flush, highest card wins, if equal, compare the next highest card.. and so on return tieBreakerFlush(sortedValueArrayForHand1, sortedValueArrayForHand2); } if(handValue==5){ //straight, compare highest card return tieBreakerStraight(sortedValueArrayForHand1, sortedValueArrayForHand2); } if(handValue==4){ //two pair, highest pair compare, lower pair, kicker compare return tieBreakerTwoaPair(sortedValueArrayForHand1, sortedValueArrayForHand2); } if(handValue==3){ //three of a kind, compare three, then highest of remainder 2, then lowest of reminader 2 return tieBreakerThreeOfAKind(sortedValueArrayForHand1, sortedValueArrayForHand2); } if(handValue==2){ //pair, compare pair, compare highest card, and so on.. //compare pair, if pair equal, remove pair and compare highest cards using function written already. return tieBreakerPair(sortedValueArrayForHand1, sortedValueArrayForHand2); } if(handValue==1){ //nothing, compare high card, if high card is equal, compare second highest card.. and so on. return tieBreakerHighCard(sortedValueArrayForHand1,sortedValueArrayForHand2); } } function compareHands(hand1, hand2){ //return bigger hand var hand1Value=handHighestValue(hand1); var hand2Value=handHighestValue(hand2); var pokerHandName=""; if(hand1Value==hand2Value){ console.log("tie, need tie breaker"); var tieBreakerValue=tieBreaker(hand1, hand2, hand1Value); if(tieBreakerValue==1){ pokerHandName+=printPokerHandName(hand1Value); console.log("hand1 wins with "+ pokerHandName); } if(tieBreakerValue==-1){ pokerHandName+=printPokerHandName(hand2Value); console.log("hand2 wins with "+ pokerHandName); } if(tieBreakerValue==0){ pokerHandName+=printPokerHandName(hand1Value); console.log("hands are tied"); } } if(hand1Value>hand2Value){ pokerHandName+=printPokerHandName(hand1Value); console.log("hand 1 wins with " + pokerHandName); } if(hand1Value<hand2Value){ pokerHandName+=printPokerHandName(hand2Value); console.log("hand 2 wins with " + pokerHandName); } } //create a new deck var newDeck = new deck; newDeck.create(); //print new deck //console.log("new deck"); //console.log(newDeck.cards); //shuffle new deck newDeck.shuffle(); //print shuffled deck //console.log("shuffled deck"); //console.log(newDeck.cards); //create a new hand var newHand1 = new hand; //draw 5 cards for hand1 for(i=0;i<5;i++){ newHand1.draw(newDeck); } var newHand2 = new hand; //draw 5 cards for hand2 for(i=0;i<5;i++){ newHand2.draw(newDeck); } //print cards in newHand1 //console.log("newHand1 cards"); //console.log(newHand1.cards); //print cards in newHand2 //console.log("newHand2 cards"); //console.log(newHand2.cards); compareHands(newHand1,newHand2); <file_sep>/README.md # cards using javascript to implement a deck of cards currently included: 1. card object 2. hand object 3. deck object 4. drawing of card from deck into hand 5. finding a poker hand in a hand of 5 cards 6. compare between two poker hands and declare winner/tie todo: 1. need to move functions into objects where appropriate, for example, finding the hand value could go into the hand object 2. need to implement tiebreakers for various poker hands 3. create an interface, such as website with this running as the backend
45f7b14a0f5f1fc06b17dce7c22c19008a718798
[ "JavaScript", "Markdown" ]
2
JavaScript
darkarty/cards
bf57c4cec95f281e8be5febc0e13bab95ba98d4e
528f361a60db52a10e85945e9b34b12dfb73807b
refs/heads/master
<file_sep>/* Developed by <NAME> */ package edu.groupchat.app; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import java.io.IOException; import java.net.*; import java.util.ArrayList; public class ChatRoomController { @FXML private VBox messageBox; @FXML private VBox userListVBox; @FXML private TextField enterTextField; @FXML private ScrollPane messageBoxScrollPane; @FXML private Button submitMessageButton; @FXML private TextArea enterTextArea; private String displayName; private String multicastIP; private int portNumber; private MulticastSocket socket; private InetAddress group; private ArrayList<String> userList = new ArrayList<>(); @FXML protected void handleOnActionEnterField(ActionEvent event) { if (enterTextField.getText().isEmpty()){ return; } Message message = new Message(displayName, enterTextField.getText()); Text localMessageText = new Text(message.getMessageSender() + ": " + message.getMessageData()); messageBox.getChildren().add(localMessageText); messageBoxScrollPane.vvalueProperty().bind(messageBox.heightProperty()); try { DatagramPacket messageObjDatagram = message.getDatagram(group, portNumber); socket.send(messageObjDatagram); } catch (IOException ex) { Alert alert = new Alert(Alert.AlertType.ERROR, "Socket error.", ButtonType.CLOSE); alert.showAndWait(); } enterTextField.clear(); } @FXML protected void handleSubmitMessageButton(ActionEvent event) { messageBox.getChildren().add(new Text(enterTextArea.getText())); } @FXML protected void handleOnExit() { sendDisconnectMessage(); Platform.exit(); System.exit(0); } protected void connect() { messageBox.getChildren().add(new Text("Connected as: " + displayName)); messageBox.getChildren().add(new Text("Joined group: " + multicastIP)); messageBox.getChildren().add(new Text("Socket port: " + Integer.toString(portNumber))); joinChat(getDisplayName(), getMulticastIP(), getPortNumber()); } @FXML private void joinChat(String displayName, String multicastHost, int portNumber) { /** * Joins the specified Multicast group and launches a thread to receive messages. * <p> * This method creates a multicast group using the InetAddress class and it's getByName * function, taking in the multicastHost String. Then a new MulticastSocket is created * with the portNumber int, and that socket joins the InetAddress group. * * @param displayName the name of the user connecting, currently not used * @param multicastHost a String that contains the IP address of the group you want to connect to * @param portNumber an int of the port for the multicastHost */ try { group = InetAddress.getByName(multicastHost); socket = new MulticastSocket(portNumber); socket.setTimeToLive(1); socket.joinGroup(group); Thread thread = new Thread(new ReadThread(socket, group, portNumber)); thread.start(); sendJoinMessage(); } catch (SocketException ex) { Alert alert = new Alert(Alert.AlertType.ERROR, "Socket error when attempting to connect to multicast group.", ButtonType.CLOSE); alert.showAndWait(); } catch (UnknownHostException ex) { Alert alert = new Alert(Alert.AlertType.ERROR, "Unexpected error in ChatRoomController, host is not a valid host.", ButtonType.CLOSE); alert.showAndWait(); } catch (IOException ex) { Alert alert = new Alert(Alert.AlertType.ERROR, "IOException when attempting to connect to multicast group.", ButtonType.CLOSE); alert.showAndWait(); } } protected void addToUserList(String user) { if (!userList.contains(user)) { userList.add(user); userListVBox.getChildren().add(new Text(user)); } } protected void removeFromUserList(String userString) { for (Node user : userListVBox.getChildren()) { Text tempUserText = (Text) user; if (tempUserText.getText().equals(userString)) { userListVBox.getChildren().remove(user); return; } } } protected void enterMessage(Message receivedMessage) { String displayMessage; Text displayMessageText; Font font = Font.font("SansSerif", FontWeight.BLACK, FontPosture.ITALIC, 12); switch (receivedMessage.getMessageType()) { case STANDARD: if (!receivedMessage.getMessageSender().equals(displayName)){ displayMessage = receivedMessage.getMessageSender() + ": " + receivedMessage.getMessageData(); displayMessageText = new Text(displayMessage); messageBox.getChildren().add(displayMessageText); } break; case JOIN: if (!receivedMessage.getMessageSender().equals(displayName)) { addToUserList(receivedMessage.getMessageSender()); sendJoinAckMessage(); displayMessage = receivedMessage.getMessageSender() + " has joined the chat!"; displayMessageText = new Text(displayMessage); displayMessageText.setFont(font); messageBox.getChildren().add(displayMessageText); } else{ displayMessage = "You have joined the chat!"; displayMessageText = new Text(displayMessage); displayMessageText.setFont(font); messageBox.getChildren().add(displayMessageText); } break; case JOIN_ACK: addToUserList(receivedMessage.getMessageSender()); break; case DISCONNECT: removeFromUserList(receivedMessage.getMessageSender()); displayMessage = receivedMessage.getMessageSender() + " " + "has left the chat!"; displayMessageText = new Text(displayMessage); displayMessageText.setFont(font); messageBox.getChildren().add(displayMessageText); break; } messageBoxScrollPane.vvalueProperty().bind(messageBox.heightProperty()); } private void sendJoinMessage(){ try{ Message joinMessage = new Message(MessageType.JOIN, displayName, "NONE"); DatagramPacket datagramPacket = joinMessage.getDatagram(group, portNumber); socket.send(datagramPacket); } catch (IOException ex){ Alert alert = new Alert(Alert.AlertType.ERROR, "Socket error when sending JOIN message.", ButtonType.CLOSE); alert.showAndWait(); } } private void sendJoinAckMessage() { try{ Message joinAckMessage = new Message(MessageType.JOIN_ACK, displayName, "NONE"); DatagramPacket datagramPacket = joinAckMessage.getDatagram(group, portNumber); socket.send(datagramPacket); } catch (IOException ex){ Alert alert = new Alert(Alert.AlertType.ERROR, "Socket error when sending JOIN_ACK message.", ButtonType.CLOSE); alert.showAndWait(); } } private void sendDisconnectMessage() { try { Message disconnectMessage = new Message(MessageType.DISCONNECT, displayName, "NONE"); DatagramPacket datagramPacket = disconnectMessage.getDatagram(group, portNumber); socket.send(datagramPacket); } catch (IOException ex) { Alert alert = new Alert(Alert.AlertType.ERROR, "Socket error when sending JOIN_ACK message.", ButtonType.CLOSE); alert.showAndWait(); } } protected String getDisplayName() { return displayName; } protected String getMulticastIP() { return multicastIP; } protected int getPortNumber() { return portNumber; } protected void setDisplayName(String displayName) { this.displayName = displayName; } protected void setMulticastIP(String multicastIP) { this.multicastIP = multicastIP; } protected void setPortNumber(int portNumber) { this.portNumber = portNumber; } } <file_sep>/* Developed by <NAME> */ package edu.groupchat.app; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class GroupChat extends Application { //declare the chat room stage and expose it's controller so that the other controller can call it static ChatRoomController chatRoomController; private static Stage primaryStage; @Override public void start(Stage loginStage) throws Exception{ //declare and load both stages, show the login screen, set the application close handler Parent root = FXMLLoader.load(getClass().getResource("login.fxml")); loginStage.setTitle("Group Chat Login"); loginStage.setScene(new Scene(root)); loginStage.show(); FXMLLoader loader = new FXMLLoader(getClass().getResource("interface.fxml")); Parent room = loader.load(); chatRoomController = (ChatRoomController) loader.getController(); primaryStage = new Stage(); primaryStage.setTitle("Group Chat"); primaryStage.setScene(new Scene(room)); primaryStage.setOnCloseRequest(event -> chatRoomController.handleOnExit()); } private static void setPrimaryStage(Stage stage) { primaryStage = stage; } protected static Stage getPrimaryStage() { return primaryStage; } protected static ChatRoomController getChatRoomController() { return chatRoomController; } public static void main(String[] args) { launch(args); } } <file_sep>/* Developed by <NAME> */ package edu.groupchat.app; import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.InetAddress; public class Message { private String messageSender; private String messageData; private MessageType messageType; protected Message(MessageType messageType, String messageSender, String messageData) { this.messageData = messageData; this.messageType = messageType; this.messageSender = messageSender; } protected Message(String messageSender, String messageData) { this.messageType = MessageType.STANDARD; this.messageData = messageData; this.messageSender = messageSender; } protected Message(byte[] buffer, DatagramPacket datagramPacket) { /* * Create a Message object from a byte array and datagram, this is used by the ReadThread when messages * are received. */ try { String rawMessage = new String(buffer, 0, datagramPacket.getLength(), "UTF-8"); String[] messageArray = rawMessage.split(";"); this.messageType = MessageType.valueOf(messageArray[0]); this.messageSender = messageArray[1]; this.messageData = messageArray[2]; } catch (UnsupportedEncodingException ex) { System.out.println("Encoding error in receiving and building messasge."); } } public DatagramPacket getDatagram(InetAddress group, int portNumber) { String message = getMessageType() + ";" + getMessageSender() + ";" + getMessageData(); byte[] buffer = message.getBytes(); DatagramPacket datagram = new DatagramPacket(buffer, buffer.length, group, portNumber); return datagram; } public String getMessageSender() { return messageSender; } public String getMessageData() { return messageData; } public MessageType getMessageType() { return messageType; } @Override public String toString() { String message = messageType.toString() + ';' + messageSender + ';' + messageData; return message; } }
42e08caa31d78bd73ea601aed5dcefac41dd83bc
[ "Java" ]
3
Java
jurquha/java-groupchat
3eed33e9ea0fc6ce3cd9898ca793e30664cbb9ec
66c2315b0fedcd652654ee89decceddbcc43e4d1
refs/heads/master
<file_sep>/** * Created by USER on 27/07/2017. */ // TODO: Agregar mas marcas y categorias. var brands = { values:["Nike", "Adidas", "Puma", "Guess", "Lacoste", "Victoria's Secret", "Zara", "Microsoft" ,"Stradivarius", "Asus", "HP", "BMW", "<NAME>"], message: 'Please type select brand' }; var categories = { values:["Clothes", "Accesories", "Cars", "Motorcycles", "Shoes", "Make up", "Technology", "Watches"], message: 'Please type select category' }; var mongoose = require('mongoose'), Schema = mongoose.Schema; var reviewSchema = new Schema({ product: String, youtubeName: String, youtubeImage: String, youtubeDate: String, youtubeLink: String, category: {type:String, enum: categories}, brand: {type:String, enum: brands}, owner_username: String, verifiedUser: Boolean, goodRate: Number, badRate: Number },{collection:'Review'}); module.exports = mongoose.model('Review', reviewSchema); <file_sep>/** * Created by USER on 28/07/2017. */ // https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id=AcUauzCn7RE&key=<KEY> var mongoose = require('mongoose'), Review = mongoose.model('Review'), User = mongoose.model('User'), https = require('https'); module.exports = { createReview: function (req, res) { User.findOne({username: req.user.username}, function (err, user) { if (user) { var str = ''; var options = { host: 'www.googleapis.com', port: '443', path: '/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id=' + req.body.youtubeLink.split('=')[1] + '&key=<KEY>' }; callback = function (response) { response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { var resp = JSON.parse(str); var review = new Review({ product: req.body.product, youtubeName: resp.items[0].snippet.title, youtubeDate: resp.items[0].snippet.publishedAt, youtubeImage: resp.items[0].snippet.thumbnails.medium.url, youtubeLink: req.body.youtubeLink, category: req.body.category, verifiedUser: req.user.verifiedUser, brand: req.body.brand, owner_username: req.user.username, goodRate: resp.items[0].statistics.likeCount, badRate: resp.items[0].statistics.dislikeCount }); review.save(function (err) { if (err) { return res.status(500).send(err.message); } // send OK return res.status(200).send(review); }) console.log(resp.items[0]) }) } var requ = https.request(options, callback).on("error", function (e) { }) requ.end() } else { return res.status(500).send(err.message); } }) }, deleteReview: function (req, res) { Review.findByIdAndRemove(req.body._id, function (err) { if (!err) { res.status(200).send(); } else { res.status(500).send(err); } }); }, getAllReviews: function (req, res) { Review.find({verifiedUser: true}, function (err, reviews) { if (!err) { res.status(200).send(reviews); } else { res.status(500).send(err); } }); }, searchReviews: function (req, res) { Review.find({$or: [{product: new RegExp(req.body.searchTerm, "i")}, {brand: new RegExp(req.body.searchTerm, "i")}, {youtubeName: new RegExp(req.body.searchTerm, "i")}, {category: new RegExp(req.body.searchTerm, "i")}]}, function (err, reviews) { if (!err) { return res.status(200).send(reviews); } else { return res.status(500).send(err); } }) }, searchReviewsByCategory: function (req, res) { Review.find({category: new RegExp(req.body.searchTerm, "i")}, function (err, reviews) { if (!err) { return res.status(200).send(reviews); } else { return res.status(500).send(err); } }) }, getMyReviews: function (req, res) { Review.find({owner_username: req.body.username}, function (err, reviews) { if (!err) { res.status(200).send(reviews); } else { res.status(500).send(err); } }); }, updateReview: function (req, res) { Review.findByIdAndUpdate(req.body._id, { "product": req.body.product, "category": req.body.category, "brand": req.body.brand }, function (err) { if (err) { res.send(err).status(500); } else { res.send("actualizada exitosamente").status(200); } }) } };<file_sep>var mongoose = require('mongoose'), Schema = mongoose.Schema; var promoSchema = new Schema({ product: String, promoCode: String, category: String, brand: String, details: String, expireDate: Date, link: String, imageLink: String },{collection:'Promo'}); module.exports = mongoose.model('Promo', promoSchema); <file_sep>var express = require('express'), router = express.Router(), https = require("https"), users = require('../controllers/user'), reviews = require('../controllers/reviews'), promo = require('../controllers/promo'), passport = require('passport'), passportConfig = require ('../../config/passport'), google = require('googleapis'), OAuth2 = google.auth.OAuth2; module.exports = function(app) { app.use('/', router); }; router.post('/searchUser', users.searchUser); router.get('/login',passport.authenticate('google',{ scope: ['profile','email','https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtube.force-ssl', 'https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/youtubepartner'],accessType: 'offline'})); router.get('/login/google/callback', passport.authenticate('google', { successRedirect: 'http://localhost/test1/',failureRedirect: 'http://localhost/test1/'})); router.get('/logout',passportConfig.estaAutenticado, users.logout); router.get('/userInfo', passportConfig.estaAutenticado, function (req,res) { res.json({username: req.user.username, _id: req.user._id, verifiedUser: req.user.verifiedUser}); }); //TODO: Cambiar las URIs router.post('/movie',passportConfig.estaAutenticado, reviews.createReview); router.post('/deleteMovie',passportConfig.estaAutenticado, reviews.deleteReview); router.get('/movie', reviews.getAllReviews); router.post('/searchMovie', reviews.searchReviews); router.post('/movieGenre', reviews.searchReviewsByCategory); router.post('/myContent',passportConfig.estaAutenticado, reviews.getMyReviews); router.post('/update',passportConfig.estaAutenticado, reviews.updateReview); router.get('/createPromo',promo.getView); router.post('/createPromo', promo.createPromo); router.post('/searchPromo', promo.searchPromo); router.post('/searchPromoByCategory', promo.searchPromoByCategory); router.get('/promos', promo.getAllPromos); <file_sep>var mongoose = require('mongoose'), Promo = mongoose.model('Promo'); module.exports = { createPromo: function (req, res) { console.log(req.body) var promo = new Promo({ product: req.body.product, promoCode: req.body.code, category: req.body.category, brand: req.body.brand, details: req.body.details, expireDate: req.body.date, link: req.body.link, imageLink: req.body.image }); promo.save(function (err) { if (err) { return res.status(500).send(err.message); } // send OK return res.status(200).send(promo); }) }, getView: function (req,res) { return res.status(200).render('promo') }, searchPromo: function (req, res) { Promo.find({$or: [{product: new RegExp(req.body.searchTerm, "i")}, {brand: new RegExp(req.body.searchTerm, "i")},{category: new RegExp(req.body.searchTerm, "i")}]}, function (err, promo) { if (!err) { return res.status(200).send(promo); } else { return res.status(500).send(err); } }) }, searchPromoByCategory: function (req, res) { Promo.find({category: new RegExp(req.body.searchTerm, "i")}, function (err, promo) { if (!err) { return res.status(200).send(promo); } else { return res.status(500).send(err); } }) }, deleteExpirePromos: function () { var cursor = Promo.find({expireDate:{$lt: new Date()}}).cursor(); cursor.on('data',function (promo) { Promo.findByIdAndRemove(promo._id,function (err) {}) }) }, getAllPromos: function (req, res) { Promo.find({}, function (err, promos) { if (!err) { res.status(200).send(promos); } else { res.status(500).send(err); } }); } }; <file_sep>/** * Created by USER on 02/08/2017. */ var passport = require ('passport'), GoogleStrategy = require('passport-google-oauth20').Strategy, Usuario = require ('../app/models/user'), google = require('googleapis'), OAuth2 = google.auth.OAuth2; passport.serializeUser(function(usuario,done){ console.log(usuario) done(null,usuario._id); }) passport.deserializeUser(function (id,done) { Usuario.findById(id, function (err,user) { done(err,user); }) }) passport.use(new GoogleStrategy({ clientID: "894365078349-cgcg4c2f5hvlcpisroo8c3tn5dt3aogb.apps.googleusercontent.com", clientSecret: <KEY>", callbackURL: 'http://localhost:3000/login/google/callback' }, function(accessToken, refreshToken, profile, cb) { process.nextTick(function() { var oauth2Client = new OAuth2( "894365078349-cgcg4c2f5hvlcpisroo8c3tn5dt3aogb.apps.googleusercontent.com", <KEY>", 'http://localhost:3000/login/google/callback' ); oauth2Client.credentials = { access_token: accessToken, refresh_token: refreshToken }; var da; google.youtube({ version: 'v3', auth: oauth2Client }).subscriptions.list({ part: 'subscriberSnippet', mySubscribers: true, headers: {} }, function(err, data, response) { if (err) { } if (data) { console.log(data); Usuario.findOne({ 'google.id': profile.id }, function(err, res) { if (err) return cb(err); if (res) { console.log("user exists"); return cb(null, res); } else { console.log("insert user"); Usuario.findOne({'google.id': profile.id}, function(err, user){ console.log(user,"google") if(err) return cb(err); if(user) return cb(null, user); else { var verified = false; if(data.pageInfo.totalResults >= 1000){ verified=true; } var newUser = new Usuario(); newUser.username = profile.emails[0].value; newUser.google.id = profile.id; newUser.google.token = accessToken; newUser.google.name = profile.displayName; newUser.google.email = profile.emails[0].value; newUser.verifiedUser = verified newUser.save(function(err){ if(err) throw err; return cb(null, newUser); }) } }); } }) } if (response) { console.log('Status code: ' + response.statusCode); } }); }); } )); exports.estaAutenticado = function (req,res,next) { if(req.isAuthenticated()){ return next(); }else{ res.status(401).send('Tienes que hacer log in para acceder a este recurso'); } }
fd206fb82b26281e097edc8a415cdfcd9213e38c
[ "JavaScript" ]
6
JavaScript
dperezg1/ReviewsServer
4502ef601e622c5306331b157e4337bdd4ed8d64
8a7e23049d3eea1eaf8c37929fcd0f4b2394ed87
refs/heads/master
<file_sep># principles AP Computer Science Principles project for the test <file_sep>public class Pixel { public byte r, g, b; public Pixel(int r, int g, int b) { this.r = (byte)(r * 0x0FF); this.g = (byte)(g & 0x0FF); this.b = (byte)(b & 0x0FF); } public Pixel(int rgb) { this.r = getBytesFromInt(rgb)[0]; this.g = getBytesFromInt(rgb)[1]; this.b = getBytesFromInt(rgb)[2]; } public static int getIntFromByte(byte r, byte g, byte b) { // n gets bitwise AND'd with 0x0ff to limit the value to be a maximum of 255 (0x0ff), // basically to get the unsigned byte // then each gets shifted a certain amount so each byte will fit in a Java 4-byte integer // the bitwise OR basically concatenates all 3 separate bytes into one /* r << 16: 00000000 11111111 00000000 00000000 g << 8: 00000000 00000000 11111111 00000000 b << 0: 00000000 00000000 00000000 11111111 bitwise OR | \/ 00000000 11111111 11111111 11111111 */ return ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff); } public static byte[] getBytesFromInt(int rgb) { // int rgb has 3 separate bytes embedded in order in it's 4-byte size // to extract each, we shift the bits by the size of the other 2 bytes // sort of like String.substring() return new byte[]{ (byte) ((rgb>>16) & 0x0ff), (byte) ((rgb>>8) & 0x0ff), (byte) (rgb & 0x0ff) }; } } <file_sep>import javax.imageio.ImageIO; //For outputting the final image import java.awt.Color; import java.awt.image.BufferedImage; import java.nio.ByteBuffer; import magick.*; public class ImageProcessor { //This is basically a port of: // https://github.com/au5ton/codered-steganography/blob/master/stego.js //TODO Extract RGBA values from pixel int //implemented in Pixel.java public static void embedData(MagickImage img, byte[] mySecret) throws MagickException { //Max size of image is 2147483639 bytes (2.1 GB) (Integer.MAX_VALUE - 8) PixelPacket[] pixelArray = reformatToPixelArray(img); if(pixelArray.length < mySecret.length + 4) { System.out.println("Not enough space available in image for the data you requested."); System.exit(1); } //if(img.) //necessary for decoding: describes the size of the data at the front of the file byte[] header = ByteBuffer.allocate(4).putInt(mySecret.length).array(); // mySecret.length -> byte[] int n = 0; for(int i = 0; i < header.length+mySecret.length; i++) { if(i < 4) { pixelArray[i] = encodeByteInPixel(pixelArray[i], header[i]); } else { pixelArray[i] = encodeByteInPixel(pixelArray[i], mySecret[n]); n++; } } int j = 0; for(int x = 0; x < img.getXResolution(); x++) { for(int y = 0; y < img.getYResolution(); y++) { img.getOnePixel(x,y).setRed(pixelArray[j].getRed()); img.getOnePixel(x,y).setGreen(pixelArray[j].getGreen()); img.getOnePixel(x,y).setBlue(pixelArray[j].getBlue()); img.getOnePixel(x,y).setOpacity(pixelArray[j].getOpacity()); j++; } } } public static PixelPacket[] reformatToPixelArray(MagickImage img) throws MagickException { PixelPacket[] pix = new PixelPacket[((int)img.getXResolution())*((int)img.getYResolution())]; int i = 0; for(int x = 0; x < (int)img.getXResolution(); x++) { for(int y = 0; y < (int)img.getYResolution(); y++) { pix[i] = img.getOnePixel(x,y); i++; } } return pix; } public static PixelPacket encodeByteInPixel(PixelPacket pixel, byte b) throws MagickException { int bit; for(int i = 0; i < 8; i++) { // get value of bit if ((b & (1 << 7-i)) == 0) { bit = 1; } else { bit = 0; } // encode bit in appropriate position in appropriate channel if (i == 0 || i == 1) { pixel = encodeBitInChannel(pixel, 'r', bit, i); } else if (i == 2 || i == 3) { pixel = encodeBitInChannel(pixel, 'g', bit, i % 2); } else if (i == 4 || i == 5) { pixel = encodeBitInChannel(pixel, 'b', bit, i % 2); } else { // position-1 to do LSBs 2 and 1 instead of 1 and 0 pixel = encodeBitInChannel(pixel, 'a', bit, (i % 2)-1); } } return pixel; } public static PixelPacket encodeBitInChannel(PixelPacket pixel, char channel, int bit, int position) throws MagickException { if (bit == 1) { // set bit to 1 if(channel == 'r') { pixel.setRed(pixel.getRed() | (1 << 1-position)); } else if(channel == 'g') { pixel.setGreen(pixel.getGreen() | (1 << 1-position)); } else if(channel == 'b') { pixel.setBlue(pixel.getBlue() | (1 << 1-position)); } else if(channel == 'a') { pixel.setOpacity(pixel.getOpacity() | (1 << 1-position)); } } else { // set bit to 0 //pixel[channel] &= ~(1 << 1-position); if(channel == 'r') { pixel.setRed(pixel.getRed() & ~(1 << 1-position)); } else if(channel == 'g') { pixel.setGreen(pixel.getGreen() & ~(1 << 1-position)); } else if(channel == 'b') { pixel.setBlue(pixel.getBlue() & ~(1 << 1-position)); } else if(channel == 'a') { pixel.setOpacity(pixel.getOpacity() & ~(1 << 1-position)); } } return pixel; } //TODO ✅ Get pixel matrix from imagebuffer //TODO ✅ Reformat pixel matrix to buffer data //TODO ✅ Encode data (steganography) into pixel matrix //TODO ✅ Encode byte in pixel //TODO ✅ Encode bit in channel //TODO Decode data from pixel matrix //TODO Decode byte from pixel //TODO Decode bit from channel }
8a8dfea81d4887a6c5c6bdf7af350e3650c013c1
[ "Markdown", "Java" ]
3
Markdown
au5ton/principles
68a4d7bd9d5ef4b5aba1e1c59dad335e241d59ea
299e9d3f44eec1c4fb61348cbee6748709275d1a
refs/heads/master
<repo_name>racket99/hello-world<file_sep>/pages/views.py from django.shortcuts import render from django.conf import settings # Create your views here. # pages/views.py from django.http import HttpResponse def homePageView(request): print(settings.BASE_DIR) return HttpResponse('Hello, World! My precious <br><img src="https://upload.wikimedia.org/wikipedia/en/e/e0/Gollum.PNG">')
b8587bfd6f80c0aa722ee2ee604371b100f3963c
[ "Python" ]
1
Python
racket99/hello-world
2384a83074706607595e45040df020ba5cb33ffd
d1e7b69af289491c6dd788393ab02b31fbf12b0a
refs/heads/master
<repo_name>steve0079/dog-api<file_sep>/src/components/Display.js import React, { useState, useEffect } from 'react'; import axios from 'axios'; const Display = () => { const [image, setImage] = useState({}) const fetchData = async () => { const response = await axios.get('https://dog.ceo/api/breeds/image/random') setImage(response.data.message) console.log(response) } useEffect(() => { fetchData() }, []); return ( <div className='display'> <div className="layer"> <div className="image"> <img src={image} alt="random dog" /> </div> <div className="button"> <input type="text" placeholder="search for" /> <button className="btn btn-primary" onClick={() => fetchData()}>Another dog, please!</button> </div> </div> </div> ); } export default Display;<file_sep>/src/components/Carousel.js import React, { useState, useEffect } from 'react'; import axios from 'axios'; const Carousel = () => { const [image, setImage] = useState([]) useEffect(() => { const fetchData = async () => { const response = await axios.get('https://dog.ceo/api/breeds/image/random/5') setImage(response.data.message); }; fetchData(); }, []); return ( <div className="bkgrnd"> <div className="row"> {image.map((image) => <ul key={image} className="sized-image" > <img src={image} alt="" /> </ul> )} </div> </div> ) }; export default Carousel;
6682358544738df542066b743e715e6c445d74d8
[ "JavaScript" ]
2
JavaScript
steve0079/dog-api
e636f48cd28dc2f9cc1e7d255674ddbc744c70ec
71c78bffc052a48538098c8fdbf25c3ee351a872
refs/heads/master
<repo_name>Bever001/silkroad-laravel<file_sep>/app/Http/Controllers/Frontend/RankingController.php <?php namespace App\Http\Controllers\Frontend; use App\HideRanking; use App\HideRankingGuild; use App\Http\Controllers\Controller; use App\Model\SRO\Shard\Char; use App\Model\SRO\Shard\CharTrijob; use App\Model\SRO\Shard\Guild; use Illuminate\Http\Request; class RankingController extends Controller { /** * @param Request $request * @param null|string $mode * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View * @throws \Throwable */ public function index(Request $request, $mode = null) { $hideRanking = HideRanking::all()->pluck('charname'); $hideRankingGuild = HideRankingGuild::all()->pluck('guild_id'); $search = $request->get('search'); $type = $request->get('type'); if ($mode !== null) { $data = $this->mode( $mode, $hideRanking, $hideRankingGuild ); } else if ($search && $type) { $data = $this->searching( $type, $search, $hideRanking, $hideRankingGuild ); } else { $chars = Char::orderBy('ItemPoints', 'DESC') ->whereNotIn('CharName16', $hideRanking) ->whereNotIn('GuildID', $hideRankingGuild) ->with('getGuildUser') ->paginate(150); $data = view('theme::frontend.ranking.results.chars', [ 'data' => $chars, ])->render(); } return view('theme::frontend.ranking.index', [ 'data' => $data, 'mode' => $mode ]); } /** * @param $type * @param $search * @param $hideRanking * @param $hideRankingGuild * @return array|void */ private function searching($type, $search, $hideRanking, $hideRankingGuild) { if ($type === __('ranking.search.search-charname')) { $chars = Char::orderBy('ItemPoints', 'DESC') ->where('CharName16', 'like', '%' . $search . '%') ->whereNotIn('CharName16', $hideRanking) ->whereNotIn('GuildID', $hideRankingGuild) ->with('getGuildUser') ->paginate(150); return view('theme::frontend.ranking.results.chars', [ 'data' => $chars, ])->render(); } if ($type === __('ranking.search.search-guild')) { $guilds = Guild::orderBy('ItemPoints', 'DESC') ->where('Name', 'like', '%' . $search . '%') ->whereNotIn('ID', $hideRankingGuild) ->paginate(150); return view('theme::frontend.ranking.results.guilds', [ 'data' => $guilds, ])->render(); } if ($type === __('ranking.search.search-job')) { $jobs = CharTrijob::whereHas('getCharacter', static function ($q) use ($search, $hideRanking, $hideRankingGuild) { $q->where('NickName16', 'like', '%' . $search . '%'); $q->whereNotIn('CharName16', $hideRanking); $q->whereNotIn('GuildID', $hideRankingGuild); }) ->with('getCharacter') ->whereIn('JobType', [1, 2, 3]) ->orderBy('Level', 'DESC') ->orderBy('Exp', 'DESC') ->paginate(150); return view('theme::frontend.ranking.results.jobs', [ 'data' => $jobs ])->render(); } } /** * @param $mode * @param $hideRanking * @param $hideRankingGuild * @return void|array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View|string */ private function mode($mode, $hideRanking, $hideRankingGuild) { if ($mode === __('ranking.search.search-charname')) { $chars = Char::orderBy('ItemPoints', 'DESC') ->whereNotIn('CharName16', $hideRanking) ->whereNotIn('GuildID', $hideRankingGuild) ->with('getGuildUser') ->paginate(150); return view('theme::frontend.ranking.results.chars', [ 'data' => $chars, ])->render(); } if ($mode === __('ranking.search.search-guild')) { $guilds = Guild::orderBy('ItemPoints', 'DESC') ->whereNotIn('ID', $hideRankingGuild) ->paginate(150); return view('theme::frontend.ranking.results.guilds', [ 'data' => $guilds, ])->render(); } if ($mode === __('ranking.search.search-trader')) { $jobs = CharTrijob::whereHas('getCharacter', static function ($q) use ($hideRanking, $hideRankingGuild) { $q->whereNotIn('CharName16', $hideRanking); $q->whereNotIn('GuildID', $hideRankingGuild); }) ->with('getCharacter') ->where('JobType', 1) ->orderBy('Level', 'DESC') ->orderBy('Exp', 'DESC') ->paginate(150); return view('theme::frontend.ranking.results.jobs', [ 'data' => $jobs ]); } if ($mode === __('ranking.search.search-hunter')) { $jobs = CharTrijob::whereHas('getCharacter', static function ($q) use ($hideRanking, $hideRankingGuild) { $q->whereNotIn('CharName16', $hideRanking); $q->whereNotIn('GuildID', $hideRankingGuild); }) ->with('getCharacter') ->where('JobType', 3) ->orderBy('Level', 'DESC') ->orderBy('Exp', 'DESC') ->paginate(150); return view('theme::frontend.ranking.results.jobs', [ 'data' => $jobs ]); } if ($mode === __('ranking.search.search-thief')) { $jobs = CharTrijob::whereHas('getCharacter', static function ($q) use ($hideRanking, $hideRankingGuild) { $q->whereNotIn('CharName16', $hideRanking); $q->whereNotIn('GuildID', $hideRankingGuild); }) ->with('getCharacter') ->where('JobType', 2) ->orderBy('Level', 'DESC') ->orderBy('Exp', 'DESC') ->paginate(150); return view('theme::frontend.ranking.results.jobs', [ 'data' => $jobs ]); } if ($mode === __('ranking.search.search-job')) { $jobs = CharTrijob::whereHas('getCharacter', static function ($q) use ($hideRanking, $hideRankingGuild) { $q->whereNotIn('CharName16', $hideRanking); $q->whereNotIn('GuildID', $hideRankingGuild); }) ->with('getCharacter') ->whereIn('JobType', [1, 2, 3]) ->orderBy('Level', 'DESC') ->orderBy('Exp', 'DESC') ->paginate(150); return view('theme::frontend.ranking.results.jobs', [ 'data' => $jobs ]); } } }
55ef70ccf244fe35eda556cc7e0bbf7a3f407f20
[ "PHP" ]
1
PHP
Bever001/silkroad-laravel
93cf96bfcf7a451ab43a7827b381e2d3c42de680
3a68619d9e751351bc5ef002e21ab7252009a8d4
refs/heads/master
<repo_name>doubleInc/the-last-dance<file_sep>/src/pages/dashboard.js import React from "react"; import { Router, Link } from "@reach/router"; import { css, ClassNames } from "@emotion/core"; // Materialui components import Typography from "@material-ui/core/Typography"; import Button from "@material-ui/core/Button"; import Container from "@material-ui/core/Container"; import TextField from "@material-ui/core/TextField"; import InputLabel from "@material-ui/core/InputLabel"; import MenuItem from "@material-ui/core/MenuItem"; import Select from "@material-ui/core/Select"; import FormControl from "@material-ui/core/FormControl"; // Ajax calls import { getCoordinates } from "../js/Ajaxcalls"; // firebase import { database, auth } from "../../firebase"; // const textFieldStyle = css` margin-left: 1em; margin-right: 1em; width: 25ch; `; const Dashboard = ({ user }) => { // state const [open, setOpen] = React.useState(false); const [state, setState] = React.useState(""); const [name, setName] = React.useState(""); const [address, setAddress] = React.useState(""); const [suburb, setSuburb] = React.useState(""); const [feedback, setFeedback] = React.useState({ success: "", error: "" }); const handleClose = () => { setOpen(false); }; const handleOpen = () => { setOpen(true); }; const captureValues = async (e) => { e.preventDefault(); if (name.length > 1 && address.length > 1 && suburb.length > 1) { const coords = await getCoordinates(`${address}, ${suburb}, ${state}`); const location = { name, address: `${address}, ${suburb}, ${state}`, coords, type: "technology", }; // add or update "new greeting" key in db await database.ref("/").push(location); // Resets { setState(""); setName(""); setAddress(""); setSuburb(""); setFeedback({ ...feedback, success: "Added location successfully!", error: "", }); } } else { //respond with error setFeedback({ ...feedback, success: "", error: "An error occurred, please check all fields.", }); } }; return ( <div> <Container css={css` margin-top: 2em; margin-bottom: 2em; height: 520px; `} fixed > <Typography variant="body1" gutterBottom css={css` color: #1b5e20; margin-left: 0.5em; width: 80%; background-color: #eee; `} > <h2 css={css` font-weight: 300; `} > Enter a New Location </h2> Please fill out all fields below. Postcode is not required as location look up will be done with suburb name and state provided. </Typography> <form onSubmit={captureValues}> <TextField id="name" label="" style={{ margin: 8 }} placeholder="Organisation name" helperText="Organisation name" autoComplete="off" fullWidth margin="normal" value={name} onChange={(e) => setName(e.target.value)} InputLabelProps={{ shrink: true, }} css={css` width: 80%; `} /> <br /> <TextField id="street" label="" style={{ margin: 8 }} placeholder="Street Address" helperText="Street address" fullWidth autoComplete="off" value={address} onChange={(e) => setAddress(e.target.value)} margin="normal" InputLabelProps={{ shrink: true, }} css={css` width: 80%; `} /> <br /> <TextField label="Suburb" defaultValue="" css={textFieldStyle} helperText="Suburb name" value={suburb} onChange={(e) => setSuburb(e.target.value)} style={{ marginLeft: "0.5em", marginBottom: "1em", }} /> <InputLabel id="state-open-select-label" css={css` margin-top: 0.5em; margin-left: 0.5em; `} > State </InputLabel> <Select labelId="state-open-select-label" id="state-open-select" open={open} onClose={handleClose} onOpen={handleOpen} value={state} onChange={(e) => setState(e.target.value)} css={css` width: 5em; margin-top: 0.5em; margin-left: 0.5em; `} > <MenuItem value={"NSW"}>NSW</MenuItem> <MenuItem value={"ACT"}>ACT</MenuItem> <MenuItem value={"VIC"}>VIC</MenuItem> <MenuItem value={"QLD"}>QLD</MenuItem> <MenuItem value={"SA"}>SA</MenuItem> <MenuItem value={"NT"}>NT</MenuItem> <MenuItem value={"WA"}>WA</MenuItem> </Select> <Button variant="contained" type="submit" style={{ backgroundColor: "blue", marginLeft: "2em", marginBottom: "0.5em", color: "white", }} > Submit </Button> </form> <div> {feedback.success.length > 1 ? ( <p css={css` color: green; `} > {feedback.success} </p> ) : null} {feedback.error.length > 1 ? ( <p css={css` color: red; `} > {feedback.error} </p> ) : null} </div> </Container> </div> ); }; export default Dashboard; <file_sep>/src/js/Ajaxcalls.js import axios from "axios"; const OPENCAGEAPI = process.env.OPENCAGE; const URL_ADDRESS_SEARCH = `https://api.opencagedata.com/geocode/v1/json?q=`; // ${location}&key=${OPENCAGEAPI} // Get stores export async function getCoordinates(address) { try { const response = await axios.get( URL_ADDRESS_SEARCH + `"${address + " australia"}"&key=${OPENCAGEAPI}` ); return response.data.results[0].geometry; } catch (err) { return err; } } <file_sep>/src/js/components/navbar.styles.js import { css } from "@emotion/core"; import styled from "@emotion/styled"; import { makeStyles, ThemeProvider, createMuiTheme, } from "@material-ui/core/styles"; // from material color library import green from "@material-ui/core/colors/green"; // project colors const colors = { primary: green, white: "#fff", }; // emotionjs css export const linkText = css` text-decoration: none; color: ${colors.white}; `; export const linkButton = (color = colors.white) => css` background-color: ${color}; `; export const logo = css` text-decoration: none; font-size: 1em; color: ${colors.white}; `; export const avatarStyle = css` margin-right: 0.25em; border: 1px solid ${colors.white}; `; export const logoText = css` flex-grow: 1; color: white; `; // extend materialui themes and styles(classes) export const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, title: { flexGrow: 1, color: colors.white, }, loginButton: { backgroundColor: "red", }, })); export const theme = createMuiTheme({ palette: { primary: colors.primary, }, }); <file_sep>/readme.md # The last dance(A final project) Visit live implementation at - https://zen-borg-dc2d79.netlify.app/ React and MaterialUI frontend, using leafmap to show all locations electrical equipment can be dropped off for recycling. Clone repo and follow steps below; 1.`npm i` 2. `npm run start`<file_sep>/scrapper/index.js /* A script that scrapes a site for addresses of recycling locations Australiawide. https://recyclingnearyou.com.au/ewastescheme/ */ const puppeteer = require("puppeteer"); const cheerio = require("cheerio"); const { getCoordinates } = require("./Ajaxcalls"); const fs = require("fs"); const firebase = require("./firebase"); //iife to run script (async () => { try { const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPage(); //enter page to scrape await page.goto("https://recyclingnearyou.com.au/ewastescheme", { waitUntil: "networkidle0", }); await page.waitForSelector(".content", { timeout: 1000 }); const body = await page.content(); await browser.close(); const root = cheerio.load(body); // use cheerio to get addresses and business names const locationsArr = root(".business-search-location-inner .col-md-9") .contents() .text() .trim() .replace(/ /g, "") .replace(/\n/g, ".") .replace(/\.\.\.\./g, ".") .split("."); //create pairs from each bussiness name and address ["officeworks", "1 ham road, Altona North"] const locationPairs = locationsArr.reduce(function ( result, value, index, array ) { if (index % 2 === 0) result.push(array.slice(index, index + 2)); return result; }, []); // temp array to process objects to be added to db //const tempArr = locationPairs.slice(299, 468); // create object from each entry to be added to db const locationObj = await Promise.all( // use either temp array above or all entries(locationPairs) locationPairs.map(async ([name, address]) => ({ name, address, type: "technology", coords: await getCoordinates(address), })) ); // add each to firebase via push locationObj.forEach(async (val) => { await firebase.database().ref("/").push(val); }); // uncomment below to write to file, need to use JSON.stringify // await fs.writeFile("./dataWithCoords.js", locationObj, (err) => { // if (err) throw err; // console.log("Data written to file"); // }); // Stream implementation to write to file // var file = fs.createWriteStream("array.txt"); // file.on("error", function (err) { // /* error handling */ // console.log(err); // }); // locationObj.forEach(function (v) { // file.write(JSON.stringify(v) + ","); // }); // file.end(); console.log("Done. Safe to exit process."); } catch (error) { console.log(error); } })(); <file_sep>/src/pages/home.js import React from "react"; import { css, ClassNames } from "@emotion/core"; // Materialui components import Typography from "@material-ui/core/Typography"; import Container from "@material-ui/core/Container"; import TextField from "@material-ui/core/TextField"; // import InputAdornment from "@material-ui/core/InputAdornment"; import PinDropIcon from "@material-ui/icons/PinDrop"; // Components import Writeup from "../js/components/Writeup"; import Mapoverlay from "../js/components/Maplay"; // Ajax calls import { getCoordinates } from "../js/Ajaxcalls"; // firebase import { database, auth } from "../../firebase"; //ramda import { props, compose, map } from "ramda"; // Class component class Home extends React.Component { // Test coordinates: auburn = [-33.8545702, 151.0255673] state = { searchLocation: [-33.8548157, 151.2164539], searchValue: "", locations: [], }; // Search for location entered on main page locationLookup = async (event) => { event.preventDefault(); const res = await getCoordinates(this.state.searchValue); const { lat, lng } = res; this.setState({ searchLocation: [lat, lng], searchValue: "", }); }; handleChange = (event) => { this.setState({ searchValue: event.target.value, }); }; // component update before loading dom componentDidMount = async () => { // listen for any change("/" => root) in the db and return a snapshot const starCountRef = await database.ref("/").on("value", (snapshot) => { // everytime a change occurs in the db, it will be logged to console const locations = []; snapshot.forEach((child) => { locations.push(child.val()); }); this.setState({ locations: locations, }); }); }; render() { return ( <React.Fragment> <Container css={css` margin-top: 2em; margin-bottom: 2em; `} fixed > <Typography component="div" style={{ backgroundColor: "#cfe8fc", height: "830px" }} > <Writeup> <form noValidate autoComplete="off" css={css` margin-top: 10px; text-align: center; `} onSubmit={this.locationLookup} > <TextField id="" label="Enter your suburb and state" css={css` width: 300px; `} name="mapsearch" value={this.state.searchValue} onChange={this.handleChange} InputProps={{ startAdornment: ( <InputAdornment position="start"> <PinDropIcon /> </InputAdornment> ), }} /> </form> </Writeup> <Mapoverlay center={this.state.searchLocation} locations={this.state.locations} /> </Typography> </Container> </React.Fragment> ); } } export default Home; <file_sep>/src/js/components/Maplay.js import React from "react"; import { css, ClassNames } from "@emotion/core"; //leaflet import { Map, TileLayer, Marker, Popup } from "react-leaflet"; import L from "leaflet"; // leaflet css file import "leaflet/dist/leaflet.css"; // hack so that leaflet's images work after going through webpack import marker from "leaflet/dist/images/marker-icon.png"; import marker2x from "leaflet/dist/images/marker-icon-2x.png"; import markerShadow from "leaflet/dist/images/marker-shadow.png"; delete L.Icon.Default.prototype._getIconUrl; L.Icon.Default.mergeOptions({ iconRetinaUrl: marker2x, iconUrl: marker, shadowUrl: markerShadow, }); const Mapmarker = ({ name, coords, address }) => { return ( <Marker position={[coords.lat, coords.lng]}> <Popup> {name}, <br /> {address}. </Popup> </Marker> ); }; class Mapoverlay extends React.Component { state = { lat: 51.505, lng: -0.09, zoom: 13, }; render() { //console.log(this.props.center); const locations = this.props.locations; return ( <React.Fragment> <Map center={this.props.center} zoom={this.state.zoom}> <TileLayer attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> {locations.map((location) => location.coords.lng !== undefined ? ( <Mapmarker {...location} /> ) : null )} </Map> </React.Fragment> ); } } export default Mapoverlay; <file_sep>/src/js/components/navbar.stylesCSS.js /* Unused styles file - ignore */ import { css } from "@emotion/core"; import styled from "@emotion/styled"; export const header = css` -webkit-tap-highlight-color: transparent; font-size: 1rem; line-height: 1.5; color: white; text-align: left; box-sizing: border-box; padding: 0.5rem 1rem; display: flex; align-items: center; flex-flow: row nowrap; justify-content: flex-start; top: 0; position: fixed; right: 0; left: 0; z-index: 1030; text-transform: uppercase !important; background-color: green !important; font-weight: 700; font-family: Montserrat; padding-top: 1.5rem; padding-bottom: 1.5rem; transition: padding-top 0.3s, padding-bottom 0.3s; `; export const nav = css` -webkit-tap-highlight-color: transparent; font-size: 1rem; line-height: 1.5; color: #212529; text-align: left; text-transform: uppercase !important; font-weight: 700; font-family: Montserrat; box-sizing: border-box; flex-grow: 1; align-items: center; display: flex !important; flex-basis: auto; `; export const ul = () => css` -webkit-tap-highlight-color: transparent; font-size: 1rem; line-height: 1.5; color: #212529; text-align: left; text-transform: uppercase !important; font-weight: 700; font-family: Montserrat; box-sizing: border-box; flex-wrap: wrap; display: flex; padding-left: 0; margin-bottom: 0; list-style: none; margin-left: auto !important; flex-direction: row; letter-spacing: 0.0625rem; margin-top: 0; `; export const listItem = () => css` -webkit-tap-highlight-color: transparent; font-size: 1rem; line-height: 1.5; color: #212529; text-transform: uppercase !important; font-weight: 700; font-family: Montserrat; list-style: none; letter-spacing: 0.0625rem; box-sizing: border-box; margin-right: 0.25rem !important; margin-left: 0.25rem !important; `; // const Navbar = () => ( // <header css={header}> // <img src="" /> // <nav css={nav}> // <ul css={ul}> // <li css={listItem}> // <Link className="link" to="/"> // Home // </Link> // </li> // <li css={listItem}> // <a href="#">User</a> // </li> // <li css={listItem}> // {/* <a href="#">Contact</a> */ // <Link className="link" to="dashboard"> // Dashboard // </Link> // </li> // </ul> // </nav> // </header> // ); <file_sep>/src/pages/index.js import React from "react"; import ReactDOM from "react-dom"; import { Router, Link } from "@reach/router"; // App components import Navbar from "../js/components/Navbar"; import Home from "./home"; import Dashboard from "./dashboard"; import Footer from "../js/components/Footer"; //// for development only import { hot } from "react-hot-loader"; // css file import "../css/main.css"; // import global reset - normalize.css import CssBaseline from "@material-ui/core/CssBaseline"; const Main = ({ children }) => ( <div> <CssBaseline /> <Navbar usrImage="https://www.nicepng.com/png/full/198-1987193_any-transparent-studio-ghibli-photos-and-or-gifs.png"> <Navbar.LoggedIn /> <Navbar.LoggedOut /> </Navbar> <Router> <Home path="/" /> <Dashboard path="dashboard" /> </Router> <Footer /> </div> ); //export default Main; export default Main; <file_sep>/src/js/components/Userdash.js import React from "react"; import { css, ClassNames } from "@emotion/core"; import { Link, navigate } from "@reach/router"; import { auth, googleAuthProvider } from "../../../firebase"; import green from "@material-ui/core/colors/green"; // materialui components import { Avatar, Button } from "@material-ui/core"; // Styles with emotionjs const colors = { white: "#fff", }; export const avatarStyle = css` margin-right: 0.25em; border: 1px solid ${colors.white}; `; const linkText = css` text-decoration: none; color: ${colors.white}; `; // Materialui style classes const classes = { loginDash: { backgroundColor: green[900], border: "1px solid white", color: colors.white, marginLeft: "1em", }, }; const Userdash = (props) => { return ( <React.Fragment> <Avatar css={avatarStyle} alt="User avatar" src={props.usrimg} /> <Button style={classes.loginDash}> <Link css={linkText} to="dashboard"> Dashboard </Link> </Button> <Button style={classes.loginDash} onClick={() => { auth.signOut(); navigate("/"); }} > Log Out </Button> </React.Fragment> ); }; export default Userdash;
5fca688a469c00d5d22dfba79093a4f1d3a22669
[ "JavaScript", "Markdown" ]
10
JavaScript
doubleInc/the-last-dance
9c7f9bb4101f99f0d9555d5ab9c1571cd6a91305
b3dd276f971805cb68d44f152ba8f4956e0295ad
refs/heads/master
<file_sep>class SportsProp { constructor(obj) { this.id = obj.id; this.title = obj.title; this.prop_date = obj.date; this.week_id = obj.contest_board_id; this.away_team = obj.away_team; this.away_team_won = obj.away_team_won; this.home_team = obj.home_team; this.home_team_won = obj.home_team_won; this.start_time = obj.start_time; this.prop_locked = obj.locked; this.prop_scored = obj.scored; } renderHtml() { let propElement = document.createElement('div'); propElement.classList.add('sports-prop', 'locked-false'); propElement.innerHTML = `<div class="prop-title"> <p>${this.title}</p> </div> <div class="competitors"> <div class="away_team"> <p><strong>${this.away_team}</strong></p> </div> <div class="home_team"> <p><strong>${this.home_team}</strong></p> </div> </div> <div class="slidercontainer" id="slider-container-${this.id}"> </div> <div class="lock-time"> Lock Time: ${this.start_time} </div>`; document.getElementById('picks').appendChild(propElement); } } export default SportsProp;<file_sep>import SportsProp from '../src/SportsProp.js'; import Slider from '../src/Slider.js'; import { addSliderListeners } from '../src/listeners/sliderListeners.js'; class SportsPropsAdapter { constructor() { this.baseUrl = "http://localhost:3000/api/v1/current"; this.sportsProps = []; } async getCurrentProps() { await fetch(this.baseUrl) .then(response => response.json()) .then(data => { for (let obj of data) { let prop = new SportsProp(obj); this.sportsProps.push(prop) let slider = new Slider(obj); prop.renderHtml(); slider.render(); } addSliderListeners(); }) } } export default SportsPropsAdapter;<file_sep>import fetchErrorHandler from './errorHandler.js'; import { closeModal } from './listeners/modalListeners.js' const fetchUser = e => { let formData = { email: e.target[0].value, username: e.target[1].value }; let configObj = { method: "POST", headers: { "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify(formData) }; fetch("http://localhost:3000/api/v1/users", configObj) .then(response => response.json()) .then(data => { if (!data.message) { closeModal(); console.log("Successfully logged in!"); console.log(data); fetchUserPicks(data) } else { fetchErrorHandler(data) } }) } const fetchUserPicks = async (data) => { let user_id = data.user.id; console.log(user_id); await fetch(`http://localhost:3000/api/v1/user_picks?user_id=${user_id}`) .then(response => response.json()) .then(json => console.log(json)); }; const createUserPicks = async () => { await fetch("http://localhost:3000/api/v1/user_picks", { method: "POST", headers: { "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify({ user_id: 100, contest_prop_id: 1, side: "away", confidence: 17 }) }) .then(response => response.json()) .then(json => console.log(json)); }; const changeUserPicks = async (e) => { let prop_id = e.target.dataset.id let value = e.target.value let winningSide, sideConfidence; if (value > 0) { side = 'home' sideConfidence = Math.abs(value) } else { side = 'away' sideConfidence = Math.abs(value) } let formData = { contest_prop_id: prop_id, user_id: user, side: winningSide, confidence: sideConfidence } console.log(formData) // await fetch('http://localhost:3000/api/vi/user_picks', { // method: 'PATCH', // { // "Content-Type": "application/json", // "Accept": "application/json" // }, // body: JSON.stringify({ // }) // }) }; export { fetchUser, fetchUserPicks, createUserPicks, changeUserPicks };<file_sep>import SportsPropsAdapter from '../adapters/SportsPropsAdapter.js'; class SportsPropBuilder { constructor() { this.adapter = new SportsPropsAdapter(); this.props = this.fetchAndBindPropstoState(); } fetchAndBindPropstoState() { this.adapter.getCurrentProps(); } } export default SportsPropBuilder;<file_sep>function displayPoints() { let sliders = [...document.getElementsByClassName('slider')]; let numOfPicksMade; let numOfProps = sliders.length; let filtered = sliders.filter(slider => { return (parseFloat(slider.value) != 0); }); numOfPicksMade = filtered.length; document.querySelector('#daily-total-picks-made').innerHTML = numOfPicksMade; document.querySelector('#helper').style.display = "inline"; document.querySelector('#daily-total-picks').innerHTML = numOfProps; } export { displayPoints };<file_sep>class Slider { constructor(prop) { this.id = prop.id; } render() { let slider = `<input type="range" min="-25" max="25" value="0" step="0.2" class="slider" data-id="${this.id}"id="slider-${this.id}"> <div class="slider-values"> <div data-id="${this.id}"id="prop-${this.id}-away-values"><strong>0 pts</strong></div> <div data-id="${this.id}"id="prop-${this.id}-home-values"><strong>0 pts</strong></div> </div>`; document.getElementById(`slider-container-${this.id}`).innerHTML = slider; } } export default Slider;<file_sep>import { displayPoints } from '../mathFuncs.js' import { changeUserPicks } from '../fetchRequests.js' function addSliderListeners() { let sliders = document.getElementsByClassName("slider"); for (let slider of sliders) { slider.addEventListener("input", e => { if (e.target.value > 0) { document.getElementById( `prop-${e.target.dataset.id}-home-values` ).innerHTML = (e.target.value * 10) / 10; document.getElementById( `prop-${e.target.dataset.id}-away-values` ).innerHTML = Math.round((e.target.value * 30) / 10) * -1; } else { document.getElementById( `prop-${e.target.dataset.id}-away-values` ).innerHTML = (e.target.value * -10) / 10; document.getElementById( `prop-${e.target.dataset.id}-home-values` ).innerHTML = Math.round((e.target.value * 30) / 10); } }) slider.addEventListener("mouseup", e => { displayPoints(); changeUserPicks(); }); }; } export { addSliderListeners };<file_sep>import App from './App.js'; import addRadioListeners from './listeners/radioButtonListeners.js' const app = new App(); window.load = addRadioListeners();<file_sep>function fetchErrorHandler(data) { let parent = document.createElement("ul"); let li = ""; data.message.errors.forEach(error => { document.getElementById("account-errors").innerHTML = ""; li += `<li>${error}</li>`; parent.innerHTML = li; return document.getElementById("account-errors").append(parent); }); } export default fetchErrorHandler;<file_sep>function closeModal() { let modal = document.getElementById("signin-account-modal"); modal.style.display = "none"; let signOutBtn = document.getElementById('signout-button') signOutBtn.classList.add('signed-in') let signInBtn = document.getElementById('open-signin-account-modal') signInBtn.classList.add('signed-in') } export { closeModal };<file_sep>import SportsPropBuilder from './SportsPropBuilder.js'; import * as eventHandler from './eventHandlers.js' import * as fetchRequests from './fetchRequests.js' class App { constructor() { this.state = { sportsProps: [], user_id: '', date: new Date(), }; this.propBuilder = new SportsPropBuilder(); this.state.sportsProps = this.propBuilder.adapter.sportsProps; this.addEventListeners(); } addEventListeners() { document .getElementById("open-signin-account-modal") .addEventListener("click", () => { let modal = document.getElementById("signin-account-modal"); modal.style.display = "block"; }); //Click 'X' inside modal document .getElementById("signin-modal-close-btn") .addEventListener("click", () => { let modal = document.getElementById("signin-account-modal"); modal.style.display = "none"; }); //Click submit in Modal document .getElementById('signin-account-form') .addEventListener("submit", e => { e.preventDefault(); fetchRequests.fetchUser(e); //alert("You are signed in!") }); //Click outside of Modal window.addEventListener("click", e => { let signinModal = document.getElementById("signin-account-modal"); if (signinModal === e.target) { e.target.style.display = "none"; } }); let signOutBtn = document.getElementById('signout-button'); let signInBtn = document.getElementById('open-signin-account-modal'); signOutBtn.addEventListener('click', e => { e.preventDefault(); eventHandler.onSignOutClick(this); if (this.state.user_id) { signOutBtn.style.display = "block"; signInBtn.style.display = "none"; } else { signOutBtn.style.display = "none"; signInBtn.style.display = "inline"; } }); } } export default App;<file_sep>import * as eventHandlers from '../eventHandlers.js'; function addListenerToSignOutBtn(app) { let signOutBtn = document.getElementById('signout-button'); let signInBtn = document.getElementById('open-signin-account-modal'); signOutBtn.addEventListener('click', e => { e.preventDefault(); eventHandlers.onSignOutClick(app); if (app.state.user_id) { signOutBtn.style.display = "block"; signInBtn.style.display = "none"; } else { signOutBtn.style.display = "none"; signInBtn.style.display = "inline"; } }); } export { addListenerToSignOutBtn, };
81137744f2dfb05fbe34b1b5f3c762298597bff4
[ "JavaScript" ]
12
JavaScript
veloblank/binary-butterfly-frontend
0d5bb023d87397e5b8b90d2f1dd88e2c4e560d10
dc0994363cbffebdd27ca228ca12939a7a95a586
refs/heads/master
<repo_name>yoshiyuki-km-ny/beanstalk-to-slack<file_sep>/BeanstalkToSlack/Function.cs using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; using Amazon.ElasticBeanstalk; using Amazon.ElasticBeanstalk.Model; using Amazon.Lambda.Core; using Newtonsoft.Json; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace BeanstalkToSlack { public class Function { public async Task FunctionHandler(EventData input, ILambdaContext context) { await SendToSlack("#random", input.Records[0].Sns.Message); } private static async Task SendToSlack(string channel, MessageData data) { var beanstalkClient = new AmazonElasticBeanstalkClient(); var response = await beanstalkClient.DescribeEnvironmentsAsync(new DescribeEnvironmentsRequest { ApplicationName = data.Application, EnvironmentNames = new List<string> { data.Environment } }); var httpClient = new HttpClient(); var payload = new { channel = channel, username = "Elastic Beanstalk", attachments = new[] { new { color = data.Status.ToString().ToLower(), text = data.Message, fields = new object[] { new { title = "Version Label", value = response.Environments[0].VersionLabel }, new { title = "Application", value = $"<https://ap-northeast-1.console.aws.amazon.com/elasticbeanstalk/home?region=ap-northeast-1#/application/overview?applicationName={data.Application}|{data.Application}>", @short = true }, new { title = "Environment", value = $"<https://ap-northeast-1.console.aws.amazon.com/elasticbeanstalk/home?region=ap-northeast-1#/environment/dashboard?applicationName={data.Application}&environmentId={response.Environments[0].EnvironmentId}|{data.Environment}>", @short = true }, new { title = "Environment URL", value = data.EnvironmentUrl }, new { title = "Timestamp", value = data.Timestamp } } } } }; var jsonString = JsonConvert.SerializeObject(payload); await httpClient.PostAsync("https://hooks.slack.com/services/XXXXX", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("payload", jsonString) })); } } public enum StatusType { Info, Good, Warning, Danger } public static class MessageDataExtension { public static StatusType GetStatus(string message) { if (DangerMessages.Any(message.Contains)) { return StatusType.Danger; } if (WarningMessages.Any(message.Contains)) { return StatusType.Warning; } if (InfoMessage.Any(message.Contains)) { return StatusType.Info; } return StatusType.Good; } private static readonly string[] DangerMessages = { " but with errors", " to RED", " to Degraded", " to Severe", "During an aborted deployment", "Failed to deploy", "Failed to deploy", "has a dependent object", "is not authorized to perform", "Pending to Degraded", "Stack deletion failed", "Unsuccessful command execution", "You do not have permission", "Your quota allows for 0 more running instance" }; private static readonly string[] WarningMessages = { " to YELLOW", " to Warning", " aborted operation", "Degraded to Info", "Deleting SNS topic", "is currently running under desired capacity", "Ok to Info", "Ok to Warning", "Pending Initialization", "Rollback of environment" }; private static readonly string[] InfoMessage = { "Adding instance", "Removed instance" }; } public class MessageData { public StatusType Status => MessageDataExtension.GetStatus(Message); public DateTime Timestamp { get; set; } public string Message { get; set; } public string Environment { get; set; } public string Application { get; set; } public string EnvironmentUrl { get; set; } } public class EventData { public Record[] Records { get; set; } } public class Record { public Sns Sns { get; set; } } public class Sns { public string Subject { get; set; } [JsonConverter(typeof(MessageDataConverter))] public MessageData Message { get; set; } public DateTime Timestamp { get; set; } } public class MessageDataConverter : JsonConverter { private static readonly Regex _regex = new Regex(@"Timestamp:\s(?<timestamp>.*?)\n.*?Message:\s(?<message>.*?)\n.*?Environment:\s(?<environment>.*?)\n.*?Application:\s(?<application>.*?)\n.*?Environment URL:\s(?<environmentUrl>.*?)\n.*?", RegexOptions.Singleline); public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var value = (string)reader.Value; var match = _regex.Match(value); if (!match.Success) { return null; } return new MessageData { Timestamp = DateTime.ParseExact(match.Groups["timestamp"].Value, "ddd MMM dd HH':'mm':'ss UTC yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal), Message = match.Groups["message"].Value, Environment = match.Groups["environment"].Value, Application = match.Groups["application"].Value, EnvironmentUrl = match.Groups["environmentUrl"].Value }; } public override bool CanConvert(Type objectType) { return objectType == typeof(string); } } }
7c6fd49371005a844db43ecef96afc95700e3015
[ "C#" ]
1
C#
yoshiyuki-km-ny/beanstalk-to-slack
096dee8ae8fb20ee83e1488aa2da63353e84659c
c88c6ade7eaeb8385b53ff2094f8bfb2a24bab8c
refs/heads/master
<file_sep> /* 穴掘り方による迷路配列生成 * 通路=0; 壁=1 * * Cf.https://algoful.com/Archive/Algorithm/MazeDig */ function createMaze(width, height){ // 配列の定義と初期化(全て壁で埋める) var x, y; maze = new Array(width); for(y = 0; y < height; y++) { maze[y] = new Array(height); for(x = 0; x < width; x++) { maze[y][x] = "wall"; } } // 迷路の外周を通路とする for(x=0; x<width;x++){ maze[0][x] = "path"; // 上端 maze[height-1][x] = "path"; // 下端 } for(y=0; y<height;y++){ maze[y][0] = "path"; // 右 maze[y][width-1] = "path"; // 左 } // 穴掘り開始座標(x,y共に奇数となる任意の座標)を指定 var start_x = 1; var start_y = 1; // 穴掘り dig(start_y, start_x); // 外周を壁に戻す // 迷路の外周を通路とする for(x=0; x<width;x++){ maze[0][x] = "wall"; // 上端 maze[height-1][x] = "wall"; // 下端 } for(y=0; y<height;y++){ maze[y][0] = "wall"; // 右 maze[y][width-1] = "wall"; // 左 } } function dig(y, x){ // 掘り進められる場合は,掘り進める while(true){ // 掘り進めることができる方向のリストを作成 var direction_list = new Array(); if(maze[y-1][x]=="wall" && maze[y-2][x]=="wall"){ direction_list.push("up"); } if(maze[y+1][x]=="wall" && maze[y+2][x]=="wall"){ direction_list.push("down"); } if(maze[y][x+1]=="wall" && maze[y][x+2]=="wall"){ direction_list.push("right"); } if(maze[y][x-1]=="wall" && maze[y][x-2]=="wall"){ direction_list.push("left"); } // 掘り進められない場合,ループを抜ける if (direction_list.length==0) break; // 指定座標を通路にする setPath(x,y); // 次に進む方向をランダムで決める var direction_num = getRandomInt(direction_list.length); // 2セル先まで通路にする switch(direction_list[direction_num]){ case "up": setPath(x, --y); setPath(x, --y); break; case "down": setPath(x, ++y); setPath(x, ++y); break; case "right": setPath(++x, y); setPath(++x, y); break; case "left": setPath(--x, y); setPath(--x, y); break; } } // 四方どこにも進めなくなった場合 // すでに通路となった座標をランダムに取得し,掘り直し if (start_points_x.length != 0){ // ランダムにスタート地点を決定 var random = getRandomInt(start_points_x.length); // 配列から要素を抜き出して,10進数でintに変換 var restart_x = parseInt(start_points_x.splice(random,1),10); var restart_y = parseInt(start_points_y.splice(random,1),10); dig(restart_y, restart_x); } } // 座標を通路(0)とする function setPath(x,y){ maze[y][x]="path"; if(x%2 == 1 && y%2 ==1) // 奇数座標の場合は,dig開始座標候補に追加 { start_points_x.push(x); start_points_y.push(y); } } <file_sep>/* * 迷路を解くゲーム */ phina.globalize(); // phina.jsを使用する(グローバルに展開) // 定数 const WALL_SIZE = 40; // 正方形の一辺の長さ const DISPLAY_WIDTH = 640; // ゲーム画面の横幅 const DISPLAY_HEIGHT = 960; // ゲーム画面の縦幅 const ONE_SECOND_FPS = 30; //ゲーム画面を、一秒間に何回更新するか // グローバル変数 var maze; // 迷路生成用配列 var start_points_x = new Array(); // 穴掘り開始地点候補の配列 var start_points_y = new Array(); // 穴掘り開始地点候補の配列 var maze_count = 0; /* * メイン処理 */ phina.main(function() { // アプリケーション生成 var app = GameApp({ // シーン選択(mainから開始) startLabel: 'start', // 画面設定 width: DISPLAY_WIDTH, //画面の横幅 height: DISPLAY_HEIGHT, //画面の縦幅 fps: ONE_SECOND_FPS, //毎秒何回画面を更新するかの設定。 scenes: [ { className: 'StartScene', label: 'start', nextLabel: 'main', }, { className: 'MainScene', label: 'main', nextLabel: 'goal', }, { className: 'GoalScene', label: 'goal', nextLabel: 'main', }, { className: 'GameOverScene', label: 'gameover', nextLabel: 'start', }, ], }); // アプリケーション実行 app.run(); }); // ランダムなint型の数を返す関数 // 0~maxの範囲で返す function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } <file_sep>/* * メインシーンの定義 */ phina.define("MainScene", { superClass: 'DisplayScene', // 初期化 init: function() { this.finish_frame = -1; this.superInit(); //初期化のおまじない this.backgroundColor = 'silver'; // 背景色 // グループを生成 this.wallGroup = DisplayElement().addChildTo(this); this.enemyGroup = DisplayElement().addChildTo(this); // ブロック数 var x_wall_num = Math.floor(DISPLAY_WIDTH / WALL_SIZE); var y_wall_num = Math.floor(DISPLAY_HEIGHT / WALL_SIZE); // 外側のフレーム幅 var frame_size_x = WALL_SIZE/2; var frame_size_y = WALL_SIZE/2; // 奇数にする if(x_wall_num%2==0){ x_wall_num--; frame_size_x = WALL_SIZE; } if(y_wall_num%2==0){ y_wall_num--; frame_size_y = WALL_SIZE; } // 迷路生成 createMaze(x_wall_num, y_wall_num); for(var i=0; i<x_wall_num; i++){ for(var j=0; j<y_wall_num; j++){ if(maze[j][i] == "wall"){ var tempRec = Wall({}); //tempRecに四角を一旦代入し、初期値を設定する tempRec.x = frame_size_x + (i * WALL_SIZE); //表示位置(x座標) tempRec.y = frame_size_y + (j * WALL_SIZE); //表示位置(y座標) tempRec.addChildTo(this.wallGroup); //グループに追加する } } } // スタート地点生成 this.start = Point().addChildTo(this); this.start.x = frame_size_x + WALL_SIZE; this.start.y = frame_size_y + WALL_SIZE; // ゴール地点生成 this.goal = Point().addChildTo(this); this.goal.x = DISPLAY_WIDTH - frame_size_x - WALL_SIZE; this.goal.y = DISPLAY_HEIGHT - frame_size_y - WALL_SIZE; // 自機生成 this.hero = Hero().addChildTo(this); this.hero.x = frame_size_x + WALL_SIZE; this.hero.y = frame_size_y + WALL_SIZE; // 敵の生成 var tempEnemy = Enemy({}); //一時的なオブジェクトに一旦代入し,初期値設定 tempEnemy.x = this.goal.x; tempEnemy.y = this.goal.y; tempEnemy.addChildTo(this.enemyGroup); //グループに追加する }, // アップデート update: function(app) { // 敵を生成 var enemy_timer = 8; // 敵を5sに一回生成 var enemy_num = 1 + getRandomInt((maze_count - 1) / 5); // 一度に生まれる敵の数 // 分裂1s前に警告する if (app.frame % (ONE_SECOND_FPS * enemy_timer ) == (ONE_SECOND_FPS * (enemy_timer - 1))) { this.enemyGroup.children.first.shadow = "red"; this.enemyGroup.children.first.speed_x = this.enemyGroup.children.first.speed_x / 2; this.enemyGroup.children.first.speed_y = this.enemyGroup.children.first.speed_y / 2; } // 定期的に分裂する if (app.frame % (ONE_SECOND_FPS * enemy_timer ) == 0) { this.enemyGroup.children.first.shadow = "white"; this.enemyGroup.children.first.speed_x = this.enemyGroup.children.first.speed_x * 2; this.enemyGroup.children.first.speed_y = this.enemyGroup.children.first.speed_y * 2; for(var i=0; i< enemy_num; i++){ var tempEnemy = Enemy({}); //一時的なオブジェクトに一旦代入し,初期値設定 tempEnemy.x=this.enemyGroup.children.first.x; tempEnemy.y=this.enemyGroup.children.first.y; tempEnemy.addChildTo(this.enemyGroup); //グループに追加する } } // 自機移動 // キーボード var speed = 10; var key = app.keyboard; // shiftを押すと加速 if(key.getKey('shift')){ speed = 17; } // 移動 if (key.getKey('left') || key.getKey('a')) { this.hero.x -= speed; if(this.hitTestWallHero()){ this.hero.x += speed; } } if (key.getKey('right') || key.getKey('d')) { this.hero.x += speed; if(this.hitTestWallHero()){ this.hero.x -= speed; } } if (key.getKey('up') || key.getKey('w')) { this.hero.y -= speed; if(this.hitTestWallHero()){ this.hero.y += speed; } } if (key.getKey('down') || key.getKey('s')) { this.hero.y += speed; if(this.hitTestWallHero()){ this.hero.y -= speed; } } // タッチ保持 var speed = 20; this.onpointstay = function(e) { // down if(this.hero.y > e.pointer.y){ this.hero.y -= speed; if(this.hitTestWallHero()){ this.hero.y += speed; } } // up if(this.hero.y < e.pointer.y){ this.hero.y += speed; if(this.hitTestWallHero()){ this.hero.y -= speed; } } // right if(this.hero.x < e.pointer.x){ this.hero.x += speed; if(this.hitTestWallHero()){ this.hero.x -= speed; } } // left if(this.hero.x > e.pointer.x){ this.hero.x -= speed; if(this.hitTestWallHero()){ this.hero.x += speed; } } }; // ゲームオーバ-判定 if(this.hitEnemy()){ this.hero.x = -100; this.hero.y = -100; this.finish_frame = app.frame + ONE_SECOND_FPS; } if(app.frame == this.finish_frame){ this.hero.remove(); this.exit("gameover"); } // ゴール判定 if (this.hero.hitTestElement(this.goal)){ maze_count++; this.exit(); } }, // プレイヤーと壁の当たり判定 hitTestWallHero: function(){ var hero = this.hero; var self = this; var onWall = false; // 壁をループ this.wallGroup.children.each(function(wall){ if(wall.hitTestElement(hero)){ onWall = true; } }); return onWall; }, // プレイヤーと敵の当たり判定 hitEnemy: function(){ var hero = this.hero; var self = this; var hitEnemy = false; // 壁をループ this.enemyGroup.children.each(function(enemy){ if(enemy.hitTestElement(hero)){ hitEnemy = true; enemy.shadow = "red"; enemy.radius = WALL_SIZE * 7 / 10; enemy.speed_x = enemy.speed_x / 2; enemy.speed_y = enemy.speed_y / 2; } }); return hitEnemy; }, }); <file_sep>/* * アドバイス */ var comment_list = [ "スライムにぶつかると食べられます", "shitキーでダッシュできます", "スライムは8秒に一回分裂します", "スライムは分裂前に赤く光ります", "スライムは分裂前に減速します", "上階層ほどスライムは増えやすくなります", "上階層のスライムは少し素早く動きます", "wasdキーでも操作できます", "Enterキーで次の画面に進むことができます", "迷路は毎回ランダムに生成されます", "スライムはクリック/タップされると減速します" ]; /* * スタートシーンの定義 */ phina.define("StartScene", { // 継承 superClass: 'DisplayScene', // 初期化 init: function() { // 親クラス初期化 this.superInit(); // 背景色 this.backgroundColor = 'teal'; // ラベル Label({ text: '迷路', fontSize: 48, fill: 'white', }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center() - 70); Label({ text: '敵を避けて、右下のゴールを目指します', fontSize: 30, fill: 'white', }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center() + 55); Label({ text: 'タッチ、矢印キーで操作できます', fontSize: 30, fill: 'white', }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center() + 55 + 45); Label({ text: 'タッチして進む', fontSize: 48, fill: 'white', }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center() + 200); }, // タッチで次のシーンへ onpointstart: function() { this.exit(); }, update: function(app) { // エンターで次のシーンへ var key = app.keyboard; if (key.getKey('return')){ this.exit(); } }, }); /* * ゴールシーンの定義 */ phina.define("GoalScene", { // 継承 superClass: 'DisplayScene', // 初期化 init: function() { // 親クラス初期化 this.superInit(); // 背景色 this.backgroundColor = 'maroon'; // ラベル Label({ text: maze_count+"個の迷路をクリアしました", fontSize: 40, fill: 'white', }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center() - 70); Label({ text: comment_list[getRandomInt(comment_list.length)], fontSize: 25, fill: 'white', }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center() +50); Label({ text: '次の迷路に進む', fontSize: 48, fill: 'white', }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center() + 200); }, // タッチで次のシーンへ onpointstart: function() { this.exit(); }, update: function(app) { // エンターで次のシーンへ var key = app.keyboard; if (key.getKey('return')) { this.exit(); } }, }); /* * gameoverシーンの定義 */ phina.define("GameOverScene", { // 継承 superClass: 'DisplayScene', // 初期化 init: function() { // 親クラス初期化 this.superInit(); // 背景色 this.backgroundColor = 'olive'; // ラベル Label({ text: '<NAME> O V E R', fontSize: 60, fill: 'purple', }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center() - 70); Label({ text: maze_count+"個の迷路をクリアしました.", fontSize: 35, fill: 'white', }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center() +50); Label({ text: comment_list[getRandomInt(comment_list.length)], fontSize: 25, fill: 'white', }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center() + 55 + 45*2); Label({ text: 'リスタート', fontSize: 48, fill: 'white', }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center() + 250); // カウントの初期化 maze_count = 0; }, // タッチで次のシーンへ onpointstart: function() { this.exit(); }, update: function(app) { // エンターで次のシーンへ var key = app.keyboard; if (key.getKey('return')) { this.exit(); } }, }); <file_sep># 無限迷路(Infinite Maze) 自動生成される迷路の中で,敵に食べられないように出口を目指すゲームです.(タッチ操作,キー操作対応) - https://infinite-maze.netlify.com/ ![maze](https://user-images.githubusercontent.com/30111767/111768060-c7c17000-88ea-11eb-97af-bc508f31339f.gif)
64a23c20912c45105afaa8c1a4247404fe946220
[ "JavaScript", "Markdown" ]
5
JavaScript
tomiokario/infinite_maze
0b0cd2b395641e50b574b9fb0c6023e1249bf30c
c1c30f17a4a2f060e84ba133e151d0de4064411b
refs/heads/master
<repo_name>whoisyourvladie/Oauth<file_sep>/Shared/SaaS.Mailer/Models/Notification.cs using System; using System.Reflection; using System.Xml.Serialization; namespace SaaS.Mailer.Models { public class Notification { public Notification() { } public Notification(Notification notification) { AccountId = notification.AccountId; FirstName = notification.FirstName; LastName = notification.LastName; Email = notification.Email; DownloadLink = notification.DownloadLink; } [XmlElement("accountId")] public Guid AccountId { get; set; } [XmlElement("firstName")] public string FirstName { get; set; } [XmlElement("lastName")] public string LastName { get; set; } [XmlElement("email")] public string Email { get; set; } [XmlElement("downloadLink")] public string DownloadLink { get; set; } [XmlIgnore] public string FullName { get { if (string.IsNullOrEmpty(FirstName) && string.IsNullOrEmpty(LastName)) return Email; return string.Format("{0} {1}", FirstName, LastName); } } public string this[string key] { get { var type = GetType(); var property = type.GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (object.Equals(property, null)) return null; var value = property.GetValue(this); if (object.Equals(value, null)) return null; return value.ToString(); } } } }<file_sep>/Shared/SaaS.Identity/AuthRepository/AuthRepository.SessionTokenExternalHistory.cs using SaaS.Data.Entities.View.Oauth; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthRepository { public async Task<List<ViewSessionTokenExternalHistory>> SessionTokenExternalHistoriesAsync(Guid accountId) { return await _context.SessionTokenExternalHistoriesGetAsync(accountId); } public async Task SessionTokenExternalHistorySetAsync(Guid accountId, string externalClientName, string externalAccountId, string email) { await _context.SessionTokenExternalHistorySetAsync(accountId, externalClientName, externalAccountId, email); } public async Task SessionTokenExternalHistoryConnectAccountAsync(Guid accountId, string externalClientName, string externalAccountId, string email) { await _context.SessionTokenExternalHistoryConnectAccountAsync(accountId, externalClientName, externalAccountId, email); } public async Task SessionTokenExternalHistorySetStateAsync(Guid id, bool isUnlinked) { await _context.SessionTokenExternalHistorySetStateAsync(id, isUnlinked); } } }<file_sep>/Shared/SaaS.Oauth2/Core/QueryStringBuilder.cs using System; using System.Linq; using System.Text; using System.Web; namespace SaaS.Oauth2.Core { internal static class QueryStringBuilder { internal static string BuildCompex(string[] dontEncode, params object[] keyValueEntries) { if (keyValueEntries.Length % 2 != 0) { throw new Exception( "KeyAndValue collection needs to be dividable by two... key, value, key, value... get it?"); } var sb = new StringBuilder(); for (int index = 0; index < keyValueEntries.Length; index ++) { var key = keyValueEntries[index++]; var value = keyValueEntries[index]; if (object.Equals(value, null)) continue; var valEncoded = HttpUtility.UrlEncode(value.ToString()); if (dontEncode != null && dontEncode.Contains(key)) valEncoded = value.ToString(); sb.AppendFormat("{0}={1}&", key, valEncoded); } return sb.ToString().TrimEnd('&'); } } } <file_sep>/Web.Api/SaaS.Api/Models/Api/Oauth/AuthNameViewModel.cs using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Api.Oauth { public class AuthNameViewModel : AuthViewModel { [MaxLength(300), RegularExpression(@"^[^\^<>()\[\]\\;:@№%\|$%*?#&¸¼!+€£¢¾½÷פ¶»¥¦µ©®°§«´¨™±°º¹²³ª¯¬`""'/]*$")] public string FirstName { get; set; } [MaxLength(300), RegularExpression(@"^[^\^<>()\[\]\\;:@№%\|$%*?#&¸¼!+€£¢¾½÷פ¶»¥¦µ©®°§«´¨™±°º¹²³ª¯¬`""'/]*$")] public string LastName { get; set; } } }<file_sep>/Shared/SaaS.Mailer/RazorParser.cs using RazorEngine; using RazorEngine.Templating; using SaaS.Common.Extensions; using SaaS.Mailer.Models; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Text; using System.Threading; using System.Web; namespace SaaS.Mailer { public class RazorParser { private static readonly string _templateFolder; private static readonly ResourceManager _resourceManager = null; private static readonly IAppSettings _appSettigns = new AppSettings(); private static readonly Dictionary<string, CultureInfo> _cultures = new Dictionary<string, CultureInfo>(StringComparer.InvariantCultureIgnoreCase); static RazorParser() { _cultures.Add("en", new CultureInfo("en-US")); _cultures.Add("fr", new CultureInfo("fr-FR")); _cultures.Add("de", new CultureInfo("de-DE")); _cultures.Add("it", new CultureInfo("it-IT")); _cultures.Add("es", new CultureInfo("es-ES")); _cultures.Add("pt", new CultureInfo("pt-PT")); _cultures.Add("ru", new CultureInfo("ru-RU")); _cultures.Add("jp", new CultureInfo("ja-JP")); _cultures.Add("ja", new CultureInfo("ja-JP")); _cultures.Add("sv", new CultureInfo("sv-FI")); var brand = string.Empty; #if LuluSoft brand = "LuluSoft"; _resourceManager = Templates.LuluSoft.App_GlobalResources.Subjects.ResourceManager; #endif #if PdfForge brand = "PdfForge"; _resourceManager = Templates.PdfForge.App_GlobalResources.Subjects.ResourceManager; #endif #if PdfSam brand = "PdfSam"; _resourceManager = Templates.PdfSam.App_GlobalResources.Subjects.ResourceManager; #endif _templateFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "templates", brand); #if LuluSoft && DEBUG _templateFolder = @"d:\svn\Canada\oauth.sodapdf.com\branches\spdf-10971(sprint-67)\Shared\SaaS.Mailer\Templates\LuluSoft"; #endif #if PdfForge && DEBUG _templateFolder = @"C:\projects\svn\oauth.sodapdf.com\branches\pa-2566(no-sprint)\Shared\SaaS.Mailer\Templates\PdfForge"; #endif #if PdfSam && DEBUG _templateFolder = @"d:\svn\Canada\oauth.sodapdf.com\branches\spdf-10971(sprint-67)\Shared\SaaS.Mailer\Templates\PdfSam\"; #endif } public RazorParser(string lang) { lang = lang ?? string.Empty; Thread.CurrentThread.CurrentUICulture = _cultures.ContainsKey(lang) ? _cultures[lang] : _cultures.First().Value; } public string ParseTemplateAsync(SendEmailAction emailAction, string xml, out object model) { model = null; switch (emailAction.TemplateId) { case EmailTemplate.EmailChangeConfirmationNotification: model = XMLSerializer.DeserializeObject<EmailChangeConfirmationNotification>(xml); break; case EmailTemplate.eSignEmailConfirmationNotification: case EmailTemplate.EmailConfirmationLateNotification: var emailConfirmation = XMLSerializer.DeserializeObject<EmailConfirmationNotification>(xml); var emailConfirmationUriBuilder = new UriBuilder(_appSettigns.Oauth.EmailConfirmation); var emailConfirmationQuery = HttpUtility.ParseQueryString(emailConfirmationUriBuilder.Query); emailConfirmationQuery.Add("userId", emailConfirmation.AccountId.ToString("N")); emailConfirmationUriBuilder.Query = emailConfirmationQuery.ToString(); emailConfirmation.ConfirmationLink = emailConfirmationUriBuilder.Uri.ToString(); model = emailConfirmation; break; case EmailTemplate.EmailConfirmationCovermountNotification: case EmailTemplate.EmailConfirmationNotification: model = XMLSerializer.DeserializeObject<EmailConfirmationNotification>(xml); break; case EmailTemplate.EmailChangeNotification: model = XMLSerializer.DeserializeObject<EmailChangeNotification>(xml); break; case EmailTemplate.ProductSuspendNotification: model = XMLSerializer.DeserializeObject<ProductSuspendNotification>(xml); break; case EmailTemplate.AccountCreationCompleteNotification: case EmailTemplate.RecoverPasswordNotification: model = XMLSerializer.DeserializeObject<RecoverPasswordNotification>(xml); break; case EmailTemplate.ProductAssignedNotification: case EmailTemplate.ProductAssignedNotificationCreatePassword: case EmailTemplate.ProductEditionAssignedNotification: case EmailTemplate.ProductEditionAssignedNotificationCreatePassword: case EmailTemplate.ProductUnassignedNotification: model = XMLSerializer.DeserializeObject<ProductAssignedNotification>(xml); break; case EmailTemplate.ProductRenewalOffNotification: model = XMLSerializer.DeserializeObject<ProductRenewalOffNotification>(xml); break; case EmailTemplate.WelcomeFreeProductNotification: case EmailTemplate.WelcomeFreeProductCovermountNotification: model = XMLSerializer.DeserializeObject<WelcomeFreeProductNotification>(xml); break; case EmailTemplate.WelcomePurchaseNotification: case EmailTemplate.WelcomePurchaseHomePlanNotification: case EmailTemplate.WelcomePurchasePremiumPlanNotification: case EmailTemplate.WelcomePurchaseBasicPlanNotification: case EmailTemplate.WelcomePurchaseHomeEditionNotification: case EmailTemplate.WelcomePurchaseProEditionNotification: case EmailTemplate.WelcomePurchasePremiumEditionNotification: case EmailTemplate.WelcomePurchaseEnterpriseNotification: case EmailTemplate.MicrotransactionCreatePasswordNotification: case EmailTemplate.WelcomePurchaseProOcrEditionNotification: //pdfsam case EmailTemplate.WelcomePurchaseStandardEditionNotification: //pdfsam case EmailTemplate.WelcomePurchaseStandardPlanNotification: //pdfsam case EmailTemplate.WelcomePurchaseProPlanNotification: //pdfsam case EmailTemplate.WelcomePurchaseProOcrPlanNotification: //pdfsam case EmailTemplate.WelcomePurchaseOcrPlanNotification: //pdfsam case EmailTemplate.WelcomePurchaseEditPlanNotification: //pdfsam case EmailTemplate.WelcomePurchaseConvertPlanNotification: //pdfsam case EmailTemplate.WelcomePurchaseMigrationFromSuiteNotification: //pdfsuite to soda var welcomeModel = XMLSerializer.DeserializeObject<WelcomePurchaseNotification>(xml); var uriBuilder = new UriBuilder(_appSettigns.Oauth.CreatePassword); if (emailAction.TemplateId == EmailTemplate.WelcomePurchaseMigrationFromSuiteNotification) uriBuilder = new UriBuilder(new Uri(string.Format(_appSettigns.Oauth.CustomLink, "online-createpassword-suite-to-soda"))); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query.Add("userId", welcomeModel.AccountId.ToString("N")); query.Add("email", welcomeModel.Email); query.Add("firstName", welcomeModel.FirstName); query.Add("lastName", welcomeModel.LastName); uriBuilder.Query = query.ToString(); welcomeModel.CreatePasswordLink = uriBuilder.Uri.ToString(); model = welcomeModel; break; case EmailTemplate.LegacyCreatePasswordReminder: case EmailTemplate.LegacyActivationCreatePasswordNotification: model = XMLSerializer.DeserializeObject<CreatePasswordNotification>(xml); break; case EmailTemplate.MergeConfirmationNotification: model = XMLSerializer.DeserializeObject<MergeConfirmationNotification>(xml); break; case EmailTemplate.eSignSignPackageNotification: model = XMLSerializer.DeserializeObject<XmlNotification>(xml); break; default: model = XMLSerializer.DeserializeObject<Notification>(xml); break; } var subject = ParseSubject(emailAction, model); return ParseTemplate(emailAction, model, subject); } public string ParseTemplate(SendEmailAction emailAction, object model, string subject) { string layoutPath = Path.Combine(_templateFolder, "Partial\\Layout.cshtml"); string partialPath = Path.Combine(_templateFolder, string.Format("{0}.cshtml", emailAction.TemplateId)); string layoutHtml = Parse(layoutPath, model); string partialHtml = Parse(partialPath, model); var builder = new StringBuilder(layoutHtml); builder.Replace("**partial**", partialHtml); builder.Replace("**subject**", subject); return builder.ToString(); } public string ParseSubject(SendEmailAction emailAction, object model) { string subject = _resourceManager.GetString(emailAction.TemplateId.ToString()); if (!string.IsNullOrEmpty(subject)) { var type = model.GetType(); var productName = type.GetProperty("ProductName", BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (!object.Equals(productName, null)) { var value = productName.GetValue(model, null) as string; subject = subject.Replace("[product name]", value); subject = subject.Replace("[Product Name]", value); //say hello for Ksenia } } return string.IsNullOrEmpty(subject) ? "SaaS" : subject; } private string Parse<TModel>(string templatePath, TModel model) { if (!Engine.Razor.IsTemplateCached(templatePath, typeof(TModel))) Engine.Razor.AddTemplate(templatePath, File.ReadAllText(templatePath)); return Engine.Razor.RunCompile(templatePath, typeof(TModel), model); } } } <file_sep>/Web.Api/SaaS.Sso/src/js/directives/logo.js angular.module('app.directives') .directive('ngLogo', ['$brand', ($brand) => { return { restrict: 'A', link: (scope, element, attrs) => { let logo = $brand.logo(); element.html(`<img width="${logo.width}" src="${logo.src}">`); } }; }]);<file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.SessionToken.cs using SaaS.Data.Entities.Oauth; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity { //TODO remove sp. [oauth].[pSessionTokenGetByParentId] public partial class AuthDbContext { internal async Task<SessionToken> SessionTokenGetAsync(Guid id) { var sqlParams = new SqlParameter[] { id.ToSql("id") }; return await ExecuteReaderAsync<SessionToken>("[oauth].[pSessionTokenGetById]", sqlParams); } internal async Task<List<SessionToken>> SessionTokensGetAsync(Guid accountId) { return await ExecuteReaderCollectionAsync<SessionToken>("[oauth].[pSessionTokenGetByAccountId]", CreateSqlParams(accountId)); } internal async Task<int> SessionTokenDeleteAsync(Guid id) { var sqlParams = new SqlParameter[] { id.ToSql("id") }; return await ExecuteNonQueryAsync("[oauth].[pSessionTokenDelete]", sqlParams); } internal async Task SessionTokenInsertAsync(SessionToken token, Guid? oldId, bool isRemoveOldSessions, bool isInsertAccountSystem) { var sqlParams = new SqlParameter[] { token.Id.ToSql("id"), token.ParentId.ToSql("parentId"), token.ClientId.ToSql("clientId"), token.ClientVersion.ToSql("clientVersion"), token.ExternalClient.ToSql("externalClientId"), token.IssuedUtc.ToSql("issuedUtc"), token.ExpiresUtc.ToSql("expiresUtc"), token.Scope.ToSql("scope"), token.ProtectedTicket.ToSql("protectedTicket"), token.AccountId.ToSql("accountId"), token.SystemId.ToSql("systemId"), token.AccountProductId.ToSql("accountProductId"), //Warning! All transmitted parameters must be implemented on the DB side in this procedure of appropriate product. #if LuluSoft token.InstallationID.ToSql("installationID"), #endif oldId.ToSql("oldId"), isRemoveOldSessions.ToSql("isRemoveOldSessions"), isInsertAccountSystem.ToSql("isInsertAccountSystem") }; await ExecuteNonQueryAsync("[oauth].[pSessionTokenInsert]", sqlParams); } } }<file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.cs using SaaS.Common.Extensions; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthDbContext { private SqlParameter[] CreateSqlParams(Guid accountId) { return new SqlParameter[] { accountId.ToSql("accountId") }; } private List<SqlParameter> CreateSqlParams(AccountProductPair pair) { return new List<SqlParameter>() { pair.AccountProductId.ToSql("accountProductId"), pair.AccountId.ToSql("accountId") }; } internal async Task<T> ExecuteReaderAsync<T>(string commandText, Guid accountId) { return await ExecuteReaderAsync<T>(commandText, CreateSqlParams(accountId)); } internal async Task<T> ExecuteReaderAsync<T>(string commandText, IEnumerable<SqlParameter> sqlParams) { var array = sqlParams.ToArray(); using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = array.CommandText(commandText); cmd.Parameters.AddRange(array); await Database.Connection.OpenAsync(); var reader = await cmd.ExecuteReaderAsync(); var entity = ((IObjectContextAdapter)this).ObjectContext.Translate<T>(reader).FirstOrDefault(); Database.Connection.Close(); return entity; } } internal List<T> ExecuteReaderCollection<T>(string commandText, IEnumerable<SqlParameter> sqlParams) { var array = sqlParams.ToArray(); using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = array.CommandText(commandText); cmd.Parameters.AddRange(array); Database.Connection.Open(); var reader = cmd.ExecuteReader(); var list = ((IObjectContextAdapter)this).ObjectContext.Translate<T>(reader).ToList(); Database.Connection.Close(); return list; } } internal async Task<List<T>> ExecuteReaderCollectionAsync<T>(string commandText, Guid accountId) { return await ExecuteReaderCollectionAsync<T>(commandText, CreateSqlParams(accountId)); } internal async Task<List<T>> ExecuteReaderCollectionAsync<T>(string commandText, IEnumerable<SqlParameter> sqlParams) { var array = sqlParams.ToArray(); using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = array.CommandText(commandText); cmd.Parameters.AddRange(array); await Database.Connection.OpenAsync(); var reader = await cmd.ExecuteReaderAsync(); var list = ((IObjectContextAdapter)this).ObjectContext.Translate<T>(reader).ToList(); Database.Connection.Close(); return list; } } internal int ExecuteNonQuery(string commandText, IEnumerable<SqlParameter> sqlParams) { var array = sqlParams.ToArray(); using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = array.CommandText(commandText); cmd.Parameters.AddRange(array); Database.Connection.Open(); var reader = cmd.ExecuteNonQuery(); Database.Connection.Close(); return reader; } } internal async Task<int> ExecuteNonQueryAsync(string commandText, IEnumerable<SqlParameter> sqlParams) { var array = sqlParams.ToArray(); using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = array.CommandText(commandText); cmd.Parameters.AddRange(array); await Database.Connection.OpenAsync(); var reader = await cmd.ExecuteNonQueryAsync(); Database.Connection.Close(); return reader; } } internal async Task<object> ExecuteScalarAsync(string commandText, IEnumerable<SqlParameter> sqlParams) { var array = sqlParams.ToArray(); using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = array.CommandText(commandText); cmd.Parameters.AddRange(array); await Database.Connection.OpenAsync(); var reader = await cmd.ExecuteScalarAsync(); Database.Connection.Close(); return reader; } } internal bool PasswordIsEqual(string source, string password) { return string.Equals(source, password.GetMD5Hash(), StringComparison.InvariantCultureIgnoreCase); } } internal static class SqlHelper { internal static SqlParameter ToSql(this object value, string key) { return object.Equals(value, null) ? new SqlParameter(key, DBNull.Value) : new SqlParameter(key, value); } internal static string CommandText(this SqlParameter[] sqlParams, string commandText) { StringBuilder builder = new StringBuilder(commandText); if (!object.Equals(sqlParams, null) && sqlParams.Length > 0) { foreach (var item in sqlParams) builder.AppendFormat(" @{0}=@{0},", item.ParameterName); builder.Length--; } return builder.ToString(); } } } <file_sep>/Shared/SaaS.Identity/AuthRepository/AuthRepository.AccountSubEmail.cs using SaaS.Data.Entities.Accounts; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Web; namespace SaaS.Identity { public partial class AuthRepository { public Uri GenerateEmailChangeConfirmationTokenLinkAsync(Uri uri, AccountSubEmailPending pending) { var uriBuilder = new UriBuilder(uri); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query.Add("token", pending.Id.ToString("N")); uriBuilder.Query = query.ToString(); return uriBuilder.Uri; } public async Task AccountEmailSetAsync(AccountSubEmailPending pending) { await _context.AccountEmailSetAsync(pending); } public async Task<List<AccountSubEmail>> AccountSubEmailsGetAsync(Guid accountId) { return await _context.AccountSubEmailsGetAsync(accountId); } public async Task AccountSubEmailDeleteAsync(int id) { await _context.AccountSubEmailDeleteAsync(id); } public async Task<AccountSubEmailPending> AccountSubEmailPendingSetAsync(Guid accountId, string email) { return await _context.AccountSubEmailPendingSetAsync(accountId, email); } public async Task<AccountSubEmailPending> AccountSubEmailPendingGetAsync(Guid id) { return await _context.AccountSubEmailPendingGetAsync(id); } public async Task<List<AccountSubEmailPending>> AccountSubEmailPendingsGetAsync(Guid accountId) { return await _context.AccountSubEmailPendingsGetAsync(accountId); } public async Task AccountSubEmailPendingDeleteAsync(Guid accountId) { await _context.AccountSubEmailPendingDeleteAsync(accountId); } } }<file_sep>/Shared/SaaS.Api.Models/Oauth/AccountDetailViewModel.cs using Newtonsoft.Json; using System; using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Oauth { public class AccountDetailsViewModel : AuthNameViewModel { public Guid Id { get; set; } [MaxLength(20)] public string Phone { get; set; } [MaxLength(20)] public string PhoneESign { get; set; } [MaxLength(128)] public string Company { get; set; } [MaxLength(128)] public string Occupation { get; set; } [MaxLength(2), JsonProperty("Country")] public string CountryISO2 { get; set; } [MaxLength(2), JsonProperty("Language")] public string LanguageISO2 { get; set; } [MaxLength(128)] public string Address1 { get; set; } [MaxLength(128)] public string Address2 { get; set; } [MaxLength(128)] public string City { get; set; } [MaxLength(32)] public string PostalCode { get; set; } [MaxLength(128)] public string State { get; set; } public ulong Status { get; set; } public bool? Optin { get; set; } } } <file_sep>/Web.Api/SaaS.UI.Admin/Controllers/AccountController.cs using System.Web.Mvc; namespace SaaS.UI.Admin.Controllers { [Authorize] public class AccountController : Controller { public ActionResult Details() { return View(); } public ActionResult Index() { return View(); } public ActionResult Search() { return View(); } public ActionResult Password() { return View(); } public ActionResult Products() { return View(); } [ActionName("Add-Product"), Authorize(Roles = "manager,admin")] public ActionResult AddProduct() { return View("AddProduct"); } public ActionResult Special() { return View(); } public ActionResult Register() { return View(); } } }<file_sep>/Shared/SaaS.Data.Entities/View/ViewOwnerProduct.cs using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Data.Entities.View { public class ViewOwnerProduct : ViewProduct { public string OwnerEmail { get; set; } public int AllowedCount { get; set; } public int UsedCount { get; set; } [NotMapped] public List<ViewOwnerAccount> Accounts { get; set; } } }<file_sep>/Shared/SaaS.Oauth2/Core/OauthSignInFactory.cs using SaaS.Oauth2.Configuration; using System; using System.Configuration; namespace SaaS.Oauth2.Core { internal static class OauthSignInFactory { internal static T CreateClient<T>(string configName) where T : ClientProvider, new() { var root = ConfigurationManager.GetSection("saas.oauth2.configuration") as OauthConfigurationSection; if (object.Equals(root, null)) return default(T); var configurationReader = root.OAuthVClientConfigurations.GetEnumerator(); while (configurationReader.MoveNext()) { var currentOauthElement = configurationReader.Current as OauthConfigurationElement; if (currentOauthElement.Name == configName && currentOauthElement != null) return (T)Activator.CreateInstance(typeof(T), new object[] { currentOauthElement }); } throw new Exception("ERROR: [MultiOAuthFactroy] ConfigurationName is not found!"); } } } <file_sep>/Shared/SaaS.Data.Entities/View/ViewAccountSystem.cs using System; namespace SaaS.Data.Entities.View { public class ViewAccountSystem { public Guid SystemId { get; set; } public Guid AccountId { get; set; } public Guid AccountProductId { get; set; } public string PcName { get; set; } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.EmailChange.cs using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Data.Entities.Accounts; using System; using System.Linq; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { [HttpPost, Route("email-change-send"), ValidateNullModel, ValidateModel, SaaSAuthorize] public async Task<IHttpActionResult> EmailChangeSend(AuthViewModel model) { try { var slaveUser = await _auth.AccountGetAsync(model.Email, isIncludeSubEmails: true); if (!object.Equals(slaveUser, null) && slaveUser.Id != AccountId) return AccountExists(); var masterUser = await GetAccountAsync(); if (string.Equals(masterUser.Email, model.Email, StringComparison.InvariantCultureIgnoreCase)) await _auth.AccountSubEmailPendingDeleteAsync(masterUser.Id); else await NotificationManager.EmailChangeConfirmationNotification(masterUser, model.Email); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } [HttpPost, Route("email-change-confirmation")] public async Task<IHttpActionResult> EmailChangeConfirmation([FromUri] Guid token) { try { var pending = await _auth.AccountSubEmailPendingGetAsync(token); if (object.Equals(pending, null)) return AccountNotFound(); var slave = await _auth.AccountGetAsync(pending.Email, true); if (!object.Equals(slave, null) && slave.Id != pending.AccountId) return AccountExists(); var masterUser = await _auth.AccountGetAsync(pending.AccountId); await _auth.AccountActivateAsync(masterUser); await _auth.AccountEmailSetAsync(pending); await NotificationManager.EmailChange(masterUser, pending.Email); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } [HttpGet, Route("email-change-pending"), SaaSAuthorize] public async Task<IHttpActionResult> EmailChangePending() { return await CurrentAccountExecuteAsync(async delegate (Account account) { var pendings = await _auth.AccountSubEmailPendingsGetAsync(AccountId); var emailChangePendingViewModel = new EmailChangePendingViewModel { Email = account.Email, PendingEmails = pendings.Select(e => e.Email).ToArray() }; return Ok(emailChangePendingViewModel); }); } [HttpDelete, Route("email-change-pending"), SaaSAuthorize] public async Task<IHttpActionResult> EmailChangePendingDelete() { try { await _auth.AccountSubEmailPendingDeleteAsync(AccountId); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.Module.cs using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Oauth; using System; using System.Linq; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { [HttpGet, Route("modules"), SaaSAuthorize] public async Task<IHttpActionResult> Modules() { try { var sessionProducts = await GetSessionTokenProducts(); if (object.Equals(sessionProducts.SessionToken, null)) return AccountUnauthorized(); if (!sessionProducts.SessionToken.AccountProductId.HasValue) return ProductNotFound(); var product = sessionProducts.Products.FirstOrDefault(e => e.AccountProductId == sessionProducts.SessionToken.AccountProductId.Value && !e.IsDisabled); if (object.Equals(product, null)) return ProductNotFound(); var modules = UserManagerHelper.GetAllowedModules(sessionProducts.Products, product.AccountProductId); var active = UserManagerHelper.GetActiveProducts(sessionProducts.Products, modules, product.AccountProductId); var features = GetModuleFeatures(product, modules); return Ok(new { id = product.AccountProductId, email = User.Identity.Name, modules = modules, moduleFeatures = features, activeProducts = active, }); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } } }<file_sep>/Web.Api/SaaS.UI.Admin/App_Start/Startup.cs using Microsoft.Owin.Security.OAuth; using Newtonsoft.Json.Serialization; using Owin; using SaaS.UI.Admin.Oauth; using StructureMap; using System; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Dispatcher; namespace SaaS.UI.Admin { public partial class Startup { public static OAuthBearerAuthenticationOptions AuthenticationOptions; static Startup() { AuthenticationOptions = new OAuthBearerAuthenticationOptions() { Provider = ObjectFactory.GetInstance<OauthBearerProvider>() }; } public void ConfigureOAuth(IAppBuilder app) { app.UseOAuthBearerAuthentication(AuthenticationOptions); HttpConfiguration config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); app.UseWebApi(config); config.Formatters.Remove(config.Formatters.XmlFormatter); var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); config.Services.Replace(typeof(IHttpControllerActivator), new ApiControllerActivator(config)); var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; //json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local; json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; json.SerializerSettings.DateFormatString = "yyyy-MM-ddThh:mm:sszzz"; json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); var contractResolver = (DefaultContractResolver)json.SerializerSettings.ContractResolver; contractResolver.IgnoreSerializableAttribute = true; } } public class ApiControllerActivator : IHttpControllerActivator { public ApiControllerActivator(HttpConfiguration configuration) { } public IHttpController Create(HttpRequestMessage request , HttpControllerDescriptor controllerDescriptor, Type controllerType) { var controller = ObjectFactory.GetInstance(controllerType) as IHttpController; return controller; } } }<file_sep>/Web.Api/SaaS.Api.Sign/Controllers/Api/Silanis/GroupsController.cs using SaaS.Api.Core.Filters; using System; using System.Net.Http; using System.Web.Http; namespace SaaS.Api.Sign.Controllers.Api.Silanis { [RoutePrefix("api/groups"), SaaSAuthorize] public class GroupsController : BaseApiController { protected override string ApiRoot { get { return "api/groups/"; } } [Route("{*url}"), HttpGet, HttpPost, HttpPut, HttpDelete] public HttpResponseMessage Index() { return HttpProxy(Request, Request.RequestUri.LocalPath); } [Route, HttpGet] public HttpResponseMessage Groups() { return HttpProxy(Request, Format()); } [Route("{groupId:guid}"), HttpGet] public HttpResponseMessage GroupId(Guid groupId) { return HttpProxy(Request, Format("{0}", groupId)); } } } <file_sep>/Web.Api/SaaS.Api/Oauth/Providers/SaaSAuthorizationServerProvider.Client.cs using Microsoft.Owin; using Microsoft.Owin.Security.OAuth; using SaaS.Common.Extensions; using SaaS.Data.Entities; using SaaS.Data.Entities.Oauth; using System; using System.Threading.Tasks; using System.Linq; namespace SaaS.Api.Oauth.Providers { public partial class SaaSAuthorizationServerProvider { public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId, clientSecret; if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) context.TryGetFormCredentials(out clientId, out clientSecret); var client = ValidateClientAuthentication(context, clientSecret); if (object.Equals(client, null)) return; string[] scope = null; SystemSignInData systemSignInData = null; string token = null; var formCollection = await context.Request.ReadFormAsync(); if (!object.Equals(formCollection, null)) { scope = GetScope(formCollection); systemSignInData = GetSystemSignInData(formCollection); token = formCollection["token"]; Guid visitorId; if (Guid.TryParse(formCollection["visitorId"], out visitorId)) context.OwinContext.Set("visitorId", visitorId); var externalClient = OauthManager.GetExternalClient(formCollection["externalClient"]); if (externalClient.HasValue) context.OwinContext.Set("externalClient", externalClient); Version clientVersion; if ((Version.TryParse(formCollection["client_version"], out clientVersion) && clientVersion.Major > 0) || Version.TryParse(client.Version, out clientVersion)) context.OwinContext.Set("clientVersion", clientVersion.ToString()); if (Guid.TryParse(formCollection["installationID"], out Guid installationID)) context.OwinContext.Set("installationID", installationID); } context.OwinContext.Set("scope", scope); context.OwinContext.Set("systemSignInData", systemSignInData); context.OwinContext.Set("client", client); context.OwinContext.Set("token", token); context.Validated(); } private Client ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context, string clientSecret) { if (object.Equals(context.ClientId, null)) { context.SetError("invalid_clientId", "ClientId should be sent."); return null; } var client = GetClient(context.ClientId); if (object.Equals(client, null)) { context.SetError("invalid_clientId", "This client is not registered in the system."); return null; } if (!client.IsActive) { context.SetError("invalid_client", "Client is inactive."); return null; } if (client.ApplicationType == ApplicationTypes.Desktop) { if (string.IsNullOrWhiteSpace(clientSecret)) { context.SetError("invalid_clientSecret", "Client secret should be sent."); return null; } if (client.Secret != clientSecret.GetHash()) { context.SetError("invalid_clientSecret", "Client secret is invalid."); return null; } } return client; } private string[] GetScope(IFormCollection formCollection) { var _scope = formCollection["scope"]; if (!string.IsNullOrEmpty(_scope)) return _scope.ToLower().Split(','); return null; } private SubscriptionSignInData GetSignInData(IFormCollection formCollection) { int accountProductId; bool setAsDefault; bool.TryParse(formCollection["setAsDefault"], out setAsDefault); if (int.TryParse(formCollection["accountProductId"], out accountProductId)) return new SubscriptionSignInData { AccountProductId = accountProductId, SetAsDefault = setAsDefault }; return new SubscriptionSignInData(); } private SystemSignInData GetSystemSignInData(IFormCollection formCollection) { var systemSignInData = new SystemSignInData { MotherboardKey = formCollection["motherboardKey"], PhysicalMac = formCollection["physicalMac"], PcName = formCollection["pcName"] ?? null }; Guid machineKey; if (Guid.TryParse(formCollection["machineKey"], out machineKey)) systemSignInData.MachineKey = machineKey; bool isAutogeneratedMachineKey; bool.TryParse(formCollection["isAutogeneratedMachineKey"], out isAutogeneratedMachineKey); systemSignInData.IsAutogeneratedMachineKey = isAutogeneratedMachineKey; return systemSignInData; } private static Client GetClient(string name) { Client client = null; if (!string.IsNullOrEmpty(name)) _clients.TryGetValue(name, out client); return client; } //private static ExternalClient GetExternalClient(string name) //{ // ExternalClient client = null; // if (!string.IsNullOrEmpty(name)) // _externalClients.TryGetValue(name, out client); // return client; //} } }<file_sep>/Shared/SaaS.Data.Entities/Oauth/AccountSystem.cs using System; namespace SaaS.Data.Entities.Oauth { public class AccountSystem : AccountEntity<Guid> { public Guid SystemId { get; set; } public Guid AccountProductId { get; set; } } } <file_sep>/Shared/SaaS.Mailer/Models/ProductSuspendNotification.cs using System; using System.Xml.Serialization; namespace SaaS.Mailer.Models { [XmlRoot("xml")] public class ProductSuspendNotification : Notification { public ProductSuspendNotification() { } public ProductSuspendNotification(Notification user, string productName, DateTime? expireDate) : base(user) { ProductName = productName; ExpireDate = expireDate; } [XmlElement("productName")] public string ProductName { get; set; } [XmlElement("expireDate", IsNullable = true)] public DateTime? ExpireDate { get; set; } } }<file_sep>/Shared/SaaS.Identity.Admin/AuthRepository/AuthRepository.User.cs using Microsoft.AspNet.Identity; using SaaS.Data.Entities.Admin.View.Oauth; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Identity.Admin { public partial class AuthRepository { public async Task<User> UserGetAsync(Guid userId) { return await _context.UserGetAsync(userId); } public async Task<User> UserGetAsync(string login) { return await _context.UserGetAsync(login); } public async Task UserSetActiveAsync(Guid userId, bool isActive) { await _context.UserSetActiveAsync(userId, isActive); } public async Task<IdentityResult> UserChangePasswordAsync(Guid userId, string oldPassword, string newPassword) { return await _userManager.ChangePasswordAsync(userId, oldPassword, newPassword); } public async Task<ViewUser> ViewUserGetAsync(Guid userId) { return await _context.ViewUserGetAsync(userId); } public async Task<ViewUser> ViewUserGetAsync(string login, string password) { return await _context.ViewUserGetAsync(login, password); } public async Task<List<ViewUser>> ViewUsersGetAsync() { return await _context.ViewUsersGetAsync(); } public async Task ViewUserSetAsync(ViewUser user) { await _context.ViewUserSetAsync(user); } public async Task ViewUserInsertAsync(ViewUser user) { await _context.ViewUserInsertAsync(user); } public async Task<string> AccountGDPRDeleteAsync(string email) { var result=await _context.AccountGDPRDeleteAsync(email); return result; } } }<file_sep>/Shared/SaaS.Identity/eSignRepository/IeSignRepository.cs using SaaS.Data.Entities.eSign; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Identity { public interface IeSignRepository : IDisposable { Task eSignUseIncreaseAsync(Guid accountId, Guid? accountProductId = null, Guid? accountMicrotransactionId = null); Task<int> eSignPackageHistoryGetFreeNumberOfSigns(int oauthClientId, eSignClient eSignClient, string ipAddressHash); Task eSignPackageHistorySetAsync(eSignPackageHistory history); Task<eSignApiKey> eSignApiKeyGetAsync(Guid accountId, eSignClient eSignClient); List<eSignApiKey> eSignApiKeysNeedRefreshGet(int top = 10); Task eSignApiKeySetAsync(Guid accountId, string email, eSignClient eSignClient, string apiKey); void eSignApiKeyDelete(int id); } } <file_sep>/Web.Api/SaaS.Zendesk/dist/js/app.min.js "use strict"; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } angular.module('app.auth', []); angular.module('app.services', []); angular.module('app.controllers', []); angular.module('app.directives', []); angular.module('app.filters', []); angular.module('app', ['ui.router', 'app.auth', 'app.services', 'app.controllers', 'app.directives', 'app.filters']).run(function ($trace, $transitions, $auth, $brand) { $trace.enable('TRANSITION'); $transitions.onBefore({ to: '**' }, function (transitions) { if (transitions.to().isProtected && !$auth.isAuthenticated()) { var query = {}; if (!$brand.isEmpty()) query.brandId = $brand.get().id; return transitions.router.stateService.target('user/sign-in', query); } }); }).config(function ($stateProvider, $urlRouterProvider) { // $locationProvider.html5Mode({ // enabled: true, // requireBase: false // }); $urlRouterProvider.otherwise('/en/index'); $stateProvider.state('app', { url: '/:locale', //templateUrl: 'index.html', restricted: false, abstract: true, views: { sidebar: { controller: 'partialSidebarController', templateUrl: 'partial/sidebar.html' }, content: { controller: 'appController' } } }); var _state = function _state(json) { json.name = json.name || json.url; json.params = json.params || {}; json.templateUrl = json.templateUrl || "views/".concat(json.url, ".html"); json.isProtected = !!json.isProtected; var state = { parent: 'app', url: "/".concat(json.url), params: json.params, templateUrl: json.templateUrl, controller: "".concat(json.controller, "Controller"), isProtected: json.isProtected }; $stateProvider.state(json.name, state); }; _state({ url: 'index', controller: 'index' }); _state({ url: 'account', controller: 'account', templateUrl: 'views/account/index.html', params: { accountId: null, brandId: null }, isProtected: true }); _state({ url: 'account/external-session-tokens', controller: 'accountExternalSessionTokens', params: { accountId: null }, isProtected: true }); _state({ url: 'account/product', controller: 'accountProduct', params: { accountId: null, accountProductId: null }, isProtected: true }); _state({ url: 'account/products', controller: 'accountProducts', params: { accountId: null }, isProtected: true }); _state({ url: 'account/sub-emails', controller: 'accountSubEmails', params: { accountId: null }, isProtected: true }); _state({ url: 'account/email-is-empty', controller: 'accountEmailIsEmpty', params: { email: null }, isProtected: true }); _state({ url: 'account/not-found', controller: 'accountNotFound', params: { email: null }, isProtected: true }); _state({ url: 'brand/not-supported', controller: 'brandNotSupported', params: { brandId: null } }); _state({ url: 'ticket/not-found', controller: 'ticketNotFound' }); _state({ url: 'ticket/requester-email-is-empty', controller: 'ticketRequesterEmailIsEmpty' }); _state({ url: 'user/sign-in', controller: 'userSignIn', params: { brandId: null } }); _state({ url: 'zat/client-not-found', controller: 'zatClientNotFound' }); }); //https://github.com/modularcode/modular-admin-angularjs/blob/master/src/_main.js angular.module('app').config(['$httpProvider', function ($httpProvider) { $httpProvider.interceptors.push([function () { var interceptor = {}; interceptor.response = function (response) { var config = response.config || {}; if (config.asJson === true) return response.data; return response; }; return interceptor; }]); }]); angular.module('app.auth').factory('$auth', ['$q', '$state', '$injector', '$authStorage', '$brand', function ($q, $state, $injector, $authStorage, $brand) { var _apiHeaders = { 'Content-Type': 'application/x-www-form-urlencoded' }; var service = {}; var _getItem = function _getItem() { var iso = $brand.getIso(); return $authStorage.getItem(iso); }; service.isAuthenticated = function () { if ($brand.isEmpty()) return false; return !!_getItem(); }; service.getAccessToken = function () { var item = _getItem(); return item ? item.access_token : null; }; service.getRefreshToken = function () { var item = _getItem(); return item ? item.refresh_token : null; }; service.signIn = function (login, password) { var $http = $injector.get("$http"); var data = ['grant_type=password', 'username=' + encodeURIComponent(login), 'password=' + encodeURIComponent(password)]; data = data.join('&'); var deferred = $q.defer(); if ($brand.isEmpty()) { deferred.reject({ error_description: 'Brand is not supported!' }); } else { var uri = $brand.getApiUri('api/token'); $http.post(uri, data, { headers: _apiHeaders, asJson: true }).then(function (json) { var iso = $brand.getIso(); $authStorage.setItem(iso, json); deferred.resolve(json); }, function (error, status, headers) { deferred.reject(error.data); }); } return deferred.promise; }; service.refreshToken = function () { var $http = $injector.get("$http"); var data = ['grant_type=refresh_token', 'refresh_token=' + service.getRefreshToken()]; data = data.join('&'); var deferred = $q.defer(); var uri = $brand.getApiUri('api/token'); $http.post(uri, data, { headers: _apiHeaders, asJson: true }).then(function (json) { var iso = $brand.getIso(); $authStorage.setItem(iso, json); deferred.resolve(json); }, function (error, status, headers) { service.logout(); deferred.reject(status); }); return deferred.promise; }; service.logout = function () { var iso = $brand.getIso(); $authStorage.removeItem(iso); $state.go('user/sign-in'); }; return service; }]); angular.module('app.auth').factory('$authBuffer', ['$injector', function ($injector) { /** Holds all the requests, so they can be re-requested in future. */ var _buffer = []; /** Service initialized later because of circular dependency problem. */ var $http; var _retryHttpRequest = function _retryHttpRequest(config, deferred) { var _success = function _success(response) { deferred.resolve(response); }; var _error = function _error(response) { deferred.reject(response); }; $http = $http || $injector.get('$http'); $http(config).then(_success, _error); }; var service = {}; /** * Appends HTTP request configuration object with deferred response attached to buffer. */ service.append = function (config, deferred) { _buffer.push({ config: config, deferred: deferred }); }; /** * Abandon or reject (if reason provided) all the buffered requests. */ service.rejectAll = function (reason) { if (reason) { for (var index = 0; index < _buffer.length; ++index) { _buffer[index].deferred.reject(reason); } } _buffer = []; }; /** * Retries all the buffered requests clears the buffer. */ service.retryAll = function (updater) { for (var index = 0; index < _buffer.length; ++index) { _retryHttpRequest(updater(_buffer[index].config), _buffer[index].deferred); } _buffer = []; }; return service; }]); angular.module('app.auth').config(['$httpProvider', function ($httpProvider) { $httpProvider.interceptors.push(['$q', '$auth', '$authInterceptor', '$authBuffer', function ($q, $auth, $authInterceptor, $authBuffer) { var interceptor = {}; interceptor.request = function (config) { config.headers = config.headers || {}; if (config.isOauth) config.headers.Authorization = 'bearer ' + $auth.getAccessToken(); return config; }; interceptor.responseError = function (rejection) { var config = rejection.config || {}; switch (rejection.status) { case 401: var deferred = $q.defer(); $authBuffer.append(config, deferred); $auth.refreshToken().then($authInterceptor.loginConfirmed, $auth.logout); return deferred.promise; } return $q.reject(rejection); }; return interceptor; }]); }]); angular.module('app.auth').factory('$authInterceptor', ['$authBuffer', function ($authBuffer) { var service = {}; /** * Call this function to indicate that authentication was successfull and trigger a * retry of all deferred requests. * @param data an optional argument to pass on to $broadcast which may be useful for * example if you need to pass through details of the user that was logged in * @param configUpdater an optional transformation function that can modify the * requests that are retried after having logged in. This can be used for example * to add an authentication token. It must return the request. */ service.loginConfirmed = function (data, configUpdater) { var updater = configUpdater || function (config) { return config; }; $authBuffer.retryAll(updater); }; /** * Call this function to indicate that authentication should not proceed. * All deferred requests will be abandoned or rejected (if reason is provided). * @param data an optional argument to pass on to $broadcast. * @param reason if provided, the requests are rejected; abandoned otherwise. */ service.loginCancelled = function (data, reason) { $authBuffer.rejectAll(reason); }; return service; }]); angular.module('app.auth').factory('$authStorage', ['$window', function ($window) { var _localStorage = {}; var _getItem = function _getItem(key) { var json = _localStorage[key]; var value = json ? JSON.parse(json) : null; _localStorage[key] = json; try { json = $window.localStorage.getItem(key); json && (value = JSON.parse(json)); } catch (error) { console.error(error); } return value; }; var _setItem = function _setItem(key, value) { var json = JSON.stringify(value); _localStorage[key] = json; try { $window.localStorage.setItem(key, json); } catch (error) { console.error(error); } }; var _removeItem = function _removeItem(key) { delete _localStorage[key]; try { $window.localStorage.removeItem(key); } catch (error) { console.error(error); } }; var service = {}; service.getItem = function (brandIso) { return _getItem("auth:".concat(brandIso)); }; service.setItem = function (brandIso, json) { _setItem("auth:".concat(brandIso), json); }; service.removeItem = function (brandIso) { _removeItem("auth:".concat(brandIso)); }; return service; }]); angular.module('app.controllers').controller('appController', ['$scope', '$state', '$zendesk', '$brand', '$auth', function ($scope, $state, $zendesk, $brand, $auth) { $zendesk.init(); if ($zendesk.isEmpty()) return $state.go('zat/client-not-found'); var _validateBrand = function _validateBrand(brand) { $brand.set(brand); if (!$brand.isSupport()) return $state.go('brand/not-supported', { brandId: brand.id }); $scope.$auth = $auth; $state.go('account', { brandId: brand.id }); }; $zendesk.get(['ticket.brand']).then(function (response) { _validateBrand(response['ticket.brand']); }, function () { $state.go('ticket/not-found'); }); $zendesk.on('ticket.brand.changed', _validateBrand); }]); angular.module('app.controllers').controller('indexController', ['$scope', function ($scope) {}]); angular.module('app.directives').directive('ngDate', ['$filter', function ($filter) { return { restrict: 'A', scope: { date: '=ngDate', format: '=ngFormat' }, link: function link(scope, element, attrs) { if (!scope.date) return; element.addClass('text-muted small'); var format = scope.format || 'yyyy-MM-dd'; /* HH:mm*/ scope.$watch('date', function (newValue, oldValue) { if (newValue || newValue != oldValue) element.html("<em>" + $filter('date')(scope.date, format) + "</em>"); }); } }; }]); angular.module('app.directives').directive('ngExternalConnectedAccountStatus', [function () { return { restrict: 'A', link: function link(scope, element, attrs) { element.addClass('fas'); if (attrs.ngExternalConnectedAccountStatus === 'false') { element.addClass('fa-user-slash text-danger').attr('title', 'Disconnected'); } else { element.addClass('fa-user text-success').attr('title', 'Connected'); } } }; }]); angular.module('app.directives').directive('ngExternalConnectedAccount', [function () { return { restrict: 'A', link: function link(scope, element, attrs) { element.addClass('fab').addClass('fa-' + attrs.ngExternalConnectedAccount); switch (attrs.ngExternalConnectedAccount) { case 'google': element.css({ color: '#d62d20' }); break; case 'facebook': element.css({ color: '#3b5998' }); break; case 'microsoft': element.css({ color: '#00a1f1' }); break; } } }; }]); angular.module('app.directives').directive('ngSidebar', ['$rootScope', '$api', function ($rootScope, $api) { return { restrict: 'A', link: function link(scope, element, attrs) { var sidebar = element.find('.sidebar:first, .sidebar-content'); var buttons = element.find('button.navbar-toggler'); buttons.eq(0).bind('click', function () { sidebar.css({ height: '100%' }); }); // element.find('.btn').bind('click', function () { // sidebar.css({ height: '0%' }); // }) buttons.eq(1).bind('click', function () { sidebar.css({ height: '0%' }); }); var cleanup = $rootScope.$on('event:closeSidebar', function () { sidebar.css({ height: '0%' }); }); scope.$on('$destroy', cleanup); } }; }]); angular.module('app.directives').directive('ngSpinner', ['$rootScope', function ($rootScope) { return { restrict: 'E', replace: true, template: '<div class="spinner" style="display:none"></div>', link: function link(scope, element, attrs) { $rootScope.$on('event:spinner-show', function () { element.show(); }); $rootScope.$on('event:spinner-hide', function () { element.hide(); }); //scope.$on('$destroy', cleanup); } }; }]); angular.module('app.services').factory('$api', ['$http', '$brand', function factory($http, $brand) { var _config = { asJson: true, isOauth: true }; var _accountStatusEnum = { none: 0, isActivated: 1 << 0, isAnonymous: 1 << 1, isBusiness: 1 << 2 }; ; var _productStatusEnum = { none: 0, isDisabled: 1 << 0, isExpired: 1 << 1, isTrial: 1 << 2, isFree: 1 << 3, isMinor: 1 << 4, isDefault: 1 << 5, isPPC: 1 << 6, isUpgradable: 1 << 7, isNew: 1 << 8, isPaymentFailed: 1 << 9, isRenewal: 1 << 10, isOwner: 1 << 11, IsNotAbleToRenewCreditCartExpired: 1 << 12 }; var service = {}; service.account = { isActivated: function isActivated(account) { return !!(account.status & _accountStatusEnum.isActivated); }, isBusiness: function isBusiness(account) { return !!(account.status & _accountStatusEnum.isBusiness); }, get: function get(params) { var method = 'api/account/'; if (params.accountId) { method += params.accountId; delete params.accountId; } var config = angular.copy(_config); config.params = params; return $http.get($brand.getApiUri(method), config); } }; service.product = { isDisabled: function isDisabled(product) { return !!(product.status & _productStatusEnum.isDisabled); }, isTrial: function isTrial(product) { return !!(product.status & _productStatusEnum.isTrial); }, isFree: function isFree(product) { return !!(product.status & _productStatusEnum.isFree); }, isPPC: function isPPC(product) { return !!(product.status & _productStatusEnum.isPPC); }, isRenewal: function isRenewal(product) { return !!(product.status & _productStatusEnum.isRenewal); }, isOwner: function isOwner(product) { return !!(product.status & _productStatusEnum.isOwner); } }; service.account.getSubEmails = function (params) { return $http.get($brand.getApiUri("api/account/".concat(params.accountId, "/sub-email")), _config); }; service.account.removeSubEmail = function (params) { return $http.delete($brand.getApiUri("api/account/".concat(params.accountId, "/sub-email/").concat(params.id)), _config); }; service.account.getExternalSessionTokens = function (params) { return $http.get($brand.getApiUri("api/account/".concat(params.accountId, "/external/session-token")), _config); }; service.account.getOwnerProducts = function (params) { return $http.get($brand.getApiUri("api/account/".concat(params.accountId, "/owner-product")), _config); }; service.account.getOwnerProductDetails = function (params) { return $http.get($brand.getApiUri("api/account/".concat(params.accountId, "/owner-product/").concat(params.accountProductId)), _config); }; return service; }]); angular.module('app.services').factory('$brand', function () { var _brands = { sodapdf: { api: 'https://cp-oauth.sodapdf.com' }, pdfarchitect: { api: 'https://cp-oauth.pdfarchitect.org' } }; var _brand = null; var service = {}; service.isEmpty = function () { return !_brand; }; service.set = function (brand) { _brand = brand; }; service.get = function () { return _brand; }; service.isSupport = function () { var iso = service.getIso(_brand); return !!_brands[iso]; }; service.getIso = function () { return _brand.subdomain; }; service.getApiUri = function (method) { var iso = service.getIso(); var api = _brands[iso].api; return "".concat(api, "/").concat(method); }; service.getLogo = function () { if (service.isEmpty()) return null; return _brand.logo.contentUrl; }; return service; }); angular.module('app.services').factory('$form', function () { var service = {}; service.submit = function (entity, form, callback) { if (form.$valid !== true) { angular.forEach(form, function (value, key) { if (_typeof(value) === 'object' && value.hasOwnProperty('$modelValue')) value.$setDirty(); }); } if (service.isReady(entity, form) === false) return; callback(form); }; service.isReady = function (entity, form) { if (entity.isBusy === true || form.$valid !== true) return false; entity.isBusy = true; return true; }; return service; }); angular.module('app.services').factory('$zendesk', [function () { var _zClient = ZAFClient.init(); var service = {}; service.init = function () { _zClient && _zClient.invoke('resize', { width: '100%', height: '400px' }); }; service.isEmpty = function () { return !_zClient; }; service.on = function (key, callback) { return _zClient.on(key, callback); }; service.get = function (key) { return _zClient.get(key); }; return service; }]); angular.module('app.controllers').controller('accountController', ['$rootScope', '$q', '$scope', '$state', '$api', '$zendesk', function ($rootScope, $q, $scope, $state, $api, $zendesk) { $scope.model = { accountId: null, account: null }; var _getAccount = function _getAccount() { var params = $state.params; var deferred = $q.defer(); if (params.accountId) { $api.account.get({ accountId: params.accountId }).then(deferred.resolve, function () { deferred.reject({ state: 'account/not-found', params: { accountId: params.accountId } }); }); } else { $zendesk.get(['ticket.requester']).then(function (response) { var requester = response['ticket.requester']; if (!requester.email) deferred.reject({ state: 'account/email-is-empty' });else { $api.account.get({ email: requester.email }).then(deferred.resolve, function () { deferred.reject({ state: 'account/not-found', params: { email: requester.email } }); }); } }, function () { deferred.reject({ state: 'ticket/requester-email-is-empty' }); }); } return deferred.promise; }; $rootScope.$broadcast('event:spinner-show'); _getAccount().then(function (json) { $scope.model.account = json; $scope.model.accountId = json.id; }, function (error) { $state.go(error.state, error.params); }).finally(function () { $rootScope.$broadcast('event:spinner-hide'); }); }]); angular.module('app.controllers').controller('accountEmailIsEmptyController', ['$scope', function ($scope) {}]); angular.module('app.controllers').controller('accountExternalSessionTokensController', ['$scope', '$state', '$api', function ($scope, $state, $api) { $scope.isLoading = true; $scope.model = { accountId: $state.params.accountId, externalSessionTokens: null }; $api.account.getExternalSessionTokens({ accountId: $scope.model.accountId }).then(function (json) { $scope.model.externalSessionTokens = json; }); }]); angular.module('app.controllers').controller('accountNotFoundController', ['$scope', '$state', '$brand', function ($scope, $state, $brand) { $scope.model = { email: $state.params.email, logo: $brand.get().logo.contentUrl }; }]); (function () { angular.module('app.controllers').controller('accountProductController', ['$scope', '$state', '$api', function ($scope, $state, $api) { $scope.$api = $api; $scope.isLoading = true; $scope.model = { accountId: $state.params.accountId, accountProductId: $state.params.accountProductId, product: null }; var query = { accountId: $scope.model.accountId, accountProductId: $scope.model.accountProductId }; $api.account.getOwnerProductDetails(query).then(function (json) { $scope.model.product = new viewProduct(json); }); }]); var viewProduct = function viewProduct(json) { Object.defineProperties(this, { id: { value: json.id, writable: false }, name: { value: json.name, writable: false }, unitName: { value: json.unitName, writable: false }, plan: { value: json.plan, writable: false }, ownerEmail: { value: json.ownerEmail, writable: false }, allowed: { value: json.allowed, writable: false } }); this.endDate = json.endDate; this.purchaseDate = json.purchaseDate; this.status = json.status; this.accounts = viewAcountBuilder.build(json); }; var viewAccount = function viewAccount(json) { Object.defineProperties(this, { accountId: { value: json.accountId, writable: false }, email: { value: json.email, writable: false } }); }; var viewAcountBuilder = function viewAcountBuilder() {}; viewAcountBuilder.build = function (json) { var accounts = []; if (json.accounts) { for (var index = 0; index < json.accounts.length; index++) { var account = json.accounts[index]; accounts.push(new viewAccount(account)); } } return accounts; }; })(); (function () { angular.module('app.controllers').controller('accountProductsController', ['$scope', '$state', '$api', function ($scope, $state, $api) { $scope.$api = $api; $scope.isLoading = true; $scope.model = { accountId: $state.params.accountId, products: null }; $api.account.getOwnerProducts({ accountId: $scope.model.accountId }).then(function (json) { $scope.model.products = viewProductBuilder.build(json, $api); }); }]); var viewProduct = function viewProduct(json, $api) { Object.defineProperties(this, { id: { value: json.id, writable: false }, name: { value: json.name, writable: false }, unitName: { value: json.unitName, writable: false }, plan: { value: json.plan, writable: false }, allowed: { value: json.allowed, writable: false }, purchaseDate: { value: json.purchaseDate, writable: false }, status: { value: json.status, writable: false } }); this.$api = $api; }; viewProduct.prototype.getTableCssClass = function () { var $api = this.$api; if ($api.product.isDisabled(this)) return 'table-danger'; if ($api.product.isFree(this) || $api.product.isTrial(this)) return 'table-primary'; return ''; }; var viewProductBuilder = function viewProductBuilder() {}; viewProductBuilder.build = function (json, $api) { var products = []; for (var index = 0; index < json.length; index++) { products.push(new viewProduct(json[index], $api)); } return products; }; })(); angular.module('app.controllers').controller('accountSubEmailsController', ['$scope', '$state', '$api', function ($scope, $state, $api) { $scope.isLoading = true; $scope.model = { accountId: $state.params.accountId, subEmails: null }; $scope.refresh = function () { $api.account.getSubEmails({ accountId: $scope.model.accountId }).then(function (json) { $scope.model.subEmails = json; }); }; $scope.remove = function (json) { $api.account.removeSubEmail(json).finally($scope.refresh); }; }]); angular.module('app.controllers').controller('brandNotSupportedController', ['$scope', '$brand', function ($scope, $brand) { $scope.model = { logo: $brand.get().logo.contentUrl }; }]); angular.module('app.controllers').controller('partialSidebarController', ['$rootScope', '$scope', '$auth', '$state', '$api', '$form', function ($rootScope, $scope, $auth, $state, $api, $form) { $scope.$auth = $auth; var _search = { filter: null }; $scope.model = { search: { filter: null } }; $scope.status = null; $scope.isBusy = false; $scope.search = function (form) { $form.submit($scope, form, function () { $scope.status = null; _search.filter = $scope.model.search.filter; if (!_search.filter) return; var query = {}; if (_search.filter.indexOf('@') !== -1) query.email = _search.filter;else query.transactionOrderUid = _search.filter; $scope.isBusy = true; $api.account.get(query).then(function (json) { $rootScope.$broadcast('event:closeSidebar'); return $state.go('account', { accountId: json.id }); }, function (error) { $scope.status = error.status; }).finally(function () { $scope.isBusy = false; }); }); }; $scope.signIn = function () { $state.go('user/sign-in'); $rootScope.$broadcast('event:closeSidebar'); }; $scope.logout = function () { $auth.logout(); $rootScope.$broadcast('event:closeSidebar'); }; }]); angular.module('app.controllers').controller('ticketNotFoundController', ['$scope', function ($scope) {}]); angular.module('app.controllers').controller('userSignInController', ['$scope', '$brand', '$state', '$auth', '$form', '$zendesk', function ($scope, $brand, $state, $auth, $form, $zendesk) { $scope.model = { logo: $brand.getLogo(), avatar: null, error: null }; $scope.status = null; $scope.isBusy = false; !$zendesk.isEmpty() && $zendesk.get('currentUser').then(function (response) { $scope.model.login = response.currentUser.email; $scope.model.avatar = response.currentUser.avatarUrl; $scope.$apply(); }); $scope.submit = function (form) { $scope.model.error = null; $form.submit($scope, form, function () { return $auth.signIn($scope.model.login, $scope.model.password).then(function () { $state.go('account'); }, function (json) { $scope.model.error = json.error_description; }).finally(function () { $scope.isBusy = false; }); }); }; }]); angular.module('app.controllers').controller('zatClientNotFoundController', ['$scope', function ($scope) {}]); angular.module('app.directives').directive('ngAccountActivated', ['$api', function ($api) { return { restrict: 'A', scope: { status: '=ngAccountActivated' }, link: function link(scope, element, attrs) { element.addClass('badge'); var watch = scope.$watch('status', function () { element.removeClass('badge-warning').removeClass('badge-success'); !$api.account.isActivated(scope) && element.addClass('badge-warning').text('not activated'); $api.account.isActivated(scope) && element.addClass('badge-success').text('activated'); }); scope.$on("$destroy", function () { watch(); }); } }; }]); angular.module('app.directives').directive('ngAccountMenu', ['$state', function ($state) { return { restrict: 'E', replace: true, templateUrl: 'directives/account/menu.html' }; }]); angular.module('app.directives').directive('ngAccountType', ['$api', function ($api) { return { restrict: 'A', scope: { status: '=ngAccountType' }, link: function link(scope, element, attrs) { element.addClass('badge'); var watch = scope.$watch('status', function () { element.removeClass('badge-primary').removeClass('badge-info'); !$api.account.isBusiness(scope) && element.addClass('badge-info').text('b2c'); $api.account.isBusiness(scope) && element.addClass('badge-primary').text('b2b'); }); scope.$on("$destroy", function () { watch(); }); } }; }]); angular.module('app.directives').directive('ngProductOwner', ['$api', function ($api) { return { restrict: 'A', scope: { status: '=ngProductOwner' }, link: function link(scope, element, attrs) { element.addClass('badge'); var watch = scope.$watch('status', function (status) { if (!status) return; element.removeClass('badge-warning').removeClass('badge-success'); !$api.product.isOwner(scope) && element.addClass('badge-danger').text('not owner'); $api.product.isOwner(scope) && element.addClass('badge-success').text('owner'); }); scope.$on("$destroy", function () { watch(); }); } }; }]);<file_sep>/Shared/SaaS.Oauth2/Configuration/OauthConfigurationSection.cs using System.Configuration; namespace SaaS.Oauth2.Configuration { public class OauthConfigurationSection : ConfigurationSection { [ConfigurationProperty("oauth", IsKey = false, IsRequired = true)] [ConfigurationCollection(typeof(OauthConfigurationElementCollection), CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)] public OauthConfigurationElementCollection OAuthVClientConfigurations { get { return base["oauth"] as OauthConfigurationElementCollection; } } } } <file_sep>/Shared/SaaS.Data.Entities/View/ViewAccountProductModule.cs using System; namespace SaaS.Data.Entities.View { public class ViewAccountProductModule { public Guid AccountProductId { get; set; } public string Module { get; set; } } }<file_sep>/Web.Api/SaaS.Api/Startup.cs using AutoMapper; using Microsoft.Owin; using Owin; using SaaS.Api.Models.Oauth; using SaaS.Api.Models.Products; using SaaS.Data.Entities.View; using SaaS.IPDetect; using System; using System.Configuration; using System.Globalization; using System.Net; using System.Web.Http; [assembly: OwinStartup(typeof(SaaS.Api.Startup))] namespace SaaS.Api { public partial class Startup { public void Configuration(IAppBuilder app) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); ConfigureOAuth(app); var config = new HttpConfiguration(); WebApiConfig.Register(config); app.Map("/api", inner => { inner.Use(typeof(IpAddressFilterMiddleware)); inner.UseWebApi(config); }); Mapper.Initialize(cfg => { cfg.CreateMap<ViewAccountProduct, AccountProductViewModel>(); cfg.CreateMap<ViewAccountProductModule, AccountProductModuleModel>(); cfg.CreateMap<ViewAccountDetails, AccountDetailsViewModel>(); cfg.CreateMap<AccountDetailsViewModel, ViewAccountDetails>(); cfg.CreateMap<RegisterViewModel, ViewAccountDetails>() .ForMember(dest => dest.IsTrial, opts => opts.MapFrom(src => src.Trial)); cfg.CreateMap<ViewUpgradeProduct, UpgradeProductViewModel>(); cfg.CreateMap<ViewOwnerProduct, OwnerProductViewModel>(); }); } } public sealed class AppSettings : IAppSettings { public AppSettingsOauth Oauth { get; private set; } public AppSettingsUpclick Upclick { get; private set; } public AppSettingsB2BLead B2BLead { get; private set; } public Uri DownloadLink { get; private set; } public long ActivationAccountTimeSpan { get; private set; } public AppSettings() { Oauth = new AppSettingsOauth(Setting<string>("oauth:resetPassword"), Setting<string>("oauth:createPassword"), Setting<string>("oauth:emailConfirmation"), Setting<string>("oauth:mergeConfirmation"), Setting<string>("oauth:emailChangeConfirmation")); Upclick = new AppSettingsUpclick(Setting<string>("upclick:merchantLogin"), Setting<string>("upclick:merchantPassword")); B2BLead = new AppSettingsB2BLead(Setting<string>("b2blead:Email")); DownloadLink = new Uri(Setting<string>("downloadLink")); ActivationAccountTimeSpan = (long)TimeSpan.FromDays(1).TotalSeconds; } private static T Setting<T>(string name) { string value = ConfigurationManager.AppSettings[name]; return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture); } } public interface IAppSettings { AppSettingsOauth Oauth { get; } AppSettingsUpclick Upclick { get; } AppSettingsB2BLead B2BLead { get; } Uri DownloadLink { get; } long ActivationAccountTimeSpan { get; } } public class AppSettingsOauth { public AppSettingsOauth(string resetPassword, string createPassword, string emailConfirmation, string mergeConfirmation, string emailChangeConfirmation) { ResetPassword = new Uri(resetPassword); CreatePassword = new Uri(createPassword); EmailConfirmation = new Uri(emailConfirmation); MergeConfirmation = new Uri(mergeConfirmation); EmailChangeConfirmation = new Uri(emailChangeConfirmation); } public readonly Uri ResetPassword; public readonly Uri CreatePassword; public readonly Uri EmailConfirmation; public readonly Uri MergeConfirmation; public readonly Uri EmailChangeConfirmation; } public class AppSettingsUpclick { public readonly string MerchantLogin; public readonly string MerchantPassword; public AppSettingsUpclick(string merchantLogin, string merchantPassword) { MerchantLogin = merchantLogin; MerchantPassword = <PASSWORD>; } } public class AppSettingsB2BLead { public readonly string Email; public AppSettingsB2BLead(string email) { Email = email; } } public sealed class AppSettingsValidation { public string FirstNamePattern { get; internal set; } public string LastNamePattern { get; internal set; } public string EmailPattern { get; internal set; } } }<file_sep>/WinService/SaaS.WinService.eSign/eSignService.cs using NLog; using System.ServiceProcess; namespace SaaS.WinService.eSign { public partial class eSignService : ServiceBase { private static Logger _logger = LogManager.GetCurrentClassLogger(); public eSignService() { InitializeComponent(); } protected override void OnStart(string[] args) { _logger.Info("OnStart"); Scheduler scheduler = new Scheduler(); scheduler.Start(); _logger.Info("OnStart Complete"); } protected override void OnStop() { _logger.Info("OnStop"); } } } <file_sep>/Web.Api/SaaS.Zendesk/qa/controllers/settings/wireless-network.js describe(`controller:settingsWirelessNetwork`, () => { var $rootScope, $scope; beforeEach(module('app')); beforeEach(inject(($injector) => { $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); $injector.get('$controller')('settingsWirelessNetworkController', { $scope: $scope }); })); it('autoDisableWifis:toBeDefined', () => { expect($scope.autoDisableWifis).toBeDefined(); }); it('autoDisableWifis:toBeGreaterThan(0)', () => { expect($scope.autoDisableWifis.length).toBeGreaterThan(0); }); it('model:toBeDefined', () => { expect($scope.model).toBeDefined(); }); });<file_sep>/Shared/SaaS.Data.Entities/Accounts/Account.cs using Microsoft.AspNet.Identity; using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Data.Entities.Accounts { public class Account : Entity<Guid>, IUser<Guid> { public Account() { this.RefreshModifyDate(); } public Account(string email) : this() { Email = email; } public Account(string email, string firstName, string lastName) : this(email) { FirstName = firstName; LastName = lastName; } [Required, MaxLength(330)] public string Email { get; set; } [DataType(DataType.Password), MaxLength(50)] public string Password { get; set; } [MaxLength(300)] public string FirstName { get; set; } [MaxLength(300)] public string LastName { get; set; } public bool? Optin { get; set; } public bool NeverLogged { get; set; } public bool IsAnonymous { get; set; } public bool IsActivated { get; set; } public bool IsBusiness { get; set; } #if LuluSoft public bool? IsPreview { get; set; } #endif [DataType(DataType.DateTime)] public DateTime ModifyDate { get; set; } [NotMapped] public string UserName { get { return string.Format("{0} {1}", FirstName, LastName); } set { } } } public static class AccountHelper { public static bool IsEmptyPassword(this Account account) { return string.IsNullOrEmpty(account.Password); } public static ulong GetStatus(this Account account) { ulong status = 0; status |= (ulong)(account.IsActivated ? AccountStatus.IsActivated : 0); status |= (ulong)(account.IsAnonymous ? AccountStatus.IsAnonymous : 0); status |= (ulong)(account.IsBusiness ? AccountStatus.IsBusiness : 0); #if LuluSoft status |= (ulong)(account.IsPreview == true ? AccountStatus.IsPreview : 0); #endif return status; } public static void RefreshModifyDate(this Account account) { account.ModifyDate = DateTime.UtcNow; } } } <file_sep>/Shared/Upclick.Api.Client/UpclickClient.Customers.cs using Newtonsoft.Json.Linq; using System; using System.Collections.Specialized; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Web; namespace Upclick.Api.Client { public partial class UpclickClient { private async Task<CustomerSubscription> ReadCustomerSubscription(HttpResponseMessage response, string xmlRoot) { if (!response.IsSuccessStatusCode) return null; var jObject = await response.Content.ReadAsAsync<JObject>(); if (!object.Equals(jObject, null)) { var token = jObject.SelectToken(xmlRoot); if (!object.Equals(token, null)) return token.ToObject<CustomerSubscription>(); } return null; } private async Task<HttpResponseMessage> _SubscriptionSuspendResume(string id, bool suspend, string source = null) { var url = suspend ? "customers/subscriptions/do/suspend" : "customers/subscriptions/do/resume"; var param = new NameValueCollection() { { "id", id } }; if (!String.IsNullOrEmpty(source)) { param.Add("source", source); } return await _upclickHttpClient.GetAsync(url, param); } private async Task<CustomersSubscription> _SubscriptionSuspendResume(string id, bool suspend, string key, string source = null) { HttpResponseMessage response = await _SubscriptionSuspendResume(id, suspend, source); if (!response.IsSuccessStatusCode) return null; var jObject = await response.Content.ReadAsAsync<JObject>(); if (!object.Equals(jObject, null)) { var token = jObject.SelectToken(key); if (!object.Equals(token, null)) { if (token is JArray) { var tokenArray = (JArray)token; var tokens = tokenArray.ToObject<CustomersSubscription[]>(); return tokens.OrderByDescending(e => e.NextRebillDate).FirstOrDefault(); } return token.ToObject<CustomersSubscription>(); } } return null; } private async Task<HttpResponseMessage> _SubscriptionCancel(string id) { return await _upclickHttpClient.GetAsync("customers/subscriptions/do/cancel", new NameValueCollection() { { "id", id } }); } private async Task<HttpResponseMessage> _SubscriptionDetails(string id) { return await _upclickHttpClient.GetAsync("customers/subscriptions/retrieve/subscriptiondetails", new NameValueCollection() { { "id", id } }); } private async Task<HttpResponseMessage> _SubscriptionUpdate(string id, DateTime nextRebillDate) { var query = HttpUtility.ParseQueryString(string.Empty); query.Add("id", id); query.Add("rebillDate", nextRebillDate.ToString("yyyy-MM-dd")); return await _upclickHttpClient.GetAsync("customers/subscriptions/do/update", query); } public async Task<CustomersSubscription> SubscriptionSuspend(string id, string source=null) { return await _SubscriptionSuspendResume(id:id, suspend:true, key:"$.customers_subscriptions_do_suspend.subscription",source:source); } public async Task<CustomersSubscription> SubscriptionResume(string id) { return await _SubscriptionSuspendResume(id:id, suspend:false, key:"$.customers_subscriptions_do_resume.subscription"); } public async Task<CustomerSubscription> SubscriptionCancel(string id) { HttpResponseMessage response = await _SubscriptionCancel(id); if (!response.IsSuccessStatusCode) return null; var jObject = await response.Content.ReadAsAsync<JObject>(); if (!object.Equals(jObject, null)) { var token = jObject.SelectToken("$.customers_subscriptions_do_cancel.result"); if (!object.Equals(token, null)) return token.ToObject<CustomerSubscription>(); } return null; } public async Task<CustomerSubscription> SubscriptionDetails(string id) { var response = await _SubscriptionDetails(id); return await ReadCustomerSubscription(response, "$.customers_subscriptions_retrieve_subscriptiondetails.subscription"); } public async Task<CustomerSubscription> SubscriptionUpdate(string id, DateTime nextRebillDate) { var response = await _SubscriptionUpdate(id, nextRebillDate); return await ReadCustomerSubscription(response, "$.customers_subscriptions_do_update.subscription"); } private async Task<HttpResponseMessage> _SubscriptionsPaymentInstruments(string email) { return await _upclickHttpClient.GetAsync("customers/subscriptions/paymentinstruments", new NameValueCollection() { { "email", email } }); } public async Task<CustomerPaymentInstrument[]> SubscriptionsPaymentInstruments(string email) { var response = await _SubscriptionsPaymentInstruments(email); if (!response.IsSuccessStatusCode) return null; var jObject = await response.Content.ReadAsAsync<JObject>(); if (!object.Equals(jObject, null)) { var instruments = jObject.SelectToken("$.customers_subscriptions_paymentinstruments.paymentinstruments"); if (!object.Equals(instruments, null)) { if (instruments is JArray) { var instrumentsArray = (JArray)instruments; return instrumentsArray.ToObject<CustomerPaymentInstrument[]>(); } return new[] { instruments.ToObject<CustomerPaymentInstrument>() }; } } return null; } } public class CustomersSubscription { public string Status { get; set; } public DateTime NextRebillDate { get; set; } } public class CustomerSubscription { public CustomerSubscriptionStatus Status { get; set; } public CustomerSubscriptionNextCycleBill NextCycleBill { get; set; } } public class CustomerSubscriptionNextCycleBill { public DateTime Date { get; set; } } public class CustomerSubscriptionStatus { public string Name { get; set; } } public class CustomerPaymentInstrument { public string PayTokenID { get; set; } public string ProductName { get; set; } public string PayType { get; set; } public string MaskedAccountNumber { get; set; } public uint Expiration { get; set; } public string EditUrl { get; set; } } }<file_sep>/Web.Api/SaaS.Api.Admin/Startup.cs using AutoMapper; using Microsoft.Owin; using Owin; using SaaS.Api.Models.Oauth; using SaaS.Api.Models.Products; using SaaS.Data.Entities.View; using System; using System.Configuration; using System.Globalization; using System.Net; using System.Web.Http; [assembly: OwinStartup(typeof(SaaS.Api.Admin.Startup))] namespace SaaS.Api.Admin { public partial class Startup { public void Configuration(IAppBuilder app) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); ConfigureOAuth(app); var config = new HttpConfiguration(); WebApiConfig.Register(config); app.Map("/api", inner => { inner.UseWebApi(config); }); Mapper.Initialize(cfg => { cfg.CreateMap<ViewAccountProduct, AccountProductViewModel>(); cfg.CreateMap<ViewAccountProductModule, AccountProductModuleModel>(); cfg.CreateMap<ViewAccountDetails, AccountDetailsViewModel>(); cfg.CreateMap<AccountDetailsViewModel, ViewAccountDetails>(); cfg.CreateMap<RegisterViewModel, ViewAccountDetails>(); cfg.CreateMap<ViewUpgradeProduct, UpgradeProductViewModel>(); cfg.CreateMap<ViewOwnerProduct, OwnerProductViewModel>(); }); } } public sealed class AppSettings : IAppSettings { public AppSettingsOauth Oauth { get; private set; } public AppSettingsUpclick Upclick { get; private set; } public Uri DownloadLink { get; private set; } public AppSettings() { Oauth = new AppSettingsOauth(Setting<string>("oauth:resetPassword")); Upclick = new AppSettingsUpclick(Setting<string>("upclick:merchantLogin"), Setting<string>("upclick:merchantPassword")); DownloadLink = new Uri(Setting<string>("downloadLink")); } private static T Setting<T>(string name) { string value = ConfigurationManager.AppSettings[name]; return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture); } } public class AppSettingsUpclick { public readonly string MerchantLogin; public readonly string MerchantPassword; public AppSettingsUpclick(string merchantLogin, string merchantPassword) { MerchantLogin = merchantLogin; MerchantPassword = <PASSWORD>; } } public interface IAppSettings { Uri DownloadLink { get; } AppSettingsOauth Oauth { get; } AppSettingsUpclick Upclick { get; } } public class AppSettingsOauth { public AppSettingsOauth(string resetPassword) { ResetPassword = new Uri(resetPassword); } public readonly Uri ResetPassword; } }<file_sep>/Shared/SaaS.Mailer/Models/CreatePasswordNotification.cs using System.Xml.Serialization; namespace SaaS.Mailer.Models { [XmlRoot("xml")] public class CreatePasswordNotification : Notification { public CreatePasswordNotification() { } public CreatePasswordNotification(Notification user) : base(user) { } [XmlElement("createPasswordLink")] public string CreatePasswordLink { get; set; } } }<file_sep>/Shared/SaaS.Api.Models/Nps/NpsViewModel.cs using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Nps { public class NpsViewModel { [MaxLength(128)] public string Questioner { get; set; } [Required, MaxLength(100)] public string ClientName { get; set; } [MaxLength(20)] public string ClientVersion { get; set; } [Range(0, 10)] public byte Rating { get; set; } [Range(0, 5)] public byte? RatingUsage { get; set; } [MaxLength(1000)] public string Comment { get; set; } } }<file_sep>/Shared/SaaS.Identity/AuthRepository/AuthRepository.Client.cs using SaaS.Data.Entities.Oauth; using System.Collections.Generic; namespace SaaS.Identity { public partial class AuthRepository { public List<Client> ClientsGet() { return _context.ClientsGet(); } } }<file_sep>/Shared/SaaS.Api.Client/SaaSApiOauthService.SignIn.cs using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace SaaS.Api.Client { public partial class SaaSApiOauthService { private StringBuilder GrantTypePassword() { var builder = new StringBuilder("grant_type=password"); builder.AppendFormat("&client_id={0}", _clientId); builder.AppendFormat("&client_secret={0}", _clientSecret); return builder; } private async Task<SignInModel> _SignInAsync(StringBuilder data, string uri) { using (var client = CreateHttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); var request = new HttpRequestMessage(HttpMethod.Post, uri); request.Content = new StringContent(data.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); SaaSApiToken token = await response.Content.ReadAsAsync<SaaSApiToken>(); return new SignInModel(token); } return new SignInModel(SignInStatus.InvalidGrant); } } public async Task<SignInModel> SignInAsync(string userName, string password) { userName = Uri.EscapeDataString(userName); password = Uri.EscapeDataString(password); var data = GrantTypePassword(); data.AppendFormat("&username={0}", userName); data.AppendFormat("&password={0}", password); return await _SignInAsync(data, "api/token"); } public async Task<SignInModel> SignInAsync(string token) { token = Uri.EscapeDataString(token); var data = GrantTypePassword(); data.AppendFormat("&token={0}", token); return await _SignInAsync(data, "api/token"); } } //+ grant_type(string, required) - Should be 'password'; //+ username(string, required) - Email; //+ password(string, required, minLength = 6, maxLength = 100) - Password; //+ client_id(string, required) - Should be `sodapdfdesktopapp`; //+ client_secret(string, required) - Should be `<KEY>`. public enum SignInStatus : byte { Ok, InvalidGrant } public class SignInModel { public readonly SignInStatus Status = SignInStatus.Ok; public readonly SaaSApiToken Token = null; public SignInModel(SaaSApiToken token) { Token = token; } public SignInModel(SignInStatus status) { Status = status; } public SignInModel(SignInStatus status, SaaSApiToken token) { Status = status; Token = token; } } } <file_sep>/Shared/SaaS.Repository.Pattern.EF6/UnitOfWork.cs using Microsoft.Practices.ServiceLocation; using SaaS.Repository.Pattern.Repositories; using SaaS.Repository.Pattern.UnitOfWork; using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Threading.Tasks; namespace SaaS.Repository.Pattern.EF6 { public class UnitOfWork : IUnitOfWorkAsync { #region Private Fields private DbContext _dataContext; private bool _disposed; //private ObjectContext _objectContext; //private DbTransaction _transaction; private Dictionary<string, dynamic> _repositories; #endregion Private Fields #region Constuctor/Dispose public UnitOfWork(DbContext dataContext) { _dataContext = dataContext; _repositories = new Dictionary<string, dynamic>(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { // free other managed objects that implement // IDisposable only //try //{ // if (_objectContext != null && _objectContext.Connection.State == ConnectionState.Open) // { // _objectContext.Connection.Close(); // } //} //catch (ObjectDisposedException) //{ // // do nothing, the objectContext has already been disposed //} if (_dataContext != null) { _dataContext.Dispose(); _dataContext = null; } } // release any unmanaged objects // set the object references to null _disposed = true; } #endregion Constuctor/Dispose public async Task<int> SaveChangesAsync() { return await _dataContext.SaveChangesAsync(); } public Task<int> SaveChangesAsync(System.Threading.CancellationToken cancellationToken) { return _dataContext.SaveChangesAsync(cancellationToken); } public Repositories.IRepositoryAsync<TEntity> RepositoryAsync<TEntity>() where TEntity : class { if (ServiceLocator.IsLocationProviderSet) { return ServiceLocator.Current.GetInstance<IRepositoryAsync<TEntity>>(); } if (_repositories == null) { _repositories = new Dictionary<string, dynamic>(); } var type = typeof(TEntity).Name; if (_repositories.ContainsKey(type)) { return (IRepositoryAsync<TEntity>)_repositories[type]; } var repositoryType = typeof(Repository<>); _repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), _dataContext, this)); return _repositories[type]; } public int SaveChanges() { return _dataContext.SaveChanges(); } public Repositories.IRepository<TEntity> Repository<TEntity>() where TEntity : class { if (ServiceLocator.IsLocationProviderSet) { return ServiceLocator.Current.GetInstance<IRepository<TEntity>>(); } return RepositoryAsync<TEntity>(); } public void BeginTransaction(System.Data.IsolationLevel isolationLevel = IsolationLevel.Unspecified) { throw new NotImplementedException(); } public bool Commit() { throw new NotImplementedException(); } public void Rollback() { throw new NotImplementedException(); } public int ExecuteSqlCommand(string query, params object[] parameters) { return _dataContext.Database.ExecuteSqlCommand(query, parameters); } public async Task<List<T>> ExecuteStoredProcedureAsync<T>(string query, params object[] parameters) { using (var cmd = _dataContext.Database.Connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddRange(parameters); await _dataContext.Database.Connection.OpenAsync(); var reader = await cmd.ExecuteReaderAsync(); var list = ((IObjectContextAdapter)_dataContext).ObjectContext.Translate<T>(reader).ToList(); _dataContext.Database.Connection.Close(); return list; } } public async Task<Tuple<List<T1>, List<T2>>> ExecuteStoredProcedureAsync<T1, T2>(string query, params object[] parameters) { //https://msdn.microsoft.com/en-us/data/jj691402.aspx using (var cmd = _dataContext.Database.Connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddRange(parameters); await _dataContext.Database.Connection.OpenAsync(); var reader = await cmd.ExecuteReaderAsync(); var list1 = ((IObjectContextAdapter)_dataContext).ObjectContext.Translate<T1>(reader).ToList(); reader.NextResult(); var list2 = ((IObjectContextAdapter)_dataContext).ObjectContext.Translate<T2>(reader).ToList(); _dataContext.Database.Connection.Close(); return new Tuple<List<T1>, List<T2>>(list1, list2); } } } }<file_sep>/Web.Api/SaaS.Zendesk/src/js/controllers/account/account.js angular.module('app.controllers') .controller('accountController', ['$rootScope', '$q', '$scope', '$state', '$api', '$zendesk', ($rootScope, $q, $scope, $state, $api, $zendesk) => { $scope.model = { accountId: null, account: null }; var _getAccount = () => { var params = $state.params; var deferred = $q.defer(); if (params.accountId) { $api.account.get({ accountId: params.accountId }) .then( deferred.resolve, () => { deferred.reject({ state: 'account/not-found', params: { accountId: params.accountId } }); }); } else { $zendesk.get(['ticket.requester']) .then( (response) => { var requester = response['ticket.requester']; if (!requester.email) deferred.reject({ state: 'account/email-is-empty' }); else { $api.account.get({ email: requester.email }) .then( deferred.resolve, () => { deferred.reject({ state: 'account/not-found', params: { email: requester.email } }); }); } }, () => { deferred.reject({ state: 'ticket/requester-email-is-empty', }); }); } return deferred.promise; }; $rootScope.$broadcast('event:spinner-show'); _getAccount() .then((json) => { $scope.model.account = json; $scope.model.accountId = json.id; }, (error) => { $state.go(error.state, error.params); }) .finally(() => { $rootScope.$broadcast('event:spinner-hide'); }); }]);<file_sep>/WinService/SaaS.WinService.Core/BaseScheduler.cs using NLog; using System; using System.Timers; namespace SaaS.WinService.Core { public abstract class BaseScheduler { protected delegate void EmptyEventHandler(); protected delegate void ErrorEventHandler(Exception exc); protected ThreadPool _queue = new ThreadPool(1); protected Logger _logger = LogManager.GetCurrentClassLogger(); protected void Do(Timer timer, EmptyEventHandler handler) { timer.Stop(); System.Threading.ThreadPool.QueueUserWorkItem(state => { object[] data = (object[])state; try { handler(); } catch (Exception exc) { _logger.Error(exc); } finally { ((Timer)data[0]).Start(); } }, new object[] { timer }); } public abstract void Start(); } } <file_sep>/Web.Api/SaaS.Api.Sign/Controllers/Api/ESign20/BaseApiController.cs using eSign20.Api.Client; using Microsoft.AspNet.Identity; using Newtonsoft.Json.Linq; using SaaS.Api.Core; using SaaS.Data.Entities.eSign; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View; using SaaS.Identity; using System; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Sign.Controllers.Api.eSign20 { public abstract class BaseApiController : ApiController { protected readonly IAuthRepository _auth; protected readonly IeSignRepository _eSign; protected readonly IAuthProductRepository _authProduct; protected BaseApiController() { _auth = new AuthRepository(); _eSign = new eSignRepository(); _authProduct = new AuthProductRepository(); } protected virtual string ApiRoot { get { throw new NotImplementedException(); } } internal virtual eSignClient eSignClient { get { return eSignClient.eSign20; } } [DebuggerStepThrough] protected string Format(string format = null, params object[] @params) { var builder = new StringBuilder(ApiRoot); if (!object.Equals(format, null)) builder.AppendFormat(format, @params); return builder.ToString(); } protected async Task<SessionToken> GetSessionToken() { var accessToken = Request.Headers.Authorization.Parameter; var ticket = Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(accessToken); var sessionId = Guid.Parse(ticket.Properties.Dictionary["session"]); return await _auth.SessionTokenGetAsync(sessionId); } private ulong GetContentLength(string header) { ulong length = 0; if (!object.Equals(Request.Headers, null) && Request.Headers.Contains(header)) { var values = Request.Headers.GetValues(header); var fileContentLength = values.FirstOrDefault(e => !string.IsNullOrEmpty(e)); ulong.TryParse(fileContentLength, out length); } return length; } protected ulong GetFileContentLength() { return GetContentLength("File-Content-Length"); } protected ulong GetRecipientsCount(string json) { var jObject = JObject.Parse(json); var jRecipients = jObject.SelectToken("$.recipients", false); var array = jRecipients as JArray; if (object.Equals(array, null)) return GetContentLength("Recipient-Content-Length"); return (ulong)array.Count; } protected HttpResponseMessage IncludeHeaders(HttpResponseMessage response, int? allowed = null, int? used = null) { if (allowed.HasValue) response.Headers.Add("Allowed", allowed.ToString()); if (used.HasValue) response.Headers.Add("Used", used.ToString()); return response; } protected HttpResponseMessage PaymentRequired(string errorDescription, int? allowed = null, int? used = null) { var response = Request.CreateResponse<dynamic>(HttpStatusCode.PaymentRequired, new { error = "invalid_request", error_description = errorDescription }); IncludeHeaders(response, allowed, used); return response; } protected async Task<HttpResponseMessage> HttpProxy(HttpRequestMessage request, string method, CancellationToken cancellationToken) { const string pref = "/api-esign20"; if (!string.IsNullOrEmpty(method) && method.StartsWith(pref, StringComparison.InvariantCultureIgnoreCase)) method = method.Remove(0, pref.Length); try { var accountId = Guid.Parse(User.Identity.GetUserId()); var entity = await _eSign.eSignApiKeyGetAsync(accountId, eSignClient); var singIn = new SignInResult(object.Equals(entity, null) ? null : entity.Key); if (singIn.IsEmptyApiKey) { singIn = await SignIn(request, accountId, cancellationToken); if (!singIn.IsSuccessStatusCode) return singIn.Response; } using (var client = new eSign20Client(request, singIn.ApiKey)) { var response = await client.SendAsync(method, cancellationToken); if (response.StatusCode != HttpStatusCode.Unauthorized) return response; } //TODO if revoke singIn = await SignIn(request, accountId, cancellationToken); if (!singIn.IsSuccessStatusCode) return singIn.Response; using (var client = new eSign20Client(request, singIn.ApiKey)) { var response = await client.SendAsync(method, cancellationToken); if (response.StatusCode == HttpStatusCode.Unauthorized) response.StatusCode = HttpStatusCode.ProxyAuthenticationRequired; return response; } } catch (Exception exc) { return request.CreateExceptionResponse(exc); } } private async Task<SignInResult> SignIn(HttpRequestMessage request, Guid accountId, CancellationToken cancellationToken) { var account = await _auth.AccountGetAsync(accountId); var response = await eSign20Client.SenderApiKeyAsync(account.Email, cancellationToken); if (!response.IsSuccessStatusCode) return new SignInResult(response); var jObject = await response.Content.ReadAsAsync<JObject>(); var apiKey = jObject.Value<string>("apiKey"); if (string.IsNullOrEmpty(apiKey)) { return new SignInResult(request.CreateResponse(HttpStatusCode.BadRequest, new { error = "invalid_request", error_description = "Api key is empty." })); } await _eSign.eSignApiKeySetAsync(account.Id, account.Email, eSignClient, apiKey); return new SignInResult(apiKey); } protected override void Dispose(bool disposing) { _auth.Dispose(); _eSign.Dispose(); _authProduct.Dispose(); base.Dispose(disposing); } private class SignInResult { public SignInResult(HttpResponseMessage response) : this(response, null) { } public SignInResult(string apiKey) : this(new HttpResponseMessage(HttpStatusCode.OK), apiKey) { } public SignInResult(HttpResponseMessage response, string apiKey) { Response = response; ApiKey = apiKey; } internal HttpResponseMessage Response { get; private set; } internal string ApiKey { get; private set; } internal bool IsSuccessStatusCode { get { return Response.IsSuccessStatusCode; } } internal bool IsEmptyApiKey { get { return string.IsNullOrEmpty(ApiKey); } } } } }<file_sep>/Web.Api/SaaS.UI.Admin/Controllers/UserController.cs using System.Web.Mvc; namespace SaaS.UI.Admin.Controllers { [Authorize] public class UserController : Controller { [AllowAnonymous] public ActionResult Login() { return View(); } public ActionResult ChangePassword() { return View(); } } }<file_sep>/Shared/eSign20.Api.Client/eSign20Client.cs using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace eSign20.Api.Client { public class eSign20Client : IDisposable { private eSign20HttpClient _eSign20HttpClient; public eSign20Client() { _eSign20HttpClient = new eSign20HttpClient(); } public eSign20Client(HttpRequestMessage request, string apiKey) { _eSign20HttpClient = new eSign20HttpClient(request, apiKey); } public async Task<HttpResponseMessage> SendAsync(string requestUri, CancellationToken cancellationToken) { return await _eSign20HttpClient.SendAsync(requestUri, cancellationToken); } internal static async Task<HttpResponseMessage> AccountSendersAsync(string email, CancellationToken cancellationToken) { using (var client = new eSign20HttpClient()) return await client.PostAsJsonAsync<dynamic>("api/v1/account/senders/", new { email = email }, cancellationToken); } public static async Task<HttpResponseMessage> AccountSendersChangeEmailAsync(IEnumerable<string> emails) { using (var client = new eSign20HttpClient()) return await client.PostAsJsonAsync<dynamic>("api/v1/account/senders/group/", new { emails = emails }); } public static async Task<HttpResponseMessage> SenderApiKeyAsync(string email, CancellationToken cancellationToken) { var response = await AccountSendersAsync(email, cancellationToken); if (!response.IsSuccessStatusCode) return response; var sender = await response.Content.ReadAsAsync<JObject>(); using (var client = new eSign20HttpClient()) return await client.GetAsync(string.Format("api/v1/account/senders/{0}/apiKey/", sender.Value<string>("id"))); } public void Dispose() { if (!object.Equals(_eSign20HttpClient, null)) _eSign20HttpClient.Dispose(); } } } <file_sep>/Web.Api/SaaS.Zendesk/tasks/zat.watch.js const gulp = require('gulp'); gulp.task('zat.watch', gulp.parallel( 'zat.css:watch', 'zat.html:watch', 'zat.js:watch')); <file_sep>/Shared/SaaS.ModuleFeatures/Model/Feature.cs using System; namespace SaaS.ModuleFeatures.Model { internal class Feature { public string Name { get; set; } public string Version { get; set; } public Version GetVersion() { Version version; if (!System.Version.TryParse(Version, out version)) return null; return version; } } }<file_sep>/Shared/Upclick.Api.Client/UpclickClient.Tools.cs using Newtonsoft.Json; using System.Collections.Generic; using System.Collections.Specialized; using System.Net.Http; using System.Threading.Tasks; namespace Upclick.Api.Client { public partial class UpclickClient { private async Task<HttpResponseMessage> _XChangeRate(string isocode = null) { return await _upclickHttpClient.GetAsync("tools/xchangerate", string.IsNullOrEmpty(isocode) ? null : new NameValueCollection() { { "isocode", isocode } }); } public async Task<List<XChange>> XChangeRate() { HttpResponseMessage response = await _XChangeRate(); var json = await response.Content.ReadAsStringAsync(); var root = await response.Content.ReadAsAsync<ToolsXChangeRateRoot>(); if (!object.Equals(root, null) && !object.Equals(root.XChangeRate, null)) return root.XChangeRate.XChanges; return null; } } public class ToolsXChangeRateRoot { [JsonProperty(PropertyName = "tools_xchangerate")] public ToolsXChangeRate XChangeRate { get; set; } } public class ToolsXChangeRate { [JsonProperty(PropertyName = "xchange")] [JsonConverter(typeof(SingleOrArrayConverter<XChange>))] public List<XChange> XChanges { get; set; } } public class XChange { [JsonProperty(PropertyName = "isoCode")] public string IsoCode { get; set; } [JsonProperty(PropertyName = "usRate")] public decimal UsRate { get; set; } [JsonProperty(PropertyName = "name")] public string Name { get; set; } [JsonProperty(PropertyName = "symbol")] public string Symbol { get; set; } } } <file_sep>/Shared/SaaS.Common/Utils/TimeHelper.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SaaS.Common.Utils { public static class TimeHelper { const int SecondsInMinute = 60; const long TicksInSecond = 10000000; const long TicksInMinute = TicksInSecond * SecondsInMinute; static readonly DateTime UnixTimeBegining = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); /// <summary> /// get Epoch time; /// Epoch time is a Unix convention - the number of seconds elapsed since Jan 1, 1970 /// </summary> /// <returns></returns> public static int GetEpochTime() { return (int)(DateTime.UtcNow - UnixTimeBegining).TotalSeconds; } /// <summary> /// get Epoch time; /// Epoch time is a Unix convention - the number of seconds elapsed since Jan 1, 1970 /// </summary> /// <param name="time"></param> /// <returns></returns> public static int GetEpochTime(this DateTime time) { return (int)(time.ToUniversalTime() - UnixTimeBegining).TotalSeconds; } /// <summary> /// convert unix time to utc datetime /// </summary> /// <param name="unixTime">Epoch time is a Unix convention - the number of seconds elapsed since Jan 1, 1970</param> /// <returns>return utc datetime</returns> public static DateTime FromEpochTime(this long unixTime) { return UnixTimeBegining.AddSeconds(unixTime); } /// <summary> /// convert UTC to relative time /// </summary> /// <param name="dateTimeUtc">utc time</param> /// <param name="timeZoneOffset">time zone offset in minutes</param> /// <returns>return point in time relative to UTC</returns> public static DateTimeOffset UtcToLocalTime(this DateTime dateTimeUtc, int timeZoneOffset) { if (dateTimeUtc.Kind != DateTimeKind.Utc) throw new Exception("Utc datetime is expected."); var offsetTimespan = new TimeSpan(timeZoneOffset * TicksInMinute); return new DateTimeOffset(dateTimeUtc).ToOffset(-offsetTimespan); } } } <file_sep>/Web.Api/SaaS.Api.Admin/Controllers/Api/AccountController.External.cs using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Admin.Controllers.Api { public partial class AccountController : SaaSApiController { [HttpGet, Route("{accountId:guid}/external/session-token")] public async Task<IHttpActionResult> AccountExternalSessionToken(Guid accountId) { try { return Ok(await _auth.SessionTokenExternalHistoriesAsync(accountId)); } catch (Exception exc) { return ErrorContent(exc); } } } }<file_sep>/saas.api_reference.md SaaS API Reference ========================= This document describes SaaS API in detail. General notes ------------- ### UTF-8 encoding Every string that passed to and from SaaS API needs to be UTF-8 encoded. ### Date/Time format SaaS API uses ISO-8601 date/time format "yyyy-MM-ddThh:mm:sszzz". For example, 12:30 p.m. 27 March 2015 in Kyiv should be "2015-03-27T12:30:00+02:00" ### <b id="authorization">Authorization</b> If a method has to have '<b style="color:red">Authorization</b>' header, you have to add one to request. ``` { "Authorization":"bearer " + access_token } ``` - access_token from SignIn In case when your access_token is expired (you will get 401 error), you have to renew access_token and refresh token: + **POST `api/token` ** * **Parameters** + grant_type (string, required) - Should be 'refresh_token'; + refresh_token (string, required) - refresh_token from previous SignIn; + client_id (string, required) - Can be: `sodapdfdesktopapp`, `saas` or `sodapdf`; + client_secret (string, required) - Should be `<KEY>`; + client_version (string, optional) - Can be: `9.1.0.0`; + machineKey (guid, required if scope == `editor`); + isAutogeneratedMachineKey (bool, required if scope == `editor`); + motherboardKey (string, required if scope == `editor`, maxLength = 128); + physicalMac (string, required if scope == `editor`); + pcName (string, optional); + scope (string, optional) - Can be: `editor`, `webeditor` or empty; For Soda PDF Desktop please use `editor`, for Soda PDF SaaS - `webeditor`. <span style="color:red">client_secret and client_secret are not real. Only for testing.</span> * **Request Body** (application/x-www-form-urlencoded) ``` grant_type=password& refresh_token="<PASSWORD>"& client_id=sodapdfdesktopapp& client_secret=<KEY> client_version=9.1.0.0=& machineKey=4d498ce0-846d-11e0-993f-f46d04483013& isAutogeneratedMachineKey=True& motherboardKey=110008970002956& physicalMac=F4:6D:04:48:30:13& pcName=lobster scope=editor ``` * **Returns** - <span style="color:green">200</span> (application/json). ``` { "access_token":"thI<PASSWORD>", "token_type":"Bearer", "expires_in":8999, "refresh_token":"<PASSWORD>", "email":"<EMAIL>", "firstName":"Ahmed", "lastName":"Kozlikov", "status": 1 "issued":"2015-12-18T02:21:09-07:00", "expires":"2015-12-18T02:21:24-07:00", "externalClient":"google" } ``` - access_token (string), refresh_token (string) - On success, the response will contain an access token and refresh token. The access token will be valid for a short time (15 minutes), and the refresh token will be valid for 1 year. The refresh token can be used to get a new access token. The refresh token in this response should replace other refresh tokens you may have stored previously; - expires_in (uint) - Lifetime of access token; - email (string) - User's- email address; - firstName (string) - User's first name; - lastName (string) - User's last name; - status (ulong) - mask ({ none: 0, isActivated: 1, isAnonymous: 2, isBusiness: 4 }) - issued (datetime) - Date when access token has been issued; - expires (datetime) - Date when access token will be expired; - externalClient (string) - External client's name; If you caught response headers like "Product-IsExpired" - in this case product is expired; * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error":"invalid_grant" } ``` If you caught response headers like "Refresh-Token-Expired" - in this case refresh_token could be expired ``` { "error":"invalid_grant", "error_description": "Unknown user." } ``` ``` { "error":"invalid_grant", "error_description": "The email or password is incorrect." } ``` ``` { "error":"invalid_grant", "error_description": "You should create an account." } ``` ``` { "error":"invalid_grant", "error_description": "You cannot sign in with this email as it is no longer associated with your account." } ``` ``` { "error":"invalid_grant", "error_description": "You should sign in with google." } ``` ``` { "error":"invalid_grant", "error_description": "You should sign in with facebook." } ``` ``` { "error":"invalid_grant", "error_description": "You should sign in with microsoft." } ``` ``` { "error":"invalid_grant", "error_description": "System is null or empty." } ``` ``` { "error":"invalid_clientId", "error_description": "ClientId should be sent." } ``` ``` { "error":"invalid_clientId", "error_description": "This client is not registered in the system." } ``` ``` { "error":"invalid_clientId", "error_description": "Client is inactive." } ``` ``` { "error":"invalid_clientSecret", "error_description": "Client secret should be sent." } ``` ``` { "error":"invalid_clientSecret", "error_description": "Client secret is invalid." } ``` -------------- ### Upgrade access token + **POST `api/token/{id:guid}/` ** + id (guid) - Identifier of product; * **Request Headers** <a href="#authorization">Authorization</a><b style="color:red">*</b> * **Returns** - <span style="color:green">200</span> SUCCESS. ``` see description for `api/token` + modules : [ { name : "convert" } ... ] ``` -modules (array) - List of modules (unioun); -modules::name (string) - Module name; -modules::allowed (uint?) - Number of allowed uses (unlimited if null); -modules::used (uint) - Number of uses; * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description": "..." } ``` ``` { "error": "invalid_grant", "error_description": "This account is not activated." } ``` - <span style="color:red">401</span> (application/json). ``` { "error": "invalid_grant", "error_description": "Authorization has been denied for this request." } ``` - <span style="color:red">404</span> ``` { "error": "invalid_grant", "error_description": "User is not exists." } ``` ``` { "error": "invalid_grant", "error_description": "Product is not exists or is disabled." } ``` - <span style="color:red">409</span> (application/json). ``` { "error": "invalid_grant", "error_description": "You are logged into too many devices." } ``` ``` { "error": "invalid_grant", "error_description": "Your license is currently associated with another device." } ``` -------------- ### Logout + **DELETE `api/token/{id:guid}/` ** + id (guid) - Identifier of session (If you need logout from current session - pass refresh token); * **Request Headers** <a href="#authorization">Authorization</a><b style="color:red">*</b> * **Returns** - <span style="color:green">200</span> SUCCESS. * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description": "..." } ``` - <span style="color:red">401</span> (application/json). ``` { "error": "invalid_grant", "error_description": "Authorization has been denied for this request." } ``` -------------- Oauth (https://oauth.sodapdf.com/) -------------- ### Register + **POST `/api/account/register` ** * **Parameters** + firstName (string, maxLength = 300) - User's first name; + lastName (string, maxLength = 300) - User's last name; + email (string, required) - User's email; + password (string, required, minLength = 6, maxLength = 100) - User's password. + source (string, optional, maxLength = 128) - Source. * **Request Body** (application/json) ``` { "firstName" : 'Ahmed' "lastName" : 'Kozlikov', "email" : '<EMAIL>', "password" : '<PASSWORD>', "source" : 'sodapdf_8.0.44.25306' } ``` * **Returns** - <span style="color:green">200</span> SUCCESS. * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` ``` { "error": "invalid_request", "error_description":"Model is required." } ``` ``` { "error": "invalid_request", "error_description":"The Email field is required." } ``` ``` { "error": "invalid_request", "error_description":"Enter a valid email address." } ``` ``` { "error": "invalid_request", "error_description":"The Password field is required." } ``` ``` { "error": "invalid_request", "error_description":"To be able to create a new account you have to sign out from the current account." } ``` - <span style="color:red">409</span> ``` { "error": "invalid_grant", "error_description":"User already exists." } ``` { "error": "invalid_grant", "error_description":"You should sign in with [microsoft/google/facebook]." } -------------- + **POST `/api/account/register-anonymous` ** * **Parameters** + password (string, required, minLength = 6, maxLength = 100) - User's password. * **Request Body** (application/json) ``` { "password" : '<PASSWORD>' } ``` * **Returns** - <span style="color:green">200</span> SUCCESS. * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` ``` { "error": "invalid_request", "error_description":"Model is required." } ``` ``` { "error": "invalid_request", "error_description":"The Password field is required." } ``` ``` { "error": "invalid_request", "error_description":"To be able to create a new account you have to sign out from the current account." } ``` -------------- ### Send activation email + **POST `/api/account/send-activation-email` ** * **Parameters** + email (string, required) - User's email. * **Request Body** (application/json) ``` { "email" : '<EMAIL>' } ``` * **Returns** - <span style="color:green">200</span> SUCCESS. * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` ``` { "error": "invalid_request", "error_description":"Model is required." } ``` ``` { "error": "invalid_request", "error_description":"The Email field is required." } ``` ``` { "error": "invalid_request", "error_description":"Enter a valid email address." } ``` - <span style="color:red">404</span> ``` { "error": "invalid_grant", "error_description": "User is not exists." } ``` -------------- ### Change password + **POST `api/account/change-password` ** * **Parameters** + oldPassword (string, required, minLength = 6, maxLength = 100) - User's old password; + newPassword (string, required, minLength = 6, maxLength = 100) - User's new password; * **Request Headers** <a href="#authorization">Authorization</a><b style="color:red">*</b> * **Request Body** (application/json) ``` { "oldPassword" : '<PASSWORD>' "newPassword" : '<PASSWORD>' } ``` * **Returns** - <span style="color:green">200</span> SUCCESS. * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` ``` { "error": "invalid_request", "error_description":"Model is required." } ``` ``` { "error": "invalid_request", "error_description":"The Password field is required." } ``` ``` { "error": "invalid_request", "error_description":"Incorrect password." } ``` - <span style="color:red">401</span> (application/json). ``` { "error": "invalid_grant", "error_description": "Authorization has been denied for this request." } ``` - <span style="color:red">404</span> ``` { "error": "invalid_grant", "error_description": "User is not exists." } ``` -------------- ### Recover password + **POST `api/account/recover-password` ** * **Parameters** + email (string, required) - User's email; * **Request Body** (application/json) ``` { "email" : '<EMAIL>' } ``` * **Returns** - <span style="color:green">200</span> SUCCESS. * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` ``` { "error": "invalid_request", "error_description":"Model is required." } ``` ``` { "error": "invalid_request", "error_description":"The Email field is required." } ``` ``` { "error": "invalid_request", "error_description":"Enter a valid email address." } ``` - <span style="color:red">401</span> (application/json). ``` { "error": "invalid_grant", "error_description": "Authorization has been denied for this request." } ``` - <span style="color:red">404</span> ``` { "error": "invalid_grant", "error_description": "User is not exists." } ``` -------------- ### Get account details + **Get `api/account/details` ** * **Request Headers** <a href="#authorization">Authorization</a><b style="color:red">*</b> * **Returns** - <span style="color:green">200</span> SUCCESS. ``` { "id": "7dbd6a51-ef43-4a7a-88a1-43f4c66a6b9a", "email": "<EMAIL>", "firstName":"Veniamin", "lastName":"Suslikov", "status": 1, "phone" : "nokia", "phoneESign" : "nokia e-sign", "company" : "Suslikov Inc", "occupation" : "moydodyr", "country" : "ua", "language" : "ua", "address1" : "kishlac 1", "address2" : "kishlac 2", "city" : "mongoloid city", "postalCode" : "F3R R4W", "eSignClient" : 0 (0 - signLive, 1 - signNow) } ``` - id (guid)- User's id; - email (string)- User's email; - firstName (string) - User's first name; - lastName (string) - User's last name; - status (ulong) - mask ({ none: 0, isActivated: 1, isAnonymous: 2, isBusiness: 4 }) - phone (string) - User's phone number; - phoneESign (string) - User's phone number(for e-sign); - company (string) - User's company; - occupation (string) - User's occupation; - country (string) - User's country(iso2 format); - language (string) - User's language(iso2 format); - address1 (string) - User's address 1; - address2 (string) - User's address 2; - city (string) - User's city; - postalCode (string) - User's postal code; - state (string) - User's state; * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` - <span style="color:red">401</span> (application/json). ``` { "error": "invalid_grant", "error_description": "Authorization has been denied for this request." } ``` - <span style="color:red">404</span> ``` { "error": "invalid_grant", "error_description": "User is not exists." } ``` -------------- ### Set account details + **POST `api/account/details` ** + `IF YOU DON'T WANT TO UPDATE SOME FIELDS - JUST DON'T PASS THEM TO REQUEST` * **Parameters** + firstName (string, maxLength = 300) - User's first name; + lastName (string, maxLength = 300) - User's last name; + phone (string, minLength = 0, maxLength = 20) - User's phone number; + phoneESign (string, minLength = 0, maxLength = 20) - User's phone number(for e-sign); + company (string, minLength = 0, maxLength = 128) - User's company; + occupation (string, minLength = 0, maxLength = 128) - User's occupation; + country (string, minLength = 2, maxLength = 2) - User's country(iso2 format); + language (string, minLength = 2, maxLength = 2) - User's language(iso2 format); + address1 (string, minLength = 0, maxLength = 128) - User's address 1; + address2 (string, minLength = 0, maxLength = 128) - User's address 2; + city (string, minLength = 0, maxLength = 128) - User's city; + postalCode (string, minLength = 0, maxLength = 32) - User's postal code; + state (string, minLength = 0, maxLength = 128) - User's state; * **Request Headers** <a href="#authorization">Authorization</a><b style="color:red">*</b> * **Request Body** (application/json) ``` { "firstName" : 'Mustafa' "lastName" : 'Oslikov', "phone" : 'nokia' } ``` * **Returns** - <span style="color:green">200</span> SUCCESS. * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` ``` { "error": "invalid_request", "error_description":"Model is required." } ``` - <span style="color:red">401</span> (application/json). ``` { "error": "invalid_grant", "error_description": "Authorization has been denied for this request." } ``` - <span style="color:red">404</span> ``` { "error": "invalid_grant", "error_description": "User is not exists." } ``` -------------- -------------- ### Get account (pre-sign-up check) + **Get `api/account/` ** * **Returns** - <span style="color:green">200</span> SUCCESS. ``` { "email": "<EMAIL>", "firstName":"Veniamin", "lastName":"Suslikov", "status": 1, "optin" : [true/false], "external":"[microsoft/google/facebook]" } Attention!!! property "external" is added only if account was created thougn 3rd party provider. * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` - <span style="color:red">404</span> ``` { "error": "invalid_grant", "error_description": "User is not exists." } ``` -------------- ### Get account products + **Get `api/account/products` ** * **Request Headers** <a href="#authorization">Authorization</a><b style="color:red">*</b> * **Returns** - <span style="color:green">200</span> SUCCESS. ``` [ { "id" : "0d446dee-78b0-44b1-9d90-28083ddc07f0", "name" : "Trial Subscription", "unitName" : "soda-trial-2-week", "purchaseDate" : "2016-04-22T07:50:14-04:00", "endDate" : "2016-04-22T07:50:14-04:00", "nextRebillDate" : "2017-04-22T07:50:14-04:00", "expiresIn" : 36589, "status" : 1, "order": 0, "modules" : [ {"name" : "view"}, {"name" : "convert"}, ... { "name" : "e-sign", "allowed" : 1, "used" : 1 } ] } ... ] ``` - id (guid)- Identifier of product; - name (string) - Product name; - unitName (string) - Product unit name; - plan (string) - Product plan; - purchaseDate (datetime) - Date when product was purchased; - endDate (datetime?) - Date when product will be expired; - nextRebillDate (datetime?) - Date when product will be rebilled; - сreditCardExpiryDate (datetime?) - Date when credit card will be expired; - expiresIn (ulong?) - Amount of seconds when product will be expired; - status (ulong) - mask ({ none: 0, isDisabled: 1, isExpired: 2, isTrial: 4, isFree: 8, isMinor: 16, isActive: 32, isPPC: 64, isUpgradable: 128, isNew: 256, isPaymentFailed = 512, isRenewal = 1024, isOwner = 1024, isNotAbleToRenewCreditCartExpired = 4096 }); - order(ushort) - Order(for UI); -modules (array) - List of modules; -modules::name (string) - Module name; -modules::allowed (uint?) - Number of allowed uses (unlimited if null); -modules::used (uint) - Number of uses; * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` - <span style="color:red">401</span> (application/json). ``` { "error": "invalid_grant", "error_description": "Authorization has been denied for this request." } ``` - <span style="color:red">404</span> ``` { "error": "invalid_grant", "error_description": "User is not exists." } ``` -------------- ### Resume product + **Get `api/account/owner-products/{id:guid}/resume` ** + id (guid) - Identifier of product; * **Request Headers** <a href="#authorization">Authorization</a><b style="color:red">*</b> * **Returns** - <span style="color:green">200</span> SUCCESS. * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` - <span style="color:red">401</span> (application/json). ``` { "error": "invalid_grant", "error_description": "Authorization has been denied for this request." } ``` - <span style="color:red">404</span> ``` { "error": "invalid_grant", "error_description": "Product is not exists or is disabled." } ``` - <span style="color:red">409</span> - if user is not a owner of product. -------------- ### Mask account product as not new + **Delete `api/account/products/{id:guid}/notification` ** + id (guid) - Identifier of product; * **Request Headers** <a href="#authorization">Authorization</a><b style="color:red">*</b> * **Returns** - <span style="color:green">200</span> SUCCESS. * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` - <span style="color:red">401</span> (application/json). ``` { "error": "invalid_grant", "error_description": "Authorization has been denied for this request." } ``` -------------- -------------- ### Get account modules (current session) + **Get `api/account/modules` ** * **Request Headers** <a href="#authorization">Authorization</a><b style="color:red">*</b> * **Returns** - <span style="color:green">200</span> SUCCESS. ``` { "id" : "0d446dee-78b0-44b1-9d90-28083ddc07f0", "email" : <EMAIL>" "modules" : [ {"name" : "view"}, {"name" : "convert"}, ... { "name" : "e-sign", "allowed" : 1, "used" : 1 } ], "moduleFeatures" : [ { "name" : "view", "features" : [ { "name" : "View.DocumentViewRotate" "status" : 4 } ... ], } ] } ``` - id (guid)- Identifier of product; - email (string) - User email; -modules (array) - List of modules; -modules::name (string) - Module name; -modules::allowed (uint?) - Number of allowed uses (unlimited if null); -modules::used (uint) - Number of uses; -moduleFeatures::features::status (ulong) - mask ({ none: 0, isHidden: 1, isUpgradable: 2, isActivated: 4 }) * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` - <span style="color:red">401</span> (application/json). ``` { "error": "invalid_grant", "error_description": "Authorization has been denied for this request." } ``` - <span style="color:red">404</span> ``` { "error": "invalid_grant", "error_description": "Product is not exists or is disabled." } ``` -------------- SaaS E-Sign API Reference ========================= ### Post package + **Post `api/packages` ** * **Request Headers** <a href="#authorization">Authorization</a><b style="color:red">*</b> * **Returns** - <span style="color:green">200</span> SUCCESS. * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` ``` { "error": "invalid_request", "error_description":"Api key is empty." } ``` - <span style="color:red">401</span> (application/json). ``` { "error": "invalid_grant", "error_description": "Authorization has been denied for this request." } ``` - <span style="color:red">402</span> ``` { "error": "invalid_request", "error_description": "User doesn't have enough number of signs." } ``` -------------- SaaS Oauth 2.0 - 3th party logins ========================= ### GET popup + **Get `api/external/login/google/` ** + **Get `api/external/login/facebook/` ** + **Get `api/external/login/microsoft/` ** + state (guid) - Unique id for request; + lang (string) - Language; * **Returns** - <span style="color:green">200</span> SUCCESS. -------------- ### Post package + **Post `api/external/token/` ** * **Parameters** + state (guid, required) - Unique id from prev step `api/external/login/google/`; `api/external/login/facebook/`; `api/external/login/microsoft/`; + grant_type (string, required) - Should be 'password'; + client_id (string, required) - Can be: `sodapdfdesktopapp`, `saas` or `sodapdf`; + client_secret (string, required) - Should be `<KEY>`; + client_version (string, optional) - Can be: `9.1.0.0`; + machineKey (guid, required if scope == `editor`); + isAutogeneratedMachineKey (bool, required if scope == `editor`); + motherboardKey (string, required if scope == `editor`, maxLength = 128); + physicalMac (string, required if scope == `editor`); + pcName (string, optional); + scope (string, optional) - Can be: `editor`, `webeditor` or empty; For Soda PDF Desktop please use `editor`, for Soda PDF SaaS - `webeditor`. <span style="color:red">client_secret and client_secret are not real. Only for testing.</span> * **Request Body** (application/x-www-form-urlencoded) ``` state=1209a3e13d006fbdbd9a6bde6744e63e& grant_type=password& client_id=sodapdfdesktopapp& client_secret=<KEY>=& client_version=9.1.0.0=& machineKey=4d498ce0-846d-11e0-993f-f46d04483013& isAutogeneratedMachineKey=True& motherboardKey=110008970002956& physicalMac=F4:6D:04:48:30:13& pcName=lobster scope=editor ``` * **Returns** - <span style="color:green">200</span> SUCCESS. ``` see description for `api/token` + * **Errors** - <span style="color:red">400</span> (application/json). ``` { "error": "invalid_request", "error_description":"..." } ``` ``` { "error": "invalid_request", "error_description":"Your facebook account is disconnected." } ``` ``` { "error": "invalid_request", "error_description":"Your google account is disconnected." } ``` ``` { "error": "invalid_request", "error_description":"Your microsoft account is disconnected." } ``` -------------- ### Get Config + **Get `/api/external/config/` ** * **Request Headers** <a href="#authorization">Authorization</a><b style="color:red">*</b> * **Returns** - <span style="color:green">200</span> SUCCESS. ``` { "google": { "window": { "width": 800, "height": 600 } }, "facebook": { "window": { "width": 700, "height": 350 } }, "microsoft": { "window": { "width": 800, "height": 600 } } } ``` --------------<file_sep>/Shared/SaaS.Identity/AuthRepository/AuthRepository.AccountMergePending.cs using SaaS.Data.Entities.View.Accounts; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Web; namespace SaaS.Identity { public partial class AuthRepository { public Uri GenerateMergeConfirmationTokenLinkAsync(Uri uri, ViewAccountMergePending pending) { var uriBuilder = new UriBuilder(uri); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query.Add("token", pending.Id.Value.ToString("N")); uriBuilder.Query = query.ToString(); return uriBuilder.Uri; } public async Task AccountMergeAsync(ViewAccountMergePending pending) { await _context.AccountMergeAsync(pending); } public async Task<ViewAccountMergePending> AccountMergePendingMergeAsync(Guid accountIdTo, Guid accountIdFrom, Guid accountIdPrimaryEmail) { return await _context.AccountMergePendingSetAsync(accountIdTo, accountIdFrom, accountIdPrimaryEmail); } public async Task<ViewAccountMergePending> AccountMergePendingGetAsync(Guid id) { return await _context.AccountMergePendingGetAsync(id); } public async Task<List<ViewAccountMergePending>> AccountMergePendingsGetAsync(Guid accountId) { return await _context.AccountMergePendingsGetAsync(accountId); } public async Task AccountMergePendingDeleteAsync(Guid accountId) { await _context.AccountMergePendingDeleteAsync(accountId); } } }<file_sep>/Web.Api/SaaS.Api.Admin/Controllers/Api/AccountController.Merge.cs using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Admin.Oauth; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Admin.Controllers.Api { public partial class AccountController : SaaSApiController { [HttpPost, Route("{accountIdTo:guid}/merge")] public async Task<IHttpActionResult> AccountMerge(Guid accountIdTo, Guid accountIdFrom, Guid accountIdPrimaryEmail) { return await CurrentAccountExecuteAsync(async delegate (Account account) { var targetUser = account; var targetUserFrom = await _auth.AccountGetAsync(accountIdFrom); if (object.Equals(targetUserFrom, null)) return AccountNotFound(); var targetUserPrimaryEmail = accountIdPrimaryEmail == accountIdFrom ? targetUserFrom: targetUser; await _auth.AccountMergePendingDeleteAsync(account.Id); var pending = await _auth.AccountMergePendingMergeAsync(targetUser.Id, targetUserFrom.Id, targetUserPrimaryEmail.Id); await _auth.AccountMergeAsync(pending); var log = string.Format("Customer({0}) has been merged with {1}. Primary email is {2}", targetUser.Email, targetUserFrom.Email, targetUserPrimaryEmail.Email); await LogInsertAsync(log, LogActionTypeEnum.AccountMerge, account.Id); return Ok(); }, accountIdTo); } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/SaaSApiController.cs using Microsoft.AspNet.Identity; using NLog; using SaaS.Api.Core; using SaaS.Api.Models.Oauth; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View; using SaaS.Identity; using SaaS.Notification; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web.Http; using Upclick.Api.Client; namespace SaaS.Api.Controllers.Api { public class SaaSApiController : ApiController { private static List<Client> _clients; protected readonly INpsRepository _nps; protected readonly IAuthRepository _auth; protected readonly IAuthProductRepository _authProduct; protected static readonly IAppSettings _appSettings = new AppSettings(); protected static Logger _oautLogLogger = LogManager.GetLogger("oauth-log"); public SaaSApiController() { _nps = new NpsRepository(); _auth = new AuthRepository(); _auth.SetDataProtectorProvider(Startup.DataProtectionProvider); _authProduct = new AuthProductRepository(); } private UpclickClient _upclickClient; private NotificationManager _notificationManager; protected UpclickClient UpclickClient { get { _upclickClient = _upclickClient ?? new UpclickClient(_appSettings.Upclick.MerchantLogin, _appSettings.Upclick.MerchantPassword); return _upclickClient; } } protected NotificationManager NotificationManager { get { _notificationManager = _notificationManager ?? new NotificationManager(_auth, new NotificationSettings { DownloadLink = _appSettings.DownloadLink, CreatePassword = _appSettings.Oauth.CreatePassword, EmailConfirmation = _appSettings.Oauth.EmailConfirmation, MergeConfirmation = _appSettings.Oauth.MergeConfirmation, EmailChangeConfirmation = _appSettings.Oauth.EmailChangeConfirmation, ResetPassword = _appSettings.Oauth.ResetPassword }); return _notificationManager; } } protected Client GetClient(int id) { _clients = _clients ?? _auth.ClientsGet(); return _clients.FirstOrDefault(e => e.Id == id); } protected Client GetClient(string name) { _clients = _clients ?? _auth.ClientsGet(); return _clients.FirstOrDefault(e => string.Equals(e.Name, name, StringComparison.InvariantCultureIgnoreCase)); } protected override void Dispose(bool disposing) { _nps.Dispose(); _auth.Dispose(); _authProduct.Dispose(); base.Dispose(disposing); } protected IHttpActionResult GetErrorResult(IdentityResult result) { string error = null; if (object.Equals(result, null)) return ErrorContent(error, httpStatusCode: HttpStatusCode.InternalServerError); if (result.Succeeded) return null; if (!object.Equals(result.Errors, null)) error = result.Errors.FirstOrDefault(); return ErrorContent("invalid_request", error); } protected IHttpActionResult AccountNotFound() { return ErrorContent("invalid_grant", "User is not exists.", HttpStatusCode.NotFound); } protected IHttpActionResult ClientNotFound() { return ErrorContent("invalid_clientId", "This client is not registered in the system."); } protected IHttpActionResult AccountExists() { return ErrorContent("invalid_grant", "User already exists.", HttpStatusCode.Conflict); } protected IHttpActionResult AccountUnauthorized() { return ErrorContent("invalid_grant", "Authorization has been denied for this request.", HttpStatusCode.Unauthorized); } protected IHttpActionResult AccountNotActivated() { return ErrorContent("invalid_grant", "This account is not activated.", HttpStatusCode.BadRequest); } protected IHttpActionResult AccountIsDisconnected(string provider) { return ErrorContent("invalid_grant", string.Format("Your {0} account is disconnected.", provider), HttpStatusCode.BadRequest); } protected IHttpActionResult ProductNotFound() { return ErrorContent("invalid_grant", "Product is not exists or is disabled.", HttpStatusCode.NotFound); } protected IHttpActionResult ErrorContent(string error, string description = null, HttpStatusCode httpStatusCode = HttpStatusCode.BadRequest) { return Content<dynamic>(httpStatusCode, new { error = error, error_description = description }); } protected delegate Task<IHttpActionResult> AccountExecuteHandlerAsync(Account account); protected delegate Task<IHttpActionResult> OwnerProductExecuteHandlerAsync(Guid accountId, ViewOwnerProduct product); protected async Task<IHttpActionResult> CurrentAccountExecuteAsync(AccountExecuteHandlerAsync handler) { try { Guid userId; if (!Guid.TryParse(User.Identity.GetUserId(), out userId)) return AccountNotFound(); var user = await _auth.AccountGetAsync(userId); if (object.Equals(user, null)) return AccountNotFound(); return await handler(user); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } protected async Task<IHttpActionResult> AccountExecuteAsync(AccountExecuteHandlerAsync handler, AuthViewModel model) { try { var user = await _auth.AccountGetAsync(model.Email); if (object.Equals(user, null) || user.IsAnonymous) return AccountNotFound(); return await handler(user); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } protected async Task<IHttpActionResult> OwnerProductExecuteAsync(OwnerProductExecuteHandlerAsync handler, Guid accountProductId, bool skipConflict = false) { try { var product = await _authProduct.OwnerProductGetAsync(CreateAccountProductPair(accountProductId)); if (object.Equals(product, null) || product.IsDisabled) return ProductNotFound(); if (!skipConflict && !product.IsOwner) return Conflict(); return await handler(AccountId, product); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } protected Guid AccountId { get { return Guid.Parse(User.Identity.GetUserId()); } } protected async Task<Account> GetAccountAsync() { return await _auth.AccountGetAsync(AccountId); } protected AccountProductPair CreateAccountProductPair(Guid accountProductId) { return new AccountProductPair(AccountId, accountProductId); } } } <file_sep>/Web.Api/SaaS.Sso/src/js/!app.js angular.module('app.components', ['ui.router', 'pascalprecht.translate']); angular.module('app.services', []); angular.module('app.controllers', []); angular.module('app.directives', []); angular.module('app.filters', []); angular.module('app.external', ['LocalStorageModule']); //angular-local-storage angular.module('app', ['ui.router', 'app.components', 'app.services', 'app.controllers', 'app.directives', 'app.filters', 'app.external']) .run(function ($trace, $transitions, $translate, $brand, $sso) { if (!$brand.validate()) return $brand.redirect(); //$trace.enable('TRANSITION'); $transitions.onBefore({ to: '**' }, (transition) => { let to = transition.to(); if (to.name === 'account/logout' && $sso.logout()) document.body.style.display = 'none'; }); //$transitions.onSuccess({ to: '**' }, (transition) => { // let stateService = transition.router.stateService; // let locale = stateService.params.locale || 'en'; // $translate.use(locale); //}); });<file_sep>/Web.Api/SaaS.UI.Admin/js/controllers/account/special.js (function () { 'use strict'; angular .module('app.controllers') .controller('accountSpecialController', controller); controller.$inject = ['$rootScope', '$scope', '$api', 'special', 'appSettings']; function controller($rootScope, $scope, $api, special, appSettings) { $scope.model = { account: null, tracking: angular.copy(special.tracking), products: angular.copy(special.products) }; Object.defineProperty($scope.model, 'link', { get: function () { $scope.model.tracking.ujId = $scope.model.discount.ujId; var tracking = special.url; tracking += '?' + $.param($scope.model.tracking); return tracking; } }); $scope.model.product = $scope.model.products[0]; $scope.isShowDiscount = function () { var discounts = $scope.model.product.discounts; return !(discounts.length == 1 && discounts[0].name == '0%'); }; $scope.productChange = function () { $scope.model.discount = $scope.model.product.discounts[0]; }; $scope.productChange(); $rootScope.$on('event:accountLoaded', function (event, json) { $scope.model.account = $scope.model.account || {}; $scope.model.account.id = json.id; $scope.model.tracking.email = json.email; json.firstName && ($scope.model.tracking.fName = json.firstName); json.lastName && ($scope.model.tracking.lName = json.lastName); json.id && $api.account.uid(json.id).then(function (json) { json.uid && ($scope.model.tracking.uid = json.uid); }); }); $rootScope.$on('event:accountDeleted', function (event, json) { $scope.model.account = $scope.model.account || {}; $scope.model.account.isDeleted = true; }); }; })();<file_sep>/Shared/Upclick.Api.Client/UpclickClient.Crossells.cs using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net.Http; using System.Threading.Tasks; namespace Upclick.Api.Client { public partial class UpclickClient { private async Task<HttpResponseMessage> _GetCrossells(string uid = null) { return await _upclickHttpClient.GetAsync("crossells/retrieve", string.IsNullOrEmpty(uid) ? null : new NameValueCollection() { { "uid", uid } }); } private async Task<HttpResponseMessage> _GetCrossellsList(string uid = null) { return await _upclickHttpClient.GetAsync("crossells/getlist", string.IsNullOrEmpty(uid) ? null : new NameValueCollection() { { "uid", uid } }); } public async Task<List<Crossell>> GetCrossells() { HttpResponseMessage response = await _GetCrossells(); var root = await response.Content.ReadAsAsync<CrossellsRetrieveRoot>(); if (!object.Equals(root, null) && !object.Equals(root.Crossells, null)) return root.Crossells.Products; return null; } public async Task<List<Crossell>> GetCrossellsList() { HttpResponseMessage response = await _GetCrossellsList(); var root = await response.Content.ReadAsAsync<CrossellsGetListRoot>(); if (!object.Equals(root, null) && !object.Equals(root.CrossellsGetList, null)) return root.CrossellsGetList.Products; return null; } } public class CrossellsRetrieveRoot { [JsonProperty(PropertyName = "crossells_retrieve")] public Crossells Crossells { get; set; } } public class CrossellsGetListRoot { [JsonProperty(PropertyName = "crossells_getlist")] public CrossellsGetList CrossellsGetList { get; set; } } public class CrossellsGetList { [JsonProperty(PropertyName = "crossell")] [JsonConverter(typeof(SingleOrArrayConverter<Crossell>))] public List<Crossell> Products { get; set; } } public class Crossells { [JsonProperty(PropertyName = "crossell")] [JsonConverter(typeof(SingleOrArrayConverter<Crossell>))] public List<Crossell> Products { get; set; } } public class Crossell : Product { public string BaseproductUid { get; set; } } } <file_sep>/Web.Api/SaaS.Zendesk/src/js/auth/storage.js angular.module('app.auth') .factory('$authStorage', ['$window', ($window) => { var _localStorage = {}; var _getItem = (key) => { var json = _localStorage[key]; var value = json ? JSON.parse(json) : null; _localStorage[key] = json; try { json = $window.localStorage.getItem(key); json && (value = JSON.parse(json)); } catch (error) { console.error(error); } return value; }; var _setItem = (key, value) => { var json = JSON.stringify(value); _localStorage[key] = json; try { $window.localStorage.setItem(key, json); } catch (error) { console.error(error); } }; var _removeItem = (key) => { delete _localStorage[key]; try { $window.localStorage.removeItem(key); } catch (error) { console.error(error); } }; var service = {}; service.getItem = (brandIso) => { return _getItem(`auth:${brandIso}`); }; service.setItem = (brandIso, json) => { _setItem(`auth:${brandIso}`, json); }; service.removeItem = (brandIso) => { _removeItem(`auth:${brandIso}`); }; return service; }]);<file_sep>/Web.Api/SaaS.Api/Oauth/UserManagerHelper.cs using Microsoft.Owin.Security; using SaaS.Api.Models.Products; using SaaS.Api.Oauth.Providers; using SaaS.Data.Entities.View; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Security.Claims; namespace SaaS.Api.Oauth { internal static class UserManagerHelper { private static readonly StringComparison _stringComparison = StringComparison.InvariantCultureIgnoreCase; private static IEnumerable<ViewAccountProduct> GetFilter(IEnumerable<ViewAccountProduct> products, Guid accountProductId) { return products.Where(e => !e.IsDisabled && (e.AccountProductId == accountProductId || e.IsMinor)); } internal static IEnumerable<Guid> GetActiveProducts(IEnumerable<ViewAccountProduct> products, IEnumerable<AccountProductModuleModel> allowedModules, Guid accountProductId) { var activeProducts = new List<ViewAccountProduct>(); var filter = GetFilter(products, accountProductId); var mainProduct = filter.FirstOrDefault(e => e.AccountProductId == accountProductId); if (!object.Equals(mainProduct, null)) { activeProducts.Add(mainProduct); var minorProducts = filter.Where(e => e.AccountProductId != accountProductId).ToList(); foreach (var module in allowedModules) { if ("e-sign".Equals(module.Module, _stringComparison)) { if (!mainProduct.AllowedEsignCount.HasValue) continue; //ignore var minorProduct = minorProducts.FirstOrDefault(e => !e.AllowedEsignCount.HasValue); if (!object.Equals(minorProduct, null)) { activeProducts.Add(minorProduct); continue; } activeProducts.AddRange(minorProducts); continue; } var mainModule = mainProduct.Modules.FirstOrDefault(e => string.Equals(e.Module, module.Module)); if (object.Equals(mainModule, null)) { var anyActiveProduct = activeProducts.FirstOrDefault(product => product.Modules.Select(e => e.Module).Contains(module.Module)); if (object.Equals(anyActiveProduct, null)) { var anyMinorProduct = minorProducts.FirstOrDefault(product => product.Modules.Select(e => e.Module).Contains(module.Module)); if (!object.Equals(anyMinorProduct, null)) activeProducts.Add(anyMinorProduct); } } } } return activeProducts.Select(e=>e.AccountProductId); } internal static List<AccountProductModuleModel> GetAllowedModules(IEnumerable<ViewAccountProduct> products, Guid accountProductId) { var modules = new List<AccountProductModuleModel>(); var filter = products.Where(e => !e.IsDisabled && (e.AccountProductId == accountProductId || e.IsMinor)); foreach (var product in filter) { foreach (var module in product.Modules) { var accountProductModule = modules.FirstOrDefault(e => string.Equals(e.Module, module.Module, _stringComparison)); if (object.Equals(accountProductModule, null)) modules.Add(new AccountProductModuleModel { Module = module.Module }); } } var eSignModule = modules.FirstOrDefault(e => "e-sign".Equals(e.Module, _stringComparison)); if (!object.Equals(eSignModule, null)) { var unlimitedEsign = filter.FirstOrDefault(e => !e.AllowedEsignCount.HasValue); if (object.Equals(unlimitedEsign, null)) eSignModule.Allowed = filter.Sum(e => e.AllowedEsignCount); eSignModule.Used = filter.Sum(e => e.UsedEsignCount); } return modules; } internal static List<AccountProductModuleModel> GetAllowedModules(IEnumerable<ViewAccountProduct> products, Guid accountProductId, ClaimsIdentity identity) { var modules = GetAllowedModules(products, accountProductId); identity.TryRemoveClaim("module"); foreach (var module in modules) identity.AddClaim(new Claim("module", module.Module)); return modules; } internal static Guid Session(HttpRequestMessage request, out AuthenticationTicket ticket) { var accessToken = request.Headers.Authorization.Parameter; ticket = Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(accessToken); return Guid.Parse(ticket.Properties.Dictionary["session"]); } } }<file_sep>/Web.Api/SaaS.Api.Sign/Controllers/Api/ESignHelper.cs using SaaS.Data.Entities.View; using System; using System.Collections.Generic; using System.Linq; namespace SaaS.Api.Sign.Controllers.Api { internal static class eSignHelper { internal static Guid? GetAllowedAccountProductId(List<ViewAccountProduct> products, Guid? accountProductId, out ViewAccountProduct product) { var sorted = products.OrderByDescending(e => e.PurchaseDate); var filter = sorted.Where(e => !e.IsDisabled); product = filter.FirstOrDefault(e => !e.AllowedEsignCount.HasValue && accountProductId.HasValue && e.AccountProductId == accountProductId.Value) ?? filter.FirstOrDefault(e => !e.AllowedEsignCount.HasValue && e.IsMinor) ?? filter.FirstOrDefault(e => e.AllowedEsignCount.HasValue && e.IsMinor && e.AllowedEsignCount > e.UsedEsignCount); if (!object.Equals(product, null)) return product.AccountProductId; return null; } internal static Guid? GetAllowedAccountMicrotransactionId(List<ViewAccountMicrotransaction> microtransactions, out ViewAccountMicrotransaction microtransaction) { var sorted = microtransactions.OrderByDescending(e => e.PurchaseDate); var filter = sorted; microtransaction = filter.FirstOrDefault(e => !e.AllowedEsignCount.HasValue) ?? filter.FirstOrDefault(e => e.AllowedEsignCount.HasValue && e.AllowedEsignCount > e.UsedEsignCount); if (!object.Equals(microtransaction, null)) return microtransaction.AccountMicrotransactionId; return null; } internal static void GetAllowedUsedCount(List<ViewAccountProduct> products, List<ViewAccountMicrotransaction> microtransactions, out int? allowed, out int? used) { allowed = 0; used = 0; var filterProducts = products.Where(e => !e.IsDisabled && e.AllowedEsignCount.HasValue); var filterMicrotransactions = microtransactions.Where(e => e.AllowedEsignCount.HasValue); allowed += filterProducts.Sum(product=> product.AllowedEsignCount); used += filterProducts.Sum(product => product.UsedEsignCount); allowed += filterMicrotransactions.Sum(product => product.AllowedEsignCount); used += filterMicrotransactions.Sum(product => product.UsedEsignCount); } } }<file_sep>/Web.Api/SaaS.UI.Admin/js/directives/date.js (function () { 'use strict'; angular .module('app.directives') .directive('ngDate', directive) directive.$inject = ['$filter']; function directive($filter) { return { link: link, scope: { date: '=ngDate', format: '=ngFormat' }, restrict: 'A' }; function link(scope, element, attrs) { if (!scope.date) return; element.addClass('text-muted small'); var format = scope.format || 'yyyy-MM-dd HH:mm'; scope.$watch('date', function (newValue, oldValue) { if (newValue || newValue != oldValue) element.html("<em>" + $filter('date')(scope.date, format) + "</em>"); }); }; }; })();<file_sep>/Shared/SaaS.Api.Models/Products/OwnerProductViewModel.cs using Newtonsoft.Json; using SaaS.Data.Entities.View; using System.Collections.Generic; namespace SaaS.Api.Models.Products { public class OwnerProductViewModel : ProductViewModel { public string OwnerEmail { get; set; } [JsonProperty("Allowed")] public int AllowedCount { get; set; } [JsonProperty("Used")] public int UsedCount { get; set; } public List<ViewOwnerAccount> Accounts { get; set; } } } <file_sep>/Shared/SaaS.Data.Entities/View/Oauth/ViewSessionToken.cs using System; namespace SaaS.Data.Entities.View.Oauth { public class ViewSessionToken { public Guid RefreshToken { get; set; } public Guid AccountId { get; set; } public Guid AccountProductId { get; set; } public string PcName { get; set; } public string Client { get; set; } } }<file_sep>/Web.Api/SaaS.Api.Admin/Oauth/Providers/SaaSAuthorizationServerProvider.cs using Microsoft.Owin.Security; using Microsoft.Owin.Security.OAuth; using SaaS.Data.Entities.Admin.View.Oauth; using SaaS.Identity.Admin; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; namespace SaaS.Api.Admin.Oauth.Providers { public partial class SaaSAuthorizationServerProvider : OAuthAuthorizationServerProvider { public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { await Task.Run(() => { context.Validated(); }); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { ViewUser user = null; using (var auth = new AuthRepository()) user = await auth.ViewUserGetAsync(context.UserName, context.Password); if (object.Equals(user, null)) { context.SetError("invalid_grant", "Your login or password is incorrect."); return; } if (!user.IsActive) { context.SetError("invalid_grant", "Your account has been deactivated. Please contact your administrator."); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); var properties = new Dictionary<string, string> { }; identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString("N"))); identity.AddClaims(user); context.Validated(new AuthenticationTicket(identity, new AuthenticationProperties(properties))); } } }<file_sep>/Web.Api/SaaS.Api.Admin/Controllers/Api/LogController.cs using CsvHelper; using SaaS.Data.Entities.Admin.Oauth; using System; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Admin.Controllers.Api { [RoutePrefix("api/log"), Authorize(Roles = "admin")] public class LogController : SaaSApiController { [HttpGet, AllowAnonymous] public async Task<IHttpActionResult> Index(DateTime from, DateTime to, Guid? userId = null, string log = null, LogActionTypeEnum? logActionTypeId = null, string format = "json") { var logs = await _authAdmin.LogsGetAsync(from, to, userId, log, logActionTypeId); if ("csv".Equals(format, StringComparison.InvariantCultureIgnoreCase)) { var memoryStream = new MemoryStream(); var streamWriter = new StreamWriter(memoryStream); var csvWriter = new CsvWriter(streamWriter); csvWriter.WriteRecords(logs); memoryStream.Position = 0; var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(memoryStream); response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = string.Format("logs-from {0} to {1}.csv", from.ToString("MMMM dd, yyyy"), to.ToString("MMMM dd, yyyy")) }; return ResponseMessage(response); } return Ok(logs); } [HttpGet, Route("action-type")] public async Task<IHttpActionResult> ActionType() { return Ok(await _authAdmin.LogActionTypesGetAsync()); } } }<file_sep>/Web.Api/SaaS.Sso/src/js/services/storage.js angular .module('app.services') .factory('$storage', ['localStorageService', ($localStorageService) => { let service = {}; let _equalAccount = (account1, account2) => { let email1 = account1.email || ''; let email2 = account2.email || ''; return email1.toLowerCase() === email2.toLowerCase(); }; service.getAccounts = () => { if (!$localStorageService.isSupported) return []; return $localStorageService.get('accounts') || []; }; service.addAccount = (account) => { if (!$localStorageService.isSupported) return; service.removeAccount(account); let accounts = service.getAccounts(); accounts.unshift({ firstName: account.firstName, lastName: account.lastName, email: account.email }); $localStorageService.set('accounts', accounts); }; service.removeAccount = (account) => { if (!$localStorageService.isSupported) return; let accounts = service.getAccounts(); for (let index = 0; index < accounts.length; ++index) { if (_equalAccount(accounts[index], account)) accounts.splice(index--, 1); }; $localStorageService.set('accounts', accounts); }; function viewAccount(json) { this.firstName = json.firstName; this.lastName = json.lastName; this.email = json.email; }; return service; }]);<file_sep>/Shared/SaaS.Identity.Admin/AuthRepository/AuthRepository.Log.cs using SaaS.Data.Entities.Admin.Oauth; using SaaS.Data.Entities.Admin.View; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Identity.Admin { public partial class AuthRepository { public async Task<List<ViewLog>> LogsGetAsync(DateTime from, DateTime to, Guid? userId, string log, LogActionTypeEnum? logActionType) { return await _context.LogsGetAsync(from, to, userId, log, logActionType); } public async Task LogInsertAsync(Guid userId, Guid? accountId, string log, LogActionTypeEnum logActionType) { await _context.LogInsertAsync(userId, accountId, log, logActionType); } public async Task<List<LogActionType>> LogActionTypesGetAsync() { return await _context.LogActionTypesGetAsync(); } } }<file_sep>/Shared/SaaS.Api.Client/SaaSApiOauthService.RefreshToken.cs using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace SaaS.Api.Client { public partial class SaaSApiOauthService { public async Task<RefreshTokenModel> RefreshTokenAsync(string refreshToken) { if (string.IsNullOrEmpty(refreshToken)) return new RefreshTokenModel(RefreshTokenStatus.InvalidGrant); var builder = new StringBuilder("grant_type=refresh_token"); builder.AppendFormat("&refresh_token={0}", refreshToken); builder.AppendFormat("&client_id={0}", _clientId); builder.AppendFormat("&client_secret={0}", _clientSecret); using (var client = CreateHttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); var request = new HttpRequestMessage(HttpMethod.Post, "api/token"); request.Content = new StringContent(builder.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); SaaSApiToken token = await response.Content.ReadAsAsync<SaaSApiToken>(); return new RefreshTokenModel(token); } return new RefreshTokenModel(RefreshTokenStatus.InvalidGrant); } } } //+ grant_type (string, required) - Should be 'refresh_token'; //+ refresh_token (string, required) - refresh_token from previous SignIn; //+ client_id (string, required) - Should be `sodapdfdesktopapp`; //+ client_secret (string, required) - Should be `<KEY>`. public enum RefreshTokenStatus : byte { Ok, InvalidGrant } public class RefreshTokenModel { public readonly RefreshTokenStatus Status = RefreshTokenStatus.Ok; public readonly SaaSApiToken Token = null; public RefreshTokenModel(SaaSApiToken token) { Token = token; } public RefreshTokenModel(RefreshTokenStatus status) { Status = status; } public RefreshTokenModel(RefreshTokenStatus status, SaaSApiToken token) { Status = status; Token = token; } } } <file_sep>/Shared/SaaS.Data.Entities/Oauth/SessionToken.cs using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Data.Entities.Oauth { public class SessionToken : AccountEntity<Guid> { public Guid? ParentId { get; set; } public int ClientId { get; set; } public string ClientName { get; set; } public string ClientVersion { get; set; } [Column("externalClientId")] public ExternalClient? ExternalClient { get; set; } public string ExternalClientName { get; set; } public DateTime IssuedUtc { get; set; } public DateTime ExpiresUtc { get; set; } public string Scope { get; set; } [Required] public string ProtectedTicket { get; set; } public Guid? SystemId { get; set; } public Guid? AccountProductId { get; set; } public Guid? InstallationID { get; set; } } public static class SessionTokenHelper { public static Version GetClientVersion(this SessionToken sessionToken) { Version version; if (!Version.TryParse(sessionToken.ClientVersion, out version)) return null; return version; } } }<file_sep>/WinService/SaaS.WinService.eSign/Scheduler.cs using SaaS.Identity; using SaaS.WinService.Core; using System; using System.Timers; namespace SaaS.WinService.eSign { public class Scheduler : BaseScheduler { public override void Start() { new Timer() { Interval = TimeSpan.FromSeconds(10).TotalMilliseconds, Enabled = true }.Elapsed += delegate (object sender, ElapsedEventArgs e) { Do((Timer)sender, DoJob); }; DoJob(); } private void DoJob() { if (_queue.IsFull) return; _queue.AddTask(new EmptyEventHandler(EmailChange), new object[] { }); } private void EmailChange() { _logger.Info("emailChange"); try { var top = 10; using (var worker = new EmailChangeWorker()) { var count = worker.Do(top); if (top == count) EmailChange(); } } catch (Exception exc) { _logger.Error(exc); } } } } <file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AdminAccountController.Password.cs using Microsoft.AspNet.Identity; using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AdminAccountController { [HttpPost, Route("change-password"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> ChangePassword(ResetPasswordViewModel model) { try { var user = await _auth.AccountGetAsync(model.UserId); if (object.Equals(user, null)) return AccountNotFound(); var result = await _auth.AccountPasswordSetAsync(user, model.NewPassword); var errorResult = GetErrorResult(result); if (!object.Equals(errorResult, null)) return errorResult; } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } [HttpPost, Route("recover-password")] public async Task<IHttpActionResult> RecoverPassword(Guid userId) { try { var user = await _auth.AccountGetAsync(userId); if (object.Equals(user, null)) return AccountNotFound(); await NotificationManager.RecoverPassword(user); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } } }<file_sep>/Web.Api/SaaS.Api/Oauth/Providers/SaaSAuthorizationServerProvider.TokenEndpoint.cs using Microsoft.Owin.Security.OAuth; using SaaS.Data.Entities.Accounts; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Api.Oauth.Providers { public partial class SaaSAuthorizationServerProvider { public override Task TokenEndpoint(OAuthTokenEndpointContext context) { foreach (KeyValuePair<string, string> property in context.Properties.Dictionary) { switch (property.Key) { case ".issued": context.AdditionalResponseParameters.Add("issued", context.Properties.IssuedUtc.Value.UtcDateTime); continue; case ".expires": context.AdditionalResponseParameters.Add("expires", context.Properties.ExpiresUtc.Value.UtcDateTime); continue; case "session": case "token": continue; } context.AdditionalResponseParameters.Add(property.Key, property.Value); } var user = context.OwinContext.Get<Account>("user"); if (!object.Equals(user, null)) { context.AdditionalResponseParameters.Add("email", user.Email); context.AdditionalResponseParameters.Add("firstName", user.FirstName ?? string.Empty); context.AdditionalResponseParameters.Add("lastName", user.LastName ?? string.Empty); context.AdditionalResponseParameters.Add("status", user.GetStatus()); } return Task.FromResult<object>(null); } } }<file_sep>/Shared/SaaS.ModuleFeatures/MapStrategy.cs using SaaS.ModuleFeatures.Model; using System; using System.Collections.Generic; namespace SaaS.ModuleFeatures { public enum MapStrategy { Subscription, PerpetualLicense } internal abstract class MapStrategyBase { protected void Normalize(ref Version license) { license = license ?? new Version(); license = new Version(license.Major < 0 ? 0 : license.Major, license.Minor < 0 ? 0 : license.Minor, license.Build < 0 ? 0 : license.Build, license.Revision < 0 ? 0 : license.Revision); } internal abstract MapModule[] GetModules(Root root, Version license); } internal class MapStrategySubscription : MapStrategyBase { internal override MapModule[] GetModules(Root root, Version license) { Normalize(ref license); var mapModules = new List<MapModule>(root.Modules.Length); foreach (var module in root.Modules) { var features = new List<MapFeature>(module.Features.Length); foreach (var feature in module.Features) features.Add(new MapFeature(feature.Name, feature.GetVersion())); mapModules.Add(new MapModule(module.Name, features.ToArray())); } return mapModules.ToArray(); } } internal class MapStrategyPerpetualLicense : MapStrategyBase { internal override MapModule[] GetModules(Root root, Version license) { if (object.Equals(root.Modules, null)) return null; Normalize(ref license); var latestVersion = root.GetLatestVersion(); var mapModules = new List<MapModule>(root.Modules.Length); foreach (var module in root.Modules) { if (object.Equals(module.Features, null)) continue; var features = new List<MapFeature>(module.Features.Length); foreach (var feature in module.Features) { var featureVersion = feature.GetVersion(); var mapFeature = new MapFeature(feature.Name, featureVersion); featureVersion = featureVersion ?? new Version(); mapFeature.IsHidden = featureVersion.Major >= license.Major && featureVersion.Minor > license.Minor && featureVersion.Major == latestVersion.Major; if (!mapFeature.IsHidden) mapFeature.IsUpgradable = featureVersion > license; features.Add(mapFeature); } mapModules.Add(new MapModule(module.Name, features.ToArray())); } return mapModules.ToArray(); } } internal abstract class MapStrategyCreator { internal abstract MapStrategyBase Factory(); internal static MapStrategyCreator Creator(MapStrategy strategy) { switch (strategy) { case MapStrategy.PerpetualLicense: return new MapStrategyPerpetualLicenseCreator(); default: return new MapStrategySubscriptionCreator(); } } } internal class MapStrategySubscriptionCreator : MapStrategyCreator { internal override MapStrategyBase Factory() { return new MapStrategySubscription { }; } } internal class MapStrategyPerpetualLicenseCreator : MapStrategyCreator { internal override MapStrategyBase Factory() { return new MapStrategyPerpetualLicense { }; } } } <file_sep>/Web.Api/SaaS.Zendesk/src/js/services/brand.js angular.module('app.services') .factory('$brand', () => { var _brands = { sodapdf: { api: 'https://cp-oauth.sodapdf.com' }, pdfarchitect: { api: 'https://cp-oauth.pdfarchitect.org' } }; var _brand = null; var service = {}; service.isEmpty = () => { return !_brand; }; service.set = (brand) => { _brand = brand; }; service.get = () => { return _brand; }; service.isSupport = () => { var iso = service.getIso(_brand); return !!_brands[iso]; }; service.getIso = () => { return _brand.subdomain; }; service.getApiUri = (method) => { var iso = service.getIso(); var api = _brands[iso].api; return `${api}/${method}`; }; service.getLogo = () => { if (service.isEmpty()) return null; return _brand.logo.contentUrl; }; return service; });<file_sep>/Shared/SaaS.Data.Entities/View/ViewProduct.cs using System; using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Data.Entities.View { public abstract class ViewProduct { public Guid AccountProductId { get; set; } public string SpId { get; set; } public string ProductName { get; set; } public string ProductUnitName { get; set; } public string Plan { get; set; } public DateTime PurchaseDate { get; set; } public DateTime? EndDate { get; set; } public DateTime? NextRebillDate { get; set; } public DateTime? CreditCardExpiryDate { get; set; } public bool IsNew { get; set; } public bool IsDisabled { get; set; } public bool IsTrial { get; set; } public bool IsFree { get; set; } public bool IsActive { get; set; } public bool IsMinor { get; set; } public bool IsPPC { get; set; } public bool IsUpgradable { get; set; } public bool IsPaymentFailed { get; set; } public bool IsRenewal { get; set; } public bool IsOwner { get; set; } public int? AllowedEsignCount { get; set; } public int UsedEsignCount { get; set; } public int? AllowedPcCount { get; set; } [NotMapped] public bool IsExpired { get { if (EndDate.HasValue) return DateTime.UtcNow >= EndDate.Value; return false; } } [NotMapped] public ulong Status { get { ulong status = 0; status |= (ulong)(IsDisabled ? ProductStatus.IsDisabled : 0); status |= (ulong)(IsExpired ? ProductStatus.IsExpired : 0); status |= (ulong)(IsTrial ? ProductStatus.IsTrial : 0); status |= (ulong)(IsFree ? ProductStatus.IsFree : 0); status |= (ulong)(IsMinor ? ProductStatus.IsMinor : 0); status |= (ulong)(IsActive ? ProductStatus.IsActive : 0); status |= (ulong)(IsPPC ? ProductStatus.IsPPC : 0); status |= (ulong)(IsUpgradable ? ProductStatus.IsUpgradable : 0); status |= (ulong)(IsNew ? ProductStatus.IsNew : 0); status |= (ulong)(IsPaymentFailed ? ProductStatus.IsPaymentFailed : 0); status |= (ulong)(IsRenewal ? ProductStatus.IsRenewal : 0); status |= (ulong)(IsOwner ? ProductStatus.IsOwner : 0); status |= (ulong)(IsNotAbleToRenewCreditCartExpired ? ProductStatus.IsNotAbleToRenewCreditCartExpired : 0); status |= (ulong)(IsRefund ? ProductStatus.IsRefund : 0); status |= (ulong)(IsChargeback ? ProductStatus.IsChargeback : 0); status |= (ulong)(IsUpgraded ? ProductStatus.IsUpgraded : 0); status |= (ulong)(IsManualCancelled ? ProductStatus.IsManualCancelled : 0); status |= (ulong)(IsNotSupportedClient ? ProductStatus.IsNotSupportedClient : 0); status |= (ulong)(IsBusiness ? ProductStatus.IsBusiness : 0); return status; } } public bool IsNotAbleToRenewCreditCartExpired { get; set; } public bool IsRefund { get; set; } public bool IsChargeback { get; set; } public bool IsUpgraded { get; set; } public bool IsManualCancelled { get; set; } public bool IsNotSupportedClient { get; set; } public bool IsBusiness { get; set; } } }<file_sep>/Shared/SaaS.MailerWorker/EmailScheduler.cs using Quartz; using Quartz.Impl; using SaaS.MailerWorker.Jobs; namespace SaaS.MailerWorker { public class EmailScheduler : IEmailScheduler { private static readonly EmailScheduler _mailer = new EmailScheduler(); private static IScheduler _scheduler; protected EmailScheduler() { ISchedulerFactory schedulerFactory = new StdSchedulerFactory(); _scheduler = schedulerFactory.GetScheduler(); IJobDetail regularJob = JobBuilder.Create<RegularMailingJob>() .WithIdentity("RegularMailing", "RegularMailingGroup") .Build(); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("RegularMailingTrigger", "RegularMailingGroup") .WithSimpleSchedule(x => x.WithIntervalInSeconds(15).RepeatForever()) .ForJob(regularJob) .Build(); AddJob(regularJob, trigger); } public static EmailScheduler GetMailer() { return _mailer; } public void AddJob(IJobDetail jobDetail, ITrigger trigger) { _scheduler.ScheduleJob(jobDetail, trigger); } public bool RemoveJob(TriggerKey triggerKey) { return _scheduler.UnscheduleJob(triggerKey); } public void StartMailing() { _scheduler.Start(); } public void StopMailing() { _scheduler.Shutdown(); } public bool IsRunning { get { return _scheduler.IsStarted; } } public bool IsStopped { get { return _scheduler.IsShutdown; } } } public interface IEmailScheduler { bool IsRunning { get; } bool IsStopped { get; } void StartMailing(); void StopMailing(); void AddJob(IJobDetail jobDetail, ITrigger trigger); bool RemoveJob(TriggerKey triggerKey); } } <file_sep>/Web.Api/SaaS.Api.Admin/Controllers/Api/EmailsController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace SaaS.Api.Admin.Controllers.Api { [RoutePrefix("api/emails"), Authorize(Roles = "admin")] public class EmailsController : SaaSApiController { [HttpGet, Route("templates")] public async Task<IHttpActionResult> Templates() { return Ok(/*await _authAdmin.LogActionTypesGetAsync()*/); } } }<file_sep>/Web.Api/SaaS.UI.Admin/js/directives/form-field.js /// <reference path="../bundle.js" /> (function () { 'use strict'; angular .module('app.directives') .directive('ngLoadingForm', ngLoadingForm) .directive('ngFormValidationGroup', ngFormValidationGroup) .directive('ngPasswordPattern', ngPasswordPattern) .directive('ngMatch', ngMatch); ngLoadingForm.$inject = []; ngFormValidationGroup.$inject = []; ngMatch.$inject = []; ngPasswordPattern.$inject = []; ngMatch.$inject = []; function ngLoadingForm() { var directive = { scope: {}, link: link, restrict: 'A' }; return directive; function link(scope, element, attr) { var buttons = element.find('[type="submit"]'); buttons.each(function () { var button = angular.element(this); button.html('<i class="fa fa-spinner fa-spin" style="display:none"></i> ' + button.val()); }); var icons = buttons.find('i'); var isBusyWatcher = scope.$watch('$parent.isBusy', function (newValue, oldValue) { buttons.prop('disabled', newValue); newValue ? icons.show() : icons.hide(); }); scope.$on('$destroy', function () { isBusyWatcher(); }); } } function ngFormValidationGroup() { var directive = { scope: { }, link: link, restrict: 'A' }; return directive; function link(scope, element, attr) { element.addClass('form-group'); if (element.find('label').size()) element.addClass('has-label'); var input = element.find('input:first, select:first, textarea:first').addClass('form-control'); element.find('span').addClass('label label-danger').hide(); var errors = []; var _addError = function (validationKey) { var currentSpan = element.find('span[data-ng-' + validationKey + '-error]'); if (!currentSpan.size()) return; errors.push({ span: currentSpan, validationKey: validationKey }); }; _addError('required'); _addError('pattern'); _addError('match'); _addError('passwordPattern'); _addError('passwordSpecialCharacters'); _addError('passwordSpecialWords'); var field = input.attr('name'); var type = input.attr('type'); var isPattern = input.is('[ng-password-pattern]'); scope.form = scope.$parent.form; var _hasError = function () { return scope.form[field].$invalid && !scope.form[field].$pristine; }; var _hasSuccess = function () { if (type === 'password' && !isPattern) return false; return !scope.form[field].$invalid && !scope.form[field].$pristine; }; var _hasValidationError = function (validationKey) { var _field = scope.form[field]; var _error = _field.$error[validationKey]; return (_error && !_field.$pristine) || (_error && !_field.$pristine); }; var _validate = function () { var hasError = _hasError(); var hasSuccess = _hasSuccess(); hasError ? element.addClass('has-error') : element.removeClass('has-error'); hasSuccess ? element.addClass('has-success') : element.removeClass('has-success'); for (var index = 0; index < errors.length; index++) errors[index].span.hide(); for (var index = 0; index < errors.length; index++) { if (_hasValidationError(errors[index].validationKey)) { errors[index].span.show(); break; } } }; scope.$watch('form.' + field + '.$pristine', _validate); for (var index = 0; index < errors.length; index++) scope.$watch('form.' + field + '.$error.' + errors[index].validationKey, _validate); } }; function ngMatch() { var directive = { require: 'ngModel', scope: { ngMatch: '=' }, link: link, restrict: 'A' }; return directive; function link(scope, element, attributes, ngModel) { ngModel.$validators.match = function (modelValue) { return modelValue == scope.ngMatch; }; scope.$watch('ngMatch', function () { ngModel.$validate(); }); } }; function ngPasswordPattern() { var regex1 = new RegExp(/^((?=.*\d)(?=.*[^ \t0-9!"\#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]).{6,})$/i); var regex2 = new RegExp(/^(?!.*(\d)\1{2})(?!.*(0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){2}).{6,100}$/i); var regex3 = new RegExp(/^(?!.*(abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz)).{6,100}$/i); var regex4 = new RegExp(/^(?!.*(.)\1{2}).*$/i); var regex5 = new RegExp(/^(?!.*(admin|administrator|password)).{6,100}$/i); var directive = { require: 'ngModel', link: link, restrict: 'A' }; return directive; function link(scope, element, attributes, ngModel) { ngModel.$validators.passwordPattern = function (modelValue) { return regex1.test(modelValue); }; ngModel.$validators.passwordSpecialCharacters = function (modelValue) { return regex2.test(modelValue) && regex3.test(modelValue) && regex4.test(modelValue); }; ngModel.$validators.passwordSpecialWords = function (modelValue) { return regex5.test(modelValue); }; } }; })();<file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.eSign.cs using SaaS.Data.Entities.eSign; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthDbContext { internal async Task eSignUseIncreaseAsync(Guid accountId, Guid? accountProductId = null, Guid? accountMicrotransactionId = null) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId"), accountProductId.ToSql("accountProductId"), accountMicrotransactionId.ToSql("accountMicrotransactionId") }; await ExecuteNonQueryAsync("[eSign].[peSignUseIncrease]", sqlParams); } internal async Task<int> eSignPackageHistoryGetFreeNumberOfSigns(int oauthClientId, eSignClient eSignClient, string ipAddressHash) { var sqlParams = new SqlParameter[] { oauthClientId.ToSql("oauthClientId"), eSignClient.ToSql("eSignClientId"), ipAddressHash.ToSql("ipAddressHash") }; return (int)(await ExecuteScalarAsync("[eSign].[peSignPackageHistoryGetFreeNumberOfSigns]", sqlParams)); } internal async Task eSignPackageHistorySetAsync(eSignPackageHistory history) { var sqlParams = new SqlParameter[] { history.AccountId.ToSql("accountId"), history.oAuthClientId.ToSql("oauthClientId"), history.eSignClientId.ToSql("eSignClientId"), history.PackageId.ToSql("packageId"), history.IsSuccess.ToSql("isSuccess"), history.HttpStatusCode.ToSql("httpStatusCode"), history.IpAddressHash.ToSql("ipAddressHash"), history.AccountProductId.ToSql("accountProductId"), history.AccountMicrotransactionId.ToSql("accountMicrotransactionId"), }; await ExecuteNonQueryAsync("[eSign].[peSignPackageHistorySet]", sqlParams); } internal async Task<eSignApiKey> eSignApiKeyGetAsync(Guid accountId, eSignClient eSignClient) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId"), eSignClient.ToSql("eSignClientId") }; return await ExecuteReaderAsync<eSignApiKey>("[eSign].[peSignApiKeyGetByAccountId]", sqlParams); } public List<eSignApiKey> eSignApiKeysNeedRefreshGet(int top = 10) { var sqlParams = new SqlParameter[] { top.ToSql("top") }; return ExecuteReaderCollection<eSignApiKey>("[eSign].[peSignApiKeyGetNeedRefresh]", sqlParams); } internal async Task eSignApiKeySetAsync(Guid accountId, string email, eSignClient eSignClient, string apiKey) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId"), email.ToSql("email"), eSignClient.ToSql("eSignClientId"), apiKey.ToSql("apiKey") }; await ExecuteNonQueryAsync("[eSign].[peSignApiKeySetByAccountId]", sqlParams); } internal void eSignApiKeyDelete(int id) { var sqlParams = new SqlParameter[] { id.ToSql("id") }; ExecuteNonQuery("[eSign].[peSignApiKeyDelete]", sqlParams); } } }<file_sep>/Shared/Upclick.Api.Client/UpclickClient.cs namespace Upclick.Api.Client { public partial class UpclickClient { private UpclickHttpClient _upclickHttpClient; public UpclickClient(string login, string password) { _upclickHttpClient = new UpclickHttpClient(login, password); } public string Token(string method) { return _upclickHttpClient.Token(method); } } } <file_sep>/Web.Api/SaaS.UI.Admin/App_Start/AppSettings.cs namespace SaaS.UI.Admin.App_Start { public interface IAppSettings { IAppSettingsOAuth OAuth { get; } IAppSettingsValidation Validation { get; } } public interface IAppSettingsOAuth { string Path { get; } string ClientId { get; } string ClientSecret { get; } string Scope { get; } } public interface IAppSettingsValidation { string FirstNamePattern { get; } string LastNamePattern { get; } string EmailPattern { get; } string UrlPattern { get; } string JsFirstNamePattern { get; } string JsLastNamePattern { get; } string JsEmailPattern { get; } string JsUrlPattern { get; } } public sealed class AppSettings : IAppSettings { public IAppSettingsOAuth OAuth { get; internal set; } public IAppSettingsValidation Validation { get; internal set; } } public sealed class AppSettingsOAuth : IAppSettingsOAuth { public string Path { get; internal set; } public string ClientId { get; internal set; } public string ClientSecret { get; internal set; } public string Scope { get; internal set; } } public sealed class AppSettingsValidation : IAppSettingsValidation { public string FirstNamePattern { get; internal set; } public string LastNamePattern { get; internal set; } public string EmailPattern { get; internal set; } public string UrlPattern { get; internal set; } public string JsFirstNamePattern { get { return string.Format("/{0}/", FirstNamePattern); } } public string JsLastNamePattern { get { return string.Format("/{0}/", LastNamePattern); } } public string JsEmailPattern { get { return string.Format("/{0}/i", EmailPattern); } } public string JsUrlPattern { get { return string.Format("/{0}/", UrlPattern); } } } }<file_sep>/Web.Api/SaaS.Api/Models/Api/Oauth/ChangePasswordViewModel.cs using SaaS.Api.Models.Validation; using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Api.Oauth { public class ChangePasswordViewModel { [Required, DataType(DataType.Password)] public string OldPassword { get; set; } [Required, DataType(DataType.Password), PasswordRegex] public string NewPassword { get; set; } } }<file_sep>/Web.Api/SaaS.Api/Models/Api/Oauth/ParamsViewModel.cs using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Api.Oauth { public class ParamsViewModel { private string _cmp = null; private string _build = null; [MaxLength(128)] public string Cmp { get { return _cmp; } set { if (string.IsNullOrEmpty(value)) return; _cmp = value.Trim(); } } [MaxLength(10)] public string Build { get { return _build; } set { if (string.IsNullOrEmpty(value)) return; _build = value.Trim(); } } } }<file_sep>/Web.Api/SaaS.Api.Sign/Controllers/Api/ESign20/eSignLiteLimitation.cs namespace SaaS.Api.Sign.Controllers.Api.eSign20 { internal static class eSignLiteLimitation { /// <summary> /// In bytes(10 mb) /// </summary> internal const ulong FileSize = 10 * 1024 * 1024; internal const string FileSizeError = "Users file exceeds the maximum size."; internal const string FileSizeMinorWarning= "Users file exceeds the maximum size. Users sign will be used."; internal const ulong Recipients = 2; internal const string RecipientsError = "User exceeded the maximum amount of recipients."; internal const string RecipientsMinorWarning = "User exceeded the maximum amount of recipients. Users sign will be used."; internal const uint SignsPerDay = 1; internal const string SignsPerDayError = "User exceeded the maximum amount of signs."; internal const string SignsPerDayMinorWarning = "User exceeded the maximum amount of signs. Users sign will be used."; } }<file_sep>/Test/SaaS.Api.Test/Models/Api/Oauth/SessionViewModel.cs using System; namespace SaaS.Api.Test.Models.Api.Oauth { public class SessionViewModel { public Guid? MachineId { get; set; } public string MotherboardID { get; set; } public string PhysicalMAC { get; set; } public bool IsAutogeneratedMachineKey { get; set; } public string OsVersion { get; set; } public string PcName { get; set; } } }<file_sep>/Shared/SaaS.Data.Entities/View/ViewOwnerAccount.cs using SaaS.Data.Entities.View.Oauth; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Data.Entities.View { public class ViewOwnerAccount { public Guid AccountId { get; set; } public string Email { get; set; } [NotMapped] public List<ViewAccountSystem> AccountSystems { get; set; } [NotMapped] public List<ViewSessionToken> SessionTokens { get; set; } } }<file_sep>/Web.Api/SaaS.Sso/src/js/controllers/index.js angular.module('app.controllers') .controller('indexController', ['$state', '$storage', ($state, $storage) => { let accounts = $storage.getAccounts(); if (accounts.length > 1) return $state.go('account/select'); return $state.go('account/identifier', { email: accounts.length ? accounts[0].email : null }); }]);<file_sep>/Web.Api/SaaS.UI.Admin/js/services/api.js (function () { 'use strict'; angular .module('app.services') .factory('$api', factory); factory.$inject = ['$q', '$http', '$notify', 'appSettings']; function factory($q, $http, $notify, appSettings) { var _apiHeaders = { 'Content-Type': 'application/x-www-form-urlencoded' }; var _uri = function (method) { return appSettings.oauth.path + method; }; var _get = function (url, json) { json = json || {}; var deferred = $q.defer(); $http.get(_uri(url + '?' + $.param(json))).then(function (response) { deferred.resolve(response.data); }, function (response) { $notify.serverError(); deferred.reject(response.status); }); return deferred.promise; }; var _put = function (url, json) { json = json || {}; var deferred = $q.defer(); $http.put(_uri(url), json).then(function (response) { deferred.resolve(response.data); }, function (response) { var error = response.data ? response.data.error_description : ''; error ? $notify.error(error) : $notify.serverError(); deferred.reject(response.status); }); return deferred.promise; }; var _post = function (url, json) { json = json || {}; var deferred = $q.defer(); $http.post(_uri(url), json).then(function (response) { deferred.resolve(response.data); }, function (response) { var error = response.data ? response.data.error_description : ''; error ? $notify.error(error) : $notify.serverError(); deferred.reject(response.status); }); return deferred.promise; }; var _delete = function (uri) { var deferred = $q.defer(); $http.delete(_uri(uri), {}).then(function (response) { deferred.resolve(response.data); }, function (response) { if (response.data.message.includes("timeout")) { $notify.info("This action took longer than expected. Please try again"); } else { $notify.error(response.data.message); } //error ? $notify.error(error) : $notify.serverError(); deferred.reject(response.status); }); return deferred.promise; }; var service = {}; var accountStatusEnum = { none: 0, isActivated: 1 << 0, isAnonymous: 1 << 1, isBusiness: 1 << 2, isPreview: 1 << 3 };; service.user = { get: function () { return _get('api/user'); }, insert: function (json) { return _post('api/user/insert', json); }, update: function (json) { return _post('api/user/update', json); }, changePassword: function (json) { return _post('api/user/change-password', json); }, activate: function (id) { return _post('api/user/' + id + '/activate'); }, deactivate: function (id) { return _post('api/user/' + id + '/deactivate'); } }; service.account = { isActivated: function (account) { return !!(account.status & accountStatusEnum.isActivated); }, isBusiness: function (account) { return !!(account.status & accountStatusEnum.isBusiness); }, isPreview: function (account) { return !!(account.status & accountStatusEnum.isPreview); }, get: function (json) { var url = 'api/account/' if (json.id) { url += json.id; delete json['id']; } return _get(url, json); }, set: function (accountId, json) { return _post('api/account/' + accountId, json); }, _delete: function (accountId) { return _delete('api/account/' + accountId); }, _deleteGDPR: function (accountId) { return _delete('api/account/gdpr/' + accountId); }, register: function (json) { return _put('api/account/', json); }, uid: function (accountId) { return _get('api/account/' + accountId + '/uid/'); }, confirmEmail: function (accountId, json) { return _post('api/account/' + accountId + '/confirm-email/?' + $.param(json)); }, changePassword: function (accountId, json) { return _post('api/account/' + accountId + '/change-password/', json); }, recoverPassword: function (accountId) { return _post('api/account/' + accountId + '/recover-password/'); }, merge: function (accountId, accountIdFrom, accountIdPrimaryEmail) { return _post('api/account/' + accountId + '/merge/?' + $.param({ accountIdFrom: accountIdFrom, accountIdPrimaryEmail: accountIdPrimaryEmail })); }, external: { sessionTokens: function (accountId) { return _get('api/account/' + accountId + '/external/session-token/'); }, }, subEmails: function (accountId) { return _get('api/account/' + accountId + '/sub-email/'); }, addProduct: function (accountId, json) { return _put('api/account/' + accountId + '/product/', json); }, ownerProducts: function (accountId) { return _get('api/account/' + accountId + '/owner-product/'); }, ownerProductDetails: function (accountId, accountProductId) { return _get('api/account/' + accountId + '/owner-product/' + accountProductId); }, ownerProductAssign: function (accountId, accountProductId, json) { return _post('api/account/' + accountId + '/owner-product/' + accountProductId + '/assign/', json); }, ownerProductUnassign: function (accountId, accountProductId, targetAccountId) { return _post('api/account/' + accountId + '/owner-product/' + accountProductId + '/unassign/' + targetAccountId); }, ownerProductDeactivate: function (accountId, accountProductId) { return _post('api/account/' + accountId + '/owner-product/' + accountProductId + '/deactivate/'); }, ownerProductResume: function (accountId, accountProductId) { return _post('api/account/' + accountId + '/owner-product/' + accountProductId + '/resume/'); }, ownerProductSuspend: function (accountId, accountProductId) { return _post('api/account/' + accountId + '/owner-product/' + accountProductId + '/suspend/'); }, ownerProductAllowed: function (accountId, accountProductId, allowed) { return _post('api/account/' + accountId + '/owner-product/' + accountProductId + '/allowed/?' + $.param({ allowed: allowed })); }, ownerProductNextRebillDate: function (accountId, accountProductId, nextRebillDate) { return _post('api/account/' + accountId + '/owner-product/' + accountProductId + '/next-rebill-date/?' + $.param({ nextRebillDate: nextRebillDate.toUTCString() })); }, ownerProductEndDate: function (accountId, accountProductId, endDate) { return _post('api/account/' + accountId + '/owner-product/' + accountProductId + '/end-date/?' + $.param({ endDate: endDate.toUTCString() })); } }; service.log = { get: function (json) { return _get('api/log/', json); }, csv: function (json) { window.open(_uri('api/log/') + '?' + $.param(json) + '&format=csv', '_self', ''); }, logActionType: { get: function (json) { return _get('api/log/action-type/', json); } } }; service.upclick = { products: function (json) { return _get('api/upclick/products', json); } }; service.emails = { getTemplates: function () { return _get('api/emails/templates'); } }; var productStatus = {}; Object.defineProperties(productStatus, { none: { value: 0, writable: false }, isDisabled: { value: 1 << 0, writable: false }, isExpired: { value: 1 << 1, writable: false }, isTrial: { value: 1 << 2, writable: false }, isFree: { value: 1 << 3, writable: false }, isMinor: { value: 1 << 4, writable: false }, isDefault: { value: 1 << 5, writable: false }, isPPC: { value: 1 << 6, writable: false }, isUpgradable: { value: 1 << 7, writable: false }, isNew: { value: 1 << 8, writable: false }, isPaymentFailed: { value: 1 << 9, writable: false }, isRenewal: { value: 1 << 10, writable: false }, isOwner: { value: 1 << 11, writable: false }, IsNotAbleToRenewCreditCartExpired: { value: 1 << 12, writable: false } }); service.productStatus = productStatus; return service; } })();<file_sep>/Shared/SaaS.Identity/AccountValidator.cs using Microsoft.AspNet.Identity; using SaaS.Data.Entities.Accounts; using System.Threading.Tasks; namespace SaaS.Identity { internal class AccountValidator<TUser> : IIdentityValidator<TUser> where TUser : Account { //private AuthDbContext _context; //internal AccountValidator() { } //internal AccountValidator(AuthDbContext context) //{ // _context = context; //} public async Task<IdentityResult> ValidateAsync(TUser user) { //if (!object.Equals(_context, null)) //{ // var account = await _context.AccountGetAsync(user.Email, isIncludeSubEmails: true); // if (!object.Equals(account, null) && account.Id != user.Id) // return IdentityResult.Failed("Select a different email address. An account has already been created with this email address."); //} return await Task.Run(() => { return IdentityResult.Success; }); } } } <file_sep>/Shared/SaaS.Data.Entities/Accounts/Email.cs using System; using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Data.Entities.Accounts { public class Email : AccountEntity<int> { [Column("status")] public Status StatusId { get; set; } [Column("emailCustomParam", TypeName = "xml")] public string EmailCustomParam { get; set; } [Column("modelCustomParam", TypeName = "xml")] public string ModelCustomParam { get; set; } [Column("languageID")] public string LanguageId { get; set; } [Column("createDate")] [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public DateTime CreateDate { get; set; } } }<file_sep>/Shared/SaaS.Identity/EmailRepository/IEmailRepository.cs using SaaS.Data.Entities; using SaaS.Data.Entities.Accounts; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Identity { public interface IEmailRepository : IDisposable { Task EmailInsertAsync(Guid accountId, Status status, string emailCustomParam, string modelCustomParam); Task<List<Email>> EmailsGetAsync(Status status, int top); Task EmailStatusSetAsync(int id, Status status); } } <file_sep>/Web.Api/SaaS.UI.Admin/DependencyResolution/IoC.cs // -------------------------------------------------------------------------------------------------------------------- // <copyright file="IoC.cs" company="Web Advanced"> // Copyright 2012 Web Advanced (www.webadvanced.com) // 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. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using SaaS.Api.Client; using SaaS.UI.Admin.App_Start; using StructureMap; using StructureMap.Graph; using System.Configuration; namespace SaaS.UI.Admin.DependencyResolution { public static class IoC { private static string GetString(string key) { return ConfigurationManager.AppSettings[key]; } public static IContainer Initialize() { var appSettings = new AppSettings { OAuth = new AppSettingsOAuth { Path = GetString("oauth:path"), ClientId = GetString("oauth:clientId"), ClientSecret = GetString("oauth:clientSecret"), Scope = GetString("oauth:scope") }, Validation = new AppSettingsValidation { FirstNamePattern = @"^[^\^<>()\[\]\\;:@?%\|$%*?#&¸¼!+€£¢¾½÷פ¶»¥¦µ©®°§«´¨™±°º¹²³ª¯¬`""'/]*$", LastNamePattern = @"^[^\^<>()\[\]\\;:@?%\|$%*?#&¸¼!+€£¢¾½÷פ¶»¥¦µ©®°§«´¨™±°º¹²³ª¯¬`""'/]*$", EmailPattern = @"^[-a-z0-9!#$%&'*+\/=?^_`{|}~]+(\.[-a-z0-9!#$%&'*+\/=?^_`{|}~]+)*@([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?\.)*[a-z]{1,20}$", UrlPattern = @"^(https?)://[^\s/$.?#].[^\s]*$" } }; var oauthService = new SaaSApiOauthService(appSettings.OAuth.Path, appSettings.OAuth.ClientId); ObjectFactory.Initialize(x => { x.Scan(scan => { scan.TheCallingAssembly(); scan.WithDefaultConventions(); }); x.For<IAppSettings>().Singleton().Use(appSettings); x.For<ISaaSApiOauthService>().Singleton().Use(oauthService); }); return ObjectFactory.Container; } } }<file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.Nps.cs using System; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthDbContext { internal async Task NpsInsertAsync(string questioner, Guid? accountId, string clientName, string clientVersion, byte rating, byte? ratingUsage, string comment) { var sqlParams = new SqlParameter[] { //questioner.ToSql("npsQuestionerName"), accountId.ToSql("accountId"), clientName.ToSql("clientName"), clientVersion.ToSql("clientVersion"), rating.ToSql("rating")//, //ratingUsage.ToSql("ratingUsage"), //comment.ToSql("comment") }; await ExecuteNonQueryAsync("[accounts].[pNpsInsert]", sqlParams); } } }<file_sep>/Shared/SaaS.Api.Models/Products/AddOwnerProductViewModel.cs using Newtonsoft.Json; using System; namespace SaaS.Api.Models.Products { public class AddOwnerProductViewModel { public Guid UserId { get; set; } public string ProductUid { get; set; } [JsonProperty("Currency")] public string Currency { get; set; } public decimal Price { get; set; } public decimal PriceUsd { get; set; } public int Quantity { get; set; } } } <file_sep>/Shared/SaaS.Identity.Admin/AuthRepository/AuthRepository.SessionToken.cs using SaaS.Data.Entities.Admin.Oauth; using System; using System.Threading.Tasks; namespace SaaS.Identity.Admin { public partial class AuthRepository { public async Task<SessionToken> SessionTokenGetAsync(Guid id) { return await _context.SessionTokenGetAsync(id); } public async Task SessionTokenInsertAsync(SessionToken token) { await _context.SessionTokenInsertAsync(token); } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AdminAccountController.Details.cs using AutoMapper; using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.View; using SaaS.IPDetect; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AdminAccountController { [HttpGet, Route("info")] public async Task<IHttpActionResult> Info(string email) { var user = await _auth.AccountGetAsync(email); if (object.Equals(user, null)) return AccountNotFound(); return Ok(new { id = user.Id, email = user.Email, firstName = user.FirstName, lastName = user.LastName, status = user.GetStatus() }); } [HttpPost, Route("info"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> Info(Guid userId, AuthNameViewModel model) { var user = await _auth.AccountGetAsync(userId); if (object.Equals(user, null)) return AccountNotFound(); var userWithEmail = await _auth.AccountGetAsync(model.Email); if (!object.Equals(userWithEmail, null) && user.Id != userWithEmail.Id) return AccountExists(); user.FirstName = model.FirstName; user.LastName = model.LastName; user.Email = model.Email; var result = await _auth.AccountUpdateAsync(user); var errorResult = GetErrorResult(result); if (!object.Equals(errorResult, null)) return errorResult; return Ok(); } [HttpGet, Route("details")] public async Task<IHttpActionResult> Details(Guid userId) { try { var user = await _auth.AccountGetAsync(userId); if (object.Equals(user, null)) return AccountNotFound(); var accountDetails = await _auth.AccountDetailsGetAsync(user.Id); var accountDetailsViewModel = new AccountDetailsViewModel(); accountDetailsViewModel = Mapper.Map(accountDetails, accountDetailsViewModel); return Ok(accountDetailsViewModel); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpPost, Route("details"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> Details(Guid userId, AccountDetailsViewModel model) { try { var account = await _auth.AccountGetAsync(userId); if (object.Equals(account, null)) return AccountNotFound(); var accountsDetail = new ViewAccountDetails(); accountsDetail = Mapper.Map(model, accountsDetail); accountsDetail.GeoIp = IpAddressDetector.IpAddress; accountsDetail.Id = account.Id; await _auth.AccountDetailsSetAsync(accountsDetail); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } } }<file_sep>/Web.Api/SaaS.Api.Admin/Oauth/Providers/SaaSAuthorizationServerProvider.GrantRefreshToken.cs using Microsoft.AspNet.Identity; using Microsoft.Owin.Security; using Microsoft.Owin.Security.OAuth; using SaaS.Data.Entities.Admin.View.Oauth; using SaaS.Identity.Admin; using System; using System.Security.Claims; using System.Threading.Tasks; namespace SaaS.Api.Admin.Oauth.Providers { public partial class SaaSAuthorizationServerProvider { public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context) { var identity = new ClaimsIdentity(context.Ticket.Identity); var properties = context.Ticket.Properties.Dictionary; ViewUser user = null; using (var auth = new AuthRepository()) user = await auth.ViewUserGetAsync(Guid.Parse(identity.GetUserId())); if (object.Equals(user, null) || !user.IsActive) return; identity.AddClaims(user); context.Validated(new AuthenticationTicket(identity, context.Ticket.Properties)); } } }<file_sep>/Web.Api/SaaS.Api.Admin/Controllers/Api/AccountController.cs using SaaS.Api.Admin.Models.Oauth; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Admin.Oauth; using System; using System.Linq; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Admin.Controllers.Api { [RoutePrefix("api/account"), Authorize] public partial class AccountController : SaaSApiController { [HttpGet] public async Task<IHttpActionResult> Index(string filter = null, string globalOrderId = null, string email = null, string transactionOrderUid = null) { try { if (!string.IsNullOrEmpty(email)) { return await CurrentAccountExecuteAsync(async delegate (Account account) { return await Task.FromResult(Ok(new AccountViewModel(account))); }, email, isIncludeSubEmails: true); } if (!string.IsNullOrEmpty(transactionOrderUid)) { var account = await _auth.AccountGetByTransactionOrderUidAsync(transactionOrderUid); if (object.Equals(account, null)) return AccountNotFound(); return Ok(new AccountViewModel(account)); } var accounts = await _auth.AccountsGetAsync(filter, globalOrderId); return Ok(accounts.Select(account => new AccountViewModel(account))); } catch (Exception exc) { return ErrorContent(exc); } } [HttpPut, ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> AccountPut(AuthNameViewModel model) { try { var account = await _auth.AccountGetAsync(model.Email, isIncludeSubEmails: true); if (!object.Equals(account, null)) return AccountExists(); account = new Account(model.Email, model.FirstName, model.LastName); var errorResult = GetErrorResult(await _auth.AccountCreateAsync(account)); if (!object.Equals(errorResult, null)) return errorResult; account = await _auth.AccountGetAsync(model.Email); var log = string.Format("Customer({0}) has been created.", account.Email); await LogInsertAsync(log, LogActionTypeEnum.AccountCreate, account.Id); return Ok(new AccountViewModel(account)); } catch (Exception exc) { return ErrorContent(exc); } } [HttpGet, Route("{accountId:guid}")] public async Task<IHttpActionResult> AccountGet(Guid accountId) { return await CurrentAccountExecuteAsync(async delegate (Account account) { return await Task.FromResult(Ok(new AccountViewModel(account))); }, accountId); } [HttpGet, Route("{accountId:guid}/uid")] public async Task<IHttpActionResult> AccountUidGet(Guid accountId) { return await CurrentAccountExecuteAsync(async delegate (Account account) { var uid = await _auth.AccountUidGetAsync(accountId); return Ok(new { uid }); }, accountId); } [HttpPost, Route("{accountId:guid}"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> AccounPost(Guid accountId, AuthNameViewModel model) { return await CurrentAccountExecuteAsync(async delegate (Account account) { var userWithEmail = await _auth.AccountGetAsync(model.Email, isIncludeSubEmails: true); if (!object.Equals(userWithEmail, null) && account.Id != userWithEmail.Id) return AccountExists(); if (!string.Equals(account.FirstName, model.FirstName, StringComparison.InvariantCultureIgnoreCase) || !string.Equals(account.LastName, model.LastName, StringComparison.InvariantCultureIgnoreCase)) { account.FirstName = model.FirstName; account.LastName = model.LastName; var errorResult = GetErrorResult(await _auth.AccountUpdateAsync(account)); if (!object.Equals(errorResult, null)) return errorResult; var log = string.Format("Customer's({0}) first or last name have been changed.", account.Email); await LogInsertAsync(log, LogActionTypeEnum.AccountEdit, account.Id); } if (!string.Equals(account.Email, model.Email, StringComparison.InvariantCultureIgnoreCase)) { account.Email = model.Email; await _auth.AccountSubEmailPendingDeleteAsync(account.Id); var pending = await _auth.AccountSubEmailPendingSetAsync(account.Id, model.Email); await _auth.AccountEmailSetAsync(pending); var log = string.Format("Customer's({0}) email has been changed.", account.Email); await LogInsertAsync(log, LogActionTypeEnum.AccountEdit, account.Id); } return Ok(new AccountViewModel(account)); }, accountId); } [HttpDelete, Route("{accountId:guid}")] public async Task<IHttpActionResult> AccountDelete(Guid accountId) { return await CurrentAccountExecuteAsync(async delegate (Account account) { await _auth.AccountDeleteAsync(accountId); var log = string.Format("Customer({0}) has been deleted.", account.Email); await LogInsertAsync(log, LogActionTypeEnum.AccountDelete, account.Id); return Ok(); }, accountId); } [HttpDelete, Route("gdpr/{accountId:guid}")] public async Task<IHttpActionResult> AccountGDPRDelete(Guid accountId) { return await CurrentAccountExecuteAsync(async delegate (Account account) { var result = await _gdpr.AccountGDPRDeleteAsync(account.Email); if (!result.Equals("success", StringComparison.InvariantCultureIgnoreCase)) { return BadRequest(result); } var log = $"Customer({account.Email}) has been deleted by GDPR."; await LogInsertAsync(log, LogActionTypeEnum.AccountDelete, account.Id); return Ok(); }, accountId); } [HttpPost, Route("{accountId:guid}/confirm-email")] public async Task<IHttpActionResult> ConfirmEmail(Guid accountId, string build) { return await CurrentAccountExecuteAsync(async delegate (Account account) { var errorResult = GetErrorResult(await _auth.AccountConfirmEmailAsync(accountId)); if (!object.Equals(errorResult, null)) return errorResult; if ("b2b".Equals(build, StringComparison.InvariantCultureIgnoreCase)) { await _auth.AccountMaskAsBusinessAsync(account); await LogInsertAsync(string.Format("Customer({0}) has been marked as business.", account.Email), LogActionTypeEnum.AccountMaskBusiness, account.Id); } await _auth.AccountActivateAsync(account); await LogInsertAsync(string.Format("Customer({0}) has been activated.", account.Email), LogActionTypeEnum.AccountActivate, account.Id); account = await _auth.AccountGetAsync(accountId); return Ok(new AccountViewModel(account)); }, accountId); } [HttpPost, Route("{accountId:guid}/change-password"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> ChangePassword(Guid accountId, CustomerChangePasswordViewModel model) { return await CurrentAccountExecuteAsync(async delegate (Account account) { var errorResult = GetErrorResult(await _auth.AccountPasswordSetAsync(account, model.NewPassword)); if (!object.Equals(errorResult, null)) return errorResult; var log = string.Format("Customer's({0}) password has been changed.", account.Email); await LogInsertAsync(log, LogActionTypeEnum.AccountChangePassword, account.Id); return Ok(); }, accountId); } [HttpPost, Route("{accountId:guid}/recover-password"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> RecoverPassword(Guid accountId) { return await CurrentAccountExecuteAsync(async delegate (Account account) { await NotificationManager.RecoverPassword(account); return Ok(); }, accountId); } } }<file_sep>/Web.Api/SaaS.UI.Admin/js/controllers/user/sign-in.js (function () { 'use strict'; angular .module('app.controllers') .controller('signInController', controller); controller.$inject = ['$scope', '$auth', '$form']; function controller($scope, $auth, $form) { $scope.model = {}; $scope.status = null; $scope.isBusy = false; $scope.submit = function (form) { $form.submit($scope, form, function () { return $auth.signIn($scope.model.login, $scope.model.password) .then(function (response) { window.location = '/'; }, function () { $scope.isBusy = false; }); }); }; }; })();<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.Survey.cs using System.Collections.Generic; using Newtonsoft.Json; using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Api.Oauth; using System.IO; using System.IO.Compression; using System.Net; using System.Threading.Tasks; using System.Web.Http; using RazorEngine; using Newtonsoft.Json.Linq; using System; using System.Linq; using SaaS.Data.Entities.Accounts; using System.Data; using Microsoft.Office.Interop.Excel; using System.Net.Http; using System.Net.Http.Headers; using System.Web; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { private static readonly string XlsxMediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; [HttpPost, Route("survey"), SaaSAuthorize, ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> Survey(SurveyViewModel model) { var compressedData = Compress(System.Text.Encoding.UTF8.GetBytes(model.Data.ToString(Formatting.None))); await _auth.SurveyAsync(AccountId, compressedData, model.Lang); return Ok(); } [HttpGet, Route("survey/getall"), SaaSAuthorize(Roles = "admin")] public async Task<IHttpActionResult> GetAllSurvey() { try { return Ok(await _auth.GetAllSurveyAsync()); } catch (Exception e) { return BadRequest(e.ToString()); } } #if DEBUG [HttpPost, Route("survey/report")] public async Task<IHttpActionResult> SurveyReport(List<AccountSurvey> surveys) { try { //only for Debug lock service on stage if (HttpContext.Current.Request.Headers.GetValues("Accept").Any(headerValue => !string.IsNullOrWhiteSpace(headerValue) && headerValue.Split(',').Any(segment => MediaTypeHeaderValue.Parse(segment).MediaType == XlsxMediaType))) return ExportToExcel(surveys); else return ExportToJson(surveys); } catch (Exception e) { return BadRequest(e.ToString()); } } #endif private IHttpActionResult ExportToJson(IEnumerable<AccountSurvey> data) { var decompressedSurveys = new List<string>(); foreach (var survey in data) { var decompressedData = Decompress(survey.CollectedData); decompressedSurveys.Add(System.Text.Encoding.UTF8.GetString(decompressedData)); } return Ok(decompressedSurveys); } private IHttpActionResult ExportToExcel(IEnumerable<AccountSurvey> data) { var sectionsTable = new List<SectionTableViewModel>(); List<SectionTableRowViewModel> rows = new List<SectionTableRowViewModel>(); foreach (var survey in data) { var row = new SectionTableRowViewModel(survey.AccountId, survey.CreateDate); try { var decompressedData = Decompress(survey.CollectedData); var surveySections = JsonConvert.DeserializeObject<IEnumerable<SurveySection>>(System.Text.Encoding.UTF8.GetString(decompressedData)); foreach (var surveySection in surveySections) { SectionTableViewModel sectionTableVM = sectionsTable.FirstOrDefault(item => item.Id == surveySection.Id); if (sectionTableVM == null) { sectionTableVM = new SectionTableViewModel(surveySection.Id); sectionsTable.Add(sectionTableVM); } foreach (var surveySectionGroup in surveySection.Groups) { SectionGroupTableViewModel sectionGroupTableVM = sectionTableVM.Groups.FirstOrDefault(g => g.Id == surveySectionGroup.Id); if (sectionGroupTableVM == null) { sectionGroupTableVM = new SectionGroupTableViewModel(surveySectionGroup.Id); sectionTableVM.Groups.Add(sectionGroupTableVM); } foreach (var surveySectionGroupQa in surveySectionGroup.Qa) { var qId = string.Format("{0}_{1}_{2}", surveySection.Id, surveySectionGroup.Id, surveySectionGroupQa.Q); if (!sectionGroupTableVM.QAs.Contains(qId)) { sectionGroupTableVM.QAs.Add(qId); } row.QAs.Add(new SurveyQATable(qId, surveySectionGroupQa.Q, surveySectionGroupQa.A)); } } } } catch (Exception e) { } rows.Add(row); } using (var table = new System.Data.DataTable()) { var allQas = sectionsTable.SelectMany(s => s.Groups.SelectMany(g => g.QAs)); table.Columns.Add("DateTime UTC", typeof(string)); table.Columns.Add("AccountId", typeof(string)); foreach (var qaColumn in allQas) { table.Columns.Add(qaColumn, typeof(string)); } foreach (var row in rows) { var dataRow = table.NewRow(); dataRow["DateTime UTC"] = row.CreateDate.ToString(); dataRow["AccountId"] = row.AccountId.ToString(); for (int i = 2; i < dataRow.Table.Columns.Count; i++) { DataColumn column = dataRow.Table.Columns[i]; var existed = row.QAs.FirstOrDefault(item => item.QId == column.ColumnName); if (existed != null) dataRow[column] = existed.A; } table.Rows.Add(dataRow); } return DataTableToExcel(table, sectionsTable); } } private IHttpActionResult DataTableToExcel(System.Data.DataTable dataTable, List<SectionTableViewModel> sectionsTable) { //var fileName = Path.GetTempFileName(); string fileName = HttpContext.Current.Server.MapPath($"temp/{Guid.NewGuid()}.xlsx"); string tempDir = Path.GetDirectoryName(fileName); if (!Directory.Exists(tempDir)) Directory.CreateDirectory(tempDir); var excel = new Microsoft.Office.Interop.Excel.Application(); var worKbooK = excel.Workbooks.Add(Type.Missing); try { excel.Visible = false; excel.DisplayAlerts = false; var worKsheeT = (Microsoft.Office.Interop.Excel.Worksheet)worKbooK.ActiveSheet; worKsheeT.Name = "SurveyReport"; int rowDataPadding = 1; int skipCells = 2; for (int i = 0; i < sectionsTable.Count; i++) { var from = skipCells; skipCells += sectionsTable[i].QaCount; worKsheeT.Cells[rowDataPadding, from + 1] = $"Section {sectionsTable[i].Id}"; var cell = worKsheeT.Cells[rowDataPadding, from + 1]; cell.Font.Bold = true; cell.Font.Size += 2; cell.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; worKsheeT.Range[worKsheeT.Cells[rowDataPadding, from + 1], worKsheeT.Cells[rowDataPadding, skipCells]].Merge(); } rowDataPadding++; skipCells = 2; var groups = sectionsTable.SelectMany(s => s.Groups).ToList(); for (int i = 0; i < groups.Count; i++) { var from = skipCells; skipCells += groups[i].QAs.Count; worKsheeT.Cells[rowDataPadding, from + 1] = $"Grop {groups[i].Id}"; var cell = worKsheeT.Cells[rowDataPadding, from + 1]; cell.Font.Bold = true; cell.Font.Size += 1; cell.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; worKsheeT.Range[worKsheeT.Cells[rowDataPadding, from + 1], worKsheeT.Cells[rowDataPadding, skipCells]].Merge(); } rowDataPadding++; skipCells = 0; for (var i = 0; i < dataTable.Columns.Count; i++) { var name = dataTable.Columns[i].ColumnName; var cheat = name.LastIndexOf("_"); if (cheat >= 0) { name = name.Substring(cheat+1); } worKsheeT.Cells[rowDataPadding, i + 1] = name; var cell = worKsheeT.Cells[rowDataPadding, i + 1]; cell.Font.Bold = true; } rowDataPadding++; for (int i = 0; i < dataTable.Rows.Count; i++) { var dataRow = dataTable.Rows[i]; for (int j = 0; j < dataTable.Columns.Count; j++) { var value = dataRow[j] as string; if (value != null) { worKsheeT.Cells[i + 1 + rowDataPadding, j + 1] = value; } } } var celLrangE = worKsheeT.Range[worKsheeT.Cells[3, 1], worKsheeT.Cells[3, dataTable.Columns.Count]]; celLrangE.EntireColumn.AutoFit(); worKbooK.SaveAs(fileName); } finally { worKbooK.Close(); excel.Quit(); } if (File.Exists(fileName)) { try { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(fileName))) { HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(ms.ToArray()); result.Content.Headers.ContentLength = ms.Length; result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "survey_report.xlsx" }; result.Content.Headers.ContentType = new MediaTypeHeaderValue(XlsxMediaType); return ResponseMessage(result); } } finally { File.Delete(fileName); } } return BadRequest(); } private static byte[] Compress(byte[] data) { using (var compressedStream = new MemoryStream()) using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress)) { zipStream.Write(data, 0, data.Length); zipStream.Close(); return compressedStream.ToArray(); } } private static byte[] Decompress(byte[] data) { using (var compressedStream = new MemoryStream(data)) { using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress)) { using (var resultStream = new MemoryStream()) { zipStream.CopyTo(resultStream); return resultStream.ToArray(); } } } } } }<file_sep>/Shared/SaaS.Common/Utils/TamperProofQuery.cs using SaaS.Common.Extensions; using System; using System.Collections.Specialized; using System.Security.Cryptography; using System.Text; using System.Web; using System.Linq; namespace SaaS.Common.Utils { public class TamperProofQuery { private readonly string _secret; private const string DefaultHashAlgorithm = "SHA256"; public TamperProofQuery(string secret = "S<KEY>") { _secret = secret; } public string ComputeDigest(string[] values, string hashAlgorithmName = DefaultHashAlgorithm) { if (string.IsNullOrEmpty(hashAlgorithmName)) hashAlgorithmName = DefaultHashAlgorithm; string saltedValues = String.Concat(values) + _secret; return ComputeHash(Encoding.UTF8.GetBytes(saltedValues), hashAlgorithmName); } public string ComputeDigestQuery(NameValueCollection query, out string encoded) { query["timestamp"] = TimeHelper.GetEpochTime().ToString(); string queryString = string.Join("&", query.AllKeys.Select(key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(query[key])))); queryString = queryString.EncryptString(); encoded = HttpUtility.UrlEncode(queryString); return ComputeDigest(new string[] { queryString }); } public bool IsTampered(string digest, string[] values, string hashAlgorithmName = DefaultHashAlgorithm) { if (string.IsNullOrEmpty(hashAlgorithmName)) hashAlgorithmName = DefaultHashAlgorithm; return !string.Equals(digest, ComputeDigest(values, hashAlgorithmName)); } public bool IsExpired(long expirePeriod) { return TimeHelper.GetEpochTime() - expirePeriod > 0; } ///// <summary> ///// check if timestamp is valid ///// </summary> ///// <param name="timestamp">time stamp</param> ///// <param name="expirePeriod">expire period in seconds</param> ///// <returns></returns> //public bool IsExpired(string timestamp, long expirePeriod) //{ // long timestampInt; // if (!long.TryParse(timestamp, out timestampInt)) // throw new ArgumentException("Time stamp is not valid integer number", "timestamp"); // return IsExpired(timestampInt, expirePeriod); //} //public bool IsExpired(long timestamp, long expirePeriod) //{ // return TimeHelper.GetEpochTime() - timestamp > expirePeriod; //} private string ComputeHash(byte[] content, string hashAlgorithmName) { byte[] hashByteArray; using (HashAlgorithm algorithm = HashAlgorithm.Create(hashAlgorithmName)) { if (algorithm == null) throw new ArgumentException("Unrecognized hash name", "hashAlgorithmName"); hashByteArray = algorithm.ComputeHash(content); } return BitConverter.ToString(hashByteArray).Replace("-", ""); } } } <file_sep>/WinService/SaaS.WinService.Core/ThreadQueue.cs using System; using System.Collections.Generic; using System.ComponentModel; namespace SaaS.WinService.Core { public class ThreadPool { internal class ThreadItem { private Delegate _task; private object[] _params; public ThreadItem(Delegate task, object[] @params) { _task = task; _params = @params; } internal void Invoke() { if (!object.Equals(_task, null)) _task.DynamicInvoke(_params); } } internal class ThreadCollection : List<ThreadItem> { } internal class ThreadQueue : Queue<ThreadItem> { } private readonly ThreadCollection _threads = new ThreadCollection(); private readonly ThreadQueue _queue = new ThreadQueue(); private readonly object addlock = new object(); private readonly object checklock = new object(); public event EventHandler Completed; private bool RaiseCompleteEventIfQueueEmpty = false; private int ThreadsMaxCount; public ThreadPool(int threadsMaxCount) { ThreadsMaxCount = threadsMaxCount; } public void Start() { CheckQueue(); } public void AddTask(Delegate task, object[] @params) { lock (addlock) { ThreadItem item = new ThreadItem(task, @params); if (IsFull) _queue.Enqueue(item); else StartThread(item); } } private void StartThread(ThreadItem task) { _threads.Add(task); BackgroundWorker thread = new BackgroundWorker(); thread.DoWork += delegate { task.Invoke(); }; thread.RunWorkerCompleted += delegate { _threads.Remove(task); CheckQueue(); if (_queue.Count == 0 && _threads.Count == 0 && RaiseCompleteEventIfQueueEmpty) OnCompleted(); }; thread.RunWorkerAsync(); } private void CheckQueue() { lock (checklock) { while (_queue.Count > 0 && _threads.Count < ThreadsMaxCount) StartThread(_queue.Dequeue()); if (_queue.Count == 0 && _threads.Count == 0 && RaiseCompleteEventIfQueueEmpty) OnCompleted(); } } protected void OnCompleted() { if (Completed != null) Completed(this, null); } public bool IsFull { get { return _threads.Count == ThreadsMaxCount; } } } } <file_sep>/Shared/SaaS.Api.Models/Oauth/ParamsViewModel.cs using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Oauth { public class ParamsViewModel { private string _cmp = null; private string _partner = null; private string _build = null; [MaxLength(128)] public string Cmp { get { return _cmp; } set { if (string.IsNullOrEmpty(value)) return; _cmp = value.Trim(); } } [MaxLength(128)] public string Partner { get { return _partner; } set { if (string.IsNullOrEmpty(value)) return; _partner = value.Trim(); } } [MaxLength(10)] public string Build { get { return _build; } set { if (string.IsNullOrEmpty(value)) return; _build = value.Trim(); } } public string Uid { get; set; } public int? GetUid() { int uid; if (int.TryParse(Uid, out uid)) return uid; return null; } } } <file_sep>/Web.Api/SaaS.Api.Mc/Startup.cs using Microsoft.Owin; using Microsoft.Owin.Security.OAuth; using Newtonsoft.Json.Serialization; using Owin; using SaaS.Api.Mc.Oauth; using System.Linq; using System.Net.Http.Formatting; using System.Web.Http; [assembly: OwinStartup(typeof(SaaS.Api.Mc.Startup))] namespace SaaS.Api.Mc { public class Startup { public static OAuthBearerAuthenticationOptions OAuthBearerOptions; static Startup() { OAuthBearerOptions = new OAuthBearerAuthenticationOptions() { Provider = new OAuthBearerProvider() }; } public void Configuration(IAppBuilder app) { app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); var config = GlobalConfiguration.Configuration; app.UseOAuthBearerAuthentication(OAuthBearerOptions); app.UseWebApi(config); config.Formatters.Remove(config.Formatters.XmlFormatter); var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; json.SerializerSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ssZ"; json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; var contractResolver = (DefaultContractResolver)json.SerializerSettings.ContractResolver; contractResolver.IgnoreSerializableAttribute = true; } } }<file_sep>/Shared/SaaS.Mailer/Models/ProductAssignedNotification.cs using System.Xml.Serialization; namespace SaaS.Mailer.Models { [XmlRoot("xml")] public class ProductAssignedNotification : CreatePasswordNotification { public ProductAssignedNotification() { } public ProductAssignedNotification(Notification user, string productName, Notification ownerUser) : base(user) { ProductName = productName; OwnerFirstName = ownerUser.FirstName; OwnerLastName = ownerUser.LastName; OwnerEmail = ownerUser.Email; } [XmlElement("productName")] public string ProductName { get; set; } [XmlElement("ownerFirstName")] public string OwnerFirstName { get; set; } [XmlElement("ownerLastName")] public string OwnerLastName { get; set; } [XmlElement("ownerEmail")] public string OwnerEmail { get; set; } [XmlIgnore] public string OwnerFullName { get { if (string.IsNullOrEmpty(OwnerFirstName) && string.IsNullOrEmpty(OwnerLastName)) return OwnerEmail; return string.Format("{0} {1}", OwnerFirstName, OwnerLastName); } } } }<file_sep>/Web.Api/SaaS.Sso/src/js/services/api.js angular .module('app.services') .factory('$api', ['$http', '$brand', ($http, $brand) => { let _uri = (method) => { return `${$brand.oauthLink()}/${method}`; }; let _getConfig = () => { return { asJson: true, isOauth: true }; }; let service = {}; service.account = { get: (params) => { let config = _getConfig(); config.params = params; return $http.get(_uri('api/account/'), config); } }; service.tokenJwt = (data) => { let config = _getConfig(); return $http.post(_uri('api/token/jwt'), data, config); }; return service; }]);<file_sep>/Shared/SaaS.Identity/AuthRepository/AuthRepository.AccountPreference.cs using SaaS.Data.Entities.Accounts; using System; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthRepository { public async Task<AccountPreference> AccountPreferenceGetAsync(Guid accountId) { return await _context.AccountPreferenceGetAsync(accountId); } public async Task AccountPreferenceSetAsync(Guid accountId, string json) { await _context.AccountPreferenceSetAsync(accountId, json); } public async Task AccountPreferenceDeleteAsync(Guid accountId) { await _context.AccountPreferenceDeleteAsync(accountId); } } }<file_sep>/Shared/SaaS.Mailer/Models/WelcomePurchaseNotification.cs using System.Xml.Serialization; namespace SaaS.Mailer.Models { [XmlRoot("xml")] public class WelcomePurchaseNotification : CreatePasswordNotification { public WelcomePurchaseNotification() { } public WelcomePurchaseNotification(Notification user, string productName) : base(user) { ProductName = productName; } [XmlElement("productName")] public string ProductName { get; set; } } }<file_sep>/Web.Api/SaaS.UI.Admin/js/controllers/admin/logs.js (function () { 'use strict'; angular .module('app.controllers') .controller('adminLogsController', controller); controller.$inject = ['$scope', '$api', '$form']; function controller($scope, $api, $form) { var _from = new Date(); var _to = new Date(); var _users = [{ login: 'All', id: null }]; var _logActionTypes = [{ name: 'All', id: null }]; var _search = { userId: null, log: null, from: _from, to: _to }; $scope.model = { logs: null, users: _users, logActionTypes: _logActionTypes, search: { user: _users[0], logActionType: _logActionTypes[0], from: _search.from, to: _search.to, log: _search.log } }; $scope.status = null; $scope.isBusy = false; $scope.refresh = function () { $scope.isBusy = true; _search.from.setHours(0, 0, 0, 0); _search.to.setHours(23, 59, 59, 59); _search.from = _search.from.toUTCString(); _search.to = _search.to.toUTCString(); $api.log.get(_search).then(function (json) { $scope.model.logs = json; }).finally(function () { $scope.isBusy = false; }); }; $scope.csv = function () { if ($scope.isBusy) return; $api.log.csv(_search); }; $scope.submit = function (form) { $form.submit($scope, form, function () { _search.userId = $scope.model.search.user.id; _search.logActionTypeId = $scope.model.search.logActionType.id; _search.log = $scope.model.search.log; if ($scope.model.search.from > $scope.model.search.to) { _search.from = $scope.model.search.to; _search.to = $scope.model.search.from; } else { _search.from = $scope.model.search.from; _search.to = $scope.model.search.to; } $scope.refresh(); }); }; $api.user.get().then(function (json) { $scope.model.users = $scope.model.users.concat(json); }); $api.log.logActionType.get().then(function (json) { $scope.model.logActionTypes = $scope.model.logActionTypes.concat(json); }); $scope.refresh(); }; })();<file_sep>/Shared/SaaS.Api.Models/Oauth/ConfirmEmalViewModel.cs using System; namespace SaaS.Api.Models.Oauth { public class ConfirmEmalViewModel { public string Token { get; set; } public Guid UserId { get; set; } public Guid? VisitorId { get; set; } public string Build { get; set; } public bool IsBusiness() { return "b2b".Equals(Build, StringComparison.InvariantCultureIgnoreCase); } } } <file_sep>/Web.Api/SaaS.Api.Sign/Controllers/Api/ESign20/LayoutsController.cs using SaaS.Api.Core.Filters; using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Sign.Controllers.Api.eSign20 { [RoutePrefix("api-esign20/v1/layouts"), SaaSAuthorize] public class ESignLayoutsController : BaseApiController { protected override string ApiRoot { get { return "api/v1/layouts/"; } } [Route("{*url}"), HttpGet, HttpPost, HttpPut, HttpDelete] public async Task<HttpResponseMessage> Index(CancellationToken cancellationToken) { return await HttpProxy(Request, Request.RequestUri.LocalPath, cancellationToken); } [Route, HttpGet, HttpPost] public async Task<HttpResponseMessage> Layouts(CancellationToken cancellationToken) { return await HttpProxy(Request, Format(), cancellationToken); } [Route("{layoutId:guid}"), HttpGet, HttpDelete] public async Task<HttpResponseMessage> Layouts(Guid layoutId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}", layoutId), cancellationToken); } } } <file_sep>/Shared/SaaS.ModuleFeatures/Map.cs using Newtonsoft.Json; using SaaS.ModuleFeatures.Model; using System; using System.IO; namespace SaaS.ModuleFeatures { public class Map { private Root _root; internal Map(Root root) { _root = root; } public static Map Load(string path) { var json = File.ReadAllText(path); var root = JsonConvert.DeserializeObject<Root>(json); return new Map(root); } public MapModule[] GetModules(MapStrategy strategy, Version license) { var creator = MapStrategyCreator.Creator(strategy); var searchMapStrategy = creator.Factory(); return searchMapStrategy.GetModules(_root, license); } } }<file_sep>/Shared/SaaS.Oauth2/readme.txt https://www.facebook.com/settings?tab=applications https://myaccount.google.com/permissions https://account.live.com/consent/Manage<file_sep>/Shared/SaaS.Oauth2/Services/MicrosoftService.cs using Newtonsoft.Json; using SaaS.Oauth2.Core; using System; using System.Collections.Generic; using System.Drawing; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using System.Web; namespace SaaS.Oauth2.Services { public class MicrosoftService : OauthService { public MicrosoftService(ClientProvider client) : base(client) { } public override string GetAuthenticationUrl(string lang) { var query = HttpUtility.ParseQueryString(string.Empty); query.Add("client_id", _clientProvider.ClientId); query.Add("redirect_uri", _clientProvider.CallBackUrl); query.Add("scope", _clientProvider.Scope); query.Add("response_type", "code"); query.Add("response_mode", "query"); return "https://login.microsoftonline.com/common/oauth2/v2.0/authorize/?" + query.ToString(); } public override Size GetWindowSize() { return new Size(800, 600); } public override async Task<TokenResult> TokenAsync(string code, CancellationToken cancellationToken) { var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("client_id", _clientProvider.ClientId), new KeyValuePair<string, string>("client_secret", _clientProvider.ClientSecret), new KeyValuePair<string, string>("scope", _clientProvider.Scope), new KeyValuePair<string, string>("redirect_uri", _clientProvider.CallBackUrl), new KeyValuePair<string, string>("code", code), new KeyValuePair<string, string>("grant_type", "authorization_code"), }); using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://login.microsoftonline.com"); var response = await client.PostAsync("common/oauth2/v2.0/token", content, cancellationToken); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<TokenResult>(json); } } return null; } public override async Task<ProfileResult> ProfileAsync(TokenResult token, CancellationToken cancellationToken) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://graph.microsoft.com"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token.AccessToken); var response = await client.GetAsync("v1.0/me/", cancellationToken); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); var profile = JsonConvert.DeserializeObject<MicrosoftProfileResult>(json); return new ProfileResult(profile); } } return null; } } }<file_sep>/Web.Api/SaaS.Zendesk/src/js/controllers/ticket/not-found.js angular.module('app.controllers') .controller('ticketNotFoundController', ['$scope', ($scope) => { }]);<file_sep>/Shared/SaaS.MailerWorker/EmailWorker.cs using NLog; using SaaS.Common.Extensions; using SaaS.Data.Entities; using SaaS.Data.Entities.Accounts; using SaaS.Mailer; using System; using System.Configuration; using System.Linq; using System.Threading.Tasks; namespace SaaS.MailerWorker { public class EmailWorker : IEmailWorker { private static readonly int DefaultBatchSize = 10; private static readonly Logger _logger = LogManager.GetLogger("Logs"); private static readonly Logger _errorsLogger = LogManager.GetLogger("Errors"); public async Task StartAsync() { try { using (var repository = new Identity.EmailRepository()) { var emails = await repository.EmailsGetAsync(Status.NotStarted, DefaultBatchSize); _logger.Info("emails in batch: {0}", emails.Count); foreach (var email in emails) { _logger.Info("-----------------------------------------------------------------------"); await repository.EmailStatusSetAsync(email.Id, Status.InProcess); await repository.EmailStatusSetAsync(email.Id, ProcessEmail(email)); _logger.Info("-----------------------------------------------------------------------"); } } GC.Collect(); } catch (Exception exc) { _errorsLogger.Error(exc); } } private Status ProcessEmail(Email email) { try { var parser = new RazorParser(email.LanguageId); SendEmailAction entity = null; var entity0 = XMLSerializer.DeserializeObject<SendEmailAction2>(email.EmailCustomParam); //сделано чтоб залогировать miss templates matching if (entity0.EmailTemplateValue == EmailTemplate.None) { throw new Exception("Couldn't find template: " + entity0.EmailTemplateDBValue + ". Will use [" + entity0.TemplateId + "] template"); } else { entity = new SendEmailAction(); entity.EmailToList = entity0.EmailToList; entity.TemplateId = entity0.EmailTemplateValue; } object model; string body = parser.ParseTemplateAsync(entity, email.ModelCustomParam, out model); string subject = parser.ParseSubject(entity, model); var templateName = Enum.GetName(typeof(EmailTemplate), entity.TemplateId); _logger.Info("try to send an email({0}): {1}", templateName, entity.EmailToList.FirstOrDefault().Email); EmailManager.Send(entity, subject, body); _logger.Info("email has been sent successfully: {0}", email.Id); return Status.Complete; } catch (Exception exc) { _logger.Info("email hasn't been sent successfully"); _errorsLogger.Error(exc, "email hasn't been sent successfully: email.Id = {0}; Exc: {1}", email.Id, exc.Message); return Status.Error; } } } public interface IEmailWorker { Task StartAsync(); } } <file_sep>/Web.Api/SaaS.Sso/src/js/services/brand.js angular.module('app.services') .factory('$brand', ['$utils', '$location', ($utils, $location) => { let brandEnum = { sodaPdf: 'sodaPdf', pdfArchitect: 'pdfArchitect' }; let _current = null; let _settings = { ssoLink: {}, oauthLink: {} }; _settings.ssoLink[brandEnum.sodaPdf] = 'https://sso.sodapdf.com'; _settings.ssoLink[brandEnum.pdfArchitect] = 'https://sso.pdfarchitect.org'; _settings.oauthLink[brandEnum.sodaPdf] = 'https://oauth.sodapdf.com'; _settings.oauthLink[brandEnum.pdfArchitect] = 'https://oauth.pdfarchitect.org'; let _getSettings = (key) => { return _settings[key][service.current()]; }; let service = {}; service.current = () => { return _current; }; service.currentName = () => { switch (service.current()) { case brandEnum.sodaPdf: return 'Soda PDF'; case brandEnum.pdfArchitect: return 'PDF Architect'; default: return ''; } }; service.ssoLink = () => { return _getSettings('ssoLink') }; service.oauthLink = () => { return _getSettings('oauthLink') }; service.validate = () => { let query = $utils.query(); let host = $location .host() .toLowerCase(); switch (host) { case 'localhost': case 'sso.sodapdf.com': _current = brandEnum.sodaPdf; break; case 'sso.pdfarchitect.org': _current = brandEnum.pdfArchitect; break; case 'sso.lulusoft.com': if (query.brand_id === '360002010612') _current = brandEnum.sodaPdf; _current = _current || brandEnum.pdfArchitect; return false; } return true; }; service.redirect = () => { document.body.style.display = 'none'; window.location = service.ssoLink() + document.location.search + document.location.hash; }; service.logo = () => { switch (service.current()) { case brandEnum.sodaPdf: return { width: 120, src: 'https://www.sodapdf.com/images/logo.svg' }; case brandEnum.pdfArchitect: return { width: 200, src: 'https://myaccount.pdfarchitect.org/images/logo.png' }; default: return {}; } }; return service; }]);<file_sep>/Shared/SaaS.Data.Entities/Enums.cs using System; namespace SaaS.Data.Entities { public enum ApplicationTypes { Web = 1, Desktop }; public enum Status : byte { None = 0, InProcess = 1, Complete = 2, Error = 3, Deleted = 4, NotStarted = 5 } [Flags] public enum AccountStatus : ulong { None = 0, IsActivated = 1 << 0, IsAnonymous = 1 << 1, IsBusiness = 1 << 2, IsPreview = 1 << 3 } [Flags] public enum ProductStatus : ulong { None = 0, IsDisabled = 1 << 0, IsExpired = 1 << 1, IsTrial = 1 << 2, IsFree = 1 << 3, IsMinor = 1 << 4, IsActive = 1 << 5, IsPPC = 1 << 6, IsUpgradable = 1 << 7, IsNew = 1 << 8, IsPaymentFailed = 1 << 9, IsRenewal = 1 << 10, IsOwner = 1 << 11, IsNotAbleToRenewCreditCartExpired = 1 << 12, IsRefund = 1 << 13, IsChargeback = 1 << 14, IsUpgraded = 1 << 15, IsManualCancelled = 1 << 16, IsNotSupportedClient = 1 << 17, IsBusiness = 1 << 18 } public enum AssignStatus { Ok = 0, Failed = -50000, FailAlreadyWasAssigned = -50013 } public enum UnassignStatus { Ok = 0, Failed = -50000, FailAlreadyWasUnassigned = -50013 } public enum AllowedCountStatus { Ok = 0, Failed = -50000, FailCantChangeAllowedCount = -50016 } public enum eSignTransactionInitiatorType { Free = 1, Product, Microtransaction } }<file_sep>/Shared/SaaS.Mailer/AppSettings.cs using System; using System.Configuration; using System.Globalization; namespace SaaS.Mailer { public sealed class AppSettings : IAppSettings { public AppSettingsOauth Oauth { get; private set; } public AppSettings() { Oauth = new AppSettingsOauth(Setting<string>("oauth:createPassword"), Setting<string>("oauth:emailConfirmation"), Setting<string>("paygw:customLink")); } private static T Setting<T>(string name) { string value = ConfigurationManager.AppSettings[name]; if (value == null) throw new Exception(string.Format("Could not find setting '{0}',", name)); return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture); } } public interface IAppSettings { AppSettingsOauth Oauth { get; } } public class AppSettingsOauth { public AppSettingsOauth(string createPassword, string emailConfirmation, string customLink) { CreatePassword = new Uri(createPassword); EmailConfirmation = new Uri(emailConfirmation); CustomLink = customLink; } public readonly Uri CreatePassword; public readonly Uri EmailConfirmation; public readonly string CustomLink; } } <file_sep>/Web.Api/SaaS.UI.Admin/Startup.cs using Microsoft.Owin; using Owin; using System.Net; [assembly: OwinStartup(typeof(SaaS.UI.Admin.Startup))] namespace SaaS.UI.Admin { public partial class Startup { public void Configuration(IAppBuilder app) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ConfigureOAuth(app); } } }<file_sep>/Shared/SaaS.Identity/eSignRepository/eSignRepository.cs using SaaS.Data.Entities.eSign; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Identity { public class eSignRepository : IeSignRepository { private readonly AuthDbContext _context; public eSignRepository() { _context = new AuthDbContext(); } public Task eSignUseIncreaseAsync(Guid accountId, Guid? accountProductId, Guid? accountMicrotransactionId) { return _context.eSignUseIncreaseAsync(accountId, accountProductId, accountMicrotransactionId); } public Task<int> eSignPackageHistoryGetFreeNumberOfSigns(int oauthClientId, eSignClient eSignClient, string ipAddressHash) { return _context.eSignPackageHistoryGetFreeNumberOfSigns(oauthClientId, eSignClient, ipAddressHash); } public Task eSignPackageHistorySetAsync(eSignPackageHistory history) { return _context.eSignPackageHistorySetAsync(history); } public Task<eSignApiKey> eSignApiKeyGetAsync(Guid accountId, eSignClient eSignClient) { return _context.eSignApiKeyGetAsync(accountId, eSignClient); } public List<eSignApiKey> eSignApiKeysNeedRefreshGet(int top = 10) { return _context.eSignApiKeysNeedRefreshGet(top); } public Task eSignApiKeySetAsync(Guid accountId, string email, eSignClient eSignClient, string apiKey) { return _context.eSignApiKeySetAsync(accountId, email, eSignClient, apiKey); } public void eSignApiKeyDelete(int id) { _context.eSignApiKeyDelete(id); } public void Dispose() { if (!object.Equals(_context, null)) _context.Dispose(); } } }<file_sep>/Web.Api/SaaS.Api/Global.asax.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Security.Principal; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Routing; namespace SaaS.Api { public class Global : HttpApplication { private static readonly HashSet<string> _adminAccounts = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); static Global() { _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); _adminAccounts.Add("<EMAIL>"); } void Application_Start(object sender, EventArgs e) { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); Trace.TraceInformation("Application has been successfully started"); } public void Application_OnAuthorizeRequest() { var user = HttpContext.Current.User; if (!user.Identity.IsAuthenticated) return; var isAdmin = _adminAccounts.Contains(user.Identity.Name); GenericPrincipal principal = new GenericPrincipal(user.Identity, isAdmin ? new string[] { "admin" } : new string[] { }); HttpContext.Current.User = principal; } } }<file_sep>/Web.Api/SaaS.Api/readme.txt facebook login/password - <EMAIL>/<PASSWORD> https://developers.facebook.com/apps/ microsoft login/password - <EMAIL> https://apps.dev.microsoft.com/#/appList<file_sep>/Shared/SaaS.Data.Entities/View/Accounts/ViewAccountMergePending.cs using System; namespace SaaS.Data.Entities.View.Accounts { public class ViewAccountMergePending : Entity<Guid?> { public Guid AccountIdTo { get; set; } public Guid AccountIdFrom { get; set; } public Guid AccountIdPrimaryEmail { get; set; } public string AccountEmailTo { get; set; } public string AccountEmailFrom { get; set; } public DateTime? CreateDate { get; set; } } }<file_sep>/Shared/SaaS.ModuleFeatures.Test/Program.cs using System; namespace SaaS.ModuleFeatures.Test { class Program { static void Main(string[] args) { var path = @"D:\oauth.sodapdf.com\branches\spdf-3427(trunk)\Web.Api\SaaS.Api\App_GlobalResources\lulu-moduleFeatures.json"; var map = Map.Load(path); Write(map, new Version(9, 0)); Write(map, new Version(10, 0)); //Write(map, new Version(11, 0)); //Write(map, new Version(12, 0)); Console.ReadKey(); } private static void Write(Map map, Version license) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("------------------{0}-----------------", license); var modules = map.GetModules(MapStrategy.PerpetualLicense, license); foreach (var module in modules) { uint index = 0; foreach (var feature in module.Features) { Console.ForegroundColor = ConsoleColor.White; Console.Write(feature.Version ?? new Version()); if (feature.IsHidden) Console.ForegroundColor = ConsoleColor.Gray; else { if (feature.IsUpgradable) Console.ForegroundColor = ConsoleColor.Red; else Console.ForegroundColor = ConsoleColor.Green; } Console.WriteLine("*"); ++index; //if (index > 7) break; } //break; } Console.WriteLine(); Console.ForegroundColor = ConsoleColor.White; } } } <file_sep>/Shared/Upclick.Api.Client/UpclickHttpClient.cs using System; using System.Collections.Specialized; using System.IO; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Web; namespace Upclick.Api.Client { internal class UpclickHttpClient { private string _uid, _password; public UpclickHttpClient(string uid, string password) { _uid = uid; _password = <PASSWORD>; } private static HttpClient CreateHttpClient() { HttpClient client = new HttpClient(); client.BaseAddress = new Uri("https://rest.upclick.com"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return client; } internal async Task<HttpResponseMessage> GetAsync(string requestUri, NameValueCollection query = null) { string token = Token(requestUri.Replace('/', '.')); string uri = Path.Combine(token, requestUri); if (!object.Equals(query, null)) { var values = HttpUtility.ParseQueryString(string.Empty); values.Add(query); uri = string.Format("{0}?{1}", uri, values); } using (var client = CreateHttpClient()) return await client.GetAsync(uri); } internal async Task<HttpResponseMessage> PostAsync<T>(string requestUri, T value, NameValueCollection query = null) { string token = Token(requestUri.Replace('/', '.')); string uri = Path.Combine(token, requestUri); using (var client = CreateHttpClient()) return await client.PostAsync(uri, value, new JsonMediaTypeFormatter()); } private string MD5Hash(string str) { Encoder encoder = Encoding.Unicode.GetEncoder(); byte[] bytes = new byte[str.Length * 2]; encoder.GetBytes(str.ToCharArray(), 0, str.Length, bytes, 0, true); MD5 md5 = new MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(bytes); StringBuilder builder = new StringBuilder(); foreach (var item in result) builder.Append(item.ToString("X2")); return builder.ToString(); } public string Token(string method) { if (!string.IsNullOrEmpty(method)) method = method.ToLower(); string password = <PASSWORD>(_password); string timeStamp = DateTime.UtcNow.AddMinutes(-5).ToString("yyyy-MM-dd HH:mm:ss.fff"); string token = string.Join("|", _uid, timeStamp, MD5Hash(string.Concat(password, timeStamp, method))); byte[] bytes = Encoding.UTF8.GetBytes(token); return Convert.ToBase64String(bytes); } } } <file_sep>/Web.Api/SaaS.Zendesk/src/js/directives/external-connected-account.js angular.module('app.directives') .directive('ngExternalConnectedAccount', [() => { return { restrict: 'A', link: (scope, element, attrs) => { element .addClass('fab') .addClass('fa-' + attrs.ngExternalConnectedAccount); switch (attrs.ngExternalConnectedAccount) { case 'google': element.css({ color: '#d62d20' }); break; case 'facebook': element.css({ color: '#3b5998' }); break; case 'microsoft': element.css({ color: '#00a1f1' }); break; } } }; }]);<file_sep>/Shared/SaaS.Identity/AuthRepository/AuthRepository.Link.cs using SaaS.Data.Entities.Accounts; using System; using System.Collections.Specialized; using System.Text; using System.Threading.Tasks; using System.Web; namespace SaaS.Identity { public partial class AuthRepository { private static string ToBase64String(string str) { var bytes = Encoding.UTF8.GetBytes(str); return Convert.ToBase64String(bytes); } private static string FromBase64String(string str) { var bytes = Convert.FromBase64String(str); return Encoding.UTF8.GetString(bytes); } public async Task<Uri> GeneratePasswordResetTokenLinkAsync(Account user, Uri uri) { string token = await _userManager.GeneratePasswordResetTokenAsync(user.Id); var uriBuilder = new UriBuilder(uri); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query.Add("token", ToBase64String(token)); query.Add("userId", user.Id.ToString("N")); uriBuilder.Query = query.ToString(); return uriBuilder.Uri; } public async Task<NameValueCollection> GenerateEmailConfirmationToken(Account user) { string token = await _userManager.GenerateEmailConfirmationTokenAsync(user.Id); var query = HttpUtility.ParseQueryString(string.Empty); query.Add("token", ToBase64String(token)); query.Add("userId", user.Id.ToString("N")); return query; } public async Task<Uri> GenerateEmailConfirmationTokenLinkAsync(Account user, Uri uri) { var uriBuilder = new UriBuilder(uri); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query.Add(await GenerateEmailConfirmationToken(user)); uriBuilder.Query = query.ToString(); return uriBuilder.Uri; } } }<file_sep>/Web.Api/SaaS.Api.Sign/Controllers/Api/ESign20/PackagesController.cs using Newtonsoft.Json.Linq; using SaaS.Api.Core.Filters; using SaaS.Common.Extensions; using SaaS.Data.Entities.eSign; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View; using SaaS.IPDetect; using System; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Sign.Controllers.Api.eSign20 { [RoutePrefix("api-esign20/v1/packages"), SaaSAuthorize] public class ESignPackagesController : BaseApiController { protected override string ApiRoot { get { return "api/v1/packages/"; } } [Route("{*url}"), HttpGet, HttpPost, HttpPut, HttpDelete] public async Task<HttpResponseMessage> Index(CancellationToken cancellationToken) { return await HttpProxy(Request, Request.RequestUri.LocalPath, cancellationToken); } [Route, HttpGet, HttpPost] public async Task<HttpResponseMessage> Packages(CancellationToken cancellationToken) { return await HttpProxy(Request, Format(), cancellationToken); } private async Task<HttpResponseMessage> Send(string json, Guid packageId, CancellationToken cancellationToken) { var session = await GetSessionToken(); if (object.Equals(session, null)) return Request.CreateResponse(HttpStatusCode.Unauthorized); Guid? accountProductId = null; Guid? accountMicrotransactionId = null; if (!await IsAvailableFreeSigns(json, session)) { ViewAccountMicrotransaction microtransaction; var microtransactions = await _authProduct.AccountMicrotransactionsGetAsync(session.AccountId); accountMicrotransactionId = eSignHelper.GetAllowedAccountMicrotransactionId(microtransactions, out microtransaction); ViewAccountProduct product; var products = await _authProduct.AccountProductsGetAsync(session.AccountId); accountProductId = eSignHelper.GetAllowedAccountProductId(products, session.AccountProductId, out product); if (!accountMicrotransactionId.HasValue && !accountProductId.HasValue) return PaymentRequired("User doesn't have enough number of signs."); else { if (accountMicrotransactionId.HasValue && !microtransaction.AllowedEsignCount.HasValue) accountProductId = null; if (accountProductId.HasValue && !product.AllowedEsignCount.HasValue) accountMicrotransactionId = null; if (accountMicrotransactionId.HasValue && accountProductId.HasValue) accountProductId = null; } } var response = await HttpProxy(Request, Format("{0}", packageId), cancellationToken); if (response.IsSuccessStatusCode && (accountProductId.HasValue || accountMicrotransactionId.HasValue)) await _eSign.eSignUseIncreaseAsync(session.AccountId, accountProductId, accountMicrotransactionId); var history = new eSignPackageHistory { AccountId = session.AccountId, oAuthClientId = session.ClientId, eSignClientId = eSignClient, HttpStatusCode = (int)response.StatusCode, IsSuccess = response.IsSuccessStatusCode, PackageId = packageId, IpAddressHash = IpAddressDetector.IpAddress.GetShortMD5Hash(), AccountProductId = accountProductId, AccountMicrotransactionId = accountMicrotransactionId }; await _eSign.eSignPackageHistorySetAsync(history); return response; } private async Task<bool> IsAvailableFreeSigns(string json, SessionToken session) { if (!"esign-lite".Equals(session.ClientName, StringComparison.InvariantCultureIgnoreCase)) return false; if (GetFileContentLength() > eSignLiteLimitation.FileSize || GetRecipientsCount(json) > eSignLiteLimitation.Recipients) return false; var ipAddressHash = IpAddressDetector.IpAddress.GetShortMD5Hash(); var freeNumberOfSigns = await _eSign.eSignPackageHistoryGetFreeNumberOfSigns(session.ClientId, eSignClient, ipAddressHash); return freeNumberOfSigns < eSignLiteLimitation.SignsPerDay; } [Route("{packageId:guid}"), HttpGet, HttpPost, HttpPut, HttpDelete] public async Task<HttpResponseMessage> Packages(Guid packageId, CancellationToken cancellationToken) { if (Request.Method == HttpMethod.Post || Request.Method == HttpMethod.Put) { string json = string.Empty; if (Request.Content.IsMimeMultipartContent("form-data")) { var stream = await Request.Content.ReadAsStreamAsync(); var multipartAsync = await Request.Content.ReadAsMultipartAsync(); stream.Seek(0, System.IO.SeekOrigin.Begin); foreach (var content in multipartAsync.Contents) { if ("\"package\"".Equals(content.Headers.ContentDisposition.Name, StringComparison.InvariantCultureIgnoreCase)) { json = await content.ReadAsStringAsync(); break; } } } else json = await Request.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(json)) { var jObject = JObject.Parse(json); if (!object.Equals(jObject, null)) { var property = jObject.Property("status"); if (!object.Equals(property, null) && "sent".Equals(property.Value.ToString(), StringComparison.InvariantCultureIgnoreCase)) return await Send(json, packageId, cancellationToken); } } } return await HttpProxy(Request, Format("{0}", packageId), cancellationToken); } [Route("{packageId:guid}/evidence/summary"), HttpGet] public async Task<HttpResponseMessage> PackagesEvidenceSummary(Guid packageId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/evidence/summary", packageId), cancellationToken); } [Route("{packageId:guid}/decline"), HttpPost] public async Task<HttpResponseMessage> PackagesDecline(Guid packageId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/decline", packageId), cancellationToken); } [Route("{packageId:guid}/forward"), HttpPost] public async Task<HttpResponseMessage> PackagesForward(Guid packageId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/forward", packageId), cancellationToken); } [Route("{packageId:guid}/recipients/{recipientId:guid}/signingUrl"), HttpGet] public async Task<HttpResponseMessage> PackagesRecipientsSigningUrl(Guid packageId, Guid recipientId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/recipients/{1}/signingUrl", packageId, recipientId), cancellationToken); } [Route("{packageId:guid}/recipients/{recipientId:guid}/signature/appearance"), HttpPost] public async Task<HttpResponseMessage> PackagesRecipientsSignatureAppearance(Guid packageId, Guid recipientId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/recipients/{1}/signature/appearance", packageId, recipientId), cancellationToken); } [Route("{packageId:guid}/review"), HttpPost] public async Task<HttpResponseMessage> PackagesReview(Guid packageId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/review", packageId), cancellationToken); } [Route("{packageId:guid}/copy"), HttpPost] public async Task<HttpResponseMessage> PackagesCopy(Guid packageId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/copy", packageId), cancellationToken); } [Route("{packageId:guid}/recipients/{recipientId:guid}/notifications"), HttpPost] public async Task<HttpResponseMessage> PackagesRecipientsNotifications(Guid packageId, Guid recipientId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/recipients/{1}/notifications", packageId, recipientId), cancellationToken); } [Route("{packageId:guid}/documents/info"), HttpPost] public async Task<HttpResponseMessage> PackagesDocumentsInfo(Guid packageId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/documents/info", packageId), cancellationToken); } [Route("{packageId:guid}/documents/zip"), HttpGet] public async Task<HttpResponseMessage> PackagesDocumentsZip(Guid packageId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/documents/zip", packageId), cancellationToken); } [Route("{packageId:guid}/documents/{documentId:guid}/info"), HttpPost] public async Task<HttpResponseMessage> PackagesDocumentsInfo(Guid packageId, Guid documentId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/documents/{1}/info", packageId, documentId), cancellationToken); } [Route("{packageId:guid}/documents/{documentId:guid}/thumbnail"), HttpPost] public async Task<HttpResponseMessage> PackagesDocumentsThumbnail(Guid packageId, Guid documentId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/documents/{1}/thumbnail", packageId, documentId), cancellationToken); } [Route("{packageId:guid}/documents/{documentId:guid}/layout/{layoutId:guid}"), HttpPost] public async Task<HttpResponseMessage> PackagesDocumentsLayout(Guid packageId, Guid documentId, Guid layoutId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/documents/{1}/layout/{2}", packageId, documentId, layoutId), cancellationToken); } [Route("{packageId:guid}/documents/{documentId:guid}/download"), HttpGet] public async Task<HttpResponseMessage> PackagesDocumentsDownload(Guid packageId, Guid documentId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/documents/{1}/download", packageId, documentId), cancellationToken); } [Route("{packageId:guid}/documents/{documentId:guid}/download/original"), HttpGet] public async Task<HttpResponseMessage> PackagesDocumentsDownloadOriginal(Guid packageId, Guid documentId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/documents/{1}/download/original", packageId, documentId), cancellationToken); } [Route("{packageId:guid}/attachments/{attachmentId:guid}"), HttpPost, HttpDelete] public async Task<HttpResponseMessage> PackagesAttachments(Guid packageId, Guid attachmentId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/attachments/{1}", packageId, attachmentId), cancellationToken); } [Route("{packageId:guid}/attachments/{attachmentId:guid}/thumbnail"), HttpPost] public async Task<HttpResponseMessage> PackagesAttachmentsThumbnail(Guid packageId, Guid attachmentId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/attachments/{1}/thumbnail", packageId, attachmentId), cancellationToken); } [Route("{packageId:guid}/recipients/{recipientId:guid}/attachments/{attachmentId:guid}"), HttpPost] public async Task<HttpResponseMessage> PackagesRecipientAattachments(Guid packageId, Guid recipientId, Guid attachmentId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/recipients/{1}/attachments/{2}", packageId, recipientId, attachmentId), cancellationToken); } [Route("{packageId:guid}/recipients/{recipientId:guid}/attachments/{attachmentId:guid}/download"), HttpGet] public async Task<HttpResponseMessage> PackagesRecipientAattachmentsDownload(Guid packageId, Guid recipientId, Guid attachmentId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/recipients/{1}/attachments/{2}/download", packageId, recipientId, attachmentId), cancellationToken); } [Route("{packageId:guid}/recipients/{recipientId:guid}/attachments/zip"), HttpGet] public async Task<HttpResponseMessage> PackagesRecipientAattachmentsZip(Guid packageId, Guid recipientId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/recipients/{1}/attachments/zip", packageId, recipientId), cancellationToken); } } } <file_sep>/Web.Api/SaaS.Api/App_Start/Startup.Auth.cs using Microsoft.Owin; using Microsoft.Owin.Security.DataProtection; using Microsoft.Owin.Security.OAuth; using Owin; using SaaS.Api.Oauth.Providers; using System; using System.Collections.Concurrent; namespace SaaS.Api { public partial class Startup { public static OAuthAuthorizationServerOptions OAuthServerOptions { get; private set; } public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; } public static IDataProtectionProvider DataProtectionProvider { get; set; } private readonly ConcurrentDictionary<string, string> _authenticationCodes = new ConcurrentDictionary<string, string>(StringComparer.Ordinal); public void ConfigureOAuth(IAppBuilder app) { DataProtectionProvider = app.GetDataProtectionProvider(); OAuthServerOptions = new OAuthAuthorizationServerOptions() { #if DEBUG AllowInsecureHttp = true, #endif AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(120), TokenEndpointPath = new PathString("/api/token"), Provider = new SaaSAuthorizationServerProvider(), RefreshTokenProvider = new SaaSRefreshTokenProvider() }; OAuthBearerOptions = new OAuthBearerAuthenticationOptions { }; app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(OAuthBearerOptions); } } }<file_sep>/Shared/SaaS.Mailer/Models/RecoverPasswordNotification.cs using System.Xml.Serialization; namespace SaaS.Mailer.Models { [XmlRoot("xml")] public class RecoverPasswordNotification : Notification { public RecoverPasswordNotification() { } public RecoverPasswordNotification(Notification user, string recoverPasswordLink) : base(user) { RecoverPasswordLink = recoverPasswordLink; } [XmlElement("recoverPasswordLink")] public string RecoverPasswordLink { get; set; } } }<file_sep>/Shared/SaaS.Data.Entities/View/ViewAccountProduct.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Data.Entities.View { public class ViewAccountProduct : ViewProduct { [NotMapped] public List<ViewAccountProductModule> Modules { get; set; } public string ProductVersion { get; set; } [NotMapped] public ushort? Order { get; set; } } public static class ViewAccountProductHelper { public static Version GetProductVersion(this ViewAccountProduct product) { Version version; if (!Version.TryParse(product.ProductVersion, out version)) return null; return version; } } }<file_sep>/Web.Api/SaaS.Sso/tasks/app.css.js const gulp = require('gulp'); const concat = require('gulp-concat'); const cleanCSS = require('gulp-clean-css'); gulp.task('app.css:app', () => { return gulp.src(['src/css/**/*.css']) .pipe(concat('app.min.css')) .pipe(cleanCSS()) .pipe(gulp.dest('dist/css')); }); gulp.task('app.css:vendor', () => { return gulp.src([ 'node_modules/bootstrap/dist/css/bootstrap.min.css' ]) .pipe(concat('vendor.min.css')) .pipe(gulp.dest('dist/css')) }); gulp.task('app.css:watch', () => { return gulp.watch('src/css/**/*.css', gulp.series('app.css:app')); }); gulp.task('app.css', gulp.parallel('app.css:app', 'app.css:vendor'));<file_sep>/Web.Api/SaaS.UI.Admin/App_Start/BundleConfig.cs using System.Web.Optimization; namespace SaaS.UI.Admin { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle("~/bundle/css") #if LuluSoft .Include("~/css/bootstrap/default/bootstrap.min.css") //https://bootswatch.com/3/ .Include("~/css/theme/luluSoft/style.css") #endif #if PdfForge .Include("~/css/bootstrap/lumen/bootstrap.min.css") //https://bootswatch.com/3/ .Include("~/css/theme/pdfForge/style.css") #endif #if PdfSam .Include("~/css/bootstrap/paper/bootstrap.min.css") //https://bootswatch.com/3/ .Include("~/css/theme/pdfSam/style.css") #endif .Include("~/css/font-awesome/css/fontawesome-all.min.css") .Include("~/css/metisMenu/metisMenu.min.css") .Include("~/css/notify/css/angular-notify-bordered.min.css") .Include("~/css/style.css") .Include("~/css/validation.css") ); string pattern = "*.js"; bundles.Add(new ScriptBundle("~/bundle/js") .Include("~/js/bundle.js") .Include("~/js/app.js") .IncludeDirectory("~/js/auth", pattern, true) .IncludeDirectory("~/js/services", pattern, true) .IncludeDirectory("~/js/directives", pattern, true) //.IncludeDirectory("~/js/filters", pattern, true) .IncludeDirectory("~/js/controllers", pattern, true) ); } } } <file_sep>/Shared/SaaS.Api.Models/Oauth/ExternalLoginSettingsViewModel.cs using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SaaS.Api.Models.Oauth { public class ExternalLoginSettingsViewModel { public ExternalLoginSettingsViewModel(ExternalLoginSettings google, ExternalLoginSettings facebook, ExternalLoginSettings microsoft) { Google = google; Facebook = facebook; Microsoft = microsoft; } public ExternalLoginSettings Google { get; set; } public ExternalLoginSettings Facebook { get; set; } public ExternalLoginSettings Microsoft { get; set; } } public class ExternalWindowSettings { public ExternalWindowSettings(Size size) { Width = size.Width; Height = size.Height; } public int Width { get; set; } public int Height { get; set; } } public class ExternalLoginSettings { public ExternalWindowSettings Window { get; set; } } } <file_sep>/Shared/SaaS.Api.Models/Oauth/MergeViewModel.cs using System; namespace SaaS.Api.Models.Oauth { public class MergeViewModel { public Guid AccountIdFrom { get; set; } public Guid AccountIdPrimaryEmail { get; set; } } }<file_sep>/Web.Api/SaaS.Api/Models/Validation/PasswordRegexAttribute.cs using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; namespace SaaS.Api.Models.Validation { public class PasswordRegexAttribute : ValidationAttribute { string[] _args; private static readonly Regex _regex1 = new Regex(@"^((?=.*\d)(?=.*[^\s0-9!""\#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]).{6,})$", RegexOptions.IgnoreCase); private static readonly Regex _regex2 = new Regex(@"^(?!.*(\d)\1{2})(?!.*(0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){2}).{6,100}$", RegexOptions.IgnoreCase); private static readonly Regex _regex3 = new Regex(@"^(?!.*(abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz)).{6,100}$", RegexOptions.IgnoreCase); private static readonly Regex _regex4 = new Regex(@"^(?!.*(.)\1{2}).*$", RegexOptions.IgnoreCase); private static readonly Regex _regex5 = new Regex(@"^(?!.*(admin|administrator|password)).{6,100}$", RegexOptions.IgnoreCase); public PasswordRegexAttribute(params string[] args) { _args = args; } public bool IsAllowNull { get; set; } protected override ValidationResult IsValid(object obj, ValidationContext validationContext) { string value = (string)obj; if (IsAllowNull && string.IsNullOrEmpty(value)) return ValidationResult.Success; if (!_regex1.IsMatch(value)) return new ValidationResult("Your password must be at least 6 characters and have both letters and numbers."); if (!_regex2.IsMatch(value) || !_regex3.IsMatch(value) || !_regex4.IsMatch(value)) return new ValidationResult("Your password cannot contain 3 or more sequential characters or have the same character repeated sequentially (eg. 123, ABC, AAA, 111)"); if (!_regex5.IsMatch(value)) return new ValidationResult("Your password cannot contain \"password\", \"admin\" or \"administrator\""); return ValidationResult.Success; } } }<file_sep>/Web.Api/SaaS.UI.Admin/js/auth/storage.js (function () { 'use strict'; angular .module('app.auth') .factory('$authStorage', authStorage); authStorage.$inject = ['appSettings']; function authStorage(appSettings) { var _accessToken = 'access_token'; var _refreshToken = '<PASSWORD>'; var _fullName = 'oauth_fullName'; var _getSet = function (key, value) { if (typeof value == 'undefined') return $.cookie(key); $.cookie.raw = false; $.cookie(key, value, { expires: 1, path: '/' }); }; var _initIdentity = function () { var identity = appSettings.user.identity; identity.fullName = _getSet(_fullName) || identity.name; return identity; }; var service = {}; service.accessToken = function (value) { return _getSet(_accessToken, value); }; service.refreshToken = function (value) { return _getSet(_refreshToken, value); }; service.name = function (firstName, lastName) { var identity = _initIdentity(); identity.fullName = (firstName || '') + ' ' + (lastName || ''); _getSet(_fullName, identity.fullName); }; service.signIn = function (json) { var fullName = (json.firstName || json.lastName) ? (json.firstName || '') + ' ' + (json.lastName || '') : json.email; _getSet(_accessToken, json.access_token); _getSet(_refreshToken, json.refresh_token); _getSet(_fullName, fullName); var identity = _initIdentity(); identity.name = json.email; identity.isAuthenticated = true; }; service.logout = function () { $.cookie(_accessToken, null, { expires: -1, path: '/' }); $.cookie(_refreshToken, null, { expires: -1, path: '/' }); $.cookie(_fullName, null, { expires: -1, path: '/' }); }; _initIdentity(); return service; }; })();<file_sep>/Shared/SaaS.Identity/AuthProductRepository/AuthProductRepository.cs using SaaS.Data.Entities; using SaaS.Data.Entities.View; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Identity { public class AuthProductRepository : IAuthProductRepository { private readonly AuthDbContext _context; public AuthProductRepository() { _context = new AuthDbContext(); } public async Task<AssignStatus> ProductAssignAsync(AccountProductPair pair, bool isIgnoreBillingCycle = false) { return await _context.ProductAssignAsync(pair, isIgnoreBillingCycle); } public async Task<ViewUnassignProduct> ProductUnassignAsync(AccountProductPair pair) { return await _context.ProductUnassignAsync(pair); } public async Task<AllowedCountStatus> ProductAllowedSetAsync(AccountProductPair pair, int allowedCount) { return await _context.ProductAllowedSetAsync(pair, allowedCount); } public async Task ProductDeactivateAsync(AccountProductPair pair) { await _context.ProductDeactivateAsync(pair); } public async Task ProductNextRebillDateSetAsync(AccountProductPair pair, DateTime? nextRebillDate) { await _context.ProductNextRebillDateSetAsync(pair, nextRebillDate); } public async Task ProductEndDateSetAsync(AccountProductPair pair, DateTime endDate) { await _context.ProductEndDateSetAsync(pair, endDate); } public async Task ProductIsNewAsync(AccountProductPair pair, bool isNew) { await _context.ProductIsNewAsync(pair, isNew); } public async Task<ViewUpgradeProduct> UpgradeProductGetAsync(Guid accountProductId) { return await _context.UpgradeProductGetAsync(accountProductId); } public async Task<List<ViewAccountProduct>> AccountProductsGetAsync(Guid accountId, Guid? systemId = null) { return await _context.AccountProductsGetAsync(accountId, systemId); } public async Task<List<ViewAccountMicrotransaction>> AccountMicrotransactionsGetAsync(Guid accountId) { return await _context.AccountMicrotransactionsGetAsync(accountId); } public async Task<List<ViewUpclickProduct>> UpclickProductsGetAsync() { return await _context.UpclickProductsGetAsync(); } public async Task<ViewOwnerProduct> OwnerProductGetAsync(AccountProductPair pair) { return await _context.OwnerProductGetAsync(pair); } public async Task<ViewOwnerProduct> OwnerProductDetailsGetAsync(AccountProductPair pair) { return await _context.OwnerProductDetailsGetAsync(pair); } public async Task<List<ViewOwnerProduct>> OwnerProductsGetAsync(Guid accountId) { return await _context.OwnerProductsGetAsync(accountId); } public async Task OwnerProductInsertAsync(Guid accountId, string productUid, string currency, decimal price, decimal priceUsd, int quantity) { await _context.OwnerProductInsertAsync(accountId, productUid, currency, price, priceUsd, quantity); } public void Dispose() { if (!object.Equals(_context, null)) _context.Dispose(); } } }<file_sep>/Test/SaaS.Api.Test/AppSettings.cs using System; namespace SaaS.Api.Test { public sealed class AppSettings : IAppSettings { public Uri PathToOAuthApi { get; private set; } public Uri PathToESignApi { get; private set; } public string ClientId { get; private set; } public string ClientSecret { get; private set; } public string Scope { get; private set; } public string Login { get; private set; } public string Password { get; private set; } public string Token { get; private set; } public AppSettings() { PathToOAuthApi = new Uri("https://stage-oauth.sodapdf.com"); //PathToOAuthApi = new Uri("https://oauth-dev.sodapdf.com"); //PathToESignApi = new Uri("https://oauth-sign-dev.sodapdf.com"); #if DEBUG PathToOAuthApi = new Uri("http://localhost:52289"); PathToESignApi = new Uri("http://localhost:53583"); #endif #region Login/Password //Login = "<EMAIL>"; //Password = "<PASSWORD>"; //Login = "abalyuk @<EMAIL>"; //Password = "<PASSWORD>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>"; //Token = "<KEY>"; Login = "<EMAIL>"; Password = "<PASSWORD>"; Token = "<KEY>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>"; //Token = "<KEY>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>"; //Token = "Y<KEY>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>"; //Token = "<KEY>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>"; //Token = "<KEY>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>"; //Token = "<KEY>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>"; //Token = "<KEY>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>!"; //Token = "<KEY>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>"; //Token = "<KEY>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>"; //Token = "<KEY>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>"; //Login = "<EMAIL>"; //Password = "<PASSWORD>"; #endregion //ClientId = "desktop"; //ClientSecret = "<KEY>; //Scope = "editor"; ClientId = "saas"; ClientSecret = ""; Scope = "webeditor"; } } public interface IAppSettings { Uri PathToOAuthApi { get; } Uri PathToESignApi { get; } } } <file_sep>/WinService/SaaS.WinService.Core/Path.cs using System.IO; using System.Reflection; namespace SaaS.WinService.Core { public static class Path { public static DirectoryInfo CurrentDirectoryInfo { get { Assembly assembly = Assembly.GetExecutingAssembly(); return new DirectoryInfo(System.IO.Path.GetDirectoryName(assembly.GetName().CodeBase).Remove(0, "file:\\".Length)); } } } } <file_sep>/Shared/SaaS.Api.Models/Products/ProductConvertor.cs using AutoMapper; using SaaS.Data.Entities.View; using System; using System.Collections.Generic; using System.Linq; namespace SaaS.Api.Models.Products { public static class ProductConvertor { public static AccountProductViewModel AccountProductConvertor(ViewAccountProduct product) { var newProduct = new AccountProductViewModel(); newProduct = Mapper.Map(product, newProduct); foreach (var module in newProduct.Modules.Where(e => "e-sign".Equals(e.Module, StringComparison.InvariantCultureIgnoreCase))) { module.Allowed = product.AllowedEsignCount; module.Used = product.UsedEsignCount; } return newProduct; } public static OwnerProductViewModel OwnerAccountProductConvertor(ViewOwnerProduct product) { var newProduct = new OwnerProductViewModel(); newProduct = Mapper.Map(product, newProduct); newProduct.Modules = new List<AccountProductModuleModel>(); //create fake modules if (product.AllowedEsignCount.GetValueOrDefault(int.MaxValue) > 0) { newProduct.Modules.Add(new AccountProductModuleModel { Module = "e-sign", Allowed = product.AllowedEsignCount, Used = product.UsedEsignCount }); } return newProduct; } public static List<OwnerProductViewModel> OwnerAccountProductConvertor(List<ViewOwnerProduct> products) { return products.ConvertAll(OwnerAccountProductConvertor); } } } <file_sep>/Web.Api/SaaS.Api/Models/Api/Oauth/ResetPasswordViewModel.cs using SaaS.Api.Models.Validation; using System; using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Api.Oauth { public class ResetPasswordViewModel { [Required] public Guid UserId { get; set; } public Guid? VisitorId { get; set; } public string Token { get; set; } [Required, DataType(DataType.Password), PasswordRegex] public string NewPassword { get; set; } [MaxLength(300), RegularExpression(@"^[^\^<>()\[\]\\;:@№%\|$%*?#&¸¼!+€£¢¾½÷פ¶»¥¦µ©®°§«´¨™±°º¹²³ª¯¬`""'/]*$")] public string FirstName { get; set; } [MaxLength(300), RegularExpression(@"^[^\^<>()\[\]\\;:@№%\|$%*?#&¸¼!+€£¢¾½÷פ¶»¥¦µ©®°§«´¨™±°º¹²³ª¯¬`""'/]*$")] public string LastName { get; set; } } }<file_sep>/Shared/SaaS.Identity.Admin/AuthDbContext.Sql/AuthDbContext.Sql.Log.cs using SaaS.Data.Entities.Admin.Oauth; using SaaS.Data.Entities.Admin.View; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity.Admin { public partial class AuthDbContext { internal async Task<List<ViewLog>> LogsGetAsync(DateTime from, DateTime to, Guid? userId, string log, LogActionTypeEnum? logActionTypeEnum) { var sqlParams = new SqlParameter[] { from.ToSql("from"), to.ToSql("to"), userId.ToSql("userId"), log.ToSql("log"), logActionTypeEnum.ToSql("logActionTypeId") }; return await ExecuteReaderCollectionAsync<ViewLog>("[oauth].[vLogGetBy]", sqlParams); } internal async Task LogInsertAsync(Guid userId, Guid? accountId, string log, LogActionTypeEnum logActionType) { var sqlParams = new SqlParameter[] { userId.ToSql("userId"), accountId.ToSql("accountId"), log.ToSql("log"), ((int)logActionType).ToSql("logActionTypeId") }; await ExecuteNonQueryAsync("[oauth].[pLogInsert]", sqlParams); } internal async Task<List<LogActionType>> LogActionTypesGetAsync(DateTime from, DateTime to, Guid? userId, string log) { var sqlParams = new SqlParameter[] { from.ToSql("from"), to.ToSql("to"), userId.ToSql("userId"), log.ToSql("log") }; return await ExecuteReaderCollectionAsync<LogActionType>("[oauth].[vLogGetBy]", sqlParams); } internal async Task<List<LogActionType>> LogActionTypesGetAsync() { return await ExecuteReaderCollectionAsync<LogActionType>("[oauth].[pLogActionTypeGet]", new SqlParameter[] { }); } } }<file_sep>/Shared/SaaS.Mailer/Models/WelcomeFreeProductNotification.cs using System.Xml.Serialization; namespace SaaS.Mailer.Models { [XmlRoot("xml")] public class WelcomeFreeProductNotification : Notification { public WelcomeFreeProductNotification() { } public WelcomeFreeProductNotification(Notification user, string productName) : base(user) { ProductName = productName; } [XmlElement("productName")] public string ProductName { get; set; } } }<file_sep>/Shared/SaaS.IPDetect/IpAddressFilterMiddleware.cs using Microsoft.Owin; using Newtonsoft.Json; using NLog; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.IPDetect { public class IpAddressFilterMiddleware : OwinMiddleware { static HashSet<string> _httpMethods; static Logger _oauthIpFilterLogger = LogManager.GetLogger("oauth-ip-filter"); static IpAddressFilterMiddleware() { _httpMethods = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); _httpMethods.Add("Get"); _httpMethods.Add("Put"); _httpMethods.Add("Post"); _httpMethods.Add("Delete"); } public IpAddressFilterMiddleware(OwinMiddleware next) : base(next) { } public async override Task Invoke(IOwinContext context) { if (_httpMethods.Contains(context.Request.Method) && !context.IsIpAddressAllowed()) { _oauthIpFilterLogger.Warn("You don't have authorization to view this page."); context.Response.StatusCode = 403; context.Response.ContentType = "application/json"; var error = new { error = "invalid_grant", error_description = "You don't have authorization to view this page." }; var json = JsonConvert.SerializeObject(error); context.Response.Write(json); return; } await Next.Invoke(context); } } }<file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.AccountMergePending.cs using SaaS.Data.Entities.View.Accounts; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthDbContext { internal async Task AccountMergeAsync(ViewAccountMergePending pending) { var sqlParams = new SqlParameter[] { pending.AccountIdTo.ToSql("accountIdTo"), pending.AccountIdFrom.ToSql("accountIdFrom"), pending.AccountIdPrimaryEmail.ToSql("accountIdOfEmailSetToPrimary") }; await ExecuteScalarAsync("[accounts].[pAccountMerge]", sqlParams); } internal async Task<ViewAccountMergePending> AccountMergePendingSetAsync(Guid accountIdTo, Guid accountIdFrom, Guid accountIdPrimaryEmail) { var sqlParams = new SqlParameter[] { accountIdTo.ToSql("accountIdTo"), accountIdFrom.ToSql("accountIdFrom"), accountIdPrimaryEmail.ToSql("accountIdPrimaryEmail") }; return await ExecuteReaderAsync<ViewAccountMergePending>("[accounts].[pAccountMergePendingSet]", sqlParams); } internal async Task<ViewAccountMergePending> AccountMergePendingGetAsync(Guid id) { var sqlParams = new SqlParameter[] { id.ToSql("id") }; return await ExecuteReaderAsync<ViewAccountMergePending>("[accounts].[pAccountMergePendingGetById]", sqlParams); } internal async Task<List<ViewAccountMergePending>> AccountMergePendingsGetAsync(Guid accountId) { return await ExecuteReaderCollectionAsync<ViewAccountMergePending>("[accounts].[pAccountMergePendingGetByAccountId]", CreateSqlParams(accountId)); } internal async Task AccountMergePendingDeleteAsync(Guid accountId) { await ExecuteScalarAsync("[accounts].[pAccountMergePendingDeleteByAccountId]", CreateSqlParams(accountId)); } } }<file_sep>/Shared/SaaS.PdfEscape.Api.Client/PdfEscapeApiToken.cs using System; namespace SaaS.PdfEscape.Api.Client { public class PdfEscapeApiToken { public PdfEscapeApiUser User { get; set; } public PdfEscapeApiMembership Membership { get; set; } } public class PdfEscapeApiUser { public string Id { get; set; } public string Name { get; set; } } public class PdfEscapeApiMembership { public DateTime Expiration { get; set; } public uint Status { get; set; } public uint Type { get; set; } } } <file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.Product.cs using SaaS.Data.Entities; using SaaS.Data.Entities.View; using SaaS.Data.Entities.View.Oauth; using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthDbContext { internal async Task<AssignStatus> ProductAssignAsync(AccountProductPair pair, bool isIgnoreBillingCycle = false) { var sqlParams = CreateSqlParams(pair); sqlParams.Add(isIgnoreBillingCycle.ToSql("isIgnoreBillingCycle")); var scalar = (int)await ExecuteScalarAsync("[accounts].[pProductAssign]", sqlParams); return (AssignStatus)scalar; } internal async Task<ViewUnassignProduct> ProductUnassignAsync(AccountProductPair pair) { var sqlParams = CreateSqlParams(pair); return await ExecuteReaderAsync<ViewUnassignProduct>("[accounts].[pProductUnAssign]", sqlParams); } internal async Task ProductDeactivateAsync(AccountProductPair pair) { var sqlParams = new SqlParameter[] { pair.AccountProductId.ToSql("accountProductId"), 3.ToSql("activationReason") }; await ExecuteNonQueryAsync("[accounts].[pProductDeactivate]", sqlParams); } internal async Task ProductNextRebillDateSetAsync(AccountProductPair pair, DateTime? nextRebillDate) { var sqlParams = new SqlParameter[] { pair.AccountId.ToSql("accountId"), pair.AccountProductId.ToSql("accountProductId"), nextRebillDate.ToSql("nextRebillDate") }; await ExecuteNonQueryAsync("[accounts].[pProductSetIsRenewalByAccountId]", sqlParams); } internal async Task ProductEndDateSetAsync(AccountProductPair pair, DateTime endDate) { var sqlParams = new SqlParameter[] { pair.AccountId.ToSql("accountId"), pair.AccountProductId.ToSql("accountProductId"), endDate.ToSql("expiryDate") }; await ExecuteNonQueryAsync("[accounts].[pProductSetExpiryDateByAccountId]", sqlParams); } internal async Task ProductIsNewAsync(AccountProductPair pair, bool isNew) { var sqlParams = CreateSqlParams(pair); sqlParams.Add(isNew.ToSql("isNew")); await ExecuteNonQueryAsync("[accounts].[pProductSetIsNewByAccountId]", sqlParams); } internal async Task<ViewUpgradeProduct> UpgradeProductGetAsync(Guid accountProductId) { var sqlParams = new SqlParameter[] { accountProductId.ToSql("accountProductId") }; return await ExecuteReaderAsync<ViewUpgradeProduct>("[accounts].[pProductUpgradeGetByAccountProductId]", sqlParams); } internal async Task<List<ViewAccountProduct>> AccountProductsGetAsync(Guid accountId, Guid? systemId) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId"), systemId.ToSql("systemId") }; using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = sqlParams.CommandText("[accounts].[pProductGetByAccountId]"); cmd.Parameters.AddRange(sqlParams); await Database.Connection.OpenAsync(); var reader = await cmd.ExecuteReaderAsync(); var products = ((IObjectContextAdapter)this).ObjectContext.Translate<ViewAccountProduct>(reader).ToList(); reader.NextResult(); var modules = ((IObjectContextAdapter)this).ObjectContext.Translate<ViewAccountProductModule>(reader).ToList(); Database.Connection.Close(); foreach (var product in products) product.Modules = modules.Where(e => e.AccountProductId == product.AccountProductId).ToList(); return products; } } internal async Task<List<ViewAccountMicrotransaction>> AccountMicrotransactionsGetAsync(Guid accountId) { var sqlParams = CreateSqlParams(accountId); using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = sqlParams.CommandText("[accounts].[pMicrotransactionGetByAccountId]"); cmd.Parameters.AddRange(sqlParams); await Database.Connection.OpenAsync(); var reader = await cmd.ExecuteReaderAsync(); var products = ((IObjectContextAdapter)this).ObjectContext.Translate<ViewAccountMicrotransaction>(reader).ToList(); reader.NextResult(); var modules = ((IObjectContextAdapter)this).ObjectContext.Translate<ViewAccountMicrotransactionModule>(reader).ToList(); Database.Connection.Close(); foreach (var product in products) product.Modules = modules.Where(e => e.AccountMicrotransactionId == product.AccountMicrotransactionId).ToList(); return products; } } internal async Task<List<ViewUpclickProduct>> UpclickProductsGetAsync() { return await ExecuteReaderCollectionAsync<ViewUpclickProduct>("[products].[pProductUpclickGet]", new SqlParameter[] { }); } internal async Task<ViewOwnerProduct> OwnerProductGetAsync(AccountProductPair pair) { var sqlParams = new SqlParameter[] { pair.AccountId.ToSql("accountId"), pair.AccountProductId.ToSql("accountProductId") }; return await ExecuteReaderAsync<ViewOwnerProduct>("[accounts].[pProductGetByOwnerIDAccountProductId]", sqlParams); } internal async Task<ViewOwnerProduct> OwnerProductDetailsGetAsync(AccountProductPair pair) { var sqlParams = CreateSqlParams(pair).ToArray(); using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = sqlParams.CommandText("[accounts].[pProductDetailGetByOwnerId]"); cmd.Parameters.AddRange(sqlParams); await Database.Connection.OpenAsync(); var reader = await cmd.ExecuteReaderAsync(); var product = ((IObjectContextAdapter)this).ObjectContext.Translate<ViewOwnerProduct>(reader).FirstOrDefault(); if (!object.Equals(product, null)) { reader.NextResult(); var accounts = ((IObjectContextAdapter)this).ObjectContext.Translate<ViewOwnerAccount>(reader).ToList(); reader.NextResult(); var accountSystems = ((IObjectContextAdapter)this).ObjectContext.Translate<ViewAccountSystem>(reader).ToList(); reader.NextResult(); var sessionTokens = ((IObjectContextAdapter)this).ObjectContext.Translate<ViewSessionToken>(reader).ToList(); Database.Connection.Close(); foreach (var account in accounts) { account.AccountSystems = accountSystems.Where(e => e.AccountId == account.AccountId).ToList(); account.SessionTokens = sessionTokens.Where(e => e.AccountId == account.AccountId).ToList(); } product.Accounts = accounts; } return product; } } internal async Task<AllowedCountStatus> ProductAllowedSetAsync(AccountProductPair pair, int allowedCount) { var sqlParams = CreateSqlParams(pair); sqlParams.Add(allowedCount.ToSql("allowedCount")); var scalar = (int)await ExecuteScalarAsync("[accounts].[pProductSetAllowedCountByOwnerIDAccountProductId] ", sqlParams); return (AllowedCountStatus)scalar; } internal async Task<List<ViewOwnerProduct>> OwnerProductsGetAsync(Guid accountId) { return await ExecuteReaderCollectionAsync<ViewOwnerProduct>("[accounts].[pProductGetByOwnerId]", CreateSqlParams(accountId)); } internal async Task OwnerProductInsertAsync(Guid accountId, string productUid, string currency, decimal price, decimal priceUsd, int quantity) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId"), productUid.ToSql("productId"), quantity.ToSql("quantity"), currency.ToSql("currency"), price.ToSql("invoicePrice"), priceUsd.ToSql("invoicePriceUsd") }; await ExecuteNonQueryAsync("[accounts].[pProductAddByAccountId]", sqlParams); } } }<file_sep>/Shared/SaaS.Data.Entities/Oauth/ExternalClient.cs namespace SaaS.Data.Entities.Oauth { public enum ExternalClient { google = 1, facebook, microsoft } } <file_sep>/Web.Api/SaaS.Sso/tasks/app.json.js const gulp = require('gulp'); gulp.task('app.json:i18n', () => { return gulp.src('src/i18n/**/*.json') .pipe(gulp.dest('dist/i18n')) }); gulp.task('app.json:watch', () => { return gulp.watch('src/i18n/**/*.json', gulp.series('app.json:i18n')); }); gulp.task('app.json', gulp.parallel('app.json:i18n'));<file_sep>/Shared/SaaS.Notification/NotificationManager.cs using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.View; using SaaS.Identity; using SaaS.Mailer.Models; using System; using System.Threading.Tasks; using System.Web; namespace SaaS.Notification { public class NotificationManager { private readonly IAuthRepository _auth; private readonly SaaS.Mailer.EmailRepository _repository; private readonly NotificationSettings _settings; private async Task<SaaS.Mailer.Models.Notification> CreateNotification(Account account) { var uriBuilder = new UriBuilder(_settings.DownloadLink); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query.Add("email", account.Email); if (account.IsBusiness) { query.Add("build", "b2b"); query.Add(await _auth.GenerateEmailConfirmationToken(account)); } uriBuilder.Query = query.ToString(); return new SaaS.Mailer.Models.Notification { AccountId = account.Id, FirstName = account.FirstName, LastName = account.LastName, Email = account.Email, DownloadLink = uriBuilder.Uri.ToString() }; } private async Task<CreatePasswordNotification> CreatePasswordNotification(Account targetAccount) { var targetUserNotification = await CreateNotification(targetAccount); var notification = new CreatePasswordNotification(targetUserNotification); var uri = await _auth.GeneratePasswordResetTokenLinkAsync(targetAccount, _settings.CreatePassword); notification.CreatePasswordLink = uri.ToString(); return notification; } public NotificationManager(IAuthRepository auth, NotificationSettings settings) { _auth = auth; _repository = new SaaS.Mailer.EmailRepository(); _settings = settings; } public async Task AccountCreationComplete(Account targetUser) { var targetUserNotification = await CreateNotification(targetUser); var uri = await _auth.GeneratePasswordResetTokenLinkAsync(targetUser, _settings.ResetPassword); var notification = new RecoverPasswordNotification(targetUserNotification, uri.ToString()); await _repository.SendAccountCreationCompleteNotification(notification); } public async Task BusinessDownloadNewAccount(Account targetUser) { var targetUserNotification = await CreateNotification(targetUser); await _repository.SendBusinessDownloadNewAccountNotification(targetUserNotification); } public async Task BusinessDownload(Account targetUser) { var targetUserNotification = await CreateNotification(targetUser); await _repository.SendBusinessDownloadNotification(targetUserNotification); } public async Task PasswordChanged(Account targetUser) { var targetUserNotification = await CreateNotification(targetUser); await _repository.SendPasswordChangedNotification(targetUserNotification); } public async Task ProductSuspend(Guid accountId, ViewOwnerProduct product, DateTime? nextRebillDate) { if (nextRebillDate.HasValue) return; if (product.EndDate.HasValue && product.EndDate.Value > DateTime.UtcNow && (product.EndDate.Value - DateTime.UtcNow).TotalDays <= 10) return; var targetUser = await _auth.AccountGetAsync(accountId); var targetUserNotification = await CreateNotification(targetUser); var productSuspendNotification = new ProductSuspendNotification(targetUserNotification, product.ProductName, product.EndDate); await _repository.SendProductSuspendNotification(productSuspendNotification); } public async Task ProductAssigned(Guid accountId, ViewOwnerProduct product, Account targetUser) { if (object.Equals(targetUser, null) || targetUser.Id == accountId) return; var ownerUser = await _auth.AccountGetAsync(accountId); var targetUserNotification = await CreateNotification(targetUser); var ownerUserNotification = await CreateNotification(ownerUser); var notification = new ProductAssignedNotification(targetUserNotification, product.ProductName, ownerUserNotification); if (targetUser.IsEmptyPassword()) { var uri = await _auth.GeneratePasswordResetTokenLinkAsync(targetUser, _settings.CreatePassword); notification.CreatePasswordLink = uri.ToString(); } if (product.IsPPC) await _repository.SendProductEditionAssignedNotification(notification); else await _repository.SendProductAssignedNotification(notification); } public async Task ProductUnassigned(Guid accountId, ViewOwnerProduct product, Account targetUser) { if (object.Equals(targetUser, null) || targetUser.Id == accountId) return; var ownerUser = await _auth.AccountGetAsync(accountId); var targetUserNotification = await CreateNotification(targetUser); var ownerUserNotification = await CreateNotification(ownerUser); var notification = new ProductAssignedNotification(targetUserNotification, product.ProductName, ownerUserNotification); await _repository.SendProductUnassignedNotification(notification); } public async Task RecoverPassword(Account targetUser) { var targetUserNotification = await CreateNotification(targetUser); var uri = await _auth.GeneratePasswordResetTokenLinkAsync(targetUser, _settings.ResetPassword); var notification = new RecoverPasswordNotification(targetUserNotification, uri.ToString()); await _repository.SendRecoverPasswordNotification(notification); } public async Task EmailConfirmationCovermount(Account targetUser) { var uri = await _auth.GenerateEmailConfirmationTokenLinkAsync(targetUser, _settings.EmailConfirmation); var targetUserNotification = await CreateNotification(targetUser); var activationNotification = new EmailConfirmationNotification(targetUserNotification, uri.ToString()); await _repository.SendEmailConfirmationCovermountNotification(activationNotification); } public async Task EmailConfirmation(Account targetUser) { var uri = await _auth.GenerateEmailConfirmationTokenLinkAsync(targetUser, _settings.EmailConfirmation); var targetUserNotification = await CreateNotification(targetUser); var activationNotification = new EmailConfirmationNotification(targetUserNotification, uri.ToString()); await _repository.SendEmailConfirmationNotification(activationNotification); } public async Task EmailChangeConfirmationNotification(Account targetUser, string newEmail) { var pending = await _auth.AccountSubEmailPendingSetAsync(targetUser.Id, newEmail); var uri = _auth.GenerateEmailChangeConfirmationTokenLinkAsync(_settings.EmailChangeConfirmation, pending); var targetUserNotification = await CreateNotification(targetUser); var activationNotification = new EmailChangeConfirmationNotification(targetUserNotification, newEmail, uri.ToString()); await _repository.SendEmailChangeConfirmationNotification(activationNotification); } public async Task EmailChange(Account targetUser, string newEmail) { var targetUserNotification = await CreateNotification(targetUser); var activationNotification = new EmailChangeNotification(targetUserNotification, newEmail); await _repository.SendEmailChangeNotification(activationNotification); } public async Task MergeConfirmationNotification(Account targetUser, Account targetUserFrom, Account targetUserPrimaryEmail) { var pending = await _auth.AccountMergePendingMergeAsync(targetUser.Id, targetUserFrom.Id, targetUserPrimaryEmail.Id); var uri = _auth.GenerateMergeConfirmationTokenLinkAsync(_settings.MergeConfirmation, pending); var targetUserNotification = await CreateNotification(targetUserFrom); var activationNotification = new MergeConfirmationNotification(targetUserNotification, uri.ToString()); await _repository.SendMergeConfirmationNotification(activationNotification); } public async Task LegacyActivationCreatePassword(Account targetUser) { var notification = await CreatePasswordNotification(targetUser); await _repository.SendLegacyActivationCreatePasswordNotification(notification); } public async Task LegacyActivationSignInNotification(Account targetUser) { var targetUserNotification = await CreateNotification(targetUser); await _repository.SendLegacyActivationSignInNotification(targetUserNotification); } public async Task LegacyCreatePasswordReminder(Account targetUser) { var notification = await CreatePasswordNotification(targetUser); await _repository.SendLegacyCreatePasswordReminder(notification); } public async Task Welcome(Account targetUser) { var targetUserNotification = await CreateNotification(targetUser); await _repository.SendWelcomeNotification(targetUserNotification); } public async Task MicrotransactionCreatePassword(Account targetUser) { var notification = await CreatePasswordNotification(targetUser); await _repository.MicrotransactionCreatePassword(notification); } } public class NotificationSettings { public Uri DownloadLink { get; set; } public Uri ResetPassword { get; set; } public Uri CreatePassword { get; set; } public Uri EmailConfirmation { get; set; } public Uri MergeConfirmation { get; set; } public Uri EmailChangeConfirmation { get; set; } } }<file_sep>/Shared/SaaS.Data.Entities.Admin/Oauth/SessionToken.cs using System; using System.ComponentModel.DataAnnotations; namespace SaaS.Data.Entities.Admin.Oauth { public class SessionToken: Entity<Guid> { public DateTime IssuedUtc { get; set; } public DateTime ExpiresUtc { get; set; } [Required] public string ProtectedTicket { get; set; } } } <file_sep>/Web.Api/SaaS.Api/Controllers/Api/ExternalController.cs using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Api.Oauth; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View; using SaaS.IPDetect; using SaaS.Oauth2.Core; using SaaS.Oauth2.Services; using System; using System.Collections.Concurrent; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http; using WebApi.OutputCache.V2; namespace SaaS.Api.Controllers.Api { [RoutePrefix("api/external")] public class ExternalController : SaaSApiController { //https://www.facebook.com/settings?tab=applications //https://myaccount.google.com/permissions private static ConcurrentDictionary<Guid, ExternalToken> _externaLoginStorage = new ConcurrentDictionary<Guid, ExternalToken>(); static ExternalController() { CancellationTokenSource cancelationTokenSource = new CancellationTokenSource(); Task.Factory.StartNew(() => { while (true) { var dateTime = DateTime.Now.AddMinutes(-20); var oldTokens = _externaLoginStorage.Values.Where(e => e.CreateDate < dateTime).ToList(); foreach (var oldToken in oldTokens) { ExternalToken token; _externaLoginStorage.TryRemove(oldToken.State, out token); } Task.Delay(TimeSpan.FromMinutes(1), cancelationTokenSource.Token).Wait(); } }, cancelationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); } private Task<ExternalToken> GetExternalToken(Guid state, CancellationToken cancellationToken) { var task = Task.Run(async delegate { ExternalToken externalToken = null; while (true) { if (cancellationToken.IsCancellationRequested) break; if (object.Equals(externalToken, null)) _externaLoginStorage.TryGetValue(state, out externalToken); if (!object.Equals(externalToken, null) && !object.Equals(externalToken.Token, null)) return externalToken; await Task.Delay(TimeSpan.FromSeconds(0.5)); } return externalToken; }, cancellationToken); task.Wait(TimeSpan.FromSeconds(10)); return task; } [HttpPost, Route("token")] public async Task<IHttpActionResult> Token(SignInViewModel internalSignInViewModel, CancellationToken cancellationToken) { var task = GetExternalToken(internalSignInViewModel.State, cancellationToken); if (task.Status == TaskStatus.WaitingForActivation || object.Equals(task.Result, null) || object.Equals(task.Result.Token, null)) return ResponseMessage(new HttpResponseMessage(HttpStatusCode.PartialContent)); var token = task.Result; internalSignInViewModel.ExternalClient = token.Provider; var service = OauthServiceFactory.CreateService(token.Provider); var profile = await service.ProfileAsync(token.Token, cancellationToken); var account = await _auth.AccountGetAsync(profile.Email, isIncludeSubEmails: true); if (!object.Equals(account, null)) { var sessionTokens = await _auth.SessionTokenExternalHistoriesAsync(account.Id); if (sessionTokens.Any(e => e.IsUnlinked && string.Equals(token.Provider, e.ExternalClientName, StringComparison.InvariantCultureIgnoreCase) && string.Equals(profile.Id, e.ExternalAccountId, StringComparison.InvariantCultureIgnoreCase))) { return AccountIsDisconnected(token.Provider); } } if (object.Equals(account, null)) { account = new Account(profile.Email, profile.FirstName, profile.LastName); var result = await _auth.AccountCreateAsync(account); var errorResult = GetErrorResult(result); if (!object.Equals(errorResult, null)) return errorResult; var accountsDetail = new ViewAccountDetails(); accountsDetail.GeoIp = IpAddressDetector.IpAddress; accountsDetail.Id = account.Id; accountsDetail.Uid = token.Uid; accountsDetail.Cmp = token.Cmp; accountsDetail.Source = token.Source; accountsDetail.WebForm = token.FormId; accountsDetail.Build = token.Build; accountsDetail.Partner = token.Partner; accountsDetail.IsTrial = token.Trial; await _auth.AccountDetailsSetAsync(accountsDetail); await NotificationManager.Welcome(account); } await _auth.AccountOptinSetAsync(account, token.Optin); await _auth.AccountActivateAsync(account); internalSignInViewModel.SetUser(account); await _auth.SessionTokenExternalHistorySetAsync(account.Id, token.Provider, profile.Id, profile.Email); return ResponseMessage(await OauthManager.InternalSignIn(internalSignInViewModel, token.VisitorId)); } [HttpPost, Route("connect-account"), SaaSAuthorize] public async Task<IHttpActionResult> ConnectAccount([FromUri] Guid state, CancellationToken cancellationToken) { try { var task = GetExternalToken(state, cancellationToken); if (task.Status == TaskStatus.WaitingForActivation || object.Equals(task.Result, null) || object.Equals(task.Result.Token, null)) return ResponseMessage(new HttpResponseMessage(HttpStatusCode.PartialContent)); var token = task.Result; var service = OauthServiceFactory.CreateService(token.Provider); var profile = await service.ProfileAsync(token.Token, cancellationToken); var user = await _auth.AccountGetAsync(profile.Email, isIncludeSubEmails: true); if (!object.Equals(user, null) && user.Id != AccountId) return AccountExists(); else await _auth.SessionTokenExternalHistoryConnectAccountAsync(AccountId, token.Provider, profile.Id, profile.Email); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } [HttpGet, Route("config")] [CacheOutput(ClientTimeSpan = 86400, ServerTimeSpan = 86400)] public IHttpActionResult Config() { var google = OauthServiceFactory.CreateService("google"); var facebook = OauthServiceFactory.CreateService("facebook"); var microsoft = OauthServiceFactory.CreateService("microsoft"); return Ok(new ExternalLoginSettingsViewModel( new ExternalLoginSettings { Window = new ExternalWindowSettings(google.GetWindowSize()) }, new ExternalLoginSettings { Window = new ExternalWindowSettings(facebook.GetWindowSize()) }, new ExternalLoginSettings { Window = new ExternalWindowSettings(microsoft.GetWindowSize()) })); } [HttpGet, Route("login/{externalClient:regex(^google|facebook|microsoft$)}")] public IHttpActionResult ExternaLogin(Guid state, ExternalClient externalClient, string lang = "en", string source = null, string formId = null, string build = null, string partner = null, Guid? visitorId = null, int? uid = null, string cmp = null, bool? optin = null, bool? trial = null) { var service = OauthServiceFactory.CreateService(OauthManager.GetExternalClientName(externalClient)); if (object.Equals(service, null)) return NotFound(); var url = new Uri(service.GetAuthenticationUrl(lang)); var query = HttpUtility.ParseQueryString(url.Query); query.Add("state", state.ToString("N")); var uriBuilder = new UriBuilder(url); uriBuilder.Query = query.ToString(); var externalToken = new ExternalToken(state, OauthManager.GetExternalClientName(externalClient)) { VisitorId = visitorId, Uid = uid, Cmp = cmp, Optin = optin, Build = build, Partner = partner, Trial = trial }; if (!string.IsNullOrEmpty(source)) externalToken.Source = string.Format("{0}-{1}", source, externalClient); if (!string.IsNullOrEmpty(formId)) externalToken.FormId = FormIdBuilder.Build(formId, string.Format("-{0}", externalClient)); _externaLoginStorage.AddOrUpdate(state, externalToken, (key, oldValue) => externalToken); return Redirect(uriBuilder.ToString()); } [HttpGet, Route("callback")] public async Task<IHttpActionResult> ExternaLoginCallback(Guid state, CancellationToken cancellationToken, string code = null, string error = null) { if (!string.IsNullOrEmpty(error)) { if ("access_denied".Equals(error, StringComparison.InvariantCultureIgnoreCase)) return Error("Your email is required to complete the sign-in process. Error is access_denied."); return Error(error); } ExternalToken externalToken; if (!_externaLoginStorage.TryGetValue(state, out externalToken)) return Error("State is undefined"); var service = OauthServiceFactory.CreateService(externalToken.Provider); var token = await service.TokenAsync(code, cancellationToken); if (object.Equals(token, null)) return Error("Token is undefined"); var profile = await service.ProfileAsync(token, cancellationToken); if (object.Equals(profile, null)) return ErrorContent("invalid_grant", "Your email is required to complete the sign-in process. Profile is null."); if (string.IsNullOrEmpty(profile.Email)) return ErrorContent("invalid_grant", "Your email is required to complete the sign-in process. Email is empty."); externalToken.Token = token; return Success(); } [HttpGet, Route("session-token"), SaaSAuthorize] public async Task<IHttpActionResult> ExternaSessionToken() { try { return Ok(await _auth.SessionTokenExternalHistoriesAsync(AccountId)); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpPost, Route("session-token"), ValidateNullModel, ValidateModel, SaaSAuthorize] public async Task<IHttpActionResult> ExternaSessionTokenState([FromBody] SetPasswordViewModel model) { return await CurrentAccountExecuteAsync(async delegate (Account user) { return await Task.Run(async () => { if (!model.IsConnect && user.IsEmptyPassword()) { var sessionTokens = await _auth.SessionTokenExternalHistoriesAsync(user.Id); if (!sessionTokens.Any(entity => entity.Id != model.Id && !entity.IsUnlinked)) { if (object.Equals(model, null) || string.IsNullOrEmpty(model.NewPassword)) return ErrorContent("invalid_request", "Password is required.", httpStatusCode: HttpStatusCode.PreconditionFailed); await _auth.AccountPasswordSetAsync(user, model.NewPassword); } } await _auth.SessionTokenExternalHistorySetStateAsync(model.Id, !model.IsConnect); return Ok(); }); }); } private IHttpActionResult Success() { var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StringContent("<script>window.open('', '_self').close();</script>", Encoding.UTF8, "text/html"); return ResponseMessage(response); } private IHttpActionResult Error(string message) { var response = new HttpResponseMessage(HttpStatusCode.BadRequest); response.Content = new StringContent(message, Encoding.UTF8, "text/html"); return ResponseMessage(response); } private class ExternalToken { public Guid State { get; set; } public string Provider { get; set; } public TokenResult Token { get; set; } public DateTime CreateDate { get; set; } public Guid? VisitorId { get; set; } public int? Uid { get; set; } public string Cmp { get; set; } public string Source { get; set; } public string FormId { get; set; } public bool? Optin { get; set; } public string Build { get; set; } public string Partner { get; set; } public bool? Trial { get; set; } public ExternalToken(Guid state, string provider) { State = state; Provider = provider; CreateDate = DateTime.Now; } } } }<file_sep>/Shared/SaaS.Data.Entities/AccountEntity.cs using System; namespace SaaS.Data.Entities { public class AccountEntity<T> : Entity<T> { public Guid AccountId { get; set; } } }<file_sep>/Web.Api/SaaS.UI.Admin/Helpers/Html.cs using Newtonsoft.Json; using SaaS.UI.Admin.App_Start; using StructureMap; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.UI; namespace SaaS.UI.Admin.Helpers { public static class Html { private static readonly IHtmlString _active = new HtmlString("active"); public static bool IsActive(this HtmlHelper html, string controller) { string _controller = (string)html.ViewContext.RouteData.Values["controller"]; return string.Compare(_controller, controller, true) == 0; } public static IHtmlString IsActiveClass(this HtmlHelper html, string controller, string action) { string _controller = (string)html.ViewContext.RouteData.Values["controller"]; string _action = (string)html.ViewContext.RouteData.Values["action"]; if (string.Compare(_controller, controller, true) == 0 && string.Compare(_action, action, true) == 0) return new HtmlString("active"); return null; } public static IHtmlString IsActiveClass(this HtmlHelper html, string controller) { return html.IsActive(controller) ? _active : null; } public static IHtmlString IsNotActiveClass(this HtmlHelper html, string controller) { string _controller = (string)html.ViewContext.RouteData.Values["controller"]; if (string.Compare(_controller, controller, true) != 0) return new HtmlString("active"); return null; } public static IHtmlString PageHeader(this HtmlHelper html, string title) { using (HtmlTextWriter writer = new HtmlTextWriter(html.ViewContext.Writer, string.Empty)) { //< div class="row"> // <div class="col-lg-12"> // <h1 class="page-header">Roles</h1> // </div> //</div> writer.AddAttribute(HtmlTextWriterAttribute.Class, "row"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.AddAttribute(HtmlTextWriterAttribute.Class, "col-lg-12"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.AddAttribute(HtmlTextWriterAttribute.Class, "page-header"); writer.RenderBeginTag(HtmlTextWriterTag.H1); writer.Write(title); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderEndTag(); } return null; } public static IHtmlString AppSettings(this HtmlHelper html) { var urlHelper = new UrlHelper(html.ViewContext.RequestContext); var user = HttpContext.Current.User; string controller = (string)html.ViewContext.RouteData.Values["controller"]; string action = (string)html.ViewContext.RouteData.Values["action"]; IAppSettings settings = ObjectFactory.GetInstance<IAppSettings>(); var appSettings = new { lang = "en", debug = HttpContext.Current.IsDebuggingEnabled, oauth = settings.OAuth, page = new { controller = controller, action = action }, user = new { identity = new { name = user.Identity.Name, isAuthenticated = user.Identity.IsAuthenticated } } }; string json = Serialize(appSettings); using (HtmlTextWriter writer = new HtmlTextWriter(html.ViewContext.Writer)) { string script = string.Format("angular.module('app').value('appSettings', {0});", json); writer.WriteScript(script); } return null; } private static void WriteScript(this HtmlTextWriter writer, string script) { writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript"); writer.RenderBeginTag(HtmlTextWriterTag.Script); writer.Write(script); writer.RenderEndTag(); } private static string Serialize(object obj) { return JsonConvert.SerializeObject(obj, Formatting.None, GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings); } public static IHtmlString Special(this HtmlHelper html) { var user = HttpContext.Current.User; #if LuluSoft #region var special = new { url = "https://cgate.sodapdf.com/join.aspx", tracking = new { wid = 6644, uid = 1015225, @ref = "sodapdf.com/support", cmp = "spdf_all_support_all_all_all_all", key1 = "support", ga = "UA-17191366-1", gtm = "GTM-52QP9R", mkey1 = user.Identity.Name, mkey2 = user.Identity.Name }, products = new SpecialProduct[] { new SpecialProduct("Soda PDF Anywhere Home(Yearly)") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "77iPNOyuq2k="), new SpecialDiscount("50%", "ugRb4nrSAzA=") } }, new SpecialProduct("Soda PDF Anywhere Premium (Yearly)") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "ELY1bRxSToE="), new SpecialDiscount("50%", "eS0Fup0MdgE=") } }, new SpecialProduct("Soda PDF Anywhere Business (Yearly)") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "+uzT/KF1LWE="), new SpecialDiscount("50%", "tbdX/7UxkUw=") } }, new SpecialProduct("Soda PDF 10 Home") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "Agw4iVbg790="), new SpecialDiscount("50%", "Tg0/FBi+QHs=") } }, new SpecialProduct("Soda PDF 10 Home + OCR") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "2SzOiUkbXzA="), new SpecialDiscount("50%", "k8mvmgOyJXc=") } }, new SpecialProduct("Soda PDF 10 Premium") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "uATpR9Wb0w4="), new SpecialDiscount("50%", "UE/t8J7I9q0=") } }, new SpecialProduct("Soda PDF 10 Premium + OCR") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "HSdgi1K/qgc="), new SpecialDiscount("50%", "VQfEVXF0MJ4=") } }, new SpecialProduct("Soda PDF 11 Home") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "vtUv1ULcsQ0="), new SpecialDiscount("50%", "jjVUfpm56GU=") } }, new SpecialProduct("Soda PDF 11 Home + OCR") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "%2BE7LOPcO7rQ="), new SpecialDiscount("50%", "Jx29FsB5h3c=") } }, new SpecialProduct("Soda PDF 11 Premium") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "VQOL4TZbJ08="), new SpecialDiscount("50%", "gXU9HkLlc08=") } }, new SpecialProduct("Soda PDF 11 Premium + OCR") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "UKWmwj5ylIQ="), new SpecialDiscount("50%", "kAxE3bow7u4=") } }, new SpecialProduct("Soda PDF 11 Business") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "1YMvd7Jp6dI="), new SpecialDiscount("50%", "aIAxsjAiqqI=") } }, new SpecialProduct("E-Sign Unlimited") { Discounts = new SpecialDiscount[] { new SpecialDiscount("0%", "VvnIFGaHq50=") } }, new SpecialProduct("OCR Add-On") { Discounts = new SpecialDiscount[] { new SpecialDiscount("0%", "p/wXwkfK3lw=") } }, new SpecialProduct("E-Sign 10-Pack") { Discounts = new SpecialDiscount[] { new SpecialDiscount("0%", "6qxF7t5DG24=") } }, new SpecialProduct("Soda PDF Back Up Protection") { Discounts = new SpecialDiscount[] { new SpecialDiscount("0%", "5OuYuAZ8ypw=") } }, new SpecialProduct("Extended Download Protection") { Discounts = new SpecialDiscount[] { new SpecialDiscount("0%", "D2cAHsJxzRs=") } }, new SpecialProduct("Back Up CD") { Discounts = new SpecialDiscount[] { new SpecialDiscount("0%", "qL5WIe1VucE=") } } } }; #endregion #endif #if PdfForge #region var special = new { url = "https://cgate.pdfarchitect.org/join.aspx", tracking = new { wid = 3843, uid = 1006694, @ref = "pdfarchitect.org", cmp = "pdfa_all_support_all_all_all_all", key1 = "support", ga = "UA-36447566-1", gtm = "GTM-W39F3W", mkey1 = user.Identity.Name, mkey2 = user.Identity.Name }, products = new SpecialProduct[] { new SpecialProduct("PDF Architect 6 Standard Edition") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "ojTLzn6zFqM="), new SpecialDiscount("50%", "jz0iCLAp5rk=") } }, new SpecialProduct("PDF Architect 6 Pro Edition") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "A3INEjQpuvs="), new SpecialDiscount("50%", "bYN2KRCp8Nk=") } }, new SpecialProduct("PDF Architect 6 Pro+OCR Edition") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "lO0vJXbW5ho="), new SpecialDiscount("50%", "cbHf4zBAyzA=") } }, new SpecialProduct("PDF Architect Standard Plan") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "jNpQGlTpprQ="), new SpecialDiscount("50%", "H3QXpieXBZM=") } }, new SpecialProduct("PDF Architect Pro Plan") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "XIQ1xx+TX7M="), new SpecialDiscount("50%", "oqjlY9T+W3I=") } }, new SpecialProduct("PDF Architect Pro+OCR Plan") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "Om1SD+OdEuk="), new SpecialDiscount("50%", "/xWSGI3sfd4=") } }, new SpecialProduct("PDF Architect - OCR Plan") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "+6YgbNSTjr0="), new SpecialDiscount("50%", "6K+QPV/V3rQ=") } }, new SpecialProduct("PDF Architect Convert Plan") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "+tY3JM8QVx8=") } }, new SpecialProduct("PDF Architect Edit Plan") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "Ncejr5pa8bw=") } }, new SpecialProduct("PDF Architect E-Sign Unlimited") { Discounts = new SpecialDiscount[] { new SpecialDiscount("25%", "yh652FTyy6o="), new SpecialDiscount("50%", "mOfywTIeFIA=") } }, new SpecialProduct("Extended Download Protection (for plans)") { Discounts = new SpecialDiscount[] { new SpecialDiscount("0%", "ziKjRhoLgJQ=") } } } }; #endregion #endif #if PdfSam var special = new { url = "https://cgate.sodapdf.com/join.aspx", tracking = new { mkey1 = user.Identity.Name, mkey2 = user.Identity.Name }, products = new SpecialProduct[] { } }; #endif string json = Serialize(special); using (HtmlTextWriter writer = new HtmlTextWriter(html.ViewContext.Writer)) { string script = string.Format("angular.module('app').value('special', {0});", json); writer.WriteScript(script); } return null; } private class SpecialProduct { public SpecialProduct(string name) { Name = name; } public string Name { get; set; } public SpecialDiscount[] Discounts { get; set; } } private class SpecialDiscount { public SpecialDiscount(string name, string ujId) { Name = name; UjId = ujId; } public string Name { get; set; } public string UjId { get; set; } } } }<file_sep>/Shared/SaaS.Data.Entities/View/ViewAccountDetails.cs using System; using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Data.Entities.View { public class ViewAccountDetails : Entity<Guid> { public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Phone { get; set; } public string PhoneESign { get; set; } public string Company { get; set; } public string Occupation { get; set; } public string CountryISO2 { get; set; } public string LanguageISO2 { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string PostalCode { get; set; } public string State { get; set; } public string Build { get; set; } public string Cmp { get; set; } public int? Uid { get; set; } public string GeoIp { get; set; } public string Partner { get; set; } public bool IsAnonymous { get; set; } public bool IsActivated { get; set; } public bool IsBusiness { get; set; } #if LuluSoft public bool? IsPreview { get; set; } public int? TrialDays { get; set; } #endif public bool? Optin { get; set; } public bool? IsTrial { get; set; } public Guid? InstallationID { get; set; } [NotMapped] public ulong Status { get { ulong status = 0; status |= (ulong)(IsActivated ? AccountStatus.IsActivated : 0); status |= (ulong)(IsAnonymous ? AccountStatus.IsAnonymous : 0); status |= (ulong)(IsBusiness ? AccountStatus.IsBusiness : 0); #if LuluSoft status |= (ulong)(IsPreview == true ? AccountStatus.IsPreview : 0); #endif return status; } } [NotMapped] public string Source { get; set; } [NotMapped] public string WebForm { get; set; } } } <file_sep>/Web.Api/SaaS.Api/Oauth/Providers/ClaimsIdentityHelper.cs using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Oauth; using SaaS.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; namespace SaaS.Api.Oauth.Providers { public static class ClaimsIdentityHelper { private static readonly HashSet<string> _specialClaims = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { "email", "firstName", "lastName", "isAnonymous", "isActivated", "status" }; public static void AddClaim(this ClaimsIdentity identity, string type, object value) { identity.AddClaim(new Claim(type, value.ToString())); } public static void TryRemoveClaim(this ClaimsIdentity identity, string type) { var claims = identity.FindAll(type).ToArray(); foreach (var claim in claims) identity.TryRemoveClaim(claim); } public static void AddClaims(this ClaimsIdentity identity, Account user, Client client) { identity.TryRemoveClaim(ClaimTypes.Name); identity.AddClaim(ClaimTypes.Name, user.Email); foreach (var specialClaim in _specialClaims) { var claim = identity.FindFirst(specialClaim); if (!object.Equals(claim, null)) identity.TryRemoveClaim(claim); } string[] modules = null; if (user.IsAnonymous) { identity.TryRemoveClaim("module"); switch (client.Name.ToLower()) { case "saas": modules = new string[] { "create", "free convert", "paywall" }; break; case "pdfrotate": modules = new string[] { "edit" }; break; case "pdfprotect": modules = new string[] { "secure" }; break; case "splitpdf": modules = new string[] { "edit" }; break; case "pdfconvert": modules = new string[] { "convert" }; break; case "pdfcreateconvert": modules = new string[] { "create", "convert", "edit", "insert", "secure" }; break; case "pdfmerge": case "pdfcombine": case "pdfjoin": case "pdfcreate": case "esign-lite": case "soda-lite": modules = new string[] { "create", }; break; case "soda-pdf-3d-reader": modules = new string[] { "create", "free convert" }; break; } } else { if ("web".Equals(client.Name, StringComparison.InvariantCultureIgnoreCase)) { identity.TryRemoveClaim("module"); modules = new string[] { "create", "convert", "edit", "insert", "secure" }; } } if ("mobile-pdf-merge".Equals(client.Name, StringComparison.InvariantCultureIgnoreCase)) { identity.TryRemoveClaim("module"); modules = new string[] { "create" }; } if (!object.Equals(modules, null)) { foreach (var module in modules) identity.AddClaim(new Claim("module", module)); } if ("soda-lite".Equals(client.Name, StringComparison.InvariantCultureIgnoreCase)) { var sodaLiteClaimName = "paywall-once-per-day"; if (!identity.HasClaim(x => x.Type == "module" && x.Value == sodaLiteClaimName)) identity.AddClaim(new Claim("module", sodaLiteClaimName)); } identity.AddClaim("status", user.GetStatus()); } } }<file_sep>/Web.Api/SaaS.Api.Sign/Controllers/Api/Silanis/BaseApiController.cs using System.Diagnostics; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http; namespace SaaS.Api.Sign.Controllers.Api.Silanis { public abstract class BaseApiController : ApiController { protected abstract string ApiRoot { get; } [DebuggerStepThrough] protected string Format(string format = null, params object[] @params) { var builder = new StringBuilder(ApiRoot); if (!object.Equals(format, null)) builder.AppendFormat(format, @params); return builder.ToString(); } protected HttpResponseMessage HttpProxy(HttpRequestMessage request, string method) { var message = new StringBuilder(); #if PdfForge message.AppendLine("To use this feature, please update to the newest version of PDF Architect 5.1.<br/>"); //en message.AppendLine("Pour utiliser cette fonctionnalité, veuillez svp mettre votre logiciel à jour avec la nouvelle version 5.1.<br/>"); //fr message.AppendLine("Чтобы использовать эту функцию, пожалуйста, обновитесь к более новой версии PDF Architect 5.1.<br/>"); //ru message.AppendLine("Um die Funktion wieder nutzen zu können müssen Sie auf die neuste Version von PDF Architect 5.1 updaten.<br/>"); //de #endif #if !LuluSoft message.AppendLine("To use this feature, please update to the newest version of Soda PDF 9.3.<br/>"); //en message.AppendLine("Pour utiliser cette fonctionnalité, veuillez svp mettre votre logiciel à jour avec la nouvelle version 9.3.<br/>"); //fr message.AppendLine("Чтобы использовать эту функцию, пожалуйста, обновитесь к более новой версии Soda PDF 9.3.<br/>"); //ru message.AppendLine("Um die Funktion wieder nutzen zu können müssen Sie auf die neuste Version von Soda PDF 9.3 updaten.<br/>"); //de #endif return request.CreateResponse(HttpStatusCode.BadRequest, new { error = "invalid_request", error_description = message.ToString() }); } } } <file_sep>/Shared/SaaS.Data.Entities.Admin/View/Oauth/ViewLog.cs using System; namespace SaaS.Data.Entities.Admin.View { public class ViewLog { public string Login { get; set; } public string Role { get; set; } public string Log { get; set; } public Guid? AccountId { get; set; } public DateTime CreateDate { get; set; } } } <file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.AccountDetails.cs using SaaS.Data.Entities.View; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthDbContext { internal async Task<ViewAccountDetails> AccountDetailsGetAsync(Guid accountId) { return await ExecuteReaderAsync<ViewAccountDetails>("[accounts].[pAccountDetailGetByAccountID]", accountId); } internal async Task AccountDetailsSetAsync(ViewAccountDetails accountDetails) { var sqlParams = new List<SqlParameter> { accountDetails.Id.ToSql("accountId"), accountDetails.FirstName.ToSql("firstName"), accountDetails.LastName.ToSql("lastName"), accountDetails.Phone.ToSql("phone"), accountDetails.PhoneESign.ToSql("phoneESign"), accountDetails.Company.ToSql("company"), accountDetails.Occupation.ToSql("occupation"), accountDetails.CountryISO2.ToSql("countryISO2"), accountDetails.LanguageISO2.ToSql("languageISO2"), accountDetails.Address1.ToSql("address1"), accountDetails.Address2.ToSql("address2"), accountDetails.City.ToSql("city"), accountDetails.State.ToSql("state"), accountDetails.PostalCode.ToSql("postalCode"), accountDetails.Build.ToSql("build"), accountDetails.Cmp.ToSql("cmp"), accountDetails.Uid.ToSql("uid"), accountDetails.GeoIp.ToSql("geoIP"), accountDetails.Source.ToSql("source"), accountDetails.Optin.ToSql("optin"), accountDetails.WebForm.ToSql("webForm"), accountDetails.Partner.ToSql("partner") //accountDetails.InstallationID.ToSql("installationID") //accountDetails.IsTrial.ToSql("isTrial") }; //Warning! All transmitted parameters must be implemented on the DB side in this procedure of appropriate product. #if LuluSoft sqlParams.Add(accountDetails.IsTrial.ToSql("trialDays")); sqlParams.Add(accountDetails.IsTrial.ToSql("isTrial")); sqlParams.Add(accountDetails.InstallationID.ToSql("installationID")); #endif await ExecuteNonQueryAsync("[accounts].[pAccountDetailSetByAccountID]", sqlParams); } internal async Task<int?> AccountUidGetAsync(Guid accountId) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId") }; object value = await ExecuteScalarAsync("[accounts].[pAccountUidGetByAccountID]", sqlParams); if (DBNull.Value == value) return null; return (int)value; } } }<file_sep>/Shared/SaaS.Data.Entities/eSign/eSignPackageHistory.cs using System; namespace SaaS.Data.Entities.eSign { public class eSignPackageHistory : AccountEntity<int> { public Guid? AccountProductId { get; set; } public Guid? AccountMicrotransactionId { get; set; } public int oAuthClientId { get; set; } public eSignClient eSignClientId { get; set; } public Guid PackageId { get; set; } public bool IsSuccess { get; set; } public int HttpStatusCode { get; set; } public DateTime CreateDate { get; set; } public string IpAddressHash { get; set; } } }<file_sep>/Web.Api/SaaS.UI.Admin/js/controllers/account/merge.js (function () { 'use strict'; angular .module('app.controllers') .controller('accountMergeController', controller); controller.$inject = ['$rootScope', '$scope', '$timeout', '$notify', '$api', '$form']; function controller($rootScope, $scope, $timeout, $notify, $api, $form) { $scope.model = { accounts: null, openCustomerInfoAfterMerge: true }; $scope.status = null; $scope.isBusy = false; var _checkSelectedItem = function () { var accounts = $scope.model.accounts; if (!accounts.length) return; var activeAccounts = accounts.filter(function (item) { return item.isActive; }); if (activeAccounts.length != 1) $scope.select(0); var activeEmailAccounts = accounts.filter(function (item) { return item.isActiveEmail; }); if (activeEmailAccounts.length != 1) $scope.selectEmail(0); }; $scope.add = function (account) { $scope.isVisible = true; $scope.model.accounts = $scope.model.accounts || []; var accounts = $scope.model.accounts.filter(function (item) { return item.id == account.id }); if (!accounts.length) $scope.model.accounts.push(account); while ($scope.model.accounts.length > 2) $scope.remove(0); _checkSelectedItem(); }; $scope.remove = function (index) { var accounts = $scope.model.accounts; accounts.splice(index, 1); _checkSelectedItem(); if (!accounts.length) $scope.close(); }; $scope.select = function (selectedIndex) { var accounts = $scope.model.accounts; for (var index = 0; index < accounts.length; index++) $scope.model.accounts[index].isActive = index == selectedIndex; }; $scope.selectEmail = function (selectedIndex) { var accounts = $scope.model.accounts; for (var index = 0; index < accounts.length; index++) $scope.model.accounts[index].isActiveEmail = index == selectedIndex; }; $scope.cancel = function () { $scope.close(); }; $scope.submit = function (form) { $form.submit($scope, form, function (form) { var accounts = $scope.model.accounts; var activeAccounts = accounts.filter(function (item) { return item.isActive; }); var activeEmailAccounts = accounts.filter(function (item) { return item.isActiveEmail; }); var notActiveAccounts = accounts.filter(function (item) { return !item.isActive; }); $api.account.merge(activeAccounts[0].id, notActiveAccounts[0].id, activeEmailAccounts[0].id) .then(function (json) { $notify.info("Customer's has been merged."); if ($scope.model.openCustomerInfoAfterMerge) { var url = '/account/?id=' + activeAccounts[0].id; $timeout(function () { window.open(url, '_self', ''); }, 1500); return; } $rootScope.$broadcast('event:accountMergeComplete', {}); }).finally(function () { $scope.isBusy = false; }); }); }; $scope.close = function () { $scope.isVisible = false; $scope.model.accounts = null; }; $rootScope.$on('event:accountMerge', function (event, json) { !$scope.isBusy && $scope.add(json); }); $rootScope.$on('event:accountMergeComplete', function (event, json) { $scope.close(); }); }; })();<file_sep>/Shared/SaaS.Api.Models/Products/AccountProductModuleModel.cs using Newtonsoft.Json; namespace SaaS.Api.Models.Products { public class AccountProductModuleModel { public int? Allowed { get; set; } public int? Used { get; set; } [JsonProperty("name")] public string Module { get; set; } } } <file_sep>/Shared/SaaS.Api.Models/Oauth/SignInViewModel.cs using Newtonsoft.Json; using SaaS.Data.Entities.Accounts; using System; namespace SaaS.Api.Models.Oauth { public class SignInViewModel { public SignInViewModel() { } public SignInViewModel(Account user, string grantType = "password", string clientId = "web") { GrantType = grantType; ClientId = clientId; SetUser(user); } [JsonProperty("grant_type")] public string GrantType { get; set; } public string UserName { get; set; } public string Password { get; set; } [JsonProperty("client_id")] public string ClientId { get; set; } [JsonProperty("client_version")] public string ClientVersion { get; set; } [JsonProperty("client_secret")] public string ClientSecret { get; set; } public Guid State { get; set; } public string Scope { get; set; } public Guid? InstallationID { get; set; } public void SetUser(Account user) { UserName = user.Email; Password = <PASSWORD>; } public string MotherboardKey { get; set; } public string PhysicalMac { get; set; } public string MachineKey { get; set; } public string PcName { get; set; } public bool IsAutogeneratedMachineKey { get; set; } public string ExternalClient { get; set; } } } <file_sep>/Shared/SaaS.Api.Models/Products/UpgradeProductViewModel.cs using Newtonsoft.Json; namespace SaaS.Api.Models.Products { public class UpgradeProductViewModel { public string OwnerEmail { get; set; } [JsonProperty("UnitName")] public string ProductUnitName { get; set; } [JsonProperty("Currency")] public string CurrencyISO { get; set; } public decimal Price { get; set; } public decimal PriceUsd { get; set; } public string SpId { get; set; } public int Quantity { get; set; } public int TimeStamp { get; set; } public ulong Status { get; set; } } }<file_sep>/Web.Api/SaaS.Zendesk/src/js/controllers/account/not-found.js angular.module('app.controllers') .controller('accountNotFoundController', ['$scope', '$state', '$brand', ($scope, $state, $brand) => { $scope.model = { email: $state.params.email, logo: $brand.get().logo.contentUrl }; }]);<file_sep>/WinService/SaaS.WinService.Mailer/Program.cs using System; using System.ServiceProcess; using System.Threading; namespace SaaS.WinService.Mailer { static class Program { static void Main() { if (!Environment.UserInteractive) { var servicesToRun = new ServiceBase[] { new MailerService() }; ServiceBase.Run(servicesToRun); } else { MailerService mailerService = new MailerService(); mailerService.StartUserInteractive(); Thread.Sleep(Timeout.Infinite); } } } } <file_sep>/Shared/SaaS.Identity.Admin/UserStore.cs using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Security.Claims; using System.Threading.Tasks; namespace SaaS.Identity.Admin { public class UserStore<TUser> : IUserStore<TUser, Guid>, IUserEmailStore<TUser, Guid>, IUserPasswordStore<TUser, Guid>, IUserClaimStore<TUser, Guid> where TUser : User { private readonly AuthDbContext _context; public UserStore(AuthDbContext context) { _context = context; } public async Task CreateAsync(TUser user) { if (object.Equals(user, null)) throw new ArgumentNullException("user"); try { _context.Users.Add(user); await _context.SaveChangesAsync(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } catch { throw; } } public Task DeleteAsync(TUser user) { throw new NotImplementedException(); } public async Task<TUser> FindByIdAsync(Guid id) { return (TUser)(await _context.UserGetAsync(id)); } public async Task<TUser> FindByEmailAsync(string email) { return (TUser)(await _context.UserGetAsync(email)); } public Task<TUser> FindByEmailAsync(string email, string password) { throw new NotImplementedException(); } public async Task<TUser> FindByNameAsync(string userName) { return (TUser)(await _context.UserGetAsync(userName)); } public async Task UpdateAsync(TUser user) { if (user == null) { throw new ArgumentNullException("user"); } try { _context.Users.AddOrUpdate(user); await _context.SaveChangesAsync(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } catch (Exception) { throw; } } public void Dispose() { _context.Dispose(); } public Task<string> GetPasswordHashAsync(TUser user) { return Task.FromResult<string>(user.Password); } public Task<bool> HasPasswordAsync(TUser user) { throw new NotImplementedException(); } public Task SetPasswordHashAsync(TUser user, string passwordHash) { if (user == null) throw new ArgumentNullException("user"); user.Password = <PASSWORD>; return Task.FromResult<object>(null); } public Task<string> GetEmailAsync(TUser user) { throw new NotImplementedException(); } public Task<bool> GetEmailConfirmedAsync(TUser user) { throw new NotImplementedException(); } public Task SetEmailAsync(TUser user, string email) { throw new NotImplementedException(); } public Task SetEmailConfirmedAsync(TUser user, bool confirmed) { return Task.FromResult<object>(null); } public Task AddClaimAsync(TUser user, Claim claim) { throw new NotImplementedException(); } public Task<IList<Claim>> GetClaimsAsync(TUser user) { throw new NotImplementedException(); } public Task RemoveClaimAsync(TUser user, System.Security.Claims.Claim claim) { throw new NotImplementedException(); } } } <file_sep>/Test/SaaS.Api.Test/Models/Api/Oauth/AuthViewModel.cs  namespace SaaS.Api.Test.Models.Api.Oauth { public class AuthViewModel { public string Email { get; set; } } }<file_sep>/Web.Api/SaaS.Sso/src/js/directives/focus.js angular.module('app.directives') .directive('ngFocus', ['$window', ($window) => { return { restrict: 'A', link: (scope, element, attrs) => { element.first().focus(); } }; }]);<file_sep>/Shared/SaaS.Api.Models/Products/ProductViewModel.cs using Newtonsoft.Json; using System; using System.Collections.Generic; namespace SaaS.Api.Models.Products { public class ProductViewModel { [JsonProperty("id")] public Guid AccountProductId { get; set; } public string SpId { get; set; } [JsonProperty("name")] public string ProductName { get; set; } [JsonProperty("unitName")] public string ProductUnitName { get; set; } public string Plan { get; set; } public DateTime PurchaseDate { get; set; } public DateTime? EndDate { get; set; } public DateTime? NextRebillDate { get; set; } public DateTime? CreditCardExpiryDate { get; set; } public ulong Status { get; set; } public List<AccountProductModuleModel> Modules { get; set; } public ushort? Order { get; set; } } } <file_sep>/Web.Api/SaaS.Zendesk/src/js/controllers/account/products.js (() => { angular.module('app.controllers') .controller('accountProductsController', ['$scope', '$state', '$api', ($scope, $state, $api) => { $scope.$api = $api; $scope.isLoading = true; $scope.model = { accountId: $state.params.accountId, products: null }; $api.account.getOwnerProducts({ accountId: $scope.model.accountId }).then((json) => { $scope.model.products = viewProductBuilder.build(json, $api); }); }]); var viewProduct = function (json, $api) { Object.defineProperties(this, { id: { value: json.id, writable: false }, name: { value: json.name, writable: false }, unitName: { value: json.unitName, writable: false }, plan: { value: json.plan, writable: false }, allowed: { value: json.allowed, writable: false }, purchaseDate: { value: json.purchaseDate, writable: false }, status: { value: json.status, writable: false } }); this.$api = $api; }; viewProduct.prototype.getTableCssClass = function () { var $api = this.$api; if ($api.product.isDisabled(this)) return 'table-danger'; if ($api.product.isFree(this) || $api.product.isTrial(this)) return 'table-primary'; return ''; }; var viewProductBuilder = () => { }; viewProductBuilder.build = (json, $api) => { const products = []; for (let index = 0; index < json.length; index++) products.push(new viewProduct(json[index], $api)); return products; }; })(); <file_sep>/Web.Api/SaaS.Zendesk/gulpfile.js const gulp = require('gulp'); require('fs').readdirSync('./tasks/').forEach(function (task) { require('./tasks/' + task); }); gulp.task('app', gulp.series('app.clean', gulp.parallel('app.html', 'app.css', 'app.js', 'app.font'))); gulp.task('zat', gulp.series('zat.clean', gulp.parallel('zat.html', 'zat.css', 'zat.js', 'zat.font', 'zat.images'))); // gulp.task('qa', gulp.series('release')); gulp.task('build', gulp.series('app', 'zat')); gulp.task('package', gulp.series('build', 'zat.package')); gulp.task('default', gulp.series('build', gulp.parallel('app.watch', 'zat.watch', 'zat.server'))); // nfotenyuk 28.03.2019 // to start in Windows gulp.task('build.windows', gulp.series('app')); gulp.task('start.windows', gulp.series('build.windows', gulp.parallel('app.watch'))); /*gulp.task('package.windows', gulp.series('build.windows'));*/ // to start in UBUNTU gulp.task('start.ubuntu', gulp.series('zat', gulp.parallel('zat.watch', 'zat.server'))); //run this task in bash (UBUNTU)<file_sep>/Shared/SaaS.Api.Client/SaaSApiOauthService.cs using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace SaaS.Api.Client { public partial class SaaSApiOauthService : ISaaSApiOauthService { private readonly Uri _uri; private readonly string _clientId; private readonly string _clientSecret; public SaaSApiOauthService(string uri = "https://oauth.sodapdf.com", string clientId = "web", string clientSecret = "") { _uri = new Uri(uri); _clientId = clientId; _clientSecret = clientSecret; } private HttpClient CreateHttpClient() { var client = new HttpClient(); client.BaseAddress = _uri; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return client; } public string AbsolutePath { get { return _uri.AbsoluteUri; } } } public interface ISaaSApiOauthService { string AbsolutePath { get; } Task<SignInModel> SignInAsync(string userName, string password); Task<SignInModel> SignInAsync(string token); Task<RefreshTokenModel> RefreshTokenAsync(string token); } } <file_sep>/Web.Api/SaaS.Api.Sign/Controllers/Api/Silanis/UsersController.cs using SaaS.Api.Core.Filters; using System.Net.Http; using System.Web.Http; namespace SaaS.Api.Sign.Controllers.Api.Silanis { [RoutePrefix("api/users"), SaaSAuthorize] public class UsersController : BaseApiController { protected override string ApiRoot { get { return "api/users/"; } } [Route("{*url}"), HttpGet, HttpPost, HttpPut, HttpDelete] public HttpResponseMessage Index() { return HttpProxy(Request, Request.RequestUri.LocalPath); } [Route, HttpGet] public HttpResponseMessage Users() { return HttpProxy(Request, Format()); } } } <file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.Client.cs using SaaS.Data.Entities.Oauth; using System.Collections.Generic; using System.Data.SqlClient; namespace SaaS.Identity { public partial class AuthDbContext { internal List<Client> ClientsGet() { return ExecuteReaderCollection<Client>("[oauth].[pClient]", new SqlParameter[] { }); } } }<file_sep>/Shared/SaaS.Api.Client/SaaSApiPrinciple.cs using System.Security.Claims; namespace SaaS.Api.Client { public class SaaSApiPrinciple : ClaimsPrincipal { public SaaSApiPrinciple(SaaSApiIdentity identity) : base(identity) { } public SaaSApiPrinciple(ClaimsPrincipal claimsPrincipal) : base(claimsPrincipal) { } } } <file_sep>/Shared/SaaS.Identity.Admin/AuthDbContext.Sql/AuthDbContext.Sql.cs using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SaaS.Identity.Admin { public partial class AuthDbContext { internal async Task<T> ExecuteReaderAsync<T>(string commandText, SqlParameter[] sqlParams) { try { using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = sqlParams.CommandText(commandText); cmd.Parameters.AddRange(sqlParams); await Database.Connection.OpenAsync(); var reader = await cmd.ExecuteReaderAsync(); var entity = ((IObjectContextAdapter)this).ObjectContext.Translate<T>(reader).FirstOrDefault(); Database.Connection.Close(); return entity; } } catch (Exception exc ) { throw exc; } } internal async Task<List<T>> ExecuteReaderCollectionAsync<T>(string commandText, SqlParameter[] sqlParams) { using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = sqlParams.CommandText(commandText); cmd.Parameters.AddRange(sqlParams); await Database.Connection.OpenAsync(); var reader = await cmd.ExecuteReaderAsync(); var list = ((IObjectContextAdapter)this).ObjectContext.Translate<T>(reader).ToList(); Database.Connection.Close(); return list; } } internal async Task<int> ExecuteNonQueryAsync(string commandText, SqlParameter[] sqlParams) { using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = sqlParams.CommandText(commandText); cmd.Parameters.AddRange(sqlParams); await Database.Connection.OpenAsync(); var reader = await cmd.ExecuteNonQueryAsync(); Database.Connection.Close(); cmd.Parameters.Clear(); return reader; } } internal async Task<String> ExecuteNonQueryOutParamAsync(string commandText, string email) { using (var cmd = Database.Connection.CreateCommand()) { cmd.CommandText = commandText; cmd.CommandType = CommandType.StoredProcedure; IDbDataParameter sourceId = cmd.CreateParameter(); IDbDataParameter typeId = cmd.CreateParameter(); IDbDataParameter userEmail = cmd.CreateParameter(); IDbDataParameter processId = cmd.CreateParameter(); sourceId.ParameterName = "@sourceID"; sourceId.Value = 1; cmd.Parameters.Add(sourceId); typeId.ParameterName = "@typeID"; typeId.Value = 6; cmd.Parameters.Add(typeId); userEmail.ParameterName = "@userEmail"; userEmail.Value = email; cmd.Parameters.Add(userEmail); //OUT param processId.ParameterName = "@processID"; processId.Direction = ParameterDirection.Output; processId.DbType = DbType.String; processId.Size = 50; cmd.Parameters.Add(processId); await Database.Connection.OpenAsync(); await cmd.ExecuteNonQueryAsync(); Database.Connection.Close(); return cmd.Parameters["@processID"].Value.ToString(); } } } internal static class SqlHelper { internal static SqlParameter ToSql(this object value, string key) { return object.Equals(value, null) ? new SqlParameter(key, DBNull.Value) : new SqlParameter(key, value); } internal static string CommandText(this SqlParameter[] sqlParams, string commandText) { StringBuilder builder = new StringBuilder(commandText); if (!object.Equals(sqlParams, null) && sqlParams.Length > 0) { foreach (var item in sqlParams) builder.AppendFormat(" @{0}=@{0},", item.ParameterName); builder.Length--; } return builder.ToString(); } } }<file_sep>/Shared/SaaS.Identity/AuthProductRepository/IAuthProductRepository.cs using SaaS.Data.Entities; using SaaS.Data.Entities.View; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Identity { public interface IAuthProductRepository : IDisposable { Task<AssignStatus> ProductAssignAsync(AccountProductPair pair, bool isIgnoreBillingCycle = false); Task<ViewUnassignProduct> ProductUnassignAsync(AccountProductPair pair); Task<AllowedCountStatus> ProductAllowedSetAsync(AccountProductPair pair, int allowedCount); Task ProductDeactivateAsync(AccountProductPair pair); Task ProductNextRebillDateSetAsync(AccountProductPair pair, DateTime? nextRebillDate); Task ProductEndDateSetAsync(AccountProductPair pair, DateTime endDate); Task ProductIsNewAsync(AccountProductPair pair, bool isNew); Task<ViewUpgradeProduct> UpgradeProductGetAsync(Guid accountProductId); Task<List<ViewAccountProduct>> AccountProductsGetAsync(Guid accountId, Guid? systemId = null); Task<List<ViewAccountMicrotransaction>> AccountMicrotransactionsGetAsync(Guid accountId); Task<List<ViewUpclickProduct>> UpclickProductsGetAsync(); Task<ViewOwnerProduct> OwnerProductGetAsync(AccountProductPair pair); Task<ViewOwnerProduct> OwnerProductDetailsGetAsync(AccountProductPair pair); Task<List<ViewOwnerProduct>> OwnerProductsGetAsync(Guid accountId); Task OwnerProductInsertAsync(Guid accountId, string productUid, string currency, decimal price, decimal priceUsd, int quantity); } }<file_sep>/Shared/SaaS.Api.Models/Products/ProductComparer.cs using SaaS.Data.Entities.View; using System.Collections.Generic; namespace SaaS.Api.Models.Products { public static class ProductComparer { public static int Comparer(ViewAccountProduct p1, ViewAccountProduct p2) { if (object.Equals(p1, null) && object.Equals(p2, null)) return 0; if (object.Equals(p1, null)) return -1; if (object.Equals(p2, null)) return 1; if (p1.IsDisabled && p2.IsDisabled) return ProductEndDateComparer(p1, p2); if (p1.IsDisabled) return -1; if (p2.IsDisabled) return 1; if (!p1.IsActive && p2.IsActive) return -1; if (p1.IsActive && !p2.IsActive) return 1; if (p1.IsPPC && p2.IsPPC) return ProductEndDateComparer(p1, p2); if (p1.IsPPC && !p2.IsPPC) return -1; if (!p1.IsPPC && p2.IsPPC) return 1; if (p1.IsMinor && p2.IsMinor) return ProductEndDateComparer(p1, p2); if (p1.IsMinor && !p2.IsMinor) return -1; if (!p1.IsMinor && p2.IsMinor) return 1; var count1 = object.Equals(p1.Modules, null) ? 0 : p1.Modules.Count; var count2 = object.Equals(p2.Modules, null) ? 0 : p2.Modules.Count; if (count1 == count2) return ProductEndDateComparer(p1, p2); return count1.CompareTo(count2); } public static int OrderComparer(ViewAccountProduct p1, ViewAccountProduct p2) { if (object.Equals(p1, null) && object.Equals(p2, null)) return 0; if (object.Equals(p1, null)) return -1; if (object.Equals(p2, null)) return 1; if (p1.IsDisabled && p2.IsDisabled) return ProductEndDateComparer(p1, p2); if (p1.IsDisabled) return -1; if (p2.IsDisabled) return 1; if (!p1.IsActive && p2.IsActive) return -1; if (p1.IsActive && !p2.IsActive) return 1; if ((p1.IsRenewal && !p1.NextRebillDate.HasValue) && (p2.IsRenewal && !p2.NextRebillDate.HasValue)) return ProductEndDateComparer(p1, p2); if ((p1.IsRenewal && !p1.NextRebillDate.HasValue) && !(p2.IsRenewal && !p2.NextRebillDate.HasValue)) return 1; if (!(p1.IsRenewal && !p1.NextRebillDate.HasValue) && (p2.IsRenewal && !p2.NextRebillDate.HasValue)) return -1; if (p1.IsMinor && p2.IsMinor) return ProductEndDateComparer(p1, p2); if (p1.IsMinor && !p2.IsMinor) return -1; if (!p1.IsMinor && p2.IsMinor) return 1; if (p1.IsPPC && !p2.IsPPC) return -1; if (!p1.IsPPC && p2.IsPPC) return 1; var count1 = object.Equals(p1.Modules, null) ? 0 : p1.Modules.Count; var count2 = object.Equals(p2.Modules, null) ? 0 : p2.Modules.Count; if (count1 == count2) return ProductEndDateComparer(p1, p2); return count1.CompareTo(count2); } public static void ProductOrderer(IEnumerable<ViewAccountProduct> products) { var source = new List<ViewAccountProduct>(products); source.Sort(OrderComparer); source.Reverse(); ushort order = 0; source.ForEach(e => { e.Order = order++; }); } public static int ProductEndDateComparer(ViewAccountProduct p1, ViewAccountProduct p2) { if (p1.EndDate.HasValue && p2.EndDate.HasValue) return p1.EndDate.Value.CompareTo(p2.EndDate.Value) * -1; return 0; } } } <file_sep>/Shared/SaaS.Data.Entities/View/Oauth/ViewSessionTokenExternalHistory.cs using System; namespace SaaS.Data.Entities.View.Oauth { public class ViewSessionTokenExternalHistory : Entity<Guid> { public string ExternalClientName { get; set; } public string ExternalAccountId { get; set; } public string Email { get; set; } public bool IsUnlinked { get; set; } public DateTime CreateDate { get; set; } public DateTime ModifyDate { get; set; } } }<file_sep>/Shared/SaaS.Data.Entities/Accounts/AccountPreference.cs using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Data.Entities.Accounts { public class AccountPreference : AccountEntity<int> { [Column("json")] public string Json { get; set; } } }<file_sep>/Shared/SaaS.Data.Entities.Admin/View/Oauth/ViewUser.cs using System; namespace SaaS.Data.Entities.Admin.View.Oauth { public class ViewUser : Entity<Guid> { public string Login { get; set; } public string Password { get; set; } public bool IsActive { get; set; } public string Role { get; set; } } }<file_sep>/Web.Api/SaaS.Zendesk/tasks/app.js.js const fn = require('gulp-fn'); const del = require('del'); const gulp = require('gulp'); const path = require('path'); const babel = require('gulp-babel'); const minify = require('gulp-minify'); const concat = require('gulp-concat'); gulp.task('app.js:app', () => { return gulp.src('src/js/**/*.js') .pipe(concat('app.min.js')) .pipe(babel({ presets: ['@babel/env'] })) // .pipe(minify({ // ext: { // src: '.js', // min: '.min.js' // }, // mangle: false, // ignoreFiles: ['.min.js'] // })) .pipe(gulp.dest('dist/js')) .pipe(fn(function (file) { if (path.basename(file.path) === 'app.js') del(file.path); })); }); gulp.task('app.js:vendor', () => { return gulp.src([ 'node_modules/jquery/dist/jquery.slim.min.js', 'node_modules/angular/angular.min.js', 'node_modules/angular-ui-router/release/angular-ui-router.min.js', 'node_modules/bootstrap/dist/js/bootstrap.bundle.min.js' ]) .pipe(concat('vendor.min.js')) .pipe(gulp.dest('dist/js')) }); gulp.task('app.js:watch', () => { return gulp.watch('src/js/**/*.js', gulp.series('app.js:app')); }); gulp.task('app.js', gulp.parallel('app.js:app', 'app.js:vendor'));<file_sep>/Web.Api/SaaS.UI.Admin/Oauth/OauthBearerProvider.cs using Microsoft.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Infrastructure; using Microsoft.Owin.Security.OAuth; using SaaS.Api.Client; using System; using System.Threading.Tasks; using System.Web; namespace SaaS.UI.Admin.Oauth { public class OauthBearerProvider : IOAuthBearerAuthenticationProvider { private ISaaSApiOauthService _oauthService; private static readonly CookieOptions _cookieOptions = new CookieOptions { Expires = DateTime.Now.AddYears(10) }; public OauthBearerProvider(ISaaSApiOauthService oauthService) { _oauthService = oauthService; } public Task ApplyChallenge(OAuthChallengeContext context) { context.Response.Redirect("/user/login"); return Task.FromResult<object>(null); } public async Task RequestToken(OAuthRequestTokenContext context) { string requestAccessToken = HttpContext.Current.Request.QueryString["access_token"]; string requestRefreshToken = HttpContext.Current.Request.QueryString["refresh_token"]; string cookieAccessToken = context.Request.Cookies["access_token"]; string cookieRefreshToken = context.Request.Cookies["refresh_token"]; AuthenticationTicket requestTicket = GetTicket(context, requestAccessToken); AuthenticationTicket cookieTicket = GetTicket(context, cookieAccessToken); if (!object.Equals(requestTicket, null) && !IsExpired(requestTicket)) { if (object.Equals(cookieTicket, null) || !string.Equals(requestTicket.Identity.Name, cookieTicket.Identity.Name, StringComparison.InvariantCultureIgnoreCase)) { if (await SignIn(context, requestAccessToken) == SignInStatus.Ok) return; } } Guid refreshToken; if (Guid.TryParse(requestRefreshToken, out refreshToken)) { if (await SignIn(context, requestRefreshToken) == SignInStatus.Ok) return; } if (object.Equals(cookieTicket, null)) return; context.Token = cookieAccessToken; if (IsExpired(cookieTicket)) await RefreshToken(context, cookieRefreshToken); } private AuthenticationTicket GetTicket(OAuthRequestTokenContext context, string accessToken) { if (string.IsNullOrEmpty(accessToken)) return null; var tokenContext = new OAuthRequestTokenContext(context.OwinContext, accessToken); var tokenReceiveContext = new AuthenticationTokenReceiveContext(context.OwinContext, Startup.AuthenticationOptions.AccessTokenFormat, tokenContext.Token); tokenReceiveContext.DeserializeTicket(tokenReceiveContext.Token); return tokenReceiveContext.Ticket; } private bool IsExpired(AuthenticationTicket ticket) { if (object.Equals(ticket, null)) return true; return ticket.Properties.ExpiresUtc.HasValue && ticket.Properties.ExpiresUtc.Value < Startup.AuthenticationOptions.SystemClock.UtcNow; } private async Task RefreshToken(OAuthRequestTokenContext context, string refreshToken) { try { var model = await _oauthService.RefreshTokenAsync(refreshToken); if (model.Status == RefreshTokenStatus.Ok) UpdateToken(context, model.Token); else RemoveToken(context); } catch { RemoveToken(context); } } private async Task<SignInStatus> SignIn(OAuthRequestTokenContext context, string token) { try { var model = await _oauthService.SignInAsync(token); if (model.Status == SignInStatus.Ok) UpdateToken(context, model.Token); return model.Status; } catch { return SignInStatus.InvalidGrant; } } internal static void UpdateToken(OAuthRequestTokenContext context, SaaSApiToken token) { context.Response.Cookies.Append("access_token", token.AccessToken, _cookieOptions); context.Response.Cookies.Append("refresh_token", token.RefreshToken, _cookieOptions); context.Response.Cookies.Append("oauth_fullName", string.Format("{0} {1}", token.FirstName, token.LastName), _cookieOptions); context.Token = token.AccessToken; } private void RemoveToken(OAuthRequestTokenContext context) { context.Response.Cookies.Delete("access_token"); context.Response.Cookies.Delete("refresh_token"); context.Response.Cookies.Delete("oauth_fullName"); context.Token = null; } public Task ValidateIdentity(OAuthValidateIdentityContext context) { return Task.FromResult<object>(null); } } }<file_sep>/Web.Api/SaaS.Zendesk/readme.txt 1) npm i --save-dev 2) gulp (to start) 3) https://avanquest.zendesk.com/agent/tickets/ 4) Open any ticket (related to sodapdf or pdf architect) and add to quesry string ?zat=true !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! https://develop.zendesk.com/hc/en-us/articles/360001075048-Installing-and-using-the-Zendesk-apps-tools !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! https://developer.zendesk.com/apps/docs/developer-guide/zat https://avanquest.zendesk.com/agent/admin/overview https://developer.zendesk.com/apps/docs/developer-guide/using_sdk https://develop.zendesk.com/hc/en-us/articles/360001069027<file_sep>/Test/SaaS.Api.Test/Models/Api/Oauth/AccountProductResultModel.cs using System; namespace SaaS.Api.Test.Models.Api.Oauth { public class AccountProductResultModel { public Guid Id { get; set; } public string Name { get; set; } } } <file_sep>/Web.Api/SaaS.Api/Oauth/Providers/SaaSAuthorizationServerProvider.GrantRefreshToken.cs using Microsoft.AspNet.Identity; using Microsoft.Owin.Security; using Microsoft.Owin.Security.OAuth; using SaaS.Data.Entities.Oauth; using SaaS.Identity; using System; using System.Security.Claims; using System.Threading.Tasks; namespace SaaS.Api.Oauth.Providers { public partial class SaaSAuthorizationServerProvider { public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context) { var identity = new ClaimsIdentity(context.Ticket.Identity); var properties = context.Ticket.Properties.Dictionary; var client = context.OwinContext.Get<Client>("client"); var sessionToken = context.OwinContext.Get<SessionToken>("sessionToken"); properties["session"] = Guid.NewGuid().ToString("N"); if (!string.IsNullOrEmpty(sessionToken.ExternalClientName)) properties["externalClient"] = sessionToken.ExternalClientName; string[] scope = context.OwinContext.Get<string[]>("scope"); var accountId = Guid.Parse(identity.GetUserId()); using (var auth = new AuthRepository()) { using (var authProduct = new AuthProductRepository()) { var account = await auth.AccountGetAsync(accountId); if (object.Equals(account, null)) return; context.OwinContext.Set("user", account); identity.TryRemoveClaim("module"); identity.AddClaims(account, client); var scopeWorker = SaaSScopeWorkerFactory.Create(scope, context, auth, authProduct); await scopeWorker.GrantClaims(identity); } } context.Validated(new AuthenticationTicket(identity, context.Ticket.Properties)); } } }<file_sep>/Web.Api/SaaS.Api.Admin/Controllers/Api/UserController.cs using SaaS.Api.Admin.Models.Oauth; using SaaS.Data.Entities.Admin.Oauth; using SaaS.Data.Entities.Admin.View.Oauth; using SaaS.Identity.Admin; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Admin.Controllers.Api { [RoutePrefix("api/user"), Authorize] public class UserController : SaaSApiController { [HttpGet, Authorize(Roles = "admin")] public async Task<IHttpActionResult> Index() { try { return Ok(await _authAdmin.ViewUsersGetAsync()); } catch (Exception exc) { return ErrorContent(exc); } } [HttpPost, Route("insert"), Authorize(Roles = "admin")] public async Task<IHttpActionResult> Insert(ViewUser model) { try { var user = await _authAdmin.UserGetAsync(model.Login); if (!object.Equals(user, null)) return UserExists(); await _authAdmin.ViewUserInsertAsync(model); var log = string.Format("User '{0}'({1}) has been created.", model.Login, model.Role); await LogInsertAsync(log, LogActionTypeEnum.UserCreate); return Ok(); } catch (Exception exc) { return ErrorContent(exc); } } [HttpPost, Route("update"), Authorize(Roles = "admin")] public async Task<IHttpActionResult> Update(ViewUser model) { try { var user = await _authAdmin.UserGetAsync(model.Id); if (object.Equals(user, null)) return UserNotFound(); var loginUser = await _authAdmin.UserGetAsync(model.Login); if (!object.Equals(loginUser, null) && loginUser.Id != user.Id) return UserExists(); await _authAdmin.ViewUserSetAsync(model); var log = string.Format("User '{0}'({1}) has been updated.", model.Login, model.Role); await LogInsertAsync(log, LogActionTypeEnum.UserEdit); return Ok(); } catch (Exception exc) { return ErrorContent(exc); } } private async Task<IHttpActionResult> UserSetActive(Guid userId, bool isActive) { try { var user = await _authAdmin.ViewUserGetAsync(userId); if (object.Equals(user, null)) return UserNotFound(); await _authAdmin.UserSetActiveAsync(userId, isActive); var log = string.Format("User '{0}'({1}) has been {2}.", user.Login, user.Role, isActive ? "activated" : "deactivated"); await LogInsertAsync(log, isActive ? LogActionTypeEnum.UserActivate : LogActionTypeEnum.UserDeactivate); return Ok(await _authAdmin.ViewUserGetAsync(userId)); } catch (Exception exc) { return ErrorContent(exc); } } [HttpPost, Route("{userId:guid}/activate"), Authorize(Roles = "admin")] public async Task<IHttpActionResult> Activate(Guid userId) { return await UserSetActive(userId, true); } [HttpPost, Route("{userId:guid}/deactivate"), Authorize(Roles = "admin")] public async Task<IHttpActionResult> Deactivate(Guid userId) { return await UserSetActive(userId, false); } [HttpPost, Route("change-password")] public async Task<IHttpActionResult> ChangePassword(ChangePasswordViewModel model) { return await CurrentUserExecuteAsync(async delegate (User user) { var result = await _authAdmin.UserChangePasswordAsync(user.Id, model.OldPassword, model.NewPassword); IHttpActionResult errorResult = GetErrorResult(result); if (!object.Equals(errorResult, null)) return errorResult; var log = string.Format("User '{0}' has updated his password. ", user.Login); await LogInsertAsync(log, LogActionTypeEnum.UserEditPassword); return Ok(); }); } } } <file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.Email.cs using SaaS.Data.Entities; using SaaS.Data.Entities.Accounts; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthDbContext { internal async Task EmailInsertAsync(Guid accountId, Status status, string emailCustomParam, string modelCustomParam) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId"), status.ToSql("status"), emailCustomParam.ToSql("emailCustomParam"), modelCustomParam.ToSql("modelCustomParam") }; await ExecuteNonQueryAsync("[accounts].[pEmailInsert]", sqlParams); } internal async Task<List<Email>> EmailsGetAsync(Status status, int top) { var sqlParams = new SqlParameter[] { status.ToSql("status"), top.ToSql("top") }; return await ExecuteReaderCollectionAsync<Email>("[accounts].[pEmailGetByStatusId]", sqlParams); } internal async Task EmailStatusSetAsync(int id, Status status) { var sqlParams = new SqlParameter[] { id.ToSql("id"), status.ToSql("status") }; await ExecuteNonQueryAsync("[accounts].[pEmailSetStatusById]", sqlParams); } } }<file_sep>/Shared/SaaS.Identity/AccountStore.cs using Microsoft.AspNet.Identity; using SaaS.Data.Entities.Accounts; using System; using System.Collections.Generic; using System.Data.Entity.Migrations; using System.Security.Claims; using System.Threading.Tasks; namespace SaaS.Identity { internal class AccountStore<TUser> : IUserStore<TUser, Guid>, IUserEmailStore<TUser, Guid>, IUserPasswordStore<TUser, Guid>, IUserClaimStore<TUser, Guid> where TUser : Account { private readonly AuthDbContext _context; internal AccountStore(AuthDbContext context) { _context = context; } public async Task CreateAsync(TUser user) { if (object.Equals(user,null)) throw new ArgumentNullException("user"); _context.Accounts.Add(user); await _context.SaveChangesAsync(); } public async Task DeleteAsync(TUser user) { await _context.AccountDeleteAsync(user.Id); } public async Task<TUser> FindByIdAsync(Guid userId) { return (TUser)(await _context.AccountGetAsync(userId)); } public async Task<TUser> FindByEmailAsync(string primaryEmail) { var user = await _context.AccountGetAsync(primaryEmail, false); return (TUser)user; } public async Task<TUser> FindByEmailAsync(string primaryEmail, string password) { var user = await _context.AccountGetAsync(primaryEmail, password); return (TUser)user; } public Task<TUser> FindByNameAsync(string userName) { throw new NotImplementedException(); } public async Task UpdateAsync(TUser user) { if (user == null) throw new ArgumentNullException("user"); _context.Accounts.AddOrUpdate(user); await _context.SaveChangesAsync(); } public void Dispose() { _context.Dispose(); } public Task<string> GetPasswordHashAsync(TUser user) { return Task.FromResult<string>(user.Password); } public Task<bool> HasPasswordAsync(TUser user) { throw new NotImplementedException(); } public Task SetPasswordHashAsync(TUser user, string passwordHash) { if (user == null) throw new ArgumentNullException("user"); user.Password = <PASSWORD>; return Task.FromResult<object>(null); } public Task<string> GetEmailAsync(TUser user) { throw new NotImplementedException(); } public Task<bool> GetEmailConfirmedAsync(TUser user) { throw new NotImplementedException(); } public Task SetEmailAsync(TUser user, string email) { throw new NotImplementedException(); } public Task SetEmailConfirmedAsync(TUser user, bool confirmed) { return Task.FromResult<object>(null); } public Task AddClaimAsync(TUser user, Claim claim) { throw new NotImplementedException(); } public Task<IList<Claim>> GetClaimsAsync(TUser user) { throw new NotImplementedException(); } public Task RemoveClaimAsync(TUser user, System.Security.Claims.Claim claim) { throw new NotImplementedException(); } } } <file_sep>/Shared/SaaS.Mailer/Html.cs using RazorEngine.Text; namespace SaaS.Mailer { public static class Html { public static RawString Raw(string value) { return new RawString(value); } } } <file_sep>/Web.Api/SaaS.Zendesk/tasks/zat.clean.js const del = require('del'); const gulp = require('gulp'); gulp.task('zat.clean', () => { return del(['zat/assets']); });<file_sep>/Web.Api/SaaS.Api.Admin/Oauth/Providers/ClaimsIdentityHelper.cs using SaaS.Data.Entities.Admin.View; using SaaS.Data.Entities.Admin.View.Oauth; using System.Linq; using System.Security.Claims; namespace SaaS.Api.Admin.Oauth.Providers { public static class ClaimsIdentityHelper { public static void TryRemoveClaim(this ClaimsIdentity identity, string type) { var claims = identity.FindAll(type).ToArray(); foreach (var claim in claims) identity.TryRemoveClaim(claim); } public static void AddClaims(this ClaimsIdentity identity, ViewUser user) { identity.TryRemoveClaim(ClaimTypes.Name); identity.TryRemoveClaim(ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.Name, user.Login)); identity.AddClaim(new Claim(ClaimTypes.Role, user.Role)); } } }<file_sep>/Shared/SaaS.Mailer/SendEmailAction.cs using System; using System.Collections.Generic; using System.Xml.Serialization; namespace SaaS.Mailer { [XmlType(AnonymousType = true)] [XmlRoot("xml")] public class SendEmailAction { [XmlArray("to")] [XmlArrayItem("email")] public List<XmlEmail> EmailToList { get; set; } [XmlAttribute("templateId")] public EmailTemplate TemplateId { get; set; } } [XmlType(AnonymousType = true)] public class XmlEmail { [XmlAttribute("email")] public string Email { get; set; } } [XmlType(AnonymousType = true)] [XmlRoot("xml")] public class SendEmailAction2 { [XmlArray("to")] [XmlArrayItem("email")] public List<XmlEmail> EmailToList { get; set; } //[XmlAttribute("templateId")] //public string TemplateId { get; set; } [XmlIgnore] public EmailTemplate EmailTemplateValue { get; set; } [XmlIgnore] public string EmailTemplateDBValue { get; set; } [XmlAttribute("templateId")] public string TemplateId { get { return EmailTemplateValue.ToString(); } set { if (string.IsNullOrEmpty(value) || Enum.IsDefined(typeof(EmailTemplate), value) == false) { EmailTemplateDBValue = value; //EmailTemplateValue = default(EmailTemplate); EmailTemplateValue = EmailTemplate.None; } else { EmailTemplateValue = (EmailTemplate)Enum.Parse(typeof(EmailTemplate), value); } } } } }<file_sep>/Shared/SaaS.Repository.Pattern/UnitOfWork/IUnitOfWorkAsync.cs using SaaS.Repository.Pattern.Repositories; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace SaaS.Repository.Pattern.UnitOfWork { public interface IUnitOfWorkAsync : IUnitOfWork { Task<int> SaveChangesAsync(); Task<int> SaveChangesAsync(CancellationToken cancellationToken); IRepositoryAsync<TEntity> RepositoryAsync<TEntity>() where TEntity : class; int ExecuteSqlCommand(string query, params object[] parameters); Task<List<T>> ExecuteStoredProcedureAsync<T>(string query, params object[] parameters); Task<Tuple<List<T1>, List<T2>>> ExecuteStoredProcedureAsync<T1, T2>(string query, params object[] parameters); } } <file_sep>/Web.Api/SaaS.Api.Sign/Controllers/Api/Silanis/PackagesController.cs using SaaS.Api.Core.Filters; using System; using System.Net.Http; using System.Web.Http; namespace SaaS.Api.Sign.Controllers.Api.Silanis { [RoutePrefix("api/packages"), SaaSAuthorize] public class PackagesController : BaseApiController { protected override string ApiRoot { get { return "api/packages/"; } } [Route("{*url}"), HttpGet, HttpPost, HttpPut, HttpDelete] public HttpResponseMessage Index() { return HttpProxy(Request, Request.RequestUri.LocalPath); } [Route, HttpGet] public HttpResponseMessage Packages() { return HttpProxy(Request, Format()); } [Route, HttpPost] public HttpResponseMessage PostPackages() { return HttpProxy(Request, Format()); } [Route("{packageId:guid}"), HttpGet, HttpPost, HttpPut, HttpDelete] public HttpResponseMessage PackageId(Guid packageId) { return HttpProxy(Request, Format("{0}", packageId)); } [Route("{packageId:guid}/clone"), HttpPost] public HttpResponseMessage PackageIdClone(Guid packageId) { return HttpProxy(Request, Format("{0}/clone", packageId)); } [Route("{packageId:guid}/signingStatus"), HttpGet] public HttpResponseMessage PackageIdSigningStatus(Guid packageId) { return HttpProxy(Request, Format("{0}/signingStatus", packageId)); } [Route("{packageId:guid}/evidence/summary"), HttpGet] public HttpResponseMessage PackageIdEvidenceSummary(Guid packageId) { return HttpProxy(Request, Format("{0}/evidence/summary", packageId)); } #region Documents [Route("{packageId:guid}/documents"), HttpPost, HttpPut] public HttpResponseMessage PackageIdDocuments(Guid packageId) { return HttpProxy(Request, Format("{0}/documents", packageId)); } [Route("{packageId:guid}/documents/zip"), HttpGet] public HttpResponseMessage PackageIdDocumentsZip(Guid packageId) { return HttpProxy(Request, Format("{0}/documents/zip", packageId)); } [Route("{packageId:guid}/documents/{documentId}"), HttpGet, HttpPut, HttpDelete] public HttpResponseMessage PackageIdDocumentsDocumentId(Guid packageId, string documentId) { return HttpProxy(Request, Format("{0}/documents/{1}", packageId, documentId)); } [Route("{packageId:guid}/documents/{documentId}/pdf"), HttpGet] public HttpResponseMessage PackageIdDocumentsDocumentIdPdf(Guid packageId, string documentId) { return HttpProxy(Request, Format("{0}/documents/{1}/pdf", packageId, documentId)); } [Route("{packageId:guid}/documents/{documentId}/actions"), HttpPost] public HttpResponseMessage PackageIdDocumentsDocumentIdActions(Guid packageId, string documentId) { return HttpProxy(Request, Format("{0}/documents/{1}/actions", packageId, documentId)); } [Route("{packageId:guid}/documents/{documentId}/layout"), HttpPost] public HttpResponseMessage PackageIdDocumentsDocumentIdLayout(Guid packageId, string documentId) { return HttpProxy(Request, Format("{0}/documents/{1}/layout", packageId, documentId)); } [Route("{packageId:guid}/documents/{documentId}/approvals"), HttpPost, HttpPut] public HttpResponseMessage PackageIdDocumentsDocumentIdApprovals(Guid packageId, string documentId) { return HttpProxy(Request, Format("{0}/documents/{1}/approvals", packageId, documentId)); } [Route("{packageId:guid}/documents/{documentId}/approvals/{approvalId}"), HttpGet, HttpPut, HttpDelete] public HttpResponseMessage PackageIdDocumentsDocumentIdApprovalsApprovalId(Guid packageId, string documentId, string approvalId) { return HttpProxy(Request, Format("{0}/documents/{1}/approvals/{2}", packageId, documentId, approvalId)); } [Route("{packageId:guid}/documents/{documentId}/approvals/{approvalId}/fields"), HttpPost] public HttpResponseMessage PackageIdDocumentsDocumentIdApprovalsApprovalIdFields(Guid packageId, string documentId, string approvalId) { return HttpProxy(Request, Format("{0}/documents/{1}/approvals/{2}/fields", packageId, documentId, approvalId)); } [Route("{packageId:guid}/documents/{documentId}/approvals/{approvalId}/fields/{fieldId}"), HttpGet, HttpPost, HttpPut, HttpDelete] public HttpResponseMessage PackageIdDocumentsDocumentIdApprovalsApprovalIdFields(Guid packageId, string documentId, string approvalId, string fieldId) { return HttpProxy(Request, Format("{0}/documents/{1}/approvals/{2}/fields/{3}", packageId, documentId, approvalId, fieldId)); } [Route("{packageId:guid}/documents/{documentId}/approvals/{approvalId}/sign"), HttpPost] public HttpResponseMessage PackageIdDocumentsDocumentIdApprovalsApprovalIdSign(Guid packageId, string documentId, string approvalId) { return HttpProxy(Request, Format("{0}/documents/{1}/approvals/{2}/sign", packageId, documentId, approvalId)); } #endregion #region Roles [Route("{packageId:guid}/roles"), HttpGet, HttpPost, HttpPut] public HttpResponseMessage PackageIdRoles(Guid packageId) { return HttpProxy(Request, Format("{0}/roles", packageId)); } [Route("{packageId:guid}/roles/{roleId}"), HttpGet, HttpPut, HttpDelete] public HttpResponseMessage PackageIdRolesRoleId(Guid packageId, string roleId) { return HttpProxy(Request, Format("{0}/roles/{1}", packageId, roleId)); } [Route("{packageId:guid}/roles/{roleId}/notifications"), HttpPost] public HttpResponseMessage PackageIdRolesRoleIdNotifications(Guid packageId, string roleId) { return HttpProxy(Request, Format("{0}/roles/{1}/notifications", packageId, roleId)); } [Route("{packageId:guid}/roles/{roleId}/sms_notification"), HttpPost] public HttpResponseMessage PackageIdRolesRoleIdSmsNotification(Guid packageId, string roleId) { return HttpProxy(Request, Format("{0}/roles/{1}/sms_notification", packageId, roleId)); } [Route("{packageId:guid}/roles/{roleId}/unlock"), HttpPost] public HttpResponseMessage PackageIdRolesRoleIdUnlock(Guid packageId, string roleId) { return HttpProxy(Request, Format("{0}/roles/{1}/unlock", packageId, roleId)); } [Route("{packageId:guid}/roles/{roleId}/signingUrl"), HttpPost] public HttpResponseMessage PackageIdRolesRoleIdSigningUrl(Guid packageId, string roleId) { return HttpProxy(Request, Format("{0}/roles/{1}/signingUrl", packageId, roleId)); } #endregion } }<file_sep>/Web.Api/SaaS.UI.Admin/js/controllers/admin/emails.js (function () { 'use strict'; angular .module('app.controllers') .controller('adminEmailsController', controller); controller.$inject = ['$scope', '$timeout', '$api', '$form', '$auth', '$http', '$authStorage']; function controller($scope, $timeout, $api, $form, $auth, $http, $authStorage) { var _langs = [ { name: 'all', id:'all' }, { name: 'en', id:'en' }, { name: 'fr', id:'fr' } ]; var _emailTemplates = [ { name: 'loading templates ...', id:"notemplates" } //{ name: 'All', id: null } ]; $scope.model = { emailTo: '<EMAIL>', emailsTemplates: _emailTemplates }; $timeout(function () { console.log($authStorage.accessToken()); }, 0); }; })();<file_sep>/Shared/SaaS.Oauth2/Clients/MicrosoftClient.cs using SaaS.Oauth2.Configuration; using SaaS.Oauth2.Core; namespace SaaS.Oauth2.Clients { public class MicrosoftClient : ClientProvider { public MicrosoftClient() { } public MicrosoftClient(OauthConfigurationElement oauth) : base(oauth) { } } } <file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.Password.cs using Microsoft.AspNet.Identity; using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Api.Oauth; using SaaS.Data.Entities.Accounts; using System; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { [HttpPost, Route("change-password"), SaaSAuthorize, ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> ChangePassword(ChangePasswordViewModel model) { return await CurrentAccountExecuteAsync(async delegate (Account user) { var errorResult = GetErrorResult(await _auth.AccountChangePasswordAsync(user.Id, model.OldPassword, model.NewPassword)); if (!object.Equals(errorResult, null)) return errorResult; await NotificationManager.PasswordChanged(user); return Ok(); }); } [HttpPost, Route("reset-password"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> ResetPassword(ResetPasswordViewModel model) { try { var user = await _auth.AccountGetAsync(model.UserId); if (object.Equals(user, null)) return AccountNotFound(); IdentityResult result = null; if (string.IsNullOrEmpty(model.Token) && user.IsEmptyPassword()) { result = await _auth.AccountPasswordSetAsync(user, model.NewPassword); } else { model.Token = HttpUtility.UrlDecode(model.Token); result = await _auth.AccountResetPasswordAsync(model.UserId, model.Token, model.NewPassword); } var errorResult = GetErrorResult(result); if (!object.Equals(errorResult, null)) return errorResult; if (user.IsEmptyPassword()) await NotificationManager.AccountCreationComplete(user); if (!string.IsNullOrEmpty(model.FirstName) || !string.IsNullOrEmpty(model.LastName)) { user = await _auth.AccountGetAsync(model.UserId); user.FirstName = string.IsNullOrEmpty(model.FirstName) ? user.FirstName : model.FirstName; user.LastName = string.IsNullOrEmpty(model.LastName) ? user.LastName : model.LastName; await _auth.AccountUpdateAsync(user); } await _auth.AccountActivateAsync(user); await _auth.AccountVisitorIdSetAsync(user, model.VisitorId); user = await _auth.AccountGetAsync(model.UserId); var internalSignInViewModel = new SignInViewModel(user); return ResponseMessage(await OauthManager.InternalSignIn(internalSignInViewModel)); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpPost, Route("recover-password"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> RecoverPassword(AuthViewModel model) { try { var slaveUser = await _auth.AccountGetAsync(model.Email, isIncludeSubEmails: true); if (!object.Equals(slaveUser, null) && slaveUser.IsEmptyPassword()) { var sessionTokensExternalHistory = await _auth.SessionTokenExternalHistoriesAsync(slaveUser.Id); var sessionTokenExternalHistory = sessionTokensExternalHistory.FirstOrDefault(e => !e.IsUnlinked); if (!object.Equals(sessionTokenExternalHistory, null)) return ErrorContent("invalid_grant", string.Format("You should sign in with {0}.", sessionTokenExternalHistory.ExternalClientName)); } var masterUser = await _auth.AccountGetAsync(model.Email); if (object.Equals(masterUser, null) || masterUser.IsAnonymous) return AccountNotFound(); await NotificationManager.RecoverPassword(masterUser); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } } }<file_sep>/Web.Api/SaaS.Zendesk/src/js/controllers/index.js angular.module('app.controllers') .controller('indexController', ['$scope', ($scope) => { }]);<file_sep>/Web.Api/SaaS.Zendesk/tasks/zat.server.js const gulp = require('gulp'); var exec = require('child_process').exec; gulp.task('zat.server', () => { return exec('zat server --path zat'); }); gulp.task('zat.validate', () => { return exec('zat validate --path zat'); }); gulp.task('zat.package', () => { return exec('zat package --path zat'); });<file_sep>/Web.Api/SaaS.Api/Controllers/Api/NpsController.cs using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Nps; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api { [RoutePrefix("api/nps")] public class NpsController : SaaSApiController { [HttpPost, ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> Post(NpsViewModel model) { try { Guid? accountId = null; if (User.Identity.IsAuthenticated) accountId = AccountId; await _nps.Rate(model.Questioner, accountId, model.ClientName, model.ClientVersion, model.Rating, model.RatingUsage, model.Comment); return Ok(); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } } }<file_sep>/Web.Api/SaaS.Zendesk/src/js/services/zendesk.js angular.module('app.services') .factory('$zendesk', [() => { var _zClient = ZAFClient.init(); var service = {}; service.init = function () { _zClient && _zClient.invoke('resize', { width: '100%', height: '400px' }); }; service.isEmpty = () => { return !_zClient; }; service.on = (key, callback) => { return _zClient.on(key, callback); }; service.get = (key) => { return _zClient.get(key); }; return service; }]);<file_sep>/Web.Api/SaaS.Zendesk/tasks/zat.images.js const gulp = require('gulp'); gulp.task('zat.images', () => { return gulp.src('zat/images/**/*.*') .pipe(gulp.dest('zat/assets')); });<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.OwnerProduct.cs using Microsoft.AspNet.Identity; using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Api.Models.Products; using SaaS.Data.Entities; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.View; using SaaS.Identity; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { [HttpGet, Route("owner-products"), SaaSAuthorize] public async Task<IHttpActionResult> OwnerProducts() { try { var products = await _authProduct.OwnerProductsGetAsync(AccountId); return Ok(products.ConvertAll(ProductConvertor.OwnerAccountProductConvertor)); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpGet, Route("owner-products/{accountProductId:guid}"), SaaSAuthorize] public async Task<IHttpActionResult> OwnerProduct(Guid accountProductId) { try { var details = await _authProduct.OwnerProductDetailsGetAsync(CreateAccountProductPair(accountProductId)); if (object.Equals(details, null)) return NotFound(); return Ok(ProductConvertor.OwnerAccountProductConvertor(details)); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } private async Task<IHttpActionResult> OwnerProductSuspend(Guid accountProductId, bool suspend, string source = null) { return await OwnerProductExecuteAsync(async delegate (Guid accountId, ViewOwnerProduct product) { var subscription = suspend ? await UpclickClient.SubscriptionSuspend(product.SpId, source) : await UpclickClient.SubscriptionResume(product.SpId); if (object.Equals(subscription, null)) return BadRequest(); DateTime? nextRebillDate = null; if (string.Equals(subscription.Status, "Active")) nextRebillDate = subscription.NextRebillDate; var pair = new AccountProductPair(accountId, product.AccountProductId); await _authProduct.ProductNextRebillDateSetAsync(pair, nextRebillDate); product = await _authProduct.OwnerProductDetailsGetAsync(pair); await NotificationManager.ProductSuspend(accountId, product, nextRebillDate); return Ok(ProductConvertor.OwnerAccountProductConvertor(product)); }, accountProductId); } [HttpGet, Route("owner-products/{accountProductId:guid}/suspend/{source?}"), SaaSAuthorize] public async Task<IHttpActionResult> OwnerProductSuspend(Guid accountProductId, string source = null) { return await OwnerProductSuspend(accountProductId, true, source); } [HttpGet, Route("owner-products/{accountProductId:guid}/resume"), SaaSAuthorize] public async Task<IHttpActionResult> OwnerProductResume(Guid accountProductId) { return await OwnerProductSuspend(accountProductId, false); } [HttpPost, Route("owner-products/{accountProductId:guid}/assign"), SaaSAuthorize, ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> OwnerProductAssign(Guid accountProductId, AuthViewModel model) { return await OwnerProductExecuteAsync(async delegate (Guid ownerAccountId, ViewOwnerProduct product) { var ownerAccount = await _auth.AccountGetAsync(ownerAccountId); var targetAccount = await _auth.AccountGetAsync(model.Email, isIncludeSubEmails: true); if (object.Equals(targetAccount, null)) { targetAccount = new Account(model.Email); var result = await _auth.AccountCreateAsync(targetAccount); var errorResult = GetErrorResult(result); if (!object.Equals(errorResult, null)) return errorResult; targetAccount = await _auth.AccountGetAsync(model.Email); } if (!object.Equals(ownerAccount, null)) { if (!product.IsFree && !product.IsTrial && !product.IsDisabled) { var status = await _authProduct.ProductAssignAsync(new AccountProductPair(targetAccount.Id, product.AccountProductId)); if (status == AssignStatus.Ok) { await NotificationManager.ProductAssigned(ownerAccountId, product, targetAccount); if (ownerAccount.IsBusiness) await _auth.AccountMaskAsBusinessAsync(targetAccount); await _auth.AccountActivateAsync(targetAccount); } if (status != AssignStatus.Ok) return Conflict(); } } product = await _authProduct.OwnerProductDetailsGetAsync(new AccountProductPair(ownerAccountId, product.AccountProductId)); var productView = ProductConvertor.OwnerAccountProductConvertor(product); return Ok(productView); }, accountProductId); } [HttpPost, Route("owner-products/{accountProductId:guid}/unassign"), SaaSAuthorize, ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> OwnerProductUnassign(AuthIdViewModel model, Guid accountProductId) { model = model ?? new AuthIdViewModel { AccountId = Guid.Parse(User.Identity.GetUserId()) }; return await OwnerProductExecuteAsync(async delegate (Guid accountId, ViewOwnerProduct product) { var user = await _auth.AccountGetAsync(model.AccountId); if (!object.Equals(user, null) && !product.IsFree && !product.IsTrial && !product.IsDisabled) { var statusResult = await _authProduct.ProductUnassignAsync(new AccountProductPair(user.Id, product.AccountProductId)); if (statusResult.Status == UnassignStatus.Ok) await NotificationManager.ProductUnassigned(accountId, product, user); if (statusResult.Status != UnassignStatus.Ok) return Conflict(); } product = await _authProduct.OwnerProductDetailsGetAsync(new AccountProductPair(accountId, product.AccountProductId)); return Ok(ProductConvertor.OwnerAccountProductConvertor(product)); }, accountProductId, true); } [HttpPost, Route("owner-products/{accountProductId:guid}/resend-assign-invitation"), SaaSAuthorize, ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> OwnerProductResendAssignInvitation(AuthIdViewModel model, Guid accountProductId) { return await OwnerProductExecuteAsync(async delegate (Guid accountId, ViewOwnerProduct product) { var user = await _auth.AccountGetAsync(model.AccountId); if (!object.Equals(user, null) && !product.IsFree && !product.IsTrial && !product.IsDisabled && accountId != user.Id) await NotificationManager.ProductAssigned(accountId, product, user); else return Conflict(); return Ok(); }, accountProductId); } } }<file_sep>/Web.Api/SaaS.Sso/src/js/services/form.js angular.module('app.services') .factory('$form', () => { var service = {}; service.submit = (entity, form, callback) => { if (form.$valid !== true) { angular.forEach(form, (value, key) => { if (typeof value === 'object' && value.hasOwnProperty('$modelValue')) value.$setDirty(); }); } if (service.isReady(entity, form) === false) return; callback(form); }; service.isReady = (entity, form) => { if (entity.isBusy === true || form.$valid !== true) return false; entity.isBusy = true; return true; }; return service; });<file_sep>/Web.Api/SaaS.Zendesk/tasks/zat.css.js const gulp = require('gulp'); gulp.task('zat.css:assets', () => { return gulp.src('dist/css/*.css') .pipe(gulp.dest('zat/assets/css')); }); gulp.task('zat.css:watch', () => { return gulp.watch('dist/css/*.css', gulp.series('zat.css:assets')); }); gulp.task('zat.css', gulp.series('zat.css:assets'));<file_sep>/Shared/SaaS.Oauth2/Clients/GoogleClient.cs using SaaS.Oauth2.Configuration; using SaaS.Oauth2.Core; namespace SaaS.Oauth2.Clients { public class GoogleClient : ClientProvider { public GoogleClient() { } public GoogleClient(OauthConfigurationElement oauth) : base(oauth) { } } } <file_sep>/Web.Api/SaaS.Api.Admin/Controllers/Api/UpclickController.cs using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Admin.Controllers.Api { [RoutePrefix("api/upclick"), Authorize] public class UpclickController : SaaSApiController { [HttpGet, Route("products")] public async Task<IHttpActionResult> Products() { return Ok(await _authProduct.UpclickProductsGetAsync()); } } } <file_sep>/Shared/SaaS.Oauth2/Clients/FacebookClient.cs using SaaS.Oauth2.Configuration; using SaaS.Oauth2.Core; namespace SaaS.Oauth2.Clients { public class FacebookClient : ClientProvider { public FacebookClient() { } public FacebookClient(OauthConfigurationElement oauth) : base(oauth) { } } } <file_sep>/Web.Api/SaaS.UI.Admin/js/services/notify.js (function () { 'use strict'; angular .module('app.services') .factory('$notify', factory); factory.$inject = ['$rootScope']; function factory($rootScope) { var service = {}; var _notify = function (type, options) { options.type = type; options.timeout = 2 * 1000; $rootScope.$emit('notify', options); angular.element('[notifybar]').css('position', 'fixed') }; service.info = function (content) { _notify('info', { title: 'Information', content: content }); }; service.warning = function (content) { _notify('warning', { title: 'Warning', content: content }); }; service.success = function (content) { _notify('success', { title: 'Success', content: content }); }; service.error = function (content) { _notify('error', { title: 'Error', content: content }); }; service.serverError = function () { _notify('error', { title: 'Error', content: 'An error has occured. Please try again or contact us.' }); }; return service; }; })();<file_sep>/WinService/SaaS.WinService.eSign/EmailChangeWorker.cs using eSign20.Api.Client; using NLog; using SaaS.Identity; using System; using System.Linq; using System.Threading.Tasks; namespace SaaS.WinService.eSign { public sealed class EmailChangeWorker : IDisposable { private const string DASHES = "---------------------------------------------------------------------------------------------------------"; private IAuthRepository _auth; private IeSignRepository _eSign; private static Logger _logger = LogManager.GetCurrentClassLogger(); public EmailChangeWorker() { _auth = new AuthRepository(); _eSign = new eSignRepository(); } public int Do(int top) { //select * from accounts.account where email like '%ozvieriev%' -- //exec[eSign].[peSignApiKeySetByAccountId] '<KEY>', 1, 'fasdfa' var apiKeys = _eSign.eSignApiKeysNeedRefreshGet(top); foreach (var apiKey in apiKeys) { var accountEmails = _auth.AccountEmailsGet(apiKey.AccountId); var responseTask = Task.Run(async () => { return await eSign20Client.AccountSendersChangeEmailAsync(accountEmails.Select(e => e.Email)); }); responseTask.Wait(); if (responseTask.Result.IsSuccessStatusCode) _logger.Info("AccountEmailChange - HttpStatus: {0} Emails: {1}", responseTask.Result.StatusCode, string.Join(",", accountEmails)); else _logger.Error("AccountEmailChange - HttpStatus: {0} Emails: {1}", responseTask.Result.StatusCode, string.Join(",", accountEmails)); _eSign.eSignApiKeyDelete(apiKey.Id); } return apiKeys.Count; } public void Dispose() { _auth.Dispose(); _eSign.Dispose(); } } } <file_sep>/Web.Api/SaaS.UI.Admin/js/controllers/account/sub-emails.js (function () { 'use strict'; angular .module('app.controllers') .controller('accountSubEmailsController', controller); controller.$inject = ['$rootScope', '$scope', '$api']; function controller($rootScope, $scope, $api) { $scope.model = { account: null, subEmails: null }; $scope.isBusy = false; var viewSubEmail = function (json) { var self = this; Object.defineProperties(this, { id: { value: json.id, writable: false }, email: { value: json.email, writable: false }, createDate: { value: json.createDate, writable: false } }); }; var _subEmails = function () { $scope.isBusy = true; $api.account.subEmails($scope.model.account.id).then(function (json) { var subEmails = []; json && json.forEach(function callback(value, index, array) { subEmails.push(new viewSubEmail(value)); }); $scope.model.subEmails = subEmails; }).finally(function () { $scope.isBusy = false; }); }; $scope.refresh = function () { if ($scope.isBusy) return; $scope.isBusy = true; _subEmails(); }; $rootScope.$on('event:accountLoaded', function (event, json) { $scope.model.account = json; $scope.refresh(); }); }; })();<file_sep>/Web.Api/SaaS.Api/Oauth/Providers/SaaSAuthorizationServerProvider.cs using Microsoft.Owin.Security; using Microsoft.Owin.Security.Infrastructure; using Microsoft.Owin.Security.OAuth; using SaaS.Data.Entities; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Oauth; using SaaS.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace SaaS.Api.Oauth.Providers { public partial class SaaSAuthorizationServerProvider : OAuthAuthorizationServerProvider { private static readonly SortedList<string, Client> _clients = new SortedList<string, Client>(StringComparer.InvariantCultureIgnoreCase); static SaaSAuthorizationServerProvider() { using (var auth = new AuthRepository()) { foreach (var client in auth.ClientsGet()) _clients.Add(client.Name, client); } } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { Account user = null; using (var auth = new AuthRepository()) { using (var authProduct = new AuthProductRepository()) { user = await GrantLocalUser(context, auth); if (object.Equals(user, null)) return; await auth.AccountNeverLoginSetAsync(user); await auth.AccountVisitorIdSetAsync(user, context.OwinContext.Get<Guid?>("visitorId")); var client = context.OwinContext.Get<Client>("client"); var externalClient = context.OwinContext.Get<ExternalClient?>("externalClient"); var scope = context.OwinContext.Get<string[]>("scope"); var scopeWorker = SaaSScopeWorkerFactory.Create(scope, context, auth, authProduct); if (!await scopeWorker.ValidateDeviceAsync(user)) return; var identity = new ClaimsIdentity(context.Options.AuthenticationType); var properties = new Dictionary<string, string> { { "session", Guid.NewGuid().ToString("N") } }; if (externalClient.HasValue) properties["externalClient"] = OauthManager.GetExternalClientName(externalClient.Value); identity.AddClaim(ClaimTypes.NameIdentifier, user.Id); identity.AddClaims(user, client); context.OwinContext.Set("user", user); context.Validated(new AuthenticationTicket(identity, new AuthenticationProperties(properties))); } } } private static async Task<Account> GrantResourceOwnerCredentialsToken(OAuthGrantResourceOwnerCredentialsContext context, AuthRepository auth) { var token = context.OwinContext.Get<string>("token"); if (!string.IsNullOrEmpty(token)) { Guid parentRefreshToken; if (Guid.TryParse(token, out parentRefreshToken)) { var sessionToken = await auth.SessionTokenGetAsync(parentRefreshToken); if (!object.Equals(sessionToken, null)) { context.OwinContext.Set("parentSessionToken", sessionToken); return await auth.AccountGetAsync(sessionToken.AccountId); } } else { var tokenContext = new OAuthRequestTokenContext(context.OwinContext, token); var tokenReceiveContext = new AuthenticationTokenReceiveContext(context.OwinContext, Startup.OAuthBearerOptions.AccessTokenFormat, tokenContext.Token); tokenReceiveContext.DeserializeTicket(tokenReceiveContext.Token); var ticket = tokenReceiveContext.Ticket; if (!object.Equals(ticket, null) && ticket.Properties.ExpiresUtc.HasValue && ticket.Properties.ExpiresUtc.Value > Startup.OAuthBearerOptions.SystemClock.UtcNow) return await auth.AccountGetAsync(ticket.Identity.Name); } } return null; } private static async Task<Account> GrantLocalUser(OAuthGrantResourceOwnerCredentialsContext context, AuthRepository auth) { var user = await GrantResourceOwnerCredentialsToken(context, auth); if (!object.Equals(user, null)) return user; user = user ?? await auth.AccountGetAsync(context.UserName); if (!object.Equals(user, null) && user.IsEmptyPassword()) { if (context.OwinContext.Get<ExternalClient?>("externalClient").HasValue) return user; var sessionTokensExternalHistory = await auth.SessionTokenExternalHistoriesAsync(user.Id); var sessionTokenExternalHistory = sessionTokensExternalHistory.FirstOrDefault(e => !e.IsUnlinked); if (!object.Equals(sessionTokenExternalHistory, null)) { context.SetError("invalid_grant", string.Format("You should sign in with {0}.", sessionTokenExternalHistory.ExternalClientName)); return null; } if (!string.IsNullOrEmpty(user.Email)) context.Response.Headers.Add("User-Email", new string[] { user.Email }); if (!string.IsNullOrEmpty(user.FirstName)) context.Response.Headers.Add("User-FirstName", new string[] { user.FirstName }); if (!string.IsNullOrEmpty(user.LastName)) context.Response.Headers.Add("User-LastName", new string[] { user.LastName }); context.SetError("invalid_grant", "You should create an account."); return null; } if (object.Equals(user, null)) { user = await auth.AccountGetAsync(context.UserName, isIncludeSubEmails: true); if (!object.Equals(user, null)) { context.SetError("invalid_grant", string.Format("You cannot sign in with this email as it is no longer associated with your account.", context.UserName)); return null; } } if (!object.Equals(user, null) && (auth.PasswordIsEqual(user.Password, context.Password) || string.Equals(user.Password, context.Password, StringComparison.InvariantCultureIgnoreCase))) return user; context.SetError("invalid_grant", "The email or password is incorrect."); return null; } } public class SubscriptionSignInData { public int? AccountProductId { get; set; } public bool SetAsDefault { get; set; } } public class SystemSignInData { public Guid MachineKey { get; set; } public string MotherboardKey { get; set; } public string PhysicalMac { get; set; } public bool IsAutogeneratedMachineKey { get; set; } public string PcName { get; set; } } }<file_sep>/Web.Api/SaaS.UI.Admin/js/auth/interceptor.js (function () { 'use strict'; angular .module('app.auth') .factory('$authInterceptor', authInterceptor) .config(['$httpProvider', function ($httpProvider) { $httpProvider.interceptors.push(['$rootScope', '$q', '$authBuffer', function ($rootScope, $q, $authBuffer) { var interceptor = {}; interceptor.request = function (config) { config.headers = config.headers || {}; if (!config.disableOauth) { var accessToken = $.cookie('access_token'); if (accessToken) config.headers.Authorization = 'Bearer ' + accessToken; } return config; }; interceptor.responseError = function (rejection) { var config = rejection.config || {}; if (!config.ignoreAuthModule) { switch (rejection.status) { case 401: var deferred = $q.defer(); $authBuffer.append(config, deferred); $rootScope.$broadcast('event:auth-loginRequired', rejection); return deferred.promise; case 403: $rootScope.$broadcast('event:auth-forbidden', rejection); break; } } // otherwise, default behaviour return $q.reject(rejection); } return interceptor; }]); }]) authInterceptor.$inject = ['$rootScope', '$authBuffer']; function authInterceptor($rootScope, $authBuffer) { var service = {}; /** * Call this function to indicate that authentication was successfull and trigger a * retry of all deferred requests. * @param data an optional argument to pass on to $broadcast which may be useful for * example if you need to pass through details of the user that was logged in * @param configUpdater an optional transformation function that can modify the * requests that are retried after having logged in. This can be used for example * to add an authentication token. It must return the request. */ service.loginConfirmed = function (data, configUpdater) { var updater = configUpdater || function (config) { return config; }; $rootScope.$broadcast('event:auth-loginConfirmed', data); $authBuffer.retryAll(updater); }; /** * Call this function to indicate that authentication should not proceed. * All deferred requests will be abandoned or rejected (if reason is provided). * @param data an optional argument to pass on to $broadcast. * @param reason if provided, the requests are rejected; abandoned otherwise. */ service.loginCancelled = function (data, reason) { $authBuffer.rejectAll(reason); $rootScope.$broadcast('event:auth-loginCancelled', data); } return service; }; })();<file_sep>/Shared/SaaS.Oauth2/Core/ProfileResult.cs using Newtonsoft.Json; namespace SaaS.Oauth2.Core { public class ProfileResult { public ProfileResult(FacebookProfileResult profile) : this(profile.Id, profile.Email, profile.FirstName, profile.LastName) { } public ProfileResult(GoogleProfileResult profile) : this(profile.Id, profile.Email, profile.FirstName, profile.LastName) { } public ProfileResult(MicrosoftProfileResult profile) : this(profile.Id, profile.Email, profile.FirstName, profile.LastName) { } public ProfileResult(string id, string email, string firstName, string lastName) { Id = id; Email = email; FirstName = firstName; LastName = lastName; } public string Id { get; set; } public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public class BaseProfileResult { public string Id { get; set;} } public class FacebookProfileResult: BaseProfileResult { public string Email { get; set; } [JsonProperty("first_name")] public string FirstName { get; set; } [JsonProperty("last_name")] public string LastName { get; set; } } public class GoogleProfileResult: BaseProfileResult { public string Email { get; set; } [JsonProperty("given_name")] public string FirstName { get; set; } [JsonProperty("family_name")] public string LastName { get; set; } } public class MicrosoftProfileResult: BaseProfileResult { [JsonProperty("userPrincipalName")] public string Email { get; set; } [JsonProperty("givenName")] public string FirstName { get; set; } [JsonProperty("surname")] public string LastName { get; set; } } } <file_sep>/Web.Api/SaaS.Api.Sign/Controllers/Api/ESign20/PresignController.cs using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Common.Extensions; using SaaS.Data.Entities; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View; using SaaS.IPDetect; using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Sign.Controllers.Api.eSign20 { [RoutePrefix("api-esign20/v1/presign"), SaaSAuthorize] public class ESignPresignController : BaseApiController { protected override string ApiRoot { get { return "api/v1/signers/"; } } [Route, HttpPost] public async Task<HttpResponseMessage> Presign(CancellationToken cancellationToken) { try { var session = await GetSessionToken(); if (object.Equals(session, null)) return Request.CreateResponse(HttpStatusCode.Unauthorized); if ("esign-lite".Equals(session.ClientName, StringComparison.InvariantCultureIgnoreCase)) return await PresignESignLite(session, cancellationToken); return Request.CreateExceptionResponse(errorDescription: "Bad client_id.", statusCode: HttpStatusCode.BadRequest); } catch (Exception exc) { return Request.CreateExceptionResponse(exc); } } private async Task<HttpResponseMessage> PresignESignLite(SessionToken session, CancellationToken cancellationToken) { int? allowed = null; int? used = null; ViewAccountMicrotransaction microtransaction; var microtransactions = await _authProduct.AccountMicrotransactionsGetAsync(session.AccountId); var accountMicrotransactionId = eSignHelper.GetAllowedAccountMicrotransactionId(microtransactions, out microtransaction); if (accountMicrotransactionId.HasValue && !microtransaction.AllowedEsignCount.HasValue) return IncludeHeaders(Request.CreateResponse(), microtransaction.AllowedEsignCount, microtransaction.UsedEsignCount); /*--------------------------------------------------------------------------------*/ ViewAccountProduct product; var products = await _authProduct.AccountProductsGetAsync(session.AccountId); var accountProductId = eSignHelper.GetAllowedAccountProductId(products, session.AccountProductId, out product); if (accountProductId.HasValue && !product.AllowedEsignCount.HasValue) return IncludeHeaders(Request.CreateResponse(), product.AllowedEsignCount, product.UsedEsignCount); /*--------------------------------------------------------------------------------*/ var type = eSignTransactionInitiatorType.Free; if (accountMicrotransactionId.HasValue && microtransaction.AllowedEsignCount.HasValue) { eSignHelper.GetAllowedUsedCount(products, microtransactions, out allowed, out used); type = eSignTransactionInitiatorType.Microtransaction; } else { if (accountProductId.HasValue && product.AllowedEsignCount.HasValue) { eSignHelper.GetAllowedUsedCount(products, microtransactions, out allowed, out used); type = eSignTransactionInitiatorType.Product; } } var json = await Request.Content.ReadAsStringAsync(); var ipAddressHash = IpAddressDetector.IpAddress.GetShortMD5Hash(); var freeNumberOfSigns = await _eSign.eSignPackageHistoryGetFreeNumberOfSigns(session.ClientId, eSignClient, ipAddressHash); var fileSize = GetFileContentLength(); var recipients = GetRecipientsCount(json); if (type == eSignTransactionInitiatorType.Free || type == eSignTransactionInitiatorType.Microtransaction) { if (fileSize > eSignLiteLimitation.FileSize) return PaymentRequired(type == eSignTransactionInitiatorType.Microtransaction ? eSignLiteLimitation.FileSizeMinorWarning : eSignLiteLimitation.FileSizeError, allowed, used); if (recipients > eSignLiteLimitation.Recipients) return PaymentRequired(type == eSignTransactionInitiatorType.Microtransaction ? eSignLiteLimitation.RecipientsMinorWarning : eSignLiteLimitation.RecipientsError, allowed, used); if (freeNumberOfSigns >= eSignLiteLimitation.SignsPerDay || type == eSignTransactionInitiatorType.Microtransaction) return PaymentRequired(type == eSignTransactionInitiatorType.Microtransaction ? eSignLiteLimitation.SignsPerDayMinorWarning : eSignLiteLimitation.SignsPerDayError, allowed, used); } if (type == eSignTransactionInitiatorType.Product) { if (fileSize > eSignLiteLimitation.FileSize) return PaymentRequired(eSignLiteLimitation.FileSizeMinorWarning, allowed, used); if (recipients > eSignLiteLimitation.Recipients) return PaymentRequired(eSignLiteLimitation.RecipientsMinorWarning, allowed, used); if (freeNumberOfSigns >= eSignLiteLimitation.SignsPerDay) return PaymentRequired(eSignLiteLimitation.SignsPerDayMinorWarning, allowed, used); } return Request.CreateResponse(); } } } <file_sep>/Shared/SaaS.IPDetect/IpAddressDetector.cs using System; using System.Configuration; using System.Net; using System.Web; namespace SaaS.IPDetect { public static class IpAddressDetector { private static char[] _splitCharacters = new char[] { ',' }; private static string _ipAddressServerVariableName = ConfigurationManager.AppSettings["IpAddressServerVariableName"]; public static string IpAddress { get { string ipAddress = null; var request = HttpContext.Current.Request; if (!string.IsNullOrWhiteSpace(_ipAddressServerVariableName)) ipAddress = request.ServerVariables[_ipAddressServerVariableName]; if (string.IsNullOrWhiteSpace(ipAddress)) ipAddress = request.UserHostAddress; if (!string.IsNullOrWhiteSpace(ipAddress) && ipAddress.IndexOf(',') != -1) { var split = ipAddress.Split(_splitCharacters, StringSplitOptions.RemoveEmptyEntries); foreach (string item in split) { var value = (item ?? string.Empty).Trim(); IPAddress tmpIpAddress; if (IPAddress.TryParse(value, out tmpIpAddress)) return value; } } return ipAddress; } } } }<file_sep>/Web.Api/SaaS.Api/Models/Validation/ArrayLengthAttribute.cs using System.Collections; using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Validation { public class ArrayMaxLengthAttribute : ValidationAttribute { private readonly int _length; public ArrayMaxLengthAttribute(int length) { _length = length; } public override bool IsValid(object value) { if (value is ICollection == false) { return false; } return ((ICollection) value).Count <= _length; } } }<file_sep>/Shared/SaaS.Data.Entities/View/ViewUpgradeProduct.cs using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Data.Entities.View { public class ViewUpgradeProduct { public string OwnerEmail { get; set; } public string ProductUnitName { get; set; } public string CurrencyISO { get; set; } public decimal Price { get; set; } public decimal PriceUsd { get; set; } public string SpId { get; set; } public int Quantity { get; set; } public int TimeStamp { get; set; } public bool IsUpgradable { get; set; } public bool IsTrial { get; set; } public bool IsFree { get; set; } [NotMapped] public ulong Status { get { ulong status = 0; status |= (ulong)(IsTrial ? ProductStatus.IsTrial : 0); status |= (ulong)(IsFree ? ProductStatus.IsFree : 0); status |= (ulong)(IsUpgradable ? ProductStatus.IsUpgradable : 0); status |= (ulong)(false ? ProductStatus.IsPaymentFailed : 0); return status; } } } } <file_sep>/Web.Api/SaaS.Sso/src/js/controllers/account/identifier.js angular.module('app.controllers') .controller('accountIdentifierController', ['$scope', '$state', '$api', '$storage', '$form', '$brand', ($scope, $state, $api, $storage, $form, $brand) => { $scope.model = { email: $state.params.email || null }; $scope.status = null; $scope.isBusy = false; $scope.subTitle = `with your ${$brand.currentName()} account`; $scope.errorNotFound = `Couldn't find your ${$brand.currentName()} account`; $scope.submit = (form) => { $scope.status = null; $scope.model.error = null; $form.submit($scope, form, () => { return $api.account.get({ email: $scope.model.email }) .then((json) => { $storage.addAccount(json); $state.go('account/password', json); }, (json) => { if (json.status !== 404) return $state.go('account/error'); $scope.status = 404; }) .finally(() => { $scope.isBusy = false; }); }); }; }]);<file_sep>/Shared/SaaS.Common/Extensions/PasswordHasher.cs using Microsoft.AspNet.Identity; using System; using System.Security.Cryptography; using System.Text; namespace SaaS.Common.Extensions { public class SaaSPasswordHasher : IPasswordHasher { public string HashPassword(string password) { return password.GetMD5Hash(); } public PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword) { return hashedPassword == HashPassword(providedPassword) ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed; } } public static class PasswordHash { public static string GetMD5Hash(this string str) { return (str ?? string.Empty).GetMD5Hash(new UnicodeEncoding()); } public static string GetShortMD5Hash(this string str) { return (str ?? string.Empty).GetShortMD5Hash(new UnicodeEncoding()); } private static byte[] GetHash(string str, Encoding encoding) { var clearBytes = encoding.GetBytes(str ?? string.Empty); var form = CryptoConfig.CreateFromName("MD5"); var algoritm = (HashAlgorithm)form; return algoritm.ComputeHash(clearBytes); } public static string GetMD5Hash(this string str, Encoding encoding) { var hash = GetHash(str, encoding); return BitConverter.ToString(hash); } public static string GetShortMD5Hash(this string str, Encoding encoding) { var hash = GetHash(str, encoding); var builder = new StringBuilder(); for (int index = 0; index < hash.Length; index++) builder.Append(hash[index].ToString("X2")); return builder.ToString(); } } } <file_sep>/Web.Api/SaaS.Api.Admin/Controllers/Api/AccountController.OwnerProduct.cs using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Api.Models.Products; using SaaS.Data.Entities; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Admin.Oauth; using SaaS.Identity; using System; using System.Net; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Admin.Controllers.Api { public partial class AccountController : SaaSApiController { private bool IsLocalSubscription(string spId) { if (string.IsNullOrEmpty(spId)) return false; return spId.StartsWith("D00000", StringComparison.InvariantCultureIgnoreCase); } [HttpGet, Route("{accountId:guid}/owner-product")] public async Task<IHttpActionResult> OwnerProducts(Guid accountId) { return await CurrentAccountExecuteAsync(async delegate (Account account) { var products = await _authProduct.OwnerProductsGetAsync(account.Id); return Ok(ProductConvertor.OwnerAccountProductConvertor(products)); }, accountId); } [HttpGet, Route("{accountId:guid}/owner-product/{accountProductId:guid}")] public async Task<IHttpActionResult> OwnerProducts(Guid accountId, Guid accountProductId) { return await CurrentAccountExecuteAsync(async delegate (Account account) { var details = await _authProduct.OwnerProductDetailsGetAsync(new AccountProductPair(accountId, accountProductId)); if (object.Equals(details, null)) return NotFound(); return Ok(ProductConvertor.OwnerAccountProductConvertor(details)); }, accountId); } [HttpPost, Route("{accountId:guid}/owner-product/{accountProductId:guid}/assign"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> OwnerProductAssign(Guid accountId, Guid accountProductId, AuthViewModel model) { try { var product = await _authProduct.OwnerProductGetAsync(new AccountProductPair(accountId, accountProductId)); if (object.Equals(product, null) || product.IsDisabled) return ProductNotFound(); var ownerAccount = await _auth.AccountGetAsync(accountId); var targetAccount = await _auth.AccountGetAsync(model.Email, isIncludeSubEmails: true); if (object.Equals(targetAccount, null)) { targetAccount = new Account(model.Email); var result = await _auth.AccountCreateAsync(targetAccount); var errorResult = GetErrorResult(result); if (!object.Equals(errorResult, null)) return errorResult; targetAccount = await _auth.AccountGetAsync(model.Email); } if (!object.Equals(ownerAccount, null)) { if (!product.IsFree && !product.IsTrial && !product.IsDisabled) { var statusResult = await _authProduct.ProductAssignAsync(new AccountProductPair(targetAccount.Id, product.AccountProductId), true); if (statusResult == AssignStatus.Ok) { var log = string.Format("Product({0}, {1}) has been assigned successfully. Customer's email is {2}.", product.ProductName, product.AccountProductId, ownerAccount.Email); await LogInsertAsync(log, LogActionTypeEnum.AccountProductAssign, ownerAccount.Id); } if (statusResult != AssignStatus.Ok) return Conflict(); } if (ownerAccount.IsBusiness) await _auth.AccountMaskAsBusinessAsync(targetAccount); await _auth.AccountActivateAsync(targetAccount); } product = await _authProduct.OwnerProductDetailsGetAsync(new AccountProductPair(accountId, product.AccountProductId)); return Ok(ProductConvertor.OwnerAccountProductConvertor(product)); } catch (Exception exc) { return ErrorContent(exc); } } [HttpPost, Route("{accountId:guid}/owner-product/{accountProductId:guid}/deactivate"), SaaSAuthorize] public async Task<IHttpActionResult> OwnerProductDeactivate(Guid accountId, Guid accountProductId) { try { var product = await _authProduct.OwnerProductGetAsync(new AccountProductPair(accountId, accountProductId)); if (object.Equals(product, null)) return ProductNotFound(); var ownerAccount = await _auth.AccountGetAsync(accountId); if (!object.Equals(ownerAccount, null) && !product.IsFree && !product.IsTrial && !product.IsDisabled) { if (!IsLocalSubscription(product.SpId) && !string.IsNullOrEmpty(product.SpId)) { var subscription = await UpclickClient.SubscriptionDetails(product.SpId); if (object.Equals(subscription, null) || object.Equals(subscription.Status, null)) return ErrorContent("Unknown subscription", "Upclick error. Unknown subscription."); if (string.Equals(subscription.Status.Name, "Active")) { subscription = await UpclickClient.SubscriptionCancel(product.SpId); //cuz Upclick has bug in API Thread.Sleep(TimeSpan.FromSeconds(3)); subscription = await UpclickClient.SubscriptionDetails(product.SpId); if (string.Equals(subscription.Status.Name, "Active")) return ErrorContent("Subscription is active", "Upclick error. Subscription is active."); } } await _authProduct.ProductDeactivateAsync(new AccountProductPair(accountId, product.AccountProductId)); var log = string.Format("Product({0}, {1}) has been deactivated successfully. Customer's email is {2}.", product.ProductName, product.AccountProductId, ownerAccount.Email); await LogInsertAsync(log, LogActionTypeEnum.AccountProductDeactivate, ownerAccount.Id); } return Ok(); } catch (Exception exc) { return ErrorContent(exc); } } [HttpPost, Route("{accountId:guid}/owner-product/{accountProductId:guid}/unassign/{targetAccountId:guid}")] public async Task<IHttpActionResult> OwnerProductUnassign(Guid accountId, Guid accountProductId, Guid targetAccountId) { try { var product = await _authProduct.OwnerProductGetAsync(new AccountProductPair(accountId, accountProductId)); if (object.Equals(product, null) || product.IsDisabled) return ProductNotFound(); var ownerAccount = await _auth.AccountGetAsync(accountId); var targetAccount = await _auth.AccountGetAsync(targetAccountId); if (!object.Equals(ownerAccount, null) && !product.IsFree && !product.IsTrial && !product.IsDisabled) { var statusResult = await _authProduct.ProductUnassignAsync(new AccountProductPair(targetAccount.Id, product.AccountProductId)); if (statusResult.Status == UnassignStatus.Ok) { var log = string.Format("Product({0}, {1}) has been unassigned successfully. Customer's email is {2}.", product.ProductName, product.AccountProductId, ownerAccount.Email); await LogInsertAsync(log, LogActionTypeEnum.AccountProductUnassign, ownerAccount.Id); } if (statusResult.Status != UnassignStatus.Ok) return Conflict(); } product = await _authProduct.OwnerProductDetailsGetAsync(new AccountProductPair(accountId, product.AccountProductId)); return Ok(ProductConvertor.OwnerAccountProductConvertor(product)); } catch (Exception exc) { return ErrorContent(exc); } } [HttpPost, Route("{accountId:guid}/owner-product/{accountProductId:guid}/allowed")] public async Task<IHttpActionResult> OwnerProductAllowed(Guid accountId, Guid accountProductId, [FromUri] int allowed) { try { var product = await _authProduct.OwnerProductDetailsGetAsync(new AccountProductPair(accountId, accountProductId)); if (object.Equals(product, null) || product.IsDisabled) return ProductNotFound(); int assignedLicenses = 0; if (!object.Equals(product.Accounts, null)) assignedLicenses = product.Accounts.Count; if (assignedLicenses > allowed) return ErrorContent("invalid_grant", "You can't change amount of licenses. Please unassign licenses from any account.", HttpStatusCode.Conflict); var ownerAccount = await _auth.AccountGetAsync(accountId); if (!object.Equals(ownerAccount, null) && !product.IsFree && !product.IsTrial) { var statusResult = await _authProduct.ProductAllowedSetAsync(new AccountProductPair(accountId, product.AccountProductId), allowed); if (statusResult == AllowedCountStatus.Ok) { var log = string.Format("Amount of licenses has been changed successfully. Product({0}, {1}). Customer's email is {2}. Amount({3}=>{4}).", product.ProductName, product.AccountProductId, ownerAccount.Email, product.AllowedCount, allowed); await LogInsertAsync(log, LogActionTypeEnum.AccountProductUnassign, ownerAccount.Id); } if (statusResult == AllowedCountStatus.FailCantChangeAllowedCount) return ErrorContent("invalid_grant", "You can't change amount of licenses for this product.", HttpStatusCode.Conflict); if (statusResult != AllowedCountStatus.Ok) return Conflict(); } product = await _authProduct.OwnerProductDetailsGetAsync(new AccountProductPair(accountId, product.AccountProductId)); return Ok(ProductConvertor.OwnerAccountProductConvertor(product)); } catch (Exception exc) { return ErrorContent(exc); } } private async Task<IHttpActionResult> OwnerProductSuspend(Guid accountId, Guid accountProductId, bool suspend) { return await CurrentAccountExecuteAsync(async delegate (Account account) { var product = await _authProduct.OwnerProductGetAsync(new AccountProductPair(accountId, accountProductId)); if (object.Equals(product, null) || product.IsDisabled) return ProductNotFound(); if (!product.IsRenewal || IsLocalSubscription(product.SpId)) return ErrorContent(string.Empty, "This product can't be suspend or resumed."); DateTime? nextRebillDate = null; var subscriptionDetails = await UpclickClient.SubscriptionDetails(product.SpId); if (object.Equals(subscriptionDetails, null)) return ErrorContent(string.Empty, "Product is not exists in Customer info(Upclick)."); var subscription = suspend ? await UpclickClient.SubscriptionSuspend(product.SpId) : await UpclickClient.SubscriptionResume(product.SpId); if (suspend && string.Equals(subscription.Status, "Active")) return ErrorContent(string.Empty, "Product can't be suspend. Product is still active in Customer info(Upclick)."); if (!suspend && !string.Equals(subscription.Status, "Active")) return ErrorContent(string.Empty, "Product can't be resumed. Product is not active in Customer info(Upclick)."); if (string.Equals(subscription.Status, "Active")) nextRebillDate = subscription.NextRebillDate; var pair = new AccountProductPair(accountId, product.AccountProductId); await _authProduct.ProductNextRebillDateSetAsync(pair, nextRebillDate); var log = string.Format("Product({0}, {1}) has been {2} successfully.", product.ProductName, product.AccountProductId, nextRebillDate.HasValue ? "resumed" : "suspended"); await LogInsertAsync(log, LogActionTypeEnum.AccountProductDeactivate, accountId); product = await _authProduct.OwnerProductDetailsGetAsync(pair); return Ok(ProductConvertor.OwnerAccountProductConvertor(product)); }, accountId); } [HttpPost, Route("{accountId:guid}/owner-product/{accountProductId:guid}/suspend")] public async Task<IHttpActionResult> OwnerProductSuspend(Guid accountId, Guid accountProductId) { return await OwnerProductSuspend(accountId, accountProductId, true); } [HttpPost, Route("{accountId:guid}/owner-product/{accountProductId:guid}/resume")] public async Task<IHttpActionResult> OwnerProductResume(Guid accountId, Guid accountProductId) { return await OwnerProductSuspend(accountId, accountProductId, false); } [HttpPost, Route("{accountId:guid}/owner-product/{accountProductId:guid}/next-rebill-date")] public async Task<IHttpActionResult> OwnerProductNextRebillDate(Guid accountId, Guid accountProductId, [FromUri] DateTime nextRebillDate) { return await CurrentAccountExecuteAsync(async delegate (Account account) { var product = await _authProduct.OwnerProductGetAsync(new AccountProductPair(accountId, accountProductId)); if (object.Equals(product, null) || product.IsDisabled || !product.IsRenewal) return ProductNotFound(); if (!product.IsRenewal || IsLocalSubscription(product.SpId)) return ErrorContent(string.Empty, "You can't change next rebill date for this product."); var subscription = await UpclickClient.SubscriptionDetails(product.SpId); if (object.Equals(subscription, null)) return ErrorContent(string.Empty, "Product is not exists in Customer info(Upclick)."); subscription = await UpclickClient.SubscriptionUpdate(product.SpId, nextRebillDate); DateTime? newNextRebillDate = null; if (string.Equals(subscription.Status.Name, "Active") && !object.Equals(subscription.NextCycleBill, null)) newNextRebillDate = subscription.NextCycleBill.Date; var pair = new AccountProductPair(accountId, product.AccountProductId); if (newNextRebillDate.HasValue) { await _authProduct.ProductNextRebillDateSetAsync(pair, newNextRebillDate); var log = string.Format("Next rebill date has been changed successfully. Product({0}, {1}).", product.ProductName, product.AccountProductId); await LogInsertAsync(log, LogActionTypeEnum.AccountProductNextRebillDateEdit, accountId); } product = await _authProduct.OwnerProductDetailsGetAsync(pair); return Ok(ProductConvertor.OwnerAccountProductConvertor(product)); }, accountId); } [HttpPost, Route("{accountId:guid}/owner-product/{accountProductId:guid}/end-date")] public async Task<IHttpActionResult> OwnerProductEndDate(Guid accountId, Guid accountProductId, [FromUri] DateTime endDate) { return await CurrentAccountExecuteAsync(async delegate (Account account) { var product = await _authProduct.OwnerProductGetAsync(new AccountProductPair(accountId, accountProductId)); if (object.Equals(product, null) || product.IsDisabled) return ProductNotFound(); if (!IsLocalSubscription(product.SpId) || product.IsPPC) return ErrorContent(string.Empty, "You can't change end date for this product."); var pair = new AccountProductPair(accountId, product.AccountProductId); await _authProduct.ProductEndDateSetAsync(pair, endDate); var log = string.Format("End date has been changed successfully. Product({0}, {1}).", product.ProductName, product.AccountProductId); await LogInsertAsync(log, LogActionTypeEnum.AccountProductEndDateEdit, accountId); product = await _authProduct.OwnerProductDetailsGetAsync(pair); return Ok(ProductConvertor.OwnerAccountProductConvertor(product)); }, accountId); } } }<file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.AccountSubEmail.cs using SaaS.Data.Entities.Accounts; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthDbContext { internal async Task AccountEmailSetAsync(AccountSubEmailPending pending) { var sqlParams = new SqlParameter[] { pending.Id.ToSql("accountSubEmailPendingId") }; await ExecuteScalarAsync("[accounts].[pAccountSetEmail]", sqlParams); } internal async Task<List<AccountSubEmail>> AccountSubEmailsGetAsync(Guid accountId) { return await ExecuteReaderCollectionAsync<AccountSubEmail>("[accounts].[pAccountSubEmailGetByAccountId]", CreateSqlParams(accountId)); } internal async Task AccountSubEmailDeleteAsync(int id) { var sqlParams = new SqlParameter[] { id.ToSql("id") }; await ExecuteNonQueryAsync("[accounts].[pAccountSubEmailDeleteById]", sqlParams); } internal async Task<AccountSubEmailPending> AccountSubEmailPendingSetAsync(Guid accountId, string email) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId"), email.ToSql("email") }; return await ExecuteReaderAsync<AccountSubEmailPending>("[accounts].[pAccountSubEmailPendingSet]", sqlParams); } internal async Task<AccountSubEmailPending> AccountSubEmailPendingGetAsync(Guid id) { var sqlParams = new SqlParameter[] { id.ToSql("id") }; return await ExecuteReaderAsync<AccountSubEmailPending>("[accounts].[pAccountSubEmailPendingGetById]", sqlParams); } internal async Task<List<AccountSubEmailPending>> AccountSubEmailPendingsGetAsync(Guid accountId) { return await ExecuteReaderCollectionAsync<AccountSubEmailPending>("[accounts].[pAccountSubEmailPendingGetByAccountId]", CreateSqlParams(accountId)); } internal async Task AccountSubEmailPendingDeleteAsync(Guid accountId) { await ExecuteScalarAsync("[accounts].[pAccountSubEmailPendingDeleteByAccountId]", CreateSqlParams(accountId)); } } }<file_sep>/WinService/SaaS.WinService.eSign/Program.cs using System; namespace SaaS.WinService.eSign { static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main() { if (!Environment.UserInteractive) { var servicesToRun = new System.ServiceProcess.ServiceBase[] { new eSignService() }; System.ServiceProcess.ServiceBase.Run(servicesToRun); } else { using (var worker = new EmailChangeWorker()) worker.Do(10); } } } }<file_sep>/Web.Api/SaaS.Zendesk/tasks/zat.html.js const gulp = require('gulp'); gulp.task('zat.html:assets', () => { return gulp.src('dist/**/*.html') .pipe(gulp.dest('zat/assets')); }); gulp.task('zat.html:watch', () => { return gulp.watch('dist/**/*.html', gulp.series('zat.html:assets')); }); gulp.task('zat.html', gulp.series('zat.html:assets'));<file_sep>/Shared/SaaS.PdfEscape.Api.Client/PdfEscapeClient.cs using System; using System.Net.Http; using System.Net.Http.Headers; namespace SaaS.PdfEscape.Api.Client { public partial class PdfEscapeClient: IPdfEscapeClient { private readonly Uri _uri; public PdfEscapeClient(string uri = "https://www.pdfescape.com") { _uri = new Uri(uri); } private HttpClient CreateHttpClient() { var client = new HttpClient(); client.BaseAddress = _uri; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return client; } } public interface IPdfEscapeClient { } } <file_sep>/Web.Api/SaaS.Zendesk/src/js/controllers/app.js angular.module('app.controllers') .controller('appController', ['$scope', '$state', '$zendesk', '$brand', '$auth', ($scope, $state, $zendesk, $brand, $auth) => { $zendesk.init(); if ($zendesk.isEmpty()) return $state.go('zat/client-not-found'); var _validateBrand = (brand) => { $brand.set(brand); if (!$brand.isSupport()) return $state.go('brand/not-supported', { brandId: brand.id }); $scope.$auth = $auth; $state.go('account', { brandId: brand.id }); }; $zendesk.get(['ticket.brand']) .then((response) => { _validateBrand(response['ticket.brand']); }, () => { $state.go('ticket/not-found'); }); $zendesk.on('ticket.brand.changed', _validateBrand); }]);<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.PaymentInformation.cs using SaaS.Api.Core; using SaaS.Api.Core.Filters; using System; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { [HttpGet, Route("payment-information"), SaaSAuthorize] public async Task<IHttpActionResult> PaymentInformation() { try { var creditCards = await UpclickClient.SubscriptionsPaymentInstruments(User.Identity.Name); if (!object.Equals(creditCards, null)) { foreach (var creditCard in creditCards) { string token = UpclickClient.Token("<PASSWORD>"); Uri uri = new Uri(string.Format("https://billing.upclick.com/{0}/PaymentInstrument/Edit", token)); var query = HttpUtility.ParseQueryString(string.Empty); query.Add("id", HttpUtility.UrlDecode(creditCard.PayTokenID)); var uriBuilder = new UriBuilder(uri); uriBuilder.Query = query.ToString(); creditCard.EditUrl = uriBuilder.Uri.ToString(); } } return Ok(creditCards); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } } } //var identity = new ClaimsIdentity(User.Identity); //var properties = new Dictionary<string, string>(); //var ticket = new AuthenticationTicket(identity, new AuthenticationProperties(properties)); ////authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(Identity), new AuthenticationProperties { IsPersistent = true }); ////var authenticateResult = await authenticationManager.AuthenticateAsync(Startup.OAuthBearerOptions.AuthenticationType); //var propertedToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);<file_sep>/Shared/SaaS.Identity/NpsRepository/NpsRepository.cs using System; using System.Threading.Tasks; namespace SaaS.Identity { public class NpsRepository : INpsRepository { private readonly AuthDbContext _context; public NpsRepository() { _context = new AuthDbContext(); } public async Task Rate(string questioner, Guid? accountId, string clientName, string clientVersion, byte rating, byte? ratingUsage, string comment) { await _context.NpsInsertAsync(questioner, accountId, clientName, clientVersion, rating, ratingUsage, comment); } public void Dispose() { if (!object.Equals(_context, null)) _context.Dispose(); } } }<file_sep>/Shared/SaaS.Api.Models/Products/AccountProductViewModel.cs using System; namespace SaaS.Api.Models.Products { public class AccountProductViewModel : ProductViewModel { public ulong? ExpiresIn { get { if (!EndDate.HasValue) return null; if (EndDate.Value <= DateTime.UtcNow) return 0; return (ulong)(EndDate.Value - DateTime.UtcNow).TotalSeconds; } } } } <file_sep>/Web.Api/SaaS.Api.Admin/Controllers/Api/AccountController.Product.cs using SaaS.Api.Core.Filters; using SaaS.Api.Models.Products; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Admin.Oauth; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Admin.Controllers.Api { public partial class AccountController : SaaSApiController { [HttpPut, Route("{accountId:guid}/product"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> AccountProductPut(Guid accountId, AddOwnerProductViewModel model) { return await CurrentAccountExecuteAsync(async delegate (Account account) { await _authProduct.OwnerProductInsertAsync(accountId, model.ProductUid, model.Currency, model.Price, model.PriceUsd, model.Quantity); var log = string.Format("Product({0}) has been added successfully. Customer's email is {1}.", model.ProductUid, account.Email); await LogInsertAsync(log, LogActionTypeEnum.AccountProductAdd, account.Id); return Ok(); }, accountId); } } }<file_sep>/Web.Api/SaaS.Sso/src/js/app.router.js angular.module('app') .config(($stateProvider, $urlRouterProvider, localStorageServiceProvider) => { localStorageServiceProvider .setPrefix('sso') .setDefaultToCookie(false); // $locationProvider.html5Mode({ // enabled: true, // requireBase: false // }); $urlRouterProvider.otherwise('/en/index'); $stateProvider.state('app', { url: '/:locale', // url: '/:locale/{brand:sodapdf}', //templateUrl: 'index.html', restricted: false, abstract: true, views: { content: { controller: 'appController' }, footer: { templateUrl: 'partial/footer.html', controller: 'partialFooterController' } } }); var _state = (json) => { json.name = json.name || json.url; json.params = json.params || {}; json.templateUrl = json.templateUrl || `views/${json.url}.html`; json.isProtected = !!json.isProtected; var state = { parent: 'app', url: `/${json.url}`, params: json.params, templateUrl: json.templateUrl, controller: `${json.controller}Controller`, isProtected: json.isProtected }; $stateProvider.state(json.name, state); }; _state({ url: 'index', controller: 'index' }); _state({ url: 'account/error', controller: 'accountError' }); _state({ url: 'account/logout', controller: 'accountLogout' }); _state({ url: 'account/identifier', controller: 'accountIdentifier', params: { email: null } }); _state({ url: 'account/password', controller: 'accountPassword', params: { firstName: null, lastName: null, email: null } }); _state({ url: 'account/remove', controller: 'accountRemove' }); _state({ url: 'account/select', controller: 'accountSelect' }); });<file_sep>/Shared/SaaS.Api.Core/HttpExceptionResult.cs using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Core { public class HttpExceptionResult : IHttpActionResult { private Exception _exc; private HttpRequestMessage _request; public HttpExceptionResult(Exception exc, HttpRequestMessage request) { _exc = exc; _request = request; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var response = _request.CreateExceptionResponse(_exc); return Task.FromResult(response); } } } <file_sep>/Web.Api/SaaS.UI.Admin/Controllers/AdminController.cs using System.Web.Mvc; namespace SaaS.UI.Admin.Controllers { [Authorize] public class AdminController : Controller { [Authorize(Roles = "admin")] public ActionResult Logs() { return View(); } [Authorize(Roles = "admin")] public ActionResult Users() { return View(); } public ActionResult Roles() { return View(); } [Authorize(Roles = "admin")] public ActionResult Emails() { return View(); } } }<file_sep>/Shared/SaaS.Data.Entities/Accounts/AccountSurvey.cs using System; namespace SaaS.Data.Entities.Accounts { public class AccountSurvey : AccountEntity<int> { public string Lang { get; set; } public DateTime CreateDate { get; set; } public int? QuizTypeId { get; set; } public byte[] CollectedData { get; set; } } } <file_sep>/Web.Api/SaaS.Api.Admin/Controllers/Api/SaaSApiController.cs using Microsoft.AspNet.Identity; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Admin.Oauth; using SaaS.Identity; using SaaS.Notification; using System; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web.Http; using Upclick.Api.Client; using AuthAdminRepository = SaaS.Identity.Admin.AuthRepository; using AuthRepository = SaaS.Identity.AuthRepository; using IAuthAdminRepository = SaaS.Identity.Admin.IAuthRepository; using IAuthRepository = SaaS.Identity.IAuthRepository; using UserIdentityAdmin = SaaS.Identity.Admin.User; namespace SaaS.Api.Admin.Controllers.Api { public class SaaSApiController : ApiController { protected readonly IAuthRepository _auth; protected readonly IAuthAdminRepository _authAdmin; protected readonly IAuthProductRepository _authProduct; //********** protected readonly IAuthAdminRepository _gdpr; protected static readonly IAppSettings _appSettings = new AppSettings(); public SaaSApiController() { _auth = new AuthRepository(); _auth.SetDataProtectorProvider(Startup.DataProtectionProvider); _authAdmin = new AuthAdminRepository(); _authAdmin.SetDataProtectorProvider(Startup.DataProtectionProvider); _authProduct = new AuthProductRepository(); _gdpr = new AuthAdminRepository("udb"); } private UpclickClient _upclickClient; private NotificationManager _notificationManager; protected UpclickClient UpclickClient { get { _upclickClient = _upclickClient ?? new UpclickClient(_appSettings.Upclick.MerchantLogin, _appSettings.Upclick.MerchantPassword); return _upclickClient; } } protected NotificationManager NotificationManager { get { _notificationManager = _notificationManager ?? new NotificationManager(_auth, new NotificationSettings { DownloadLink = _appSettings.DownloadLink, ResetPassword = _appSettings.Oauth.ResetPassword }); return _notificationManager; } } protected override void Dispose(bool disposing) { _auth.Dispose(); _authAdmin.Dispose(); _authProduct.Dispose(); base.Dispose(disposing); } protected IHttpActionResult GetErrorResult(IdentityResult result) { string error = null; if (object.Equals(result, null)) return ErrorContent(error, httpStatusCode: HttpStatusCode.InternalServerError); if (result.Succeeded) return null; if (!object.Equals(result.Errors, null)) error = result.Errors.FirstOrDefault(); return ErrorContent("invalid_request", error); } protected IHttpActionResult ErrorContent(Exception exc) { return ErrorContent("invalid_request", exc.Message); } protected IHttpActionResult UserNotFound() { return ErrorContent("invalid_grant", "User is not exists.", HttpStatusCode.NotFound); } protected IHttpActionResult AccountNotFound() { return ErrorContent("invalid_grant", "Customer is not exists.", HttpStatusCode.NotFound); } protected IHttpActionResult UserExists() { return ErrorContent("invalid_grant", "User already exists.", HttpStatusCode.Conflict); } protected IHttpActionResult AccountExists() { return ErrorContent("invalid_grant", "Customer already exists.", HttpStatusCode.Conflict); } protected async Task LogInsertAsync(string log, LogActionTypeEnum logActionType, Guid? accountId = null) { await _authAdmin.LogInsertAsync(UserId, accountId, log, logActionType); } protected IHttpActionResult ProductNotFound() { return ErrorContent("invalid_grant", "Product is not exists or is disabled.", HttpStatusCode.NotFound); } protected IHttpActionResult ErrorContent(string error, string description = null, HttpStatusCode httpStatusCode = HttpStatusCode.BadRequest) { return Content<dynamic>(httpStatusCode, new { error = error, error_description = description }); } public Guid UserId { get { return Guid.Parse(User.Identity.GetUserId()); } } protected delegate Task<IHttpActionResult> UserExecuteHandlerAsync(UserIdentityAdmin user); protected async Task<IHttpActionResult> CurrentUserExecuteAsync(UserExecuteHandlerAsync handler) { try { var user = await _authAdmin.UserGetAsync(UserId); if (object.Equals(user, null)) return UserNotFound(); return await handler(user); } catch (Exception exc) { return ErrorContent(exc); } } protected delegate Task<IHttpActionResult> AccountExecuteHandlerAsync(Account account); protected async Task<IHttpActionResult> CurrentAccountExecuteAsync(AccountExecuteHandlerAsync handler, Guid accountId) { try { var account = await _auth.AccountGetAsync(accountId); if (object.Equals(account, null)) return AccountNotFound(); return await handler(account); } catch (Exception exc) { return ErrorContent(exc); } } protected async Task<IHttpActionResult> CurrentAccountExecuteAsync(AccountExecuteHandlerAsync handler, string email, bool isIncludeSubEmails = false) { try { var account = await _auth.AccountGetAsync(email, isIncludeSubEmails: isIncludeSubEmails); if (object.Equals(account, null)) return AccountNotFound(); return await handler(account); } catch (Exception exc) { return ErrorContent(exc); } } } }<file_sep>/Shared/SaaS.ModuleFeatures/MapModule.cs namespace SaaS.ModuleFeatures { public class MapModule { public MapModule(string name, MapFeature[] features) { Name = name; Features = features; } public string Name { get; private set; } public MapFeature[] Features { get; private set; } public void ActivateFeatures() { if (object.Equals(Features, null)) return; foreach (var feature in Features) feature.Activate(); } } } <file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.AccountPreference.cs using SaaS.Data.Entities.Accounts; using System; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthDbContext { internal async Task<AccountPreference> AccountPreferenceGetAsync(Guid accountId) { return await ExecuteReaderAsync<AccountPreference>("[accounts].[pAccountPreferenceGetByAccountId]", accountId); } internal async Task AccountPreferenceSetAsync(Guid accountId, string json) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId"), json.ToSql("json") }; await ExecuteNonQueryAsync("[accounts].[pAccountPreferenceSetByAccountId]", sqlParams); } internal async Task AccountPreferenceDeleteAsync(Guid accountId) { await ExecuteNonQueryAsync("[accounts].[pAccountPreferenceDeleteByAccountId]", CreateSqlParams(accountId)); } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.cs using Newtonsoft.Json.Linq; using SaaS.Api.Models.Products; using SaaS.Data.Entities.View; using SaaS.ModuleFeatures; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web.Hosting; using System.Web.Http; using ValidateAntiForgeryToken = System.Web.Mvc.ValidateAntiForgeryTokenAttribute; namespace SaaS.Api.Controllers.Api.Oauth { [RoutePrefix("api/account"), ValidateAntiForgeryToken] public partial class AccountController : SaaSApiController { private static Map _moduleFeaturesMap; private static string _defaultPreferencesJson; private static readonly HashSet<string> _b2bleadSourceCollection; static AccountController() { _b2bleadSourceCollection = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); #if LuluSoft _b2bleadSourceCollection.Add("sodapdf.com-request-quote"); _b2bleadSourceCollection.Add("sodapdf.com-get-trial"); _b2bleadSourceCollection.Add("sodapdf.com-contact-us"); _b2bleadSourceCollection.Add("sodapdf.com-webinar"); _b2bleadSourceCollection.Add("sodapdf.com-white-paper"); _b2bleadSourceCollection.Add("sodapdf.com-reseller"); #endif var defaultPreferencesFileInfo = new FileInfo(DefaultPreferencesFilePath); _defaultPreferencesJson = defaultPreferencesFileInfo.Exists ? File.ReadAllText(DefaultPreferencesFilePath) : "{}"; _moduleFeaturesMap = string.IsNullOrEmpty(ModuleFeaturesFilePath) ? null : Map.Load(ModuleFeaturesFilePath); } private static JObject DefaultPreferences() { return JObject.Parse(_defaultPreferencesJson); } private static string[] GetJObjectProperties(JObject jObject) { return jObject.Properties() .Select(property => property.Name) .ToArray(); } private static string DefaultPreferencesFilePath { get { #if LuluSoft return HostingEnvironment.MapPath("~/bin/App_GlobalResources/luluSoft-defaultPreferences.json"); #endif #if PdfForge return HostingEnvironment.MapPath("~/bin/App_GlobalResources/pdfForge-defaultPreferences.json"); #endif #if PdfSam return HostingEnvironment.MapPath("~/bin/App_GlobalResources/pdfSam-defaultPreferences.json"); #endif } } private static string ModuleFeaturesFilePath { get { #if LuluSoft return HostingEnvironment.MapPath("~/bin/App_GlobalResources/luluSoft-moduleFeatures.json"); #endif #if PdfForge return HostingEnvironment.MapPath("~/bin/App_GlobalResources/pdfForge-moduleFeatures.json"); #endif #if PdfSam return HostingEnvironment.MapPath("~/bin/App_GlobalResources/pdfSam-moduleFeatures.json"); #endif } } internal static MapModule[] GetModuleFeatures(ViewAccountProduct product, List<AccountProductModuleModel> modules) { if (object.Equals(_moduleFeaturesMap, null)) return null; Version productVersion; Version.TryParse(product.ProductVersion, out productVersion); var mapStrategy = product.IsPPC ? MapStrategy.PerpetualLicense : MapStrategy.Subscription; var moduleFeatures = _moduleFeaturesMap.GetModules(mapStrategy, productVersion); if (!object.Equals(modules, null) && !object.Equals(moduleFeatures, null)) { foreach (var module in modules) { var moduleFeature = moduleFeatures.FirstOrDefault(e => string.Equals(e.Name, module.Module, StringComparison.InvariantCultureIgnoreCase)); if (!object.Equals(moduleFeature, null)) moduleFeature.ActivateFeatures(); } } return moduleFeatures; } } }<file_sep>/Shared/SaaS.Data.Entities/eSign/eSignApiKey.cs using System; using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Data.Entities.eSign { public class eSignApiKey : AccountEntity<int> { [Column("eSignClientId")] public eSignClient eSignClient { get; set; } public string Key { get; set; } public string Email { get; set; } public bool IsNeedRefresh { get; set; } public DateTime CreateDate { get; set; } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.Preferences.cs using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Data.Entities.Accounts; using System; using System.IO; using System.Linq; using System.Runtime.Caching; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { private ObjectCache _cache = MemoryCache.Default; private string GetPreferencesMemoryCacheKey() { return string.Format("account_preferences_{0}", AccountId); } private void RemovePreferencesMemoryCache() { _cache.Remove(GetPreferencesMemoryCacheKey()); } private void SetPreferencesMemoryCache(string value) { _cache.Set(GetPreferencesMemoryCacheKey(), value, DateTimeOffset.UtcNow.AddMinutes(5)); } private string GetPreferencesMemoryCache() { return _cache.Get(GetPreferencesMemoryCacheKey()) as string; } private static void CutExtraPreferences(JObject preferences, string[] categories) { if (object.Equals(categories, null) || categories.Length <= 0) return; var properties = GetJObjectProperties(preferences); foreach (var property in properties) { if (!categories.Contains(property, StringComparer.InvariantCultureIgnoreCase)) preferences.Remove(property); } } [HttpGet, Route("default-preferences")] public IHttpActionResult GetDefaultPreferences([FromUri(Name = "category")] string[] categories = null) { try { var preferences = DefaultPreferences(); CutExtraPreferences(preferences, categories); return Ok(DefaultPreferences()); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpPost, Route("default-preferences")] public async Task<IHttpActionResult> PostDefaultPreferences([FromUri] string key = null) { if (!"rHQ4TQsQJaHgNsLU".Equals(key, StringComparison.InvariantCultureIgnoreCase)) return NotFound(); try { var json = await Request.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(json)) { File.WriteAllText(DefaultPreferencesFilePath, json); _defaultPreferencesJson = json; } } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } [HttpGet, Route("cache-preferences")] public IHttpActionResult GetPreferencesCache() { try { return Ok(new { size = System.Runtime.Caching.MemoryCache.Default.GetCount() }); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpGet, Route("preferences"), SaaSAuthorize] public async Task<IHttpActionResult> GetPreferences([FromUri(Name = "category")] string[] categories = null) { try { var cachePreferences = GetPreferencesMemoryCache(); var dbPreferences = !string.IsNullOrEmpty(cachePreferences) ? new AccountPreference { Json = cachePreferences } : await _auth.AccountPreferenceGetAsync(AccountId); var preferences = !object.Equals(dbPreferences, null) ? JObject.Parse(dbPreferences.Json) : DefaultPreferences(); SetPreferencesMemoryCache(preferences.ToString(Formatting.None)); if (!object.Equals(dbPreferences, null)) { var defaultPreferences = DefaultPreferences(); var defaultPreferencesProperties = GetJObjectProperties(defaultPreferences); foreach (var property in defaultPreferencesProperties) { JToken jValue; if (preferences.TryGetValue(property, StringComparison.InvariantCultureIgnoreCase, out jValue)) continue; preferences.Add(property, defaultPreferences.GetValue(property)); } } CutExtraPreferences(preferences, categories); return Ok(preferences); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpPost, Route("preferences"), SaaSAuthorize] public async Task<IHttpActionResult> PostPreferences([FromUri(Name = "category")] string[] categories = null, bool returnPreferences = false) { try { var json = await Request.Content.ReadAsStringAsync(); var dbPreferences = await _auth.AccountPreferenceGetAsync(AccountId); var preferences = object.Equals(dbPreferences, null) ? new JObject() : JObject.Parse(dbPreferences.Json); var preferencesJson = JObject.Parse(json); foreach (var property in GetJObjectProperties(preferencesJson)) { JToken jValue; if (preferencesJson.TryGetValue(property, StringComparison.InvariantCultureIgnoreCase, out jValue)) { preferences.Remove(property); preferences.Add(property, jValue); } } json = preferences.ToString(Formatting.None); await _auth.AccountPreferenceSetAsync(AccountId, json); SetPreferencesMemoryCache(json); return returnPreferences ? await GetPreferences(categories) : Ok(); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpDelete, Route("preferences"), SaaSAuthorize] public async Task<IHttpActionResult> DeletePreferences([FromUri(Name = "category")] string[] categories = null, bool returnPreferences = false) { try { var dbPreferences = await _auth.AccountPreferenceGetAsync(AccountId); if (!object.Equals(dbPreferences, null)) { var preferences = JObject.Parse(dbPreferences.Json); if (!object.Equals(categories, null) && categories.Length > 0) { foreach (var category in categories.Where(category => !string.IsNullOrEmpty(category))) preferences.Remove(category); } else preferences = new JObject(); var properties = GetJObjectProperties(preferences); if (properties.Length <= 0) await _auth.AccountPreferenceDeleteAsync(AccountId); else { var json = preferences.ToString(Formatting.None); if (!string.Equals(json, dbPreferences.Json, StringComparison.InvariantCultureIgnoreCase)) await _auth.AccountPreferenceSetAsync(AccountId, json); } } RemovePreferencesMemoryCache(); return returnPreferences ? await GetPreferences(categories) : Ok(); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } } }<file_sep>/Web.Api/SaaS.Sso/tasks/app.watch.js const gulp = require('gulp'); gulp.task('app.watch', gulp.parallel( 'app.html:watch', 'app.css:watch', 'app.js:watch', 'app.json:watch')); <file_sep>/Shared/SaaS.IPDetect/IpAddressFilteringSection.cs using System.Configuration; namespace SaaS.IPDetect { public class IpAddressFilteringSection : ConfigurationSection { [ConfigurationProperty("ipAddresses", IsDefaultCollection = true)] public IpAddressElementCollection IpAddresses { get { return (IpAddressElementCollection)this["ipAddresses"]; } set { this["ipAddresses"] = value; } } } } <file_sep>/Shared/SaaS.Identity/EmailRepository/EmailRepository.cs using SaaS.Data.Entities; using SaaS.Data.Entities.Accounts; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Identity { public class EmailRepository : IEmailRepository { private readonly AuthDbContext _context; public EmailRepository() { _context = new AuthDbContext(); } public async Task EmailInsertAsync(Guid accountId, Status status, string emailCustomParam, string modelCustomParam) { await _context.EmailInsertAsync(accountId, status, emailCustomParam, modelCustomParam); } public async Task<List<Email>> EmailsGetAsync(Status status = Status.NotStarted, int top = 10) { return await _context.EmailsGetAsync(status, top); } public async Task EmailStatusSetAsync(int id, Status status) { await _context.EmailStatusSetAsync(id, status); } public void Dispose() { if (!object.Equals(_context, null)) _context.Dispose(); } } }<file_sep>/Web.Api/SaaS.Api/Models/Api/Oauth/SurveyViewModel.cs using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Linq; using Newtonsoft.Json.Linq; using SaaS.Api.Models.Validation; namespace SaaS.Api.Models.Api.Oauth { public class SurveyViewModel { [Required] [MinLength(2)] [MaxLength(2)] public string Lang { get; set; } [Required] public JArray Data { get; set; } } public class SurveySection { public string Id { get; set; } public IEnumerable<SurveySectionGroup> Groups { get; set; } } public class SurveySectionGroup { public string Id { get; set; } public IEnumerable<SurveyQA> Qa { get; set; } } public class SurveyQA { public string Q { get; set; } public string A { get; set; } } public class SectionTableViewModel { public string Id { get; set; } public IList<SectionGroupTableViewModel> Groups { get; set; } public int QaCount { get { return Groups.Sum((group) => group.QAs.Count); } } public SectionTableViewModel(string id) { Id = id; Groups = new List<SectionGroupTableViewModel>(); } } public class SectionGroupTableViewModel { public string Id { get; set; } public IList<string> QAs { get; set; } public SectionGroupTableViewModel(string id) { Id = id; QAs = new List<string>(); } } public class SectionTableRowViewModel { public Guid AccountId { get; set; } public DateTime CreateDate { get; set; } public List<SurveyQATable> QAs { get; set; } public SectionTableRowViewModel(Guid accountId, DateTime createDate) { AccountId = accountId; CreateDate = createDate; QAs = new List<SurveyQATable>(); } } public class SurveyQATable { public string QId { get; set; } public string Q { get; set; } public string A { get; set; } public SurveyQATable(string qId, string q, string a) { QId = qId; Q = q; A = a; } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AdminAccountController.cs using SaaS.Api.Core; using SaaS.Api.Core.Filters; using System; using System.Threading.Tasks; using System.Web.Http; using ValidateAntiForgeryToken = System.Web.Mvc.ValidateAntiForgeryTokenAttribute; namespace SaaS.Api.Controllers.Api.Oauth { [RoutePrefix("api/admin/account"), ValidateAntiForgeryToken, SaaSAuthorize(Roles = "admin")] public partial class AdminAccountController : SaaSApiController { [HttpDelete, Route] public async Task<IHttpActionResult> Delete(Guid userId) { try { var user = await _auth.AccountGetAsync(userId); if (object.Equals(user, null)) return AccountNotFound(); await _auth.AccountDeleteAsync(user); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } } }<file_sep>/Shared/SaaS.Identity/AuthRepository/AuthRepository.AccountSurvey.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using SaaS.Data.Entities.Accounts; namespace SaaS.Identity { public partial class AuthRepository { public async Task SurveyAsync(Guid accountId, byte[] data, string lang) { await _context.SurveyAsync(accountId, data, lang); } public async Task<List<AccountSurvey>> GetAllSurveyAsync() { return await _context.GetAllSurveyAsync(); } } } <file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.AccountSurvey.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; using SaaS.Data.Entities.Accounts; namespace SaaS.Identity { public partial class AuthDbContext { internal async Task SurveyAsync(Guid accountId, byte[] data, string lang) { var action = 1; // INSERT var sqlParams = new SqlParameter[] { accountId.ToSql("accountID"), data.ToSql("collectedData"), lang.ToSql("lang"), action.ToSql("action") }; await ExecuteNonQueryAsync("[accounts].[pAccountQuiz]", sqlParams); } internal async Task<List<AccountSurvey>> GetAllSurveyAsync() { var query = "SELECT * FROM [accounts].[accountQuiz]"; return await ExecuteReaderCollectionAsync<AccountSurvey>(query, new SqlParameter[]{ }); } } } <file_sep>/Shared/SaaS.Api.Core/FormIdBuilder.cs using System.Text; using System.Text.RegularExpressions; using System.Web; namespace SaaS.Api.Core { public static class FormIdBuilder { private static readonly Regex _hostRegex = new Regex(@"^www[0-9]*\.", _regexOptions); private static readonly RegexOptions _regexOptions = RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline; public static string Build(string formId, string suffix = null) { if (string.IsNullOrEmpty(formId)) return null; var builder = new StringBuilder(formId.Replace("_", "-")); if (!string.IsNullOrEmpty(suffix)) builder.Append(suffix); var urlReferrer = HttpContext.Current?.Request?.UrlReferrer; if (!object.Equals(urlReferrer, null)) { var host = _hostRegex.Replace(urlReferrer.Host, string.Empty); var localPath = urlReferrer.LocalPath .TrimEnd('/') .Replace("/", "."); builder.AppendFormat("-{0}{1}", host, localPath); } return builder.ToString(); } } } <file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AdminAccountController.UpclickProduct.cs using SaaS.Api.Core.Filters; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AdminAccountController { [HttpGet, Route("upclick-products"), SaaSAuthorize] public async Task<IHttpActionResult> Products() { return Ok(await _authProduct.UpclickProductsGetAsync()); } } }<file_sep>/Shared/SaaS.MailerWorker/Jobs/RegularMailingJob.cs using NLog; using Quartz; using System; namespace SaaS.MailerWorker.Jobs { [DisallowConcurrentExecution] public class RegularMailingJob : IMailingJob { private static readonly Logger _logger = LogManager.GetLogger("Logs"); private static readonly Logger _errorsLogger = LogManager.GetLogger("Errors"); public void Execute(IJobExecutionContext context) { try { new EmailWorker().StartAsync().Wait(); } catch (Exception exc) { _errorsLogger.Error(exc); throw new JobExecutionException(exc); } } } public interface IMailingJob : IJob { } } <file_sep>/Shared/SaaS.Mailer/Models/MergeConfirmationNotification.cs using System.Xml.Serialization; namespace SaaS.Mailer.Models { [XmlRoot("xml")] public class MergeConfirmationNotification : Notification { public MergeConfirmationNotification() { } public MergeConfirmationNotification(Notification user, string confirmationLink) : base(user) { ConfirmationLink = confirmationLink; } [XmlElement("confirmationLink")] public string ConfirmationLink { get; set; } } }<file_sep>/Shared/SaaS.Api.Core/HttpRequestMessageExtensions.cs using NLog; using System; using System.Net; using System.Net.Http; namespace SaaS.Api.Core { public static class HttpRequestMessageExtensions { private static Logger _oauthLogLogger = LogManager.GetLogger("oauth-log"); public static HttpResponseMessage CreateExceptionResponse(this HttpRequestMessage request, Exception exc, HttpStatusCode statusCode = HttpStatusCode.BadRequest) { var response = request.CreateExceptionResponse(errorDescription: "An unexpected error has occurred. Please try again later.", statusCode: statusCode); if (!object.Equals(exc, null)) { _oauthLogLogger.Error(exc); response.Headers.Add("Exc-Message", exc.Message.Replace(Environment.NewLine, string.Empty)); } return response; } public static HttpResponseMessage CreateExceptionResponse(this HttpRequestMessage request, string error = "invalid_request", string errorDescription = null, HttpStatusCode statusCode = HttpStatusCode.BadRequest) { var response = request.CreateResponse(statusCode, new { error = error, error_description = errorDescription }); return response; } public static HttpExceptionResult HttpExceptionResult(this HttpRequestMessage request, Exception exc) { return new HttpExceptionResult(exc, request); } } }<file_sep>/Web.Api/SaaS.Zendesk/tasks/app.font.js const gulp = require('gulp'); gulp.task('app.font:font-awesome-5', () => { return gulp.src(['node_modules/font-awesome-5-css/webfonts/**/*.*']) .pipe(gulp.dest('dist/webfonts')) }); gulp.task('app.font', gulp.parallel('app.font:font-awesome-5'));<file_sep>/Web.Api/SaaS.Api.Admin/Oauth/Providers/SaaSRefreshTokenProvider.cs using Microsoft.Owin.Security; using Microsoft.Owin.Security.Infrastructure; using SaaS.Data.Entities.Admin.Oauth; using SaaS.Identity.Admin; using System; using System.Threading.Tasks; namespace SaaS.Api.Admin.Oauth.Providers { public class SaaSRefreshTokenProvider : IAuthenticationTokenProvider { private static ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get { return Startup.OAuthBearerOptions.AccessTokenFormat; } } public async Task CreateAsync(AuthenticationTokenCreateContext context) { var issued = DateTime.UtcNow; var expires = issued.Add(Startup.OAuthServerOptions.AccessTokenExpireTimeSpan); context.Ticket.Properties.IssuedUtc = issued; context.Ticket.Properties.ExpiresUtc = expires; var sessionToken = new SessionToken { Id = Guid.NewGuid(), IssuedUtc = issued, ExpiresUtc = expires, ProtectedTicket = AccessTokenFormat.Protect(context.Ticket) }; using (var auth = new AuthRepository()) await auth.SessionTokenInsertAsync(sessionToken); context.SetToken(sessionToken.Id.ToString("N")); } public async Task ReceiveAsync(AuthenticationTokenReceiveContext context) { Guid id; if (!Guid.TryParseExact(context.Token, "N", out id)) return; SessionToken token = null; using (var auth = new AuthRepository()) token = await auth.SessionTokenGetAsync(id); if (!object.Equals(token, null)) { var ticket = AccessTokenFormat.Unprotect(token.ProtectedTicket); var issued = DateTime.UtcNow; var expires = issued.Add(Startup.OAuthServerOptions.AccessTokenExpireTimeSpan); ticket.Properties.IssuedUtc = issued; ticket.Properties.ExpiresUtc = expires; context.SetTicket(ticket); } else { context.Response.Headers.Add("Refresh-Token-Expired", new[] { "token: " + (context.Token ?? string.Empty) }); context.Response.Headers.Add("Access-Control-Expose-Headers", new[] { "Refresh-Token-Expired" }); } } public void Create(AuthenticationTokenCreateContext context) { throw new NotImplementedException(); } public void Receive(AuthenticationTokenReceiveContext context) { throw new NotImplementedException(); } } }<file_sep>/Web.Api/SaaS.Api.Mc/Filters/SaaSAnonymousAttribute.cs using System.Net; using System.Net.Http; using System.Web.Http.Controllers; namespace SaaS.Api.Mc.Filters { public class SaaSAnonymousAttribute : System.Web.Http.AuthorizeAttribute { public override void OnAuthorization(HttpActionContext actionContext) { var authorization = actionContext.Request.Headers.Authorization; if (object.Equals(authorization, null)) return; base.OnAuthorization(actionContext); } protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { var response = actionContext.Request.CreateResponse<dynamic>(HttpStatusCode.Unauthorized, new { error = "invalid_grant", error_description = "Authorization has been denied for this request." }); actionContext.Response = response; } } }<file_sep>/Shared/SaaS.Oauth2/Services/OauthService.cs using SaaS.Oauth2.Core; using System.Drawing; using System.Threading; using System.Threading.Tasks; namespace SaaS.Oauth2.Services { public abstract class OauthService { protected ClientProvider _clientProvider; protected OauthService(ClientProvider clientProvider) { _clientProvider = clientProvider; } public abstract string GetAuthenticationUrl(string lang); public abstract Size GetWindowSize(); public abstract Task<TokenResult> TokenAsync(string code, CancellationToken cancellationToken); public abstract Task<ProfileResult> ProfileAsync(TokenResult token, CancellationToken cancellationToken); } }<file_sep>/Shared/SaaS.Data.Entities.Admin/Oauth/LogActionType.cs namespace SaaS.Data.Entities.Admin.Oauth { public class LogActionType : Entity<int> { public string Name { get; set; } } public enum LogActionTypeEnum { UserActivate = 1, UserDeactivate = 2, UserEdit = 3, UserCreate = 4, UserEditPassword = 5, AccountCreate = 6, AccountEdit = 7, AccountDelete = 8, AccountMaskBusiness = 9, AccountActivate = 10, AccountChangePassword = 11, AccountProductAdd = 12, AccountProductAssign = 13, AccountProductUnassign = 14, AccountProductDeactivate = 15, AccountMerge = 16, AccountProductNextRebillDateEdit = 17, AccountProductEndDateEdit = 18 } }<file_sep>/Shared/SaaS.Oauth2/Core/ClientProvider.cs using SaaS.Oauth2.Configuration; namespace SaaS.Oauth2.Core { public abstract class ClientProvider { protected ClientProvider() { } protected ClientProvider(OauthConfigurationElement oauth) { ClientId = oauth.ClientId; ClientSecret = oauth.ClientSecret; CallBackUrl = oauth.CallbackUrl; Scope = oauth.Scope; } public string ClientId { get; set; } public string ClientSecret { get; set; } public string CallBackUrl { get; set; } public string Scope { get; set; } public string AccessToken { get; set; } public string TokenSecret { get; set; } } } <file_sep>/Shared/SaaS.Api.Core/Localization/LanguageMessageHandler.cs using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; namespace SaaS.Api.Core.Localization { public class LanguageMessageHandler : DelegatingHandler { private static readonly StringComparer _stringComparer = StringComparer.InvariantCultureIgnoreCase; private static readonly Dictionary<string, CultureInfo> _cultures = new Dictionary<string, CultureInfo>(_stringComparer) { }; static LanguageMessageHandler() { _cultures.Add("en", new CultureInfo("en-US")); _cultures.Add("fr", new CultureInfo("fr-FR")); _cultures.Add("de", new CultureInfo("de-DE")); _cultures.Add("it", new CultureInfo("it-IT")); _cultures.Add("es", new CultureInfo("es-ES")); _cultures.Add("pt", new CultureInfo("pt-PT")); _cultures.Add("ru", new CultureInfo("ru-RU")); _cultures.Add("jp", new CultureInfo("ja-JP")); _cultures.Add("ja", new CultureInfo("ja-JP")); } private CultureInfo CultureInfo(HttpRequestMessage request) { foreach (var lang in request.Headers.AcceptLanguage) { if (string.IsNullOrEmpty(lang.Value) || lang.Value.Length < 2) continue; var language = lang.Value.Substring(0, 2); if (_cultures.ContainsKey(language)) return _cultures[language]; } return _cultures.First().Value; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var culture = CultureInfo(request); request.Headers.AcceptLanguage.Clear(); request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue(culture.Name)); return await base.SendAsync(request, cancellationToken); } } } <file_sep>/Web.Api/SaaS.Api.Mc/Controllers/Api/v1/MessagesController.cs using Microsoft.AspNet.Identity; using Newtonsoft.Json.Linq; using SaaS.Api.Mc.Filters; using System; using System.Net.Http; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Mc.Controllers.Api.v1 { [RoutePrefix("api/v{version:int:regex(1|2)}/messages")] public class MessagesController : BaseApiController { protected override string ApiRoot { get { var uri = Request.RequestUri; if (uri.AbsolutePath.IndexOf("api/v1/messages", StringComparison.InvariantCultureIgnoreCase) != -1) return "api/v1/messages/"; return "api/v2/messages/"; } } [Route("{*url}"), HttpGet, HttpPost, HttpPut, HttpDelete] public async Task<HttpResponseMessage> Index(CancellationToken cancellationToken) { return await HttpProxy(Request, Request.RequestUri.LocalPath, cancellationToken); } private JObject InjectUserIdentity(JObject jObject, string key) { jObject.Remove(key); var jChild = new JObject(); jObject.Add(key, jChild); return jChild; } private void InjectUserIdentity(JObject jObject) { var jUser = InjectUserIdentity(jObject, "user"); var jIdentity = InjectUserIdentity(jUser, "identity"); jIdentity.Add("isAuthenticated", User.Identity.IsAuthenticated); if (User.Identity.IsAuthenticated) { jIdentity.Add("id", User.Identity.GetUserId()); jIdentity.Add("name", User.Identity.Name); var claimIdentity = User.Identity as ClaimsIdentity; if (!object.Equals(claimIdentity, null)) { var statusClaim = claimIdentity.FindFirstValue("status"); uint status; if (uint.TryParse(statusClaim, out status)) jUser.Add("status", status); var jClaims = new JArray(); var moduleClaims = claimIdentity.FindAll("module"); foreach (var claim in moduleClaims) { var jClaim = new JObject(); jClaim.Add("type", claim.Type); jClaim.Add("value", claim.Value); jClaims.Add(jClaim); } jIdentity.Add("claims", jClaims); } } } private async Task<HttpResponseMessage> InjectUserIdentity(string method, CancellationToken cancellationToken) { if (!Request.Content.IsMimeMultipartContent()) { var jObject = new JObject(); string json = await Request.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(json)) jObject = JObject.Parse(json); InjectUserIdentity(jObject); var content = new StringContent(jObject.ToString()); content.Headers.ContentDisposition = Request.Content.Headers.ContentDisposition; content.Headers.ContentType = Request.Content.Headers.ContentType; Request.Content = content; } return await HttpProxy(Request, method, cancellationToken); } [Route, HttpPost, SaaSAnonymousAttribute] public async Task<HttpResponseMessage> Messages(CancellationToken cancellationToken) { return await InjectUserIdentity(Format(), cancellationToken); } [Route("{messageId:guid}/banner"), HttpGet] public async Task<HttpResponseMessage> PackagesBanner(Guid messageId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/banner", messageId), cancellationToken); } [Route("{messageId:guid}/content"), HttpGet] public async Task<HttpResponseMessage> PackagesContent(Guid messageId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/content", messageId), cancellationToken); } [Route("{messageId:guid}/notification"), HttpGet] public async Task<HttpResponseMessage> PackagesNotification(Guid messageId, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/notification", messageId), cancellationToken); } } }<file_sep>/Shared/SaaS.ModuleFeatures/Model/Root.cs using System; namespace SaaS.ModuleFeatures.Model { internal class Root { public string LatestVersion { get; set; } public Module[] Modules { get; set; } public Version GetLatestVersion() { return System.Version.Parse(LatestVersion); } } }<file_sep>/Shared/SaaS.Common/Extensions/StringExtensions.cs using System; using System.Security.Cryptography; namespace SaaS.Common.Extensions { public static class StringExtensions { private const string _keyforhashing = "<KEY>"; public static string EncryptString(this string texttoencrypt) { if (string.IsNullOrEmpty(texttoencrypt)) throw new ArgumentNullException("texttoencrypt can not be null or empty"); var rijndaelCipher = new RijndaelManaged(); var plainText = System.Text.Encoding.Unicode.GetBytes(texttoencrypt); var salt = System.Text.Encoding.ASCII.GetBytes(_keyforhashing.Length.ToString()); var encryptedData = ""; //var secretKey = new Rfc2898DeriveBytes(_keyforhashing, salt); var secretKey = new PasswordDeriveBytes(_keyforhashing, salt); //Creates a symmetric encryptor object. ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)); using (var memoryStream = new System.IO.MemoryStream()) { //Defines a stream that links data streams to cryptographic transformations using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainText, 0, plainText.Length); cryptoStream.FlushFinalBlock(); var cipherBytes = memoryStream.ToArray(); encryptedData = Convert.ToBase64String(cipherBytes); } } return encryptedData; } public static string DecryptString(this string texttodecrypt) { if (string.IsNullOrWhiteSpace(texttodecrypt)) throw new ArgumentNullException("texttodecrypt can not be null or empty"); var rijndaelCipher = new RijndaelManaged(); var encryptedData = Convert.FromBase64String(texttodecrypt); var salt = System.Text.Encoding.ASCII.GetBytes(_keyforhashing.Length.ToString()); var decryptedData = ""; //Making of the key for decryption //var secretKey = new Rfc2898DeriveBytes(_keyforhashing, salt); var secretKey = new PasswordDeriveBytes(_keyforhashing, salt); //Creates a symmetric Rijndael decryptor object. ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)); using (var memoryStream = new System.IO.MemoryStream(encryptedData)) { //Defines the cryptographics stream for decryption.THe stream contains decrpted data using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { var plainText = new byte[encryptedData.Length]; var decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length); decryptedData = System.Text.Encoding.Unicode.GetString(plainText, 0, decryptedCount); } } return decryptedData; } public static bool IsValidGuid(this string str) { Guid guid; return Guid.TryParse(str, out guid); } public static bool IsValidGuid(this string str, out Guid guid) { return Guid.TryParse(str, out guid); } } } <file_sep>/Shared/SaaS.Identity.Admin/AuthRepository/IAuthRepository.cs using Microsoft.AspNet.Identity; using Microsoft.Owin.Security.DataProtection; using SaaS.Data.Entities.Admin.Oauth; using SaaS.Data.Entities.Admin.View; using SaaS.Data.Entities.Admin.View.Oauth; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Identity.Admin { public interface IAuthRepository : IDisposable { void SetDataProtectorProvider(IDataProtectionProvider dataProtectorProvider); /*******************************************User****************************************************/ Task<User> UserGetAsync(Guid userId); Task<User> UserGetAsync(string login); Task UserSetActiveAsync(Guid userId, bool isActive); Task<IdentityResult> UserChangePasswordAsync(Guid userId, string oldPassword, string newPassword); Task<ViewUser> ViewUserGetAsync(Guid userId); Task<List<ViewUser>> ViewUsersGetAsync(); Task ViewUserSetAsync(ViewUser user); Task ViewUserInsertAsync(ViewUser user); Task<string> AccountGDPRDeleteAsync(string email); /*******************************************Log*****************************************************/ Task<List<ViewLog>> LogsGetAsync(DateTime from, DateTime to, Guid? userId, string log, LogActionTypeEnum? logActionType); Task LogInsertAsync(Guid userId, Guid? accountId, string log, LogActionTypeEnum logActionType); Task<List<LogActionType>> LogActionTypesGetAsync(); /*******************************************SessionToken********************************************/ Task<SessionToken> SessionTokenGetAsync(Guid id); Task SessionTokenInsertAsync(SessionToken token); } } <file_sep>/Web.Api/SaaS.Api.Sign/Controllers/Api/ESign20/SignersController.cs using SaaS.Api.Core.Filters; using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Sign.Controllers.Api.eSign20 { [RoutePrefix("api-esign20/v1/signers"), SaaSAuthorize] public class ESignSignersController : BaseApiController { protected override string ApiRoot { get { return "api/v1/signers/"; } } [Route("{*url}"), HttpGet, HttpPost, HttpPut, HttpDelete] public async Task<HttpResponseMessage> Index(CancellationToken cancellationToken) { return await HttpProxy(Request, Request.RequestUri.LocalPath, cancellationToken); } [Route, HttpGet, HttpPost] public async Task<HttpResponseMessage> Signers(CancellationToken cancellationToken) { return await HttpProxy(Request, Format(), cancellationToken); } [Route("{id:guid}"), HttpPut, HttpDelete] public async Task<HttpResponseMessage> Signers(Guid id, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}", id), cancellationToken); } [Route("order"), HttpPut] public async Task<HttpResponseMessage> Order(CancellationToken cancellationToken) { return await HttpProxy(Request, Format("order"), cancellationToken); } } } <file_sep>/Web.Api/SaaS.Zendesk/tasks/zat.font.js const gulp = require('gulp'); gulp.task('zat.font:webfonts', () => { return gulp.src('dist/webfonts/**') .pipe(gulp.dest('zat/assets/webfonts')); }); gulp.task('zat.font', gulp.series('zat.font:webfonts'));<file_sep>/Shared/SaaS.Data.Entities.Admin/Oauth/User.cs using Microsoft.AspNet.Identity; using SaaS.Data.Entities.Admin; using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Identity.Admin { public class User : Entity<Guid>, IUser<Guid> { [Required, MaxLength(330)] public string Login { get; set; } [DataType(DataType.Password), MaxLength(50)] public string Password { get; set; } public bool IsActive { get; set; } [NotMapped] public string UserName { get { return string.Empty; } set { } } } } <file_sep>/Shared/SaaS.Data.Entities/View/ViewAccountMicrotransactionModule.cs using System; namespace SaaS.Data.Entities.View { public class ViewAccountMicrotransactionModule { public Guid AccountMicrotransactionId { get; set; } public string Module { get; set; } } }<file_sep>/WinService/SaaS.WinService.Mailer/ProjectInstaller.cs using System.Collections; using System.ComponentModel; namespace SaaS.WinService.Mailer { [RunInstaller(true)] public partial class ProjectInstaller : System.Configuration.Install.Installer { public ProjectInstaller() { InitializeComponent(); } protected override void OnBeforeInstall(IDictionary savedState) { SetServiceName(); base.OnBeforeInstall(savedState); } protected override void OnBeforeUninstall(IDictionary savedState) { SetServiceName(); base.OnBeforeUninstall(savedState); } private void SetServiceName() { if (Context.Parameters.ContainsKey("ServiceName")) this.serviceInstaller.ServiceName = Context.Parameters["ServiceName"]; if (Context.Parameters.ContainsKey("DisplayName")) this.serviceInstaller.DisplayName = Context.Parameters["DisplayName"]; } } } <file_sep>/Web.Api/SaaS.Zendesk/src/js/controllers/brand/not-supported.js angular.module('app.controllers') .controller('brandNotSupportedController', ['$scope', '$brand', ($scope, $brand) => { $scope.model = { logo: $brand.get().logo.contentUrl }; }]);<file_sep>/Web.Api/SaaS.Zendesk/src/js/controllers/account/external-session-tokens.js angular.module('app.controllers') .controller('accountExternalSessionTokensController', ['$scope', '$state', '$api', ($scope, $state, $api) => { $scope.isLoading = true; $scope.model = { accountId: $state.params.accountId, externalSessionTokens: null }; $api.account.getExternalSessionTokens({ accountId: $scope.model.accountId }).then((json) => { $scope.model.externalSessionTokens = json; }); }]);<file_sep>/Shared/SaaS.Identity.Admin/AuthDbContext.Sql/AuthDbContext.Sql.User.cs using SaaS.Common.Extensions; using SaaS.Data.Entities.Admin.View.Oauth; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace SaaS.Identity.Admin { public partial class AuthDbContext { internal bool PasswordIsEqual(string source, string password) { return string.Equals(source, password.GetMD5Hash(), StringComparison.InvariantCultureIgnoreCase); } internal async Task<User> UserGetAsync(Guid userId) { var sqlParams = new SqlParameter[] { userId.ToSql("id") }; return await ExecuteReaderAsync<User>("[oauth].[pUserGetById]", sqlParams); } internal async Task<User> UserGetAsync(string login) { var sqlParams = new SqlParameter[] { login.ToSql("login") }; return await ExecuteReaderAsync<User>("[oauth].[pUserGetByLogin]", sqlParams); } internal async Task UserSetActiveAsync(Guid userId, bool isActive) { var sqlParams = new SqlParameter[] { userId.ToSql("id"), isActive.ToSql("isActive") }; await ExecuteNonQueryAsync("[oauth].[pUserSetActive]", sqlParams); } internal async Task<ViewUser> ViewUserGetAsync(Guid userId) { var sqlParams = new SqlParameter[] { userId.ToSql("id") }; return await ExecuteReaderAsync<ViewUser>("[oauth].[vUserGetById]", sqlParams); } internal async Task<ViewUser> ViewUserGetAsync(string login, string password) { var sqlParams = new SqlParameter[] { login.ToSql("login") }; var user = await ExecuteReaderAsync<ViewUser>("[oauth].[vUserGetByLogin]", sqlParams); if (!object.Equals(user, null) && !PasswordIsEqual(user.Password, password)) user = null; return user; } internal async Task<List<ViewUser>> ViewUsersGetAsync() { return await ExecuteReaderCollectionAsync<ViewUser>("[oauth].[vUserGet]", new SqlParameter[] { }); } internal async Task ViewUserSetAsync(ViewUser user) { var password = string.IsNullOrEmpty(user.Password) ? null : user.Password.Trim().GetMD5Hash(); var sqlParams = new SqlParameter[] { user.Id.ToSql("id"), user.Login.ToSql("login"), password.ToSql("<PASSWORD>"), user.Role.ToSql("role") }; await ExecuteNonQueryAsync("[oauth].[vUserSet]", sqlParams); } internal async Task ViewUserInsertAsync(ViewUser user) { var password = string.IsNullOrEmpty(user.Password) ? null : user.Password.Trim().GetMD5Hash(); var sqlParams = new SqlParameter[] { user.Login.ToSql("login"), password.ToSql("password"), user.Role.ToSql("role") }; await ExecuteNonQueryAsync("[oauth].[vUserInsert]", sqlParams); } internal async Task<string> AccountGDPRDeleteAsync(string userEmail) { var error=""; try { var sqlParams = new SqlParameter[] { 1.ToSql("action"), 1.ToSql("sourceID"), 6.ToSql("typeID"), userEmail.ToSql("userEmail") }; var status = await ExecuteNonQueryAsync("[gdpr].[pQueue]", sqlParams); if (status == -1) { var data = await ExecuteNonQueryOutParamAsync("[gdpr].[pQueue_Process]", userEmail); if (data.Length > 0) return "success"; } } catch (Exception ex) { error = ex.Message; } return error; } } }<file_sep>/Shared/SaaS.Identity/AuthRepository/IAuthRepository.cs using Microsoft.AspNet.Identity; using Microsoft.Owin.Security.DataProtection; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View; using SaaS.Data.Entities.View.Accounts; using SaaS.Data.Entities.View.Oauth; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Threading.Tasks; namespace SaaS.Identity { public interface IAuthRepository : IDisposable { void SetDataProtectorProvider(IDataProtectionProvider dataProtectorProvider); /*******************************************Account*****************************************************/ string HashPassword(string password); bool PasswordIsEqual(string source, string password); Task<Account> AccountGetAsync(Guid accountId); Task<Account> AccountGetAsync(string email, bool isIncludeSubEmails = false); Task<Account> AccountGetAsync(string email, string password); Task<Account> AccountGetByTransactionOrderUidAsync(string transactionOrderUid); Task<List<Account>> AccountsGetAsync(string filter, string globalOrderId); Task AccountDeleteAsync(Guid accountId); Task AccountDeleteAsync(Account user); Task AccountActivateAsync(Account user); Task AccountMaskAsBusinessAsync(Account user); Task AccountOptinSetAsync(Account account, bool? optin); Task AccountVisitorIdSetAsync(Account account, Guid? visitorId); Task<IdentityResult> AccountCreateAsync(Account user, string password = ""); Task<IdentityResult> AccountChangePasswordAsync(Guid accountId, string oldPassword, string newPassword); Task<IdentityResult> AccountConfirmEmailAsync(Guid accountId); Task<IdentityResult> AccountConfirmEmailAsync(Guid accountId, string token); Task<IdentityResult> AccountResetPasswordAsync(Guid accountId, string token, string password); Task<IdentityResult> AccountUpdateAsync(Account user); Task<IdentityResult> AccountPasswordSetAsync(Account user, string password); List<ViewAccountEmail> AccountEmailsGet(Guid accountId); Task<List<AccountSystem>> AccountSystemsGetAsync(AccountProductPair pair); Task<Account> AccountAnonymousCreateAsync(string password); /*******************************************AccountDetails*****************************************************/ Task<ViewAccountDetails> AccountDetailsGetAsync(Guid accountId); Task AccountDetailsSetAsync(ViewAccountDetails accountDetail); Task<int?> AccountUidGetAsync(Guid accountId); /*******************************************AccountPreference*****************************************************/ Task<AccountPreference> AccountPreferenceGetAsync(Guid accountId); Task AccountPreferenceSetAsync(Guid accountId, string json); Task AccountPreferenceDeleteAsync(Guid accountId); /*******************************************AccountSubEmailPending*****************************************************/ Task AccountEmailSetAsync(AccountSubEmailPending pending); Task<List<AccountSubEmail>> AccountSubEmailsGetAsync(Guid accountId); Task AccountSubEmailDeleteAsync(int id); Task<AccountSubEmailPending> AccountSubEmailPendingSetAsync(Guid accountId, string email); Task<AccountSubEmailPending> AccountSubEmailPendingGetAsync(Guid id); Task<List<AccountSubEmailPending>> AccountSubEmailPendingsGetAsync(Guid accountId); Task AccountSubEmailPendingDeleteAsync(Guid accountId); /*******************************************Client*****************************************************/ List<Client> ClientsGet(); /*******************************************AccountMergePending*****************************************************/ Task AccountMergeAsync(ViewAccountMergePending pending); Task<ViewAccountMergePending> AccountMergePendingMergeAsync(Guid accountIdTo, Guid accountIdFrom, Guid accountIdPrimaryEmail); Task<ViewAccountMergePending> AccountMergePendingGetAsync(Guid id); Task<List<ViewAccountMergePending>> AccountMergePendingsGetAsync(Guid accountId); Task AccountMergePendingDeleteAsync(Guid accountId); /*******************************************Link*************************************************************/ Task<Uri> GeneratePasswordResetTokenLinkAsync(Account user, Uri uri); Task<NameValueCollection> GenerateEmailConfirmationToken(Account user); Task<Uri> GenerateEmailConfirmationTokenLinkAsync(Account user, Uri uri); Uri GenerateEmailChangeConfirmationTokenLinkAsync(Uri uri, AccountSubEmailPending pending); Uri GenerateMergeConfirmationTokenLinkAsync(Uri uri, ViewAccountMergePending pending); /*******************************************OauthSystem*****************************************************/ Task<OauthSystem> SystemInsertAsync(OauthSystem system); /*******************************************SessionToken*****************************************************/ Task<SessionToken> SessionTokenGetAsync(Guid id); Task<List<SessionToken>> SessionTokensGetAsync(Guid accountId); Task SessionTokenDeleteAsync(Guid id); Task SessionTokenInsertAsync(SessionToken token, Guid? oldId, bool isRemoveOldSessions, bool isInsertAccountSystem); /*******************************************SessionTokenExternalHistory*****************************************************/ Task<List<ViewSessionTokenExternalHistory>> SessionTokenExternalHistoriesAsync(Guid accountId); Task SessionTokenExternalHistorySetAsync(Guid accountId, string externalClientName, string externalAccountId, string email); Task SessionTokenExternalHistoryConnectAccountAsync(Guid accountId, string externalClientName, string externalAccountId, string email); Task SessionTokenExternalHistorySetStateAsync(Guid id, bool isUnlinked); /*******************************************Survey*****************************************************/ Task SurveyAsync(Guid accountId, byte[] data, string lang); Task<List<AccountSurvey>> GetAllSurveyAsync(); } }<file_sep>/Shared/SaaS.Common/Extensions/XMLSerializer.cs using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; namespace SaaS.Common.Extensions { public class XMLSerializer { public static string SerializeObject<T>(T obj) where T : new() { try { using (var memoryStream = new MemoryStream()) { var xs = new XmlSerializer(typeof (T)); var xmlwtSettings = new XmlWriterSettings(); xmlwtSettings.OmitXmlDeclaration = true; xmlwtSettings.Encoding = Encoding.UTF8; using (var xmlTextWriter = XmlWriter.Create(memoryStream, xmlwtSettings)) { var ns = new XmlSerializerNamespaces(); ns.Add("", ""); xs.Serialize(xmlTextWriter, obj, ns); } memoryStream.Seek(0, SeekOrigin.Begin); using (var sr = new StreamReader(memoryStream)) { return sr.ReadToEnd(); } } } catch { return string.Empty; } } public static T DeserializeObject<T>(string xml) where T : new() { XmlSerializer xs = new XmlSerializer(typeof (T)); using (MemoryStream memoryStream = new MemoryStream(new UTF8Encoding().GetBytes(xml))) { return (T) xs.Deserialize(memoryStream); } } } } <file_sep>/WinService/SaaS.WinService.Mailer.Qa/Sender.cs using SaaS.Identity; using SaaS.Mailer; using SaaS.Mailer.Models; using System; using System.Collections.Generic; namespace SaaS.WinService.Mailer.Qa { internal static class Sender { static IAuthRepository auth = new AuthRepository(); internal static void AccountCreationCompleteNotification(string language, Notification notification) { notification = new RecoverPasswordNotification(notification, "https://sodapdf.com"); Send(language, EmailTemplate.AccountCreationCompleteNotification, notification); } internal static void BusinessToPremiumNotification(string language, Notification notification) { Send(language, EmailTemplate.BusinessToPremiumNotification, notification); } internal static void eSignEmailConfirmationNotification(string language, Notification notification) { notification = new EmailConfirmationNotification(notification, "https://sodapdf.com/"); Send(language, EmailTemplate.eSignEmailConfirmationNotification, notification); } internal static void eSignSignPackageNotification(string language, Notification notification) { Send(language, EmailTemplate.eSignSignPackageNotification, notification); } internal static void MicrotransactionCreatePassword(string language, Notification notification) { notification = new WelcomePurchaseNotification(notification, string.Empty) { CreatePasswordLink = "https://sodapdf.com/", }; Send(language, EmailTemplate.MicrotransactionCreatePasswordNotification, notification); } internal static void MergeConfirmation(string language, Notification notification) { notification = new MergeConfirmationNotification(notification, "https://sodapdf.com/"); Send(language, EmailTemplate.MergeConfirmationNotification, notification); } internal static void PasswordChangedNotification(string language, Notification notification) { Send(language, EmailTemplate.PasswordChangedNotification, notification); } internal static void ProductAssignedNotificationCreatePassword(string language, Notification notification) { Send(language, EmailTemplate.ProductAssignedNotificationCreatePassword, notification); } internal static void Welcome(string language, Notification notification) { Send(language, EmailTemplate.WelcomeNotification, notification); } internal static void WelcomePurchase(string language, Notification notification, string product) { notification = new WelcomePurchaseNotification(notification, product) { CreatePasswordLink = "https://sodapdf.com/" }; var templateId = EmailTemplate.WelcomeFreeProductNotification; if (product == "Soda PDF Free") notification = new WelcomeFreeProductNotification(notification, product); switch (product) { case "Soda PDF Basic Plan": templateId = EmailTemplate.WelcomePurchaseBasicPlanNotification; break; case "Soda PDF Business Plan": templateId = EmailTemplate.WelcomePurchaseBusinessPlanNotification; break; case "Soda PDF Enterprise": templateId = EmailTemplate.WelcomePurchaseEnterpriseNotification; break; case "Soda PDF Home Edition": templateId = EmailTemplate.WelcomePurchaseHomeEditionNotification; break; case "Soda PDF Home Plan": templateId = EmailTemplate.WelcomePurchaseHomePlanNotification; break; case "Soda PDF Premium Edition": templateId = EmailTemplate.WelcomePurchasePremiumEditionNotification; break; case "Soda PDF Premium Plan": templateId = EmailTemplate.WelcomePurchasePremiumPlanNotification; break; case "Soda PDF Pro Edition": templateId = EmailTemplate.WelcomePurchaseProEditionNotification; break; } #if PdfForge templateId = EmailTemplate.WelcomePurchaseNotification; #endif #if PdfSam templateId = EmailTemplate.WelcomePurchaseNotification; #endif Send(language, templateId, notification); } internal static void WelcomeFreeProductCovermountNotification(string language, Notification notification, string product) { notification = new WelcomeFreeProductNotification(notification, product); Send(language, EmailTemplate.WelcomeFreeProductCovermountNotification, notification); } internal static void WelcomePurchaseMigrationFromSuiteNotification(string language, Notification notification, string product) { notification = new WelcomePurchaseNotification(notification, product); (notification as WelcomePurchaseNotification).CreatePasswordLink = "link"; Send(language, EmailTemplate.WelcomePurchaseMigrationFromSuiteNotification, notification); } internal static void EmailConfirmationCovermount(string language, Notification notification) { notification = new EmailConfirmationNotification(notification, "https://sodapdf.com/"); Send(language, EmailTemplate.EmailConfirmationCovermountNotification, notification); } internal static void EmailConfirmation(string language, Notification notification) { notification = new EmailConfirmationNotification(notification, "https://sodapdf.com/"); Send(language, EmailTemplate.EmailConfirmationNotification, notification); } internal static void EmailConfirmationLate(string language, Notification notification) { notification = new EmailConfirmationNotification(notification, "https://sodapdf.com/"); Send(language, EmailTemplate.EmailConfirmationLateNotification, notification); } internal static void EmailChange(string language, Notification notification) { notification = new EmailChangeNotification(notification, string.Empty); Send(language, EmailTemplate.EmailChangeNotification, notification); } internal static void EmailChangeConfirmation(string language, Notification notification) { notification = new EmailChangeConfirmationNotification(notification, string.Empty, "https://sodapdf.com/"); Send(language, EmailTemplate.EmailChangeConfirmationNotification, notification); } internal static void OsSunset(string language, Notification notification) { Send(language, EmailTemplate.OsSunsetNotification, notification); } internal static void PolicyUpdate(string language, Notification notification) { Send(language, EmailTemplate.PolicyUpdateNotification, notification); } internal static void ProductSuspend(string language, Notification notification, string product) { notification = new ProductSuspendNotification(notification, product, DateTime.Now); Send(language, EmailTemplate.ProductSuspendNotification, notification); } internal static void ProductRenewalOff(string language, Notification notification, string product) { notification = new ProductRenewalOffNotification(notification, product); Send(language, EmailTemplate.ProductRenewalOffNotification, notification); } internal static void ProductAssignedCreatePassword(string language, Notification notification, string product) { notification = new ProductAssignedNotification(notification, product, notification) { DownloadLink = "https://sodapdf.com/" }; Send(language, EmailTemplate.ProductAssignedNotificationCreatePassword, notification); } internal static void ProductUnassigned(string language, Notification notification, string product) { notification = new ProductAssignedNotification(notification, product, notification); Send(language, EmailTemplate.ProductUnassignedNotification, notification); } private static void Send(string language, EmailTemplate templateId, Notification notification) { var emailAction = new SendEmailAction { EmailToList = new List<XmlEmail>(), TemplateId = templateId }; emailAction.EmailToList.Add(new XmlEmail { Email = notification.Email }); var parser = new RazorParser(language); string subject = parser.ParseSubject(emailAction, notification); string body = parser.ParseTemplate(emailAction, notification, subject); EmailManager.Send(emailAction, subject, body); } } } <file_sep>/Shared/SaaS.Mailer/Models/EmailConfirmationNotification.cs using System.Xml.Serialization; namespace SaaS.Mailer.Models { [XmlRoot("xml")] public class EmailConfirmationNotification : Notification { public EmailConfirmationNotification() { } public EmailConfirmationNotification(Notification user, string confirmationLink) : base(user) { ConfirmationLink = confirmationLink; } [XmlElement("confirmationLink")] public string ConfirmationLink { get; set; } } } <file_sep>/Web.Api/SaaS.Zendesk/qa/services/ws.js describe('service:$ws', () => { var $ws; beforeEach(module('app')); beforeEach(inject(($injector) => { $ws = $injector.get('$ws'); })); it('wifi:toBeDefined', () => { expect($ws.wifi).toBeDefined(); }); it('wifi.scan:toBeDefined', () => { expect($ws.wifi.scan).toBeDefined(); }); });<file_sep>/Shared/SaaS.PdfEscape.Api.Client/PdfEscapeClient.SignIn.cs using Newtonsoft.Json; using System.Net.Http; using System.Threading.Tasks; namespace SaaS.PdfEscape.Api.Client { public partial class PdfEscapeClient { public async Task<SignInModel> SignInAsync(string token) { using (var client = CreateHttpClient()) { var response = await client.GetAsync(string.Format("_desktop/verify/?token={0}", token)); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); var singInToken = JsonConvert.DeserializeObject<PdfEscapeApiToken>(json); return new SignInModel(singInToken); } return new SignInModel(SignInStatus.InvalidGrant); } } } public enum SignInStatus : byte { Ok, InvalidGrant } public class SignInModel { public readonly SignInStatus Status = SignInStatus.Ok; public readonly PdfEscapeApiToken Token = null; public SignInModel(PdfEscapeApiToken token) { Token = token; } public SignInModel(SignInStatus status) { Status = status; } public SignInModel(SignInStatus status, PdfEscapeApiToken token) { Status = status; Token = token; } } } <file_sep>/Web.Api/SaaS.UI.Admin/js/services/query.js (function () { 'use strict'; angular .module('app.services') .factory('$query', query); query.$inject = []; function query() { var service = {}; service.getJson = function (str) { try { str = str || document.location.search; return str.replace(/(^\?)/, '').split("&").map(function (item) { var index = item.indexOf('='); if (index != -1) { var key = item.substring(0, index); var value = item.substr(index + 1); this[key.toLowerCase()] = decodeURIComponent(value); } return this; }.bind({}))[0]; } catch (e) { return {}; } }; service.getQuery = function (str) { str = str || document.location.search; return str.slice(str.indexOf('?') + 1); }; service.getHash = function (removeHash) { var hash = window.location.hash; if (!hash || !hash.startsWith('#')) return null; if (hash.indexOf("#/") != -1) hash = hash.replace('#/', '#'); if (removeHash === true) hash = hash.replace('#', ''); return hash.toLowerCase(); }; return service; }; })();<file_sep>/Shared/SaaS.Api.Core/Filters/SaaSAuthorizeAttribute.cs using System.Net; using System.Net.Http; using System.Web.Http.Controllers; namespace SaaS.Api.Core.Filters { public class SaaSAuthorizeAttribute : System.Web.Http.AuthorizeAttribute { protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { var response = actionContext.Request.CreateResponse<dynamic>(HttpStatusCode.Unauthorized, new { error = "invalid_grant", error_description = "Authorization has been denied for this request." }); actionContext.Response = response; } } } <file_sep>/Web.Api/SaaS.Api.Mc/Global.asax.cs using System.Net; using System.Web.Http; namespace SaaS.Api.Mc { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; GlobalConfiguration.Configure(WebApiConfig.Register); } } } <file_sep>/Web.Api/SaaS.UI.Admin/js/services/form.js (function () { 'use strict'; angular .module('app.services') .factory('$form', form); form.$inject = []; function form() { var service = {}; service.submit = function (entity, form, callback) { if (form.$valid !== true) { angular.forEach(form, function (value, key) { if (typeof value === 'object' && value.hasOwnProperty('$modelValue')) value.$setDirty(); }); } if (service.isReady(entity, form) === false) return; callback(form); }; service.isReady = function (entity, form) { if (entity.isBusy === true || form.$valid !== true) return false; entity.isBusy = true; return true; }; return service; }; })();<file_sep>/Shared/SaaS.Data.Entities/View/ViewAccountMicrotransaction.cs using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace SaaS.Data.Entities.View { public class ViewAccountMicrotransaction : ViewMicrotransaction { [NotMapped] public List<ViewAccountMicrotransactionModule> Modules { get; set; } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.Merge.cs using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.View.Accounts; using SaaS.Identity; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { [HttpPost, Route("merge-send"), ValidateNullModel, ValidateModel, SaaSAuthorize] public async Task<IHttpActionResult> MergeSend(MergeViewModel model) { return await CurrentAccountExecuteAsync(async delegate (Account user) { var userFrom = await _auth.AccountGetAsync(model.AccountIdFrom); if (object.Equals(userFrom, null) || userFrom.Id == AccountId) return AccountNotFound(); var userPrimaryEmail = model.AccountIdPrimaryEmail == userFrom.Id ? userFrom : user; await NotificationManager.MergeConfirmationNotification(user, userFrom, userPrimaryEmail); return Ok(); }); } [HttpPost, Route("merge-confirmation")] public async Task<IHttpActionResult> MergeConfirmation([FromUri] Guid token) { try { var pending = await _auth.AccountMergePendingGetAsync(token); if (object.Equals(pending, null)) return AccountNotFound(); await _auth.AccountMergeAsync(pending); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } [HttpPost, Route("merge-request"), ValidateNullModel, ValidateModel, SaaSAuthorize] public async Task<IHttpActionResult> MergeRequest(AuthViewModel model) { return await CurrentAccountExecuteAsync(async delegate (Account user) { var userFrom = await _auth.AccountGetAsync(model.Email); if (object.Equals(userFrom, null) || userFrom.Id == user.Id) return AccountNotFound(); return Ok(new ViewAccountMergePending { AccountIdTo = user.Id, AccountEmailTo = user.Email, AccountIdFrom = userFrom.Id, AccountEmailFrom = userFrom.Email, AccountIdPrimaryEmail = user.Id }); }); } [HttpGet, Route("merge-pending"), SaaSAuthorize] public async Task<IHttpActionResult> MergePending() { try { return Ok(await _auth.AccountMergePendingsGetAsync(AccountId)); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpDelete, Route("merge-pending"), SaaSAuthorize] public async Task<IHttpActionResult> MergePendingDelete() { try { await _auth.AccountMergePendingDeleteAsync(AccountId); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } } }<file_sep>/Shared/SaaS.Api.Models/Oauth/RegisterViewModel.cs using Newtonsoft.Json; using SaaS.Api.Models.Validation; using System; using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Oauth { public class RegisterViewModel : AuthNameViewModel { private string _build = null; [DataType(DataType.Password), PasswordRegex(IsAllowNull = true)] public string Password { get; set; } [MaxLength(128)] public string Source { get; set; } [MaxLength(10)] public string Build { get { return _build; } set { if (string.IsNullOrEmpty(value)) return; _build = value.Trim(); } } public bool IsBusiness() { return string.Equals(Build, "b2b", StringComparison.InvariantCultureIgnoreCase); } [MaxLength(2), JsonProperty("Country")] public string CountryISO2 { get; set; } public ParamsViewModel Params { get; set; } public string Phone { get; set; } public string PhoneESign { get; set; } public string Company { get; set; } public string Occupation { get; set; } public string LanguageISO2 { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string PostalCode { get; set; } public string State { get; set; } public string Industry { get; set; } public string JobRole { get; set; } public string Licenses { get; set; } public string Product { get; set; } public string FormId { get; set; } public Guid? VisitorId { get; set; } public bool? Optin { get; set; } public bool? Trial { get; set; } public Guid? InstallationID { get; set; } [JsonProperty("trial-days")] public int? TrialDays { get; set; } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.Data.cs using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Api.Models.Products; using SaaS.Api.Oauth; using SaaS.ModuleFeatures; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { public class AccountDetailsProducts { public Guid? Id { get; set; } public AccountDetailsViewModel Details { get; set; } public List<AccountProductViewModel> Products { get; set; } public List<AccountProductModuleModel> Modules { get; set; } public MapModule[] ModuleFeatures { get; set; } public IEnumerable<Guid> ActiveProducts { get; set; } } [HttpGet, Route("data"), SaaSAuthorize] public async Task<IHttpActionResult> Data(bool isIncludeModules = false) { try { var sessionProducts = await GetSessionTokenProducts(); if (object.Equals(sessionProducts.SessionToken, null)) return AccountUnauthorized(); sessionProducts.Products.Sort(ProductComparer.Comparer); sessionProducts.Products.Reverse(); ProductComparer.ProductOrderer(sessionProducts.Products); var accountDetailsProducts = new AccountDetailsProducts { Details = await GetAccountDetails(), Products = sessionProducts.Products.ConvertAll(ProductConvertor.AccountProductConvertor) }; if (isIncludeModules && sessionProducts.SessionToken.AccountProductId.HasValue) { var product = sessionProducts.Products.FirstOrDefault(e => e.AccountProductId == sessionProducts.SessionToken.AccountProductId.Value && !e.IsDisabled); if (!object.Equals(product, null)) { var modules = UserManagerHelper.GetAllowedModules(sessionProducts.Products, product.AccountProductId); var active = UserManagerHelper.GetActiveProducts(sessionProducts.Products, modules, product.AccountProductId); var features = GetModuleFeatures(product, modules); accountDetailsProducts.Id = product.AccountProductId; accountDetailsProducts.Modules = modules; accountDetailsProducts.ModuleFeatures = features; accountDetailsProducts.ActiveProducts = active; } } return Ok(accountDetailsProducts); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } } }<file_sep>/Shared/SaaS.Mailer/Models/EmailChangeConfirmationNotification.cs using System.Xml.Serialization; namespace SaaS.Mailer.Models { [XmlRoot("xml")] public class EmailChangeConfirmationNotification : Notification { public EmailChangeConfirmationNotification() { } public EmailChangeConfirmationNotification(Notification user, string newEmail, string confirmationLink) : base(user) { NewEmail = newEmail; ConfirmationLink = confirmationLink; } [XmlElement("newEmail")] public string NewEmail { get; set; } [XmlElement("confirmationLink")] public string ConfirmationLink { get; set; } } }<file_sep>/Web.Api/SaaS.Api/Oauth/Providers/SaaSRefreshTokenProvider.cs using Microsoft.AspNet.Identity; using Microsoft.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Infrastructure; using NLog; using SaaS.Data.Entities.Oauth; using SaaS.Identity; using System; using System.Text; using System.Threading.Tasks; namespace SaaS.Api.Oauth.Providers { public class SaaSRefreshTokenProvider : IAuthenticationTokenProvider { private static Logger _oauthRefreshTokenLogger = LogManager.GetLogger("oauth-refresh-token"); private async Task<SessionToken> GetSessionToken(IOwinContext owinContext, Guid sessionTokenId) { SessionToken sessionToken = null; try { using (var auth = new AuthRepository()) sessionToken = await auth.SessionTokenGetAsync(sessionTokenId); if (object.Equals(sessionToken, null)) { var client = owinContext.Get<Client>("client"); var clientName = object.Equals(client, null) ? string.Empty : client.Name; var userAgent = owinContext.Request.Headers.Get("User-Agent"); var referer = owinContext.Request.Headers.Get("Referer"); _oauthRefreshTokenLogger.Warn("Session token '{0}' doesn't exist. Client: {1}", sessionTokenId.ToString("N"), clientName); } } catch (Exception exc) { _oauthRefreshTokenLogger.Error(exc); } return sessionToken; } private static SessionToken CreateSessionToken(IOwinContext owinContext, AuthenticationTicket ticket, out Client client) { SessionToken sessionToken = null; client = owinContext.Get<Client>("client"); if (object.Equals(client, null)) { _oauthRefreshTokenLogger.Warn("Client is null"); return sessionToken; } var session = ticket.Properties.Dictionary["session"]; Guid sessionId; if (!Guid.TryParse(session, out sessionId)) { _oauthRefreshTokenLogger.Warn($"Session Id '{session}' is not valid"); return sessionToken; } var account = ticket.Identity.GetUserId(); Guid accountId; if (!Guid.TryParse(account, out accountId)) { _oauthRefreshTokenLogger.Warn($"Account Id '{account}' is not valid"); return sessionToken; } var systemId = owinContext.Get<Guid?>("systemId"); var clientVersion = owinContext.Get<string>("clientVersion"); var externalClient = owinContext.Get<ExternalClient?>("externalClient"); var installationID = owinContext.Get<Guid?>("installationID"); var issued = DateTime.UtcNow; var expires = issued.Add(Startup.OAuthServerOptions.AccessTokenExpireTimeSpan); sessionToken = new SessionToken { Id = sessionId, AccountId = accountId, SystemId = systemId, ClientId = client.Id, ClientVersion = clientVersion, ExternalClient = externalClient, IssuedUtc = issued, ExpiresUtc = expires, InstallationID = installationID }; var parentSessionToken = owinContext.Get<SessionToken>("parentSessionToken"); if (!object.Equals(parentSessionToken, null)) sessionToken.ParentId = parentSessionToken.Id; return sessionToken; } private static ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get { return Startup.OAuthBearerOptions.AccessTokenFormat; } } public async Task CreateAsync(AuthenticationTokenCreateContext context) { Client client; var newSessionToken = CreateSessionToken(context.OwinContext, context.Ticket, out client); if (object.Equals(newSessionToken, null)) return; var scope = context.OwinContext.Get<string[]>("scope"); var sessionToken = context.OwinContext.Get<SessionToken>("sessionToken"); context.Ticket.Properties.IssuedUtc = newSessionToken.IssuedUtc; context.Ticket.Properties.ExpiresUtc = newSessionToken.ExpiresUtc; newSessionToken.Scope = SaaSScopeWorkerFactory.ScopeToString(scope); newSessionToken.ProtectedTicket = AccessTokenFormat.Protect(context.Ticket); Guid? oldSessionId = null; if (!object.Equals(sessionToken, null)) //come from grant_refresh { oldSessionId = sessionToken.Id; newSessionToken.ClientVersion = sessionToken.ClientVersion; newSessionToken.AccountProductId = sessionToken.AccountProductId; newSessionToken.ExternalClient = sessionToken.ExternalClient; newSessionToken.InstallationID = sessionToken.InstallationID; } using (var auth = new AuthRepository()) { try { var scopeWorker = SaaSScopeWorkerFactory.Create(scope, auth); await scopeWorker.SessionTokenInsertAsync(newSessionToken, oldSessionId); context.SetToken(newSessionToken.Id.ToString("N")); } catch (Exception exc) { var builder = new StringBuilder(); builder.AppendLine(exc.Message); builder.AppendLine($"Old session token Id: '{oldSessionId}'"); builder.AppendLine($"Client: '{client.Name}'"); builder.AppendLine($"Client version: '{newSessionToken.ClientVersion}'"); _oauthRefreshTokenLogger.Error(exc, builder.ToString()); } } } public async Task ReceiveAsync(AuthenticationTokenReceiveContext context) { Guid sessionTokenId; if (!Guid.TryParseExact(context.Token, "N", out sessionTokenId)) return; var sessionToken = await GetSessionToken(context.OwinContext, sessionTokenId); if (object.Equals(sessionToken, null)) { context.Response.Headers.Add("Refresh-Token-Expired", new[] { string.Format("token: {0}", sessionTokenId.ToString("N")) }); context.Response.Headers.Add("Access-Control-Expose-Headers", new[] { "Refresh-Token-Expired" }); return; } //TODO external provider password verification context.OwinContext.Set("scope", SaaSScopeWorkerFactory.StringToScope(sessionToken.Scope)); context.OwinContext.Set("systemId", sessionToken.SystemId); context.OwinContext.Set("sessionToken", sessionToken); //context.DeserializeTicket(token.ProtectedTicket); var ticket = AccessTokenFormat.Unprotect(sessionToken.ProtectedTicket); var issued = DateTime.UtcNow; var expires = issued.Add(Startup.OAuthServerOptions.AccessTokenExpireTimeSpan); ticket.Properties.IssuedUtc = issued; ticket.Properties.ExpiresUtc = expires; context.SetTicket(ticket); } public void Create(AuthenticationTokenCreateContext context) { throw new NotImplementedException(); } public void Receive(AuthenticationTokenReceiveContext context) { throw new NotImplementedException(); } } }<file_sep>/Shared/SaaS.Mailer/Enums.cs namespace SaaS.Mailer { public enum EmailTemplate { None, //когда нет mapping с базой, то прилетает от базы нулевой templateId или вообще ничего не прилетает AccountCreationCompleteNotification, BusinessDownloadNewAccountNotification, BusinessDownloadNotification, BusinessToPremiumNotification, EmailChangeConfirmationNotification, EmailChangeNotification, EmailConfirmationLateNotification, EmailConfirmationCovermountNotification, EmailConfirmationNotification, eSignEmailConfirmationNotification, eSignSignPackageNotification, PasswordChangedNotification, RecoverPasswordNotification, ProductSuspendNotification, OsSunsetNotification, PolicyUpdateNotification, ProductAssignedNotification, ProductAssignedNotificationCreatePassword, ProductEditionAssignedNotification, ProductEditionAssignedNotificationCreatePassword, WelcomeNotification, WelcomeFreeProductCovermountNotification, WelcomeFreeProductNotification, WelcomePurchaseNotification, WelcomePurchaseHomePlanNotification, WelcomePurchasePremiumPlanNotification, WelcomePurchaseBasicPlanNotification, WelcomePurchaseBusinessPlanNotification, //PdfSam products WelcomePurchaseStandardPlanNotification, WelcomePurchaseConvertPlanNotification, WelcomePurchaseProOcrEditionNotification, WelcomePurchaseStandardEditionNotification, WelcomePurchaseProPlanNotification, WelcomePurchaseProOcrPlanNotification, WelcomePurchaseOcrPlanNotification, WelcomePurchaseEditPlanNotification, // ============= WelcomePurchaseHomeEditionNotification, WelcomePurchaseProEditionNotification, WelcomePurchasePremiumEditionNotification, WelcomePurchaseEnterpriseNotification, ProductUnassignedNotification, ProductRenewalOffNotification, LegacyActivationCreatePasswordNotification, LegacyActivationSignInNotification, LegacyCreatePasswordReminder, MergeConfirmationNotification, MicrotransactionCreatePasswordNotification, WelcomePurchaseMigrationFromSuiteNotification } }<file_sep>/Shared/SaaS.Oauth2/Services/OauthServiceFactory.cs using SaaS.Oauth2.Clients; using SaaS.Oauth2.Core; using System; namespace SaaS.Oauth2.Services { public static class OauthServiceFactory { public static OauthService CreateService(string provider) { var comparison = StringComparison.InvariantCultureIgnoreCase; if ("google".Equals(provider, comparison)) return new GoogleService(OauthSignInFactory.CreateClient<GoogleClient>("Google")); if ("facebook".Equals(provider, comparison)) return new FacebookService(OauthSignInFactory.CreateClient<FacebookClient>("Facebook")); if ("microsoft".Equals(provider, comparison)) return new MicrosoftService(OauthSignInFactory.CreateClient<MicrosoftClient>("Microsoft")); return null; } } } <file_sep>/Web.Api/SaaS.Zendesk/src/js/controllers/account/sub-emails.js angular.module('app.controllers') .controller('accountSubEmailsController', ['$scope', '$state', '$api', ($scope, $state, $api) => { $scope.isLoading = true; $scope.model = { accountId: $state.params.accountId, subEmails: null }; $scope.refresh = () => { $api.account.getSubEmails({ accountId: $scope.model.accountId }) .then((json) => { $scope.model.subEmails = json; }); }; $scope.remove = (json) => { $api.account.removeSubEmail(json) .finally($scope.refresh); }; }]);<file_sep>/Web.Api/SaaS.UI.Admin/js/controllers/menu.js (function () { 'use strict'; angular .module('app.controllers') .controller('menuController', controller); controller.$inject = ['$scope', '$auth']; function controller($scope, $auth) { $scope.$auth = $auth; }; })();<file_sep>/Web.Api/SaaS.UI.Admin/js/controllers/admin/roles.js (function () { 'use strict'; angular .module('app.controllers') .controller('adminRolesController', controller); controller.$inject = ['$scope']; var roleEnum = { none: 0, addUser: 1 << 0, editUser: 1 << 1, deleteUser: 1 << 2, addAccount: 1 << 3, editAccount: 1 << 4, deleteAccount: 1 << 5, addProduct: 1 << 6, editProduct: 1 << 7, deleteProduct: 1 << 8 }; function controller($scope) { $scope.model = { roles: [ { title: 'Add/Edit an account', description: 'Create or modify customer accounts', status: roleEnum.addAccount | roleEnum.editAccount }, { title: 'Delete an account', description: 'Delete only accounts that have no purchases accossiated to them', status: roleEnum.deleteAccount }, { title: 'Add a product', description: 'Add products to an existing account', status: roleEnum.addProduct }, { title: 'Edit a product', description: 'modify products and billing within an account', status: roleEnum.editProduct }, { title: 'Add/Edit/Delete an user', description: 'create a with permission to allow use of the Admin portal', status: roleEnum.addUser | roleEnum.editUser | roleEnum.deleteUser } ], groups: [ { title: 'Agent', status: roleEnum.addAccount | roleEnum.editAccount | roleEnum.deleteAccount | roleEnum.editProduct }, { title: 'Supervisior', status: roleEnum.addAccount | roleEnum.editAccount | roleEnum.deleteAccount | roleEnum.editProduct }, { title: 'Manager', status: roleEnum.addAccount | roleEnum.editAccount | roleEnum.deleteAccount | roleEnum.editProduct | roleEnum.addProduct }, { title: 'Admin', status: roleEnum.addAccount | roleEnum.editAccount | roleEnum.deleteAccount | roleEnum.editProduct | roleEnum.addProduct | roleEnum.addUser | roleEnum.editUser | roleEnum.deleteUser } ] }; $scope.isStatus = function (group, role) { return !!(group.status & role.status); }; }; })(); <file_sep>/Web.Api/SaaS.Api.Admin/Controllers/Api/AccountController.SubEmail.cs using SaaS.Data.Entities.Accounts; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Admin.Controllers.Api { public partial class AccountController : SaaSApiController { [HttpGet, Route("{accountId:guid}/sub-email")] public async Task<IHttpActionResult> AccountSubEmail(Guid accountId) { try { return Ok(await _auth.AccountSubEmailsGetAsync(accountId)); } catch (Exception exc) { return ErrorContent(exc); } } [HttpDelete, Route("{accountId:guid}/sub-email/{id:int}")] public async Task<IHttpActionResult> AccountSubEmailDelete(Guid accountId, int id) { return await CurrentAccountExecuteAsync(async delegate (Account account) { await _auth.AccountSubEmailDeleteAsync(id); return Ok(); }, accountId); } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AdminAccountController.OwnerProduct.cs using SaaS.Api.Models.Products; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AdminAccountController { [HttpGet, Route("owner-products")] public async Task<IHttpActionResult> OwnerProducts(Guid userId) { var products = await _authProduct.OwnerProductsGetAsync(userId); return Ok(ProductConvertor.OwnerAccountProductConvertor(products)); } [HttpPost, Route("owner-products")] public async Task<IHttpActionResult> OwnerProductInsert(AddOwnerProductViewModel model) { await _authProduct.OwnerProductInsertAsync(model.UserId, model.ProductUid, model.Currency, model.Price, model.PriceUsd, model.Quantity); return Ok(); } } }<file_sep>/Shared/SaaS.Identity/AuthProductRepository/AccountProductPair.cs using System; namespace SaaS.Identity { public struct AccountProductPair { public Guid AccountId; public Guid AccountProductId; public AccountProductPair(Guid accountId, Guid accountProductId) { AccountId = accountId; AccountProductId = accountProductId; } } } <file_sep>/Web.Api/SaaS.Zendesk/src/js/directives/product/owner.js angular.module('app.directives') .directive('ngProductOwner', ['$api', ($api) => { return { restrict: 'A', scope: { status: '=ngProductOwner' }, link: (scope, element, attrs) => { element.addClass('badge'); var watch = scope.$watch('status', (status) => { if (!status) return; element .removeClass('badge-warning') .removeClass('badge-success'); !$api.product.isOwner(scope) && element.addClass('badge-danger').text('not owner'); $api.product.isOwner(scope) && element.addClass('badge-success').text('owner'); }); scope.$on("$destroy", () => { watch(); }); } }; }]);<file_sep>/Shared/SaaS.Mailer/EmailRepository.cs using SaaS.Common.Extensions; using SaaS.Data.Entities; using SaaS.Mailer.Models; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Mailer { public class EmailRepository { private async Task EmailInsert<T>(Guid accountId, EmailTemplate templateId, string email, T model) where T : new() { var action = new SendEmailAction() { TemplateId = templateId, EmailToList = new List<XmlEmail>() { new XmlEmail { Email = email } } }; string actionXml = XMLSerializer.SerializeObject(action); string modelXml = XMLSerializer.SerializeObject(model); using (var respository = new SaaS.Identity.EmailRepository()) await respository.EmailInsertAsync(accountId, Status.NotStarted, actionXml, modelXml); } public async Task SendAccountCreationCompleteNotification(RecoverPasswordNotification model) { await EmailInsert(model.AccountId, EmailTemplate.AccountCreationCompleteNotification, model.Email, model); } public async Task SendBusinessDownloadNewAccountNotification(Notification model) { await EmailInsert(model.AccountId, EmailTemplate.BusinessDownloadNewAccountNotification, model.Email, model); } public async Task SendBusinessDownloadNotification(Notification model) { await EmailInsert(model.AccountId, EmailTemplate.BusinessDownloadNotification, model.Email, model); } public async Task SendRecoverPasswordNotification(RecoverPasswordNotification model) { await EmailInsert(model.AccountId, EmailTemplate.RecoverPasswordNotification, model.Email, model); } public async Task SendPasswordChangedNotification(Notification model) { await EmailInsert(model.AccountId, EmailTemplate.PasswordChangedNotification, model.Email, model); } public async Task SendEmailConfirmationCovermountNotification(EmailConfirmationNotification model) { await EmailInsert(model.AccountId, EmailTemplate.EmailConfirmationCovermountNotification, model.Email, model); } public async Task SendEmailConfirmationNotification(EmailConfirmationNotification model) { await EmailInsert(model.AccountId, EmailTemplate.EmailConfirmationNotification, model.Email, model); } public async Task SendEmailChangeConfirmationNotification(EmailChangeConfirmationNotification model) { await EmailInsert(model.AccountId, EmailTemplate.EmailChangeConfirmationNotification, model.NewEmail, model); } public async Task SendEmailChangeNotification(EmailChangeNotification model) { await EmailInsert(model.AccountId, EmailTemplate.EmailChangeNotification, model.Email, model); } public async Task SendMergeConfirmationNotification(MergeConfirmationNotification model) { await EmailInsert(model.AccountId, EmailTemplate.MergeConfirmationNotification, model.Email, model); } public async Task SendProductAssignedNotification(ProductAssignedNotification model) { var emailTemplate = EmailTemplate.ProductAssignedNotification; if (!string.IsNullOrEmpty(model.CreatePasswordLink)) emailTemplate = EmailTemplate.ProductAssignedNotificationCreatePassword; await EmailInsert(model.AccountId, emailTemplate, model.Email, model); } public async Task SendProductEditionAssignedNotification(ProductAssignedNotification model) { var emailTemplate = EmailTemplate.ProductEditionAssignedNotification; if (!string.IsNullOrEmpty(model.CreatePasswordLink)) emailTemplate = EmailTemplate.ProductEditionAssignedNotificationCreatePassword; await EmailInsert(model.AccountId, emailTemplate, model.Email, model); } public async Task SendProductSuspendNotification(ProductSuspendNotification model) { await EmailInsert(model.AccountId, EmailTemplate.ProductSuspendNotification, model.Email, model); } public async Task SendProductUnassignedNotification(ProductAssignedNotification model) { await EmailInsert(model.AccountId, EmailTemplate.ProductUnassignedNotification, model.Email, model); } public async Task SendLegacyActivationCreatePasswordNotification(CreatePasswordNotification model) { await EmailInsert(model.AccountId, EmailTemplate.LegacyActivationCreatePasswordNotification, model.Email, model); } public async Task SendLegacyActivationSignInNotification(Notification model) { await EmailInsert(model.AccountId, EmailTemplate.LegacyActivationSignInNotification, model.Email, model); } public async Task SendLegacyCreatePasswordReminder(CreatePasswordNotification model) { await EmailInsert(model.AccountId, EmailTemplate.LegacyCreatePasswordReminder, model.Email, model); } public async Task SendWelcomeNotification(Notification model) { await EmailInsert(model.AccountId, EmailTemplate.WelcomeNotification, model.Email, model); } public async Task MicrotransactionCreatePassword(CreatePasswordNotification model) { await EmailInsert(model.AccountId, EmailTemplate.MicrotransactionCreatePasswordNotification, model.Email, model); } } }<file_sep>/Shared/SaaS.Identity.Admin/AuthDbContext.cs using System.Data.Entity; namespace SaaS.Identity.Admin { public partial class AuthDbContext : DbContext { public AuthDbContext() : base("oauthAdmin") { Database.SetInitializer<AuthDbContext>(null); Configuration.ProxyCreationEnabled = false; Configuration.LazyLoadingEnabled = false; } public AuthDbContext(string connectionString) : base(connectionString) { Database.SetInitializer<AuthDbContext>(null); Configuration.ProxyCreationEnabled = false; Configuration.LazyLoadingEnabled = false; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<User>().ToTable("oauth.user"); } public DbSet<User> Users { get; set; } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.Details.cs using AutoMapper; using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.View; using SaaS.IPDetect; using System; using System.Linq; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { private IHttpActionResult GetAccountResult(Account account) { return Ok(new { email = account.Email, firstName = account.FirstName, lastName = account.LastName, status = account.GetStatus(), //need remove it in future isAnonymous = account.IsAnonymous, isActivated = account.IsActivated }); } private async Task<AccountDetailsViewModel> GetAccountDetails() { var accountDetails = await _auth.AccountDetailsGetAsync(AccountId); if (object.Equals(accountDetails, null)) return null; var accountDetailsViewModel = new AccountDetailsViewModel(); return Mapper.Map(accountDetails, accountDetailsViewModel); } [HttpGet] public async Task<IHttpActionResult> GetByEmail(string email) { try { var account = await _auth.AccountGetAsync(email, isIncludeSubEmails: true); if (object.Equals(account, null)) return AccountNotFound(); else if (account.IsEmptyPassword()) { var sessionTokensExternalHistory = await _auth.SessionTokenExternalHistoriesAsync(account.Id); var sessionTokenExternalHistory = sessionTokensExternalHistory.FirstOrDefault(e => !e.IsUnlinked); if (!object.Equals(sessionTokenExternalHistory, null)) { return Ok(new { email = account.Email, firstName = account.FirstName, lastName = account.LastName, status = account.GetStatus(), optin = account.Optin, external = sessionTokenExternalHistory.ExternalClientName }); } } return Ok(new { email = account.Email, firstName = account.FirstName, lastName = account.LastName, status = account.GetStatus(), optin = account.Optin }); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpGet, Route("info"), SaaSAuthorize] public async Task<IHttpActionResult> Info() { return await CurrentAccountExecuteAsync(async delegate (Account user) { return await Task.Run(() => { return GetAccountResult(user); }); }); } [HttpGet, Route("{accountId:guid}/info")] public async Task<IHttpActionResult> InfoById(Guid accountId) { try { var account = await _auth.AccountGetAsync(accountId); if (object.Equals(account, null)) return AccountNotFound(); return GetAccountResult(account); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpPost, Route("info"), SaaSAuthorize, ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> Info(UserInfoViewModel model) { return await CurrentAccountExecuteAsync(async delegate (Account account) { account.FirstName = model.FirstName; account.LastName = model.LastName; var errorResult = GetErrorResult(await _auth.AccountUpdateAsync(account)); if (!object.Equals(errorResult, null)) return errorResult; return Ok(); }); } [HttpGet, Route("details"), SaaSAuthorize] public async Task<IHttpActionResult> Details() { try { var accountDetails = await GetAccountDetails(); if (object.Equals(accountDetails, null)) return AccountNotFound(); return Ok(accountDetails); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpPost, Route("details"), SaaSAuthorize, ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> Details(AccountDetailsViewModel model) { try { var accountsDetail = new ViewAccountDetails(); accountsDetail = Mapper.Map(model, accountsDetail); accountsDetail.Id = AccountId; accountsDetail.GeoIp = IpAddressDetector.IpAddress; await _auth.AccountDetailsSetAsync(accountsDetail); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } } }<file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.System.cs using System; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthDbContext { internal async Task<Data.Entities.Oauth.OauthSystem> SystemInsertAsync(Data.Entities.Oauth.OauthSystem system) { var sqlParams = new SqlParameter[] { system.MachineKey.ToSql("machineKey"), system.MotherboardKey.ToSql("motherboardKey"), system.PhysicalMac.ToSql("physicalMAC"), system.IsAutogeneratedMachineKey.ToSql("isAutogeneratedMachineKey"), system.PcName.ToSql("pcName") }; return await ExecuteReaderAsync<Data.Entities.Oauth.OauthSystem>("[oauth].[pSystemInsert]", sqlParams); } } }<file_sep>/Shared/SaaS.Data.Entities/Oauth/OauthSystem.cs using System; using System.ComponentModel.DataAnnotations; namespace SaaS.Data.Entities.Oauth { public class OauthSystem : Entity<Guid> { public Guid MachineKey { get; set; } [MaxLength(32)] public string MotherboardKey { get; set; } public string PhysicalMac { get; set; } public bool IsAutogeneratedMachineKey { get; set; } [MaxLength(200)] public string PcName { get; set; } } }<file_sep>/Web.Api/SaaS.Api.Sign/App_Start/WebApiConfig.cs using SaaS.Api.Core; using System.Web.Http; namespace SaaS.Api.Sign { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.MessageHandlers.Add(new CancelledTaskHandler()); } } } <file_sep>/Web.Api/SaaS.Zendesk/src/js/auth/buffer.js angular.module('app.auth') .factory('$authBuffer', ['$injector', ($injector) => { /** Holds all the requests, so they can be re-requested in future. */ var _buffer = []; /** Service initialized later because of circular dependency problem. */ var $http; var _retryHttpRequest = (config, deferred) => { var _success = (response) => { deferred.resolve(response); }; var _error = (response) => { deferred.reject(response); }; $http = $http || $injector.get('$http'); $http(config).then(_success, _error); } var service = {}; /** * Appends HTTP request configuration object with deferred response attached to buffer. */ service.append = (config, deferred) => { _buffer.push({ config: config, deferred: deferred }); }; /** * Abandon or reject (if reason provided) all the buffered requests. */ service.rejectAll = (reason) => { if (reason) { for (var index = 0; index < _buffer.length; ++index) _buffer[index].deferred.reject(reason); } _buffer = []; }; /** * Retries all the buffered requests clears the buffer. */ service.retryAll = (updater) => { for (var index = 0; index < _buffer.length; ++index) _retryHttpRequest(updater(_buffer[index].config), _buffer[index].deferred); _buffer = []; } return service; }]);<file_sep>/Web.Api/SaaS.Zendesk/qa/controllers/index.js describe(`controller:index`, () => { // it('getName', done => { // expect('Alex').toEqual($scope.getName()); // done(); // }); // it('getName 2', function () { // expect('Alex').toEqual($scope.getName()); // }); });<file_sep>/Web.Api/SaaS.UI.Admin/js/app.js /// <reference path="bundle.js" /> if (!String.prototype.startsWith) { String.prototype.startsWith = function (searchString, position) { position = position || 0; return this.indexOf(searchString, position) === position; }; } !function () { 'use strict'; angular.module('app.auth', []); angular.module('app.services', ['angularNotify']); angular.module('app.controllers', []); angular.module('app.directives', []); angular.module('app.filters', []); angular.module('app', ['angularNotify', 'ui.bootstrap', 'app.auth', 'app.services', 'app.controllers', 'app.directives', 'app.filters']) .config(['$httpProvider', '$locationProvider', function ($httpProvider, $locationProvider) { $locationProvider.html5Mode({ enabled: true, requireBase: false, rewriteLinks: false }); var regexIso8601 = /(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})Z/; var convertDateStringsToDates = function (input) { if (typeof input !== 'object') return input; for (var key in input) { if (!input.hasOwnProperty(key)) continue; var value = input[key]; var match; if (typeof value === "string" && (match = value.match(regexIso8601))) { var milliseconds = Date.parse(match[0]) if (!isNaN(milliseconds)) input[key] = new Date(milliseconds); } else if (typeof value === 'object') convertDateStringsToDates(value); } } $httpProvider.interceptors.push(['$q', function ($q) { return { request: function (config) { config.headers['Accept-Language'] = 'en-US'; return config || $q.when(config); } } }]); $httpProvider.defaults.transformResponse.push(function (responseData) { convertDateStringsToDates(responseData); return responseData; }); }]) .run(['$rootScope', '$authInterceptor', '$auth', function ($rootScope, $authInterceptor, $auth) { $rootScope.$on('event:auth-loginRequired', function () { return $auth.refreshToken().then($authInterceptor.loginConfirmed, $auth.logout); }); }]) }();<file_sep>/Web.Api/SaaS.Zendesk/src/js/controllers/account/product.js (() => { angular.module('app.controllers') .controller('accountProductController', ['$scope', '$state', '$api', ($scope, $state, $api) => { $scope.$api = $api; $scope.isLoading = true; $scope.model = { accountId: $state.params.accountId, accountProductId: $state.params.accountProductId, product: null }; let query = { accountId: $scope.model.accountId, accountProductId: $scope.model.accountProductId } $api.account.getOwnerProductDetails(query).then((json) => { $scope.model.product = new viewProduct(json); }); }]); let viewProduct = function (json) { Object.defineProperties(this, { id: { value: json.id, writable: false }, name: { value: json.name, writable: false }, unitName: { value: json.unitName, writable: false }, plan: { value: json.plan, writable: false }, ownerEmail: { value: json.ownerEmail, writable: false }, allowed: { value: json.allowed, writable: false } }); this.endDate = json.endDate; this.purchaseDate = json.purchaseDate; this.status = json.status; this.accounts = viewAcountBuilder.build(json); }; let viewAccount = function (json) { Object.defineProperties(this, { accountId: { value: json.accountId, writable: false }, email: { value: json.email, writable: false } }); }; let viewAcountBuilder = () => { }; viewAcountBuilder.build = (json) => { let accounts = []; if (json.accounts) { for (let index = 0; index < json.accounts.length; index++) { let account = json.accounts[index]; accounts.push(new viewAccount(account)); } } return accounts; }; })(); <file_sep>/Shared/SaaS.Mailer/Models/ProductRenewalOffNotification.cs using System.Xml.Serialization; namespace SaaS.Mailer.Models { [XmlRoot("xml")] public class ProductRenewalOffNotification : Notification { public ProductRenewalOffNotification() { } public ProductRenewalOffNotification(Notification user, string productName) : base(user) { ProductName = productName; } [XmlElement("productName")] public string ProductName { get; set; } } }<file_sep>/Shared/SaaS.Common/Extensions/RegexPattern.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace SaaS.Common.Extensions { public static class RegexPattern { private static readonly string _emailPattern = @"^(([^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$"; private static readonly Regex _emailRegex = new Regex(_emailPattern); public static bool IsValidEmail(this string email) { if (string.IsNullOrEmpty(email)) return false; return _emailRegex.IsMatch(email); } } } <file_sep>/Shared/SaaS.Api.OauthClientGenerator/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SaaS.Common.Extensions; namespace SaaS.Api.OauthClientGenerator { class Program { static void Main(string[] args) { var hash = "K4K1By1dpmVS2eP4e3WDIZ3fHZLPMP1OReo6bBD5YZI=".GetHash(); Console.WriteLine(hash); Console.ReadLine(); } } } <file_sep>/WinService/SaaS.WinService.Core/Enums.cs using System.Collections.Generic; using System.Linq; namespace SaaS.WinService.Core { public static class Enums { public static IEnumerable<T> Get<T>() { return System.Enum.GetValues(typeof(T)).Cast<T>(); } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.EmailConfirmation.cs using Microsoft.AspNet.Identity; using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Api.Oauth; using SaaS.Data.Entities.Accounts; using System; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { [HttpPost, Route("send-activation-email"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> SendActivationEmail(AuthViewModel model) { return await AccountExecuteAsync(async delegate (Account account) { #if PdfForge var accountDetails = await _auth.AccountDetailsGetAsync(account.Id); if (!object.Equals(accountDetails, null) && "covermount".Equals(accountDetails.Build, StringComparison.InvariantCultureIgnoreCase)) { await NotificationManager.EmailConfirmationCovermount(account); return Ok(); } #endif await NotificationManager.EmailConfirmation(account); return Ok(); }, model); } [HttpPost, Route("confirm-email"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> ConfirmEmail(ConfirmEmalViewModel model) { try { var account = await _auth.AccountGetAsync(model.UserId); if (object.Equals(account, null)) return AccountNotFound(); model.Token = HttpUtility.UrlDecode(model.Token); IdentityResult result = null; if (string.IsNullOrEmpty(model.Token)) //such bad solution, but saves a lot of time result = await _auth.AccountConfirmEmailAsync(account.Id); else result = await _auth.AccountConfirmEmailAsync(account.Id, model.Token); var errorResult = GetErrorResult(result); if (!object.Equals(errorResult, null)) return errorResult; if (model.IsBusiness()) await _auth.AccountMaskAsBusinessAsync(account); await _auth.AccountActivateAsync(account); await _auth.AccountVisitorIdSetAsync(account, model.VisitorId); var internalSignInViewModel = new SignInViewModel(account); return ResponseMessage(await OauthManager.InternalSignIn(internalSignInViewModel)); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } } }<file_sep>/Web.Api/SaaS.Api/Models/Api/Oauth/RegisterAnonymousViewModel.cs using Newtonsoft.Json; using SaaS.Api.Models.Validation; using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Api.Oauth { public class RegisterAnonymousViewModel { [Required, DataType(DataType.Password), PasswordRegex] public string Password { get; set; } public string client_id { get; set; } //[MaxLength(128)] //public string Source { get; set; } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.Product.cs using Microsoft.Owin.Security; using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Products; using SaaS.Api.Oauth; using SaaS.Api.Oauth.Providers; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View; using SaaS.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { private class SessionTokenProducts { internal SessionTokenProducts() { } internal SessionTokenProducts(SessionToken sessionToken, List<ViewAccountProduct> products) { SessionToken = sessionToken; Products = products; } internal SessionToken SessionToken { get; set; } internal List<ViewAccountProduct> Products { get; set; } } private async Task<SessionTokenProducts> GetSessionTokenProducts() { AuthenticationTicket ticket; var session = UserManagerHelper.Session(Request, out ticket); var sessionToken = await _auth.SessionTokenGetAsync(session); if (object.Equals(sessionToken, null)) return new SessionTokenProducts(); var products = await _authProduct.AccountProductsGetAsync(sessionToken.AccountId, sessionToken.SystemId); var scopeWorker = SaaSScopeWorkerFactory.Create(sessionToken.Scope); scopeWorker.FilterProducts(products, sessionToken); return new SessionTokenProducts(sessionToken, products); } [HttpGet, Route("products"), SaaSAuthorize] public async Task<IHttpActionResult> Products() { try { var sessionProducts = await GetSessionTokenProducts(); if (object.Equals(sessionProducts.SessionToken, null)) return AccountUnauthorized(); sessionProducts.Products.Sort(ProductComparer.Comparer); sessionProducts.Products.Reverse(); ProductComparer.ProductOrderer(sessionProducts.Products); return Ok(sessionProducts.Products.ConvertAll(ProductConvertor.AccountProductConvertor)); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpGet, Route("products/{accountProductId:guid}"), SaaSAuthorize] public async Task<IHttpActionResult> Products(Guid accountProductId) { try { AuthenticationTicket ticket; var session = UserManagerHelper.Session(Request, out ticket); var sessionToken = await _auth.SessionTokenGetAsync(session); if (object.Equals(sessionToken, null)) return Unauthorized(); int usedPerSystem = 0; if (sessionToken.SystemId.HasValue) { var accountSystems = await _auth.AccountSystemsGetAsync(new AccountProductPair(sessionToken.AccountId, accountProductId)); usedPerSystem = accountSystems.Count(e => e.SystemId == sessionToken.SystemId.Value); } return Ok(new { usedPerSystem = usedPerSystem }); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpDelete, Route("products/{accountProductId:guid}/notification"), SaaSAuthorize] public async Task<IHttpActionResult> ProductsDeleteNotification(Guid accountProductId) { try { var pair = CreateAccountProductPair(accountProductId); await _authProduct.ProductIsNewAsync(pair, false); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } } }<file_sep>/Test/SaaS.Api.Test/ESign/Packages.cs using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; using System; using System.Threading.Tasks; namespace SaaS.Api.Test.ESign { [TestClass] public class Packages : HttpTestHelper { [TestMethod] public async Task GetPackages() { var json = await AssertIsTrue(await ESignHelper.GetPackages()); } [TestMethod] public async Task PostPackages() { var json = await AssertIsTrue(await ESignHelper.PostPackages()); } [TestMethod] public async Task GetPackageId() { var packageId = new Guid("de5e2862-cf11-4005-a5e6-8c9b1b5f836a"); var json = await AssertIsTrue(await ESignHelper.GetPackageId(packageId)); } [TestMethod] public async Task PostPackageId() { var packageId = new Guid("c68e0ad5-17e2-4708-91ce-b9112b1c26d8"); JObject content = new JObject(); content.Add("trashed", true); var json = await AssertIsTrue(await ESignHelper.PostPackageId(packageId, content)); } [TestMethod] public async Task DeletePackageId() { var packageId = new Guid("5538ad7d-c49d-4877-bec0-953dc1c78bed"); var json = await AssertIsTrue(await ESignHelper.DeletePackageId(packageId)); } } } <file_sep>/Shared/SaaS.Data.Entities/eSign/eSignClient.cs namespace SaaS.Data.Entities.eSign { public enum eSignClient { eSign20 = 1 } }<file_sep>/Test/SaaS.Api.Test/OAuthHelper.cs using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; using SaaS.Api.Test.Models.Api.Oauth; using System; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Linq; namespace SaaS.Api.Test { internal class OAuthHelper { protected static readonly AppSettings _appSettings = new AppSettings(); private static HttpClient CreateHttpClient() { var client = new HttpClient(); client.BaseAddress = _appSettings.PathToOAuthApi; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return client; } private static async Task<HttpClient> CreateHttpClientAuthorized(string accessToken = "") { if (string.IsNullOrEmpty(accessToken)) { TokenResultModel token = await SignIn(); accessToken = token.access_token; } return await Task.Run(() => { var client = CreateHttpClient(); client.DefaultRequestHeaders.Add("Authorization", string.Format("bearer {0}", accessToken)); return client; }); } internal static async Task<HttpResponseMessage> SignIn(string login, string password, string token = "") { login = Uri.EscapeDataString(login); password = Uri.EscapeDataString(password); var builder = new StringBuilder("grant_type=password"); builder.AppendFormat("&username={0}", login); builder.AppendFormat("&password={0}", password); builder.AppendFormat("&token={0}", token); builder.AppendFormat("&client_id={0}", _appSettings.ClientId); builder.AppendFormat("&client_secret={0}", _appSettings.ClientSecret); builder.AppendFormat("&scope={0}", _appSettings.Scope); builder.AppendFormat("&motherboardKey={0}", "..<KEY>."); builder.AppendFormat("&physicalMac={0}", "34:17:EB:98:1A:45"); builder.AppendFormat("&machineKey={0}", "5C4C4544-0056-4A10-8059-B1C04F4E3032"); builder.AppendFormat("&pcName={0}", "D01505"); builder.AppendFormat("&isAutogeneratedMachineKey=false"); using (var client = CreateHttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); var request = new HttpRequestMessage(HttpMethod.Post, "api/token"); request.Content = new StringContent(builder.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await client.SendAsync(request); string json = await response.Content.ReadAsStringAsync(); Debug.WriteLine("Response status code: {0}", response.StatusCode); return response; } } private static async Task<HttpResponseMessage> ReSignIn(string login, string password) { var response = await SignIn(login, password); Assert.IsTrue(response.IsSuccessStatusCode); var json = await response.Content.ReadAsStringAsync(); var token = await response.Content.ReadAsAsync<TokenResultModel>(); response = await RefreshToken(token.refresh_token); token = await response.Content.ReadAsAsync<TokenResultModel>(); using (var client = await CreateHttpClientAuthorized(token.access_token)) { var productsResponse = await client.GetAsync("api/account/products"); Assert.IsTrue(response.IsSuccessStatusCode); var products = await productsResponse.Content.ReadAsAsync<AccountProductResultModel[]>(); var productResponse = await client.PostAsync(string.Format("api/token/{0}", "<PASSWORD>"), null); Assert.IsTrue(productResponse.IsSuccessStatusCode); return productResponse; } } internal static async Task<HttpResponseMessage> RefreshToken(string refreshToken) { refreshToken = Uri.EscapeDataString(refreshToken); var builder = new StringBuilder("grant_type=refresh_token"); builder.AppendFormat("&refresh_token={0}", refreshToken); builder.AppendFormat("&client_id={0}", _appSettings.ClientId); builder.AppendFormat("&client_secret={0}", _appSettings.ClientSecret); HttpStatusCode httpStatus = HttpStatusCode.OK; string json = string.Empty; using (var client = CreateHttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); var request = new HttpRequestMessage(HttpMethod.Post, "api/token"); request.Content = new StringContent(builder.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await client.SendAsync(request); httpStatus = response.StatusCode; json = await response.Content.ReadAsStringAsync(); Debug.WriteLine("Response status code: {0}", response.StatusCode); return response; } } internal static RegisterViewModel RegisterViewModel() { var guid = Guid.NewGuid(); return new RegisterViewModel() { Email = _appSettings.Login, Password = _<PASSWORD>, FirstName = string.Format("FirstName - {0}", guid), LastName = string.Format("LastName - {0}", guid) }; } internal static RegisterViewModel CreateRandomRegisterViewModel() { var guid = Guid.NewGuid(); return new RegisterViewModel() { Email = string.Format("{<EMAIL>", guid), Password = "<PASSWORD>", FirstName = string.Format("FirstName - {0}", guid), LastName = string.Format("LastName - {0}", guid) }; } internal static async Task<HttpResponseMessage> Register(RegisterViewModel model) { using (var client = CreateHttpClient()) { var response = await client.PostAsJsonAsync("api/account/register", model); string json = await response.Content.ReadAsStringAsync(); Debug.WriteLine("Response status code: {0}", response.StatusCode); return response; } } internal static async Task<HttpResponseMessage> RegisterAnonymous() { using (var client = CreateHttpClient()) { var response = await client.PostAsJsonAsync("api/account/register-anonymous", new { password = "<PASSWORD>", client_id = "saas" }); string json = await response.Content.ReadAsStringAsync(); Debug.WriteLine("Response status code: {0}", response.StatusCode); return response; } } internal static async Task<HttpResponseMessage> SendActivationEmail(AuthViewModel model) { using (var client = CreateHttpClient()) { var response = await client.PostAsJsonAsync<AuthViewModel>("api/account/send-activation-email", model); string json = await response.Content.ReadAsStringAsync(); Debug.WriteLine("Response status code: {0}", response.StatusCode); return response; } } internal static async Task<TokenResultModel> SignIn() { var response = await SignIn(_appSettings.Login, _appSettings.Password, _appSettings.Token); var json = await response.Content.ReadAsStringAsync(); Assert.IsTrue(response.IsSuccessStatusCode); return await response.Content.ReadAsAsync<TokenResultModel>(); } internal static async Task<HttpResponseMessage> Logout() { TokenResultModel token = await SignIn(); return await Logout(token.access_token, token.refresh_token); } internal static async Task<HttpResponseMessage> Logout(string accessToken, string refreshToken) { using (var client = await CreateHttpClientAuthorized(accessToken)) return await client.DeleteAsync(string.Format("api/token/{0}", refreshToken)); } internal static async Task<TokenResultModel> ReSignIn() { var response = await ReSignIn(_appSettings.Login, _appSettings.Password); var json = await response.Content.ReadAsStringAsync(); Assert.IsTrue(response.IsSuccessStatusCode); return await response.Content.ReadAsAsync<TokenResultModel>(); } internal static async Task<HttpResponseMessage> ChangePassword(ChangePasswordViewModel model) { using (var client = await CreateHttpClientAuthorized()) return await client.PostAsJsonAsync("api/account/change-password", model); } internal static async Task<HttpResponseMessage> GetProduct(Guid id, string accessToken = "") { using (var client = await CreateHttpClientAuthorized(accessToken: accessToken)) return await client.PostAsync(string.Format("api/token/{0}", id), null); } internal static async Task<HttpResponseMessage> GetModules(string accessToken = "") { using (var client = await CreateHttpClientAuthorized(accessToken: accessToken)) return await client.GetAsync("api/account/modules"); } internal static async Task<HttpResponseMessage> Auto(string accessToken = "") { using (var client = await CreateHttpClientAuthorized(accessToken: accessToken)) return await client.PostAsync("api/token/auto", null); } internal static async Task<HttpResponseMessage> GetProducts(string accessToken = "") { using (var client = await CreateHttpClientAuthorized(accessToken: accessToken)) return await client.GetAsync("api/account/products"); } } } <file_sep>/Shared/SaaS.Identity.Admin/AuthDbContext.Sql/AuthDbContext.Sql.SessionToken.cs using SaaS.Data.Entities.Admin.Oauth; using System; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity.Admin { public partial class AuthDbContext { internal async Task<SessionToken> SessionTokenGetAsync(Guid id) { var sqlParams = new SqlParameter[] { id.ToSql("id") }; return await ExecuteReaderAsync<SessionToken>("[oauth].[pTakeSessionToken]", sqlParams); } internal async Task SessionTokenInsertAsync(SessionToken token) { var sqlParams = new SqlParameter[] { token.Id.ToSql("id"), token.IssuedUtc.ToSql("issuedUtc"), token.ExpiresUtc.ToSql("expiresUtc"), token.ProtectedTicket.ToSql("protectedTicket") }; await ExecuteNonQueryAsync("[oauth].[pInsertSessionToken]", sqlParams); } } } <file_sep>/Shared/SaaS.Api.Models/Oauth/ChangePasswordViewModel.cs using SaaS.Api.Models.Validation; using System; using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Oauth { public class ChangePasswordViewModel { [Required, DataType(DataType.Password)] public string OldPassword { get; set; } [Required, DataType(DataType.Password), PasswordRegex] public string NewPassword { get; set; } } public class SetPasswordViewModel { [Required] public Guid Id { get; set; } [DataType(DataType.Password), PasswordRegex(IsAllowNull = true)] public string NewPassword { get; set; } public bool IsConnect { get; set; } } }<file_sep>/Web.Api/SaaS.Zendesk/src/js/directives/account/menu.js angular.module('app.directives') .directive('ngAccountMenu', ['$state', ($state) => { return { restrict: 'E', replace: true, templateUrl: 'directives/account/menu.html' }; }]);<file_sep>/Shared/SaaS.Identity/AuthRepository/AuthRepository.AccountDetails.cs using SaaS.Data.Entities.View; using System; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthRepository { public async Task<ViewAccountDetails> AccountDetailsGetAsync(Guid accountId) { return await _context.AccountDetailsGetAsync(accountId); } public async Task AccountDetailsSetAsync(ViewAccountDetails accountDetails) { await _context.AccountDetailsSetAsync(accountDetails); } public async Task<int?> AccountUidGetAsync(Guid accountId) { return await _context.AccountUidGetAsync(accountId); } } }<file_sep>/Web.Api/SaaS.Api.Mc/Controllers/Api/v1/BaseApiController.cs using SaaS.Api.Mc.Http; using System; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Mc.Controllers.Api.v1 { public abstract class BaseApiController : ApiController { protected abstract string ApiRoot { get; } [DebuggerStepThrough] protected string Format(string format = null, params object[] @params) { var builder = new StringBuilder(ApiRoot); if (!object.Equals(format, null)) builder.AppendFormat(format, @params); return builder.ToString(); } protected async Task<HttpResponseMessage> HttpProxy(HttpRequestMessage request, string method, CancellationToken cancellationToken) { try { using (var client = new McHttpClient(request)) return await client.SendAsync(method, cancellationToken); } catch (Exception exc) { return request.CreateResponse(HttpStatusCode.BadRequest, new { error = "invalid_request", error_description = exc.Message }); } } } }<file_sep>/Web.Api/SaaS.Zendesk/src/js/directives/account/activated.js angular.module('app.directives') .directive('ngAccountActivated', ['$api', ($api) => { return { restrict: 'A', scope: { status: '=ngAccountActivated' }, link: (scope, element, attrs) => { element.addClass('badge'); var watch = scope.$watch('status', () => { element .removeClass('badge-warning') .removeClass('badge-success'); !$api.account.isActivated(scope) && element.addClass('badge-warning').text('not activated'); $api.account.isActivated(scope) && element.addClass('badge-success').text('activated'); }); scope.$on("$destroy", () => { watch(); }); } }; }]);<file_sep>/WinService/SaaS.WinService.Mailer/MailerService.cs using SaaS.MailerWorker; using System.ServiceProcess; namespace SaaS.WinService.Mailer { public partial class MailerService : ServiceBase { private readonly EmailScheduler _mailer; public MailerService() { InitializeComponent(); _mailer = EmailScheduler.GetMailer(); } protected internal void StartUserInteractive() { OnStart(new string[] { }); } protected override void OnStart(string[] args) { _mailer.StartMailing(); } protected override void OnStop() { _mailer.StopMailing(); } } } <file_sep>/Shared/SaaS.ModuleFeatures/MapFeature.cs using Newtonsoft.Json; using System; namespace SaaS.ModuleFeatures { public class MapFeature { public MapFeature(string name, Version version) { Name = name; Version = version; } public string Name { get; set; } public Version Version { get; set; } [JsonIgnore] public bool IsHidden { get; set; } [JsonIgnore] public bool IsUpgradable { get; set; } [JsonIgnore] public bool IsActivated { get; set; } public ulong Status { get { ulong status = 0; status |= (ulong)(IsHidden ? MapFeatureStatus.IsHidden : 0); status |= (ulong)(IsUpgradable ? MapFeatureStatus.IsUpgradable : 0); status |= (ulong)(IsActivated ? MapFeatureStatus.IsActivated : 0); return status; } } [Flags] public enum MapFeatureStatus { None = 0, IsHidden = 1, IsUpgradable = 2, IsActivated = 4 } internal void Activate() { if (IsHidden || IsUpgradable) return; IsActivated = true; } } } <file_sep>/Shared/SaaS.Identity.Admin/AuthRepository/AuthRepository.cs using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security.DataProtection; using SaaS.Common.Extensions; using System; namespace SaaS.Identity.Admin { public partial class AuthRepository : IAuthRepository { protected readonly AuthDbContext _context; protected readonly UserManager<User, Guid> _userManager; public AuthRepository() { _context = new AuthDbContext(); _userManager = new UserManager<User, Guid>(new UserStore<User>(_context)); _userManager.UserValidator = new UserValidator<User>(_userManager); _userManager.PasswordHasher = new SaaSPasswordHasher(); } public AuthRepository(string connectionString) { _context = new AuthDbContext(connectionString); _userManager = new UserManager<User, Guid>(new UserStore<User>(_context)); _userManager.UserValidator = new UserValidator<User>(_userManager); _userManager.PasswordHasher = new SaaSPasswordHasher(); } public void SetDataProtectorProvider(IDataProtectionProvider dataProtectorProvider) { var dataProtector = dataProtectorProvider.Create("SodaPDFAdmin"); _userManager.UserTokenProvider = new DataProtectorTokenProvider<User, Guid>(dataProtector) { TokenLifespan = TimeSpan.FromHours(24), }; } public void Dispose() { _context.Dispose(); _userManager.Dispose(); } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/TokenController.cs using JWT; using JWT.Algorithms; using JWT.Serializers; using Microsoft.Owin.Security; using SaaS.Api.Controllers.Api.Oauth; using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Api.Oauth; using SaaS.Api.Oauth.Providers; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api { [RoutePrefix("api"), SaaSAuthorize, System.Web.Mvc.ValidateAntiForgeryToken] public class TokenController : SaaSApiController { internal async Task<IHttpActionResult> PostToken(List<ViewAccountProduct> products, ViewAccountProduct product, List<SessionToken> sessions, SessionToken session, Account user, AuthenticationTicket ticket) { if (object.Equals(product, null)) return ProductNotFound(); var scopeWorker = SaaSScopeWorkerFactory.Create(session.Scope, _auth, _authProduct); if (!scopeWorker.ValidateSessionTokenAsync(user, sessions, session, product)) return ErrorContent("invalid_grant", "You are logged into too many devices.", HttpStatusCode.Conflict); if (!await scopeWorker.ValidateAccountSystemAsync(user, session, product)) return ErrorContent("invalid_grant", "Your license is currently associated with another device.", HttpStatusCode.Conflict); var modules = UserManagerHelper.GetAllowedModules(products, product.AccountProductId, ticket.Identity); var activeProducts = UserManagerHelper.GetActiveProducts(products, modules, product.AccountProductId); var moduleFeatures = AccountController.GetModuleFeatures(product, modules); var client = GetClient(session.ClientId); var oldId = OauthManager.UpdateTicket(user, session, ticket, product, client); await _auth.SessionTokenInsertAsync(session, oldId, false, product.IsPPC); return Ok(OauthManager.ReleaseToken(session, ticket, modules, moduleFeatures, activeProducts, user)); } [HttpPost, Route("token/auto")] public async Task<IHttpActionResult> PostToken() { return await CurrentAccountExecuteAsync(async delegate (Account user) { AuthenticationTicket ticket; var sessionId = UserManagerHelper.Session(Request, out ticket); var sessions = await _auth.SessionTokensGetAsync(user.Id); var sessionToken = sessions.FirstOrDefault(e => e.Id == sessionId); if (object.Equals(sessionToken, null)) return AccountUnauthorized(); var products = await _authProduct.AccountProductsGetAsync(sessionToken.AccountId, sessionToken.SystemId); var scopeWorker = SaaSScopeWorkerFactory.Create(sessionToken.Scope); scopeWorker.FilterProducts(products, sessionToken); var offeringProducts = products.Where(e => !e.IsDisabled && !e.IsMinor && !e.IsPPC); var product = offeringProducts.FirstOrDefault(e => !e.IsFree) ?? offeringProducts.FirstOrDefault(); return await PostToken(products, product, sessions, sessionToken, user, ticket); }); } [HttpPost, Route("token/{accountProductId:guid}")] public async Task<IHttpActionResult> PostToken(Guid accountProductId, bool setAsDefault = false) { return await CurrentAccountExecuteAsync(async delegate (Account user) { if (!user.IsActivated && !user.IsAnonymous) return AccountNotActivated(); AuthenticationTicket ticket; var sessionId = UserManagerHelper.Session(Request, out ticket); var sessions = await _auth.SessionTokensGetAsync(user.Id); var sessionToken = sessions.FirstOrDefault(e => e.Id == sessionId); if (object.Equals(sessionToken, null)) return AccountUnauthorized(); var products = await _authProduct.AccountProductsGetAsync(sessionToken.AccountId, sessionToken.SystemId); var scopeWorker = SaaSScopeWorkerFactory.Create(sessionToken.Scope); scopeWorker.FilterProducts(products, sessionToken); var product = products.FirstOrDefault(e => e.AccountProductId == accountProductId && !e.IsDisabled); return await PostToken(products, product, sessions, sessionToken, user, ticket); }); } [HttpDelete, Route("token/{refreshToken:guid}"), AllowAnonymous] public async Task<IHttpActionResult> DeleteToken(Guid refreshToken) { try { await _auth.SessionTokenDeleteAsync(refreshToken); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } [HttpDelete, Route("token/logout"), AllowAnonymous] public async Task<IHttpActionResult> Logout() { if (User.Identity.IsAuthenticated) { AuthenticationTicket ticket; try { var session = UserManagerHelper.Session(Request, out ticket); await _auth.SessionTokenDeleteAsync(session); } catch (Exception exc) { _oautLogLogger.Error(exc); } } return Ok(); } [HttpPost, Route("token/jwt"), AllowAnonymous] public async Task<IHttpActionResult> TokenJwt(AuthPasswordViewModel model) { //TODO //Add client_id, client_secret ... //Add secret //Add different options as jwt, ... return await AccountExecuteAsync(async delegate (Account account) { if (account.IsEmptyPassword() || !_auth.PasswordIsEqual(account.Password, model.Password)) return AccountNotFound(); var epochTime = (DateTime.UtcNow - new DateTime(1970, 1, 1)); var payload = new Dictionary<string, object>() { { "iat", (int)epochTime.TotalSeconds }, { "jti", Guid.NewGuid().ToString() }, { "name", account.UserName }, { "email", account.Email } }; var algorithm = new HMACSHA256Algorithm(); var serializer = new JsonNetSerializer(); var urlEncoder = new JwtBase64UrlEncoder(); var encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var key = "<KEY>"; #if STAGE key = "<KEY>"; #endif var jwt = encoder.Encode(payload, key); return Ok(new { jwt }); }, model); } } }<file_sep>/Web.Api/SaaS.Zendesk/tasks/zat.js.js const gulp = require('gulp'); gulp.task('zat.js:assets', () => { return gulp.src('dist/js/*.js') .pipe(gulp.dest('zat/assets/js')); }); gulp.task('zat.js:watch', () => { return gulp.watch('dist/js/*.js', gulp.series('zat.js:assets')); }); gulp.task('zat.js', gulp.series('zat.js:assets'));<file_sep>/Web.Api/SaaS.Zendesk/src/js/auth/auth.js angular.module('app.auth') .factory('$auth', ['$q', '$state', '$injector', '$authStorage', '$brand', ($q, $state, $injector, $authStorage, $brand) => { var _apiHeaders = { 'Content-Type': 'application/x-www-form-urlencoded' }; var service = {}; var _getItem = () => { var iso = $brand.getIso(); return $authStorage.getItem(iso); }; service.isAuthenticated = () => { if ($brand.isEmpty()) return false; return !!_getItem(); }; service.getAccessToken = () => { var item = _getItem(); return item ? item.access_token : null; }; service.getRefreshToken = () => { var item = _getItem(); return item ? item.refresh_token : null; }; service.signIn = (login, password) => { var $http = $injector.get("$http"); var data = [ 'grant_type=password', 'username=' + encodeURIComponent(login), 'password=' + encodeURIComponent(<PASSWORD>) ]; data = data.join('&'); var deferred = $q.defer(); if ($brand.isEmpty()) { deferred.reject({ error_description: 'Brand is not supported!' }); } else { var uri = $brand.getApiUri('api/token'); $http.post(uri, data, { headers: _apiHeaders, asJson: true }).then((json) => { var iso = $brand.getIso(); $authStorage.setItem(iso, json); deferred.resolve(json); }, (error, status, headers) => { deferred.reject(error.data); }); } return deferred.promise; }; service.refreshToken = () => { var $http = $injector.get("$http"); var data = [ 'grant_type=refresh_token', 'refresh_token=' + service.getRefreshToken(), ]; data = data.join('&'); var deferred = $q.defer(); var uri = $brand.getApiUri('api/token'); $http.post(uri, data, { headers: _apiHeaders, asJson: true }).then((json) => { var iso = $brand.getIso(); $authStorage.setItem(iso, json); deferred.resolve(json); }, (error, status, headers) => { service.logout(); deferred.reject(status); }); return deferred.promise; }; service.logout = () => { var iso = $brand.getIso(); $authStorage.removeItem(iso); $state.go('user/sign-in'); }; return service; }]);<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AdminAccountController.Register.cs using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Data.Entities.Accounts; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AdminAccountController { [HttpPost, Route("register"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> Register(AuthNameViewModel model) { try { var user = await _auth.AccountGetAsync(model.Email, isIncludeSubEmails: true); if (!object.Equals(user, null)) return AccountExists(); user = new Account(model.Email, model.FirstName, model.LastName); var result = await _auth.AccountCreateAsync(user); var errorResult = GetErrorResult(result); if (!object.Equals(errorResult, null)) return errorResult; } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } } }<file_sep>/Web.Api/SaaS.Api/Oauth/OauthLogger.cs using NLog; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.View; using System.Net.Http; using System.Text; namespace SaaS.Api.Oauth { internal static class OauthLogger { //private static Logger _oauthCreateAccountLogger; static OauthLogger() { //_oauthCreateAccountLogger = LogManager.GetLogger("oauth-create-account"); //_oauthCreateAccountLogger.Warn("Start"); } internal static void CreateAccountWarn(HttpRequestMessage request, Account account, ViewAccountDetails details, string stackTrace) { //string message = null; //if (object.Equals(details, null)) // message = "ViewAccountDetails is null."; //if (!object.Equals(details, null) && !details.Uid.HasValue) // message = "ViewAccountDetails.Uid is null."; //if (!object.Equals(message, null)) //{ // var referrer = string.Empty; // if (!object.Equals(request.Headers, null) && !object.Equals(request.Headers.Referrer, null)) // referrer = request.Headers.Referrer.ToString(); // var source = string.Empty; // if (!object.Equals(details, null)) // source = details.Source; // var builder = new StringBuilder(); // builder.AppendLine(message); // builder.AppendLine(string.Format("AccountId: {0}", account.Id)); // builder.AppendLine(string.Format("Referrer: {0}", referrer)); // builder.AppendLine(string.Format("Stack trace: {0}", stackTrace)); // builder.AppendLine(string.Format("Source: {0}", source)); // _oauthCreateAccountLogger.Warn(builder.ToString()); //} } } }<file_sep>/Shared/SaaS.Data.Entities/View/ViewUnassignProduct.cs using System; namespace SaaS.Data.Entities.View { public class ViewUnassignProduct { public UnassignStatus Status { get; set; } public DateTime CreateDate { get; set; } } } <file_sep>/Web.Api/SaaS.Api.Sign/Controllers/Api/ESign20/SignatureAppearancesController.cs using SaaS.Api.Core.Filters; using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Sign.Controllers.Api.eSign20 { [RoutePrefix("api-esign20/v1/signature-appearances"), SaaSAuthorize] public class SignatureAppearancesController : BaseApiController { protected override string ApiRoot { get { return "api/v1/signature-appearances/"; } } [Route("{*url}"), HttpGet, HttpPost, HttpPut, HttpDelete] public async Task<HttpResponseMessage> Index(CancellationToken cancellationToken) { return await HttpProxy(Request, Request.RequestUri.LocalPath, cancellationToken); } [Route, HttpGet, HttpPost] public async Task<HttpResponseMessage> SignatureAppearances(CancellationToken cancellationToken) { return await HttpProxy(Request, Format(), cancellationToken); } [Route("{id:guid}"), HttpPut, HttpDelete] public async Task<HttpResponseMessage> SignatureAppearances(Guid id, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}", id), cancellationToken); } [Route("{id:guid}/thumbnail"), HttpPost] public async Task<HttpResponseMessage> SignatureAppearancesThumbnail(Guid id, CancellationToken cancellationToken) { return await HttpProxy(Request, Format("{0}/thumbnail", id), cancellationToken); } } }<file_sep>/Test/SaaS.Api.Test/Models/Api/Oauth/ChangeInfoViewModel.cs  namespace SaaS.Api.Test.Models.Api.Oauth { public class ChangeInfoViewModel { public string FirstName { get; set; } public string LastName { get; set; } } } <file_sep>/Web.Api/SaaS.Api.Sign/Oauth/OAuthBearerProvider.cs using Microsoft.Owin.Security.OAuth; using System.Threading.Tasks; namespace SaaS.Api.Sign.Providers { public class OauthBearerProvider : IOAuthBearerAuthenticationProvider { public Task ApplyChallenge(OAuthChallengeContext context) { return Task.FromResult<object>(null); } public Task RequestToken(OAuthRequestTokenContext context) { return Task.FromResult<object>(null); } public Task ValidateIdentity(OAuthValidateIdentityContext context) { return Task.FromResult<object>(null); } } }<file_sep>/Shared/SaaS.Oauth2/Services/GoogleService.cs using Newtonsoft.Json; using SaaS.Oauth2.Core; using System; using System.Collections.Generic; using System.Drawing; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web; namespace SaaS.Oauth2.Services { public class GoogleService : OauthService { public GoogleService(ClientProvider client) : base(client) { } public override string GetAuthenticationUrl(string lang) { var query = QueryStringBuilder.BuildCompex(new[] { "scope" }, "scope", _clientProvider.Scope, "redirect_uri", _clientProvider.CallBackUrl, "client_id", _clientProvider.ClientId, "response_type", "code", "approval_prompt", "force", //auto //"prompt", "select_account", //https://stackoverflow.com/questions/14384354/force-google-account-chooser "access_type", "online", "hl", lang ); return "https://accounts.google.com/o/oauth2/auth?" + query; } public override Size GetWindowSize() { return new Size(800, 600); } public override async Task<TokenResult> TokenAsync(string code, CancellationToken cancellationToken) { var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("client_id", _clientProvider.ClientId), new KeyValuePair<string, string>("client_secret", _clientProvider.ClientSecret), new KeyValuePair<string, string>("redirect_uri", _clientProvider.CallBackUrl), new KeyValuePair<string, string>("code", code), new KeyValuePair<string, string>("grant_type", "authorization_code") }); using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://www.googleapis.com"); var response = await client.PostAsync("oauth2/v4/token", content, cancellationToken); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<TokenResult>(json); } } return null; } public override async Task<ProfileResult> ProfileAsync(TokenResult token, CancellationToken cancellationToken) { var query = HttpUtility.ParseQueryString(string.Empty); query.Add("access_token", token.AccessToken); using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://www.googleapis.com"); var response = await client.GetAsync("oauth2/v1/userinfo/?" + query.ToString(), cancellationToken); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); var profile = JsonConvert.DeserializeObject<GoogleProfileResult>(json); return new ProfileResult(profile); } } return null; } //public override async Task<bool> RevokeAsync(TokenResult token, CancellationToken cancellationToken) //{ // var query = HttpUtility.ParseQueryString(string.Empty); // query.Add("token", token.AccessToken); // var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[] // { // }); // using (var client = new HttpClient()) // { // client.BaseAddress = new Uri("https://accounts.google.com"); // var response = await client.PostAsync("o/oauth2/revoke/?" + query.ToString(), content, cancellationToken); // return response.IsSuccessStatusCode; // } //} } }<file_sep>/WinService/SaaS.WinService.Mailer.Qa/MainForm.cs using SaaS.Mailer.Models; using System; using System.Linq; using System.Windows.Forms; namespace SaaS.WinService.Mailer.Qa { public partial class MainForm : Form { public MainForm() { InitializeComponent(); cbxLanguage.SelectedIndex = 0; var emailTemplates = Enum.GetNames(typeof(EmailTemplate)).OrderBy(e => e); foreach (var emailTemplate in emailTemplates) cbxEmailTemplate.Items.Add(emailTemplate); cbxEmailTemplate.SelectedIndex = 0; cbxProducts.SelectedIndex = 0; } private string FirstName { get { return txtFirstName.Text.Trim(); } } private string LastName { get { return txtLastName.Text.Trim(); } } private string Email { get { return txtEmail.Text.Trim(); } } private string Language { get { return cbxLanguage.Text.Trim(); } } private string Product { get { return cbxProducts.Text.Trim(); } } private EmailTemplate emailTemplate { get { return (EmailTemplate)Enum.Parse(typeof(EmailTemplate), cbxEmailTemplate.SelectedItem.ToString()); } } private enum EmailTemplate { //SupportIntro, TipsTricks AccountCreationCompleteNotification, BusinessToPremiumNotification, eSignEmailConfirmationNotification, eSignSignPackageNotification, MicrotransactionCreatePassword, MergeConfirmation, PasswordChangedNotification, ProductAssignedNotificationCreatePassword, Welcome, WelcomePurchase, WelcomeFreeProductCovermountNotification, EmailConfirmationCovermount, EmailConfirmation, EmailConfirmationLate, EmailChange, EmailChangeConfirmation, OsSunset, PolicyUpdate, ProductSuspend, ProductRenewalOff, ProductAssignedCreatePassword, ProductUnassigned, WelcomePurchaseMigrationFromSuiteNotification } private void btnOk_Click(object sender, EventArgs e) { var notification = new Notification { FirstName = FirstName, LastName = LastName, Email = Email }; switch (emailTemplate) { case EmailTemplate.AccountCreationCompleteNotification: Sender.AccountCreationCompleteNotification(Language, notification); break; case EmailTemplate.BusinessToPremiumNotification: Sender.BusinessToPremiumNotification(Language, notification); break; case EmailTemplate.eSignEmailConfirmationNotification: Sender.eSignEmailConfirmationNotification(Language, notification); break; case EmailTemplate.eSignSignPackageNotification: Sender.eSignSignPackageNotification(Language, notification); break; case EmailTemplate.MicrotransactionCreatePassword: Sender.MicrotransactionCreatePassword(Language, notification); break; case EmailTemplate.MergeConfirmation: Sender.MergeConfirmation(Language, notification); break; case EmailTemplate.PasswordChangedNotification: Sender.PasswordChangedNotification(Language, notification); break; case EmailTemplate.ProductAssignedNotificationCreatePassword: Sender.ProductAssignedNotificationCreatePassword(Language, notification); break; case EmailTemplate.Welcome: Sender.Welcome(Language, notification); break; case EmailTemplate.WelcomePurchase: Sender.WelcomePurchase(Language, notification, Product); break; case EmailTemplate.WelcomeFreeProductCovermountNotification: Sender.WelcomeFreeProductCovermountNotification(Language, notification, Product); break; case EmailTemplate.WelcomePurchaseMigrationFromSuiteNotification: Sender.WelcomePurchaseMigrationFromSuiteNotification(Language, notification, Product); break; case EmailTemplate.EmailConfirmationCovermount: Sender.EmailConfirmationCovermount(Language, notification); break; case EmailTemplate.EmailConfirmation: Sender.EmailConfirmation(Language, notification); break; case EmailTemplate.EmailConfirmationLate: Sender.EmailConfirmationLate(Language, notification); break; case EmailTemplate.EmailChange: Sender.EmailChange(Language, notification); break; case EmailTemplate.EmailChangeConfirmation: Sender.EmailChangeConfirmation(Language, notification); break; case EmailTemplate.OsSunset: Sender.OsSunset(Language, notification); break; case EmailTemplate.PolicyUpdate: Sender.PolicyUpdate(Language, notification); break; case EmailTemplate.ProductSuspend: Sender.ProductSuspend(Language, notification, Product); break; case EmailTemplate.ProductRenewalOff: Sender.ProductRenewalOff(Language, notification, Product); break; case EmailTemplate.ProductAssignedCreatePassword: Sender.ProductAssignedCreatePassword(Language, notification, Product); break; case EmailTemplate.ProductUnassigned: Sender.ProductUnassigned(Language, notification, Product); break; default: MessageBox.Show("Email template is not exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } MessageBox.Show("Done"); } private void cbxEmailTemplate_SelectedIndexChanged(object sender, EventArgs e) { lblProducts.Visible = emailTemplate == EmailTemplate.ProductSuspend || emailTemplate == EmailTemplate.ProductRenewalOff || emailTemplate == EmailTemplate.ProductRenewalOff; cbxProducts.Visible = lblProducts.Visible; } } }<file_sep>/Shared/SaaS.Identity/NpsRepository/INpsRepository.cs using SaaS.Data.Entities.Oauth; using System; using System.Threading.Tasks; namespace SaaS.Identity { public interface INpsRepository : IDisposable { Task Rate(string questioner, Guid? accountId, string clientName, string clientVersion, byte rating, byte? ratingUsage, string comment); } }<file_sep>/Shared/SaaS.Identity/AuthRepository/AuthRepository.Account.cs using Microsoft.AspNet.Identity; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View.Accounts; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthRepository { public string HashPassword(string password) { return _userManager.PasswordHasher.HashPassword(password); } public bool PasswordIsEqual(string source, string password) { return _context.PasswordIsEqual(source, password); } public async Task<Account> AccountGetAsync(Guid accountId) { return await _context.AccountGetAsync(accountId); } public async Task<Account> AccountGetAsync(string userEmail, bool isIncludeSubEmails = false) { return await _context.AccountGetAsync(userEmail, isIncludeSubEmails: isIncludeSubEmails); } public async Task<Account> AccountGetAsync(string primaryEmail, string password) { return await _context.AccountGetAsync(primaryEmail, password); } public async Task<List<Account>> AccountsGetAsync(string filter, string globalOrderId) { return await _context.AccountsGetAsync(filter, globalOrderId); } public async Task<Account> AccountGetByTransactionOrderUidAsync(string transactionOrderUid) { return await _context.AccountGetByTransactionOrderUidAsync(transactionOrderUid); } public async Task AccountDeleteAsync(Guid accountId) { await _context.AccountDeleteAsync(accountId); } public async Task AccountDeleteAsync(Account user) { await _context.AccountDeleteAsync(user.Id); } public async Task AccountActivateAsync(Account account) { if (!object.Equals(account, null) && (!account.IsActivated || account.IsBusiness) && !account.IsAnonymous) { account.IsActivated = true; await _context.AccountActivateAsync(account.Id); } } public async Task AccountMaskAsBusinessAsync(Account account) { if (object.Equals(account, null) || account.IsBusiness) return; account.IsBusiness = true; account.RefreshModifyDate(); await _userManager.UpdateAsync(account); } public async Task AccountOptinSetAsync(Account account, bool? optin) { if (object.Equals(account, null) || !optin.HasValue) return; if (account.Optin.GetValueOrDefault() == optin.Value) return; account.Optin = optin.Value; account.RefreshModifyDate(); await _userManager.UpdateAsync(account); } public async Task AccountNeverLoginSetAsync(Account account) { if (object.Equals(account, null) || !account.NeverLogged) return; account.NeverLogged = false; await _userManager.UpdateAsync(account); } public async Task AccountVisitorIdSetAsync(Account account, Guid? visitorId) { if (object.Equals(account, null) || !visitorId.HasValue) return; await _context.AccountVisitorIdSetAsync(account.Id, visitorId.Value); } public async Task<IdentityResult> AccountCreateAsync(Account user, string password) { if (string.IsNullOrEmpty(password)) return await _userManager.CreateAsync(user); return await _userManager.CreateAsync(user, password); } public async Task<IdentityResult> AccountChangePasswordAsync(Guid userId, string oldPassword, string newPassword) { return await _userManager.ChangePasswordAsync(userId, oldPassword, newPassword); } public async Task<IdentityResult> AccountConfirmEmailAsync(Guid userId) { string token = await _userManager.GenerateEmailConfirmationTokenAsync(userId); token = ToBase64String(token); return await AccountConfirmEmailAsync(userId, token); } public async Task<IdentityResult> AccountConfirmEmailAsync(Guid userId, string token) { token = FromBase64String(token); return await _userManager.ConfirmEmailAsync(userId, token); } public async Task<IdentityResult> AccountResetPasswordAsync(Guid userId, string token, string password) { token = FromBase64String(token); return await _userManager.ResetPasswordAsync(userId, token, password); } public async Task<IdentityResult> AccountUpdateAsync(Account user) { return await _userManager.UpdateAsync(user); } public async Task<IdentityResult> AccountPasswordSetAsync(Account user, string password) { user.Password = <PASSWORD>); return await _userManager.UpdateAsync(user); } public List<ViewAccountEmail> AccountEmailsGet(Guid accountId) { return _context.AccountEmailsGet(accountId); } public async Task<List<AccountSystem>> AccountSystemsGetAsync(AccountProductPair pair) { return await _context.AccountSystemsGetAsync(pair); } public async Task<Account> AccountAnonymousCreateAsync(string password) { var account = new Account { Email = string.Format("{<EMAIL>", Guid.NewGuid().ToString("N")), IsAnonymous = true }; var result = await _userManager.CreateAsync(account, password); if (!result.Succeeded) return null; account.Password = <PASSWORD>; return account; } } }<file_sep>/Test/SaaS.Api.Test/ESignHelper.cs using Newtonsoft.Json.Linq; using SaaS.Api.Test.Models.Api.Oauth; using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace SaaS.Api.Test { internal class ESignHelper { protected static readonly AppSettings _appSettings = new AppSettings(); private static async Task<HttpClient> CreateHttpClient() { TokenResultModel token = await OAuthHelper.SignIn(); var client = new HttpClient(); client.BaseAddress = _appSettings.PathToESignApi; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", string.Format("{0} {1}", token.token_type, token.access_token)); return client; } public static async Task<HttpResponseMessage> GetPackages() { using (var client = await CreateHttpClient()) return await client.GetAsync("api-esign20/v1/packages?query=inbox"); } public static async Task<HttpResponseMessage> PostPackages() { using (var client = await CreateHttpClient()) return await client.PostAsync("api/packages", null); } public static async Task<HttpResponseMessage> GetPackageId(Guid packageId) { using (var client = await CreateHttpClient()) return await client.GetAsync(string.Format("api/packages/{0}", packageId)); } public static async Task<HttpResponseMessage> PostPackageId(Guid packageId, JObject content) { using (var client = await CreateHttpClient()) return await client.PostAsJsonAsync(string.Format("api/packages/{0}", packageId), content); } public static async Task<HttpResponseMessage> DeletePackageId(Guid packageId) { using (var client = await CreateHttpClient()) return await client.DeleteAsync(string.Format("api/packages/{0}", packageId)); } } } <file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.Account.cs using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View.Accounts; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthDbContext { internal async Task<Account> AccountGetAsync(Guid accountId) { var sqlParams = new SqlParameter[] { accountId.ToSql("id") }; return await ExecuteReaderAsync<Account>("[accounts].[pAccountGetById]", sqlParams); } internal async Task<Account> AccountGetAsync(string email, bool isIncludeSubEmails) { var sqlParams = new SqlParameter[] { email.ToSql("email"), isIncludeSubEmails.ToSql("isIncludeSubEmails") }; return await ExecuteReaderAsync<Account>("[accounts].[pAccountGetByEmail]", sqlParams); } internal async Task<Account> AccountGetAsync(string primaryEmail, string password) { var user = await AccountGetAsync(primaryEmail, isIncludeSubEmails: false); if (!object.Equals(user, null) && !PasswordIsEqual(user.Password, password)) user = null; return user; } internal async Task<List<Account>> AccountsGetAsync(string filter, string globalOrderId) { var sqlParams = new SqlParameter[] { filter.ToSql("filter"), globalOrderId.ToSql("globalOrderId") }; return await ExecuteReaderCollectionAsync<Account>("[accounts].[pAccountGetByFilter]", sqlParams); } internal async Task<Account> AccountGetByTransactionOrderUidAsync(string transactionOrderUid) { var sqlParams = new SqlParameter[] { transactionOrderUid.ToSql("transactionOrderUid") }; return await ExecuteReaderAsync<Account>("[accounts].[pAccountGetByTransactionOrderUid]", sqlParams); } internal async Task AccountDeleteAsync(Guid accountId) { var status = await ExecuteReaderAsync<int>("[accounts].[pAccountDelete]", accountId); if (status != 0) { switch (status) { case -50001: throw new Exception("Customer is not exists."); case -50013: throw new Exception("Customer can't bee removed."); default: throw new Exception(); } } } internal async Task AccountActivateAsync(Guid accountId) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId"), 0.ToSql("mode") }; await ExecuteNonQueryAsync("[accounts].[pAccountActivate]", sqlParams); } internal async Task AccountVisitorIdSetAsync(Guid accountId, Guid visitorId) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId"), visitorId.ToSql("visitorId") }; await ExecuteNonQueryAsync("[accounts].[pAccountVisitorSet]", sqlParams); } internal List<ViewAccountEmail> AccountEmailsGet(Guid accountId) { return ExecuteReaderCollection<ViewAccountEmail>("[accounts].[pAccountGetEmailsByAccountId]", CreateSqlParams(accountId)); } public async Task<List<AccountSystem>> AccountSystemsGetAsync(AccountProductPair pair) { var sqlParams = new SqlParameter[] { pair.AccountId.ToSql("accountId"), pair.AccountProductId.ToSql("accountProductId") }; return await ExecuteReaderCollectionAsync<AccountSystem>("[oauth].[pAccountSystemSelectByAccountIdProductId]", sqlParams); } } }<file_sep>/Test/SaaS.Api.Test/Models/Api/Oauth/RegisterViewModel.cs  namespace SaaS.Api.Test.Models.Api.Oauth { public class RegisterViewModel : AuthViewModel { public string Password { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } }<file_sep>/Web.Api/SaaS.Api/Oauth/Providers/SaaSScopeHelper.cs using Microsoft.Owin.Security.OAuth; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View; using SaaS.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace SaaS.Api.Oauth.Providers { internal class SaaSScopeWorkerFactory { private readonly static StringComparer _comparer = StringComparer.InvariantCultureIgnoreCase; internal static SaaSScopeBase Create(string[] scope) { if (!object.Equals(scope, null)) { if (scope.Contains("editor", _comparer)) return new EditorSaaSScopeHelper(); if (scope.Contains("webeditor", _comparer)) return new WebEditorSaaSScopeWorker(); } return new DefaultSaaSScopeHelper(); } internal static SaaSScopeBase Create(string[] scope, IAuthRepository auth = null, IAuthProductRepository authProduct = null) { var worker = Create(scope); worker.Auth = auth; worker.AuthProduct = authProduct; return worker; } internal static SaaSScopeBase Create(string scope, IAuthRepository auth = null, IAuthProductRepository authProduct = null) { return Create(StringToScope(scope), auth, authProduct); } internal static SaaSScopeBase Create(string[] scope, BaseValidatingTicketContext<OAuthAuthorizationServerOptions> context, AuthRepository auth, AuthProductRepository authProduct) { var worker = Create(scope, auth, authProduct); worker.Context = context; return worker; } internal static string ScopeToString(string[] scope) { return object.Equals(scope, null) || scope.Length == 0 ? null : string.Join(",", scope); } internal static string[] StringToScope(string scope) { if (string.IsNullOrEmpty(scope)) return null; return scope.Split(','); } } internal abstract class SaaSScopeBase { internal BaseValidatingTicketContext<OAuthAuthorizationServerOptions> Context; internal IAuthRepository Auth; internal IAuthProductRepository AuthProduct; internal virtual async Task<bool> ValidateDeviceAsync(Account user) { return await Task.FromResult(true); } internal virtual bool ValidateSessionTokenAsync(Account user, IEnumerable<SessionToken> sessions, SessionToken session, ViewAccountProduct product) { return true; } internal virtual async Task<bool> ValidateAccountSystemAsync(Account user, SessionToken session, ViewAccountProduct product) { return await Task.FromResult(true); } internal virtual async Task SessionTokenInsertAsync(SessionToken token, Guid? oldId) { await Auth.SessionTokenInsertAsync(token, oldId, false, false); } internal virtual void FilterProducts(IList<ViewAccountProduct> products, SessionToken session) { } internal virtual async Task GrantClaims(ClaimsIdentity identity) { var sessionToken = Context.OwinContext.Get<SessionToken>("sessionToken"); if (sessionToken.AccountProductId.HasValue) { var products = await AuthProduct.AccountProductsGetAsync(sessionToken.AccountId, sessionToken.SystemId); var product = products.FirstOrDefault(e => e.AccountProductId == sessionToken.AccountProductId.Value); if (object.Equals(product, null) || product.IsDisabled) Context.Response.Headers.Add("Product-IsDisabled", new[] { bool.TrueString }); if (object.Equals(product, null) || product.IsExpired) Context.Response.Headers.Add("Product-IsExpired", new[] { bool.TrueString }); if (!object.Equals(product, null) && !product.IsDisabled) UserManagerHelper.GetAllowedModules(products, sessionToken.AccountProductId.Value, identity); } } } internal sealed class DefaultSaaSScopeHelper : SaaSScopeBase { internal override Task GrantClaims(ClaimsIdentity identity) { return Task.Run(() => { }); } } internal sealed class EditorSaaSScopeHelper : SaaSScopeBase { private readonly static StringComparison _comparison = StringComparison.InvariantCultureIgnoreCase; internal override async Task<bool> ValidateDeviceAsync(Account user) { SystemSignInData data = Context.OwinContext.Get<SystemSignInData>("systemSignInData") ?? new SystemSignInData { }; if ((object.Equals(data, null)) || (data.MachineKey == Guid.Empty && string.IsNullOrEmpty(data.MotherboardKey) && string.IsNullOrEmpty(data.PhysicalMac))) { Context.SetError("invalid_grant", "System is null or empty."); return false; } var system = await Auth.SystemInsertAsync(new Data.Entities.Oauth.OauthSystem { MachineKey = data.MachineKey, MotherboardKey = data.MotherboardKey, PhysicalMac = data.PhysicalMac, IsAutogeneratedMachineKey = data.IsAutogeneratedMachineKey, PcName = data.PcName }); Context.OwinContext.Set("systemId", system.Id); return true; } internal override bool ValidateSessionTokenAsync(Account user, IEnumerable<SessionToken> sessions, SessionToken session, ViewAccountProduct product) { var accountProductSessions = sessions.Where(e => (e.AccountProductId.HasValue && e.AccountProductId.Value == product.AccountProductId && e.SystemId.HasValue && e.SystemId.Value != session.SystemId.Value) || (e.Id == session.Id)); var limit = 3; #if PdfSam limit = 2; #endif #if LuluSoft if (product.IsFree) limit = 10; #endif //if user is logged into more than {{limit}} devices return accountProductSessions.Count() <= limit; } internal override async Task<bool> ValidateAccountSystemAsync(Account account, SessionToken session, ViewAccountProduct product) { if (!product.IsPPC) return await Task.FromResult(true); var accountSystems = await Auth.AccountSystemsGetAsync(new AccountProductPair(account.Id, product.AccountProductId)); var accountSystemsWithoutCurrent = accountSystems.Where(e => e.SystemId != session.SystemId.Value); var limit = 1; //if user's license associated more than {{limit}} devices return await Task.FromResult(accountSystemsWithoutCurrent.Count() < limit); } internal override async Task SessionTokenInsertAsync(SessionToken token, Guid? oldId) { await Auth.SessionTokenInsertAsync(token, oldId, false, false); } internal override void FilterProducts(IList<ViewAccountProduct> products, SessionToken session) { var clientVersion = session.GetClientVersion(); if (object.Equals(clientVersion, null)) return; for (int index = 0; index < products.Count; index++) { var product = products[index]; if (!product.IsPPC) continue; var productVersion = product.GetProductVersion(); if (object.Equals(productVersion, null)) continue; if (clientVersion.Major != productVersion.Major) products.RemoveAt(index--); } if ("desktop".Equals(session.ClientName, _comparison)) { for (int index = 0; index < products.Count; index++) { var product = products[index]; #if LuluSoft if ("soda-business-trial-2-week".Equals(product.ProductUnitName, _comparison) || "soda-business-trial-monthly".Equals(product.ProductUnitName, _comparison) || "soda-business-trial-3-month".Equals(product.ProductUnitName, _comparison) || "soda-business-monthly".Equals(product.ProductUnitName, _comparison) || "soda-business-yearly".Equals(product.ProductUnitName, _comparison) || "soda-business-2-year".Equals(product.ProductUnitName, _comparison)) { var ocrTess = product.Modules.FirstOrDefault(module => "ocr-tess".Equals(module.Module, _comparison)); if (!object.Equals(ocrTess, null)) ocrTess.Module = "ocr"; } #endif #if PdfForge if ("architect-free".Equals(product.ProductUnitName, _comparison) || "architect-esign-yearly".Equals(product.ProductUnitName, _comparison) || "architect-esign-10-pack".Equals(product.ProductUnitName, _comparison) || "architect-esign-trial-2-week".Equals(product.ProductUnitName, _comparison)) { } else products.RemoveAt(index--); #endif } } #if PdfForge //PA-2746 var hasOCR = products.Any(product => ("architect-ocr-yearly".Equals(product.ProductUnitName, _comparison) || "architect-ocr-standard-yearly".Equals(product.ProductUnitName, _comparison)) && !product.IsDisabled && !product.IsExpired && !product.IsTrial); if (hasOCR) { foreach (var proProd in products.Where(product => ("architect-pro-ppc".Equals(product.ProductUnitName, _comparison) || "architect-pro-yearly".Equals(product.ProductUnitName, _comparison)) && !product.IsDisabled && !product.IsExpired && !product.IsTrial)) { proProd.IsUpgradable = false; } } #endif } } internal sealed class WebEditorSaaSScopeWorker : SaaSScopeBase { internal override async Task SessionTokenInsertAsync(SessionToken token, Guid? oldId) { await Auth.SessionTokenInsertAsync(token, oldId, true, false); } internal override void FilterProducts(IList<ViewAccountProduct> products, SessionToken session) { for (int index = 0; index < products.Count; index++) { if (products[index].IsPPC) products.RemoveAt(index--); } } } }<file_sep>/Web.Api/SaaS.UI.Admin/js/directives/external-connected-account.js (function () { 'use strict'; angular .module('app.directives') .directive('ngExternalConnectedAccount', directive) directive.$inject = ['$filter']; var _init = function (element, provider) { element .addClass('fab') .addClass('fa-' + provider) .css({ 'font-size': 18 }); switch (provider) { case 'google': element.css({ color: '#d62d20' }); break; case 'facebook': element.css({ color: '#3b5998' }); break; case 'microsoft': element.css({ color: '#00a1f1' }); break; } }; function directive() { return { link: link, restrict: 'A' }; function link(scope, element, attrs) { var text = element.text(); _init(element, attrs.ngExternalConnectedAccount); } }; })();<file_sep>/Web.Api/SaaS.Sso/tasks/app.serve.js const gulp = require('gulp'); const browserSync = require('browser-sync').create(); gulp.task('app.serve', function () { browserSync.init({ server: { baseDir: "./dist" } }); gulp .watch(['dist/index.html', 'dist/**/*.css', 'dist/**/*.js']) .on("change", browserSync.reload); });<file_sep>/Shared/SaaS.Api.Models/Oauth/AuthViewModel.cs using System; using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Oauth { public class AuthViewModel { [Required, DataType(DataType.EmailAddress)] [RegularExpression(@"(?i)^[-a-z0-9!#$%&'*+\/=?^_`{|}~]+(\.[-a-z0-9!#$%&'*+\/=?^_`{|}~]+)*@([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?\.)*[a-z]{1,20}$")] public string Email { get; set; } } public class AuthIdViewModel { public Guid AccountId { get; set; } } public class AuthNameViewModel : AuthViewModel { [MaxLength(300), RegularExpression(@"^[^\^<>()\[\]\\;:@№%\|$%*?#&¸¼!+€£¢¾½÷פ¶»¥¦µ©®°§«´¨™±°º¹²³ª¯¬`""'/]*$")] public string FirstName { get; set; } [MaxLength(300), RegularExpression(@"^[^\^<>()\[\]\\;:@№%\|$%*?#&¸¼!+€£¢¾½÷פ¶»¥¦µ©®°§«´¨™±°º¹²³ª¯¬`""'/]*$")] public string LastName { get; set; } } public class AuthPasswordViewModel : AuthViewModel { public string Password { get; set; } } } <file_sep>/Shared/SaaS.Identity/AuthRepository/AuthRepository.SessionToken.cs using SaaS.Data.Entities.Oauth; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthRepository { public async Task<SessionToken> SessionTokenGetAsync(Guid id) { return await _context.SessionTokenGetAsync(id); } public async Task<List<SessionToken>> SessionTokensGetAsync(Guid accountId) { return await _context.SessionTokensGetAsync(accountId); } public async Task SessionTokenDeleteAsync(Guid id) { await _context.SessionTokenDeleteAsync(id); } public async Task SessionTokenInsertAsync(SessionToken token, Guid? oldId, bool isRemoveOldSessions, bool isInsertAccountSystem) { await _context.SessionTokenInsertAsync(token, oldId, isRemoveOldSessions, isInsertAccountSystem); } } }<file_sep>/Shared/SaaS.Identity.Admin/UserValidator.cs using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SaaS.Identity.Admin { public class UserValidator<TUser> : IIdentityValidator<TUser> where TUser : User { private readonly UserManager<TUser, Guid> _manager; public UserValidator() { } public UserValidator(UserManager<TUser, Guid> manager) { _manager = manager; } public async Task<IdentityResult> ValidateAsync(TUser item) { var errors = new List<string>(); if (_manager != null) { var otherAccount = await _manager.FindByEmailAsync(item.Login); if (otherAccount != null && otherAccount.Id != item.Id) errors.Add("Select a different email address. An account has already been created with this email address."); } return errors.Any() ? IdentityResult.Failed(errors.ToArray()) : IdentityResult.Success; } } } <file_sep>/Shared/SaaS.Mailer/Models/EmailChangeNotification.cs using System.Xml.Serialization; namespace SaaS.Mailer.Models { [XmlRoot("xml")] public class EmailChangeNotification : Notification { public EmailChangeNotification() { } public EmailChangeNotification(Notification user, string newEmail) : base(user) { NewEmail = newEmail; } [XmlElement("newEmail")] public string NewEmail { get; set; } } } <file_sep>/Web.Api/SaaS.Api/Controllers/Api/ConfigController.cs using System; using System.Web.Http; using WebApi.OutputCache.V2; namespace SaaS.Api.Controllers.Api { [RoutePrefix("api/config")] public class ConfigController : ApiController { [HttpGet] [CacheOutput(ClientTimeSpan = 864000, ServerTimeSpan = 864000)] public IHttpActionResult Config() { return Ok(new { minRequestDelay = (ulong)TimeSpan.FromMinutes(1).TotalSeconds, clientCacheTimeLive = (ulong)TimeSpan.FromDays(7).TotalSeconds }); } } }<file_sep>/Shared/SaaS.Api.Client/SaaSApiToken.cs using Newtonsoft.Json; namespace SaaS.Api.Client { public class SaaSApiToken { [JsonProperty(PropertyName = "access_token")] public string AccessToken { get; set; } [JsonProperty(PropertyName = "refresh_token")] public string RefreshToken { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public ulong Status { get; set; } } } <file_sep>/Web.Api/SaaS.Zendesk/src/js/services/api.js angular .module('app.services') .factory('$api', ['$http', '$brand', function factory($http, $brand) { const _config = { asJson: true, isOauth: true }; const _accountStatusEnum = { none: 0, isActivated: 1 << 0, isAnonymous: 1 << 1, isBusiness: 1 << 2 };; const _productStatusEnum = { none: 0, isDisabled: 1 << 0, isExpired: 1 << 1, isTrial: 1 << 2, isFree: 1 << 3, isMinor: 1 << 4, isDefault: 1 << 5, isPPC: 1 << 6, isUpgradable: 1 << 7, isNew: 1 << 8, isPaymentFailed: 1 << 9, isRenewal: 1 << 10, isOwner: 1 << 11, IsNotAbleToRenewCreditCartExpired: 1 << 12 }; var service = {}; service.account = { isActivated: (account) => { return !!(account.status & _accountStatusEnum.isActivated); }, isBusiness: (account) => { return !!(account.status & _accountStatusEnum.isBusiness); }, get: (params) => { var method = 'api/account/'; if (params.accountId) { method += params.accountId; delete params.accountId; } let config = angular.copy(_config); config.params = params; return $http.get($brand.getApiUri(method), config); } }; service.product = { isDisabled: (product) => { return !!(product.status & _productStatusEnum.isDisabled); }, isTrial: (product) => { return !!(product.status & _productStatusEnum.isTrial); }, isFree: (product) => { return !!(product.status & _productStatusEnum.isFree); }, isPPC: (product) => { return !!(product.status & _productStatusEnum.isPPC); }, isRenewal: (product) => { return !!(product.status & _productStatusEnum.isRenewal); }, isOwner: (product) => { return !!(product.status & _productStatusEnum.isOwner); } }; service.account.getSubEmails = (params) => { return $http.get($brand.getApiUri(`api/account/${params.accountId}/sub-email`), _config); }; service.account.removeSubEmail = (params) => { return $http.delete($brand.getApiUri(`api/account/${params.accountId}/sub-email/${params.id}`), _config); }; service.account.getExternalSessionTokens = (params) => { return $http.get($brand.getApiUri(`api/account/${params.accountId}/external/session-token`), _config); }; service.account.getOwnerProducts = (params) => { return $http.get($brand.getApiUri(`api/account/${params.accountId}/owner-product`), _config); }; service.account.getOwnerProductDetails = (params) => { return $http.get($brand.getApiUri(`api/account/${params.accountId}/owner-product/${params.accountProductId}`), _config); }; return service; }]);<file_sep>/Web.Api/SaaS.Sso/src/js/services/utils.js angular.module('app.services') .factory('$utils', () => { let service = {}; service.query = (query) => { let json = {}; try { if (typeof query === 'undefined') query = document.location.search; var split = query.replace(/(^\?)/, '').split('&'); for (let i = 0; i < split.length; ++i) { let item = split[i]; let index = item.indexOf('='); if (index === -1) continue; let key = item.substring(0, index); let value = item.substr(index + 1).trim(); json[key.toLowerCase()] = decodeURIComponent(value); } } catch (e) { } return json; }; service.params = (json) => { let queryString = []; for (let key in json) queryString.push(key.toLowerCase() + '=' + encodeURIComponent(json[key])); return queryString.join('&'); }; service.hash = (value) => { let hash = 0; if (!value) return hash; for (let index = 0; index < value.length; index++) hash = value.charCodeAt(index) + ((hash << 5) - hash); return hash; }; service.intToRgb = (value) => { let str = (value & 0x00FFFFFF) .toString(16) .toUpperCase(); return '00000'.substring(0, 6 - str.length) + str; }; service.stringToColor = (value) => { let hash = service.hash(value); let rgb = service.intToRgb(hash); return `#${rgb}`; }; return service; });<file_sep>/Web.Api/SaaS.Api.Admin/App_Start/WebApiConfig.cs using Newtonsoft.Json.Serialization; using System.Linq; using System.Net.Http.Formatting; using System.Web.Http; namespace SaaS.Api.Admin { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.Remove(config.Formatters.XmlFormatter); var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; json.SerializerSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ssZ"; json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; var contractResolver = (DefaultContractResolver)json.SerializerSettings.ContractResolver; contractResolver.IgnoreSerializableAttribute = true; } } }<file_sep>/Shared/SaaS.ModuleFeatures/Model/Module.cs namespace SaaS.ModuleFeatures.Model { internal class Module { public string Name { get; set; } public Feature[] Features { get; set; } } }<file_sep>/Shared/SaaS.Api.Core/Filters/ValidateNullModelAttribute.cs using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace SaaS.Api.Core.Filters { public class ValidateNullModelAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { foreach (var item in actionContext.ActionArguments) { if (!object.Equals(item.Value, null)) return; } actionContext.Response = actionContext.Request.CreateExceptionResponse(errorDescription: "Model is required."); } } }<file_sep>/Test/SaaS.Api.Test/Oauth/Account.cs using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SaaS.Api.Test.Models.Api.Oauth; using System; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace SaaS.Api.Test.Oauth { [TestClass] public class Account : HttpTestHelper { [TestMethod] public async Task TEST() { var token = await OAuthHelper.RegisterAnonymous(); //var json = await AssertIsTrue(await OAuthHelper.Auto(token.access_token)); //products = await OAuthHelper.GetProduct(new Guid("5d3dda08-0946-4107-97d0-188d86c9959f"), token.access_token); //json = await AssertIsTrue(products); } #region Register [TestMethod] public async Task Register() { var model = OAuthHelper.RegisterViewModel(); Debug.WriteLine("Trying register user..."); var json = await AssertIsTrue(await OAuthHelper.Register(model)); } [TestMethod] public async Task RegisterUnique() { var model = OAuthHelper.CreateRandomRegisterViewModel(); Debug.WriteLine("Trying register unique user..."); var json = await AssertIsTrue(await OAuthHelper.Register(model)); } [TestMethod] public async Task RegisterAnonymous() { Debug.WriteLine("Trying register anonymous user ..."); var json = await AssertIsTrue(await OAuthHelper.RegisterAnonymous()); } [TestMethod] public async Task RegisterNotUnique() { var model = OAuthHelper.CreateRandomRegisterViewModel(); Debug.WriteLine("Trying register not unique user..."); await OAuthHelper.Register(model); var json = await AssertIsFalse(await OAuthHelper.Register(model)); } [TestMethod] public async Task RegisterWithNullModel() { Debug.WriteLine("Trying register with null module..."); var json = await AssertIsFalse(await OAuthHelper.Register(null)); } [TestMethod] public async Task RegisterWithWrongEmail() { var model = OAuthHelper.CreateRandomRegisterViewModel(); model.Email = "hello"; Debug.WriteLine("Trying register unique user with wrong email..."); var json = await AssertIsFalse(await OAuthHelper.Register(model)); } [TestMethod] public async Task RegisterWithEmptyEmail() { var model = OAuthHelper.CreateRandomRegisterViewModel(); model.Email = null; Debug.WriteLine("Trying register unique user with empty email..."); var json = await AssertIsFalse(await OAuthHelper.Register(model)); } [TestMethod] public async Task RegisterWithEmptyPassword() { var model = OAuthHelper.CreateRandomRegisterViewModel(); model.Password = <PASSWORD>; Debug.WriteLine("Trying register unique user with empty password..."); var json = await AssertIsFalse(await OAuthHelper.Register(model)); } #endregion #region SignIn [TestMethod] public async Task SignIn() { var token = await OAuthHelper.SignIn(); //var token2 = await OAuthHelper.SignIn(); var response = await OAuthHelper.RefreshToken(token.refresh_token); } [TestMethod] public async Task Logout() { var token = await OAuthHelper.Logout(); } [TestMethod] public async Task ReSignIn() { var token = await OAuthHelper.ReSignIn(); await OAuthHelper.RefreshToken(token.refresh_token); } #endregion #region SendActivationEmail [TestMethod] public async Task SendActivationEmail() { var model = OAuthHelper.RegisterViewModel(); Debug.WriteLine("Trying to send activation email..."); var json = await AssertIsTrue(await OAuthHelper.SendActivationEmail(model)); } [TestMethod] public async Task SendActivationEmailWithNullModel() { Debug.WriteLine("Trying to send activation email with null module..."); var json = await AssertIsFalse(await OAuthHelper.SendActivationEmail(null)); } [TestMethod] public async Task SendActivationEmailWithEmptyEmail() { var model = new AuthViewModel(); Debug.WriteLine("Trying to send activation email with empty email..."); var json = await AssertIsFalse(await OAuthHelper.SendActivationEmail(model)); } #endregion #region Products [TestMethod] public async Task Products() { var json = await AssertIsTrue(await OAuthHelper.GetProduct(new Guid("14732597-54c2-42e1-8390-5aa86387e1af"))); var access_token = JObject.Parse(json).GetValue("access_token").Value<string>(); var d = await OAuthHelper.GetModules(access_token ); json = await d.Content.ReadAsStringAsync(); } #endregion #region ChangePassword //[TestMethod] //public async Task ChangePassword() //{ // var changePasswordModel = new ChangePasswordViewModel() // { // OldPassword = "<PASSWORD>", // NewPassword = "<PASSWORD>!!!" // }; // var json = await AssertIsTrue(await OAuthHelper.ChangePassword(changePasswordModel)); //} #endregion //#region RecoverPassword //private static async Task<HttpResponseMessage> RecoverPassword(AuthViewModel model) //{ // using (var client = CreateHttpClient()) // { // var response = await client.PostAsJsonAsync<AuthViewModel>("api/oauth/account/recover-password", model); // Debug.WriteLine("Response status code: {0}", response.StatusCode); // return response; // } //} //[TestMethod] //public async Task RecoverPassword() //{ // var model = await CreateRegisterViewModel(); // Debug.WriteLine("Trying to recover password in user..."); // AssertIsTrue(await RecoverPassword(model)); // Debug.WriteLine("Trying sign in user with old password..."); // AssertIsFalse(await SignIn(model.Email, model.Password)); //} ////[TestMethod] ////public async Task RecoverPasswordForNormalUser() ////{ //// var model = new RegisterViewModel() //// { //// Email = "<EMAIL>", //// Password = "<PASSWORD>", //// ConfirmPassword = "<PASSWORD>", //// FirstName = "alex", //// LastName = "zverev" //// }; //// var response = await Register(model); //// Debug.WriteLine("Trying to recover password in user..."); //// response = await RecoverPassword(model); //// Assert.IsTrue(response.IsSuccessStatusCode); //// Debug.WriteLine("Trying sign in user with old password..."); //// response = await SignIn(model.Email, model.Password); //// Assert.IsFalse(response.IsSuccessStatusCode); ////} //#endregion //#endregion //#region Info //[TestMethod] //public async Task GetAccountInfoForNormalUser() //{ // TokenResultModel token = await SignInForNormalUser(); // using (var client = CreateHttpClient()) // { // client.DefaultRequestHeaders.Add("Authorization", string.Format("{0} {1}", token.token_type, token.access_token)); // AssertIsTrue(await client.GetAsync("api/oauth/account/info")); // } //} //[TestMethod] //public async Task GetAccountInfoNotAuthorized() //{ // using (var client = CreateHttpClient()) // AssertIsFalse(await client.GetAsync("api/oauth/account/info")); //} //[TestMethod] //public async Task SetAccountInfoForNormalUser() //{ // TokenResultModel token = await SignInForNormalUser(); // var changeInfoViewModel = new ChangeInfoViewModel() // { // FirstName = string.Format("FirstName - {0}", Guid.NewGuid()), // LastName = string.Format("LastName - {0}", Guid.NewGuid()) // }; // using (var client = CreateHttpClient()) // { // client.DefaultRequestHeaders.Add("Authorization", string.Format("{0} {1}", token.token_type, token.access_token)); // AssertIsTrue(await client.PostAsJsonAsync<ChangeInfoViewModel>("api/oauth/account/info", changeInfoViewModel)); // } // token = await SignInForNormalUser(); // Assert.IsTrue(changeInfoViewModel.FirstName == token.firstName); // Assert.IsTrue(changeInfoViewModel.LastName == token.lastName); //} //[TestMethod] //public async Task SetAccountInfoNotAuthorized() //{ // var changeInfoViewModel = new ChangeInfoViewModel() // { // FirstName = string.Format("FirstName - {0}", Guid.NewGuid()), // LastName = string.Format("LastName - {0}", Guid.NewGuid()) // }; // using (var client = CreateHttpClient()) // AssertIsFalse(await client.PostAsJsonAsync<ChangeInfoViewModel>("api/oauth/account/info", changeInfoViewModel)); //} //[TestMethod] //public async Task SetAccountInfoForNormalUserWithNullModel() //{ // TokenResultModel token = await SignInForNormalUser(); // using (var client = CreateHttpClient()) // { // client.DefaultRequestHeaders.Add("Authorization", string.Format("{0} {1}", token.token_type, token.access_token)); // AssertIsFalse(await client.PostAsJsonAsync<ChangeInfoViewModel>("api/oauth/account/info", null)); // } //} //[TestMethod] //public async Task SetAccountInfoForNormalUserWithEmptyFirstNameAndLastName() //{ // TokenResultModel token = await SignInForNormalUser(); // var changeInfoViewModel = new ChangeInfoViewModel() { }; // using (var client = CreateHttpClient()) // { // client.DefaultRequestHeaders.Add("Authorization", string.Format("{0} {1}", token.token_type, token.access_token)); // AssertIsFalse(await client.PostAsJsonAsync<ChangeInfoViewModel>("api/oauth/account/info", changeInfoViewModel)); // } //} //#endregion //#region Data //[TestMethod] //public async Task GetAccountDataRecentDocumentsForNormalUser() //{ // TokenResultModel token = await SignInForNormalUser(); // using (var client = CreateHttpClient()) // { // client.DefaultRequestHeaders.Add("Authorization", string.Format("{0} {1}", token.token_type, token.access_token)); // AssertIsTrue(await client.GetAsync("api/oauth/account/data/recent-documents")); // } //} //[TestMethod] //public async Task GetAccountDataRecentDocumentsNotAuthorized() //{ // using (var client = CreateHttpClient()) // AssertIsFalse(await client.GetAsync("api/oauth/account/data/recent-documents")); //} //#endregion //#region Settings //[TestMethod] //public async Task GetAccountSettingsForNormalUser() //{ // TokenResultModel token = await SignInForNormalUser(); // using (var client = CreateHttpClient()) // { // client.DefaultRequestHeaders.Add("Authorization", string.Format("{0} {1}", token.token_type, token.access_token)); // AssertIsTrue(await client.GetAsync("api/account/settings")); // } //} //[TestMethod] //public async Task GetAccountSettingsNotAuthorized() //{ // using (var client = CreateHttpClient()) // AssertIsFalse(await client.GetAsync("api/account/settings")); //} //#endregion } }<file_sep>/Shared/SaaS.Mailer/EmailManager.cs using System.Net.Mail; using System.Text; namespace SaaS.Mailer { public static class EmailManager { public static void Send(SendEmailAction emailAction, string subject, string body) { using (MailMessage message = new MailMessage()) { foreach (var mailAddress in emailAction.EmailToList) message.To.Add(mailAddress.Email); message.Subject = subject; message.SubjectEncoding = Encoding.UTF8; message.Body = body; message.IsBodyHtml = true; message.BodyEncoding = Encoding.UTF8; using (var client = new SmtpClient()) client.Send(message); } } } } <file_sep>/Shared/SaaS.IPDetect/OwinContextExtensions.cs using Microsoft.Owin; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; namespace SaaS.IPDetect { internal static class OwinContextExtensions { static readonly HashSet<string> _deniedIpAddress = null; static OwinContextExtensions() { var ipAddressFiltering = ConfigurationManager.GetSection("saas.ip.configuration") as IpAddressFilteringSection; if (!object.Equals(ipAddressFiltering, null)) { _deniedIpAddress = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); foreach (var entity in ipAddressFiltering.IpAddresses .Cast<IpAddressElement>() .Where(entity => entity.Denied)) { _deniedIpAddress.Add(entity.Address); } } } internal static bool IsIpAddressAllowed(this IOwinContext context) { if (object.Equals(_deniedIpAddress, null)) return true; return !_deniedIpAddress.Contains(IpAddressDetector.IpAddress); } } }<file_sep>/Web.Api/SaaS.UI.Admin/js/controllers/account/search.js (function () { 'use strict'; angular .module('app.controllers') .controller('accountSearchController', controller); controller.$inject = ['$rootScope', '$scope', '$notify', '$api', '$form']; function controller($rootScope, $scope, $notify, $api, $form) { var _search = { filter: null, globalOrderId: null }; $scope.model = { accounts: null, search: { filter: null, globalOrderId: null } }; $scope.status = null; $scope.isBusy = false; $scope.refresh = function () { if (!_search.filter && !_search.globalOrderId) { $scope.model.accounts = []; return; } $scope.isBusy = true; $api.account.get(_search).then(function (json) { $scope.model.accounts = json; }).finally(function () { $scope.isBusy = false; }); }; $scope.merge = function (account) { $rootScope.$broadcast('event:accountMerge', account); }; $scope.submit = function (form) { $form.submit($scope, form, function () { _search.filter = $scope.model.search.filter; _search.globalOrderId = $scope.model.search.globalOrderId; $scope.refresh(); }); }; $rootScope.$on('event:accountMergeComplete', function (event, json) { $scope.model.accounts = []; $scope.refresh(); }); }; })();<file_sep>/Web.Api/SaaS.Api/Oauth/OauthManager.cs using Microsoft.Owin.Security; using SaaS.Api.Models.Oauth; using SaaS.Api.Oauth.Providers; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View; using System; using System.Collections.Specialized; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web; namespace SaaS.Api.Oauth { internal static class OauthManager { internal static async Task<HttpResponseMessage> InternalSignIn(SignInViewModel model, Guid? visitorId = null) { var query = HttpUtility.ParseQueryString(string.Empty); query.Add("grant_type", model.GrantType); query.Add("client_id", model.ClientId); query.Add("client_version", model.ClientVersion); Add(query, "client_secret", model.ClientSecret); query.Add("username", model.UserName); query.Add("password", <PASSWORD>); Add(query, "scope", model.Scope); Add(query, "motherboardKey", model.MotherboardKey); Add(query, "physicalMac", model.PhysicalMac); Add(query, "machineKey", model.MachineKey); Add(query, "pcName", model.PcName); Add(query, "isAutogeneratedMachineKey", model.IsAutogeneratedMachineKey.ToString()); Add(query, "externalClient", model.ExternalClient); if (model.InstallationID.HasValue) query.Add("installationID", model.InstallationID.Value.ToString("N")); if (visitorId.HasValue) query.Add("visitorId", visitorId.Value.ToString("N")); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.BaseAddress = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)); var request = new HttpRequestMessage(HttpMethod.Post, "api/token"); request.Content = new StringContent(query.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded"); return await client.SendAsync(request); } } private static void Add(NameValueCollection query, string key, string value) { if (!string.IsNullOrEmpty(value)) query.Add(key, value); } internal static Guid UpdateTicket(Account user, SessionToken session, AuthenticationTicket ticket, ViewAccountProduct product, Client client) { var currentSessionId = session.Id; session.Id = Guid.NewGuid(); var timeSpan = session.ExpiresUtc - session.IssuedUtc; var issued = DateTime.UtcNow; session.IssuedUtc = issued; session.ExpiresUtc = issued.Add(timeSpan); ticket.Properties.IssuedUtc = session.IssuedUtc; ticket.Properties.ExpiresUtc = session.ExpiresUtc; ticket.Properties.Dictionary["session"] = session.Id.ToString("N"); ticket.Identity.AddClaims(user, client); session.ProtectedTicket = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket); session.AccountProductId = product.AccountProductId; return currentSessionId; } internal static dynamic ReleaseToken(SessionToken session, AuthenticationTicket ticket, object modules, object moduleFeatures, object activeProducts, Account user) { return new { access_token = session.ProtectedTicket, refresh_token = session.Id.ToString("N"), token_type = ticket.Identity.AuthenticationType, expires_in = (int)(ticket.Properties.ExpiresUtc - ticket.Properties.IssuedUtc).Value.TotalSeconds, externalClient = session.ExternalClientName, status = user.GetStatus(), email = user.Email, modules = modules, moduleFeatures = moduleFeatures, activeProducts = activeProducts, issued = ticket.Properties.IssuedUtc, expires = ticket.Properties.ExpiresUtc }; } internal static int? GetExternalClientId(string value) { ExternalClient? externalClient = GetExternalClient(value); if (externalClient.HasValue) return (int)externalClient.Value; return null; } internal static ExternalClient? GetExternalClient(string value) { ExternalClient externalClient; if (Enum.TryParse(value, true, out externalClient)) return externalClient; return null; } internal static string GetExternalClientName(ExternalClient externalClient) { return Enum.GetName(typeof(ExternalClient), externalClient); } } }<file_sep>/Shared/Upclick.Api.Client/UpclickClient.Products.cs using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net.Http; using System.Threading.Tasks; namespace Upclick.Api.Client { public partial class UpclickClient { private async Task<HttpResponseMessage> _GetProducts(string uid = null) { return await _upclickHttpClient.GetAsync("products/retrieve", string.IsNullOrEmpty(uid) ? null : new NameValueCollection() { { "uid", uid } }); } private async Task<HttpResponseMessage> _GetProductsList(string uid = null) { return await _upclickHttpClient.GetAsync("products/getlist", string.IsNullOrEmpty(uid) ? null : new NameValueCollection() { { "uid", uid } }); } public async Task<List<Product>> GetProducts() { HttpResponseMessage response = await _GetProducts(); var root = await response.Content.ReadAsAsync<ProductsRetrieveRoot>(); if (!object.Equals(root, null) && !object.Equals(root.ProductsRetrieve, null)) return root.ProductsRetrieve.Products; return null; } public async Task<List<Product>> GetProductsList() { HttpResponseMessage response = await _GetProductsList(); var root = await response.Content.ReadAsAsync<ProductsGetListRoot>(); if (!object.Equals(root, null) && !object.Equals(root.ProductsGetList, null)) return root.ProductsGetList.Products; return null; } } public class ProductsRetrieveRoot { [JsonProperty(PropertyName = "products_retrieve")] public ProductsRetrieve ProductsRetrieve { get; set; } } public class ProductsRetrieve { [JsonProperty(PropertyName = "product")] [JsonConverter(typeof(SingleOrArrayConverter<Product>))] public List<Product> Products { get; set; } } public class ProductsGetListRoot { [JsonProperty(PropertyName = "products_getlist")] public ProductsGetList ProductsGetList { get; set; } } public class ProductsGetList { [JsonProperty(PropertyName = "product")] [JsonConverter(typeof(SingleOrArrayConverter<Product>))] public List<Product> Products { get; set; } } public class Product { public string Uid { get; set; } public string ProductTitle { get; set; } [JsonProperty(PropertyName = "names")] public ProductNames ProductNames { get; set; } } public class ProductNames { [JsonProperty("name")] [JsonConverter(typeof(SingleOrArrayConverter<ProductName>))] public List<ProductName> Names { get; set; } } [JsonObject("Name")] public class ProductName { [JsonProperty("culture")] public string Cultute { get; set; } [JsonProperty("producttitle")] public string ProductTitle { get; set; } } class SingleOrArrayConverter<T> : JsonConverter { public override bool CanConvert(Type objectType) { return (objectType == typeof(List<T>)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JToken token = JToken.Load(reader); if (token.Type == JTokenType.Array) return token.ToObject<List<T>>(); return new List<T> { token.ToObject<T>() }; } public override bool CanWrite { get { return false; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } } <file_sep>/Shared/SaaS.Identity/AuthRepository/AuthRepository.cs using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security.DataProtection; using SaaS.Common.Extensions; using SaaS.Data.Entities.Accounts; using System; namespace SaaS.Identity { public partial class AuthRepository : IAuthRepository { protected readonly AuthDbContext _context; protected readonly UserManager<Account, Guid> _userManager; public AuthRepository() { _context = new AuthDbContext(); _userManager = new UserManager<Account, Guid>(new AccountStore<Account>(_context)); _userManager.UserValidator = new AccountValidator<Account>(); _userManager.PasswordHasher = new SaaSPasswordHasher(); } public void SetDataProtectorProvider(IDataProtectionProvider dataProtectorProvider) { var dataProtector = dataProtectorProvider.Create("SodaPDF"); _userManager.UserTokenProvider = new DataProtectorTokenProvider<Account, Guid>(dataProtector) { TokenLifespan = TimeSpan.FromHours(24), }; } public void Dispose() { _context.Dispose(); _userManager.Dispose(); } } }<file_sep>/Web.Api/SaaS.UI.Admin/gulpfile.js /// <binding ProjectOpened='sass, sass:watch' /> "use strict"; var gulp = require("gulp"), concat = require("gulp-concat"), uglify = require("gulp-uglify"), sass = require("gulp-sass"); gulp.task('bundle', function (done) { var src = ['scripts/jquery-2.2.0.min.js', 'scripts/jquery.cookie-1.4.1.min.js', 'scripts/bootstrap.min.js', 'scripts/respond.min.js', 'scripts/metisMenu.min.js', 'scripts/angular.js', 'scripts/angular-ui/ui-bootstrap-tpls-2.5.0.min.js', 'scripts/angular-notify.min.js']; gulp.src(src) .pipe(concat('bundle.js')) .pipe(uglify()) .pipe(gulp.dest('js')); done(); }); //gulp.task('sass', function () { // return gulp.src('stylesheets/**/*.scss') // .pipe(sass({ outputStyle: 'compressed' })) // .pipe(gulp.dest('css')); //}); //gulp.task('sass:watch', function () { // return gulp.watch('stylesheets/**/*.scss', ['sass']); //});<file_sep>/Shared/SaaS.Data.Entities/View/ViewMicrotransaction.cs using System; namespace SaaS.Data.Entities.View { public abstract class ViewMicrotransaction { public Guid AccountMicrotransactionId { get; set; } public string ProductName { get; set; } public string ProductUnitName { get; set; } public string Plan { get; set; } public DateTime PurchaseDate { get; set; } public int? AllowedEsignCount { get; set; } public int UsedEsignCount { get; set; } } }<file_sep>/Shared/SaaS.Api.Core/Filters/ValidateModelAttribute.cs using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace SaaS.Api.Core.Filters { public class ValidateModelAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (actionContext.ModelState.IsValid == false) { string errorDescription = null; foreach (var value in actionContext.ModelState.Values) { foreach (var error in value.Errors) { errorDescription = error.ErrorMessage; break; } if (!string.IsNullOrEmpty(errorDescription)) break; } actionContext.Response = actionContext.Request.CreateExceptionResponse(errorDescription: errorDescription); } } } }<file_sep>/Test/SaaS.Api.Test/Models/Api/Oauth/TokenResultModel.cs  namespace SaaS.Api.Test.Models.Api.Oauth { public class TokenResultModel { public string access_token { get; set; } public string refresh_token { get; set; } public string token_type { get; set; } } } <file_sep>/Shared/SaaS.Data.Entities/View/ViewUpclickProduct.cs namespace SaaS.Data.Entities.View { public class ViewUpclickProduct { public string ProductUid { get; set; } public string ProductName { get; set; } public string ProductUnitName { get; set; } } } <file_sep>/Web.Api/SaaS.UI.Admin/js/controllers/account/change-password.js (function () { 'use strict'; angular .module('app.controllers') .controller('accountChangePasswordController', controller); controller.$inject = ['$rootScope', '$scope', '$notify', '$api', '$form']; function controller($rootScope, $scope, $notify, $api, $form) { $scope.model = { account: null }; $scope.recoverPassword = function () { $api.account.recoverPassword($scope.model.account.id).then(function (json) { $notify.info("An email has been sent to customer to reset your password."); }); }; $scope.submit = function (form) { $form.submit($scope, form, function (form) { $api.account.changePassword($scope.model.account.id, { newPassword: $<PASSWORD> }).then(function (json) { $notify.info("Customer's password has been changed."); }).finally(function () { $scope.isBusy = false; }); }); }; $rootScope.$on('event:accountLoaded', function (event, json) { $scope.model.account = $scope.model.account || {}; $scope.model.account.id = json.id; }); $rootScope.$on('event:accountDeleted', function (event, json) { $scope.model.account = $scope.model.account || {}; $scope.model.account.isDeleted = true; }); }; })();<file_sep>/Web.Api/SaaS.Sso/src/js/app.i18n.js angular.module('app') .config(['$translateProvider', '$translatePartialLoaderProvider', ($translateProvider, $translatePartialLoaderProvider) => { // // $translateProvider.useLoader('$i18nLoader', {}); // // $translateProvider.useLocalStorage(); $translateProvider.useLoader('$translatePartialLoader', { urlTemplate: 'i18n/{lang}.json' }); $translateProvider.preferredLanguage('en'); $translateProvider.fallbackLanguage('en'); $translatePartialLoaderProvider.addPart('index'); }]);<file_sep>/Shared/SaaS.Api.Models/Oauth/EmailChangePendingViewModel.cs namespace SaaS.Api.Models.Oauth { public class EmailChangePendingViewModel : AuthViewModel { public string[] PendingEmails { get; set; } } } <file_sep>/Web.Api/SaaS.Api/Models/Api/Oauth/AuthViewModel.cs using System; using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Models.Api.Oauth { public class AuthViewModel { [Required, DataType(DataType.EmailAddress)] [RegularExpression(@"(?i)^[-a-z0-9!#$%&'*+\/=?^_`{|}~]+(\.[-a-z0-9!#$%&'*+\/=?^_`{|}~]+)*@([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?\.)*[a-z]{1,20}$")] public string Email { get; set; } } public class AuthIdViewModel { public Guid AccountId { get; set; } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.Register.cs using AutoMapper; using Microsoft.Owin.Security; using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using SaaS.Api.Oauth; using SaaS.Api.Oauth.Providers; using SaaS.Data.Entities.Accounts; using SaaS.Data.Entities.Oauth; using SaaS.Data.Entities.View; using SaaS.IPDetect; using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { private async Task<IHttpActionResult> _register(RegisterViewModel model, Account account, ViewAccountDetails accountDetails, string stackTrace) { if (!object.Equals(account, null)) { await _auth.AccountVisitorIdSetAsync(account, model.VisitorId); if (model.IsBusiness()) { await _auth.AccountMaskAsBusinessAsync(account); //make sure that user will get b2b 30 trial await _auth.AccountActivateAsync(account); } if (account.IsBusiness && string.Equals(model.Source, "sodapdf.com-get-trial", StringComparison.InvariantCultureIgnoreCase)) await NotificationManager.BusinessDownload(account); if (account.IsEmptyPassword()) { if (!string.IsNullOrEmpty(model.Password)) { await _auth.AccountPasswordSetAsync(account, model.Password); await NotificationManager.AccountCreationComplete(account); } accountDetails.GeoIp = IpAddressDetector.IpAddress; accountDetails.Id = account.Id; await _auth.AccountDetailsSetAsync(accountDetails); return Ok(); } return AccountExists(); } account = new Account(model.Email, model.FirstName, model.LastName); account.IsBusiness = model.IsBusiness(); var result = await _auth.AccountCreateAsync(account, model.Password); var errorResult = GetErrorResult(result); if (!object.Equals(errorResult, null)) return errorResult; accountDetails.GeoIp = IpAddressDetector.IpAddress; accountDetails.Id = account.Id; accountDetails.Source = model.Source; accountDetails.WebForm = FormIdBuilder.Build(model.FormId); await _auth.AccountOptinSetAsync(account, model.Optin); await _auth.AccountDetailsSetAsync(accountDetails); await _auth.AccountVisitorIdSetAsync(account, model.VisitorId); OauthLogger.CreateAccountWarn(Request, account, accountDetails, stackTrace); if ("sodapdf.com-esign-lite".Equals(model.Source, StringComparison.InvariantCultureIgnoreCase)) return Ok(); // if (account.IsBusiness && "sodapdf.com-get-trial".Equals(model.Source, StringComparison.InvariantCultureIgnoreCase)) await NotificationManager.BusinessDownloadNewAccount(account); else { if (!string.IsNullOrEmpty(model.Password)) { #if PdfForge if (!object.Equals(accountDetails, null) && "covermount".Equals(accountDetails.Build, StringComparison.InvariantCultureIgnoreCase)) { await NotificationManager.EmailConfirmationCovermount(account); return Ok(); } #endif await NotificationManager.EmailConfirmation(account); } else { if ("sodapdf.com-opdfs".Equals(model.Source, StringComparison.InvariantCultureIgnoreCase) || "sodapdf.com-opdfs-send-to-email".Equals(model.Source, StringComparison.InvariantCultureIgnoreCase)) await NotificationManager.MicrotransactionCreatePassword(account); } } return Ok(); } private async Task<IHttpActionResult> _registerLegal(RegisterViewModel model, Account account, ViewAccountDetails accountDetails) { if (!object.Equals(account, null)) { await _auth.AccountVisitorIdSetAsync(account, model.VisitorId); if (account.IsActivated) await NotificationManager.LegacyActivationSignInNotification(account); else await NotificationManager.LegacyCreatePasswordReminder(account); return AccountExists(); } account = new Account(model.Email, model.FirstName, model.LastName); account.IsBusiness = model.IsBusiness(); var result = await _auth.AccountCreateAsync(account, model.Password); var errorResult = GetErrorResult(result); if (!object.Equals(errorResult, null)) return errorResult; accountDetails.GeoIp = IpAddressDetector.IpAddress; accountDetails.Id = account.Id; accountDetails.Source = model.Source; accountDetails.WebForm = FormIdBuilder.Build(model.FormId); await _auth.AccountOptinSetAsync(account, model.Optin); await _auth.AccountDetailsSetAsync(accountDetails); await _auth.AccountVisitorIdSetAsync(account, model.VisitorId); await NotificationManager.LegacyActivationCreatePassword(account); OauthLogger.CreateAccountWarn(Request, account, accountDetails, "registerLegal"); return Ok(); } private void _b2blead(RegisterViewModel model) { if (object.Equals(model, null) || !_b2bleadSourceCollection.Contains(model.Source)) return; try { using (MailMessage message = new MailMessage()) { message.To.Add(_appSettings.B2BLead.Email); message.Subject = string.Format("{0} - {1} {2}", model.Source, model.FirstName, model.LastName); message.SubjectEncoding = Encoding.UTF8; StringBuilder body = new StringBuilder(); _b2bleadBuilder(body, "Email", model.Email); body.AppendFormat("Name: {0} {1}", model.FirstName, model.LastName); body.AppendLine(); _b2bleadBuilder(body, "Company", model.Company); _b2bleadBuilder(body, "Occupation", model.Occupation); _b2bleadBuilder(body, "Phone", model.Phone); _b2bleadBuilder(body, "Language", model.LanguageISO2); _b2bleadBuilder(body, "Country", model.CountryISO2); _b2bleadBuilder(body, "State", model.State); _b2bleadBuilder(body, "City", model.City); _b2bleadBuilder(body, "Address1", model.Address1); _b2bleadBuilder(body, "Address2", model.Address2); _b2bleadBuilder(body, "PostalCode", model.PostalCode); _b2bleadBuilder(body, "Industry", model.Industry); _b2bleadBuilder(body, "JobRole", model.JobRole); _b2bleadBuilder(body, "Licenses", model.Licenses); _b2bleadBuilder(body, "Product", model.Product); message.Body = body.ToString(); message.BodyEncoding = Encoding.UTF8; using (var client = new SmtpClient()) client.Send(message); } } catch { } } private void _b2bleadBuilder(StringBuilder builder, string key, string value) { if (string.IsNullOrEmpty(value)) return; builder.AppendFormat("{0}: {1}", key, value); builder.AppendLine(); } [HttpPost, Route("register"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> Register(RegisterViewModel model) { try { var accountsDetail = new ViewAccountDetails(); accountsDetail = Mapper.Map(model, accountsDetail); var acceptLanguage = Request.Headers.AcceptLanguage.FirstOrDefault(); if (!object.Equals(acceptLanguage, null) && !string.IsNullOrEmpty(acceptLanguage.Value)) accountsDetail.LanguageISO2 = acceptLanguage.Value.Substring(0, 2).ToLower(); _b2blead(model); if (!object.Equals(model.Params, null)) { accountsDetail.Cmp = model.Params.Cmp; accountsDetail.Partner = model.Params.Partner; accountsDetail.Build = model.Params.Build; accountsDetail.Uid = model.Params.GetUid(); } var account = await _auth.AccountGetAsync(model.Email); if (object.Equals(account, null)) { account = await _auth.AccountGetAsync(model.Email, isIncludeSubEmails: true); if (!object.Equals(account, null)) return AccountExists(); } else if (account.IsEmptyPassword()) { var sessionTokensExternalHistory = await _auth.SessionTokenExternalHistoriesAsync(account.Id); var sessionTokenExternalHistory = sessionTokensExternalHistory.FirstOrDefault(e => !e.IsUnlinked); if (!object.Equals(sessionTokenExternalHistory, null)) return ErrorContent("invalid_grant", string.Format("You should sign in with {0}.", sessionTokenExternalHistory.ExternalClientName),System.Net.HttpStatusCode.Conflict); } if ("soda pdf 8".Equals(model.Source, StringComparison.InvariantCultureIgnoreCase)) return await _registerLegal(model, account, accountsDetail); return await _register(model, account, accountsDetail, "register"); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } [HttpPost, Route("register-anonymous"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> RegisterAnonymous(RegisterAnonymousViewModel model, Guid? visitorId = null) { try { var account = await _auth.AccountAnonymousCreateAsync(model.Password); if (object.Equals(account, null)) return AccountNotFound(); var client = GetClient(model.client_id); if (object.Equals(client, null)) return ClientNotFound(); var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType); var session = Guid.NewGuid(); var properties = new Dictionary<string, string> { { "session", session.ToString("N") } }; identity.AddClaim(ClaimTypes.NameIdentifier, account.Id); identity.AddClaim(ClaimTypes.Name, account.Email); identity.AddClaims(account, client); var ticket = new AuthenticationTicket(identity, new AuthenticationProperties(properties)); var issued = DateTime.UtcNow; var expires = issued.Add(Startup.OAuthServerOptions.AccessTokenExpireTimeSpan); var token = new SessionToken { Id = session, AccountId = account.Id, ClientId = client.Id, ClientVersion = model.client_version, IssuedUtc = issued, ExpiresUtc = expires }; ticket.Properties.IssuedUtc = issued; ticket.Properties.ExpiresUtc = expires; token.ProtectedTicket = Startup.OAuthServerOptions.AccessTokenFormat.Protect(ticket); var scopeWorker = SaaSScopeWorkerFactory.Create("webeditor", _auth, _authProduct); await scopeWorker.SessionTokenInsertAsync(token, null); await _auth.AccountVisitorIdSetAsync(account, visitorId); return Ok(new { access_token = token.<PASSWORD>, token_type = ticket.Identity.AuthenticationType, expires_in = (int)(ticket.Properties.ExpiresUtc - ticket.Properties.IssuedUtc).Value.TotalSeconds, refresh_token = token.Id.ToString("N"), issued = ticket.Properties.IssuedUtc, expires = ticket.Properties.ExpiresUtc, email = account.Email, firstName = account.FirstName, lastName = account.LastName, status = account.GetStatus() }); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } } }<file_sep>/Shared/SaaS.Api.Client/SaaSApiModule.cs namespace SaaS.Api.Client { public class SaaSApiModule { public string Name { get; set; } } } <file_sep>/Shared/SaaS.Identity/AuthDbContext.Sql/AuthDbContext.Sql.SessionTokenExternalHistory.cs using SaaS.Data.Entities.View.Oauth; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthDbContext { internal async Task<List<ViewSessionTokenExternalHistory>> SessionTokenExternalHistoriesGetAsync(Guid accountId) { return await ExecuteReaderCollectionAsync<ViewSessionTokenExternalHistory>("[oauth].[pSessionTokenExternalHistoryGetByAccountId]", accountId); } internal async Task SessionTokenExternalHistorySetAsync(Guid accountId, string externalClientName, string externalAccountId, string email) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId"), externalClientName.ToSql("externalClientName"), externalAccountId.ToSql("externalAccountId"), email.ToSql("email") }; await ExecuteScalarAsync("[oauth].[pSessionTokenExternalHistorySet]", sqlParams); } internal async Task SessionTokenExternalHistoryConnectAccountAsync(Guid accountId, string externalClientName, string externalAccountId, string email) { var sqlParams = new SqlParameter[] { accountId.ToSql("accountId"), externalClientName.ToSql("externalClientName"), externalAccountId.ToSql("externalAccountId"), email.ToSql("email") }; await ExecuteScalarAsync("[oauth].[pSessionTokenExternalHistoryConnectAccount]", sqlParams); } internal async Task SessionTokenExternalHistorySetStateAsync(Guid id, bool isUnlinked) { var sqlParams = new SqlParameter[] { id.ToSql("id"), isUnlinked.ToSql("isUnlinked") }; await ExecuteScalarAsync("[oauth].[pSessionTokenExternalHistorySetState]", sqlParams); } } }<file_sep>/Shared/SaaS.Common/Extensions/ExtensionMethods.cs using System; using System.Net.Http; using System.Security.Cryptography; using System.Text; namespace SaaS.Common.Extensions { public static class ExtensionMethods { public static string GetHash(this string input) { var hashAlgorithm = new SHA256CryptoServiceProvider(); var byteValue = Encoding.UTF8.GetBytes(input); var byteHash = hashAlgorithm.ComputeHash(byteValue); return Convert.ToBase64String(byteHash); } public static Uri CreateUri(this HttpRequestMessage request,string localPath) { var uri = new Uri(request.RequestUri.GetLeftPart(UriPartial.Authority)); return new Uri(uri, localPath); } } } <file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AccountController.UpgradeProduct.cs using AutoMapper; using SaaS.Api.Core; using SaaS.Api.Models.Products; using SaaS.Data.Entities.View; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AccountController { [HttpGet, Route("upgrade-products/{accountProductId:guid}")] public async Task<IHttpActionResult> UpgradeProduct(Guid accountProductId) { try { var product = await _authProduct.UpgradeProductGetAsync(accountProductId); if (object.Equals(product, null)) return NotFound(); return Ok(UpgradeProductConvertor(product)); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } } private static UpgradeProductViewModel UpgradeProductConvertor(ViewUpgradeProduct product) { return Mapper.Map(product, new UpgradeProductViewModel()); } } }<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AdminAccountController.EmailConfirmation.cs using SaaS.Api.Core; using SaaS.Api.Core.Filters; using SaaS.Api.Models.Oauth; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AdminAccountController { [HttpPost, Route("confirm-email"), ValidateNullModel, ValidateModel] public async Task<IHttpActionResult> ConfirmEmail(ConfirmEmalViewModel model) { try { var user = await _auth.AccountGetAsync(model.UserId); if (object.Equals(user, null)) return AccountNotFound(); var result = await _auth.AccountConfirmEmailAsync(user.Id); var errorResult = GetErrorResult(result); if (!object.Equals(errorResult, null)) return errorResult; if (model.IsBusiness()) await _auth.AccountMaskAsBusinessAsync(user); await _auth.AccountActivateAsync(user); } catch (Exception exc) { return Request.HttpExceptionResult(exc); } return Ok(); } } }<file_sep>/Web.Api/SaaS.Sso/dist/js/app.min.js "use strict"; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } angular.module('app.components', ['ui.router', 'pascalprecht.translate']); angular.module('app.services', []); angular.module('app.controllers', []); angular.module('app.directives', []); angular.module('app.filters', []); angular.module('app.external', ['LocalStorageModule']); //angular-local-storage angular.module('app', ['ui.router', 'app.components', 'app.services', 'app.controllers', 'app.directives', 'app.filters', 'app.external']).run(function ($trace, $transitions, $translate, $brand, $sso) { if (!$brand.validate()) return $brand.redirect(); //$trace.enable('TRANSITION'); $transitions.onBefore({ to: '**' }, function (transition) { var to = transition.to(); if (to.name === 'account/logout' && $sso.logout()) document.body.style.display = 'none'; }); //$transitions.onSuccess({ to: '**' }, (transition) => { // let stateService = transition.router.stateService; // let locale = stateService.params.locale || 'en'; // $translate.use(locale); //}); }); angular.module('app').config(['$httpProvider', function ($httpProvider) { $httpProvider.interceptors.push([function () { var interceptor = {}; interceptor.response = function (response) { var config = response.config || {}; if (config.asJson === true) return response.data; return response; }; return interceptor; }]); }]); angular.module('app').config(['$translateProvider', '$translatePartialLoaderProvider', function ($translateProvider, $translatePartialLoaderProvider) { // // $translateProvider.useLoader('$i18nLoader', {}); // // $translateProvider.useLocalStorage(); $translateProvider.useLoader('$translatePartialLoader', { urlTemplate: 'i18n/{lang}.json' }); $translateProvider.preferredLanguage('en'); $translateProvider.fallbackLanguage('en'); $translatePartialLoaderProvider.addPart('index'); }]); angular.module('app').config(function ($stateProvider, $urlRouterProvider, localStorageServiceProvider) { localStorageServiceProvider.setPrefix('sso').setDefaultToCookie(false); // $locationProvider.html5Mode({ // enabled: true, // requireBase: false // }); $urlRouterProvider.otherwise('/en/index'); $stateProvider.state('app', { url: '/:locale', // url: '/:locale/{brand:sodapdf}', //templateUrl: 'index.html', restricted: false, abstract: true, views: { content: { controller: 'appController' }, footer: { templateUrl: 'partial/footer.html', controller: 'partialFooterController' } } }); var _state = function _state(json) { json.name = json.name || json.url; json.params = json.params || {}; json.templateUrl = json.templateUrl || "views/".concat(json.url, ".html"); json.isProtected = !!json.isProtected; var state = { parent: 'app', url: "/".concat(json.url), params: json.params, templateUrl: json.templateUrl, controller: "".concat(json.controller, "Controller"), isProtected: json.isProtected }; $stateProvider.state(json.name, state); }; _state({ url: 'index', controller: 'index' }); _state({ url: 'account/error', controller: 'accountError' }); _state({ url: 'account/logout', controller: 'accountLogout' }); _state({ url: 'account/identifier', controller: 'accountIdentifier', params: { email: null } }); _state({ url: 'account/password', controller: 'accountPassword', params: { firstName: null, lastName: null, email: null } }); _state({ url: 'account/remove', controller: 'accountRemove' }); _state({ url: 'account/select', controller: 'accountSelect' }); }); angular.module('app.controllers').controller('appController', ['$scope', '$state', function ($scope, $state) {}]); angular.module('app.controllers').controller('indexController', ['$state', '$storage', function ($state, $storage) { var accounts = $storage.getAccounts(); if (accounts.length > 1) return $state.go('account/select'); return $state.go('account/identifier', { email: accounts.length ? accounts[0].email : null }); }]); angular.module('app.directives').directive('ngFocus', ['$window', function ($window) { return { restrict: 'A', link: function link(scope, element, attrs) { element.first().focus(); } }; }]); angular.module('app.directives').directive('ngLogo', ['$brand', function ($brand) { return { restrict: 'A', link: function link(scope, element, attrs) { var logo = $brand.logo(); element.html("<img width=\"".concat(logo.width, "\" src=\"").concat(logo.src, "\">")); } }; }]); angular.module('app.services').factory('$api', ['$http', '$brand', function ($http, $brand) { var _uri = function _uri(method) { return "".concat($brand.oauthLink(), "/").concat(method); }; var _getConfig = function _getConfig() { return { asJson: true, isOauth: true }; }; var service = {}; service.account = { get: function get(params) { var config = _getConfig(); config.params = params; return $http.get(_uri('api/account/'), config); } }; service.tokenJwt = function (data) { var config = _getConfig(); return $http.post(_uri('api/token/jwt'), data, config); }; return service; }]); angular.module('app.services').factory('$brand', ['$utils', '$location', function ($utils, $location) { var brandEnum = { sodaPdf: 'sodaPdf', pdfArchitect: 'pdfArchitect' }; var _current = null; var _settings = { ssoLink: {}, oauthLink: {} }; _settings.ssoLink[brandEnum.sodaPdf] = 'https://sso.sodapdf.com'; _settings.ssoLink[brandEnum.pdfArchitect] = 'https://sso.pdfarchitect.org'; _settings.oauthLink[brandEnum.sodaPdf] = 'https://oauth.sodapdf.com'; _settings.oauthLink[brandEnum.pdfArchitect] = 'https://oauth.pdfarchitect.org'; var _getSettings = function _getSettings(key) { return _settings[key][service.current()]; }; var service = {}; service.current = function () { return _current; }; service.currentName = function () { switch (service.current()) { case brandEnum.sodaPdf: return 'Soda PDF'; case brandEnum.pdfArchitect: return 'PDF Architect'; default: return ''; } }; service.ssoLink = function () { return _getSettings('ssoLink'); }; service.oauthLink = function () { return _getSettings('oauthLink'); }; service.validate = function () { var query = $utils.query(); var host = $location.host().toLowerCase(); switch (host) { case 'localhost': case 'sso.sodapdf.com': _current = brandEnum.sodaPdf; break; case 'sso.pdfarchitect.org': _current = brandEnum.pdfArchitect; break; case 'sso.lulusoft.com': if (query.brand_id === '360002010612') _current = brandEnum.sodaPdf; _current = _current || brandEnum.pdfArchitect; return false; } return true; }; service.redirect = function () { document.body.style.display = 'none'; window.location = service.ssoLink() + document.location.search + document.location.hash; }; service.logo = function () { switch (service.current()) { case brandEnum.sodaPdf: return { width: 120, src: 'https://www.sodapdf.com/images/logo.svg' }; case brandEnum.pdfArchitect: return { width: 200, src: 'https://myaccount.pdfarchitect.org/images/logo.png' }; default: return {}; } }; return service; }]); angular.module('app.services').factory('$form', function () { var service = {}; service.submit = function (entity, form, callback) { if (form.$valid !== true) { angular.forEach(form, function (value, key) { if (_typeof(value) === 'object' && value.hasOwnProperty('$modelValue')) value.$setDirty(); }); } if (service.isReady(entity, form) === false) return; callback(form); }; service.isReady = function (entity, form) { if (entity.isBusy === true || form.$valid !== true) return false; entity.isBusy = true; return true; }; return service; }); angular.module('app.services').factory('$sso', ['$location', '$utils', function ($location, $utils) { var service = {}; service.signInJwt = function (json) { var query = $utils.query(); query.return_to && (json.return_to = query.return_to); var location = "".concat(query.redirect_uri, "?").concat($utils.params(json)); window.location = location; }; service.logout = function () { var query = $utils.query(); if (query.return_to) return !!(window.location = query.return_to); }; return service; }]); angular.module('app.services').factory('$storage', ['localStorageService', function ($localStorageService) { var service = {}; var _equalAccount = function _equalAccount(account1, account2) { var email1 = account1.email || ''; var email2 = account2.email || ''; return email1.toLowerCase() === email2.toLowerCase(); }; service.getAccounts = function () { if (!$localStorageService.isSupported) return []; return $localStorageService.get('accounts') || []; }; service.addAccount = function (account) { if (!$localStorageService.isSupported) return; service.removeAccount(account); var accounts = service.getAccounts(); accounts.unshift({ firstName: account.firstName, lastName: account.lastName, email: account.email }); $localStorageService.set('accounts', accounts); }; service.removeAccount = function (account) { if (!$localStorageService.isSupported) return; var accounts = service.getAccounts(); for (var index = 0; index < accounts.length; ++index) { if (_equalAccount(accounts[index], account)) accounts.splice(index--, 1); } ; $localStorageService.set('accounts', accounts); }; function viewAccount(json) { this.firstName = json.firstName; this.lastName = json.lastName; this.email = json.email; } ; return service; }]); angular.module('app.services').factory('$utils', function () { var service = {}; service.query = function (query) { var json = {}; try { if (typeof query === 'undefined') query = document.location.search; var split = query.replace(/(^\?)/, '').split('&'); for (var i = 0; i < split.length; ++i) { var item = split[i]; var index = item.indexOf('='); if (index === -1) continue; var key = item.substring(0, index); var value = item.substr(index + 1).trim(); json[key.toLowerCase()] = decodeURIComponent(value); } } catch (e) {} return json; }; service.params = function (json) { var queryString = []; for (var key in json) { queryString.push(key.toLowerCase() + '=' + encodeURIComponent(json[key])); } return queryString.join('&'); }; service.hash = function (value) { var hash = 0; if (!value) return hash; for (var index = 0; index < value.length; index++) { hash = value.charCodeAt(index) + ((hash << 5) - hash); } return hash; }; service.intToRgb = function (value) { var str = (value & 0x00FFFFFF).toString(16).toUpperCase(); return '00000'.substring(0, 6 - str.length) + str; }; service.stringToColor = function (value) { var hash = service.hash(value); var rgb = service.intToRgb(hash); return "#".concat(rgb); }; return service; }); angular.module('app.controllers').controller('accountErrorController', ['$scope', function ($scope) {}]); angular.module('app.controllers').controller('accountIdentifierController', ['$scope', '$state', '$api', '$storage', '$form', '$brand', function ($scope, $state, $api, $storage, $form, $brand) { $scope.model = { email: $state.params.email || null }; $scope.status = null; $scope.isBusy = false; $scope.subTitle = "with your ".concat($brand.currentName(), " account"); $scope.errorNotFound = "Couldn't find your ".concat($brand.currentName(), " account"); $scope.submit = function (form) { $scope.status = null; $scope.model.error = null; $form.submit($scope, form, function () { return $api.account.get({ email: $scope.model.email }).then(function (json) { $storage.addAccount(json); $state.go('account/password', json); }, function (json) { if (json.status !== 404) return $state.go('account/error'); $scope.status = 404; }).finally(function () { $scope.isBusy = false; }); }); }; }]); angular.module('app.controllers').controller('accountPasswordController', ['$scope', '$state', '$utils', '$api', '$sso', '$form', function ($scope, $state, $utils, $api, $sso, $form) { var params = $state.params; if (!params.email) $state.go('index'); $scope.model = { firstName: params.firstName, lastName: params.lastName, email: params.email }; $scope.status = null; $scope.isBusy = false; $scope.getFirstChar = function () { var value = $scope.model.email || $scope.model.firstName || $scope.model.lastName || ' '; return value[0]; }; $scope.getColor = function (account) { return $utils.stringToColor($scope.model.email); }; $scope.submit = function (form) { $scope.status = null; $scope.model.error = null; $form.submit($scope, form, function () { return $api.tokenJwt({ email: $scope.model.email, password: $scope.<PASSWORD> }).then($sso.signInJwt, function (json) { if (json.status !== 404) return $state.go('account/error'); $scope.status = 404; }).finally(function () { $scope.isBusy = false; }); }); }; }]); angular.module('app.controllers').controller('accountRemoveController', ['$scope', '$state', '$utils', '$storage', function ($scope, $state, $utils, $storage) { var accounts = $storage.getAccounts(); if (!accounts.length) return $state.go('index'); $scope.model = { accounts: accounts }; $scope.remove = function (account) { $storage.removeAccount(account); $scope.model.accounts = $storage.getAccounts(); }; $scope.getFirstChar = function (account) { var value = account.email || account.firstName || account.lastName || ' '; return value[0]; }; $scope.getColor = function (account) { return $utils.stringToColor(account.email); }; }]); angular.module('app.controllers').controller('accountSelectController', ['$scope', '$state', '$utils', '$storage', function ($scope, $state, $utils, $storage) { var accounts = $storage.getAccounts(); if (!accounts.length) return $state.go('index'); $scope.model = { accounts: accounts }; $scope.select = function (account) { return $state.go('account/password', account); }; $scope.getFirstChar = function (account) { var value = account.email || account.firstName || account.lastName || ' '; return value[0]; }; $scope.getColor = function (account) { return $utils.stringToColor(account.email); }; }]); angular.module('app.controllers').controller('partialFooterController', ['$scope', '$state', '$brand', function ($scope, $state, $brand) { var _languages = { en: 'English', fr: 'Français', de: 'Deutsch‬' }; $scope.$brand = $brand; $scope.model = { locale: $state.params.locale.toLowerCase() }; $scope.currentLanguageTitle = function () { return _languages[$scope.model.locale]; }; $scope.changeLanguage = function (locale) { $scope.model.locale = locale; var url = $state.current.url.replace(/^\//gi, ''); var params = angular.copy($state.params); params.locale = locale; $state.go(url, params); }; }]);<file_sep>/Web.Api/SaaS.Api/Controllers/Api/Oauth/AdminAccountController.Product.cs using SaaS.Api.Models.Products; using System; using System.Threading.Tasks; using System.Web.Http; namespace SaaS.Api.Controllers.Api.Oauth { public partial class AdminAccountController { [HttpGet, Route("products")] public async Task<IHttpActionResult> Products(Guid userId) { var products = await _authProduct.AccountProductsGetAsync(userId); products.Sort(ProductComparer.Comparer); products.Reverse(); ProductComparer.ProductOrderer(products); return Ok(products.ConvertAll(ProductConvertor.AccountProductConvertor)); } } }<file_sep>/Web.Api/SaaS.Api.Admin/Models/Oauth/ChangePasswordViewModel.cs using System.ComponentModel.DataAnnotations; namespace SaaS.Api.Admin.Models.Oauth { public class ChangePasswordViewModel { [Required, DataType(DataType.Password)] public string OldPassword { get; set; } [Required, DataType(DataType.Password)] public string NewPassword { get; set; } } }<file_sep>/Shared/SaaS.Identity/AuthRepository/AuthRepository.System.cs using System.Threading.Tasks; namespace SaaS.Identity { public partial class AuthRepository { public async Task<Data.Entities.Oauth.OauthSystem> SystemInsertAsync(Data.Entities.Oauth.OauthSystem system) { return await _context.SystemInsertAsync(system); } } }<file_sep>/Shared/SaaS.Identity/AuthDbContext.cs using SaaS.Data.Entities.Accounts; using System.Data.Entity; namespace SaaS.Identity { public partial class AuthDbContext : DbContext { public AuthDbContext() : base("oauth") { Database.SetInitializer<AuthDbContext>(null); Configuration.ProxyCreationEnabled = false; Configuration.LazyLoadingEnabled = false; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Account>().ToTable("accounts.account"); } public DbSet<Account> Accounts { get; set; } } }<file_sep>/Web.Api/SaaS.Sso/src/js/controllers/account/select.js angular.module('app.controllers') .controller('accountSelectController', ['$scope', '$state', '$utils', '$storage', ($scope, $state, $utils, $storage) => { let accounts = $storage.getAccounts(); if (!accounts.length) return $state.go('index'); $scope.model = { accounts: accounts }; $scope.select = (account) => { return $state.go('account/password', account); }; $scope.getFirstChar = (account) => { let value = account.email || account.firstName || account.lastName || ' '; return value[0]; }; $scope.getColor = (account) => { return $utils.stringToColor(account.email); }; }]);<file_sep>/Shared/SaaS.Data.Entities/View/Accounts/ViewAccountEmail.cs using System; namespace SaaS.Data.Entities.View.Accounts { public class ViewAccountEmail : Entity<Guid> { public string Email { get; set; } } } <file_sep>/Shared/SaaS.Data.Entities/Accounts/AccountSubEmail.cs using System; namespace SaaS.Data.Entities.Accounts { public class AccountSubEmail : AccountEntity<int> { public string Email { get; set; } public DateTime CreateDate { get; set; } } }<file_sep>/readme.txt Devel Server http://dev-cp.sodapdf.com http://dev-cp-oauth.sodapdf.com www\web\dev-cp.sodapdf.com www\OAUTH\dev-cp-oauth.sodapdf.com Stage Server https://stage-cp.sodapdf.com https://stage-cp-oauth.sodapdf.com www2\Websites/Sodapdf/stage-cp.sodapdf.com www\Oauth\stage-cp-oauth.sodapdf.com Production: https://cp.sodapdf.com ( in the 2 sodapdf webservers ) https://cp-aouth.sodapdf.com ( in the 2 OAUTH webservers) WWW\Main_Websites\Websites\Soda\cp.sodapdf.com www\sodapdf\cp-oauth.sodapdf.com<file_sep>/Shared/SaaS.Mailer/Models/XmlNotification.cs using System.Xml.Serialization; namespace SaaS.Mailer.Models { [XmlRoot("xml")] public class XmlNotification : Notification { } }<file_sep>/Test/SaaS.Api.Test/HttpTestHelper.cs using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Diagnostics; using System.Net.Http; using System.Threading.Tasks; namespace SaaS.Api.Test { public class HttpTestHelper { protected static async Task<string> AssertIsTrue(HttpResponseMessage response) { Debug.WriteLine("Response status code: {0}", response.StatusCode); string json = await response.Content.ReadAsStringAsync(); Assert.IsTrue(response.IsSuccessStatusCode); return json; } protected static async Task<string> AssertIsFalse(HttpResponseMessage response) { Debug.WriteLine("Response status code: {0}", response.StatusCode); string json = await response.Content.ReadAsStringAsync(); Assert.IsFalse(response.IsSuccessStatusCode); return json; } } } <file_sep>/Shared/SaaS.Mailer/Links.cs using System; using System.Collections.Specialized; using System.Threading; using System.Web; namespace SaaS.Mailer { public static class links { private static string GetLink(string action, NameValueCollection collection = null, string fragment = null) { var uri = string.Empty; #if LuluSoft uri = "http://paygw.sodapdf.com/redirect/{0}/soda-pdf-desktop/"; #endif #if PdfForge uri = "http://paygw.pdfarchitect.org/redirect/{0}/pdf-architect-6/"; #endif #if PdfSam uri = "https://paygw.pdfsam.org/redirect/{0}/pdfsam-enhanced-6/"; #endif var uriBuilder = new UriBuilder(string.Format(uri, action)); var query = HttpUtility.ParseQueryString(string.Empty); query.Add("lang", Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2)); if (!object.Equals(collection, null)) { foreach (string item in collection) query.Set(item, collection[item]); } uriBuilder.Query = query.ToString(); uriBuilder.Fragment = fragment; return uriBuilder.Uri.ToString(); } public static string Localize(string url) { if (string.IsNullOrEmpty(url)) return url; var uriBuilder = new UriBuilder(url); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query.Add("lang", Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2)); uriBuilder.Query = query.ToString(); return uriBuilder.Uri.ToString(); } private static string GetCustomLink(string customValue, string fragment = null) { return GetLink("custom", new NameValueCollection { { "customValue", customValue } }, fragment); } public static string getTrial { get { return GetCustomLink("get-trial"); } } public static string saas { get { return GetCustomLink("saas"); } } public static string saasEsign { get { return GetCustomLink("saas", "esign"); } } public static string privacy { get { return GetLink("privacy"); } } public static string terms { get { return GetCustomLink("online-terms"); } } public static string subscribe { get { return GetCustomLink("subscribe"); } } public static string unsubscribe { get { return GetCustomLink("subscribe"); } } public static string support { get { return GetLink("support"); } } public static string upgrade { get { return GetLink("upgrade"); } } public static string productPricing { get { return GetCustomLink("product-and-pricing"); } } public static string account { get { return GetCustomLink("online-account"); } } public static string knowledgeBase { get { return GetCustomLink("knowledge-base"); } } public static string knowledgeBaseSwitchProduct { get { return GetCustomLink("knowledge-base-switch-product"); } } public static string knowledgeBaseCreatePassword { get { return GetCustomLink("knowledge-base-create-password"); } } public static string knowledgeBaseModifyPlan { get { return GetCustomLink("knowledge-base-modify-plan"); } } } }<file_sep>/Web.Api/SaaS.Api.Mc/Http/McHttpClient.cs using System; using System.Configuration; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace SaaS.Api.Mc.Http { internal class McHttpClient : HttpClient { internal readonly static Uri _path = new Uri(ConfigurationManager.AppSettings["mc:path"]); internal readonly static string _token = ConfigurationManager.AppSettings["mc:token"]; private readonly HttpRequestMessage _request; internal McHttpClient(string token = null) { BaseAddress = _path; if (string.IsNullOrEmpty(token)) token = _token; DefaultRequestHeaders.Add("Authorization", string.Format("Basic {0}", token)); } internal McHttpClient(HttpRequestMessage request, string apiKey = null) : this(apiKey) { _request = request; foreach (var header in _request.Headers.Where(header => !"Authorization".Equals(header.Key, StringComparison.InvariantCultureIgnoreCase))) DefaultRequestHeaders.Add(header.Key, header.Value); DefaultRequestHeaders.Remove("Host"); } internal async Task<HttpResponseMessage> SendAsync(string requestUri, CancellationToken cancellationToken) { string query = _request.RequestUri.Query; if (!string.IsNullOrEmpty(query)) requestUri += query; if (_request.Method == HttpMethod.Get) return await GetAsync(requestUri, cancellationToken); if (_request.Method == HttpMethod.Post) return await PostAsync(requestUri, _request.Content, cancellationToken); if (_request.Method == HttpMethod.Put) return await PutAsync(requestUri, _request.Content, cancellationToken); if (_request.Method == HttpMethod.Delete) return await DeleteAsync(requestUri, cancellationToken); return _request.CreateResponse<dynamic>(System.Net.HttpStatusCode.BadRequest, new { error = "invalid_grant" }); } } }
489f43775806ad7c294a3550d544c4fe665521dd
[ "JavaScript", "C#", "Text", "Markdown" ]
391
C#
whoisyourvladie/Oauth
202f7c042114ca1f734a48c84dc95e300a1b1f5f
eeb1494447665ffc3f1baa98b6e1b272fec5629e
refs/heads/master
<repo_name>dimashermanto/COVIDDashboardApp<file_sep>/app/src/main/java/com/example/kawalcovid/adapter/IndonesiaMostHitProvinceAdapter.kt package com.example.kawalcovid.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.kawalcovid.R import com.example.kawalcovid.dataClasses.ProvinceResponse import kotlinx.android.synthetic.main.indonesia_most_hit_list_item_layout.view.* import kotlinx.android.synthetic.main.item_province.view.* import java.text.NumberFormat class IndonesiaMostHitProvinceAdapter(private var list: ArrayList<ProvinceResponse>): RecyclerView.Adapter<IndonesiaMostHitProvinceAdapter.IndonesiaMostHitProvinceViewHolder>() { inner class IndonesiaMostHitProvinceViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){ fun bind(province: ProvinceResponse){ with(itemView){ mostHitCityName.text = province.attributes.province tvIndonesiaMostHitCityInfection.text = NumberFormat.getInstance().format(province.attributes.positive).toString() } } } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): IndonesiaMostHitProvinceAdapter.IndonesiaMostHitProvinceViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.indonesia_most_hit_list_item_layout, parent, false) return IndonesiaMostHitProvinceViewHolder(view) } override fun getItemCount(): Int { return list.size } override fun onBindViewHolder(holder: IndonesiaMostHitProvinceAdapter.IndonesiaMostHitProvinceViewHolder, position: Int) { holder.bind(list[position]) } }<file_sep>/settings.gradle rootProject.name='KawalCOVID' include ':app' <file_sep>/app/src/main/java/com/example/kawalcovid/dataClasses/GlobalOverallResponse.kt package com.example.kawalcovid.dataClasses data class GlobalOverallResponse ( val attributes: Country )<file_sep>/app/src/main/java/com/example/kawalcovid/api/Api.kt package com.example.kawalcovid.api import com.example.kawalcovid.dataClasses.* import retrofit2.Call import retrofit2.http.GET interface Api { @GET("indonesia") fun getIndonesia(): Call<ArrayList<IndonesiaResponse>> @GET("indonesia/provinsi") fun getProvince(): Call<ArrayList<ProvinceResponse>> @GET("positif") fun getGlobalPositive(): Call<GlobalPositiveResponse> @GET("sembuh") fun getGlobalHealed(): Call<GlobalHealedResponse> @GET("meninggal") fun getGlobalDeath(): Call<GlobalDeathResponse> @GET(".") fun getGlobalOverall(): Call<ArrayList<GlobalOverallResponse>> }<file_sep>/app/src/main/java/com/example/kawalcovid/adapter/ProvinceAdapter.kt package com.example.kawalcovid.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.kawalcovid.R import com.example.kawalcovid.dataClasses.GlobalOverallResponse import com.example.kawalcovid.dataClasses.ProvinceResponse import kotlinx.android.synthetic.main.item_province.view.* import java.text.NumberFormat class ProvinceAdapter(private var list: ArrayList<ProvinceResponse>, private val itemClickListener: ProvinceListOnItemClickListener): RecyclerView.Adapter<ProvinceAdapter.ProvinceViewHolder>() { inner class ProvinceViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){ fun bind(province: ProvinceResponse, clickListener: ProvinceListOnItemClickListener){ with(itemView){ tvProvinceName.text = province.attributes.province tvPositive.text = NumberFormat.getInstance().format(province.attributes.positive).toString() tvDeath.text = NumberFormat.getInstance().format(province.attributes.death).toString() } itemView.setOnClickListener { clickListener.onItemClickListener(province) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProvinceViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_province, parent, false) return ProvinceViewHolder(view) } override fun getItemCount(): Int { return list.size } override fun onBindViewHolder(holder: ProvinceViewHolder, position: Int) { holder.bind(list[position], itemClickListener) } fun filterList(filteredList: ArrayList<ProvinceResponse>) { list = filteredList notifyDataSetChanged() } } interface ProvinceListOnItemClickListener{ fun onItemClickListener(item: ProvinceResponse) }<file_sep>/app/src/main/java/com/example/kawalcovid/dataClasses/ProvinceResponse.kt package com.example.kawalcovid.dataClasses data class ProvinceResponse ( val attributes: Province )<file_sep>/app/src/main/java/com/example/kawalcovid/activity/ProvinceActivity.kt package com.example.kawalcovid.activity import android.icu.text.NumberFormat import android.os.Build import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.widget.ProgressBar import android.widget.Toast import androidx.annotation.RequiresApi import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.example.kawalcovid.adapter.ProvinceAdapter import com.example.kawalcovid.R import com.example.kawalcovid.adapter.ProvinceListOnItemClickListener import com.example.kawalcovid.api.RetrofitClient import com.example.kawalcovid.dataClasses.ProvinceResponse import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputLayout import com.stone.vega.library.VegaLayoutManager import kotlinx.android.synthetic.main.activity_global.* import kotlinx.android.synthetic.main.activity_province.* import kotlinx.android.synthetic.main.country_list_dialog_layout.view.* import kotlinx.android.synthetic.main.country_list_dialog_layout.view.deathTotal import kotlinx.android.synthetic.main.country_list_dialog_layout.view.infectedTotal import kotlinx.android.synthetic.main.country_list_dialog_layout.view.recoveredTotal import kotlinx.android.synthetic.main.province_list_dialog_layout.view.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* import kotlin.collections.ArrayList class ProvinceActivity : AppCompatActivity(), ProvinceListOnItemClickListener, SwipeRefreshLayout.OnRefreshListener { private lateinit var result: ArrayList<ProvinceResponse> lateinit var adapter: ProvinceAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_province) showProvince() provinceRecylerViewBaseSwipeLayout.setOnRefreshListener(this) findViewById<TextInputEditText>(R.id.SearchBarEditText).addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { filterString(s.toString()) } }) } fun filterString(text: String) { val filteredList: ArrayList<ProvinceResponse> = ArrayList() for (item in result) { if (item.attributes.province.toLowerCase(Locale.ROOT).contains(text.toLowerCase(Locale.ROOT))) { filteredList.add(item) } } adapter.filterList(filteredList) } private fun showProvince() { findViewById<TextInputLayout>(R.id.SearchBarInputLayout).isEnabled = false rvProvince.setHasFixedSize(true) rvProvince.visibility = View.GONE RetrofitClient.instance.getProvince().enqueue(object: Callback<ArrayList<ProvinceResponse>>{ override fun onFailure(call: Call<ArrayList<ProvinceResponse>>, t: Throwable) { findViewById<ProgressBar>(R.id.progressBar).visibility = View.GONE findViewById<TextInputLayout>(R.id.SearchBarInputLayout).helperText = t.localizedMessage Toast.makeText(this@ProvinceActivity, t.message, Toast.LENGTH_SHORT).show() provinceRecylerViewBaseSwipeLayout.isRefreshing = false } override fun onResponse( call: Call<ArrayList<ProvinceResponse>>, response: Response<ArrayList<ProvinceResponse>> ) { findViewById<TextInputLayout>(R.id.SearchBarInputLayout).isEnabled = true findViewById<ProgressBar>(R.id.progressBar).visibility = View.GONE rvProvince.visibility = View.VISIBLE try { val list = response.body() adapter = list?.let { ProvinceAdapter( it, this@ProvinceActivity ) }!! rvProvince.setHasFixedSize(true) rvProvince.onFlingListener = null rvProvince.layoutManager = VegaLayoutManager() rvProvince.adapter = adapter provinceRecylerViewBaseSwipeLayout.isRefreshing = false result = response.body()!! }catch (e: NullPointerException){ Toast.makeText(this@ProvinceActivity, "NullFuckingPointerException returned", Toast.LENGTH_SHORT).show() }catch (e: TypeCastException){ Toast.makeText(this@ProvinceActivity, "TypeCastException returned", Toast.LENGTH_SHORT).show() } } }) } override fun onRefresh() { showProvince() } @RequiresApi(Build.VERSION_CODES.N) override fun onItemClickListener(item: ProvinceResponse) { //Inflate the dialog with custom view val mDialogView = LayoutInflater.from(this).inflate( R.layout.province_list_dialog_layout, null ) mDialogView.provinceId.text = item.attributes.code.toString() mDialogView.provinceName.text = item.attributes.province mDialogView.infectedTotal.text = NumberFormat.getInstance().format(item.attributes.positive).toString() mDialogView.deathTotal.text = NumberFormat.getInstance().format(item.attributes.death).toString() mDialogView.recoveredTotal.text = NumberFormat.getInstance().format(item.attributes.recover).toString() //AlertDialogBuilder val mBuilder = AlertDialog.Builder(this) .setView(mDialogView) //show dialog val mAlertDialog = mBuilder.show() mDialogView.provinceCloseButton.setOnClickListener { //dismiss dialog mAlertDialog.dismiss() } } } <file_sep>/app/src/main/java/com/example/kawalcovid/adapter/CountryAdapter.kt package com.example.kawalcovid.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.kawalcovid.R import com.example.kawalcovid.dataClasses.Country import com.example.kawalcovid.dataClasses.GlobalOverallResponse import kotlinx.android.synthetic.main.item_country.view.* import java.text.NumberFormat class CountryAdapter(private var list: ArrayList<GlobalOverallResponse>, private var itemClickListener: CountryListOnItemClickListener): RecyclerView.Adapter<CountryAdapter.CountryViewHolder>() { inner class CountryViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { fun bind(country: GlobalOverallResponse, clickListener: CountryListOnItemClickListener){ with(itemView){ tvCountryName.text = country.attributes.country tvCountryPositive.text = NumberFormat.getInstance().format(country.attributes.positive).toString() tvCountryDeath.text = NumberFormat.getInstance().format(country.attributes.death).toString() } itemView.setOnClickListener { clickListener.onItemClickListener(country) } } } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): CountryViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_country, parent, false) return CountryViewHolder(view) } override fun getItemCount(): Int { return list.size } override fun onBindViewHolder(holder: CountryViewHolder, position: Int) { holder.bind(list[position], itemClickListener) } fun filterList(filteredList: ArrayList<GlobalOverallResponse>) { list = filteredList notifyDataSetChanged() } } interface CountryListOnItemClickListener{ fun onItemClickListener(item: GlobalOverallResponse) }<file_sep>/app/src/main/java/com/example/kawalcovid/activity/IntroActivity.kt package com.example.kawalcovid.activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import com.example.kawalcovid.R class IntroActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_intro) Handler().postDelayed({ redirectToMainActivity() }, 3000) } private fun redirectToMainActivity() { Intent(this, MainActivity::class.java).also { it.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK startActivity(it) } } }<file_sep>/app/src/main/java/com/example/kawalcovid/activity/MainActivity.kt package com.example.kawalcovid.activity import android.content.Intent import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.example.kawalcovid.R import com.example.kawalcovid.adapter.IndonesiaMostHitProvinceAdapter import com.example.kawalcovid.api.RetrofitClient import com.example.kawalcovid.dataClasses.ProvinceResponse import com.example.kawalcovid.viewModel.MainViewModel import kotlinx.android.synthetic.main.activity_main.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener { private lateinit var viewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java) viewModel.showIndonesia() viewModel.showGlobalOverall() getIndonesianProvinceData() setupObserverOfDashboardData() rvIndonesiaMostHit.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) globaSeeAllButton.setOnClickListener { navigateToCountryList() } indonesiaSeeAllButton.setOnClickListener { navigateToProvinceList() } } private fun getIndonesianProvinceData(){ tvJakartaInfection.text = "Loading" tvWestJavaInfection.text = "Loading" RetrofitClient.instance.getProvince().enqueue(object: Callback<ArrayList<ProvinceResponse>> { override fun onFailure(call: Call<ArrayList<ProvinceResponse>>, t: Throwable) { tvJakartaInfection.text = "N/A" tvWestJavaInfection.text = "N/A" } override fun onResponse( call: Call<ArrayList<ProvinceResponse>>, response: Response<ArrayList<ProvinceResponse>> ) { val jakartaAttributes = response.body()?.filter { it.attributes.province == "DKI Jakarta" } val jakartaPositive = jakartaAttributes?.get(0)?.attributes?.positive val westJavaAttributes = response.body()?.filter { it.attributes.province == "Jawa Barat" } val westJavaPositive = westJavaAttributes?.get(0)?.attributes?.positive Log.i("MainVM", "Most Hit Province : ${response.body()?.slice(0..4)}") rvIndonesiaMostHit.adapter = IndonesiaMostHitProvinceAdapter(response.body()?.slice(0..5) as ArrayList<ProvinceResponse>) tvWestJavaInfection.text = "$westJavaPositive" tvJakartaInfection.text = "$jakartaPositive" } }) } private fun setupObserverOfDashboardData() { viewModel.globalPositiveTotal.observe(this, Observer { it -> tvGlobalPositive.text = it }) viewModel.globalHealedTotal.observe(this, Observer { it -> tvGlobalRecover.text = it }) viewModel.globalDeathTotal.observe(this, Observer { it -> tvGlobalDeath.text = it }) tvGlobalHospitalized.text = "N/A" viewModel.indonesiaPositiveTotal.observe(this, Observer { it -> tvIndonesiaPositive.text = it }) viewModel.indonesiaHospitalizedTotal.observe(this, Observer { it -> tvIndonesiaHospitalized.text = it }) viewModel.indonesiaHealedTotal.observe(this, Observer { it -> tvIndonesiaRecover.text = it }) viewModel.indonesiaDeathTotal.observe(this, Observer { it -> tvIndonesiaDeath.text = it }) viewModel.provinceButtonEnabledStatus.observe(this, Observer { indonesiaSeeAllButton.isEnabled = it }) viewModel.countriesButtonEnabledStatus.observe(this, Observer { globaSeeAllButton.isEnabled = it }) } private fun navigateToCountryList(){ Log.i("Country", "Clicked!") Intent(this@MainActivity, GlobalActivity::class.java).also { startActivity(it) } } private fun navigateToProvinceList(){ Log.i("Province", "Clicked!") Intent(this@MainActivity, ProvinceActivity::class.java).also { startActivity(it) } } override fun onRefresh() { viewModel.showIndonesia() viewModel.showGlobalOverall() } } <file_sep>/app/src/main/java/com/example/kawalcovid/activity/GlobalActivity.kt package com.example.kawalcovid.activity import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.icu.text.NumberFormat import android.os.Build import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.widget.Toast import androidx.annotation.RequiresApi import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.example.kawalcovid.R import com.example.kawalcovid.adapter.CountryAdapter import com.example.kawalcovid.adapter.CountryListOnItemClickListener import com.example.kawalcovid.api.RetrofitClient import com.example.kawalcovid.dataClasses.GlobalOverallResponse import com.google.android.material.textfield.TextInputEditText import com.stone.vega.library.VegaLayoutManager import kotlinx.android.synthetic.main.activity_global.* import kotlinx.android.synthetic.main.country_list_dialog_layout.view.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* import kotlin.collections.ArrayList class GlobalActivity : AppCompatActivity(), CountryListOnItemClickListener, SwipeRefreshLayout.OnRefreshListener { // private lateinit var viewModel: GlobalActivityViewModel lateinit var resultsForSearchUtility: ArrayList<GlobalOverallResponse> lateinit var adapter: CountryAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_global) showCountries() globalRecylerViewBaseSwipeLayout.setOnRefreshListener(this) findViewById<TextInputEditText>(R.id.countrySearchBarEditText).addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { filterString(s.toString()) } }) } private fun showCountries() { rvCountry.visibility = View.GONE countrySearchBarInputLayout.isEnabled = false RetrofitClient.instance.getGlobalOverall() .enqueue(object : Callback<ArrayList<GlobalOverallResponse>> { override fun onFailure(call: Call<ArrayList<GlobalOverallResponse>>, t: Throwable) { } override fun onResponse( call: Call<ArrayList<GlobalOverallResponse>>, response: Response<ArrayList<GlobalOverallResponse>> ) { rvCountry.visibility = View.VISIBLE countrySearchBarInputLayout.isEnabled = true val countryList = response.body() try { adapter = countryList?.let { CountryAdapter( it, this@GlobalActivity ) }!! rvCountry.setHasFixedSize(true) rvCountry.onFlingListener = null rvCountry.layoutManager = VegaLayoutManager() rvCountry.adapter = adapter globalProgressBar.visibility = View.GONE globalRecylerViewBaseSwipeLayout.isRefreshing = false resultsForSearchUtility = response.body()!! } catch (e: NullPointerException) { Toast.makeText( this@GlobalActivity, "NullFuckingPointerException returned", Toast.LENGTH_SHORT ).show() } catch (e: TypeCastException) { Toast.makeText( this@GlobalActivity, "TypeCastException returned", Toast.LENGTH_SHORT ).show() } } }) } fun filterString(text: String) { val filteredList: ArrayList<GlobalOverallResponse> = ArrayList() for (item in resultsForSearchUtility) { if (item.attributes.country.toLowerCase(Locale.ROOT) .contains(text.toLowerCase(Locale.ROOT)) ) { filteredList.add(item) } } adapter.filterList(filteredList) } override fun onRefresh() { showCountries() } @RequiresApi(Build.VERSION_CODES.N) override fun onItemClickListener(item: GlobalOverallResponse) { //Inflate the dialog with custom view val mDialogView = LayoutInflater.from(this).inflate( R.layout.country_list_dialog_layout, null ) mDialogView.countryId.text = item.attributes.OBJECTID.toString() mDialogView.countryName.text = item.attributes.country mDialogView.infectedTotal.text = NumberFormat.getInstance().format(item.attributes.positive).toString() mDialogView.deathTotal.text = NumberFormat.getInstance().format(item.attributes.death).toString() mDialogView.recoveredTotal.text = NumberFormat.getInstance().format(item.attributes.recovered).toString() mDialogView.currentInfected.text = NumberFormat.getInstance().format(item.attributes.active).toString() //AlertDialogBuilder val mBuilder = AlertDialog.Builder(this) .setView(mDialogView) //show dialog val mAlertDialog = mBuilder.show() mAlertDialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) mDialogView.countryCloseButton.setOnClickListener { //dismiss dialog mAlertDialog.dismiss() } } } <file_sep>/app/src/main/java/com/example/kawalcovid/viewModel/MainViewModel.kt package com.example.kawalcovid.viewModel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.kawalcovid.api.RetrofitClient import com.example.kawalcovid.dataClasses.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainViewModel : ViewModel() { private var _globalPositiveTotal = MutableLiveData<String>() val globalPositiveTotal: LiveData<String> get() = _globalPositiveTotal private var _globalHealedTotal = MutableLiveData<String>() val globalHealedTotal: LiveData<String> get() = _globalHealedTotal private var _globalDeathTotal = MutableLiveData<String>() val globalDeathTotal: LiveData<String> get() = _globalDeathTotal private var _depokInfectedTotal = MutableLiveData<String>() val depokInfectedTotal: LiveData<String> get() = _depokInfectedTotal private var _jakartaInfectedTotal = MutableLiveData<String>() val jakartaInfectedTotal: LiveData<String> get() = _jakartaInfectedTotal private var _indonesiaPositiveTotal = MutableLiveData<String>() val indonesiaPositiveTotal: LiveData<String> get() =_indonesiaPositiveTotal private var _indonesiaHospitalizedTotal = MutableLiveData<String>() val indonesiaHospitalizedTotal: LiveData<String> get() =_indonesiaHospitalizedTotal private var _indonesiaDeathTotal = MutableLiveData<String>() val indonesiaDeathTotal: LiveData<String> get() =_indonesiaDeathTotal private var _indonesiaHealedTotal = MutableLiveData<String>() val indonesiaHealedTotal: LiveData<String> get() =_indonesiaHealedTotal private var _indonesiaMostHitProvinceList = MutableLiveData<ArrayList<ProvinceResponse>>() val indonesiaMostHitProvinceList: LiveData<ArrayList<ProvinceResponse>> get() = _indonesiaMostHitProvinceList private var _refreshStatus = MutableLiveData<Boolean>() val refreshStatus: LiveData<Boolean> get() = _refreshStatus private var _provinceButtonEnabledStatus = MutableLiveData<Boolean>() val provinceButtonEnabledStatus: LiveData<Boolean> get() = _provinceButtonEnabledStatus private var _countriesButtonEnabledStatus = MutableLiveData<Boolean>() val countriesButtonEnabledStatus: LiveData<Boolean> get() = _countriesButtonEnabledStatus init { _indonesiaPositiveTotal.value = "Loading..." _indonesiaHospitalizedTotal.value = "Loading..." _indonesiaDeathTotal.value = "Loading..." _indonesiaHealedTotal.value = "Loading..." _globalPositiveTotal.value = "Loading..." _globalDeathTotal.value = "Loading..." _globalHealedTotal.value = "Loading..." _jakartaInfectedTotal.value = "Loading..." _depokInfectedTotal.value = "Loading..." _indonesiaMostHitProvinceList = MutableLiveData<ArrayList<ProvinceResponse>>() _refreshStatus.value = false } fun showGlobalOverall(){ showGlobalDeath() showGlobalPositive() showGlobalHealed() } private fun showGlobalPositive() { _globalPositiveTotal.value = "Loading..." _countriesButtonEnabledStatus.value = false RetrofitClient.instance.getGlobalPositive().enqueue(object : Callback<GlobalPositiveResponse> { override fun onFailure(call: Call<GlobalPositiveResponse>, t: Throwable) { _globalPositiveTotal.value = "N/A" } override fun onResponse( call: Call<GlobalPositiveResponse>, response: Response<GlobalPositiveResponse> ) { _globalPositiveTotal.value = response.body()?.value.toString() _countriesButtonEnabledStatus.value = true } }) } private fun showGlobalHealed() { _globalHealedTotal.value = "Loading..." RetrofitClient.instance.getGlobalHealed().enqueue(object : Callback<GlobalHealedResponse> { override fun onFailure(call: Call<GlobalHealedResponse>, t: Throwable) { _globalHealedTotal.value = "N/A" } override fun onResponse( call: Call<GlobalHealedResponse>, response: Response<GlobalHealedResponse> ) { _globalHealedTotal.value = response.body()?.value.toString() } }) } private fun showGlobalDeath() { _globalDeathTotal.value = "Loading..." RetrofitClient.instance.getGlobalDeath().enqueue(object : Callback<GlobalDeathResponse> { override fun onFailure(call: Call<GlobalDeathResponse>, t: Throwable) { _globalDeathTotal.value = "N/A" } override fun onResponse( call: Call<GlobalDeathResponse>, response: Response<GlobalDeathResponse> ) { _globalDeathTotal.value = response.body()?.value.toString() } }) } fun showIndonesia() { _indonesiaPositiveTotal.value = "Loading..." _indonesiaHospitalizedTotal.value = "Loading..." _indonesiaDeathTotal.value = "Loading..." _indonesiaHealedTotal.value = "Loading..." _provinceButtonEnabledStatus.value = false RetrofitClient.instance.getIndonesia().enqueue(object : Callback<ArrayList<IndonesiaResponse>> { override fun onFailure(call: Call<ArrayList<IndonesiaResponse>>, t: Throwable) { _indonesiaPositiveTotal.value = "N/A" _indonesiaHospitalizedTotal.value = "N/A" _indonesiaHealedTotal.value = "N/A" _indonesiaDeathTotal.value = "N/A" _refreshStatus.value = false } override fun onResponse( call: Call<ArrayList<IndonesiaResponse>>, response: Response<ArrayList<IndonesiaResponse>> ) { val indonesiaResponseBody = response.body()?.get(0) val positiveCount = indonesiaResponseBody?.positif.toString() val hospitalizedCount = indonesiaResponseBody?.dirawat.toString() val recoveredCount = indonesiaResponseBody?.sembuh.toString() val deathCOunt = indonesiaResponseBody?.meninggal.toString() _indonesiaPositiveTotal.value = positiveCount _indonesiaHospitalizedTotal.value = hospitalizedCount _indonesiaHealedTotal.value = recoveredCount _indonesiaDeathTotal.value = deathCOunt _refreshStatus.value = false _provinceButtonEnabledStatus.value = true } }) } }<file_sep>/app/src/main/java/com/example/kawalcovid/dataClasses/Country.kt package com.example.kawalcovid.dataClasses import com.google.gson.annotations.SerializedName data class Country ( @SerializedName("OBJECTID") val OBJECTID: Int, @SerializedName("Country_Region") val country: String, @SerializedName("Confirmed") val positive: Int, @SerializedName("Deaths") val death: Int, @SerializedName("Recovered") val recovered: Int, @SerializedName("Active") val active: Int )<file_sep>/app/src/main/java/com/example/kawalcovid/viewModel/GlobalActivityViewModel.kt package com.example.kawalcovid.viewModel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.kawalcovid.adapter.CountryAdapter import com.example.kawalcovid.adapter.CountryListOnItemClickListener import com.example.kawalcovid.api.RetrofitClient import com.example.kawalcovid.dataClasses.GlobalOverallResponse import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* import kotlin.collections.ArrayList class GlobalActivityViewModel: ViewModel(), CountryListOnItemClickListener { private var _result = MutableLiveData<ArrayList<GlobalOverallResponse>>() val result: LiveData<ArrayList<GlobalOverallResponse>> get() = _result private var _loadStatus = MutableLiveData<Boolean>() val loadStatus : LiveData<Boolean> get() = _loadStatus lateinit var adapter: CountryAdapter init { _loadStatus.value = false } fun showCountries() { RetrofitClient.instance.getGlobalOverall() .enqueue(object : Callback<ArrayList<GlobalOverallResponse>> { override fun onFailure(call: Call<ArrayList<GlobalOverallResponse>>, t: Throwable) { } override fun onResponse( call: Call<ArrayList<GlobalOverallResponse>>, response: Response<ArrayList<GlobalOverallResponse>> ) { _loadStatus.value = true Log.i("Country", response.body().toString()) val list = response.body() adapter = list?.let { CountryAdapter( it, this@GlobalActivityViewModel ) }!! _result.value = response.body()!! } }) } fun filterString(text: String) { val filteredList: ArrayList<GlobalOverallResponse> = ArrayList() for (item in _result.value!!) { if (item.attributes.country.toLowerCase(Locale.ROOT) .contains(text.toLowerCase(Locale.ROOT)) ) { filteredList.add(item) } } adapter.filterList(filteredList) } override fun onItemClickListener(item: GlobalOverallResponse) { //Do Nothing } }
9cdee8338289c0b15c87a8341cb799aefadaf38c
[ "Kotlin", "Gradle" ]
14
Kotlin
dimashermanto/COVIDDashboardApp
4a1380573e21e99658d6d1b07cafde86caabc807
e8207768333153f6a812f74239889c5be9e8e4b8
refs/heads/master
<repo_name>andreepdias/IA0001<file_sep>/Anealling/plot.py import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('classic') arquivo = 'uf250_01.cnf' tipo_resfriamento = '8' numero_iteracoes = 250000 numero_testes = 10 prefixo = '' arrays = [0.0] * numero_testes for i in range(0, numero_testes): arrays[i] = [0.0] * numero_iteracoes for i in range(0, numero_testes): nome_arquivo = arquivo + '_' + tipo_resfriamento + '_' + str(i+1) + prefixo with open(nome_arquivo) as f: j = 0 for line in f: # read rest of lines arrays[i][j] = float(line) j = j +1 array = [] x = 0 for k in range(0, numero_iteracoes): media = 0.0 for i in range(0, numero_testes): media = media + arrays[i][k] media = media / numero_testes print(media) x = x + 1 if x == 1: array.append(media) x = 0 # print(arrays[0][0]) # print(arrays[1][0]) # print(arrays[2][0]) # print(arrays[3][0]) # print(arrays[4][0]) # print(arrays[5][0]) # print(arrays[6][0]) # print(arrays[7][0]) # print(arrays[8][0]) # print(arrays[9][0]) # print(array[0]) plt.plot(array, marker=None, color="r") plt.savefig('250_anealing_1.png') <file_sep>/Anealling/anealling.cpp /** representar solução do problema: vetor de cláusulas avaliar solução do problema: número de cláusulas satisfeitas pertubar solução do problema: alterar uma variável .. Clever Algorithms: Nature-Inspired Programming Recipes www.cleveralgorithms.com/nature-inspired/stochastic/random_search.html dicas execuoes: 1. varias vezes independente 2. grafico de convergencia resultado da solução a cada iteração gnu-plot https://stackoverflow.com/questions/18176591/importerror-no-module-named-matplotlib-pyplot https://github.com/google/python-subprocess32/issues/38 sudo apt-get install -y python-subprocess32 sudo pip uninstall matplotlib sudo python3 -m pip install matplotlib sudo apt-get install python3-tk **/ #include <bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef vector<bool> vb; #define PI 3.14159265 struct Clausula{ int *v; Clausula(int a, int b, int c){ v = new int[3]; if(a > 0) a--; else a++; if(b > 0) b--; else b++; if(c > 0) c--; else c++; v[0] = a, v[1] = b, v[2] = c; } bool isTrue(vb &variaveis){ return (v[0] > 0 ? (variaveis[v[0]]) : (not variaveis[-v[0]])) or (v[1] > 0 ? (variaveis[v[1]]) : (not variaveis[-v[1]])) or (v[2] > 0 ? (variaveis[v[2]]) : (not variaveis[-v[2]])); } }; typedef vector<Clausula> vc; void printClausulas(vc &clausulas, int var, int clau){ cout << var << " " << clau << endl; for(int i = 0; i < clau; i++){ cout << i+1 << ".\t" << clausulas[i].v[0] << "\t" << clausulas[i].v[1] << "\t" << clausulas[i].v[2] << endl; } } void printVariables(vb &variaveis){ for(int i = 0; i < variaveis.size(); i++){ cout << i+1 << ".\t"; if(variaveis[i]){ cout << "true"; }else{ cout << "false"; } cout << endl; } } void readFile(vc &clausulas, vb &variaveis, ifstream &arquivo, int &n, double &t0, double &tn){ int var, clau, a, b, c, x; ifstream arquivo_parametros("parametros"); arquivo >> var >> clau; arquivo_parametros >> n >> t0 >> tn; for(int i = 0; i < var; i++){ variaveis.push_back(false); } while(arquivo >> a >> b >> c >> x){ clausulas.push_back(Clausula(a, b, c)); } // printClausulas(clausulas, var, clau); } void randomize(vb &variaveis){ // srand(time(NULL)); int x; for(int i = 0; i < variaveis.size(); i++){ x = rand() % 2; x == 0 ? (variaveis[i] = false) : (variaveis[i] = true); } // printVariables(variaveis); } int avaliate(vb &variaveis, vc &clausulas){ int cont = 0; for(int i = 0; i < clausulas.size(); i++){ if(clausulas[i].isTrue(variaveis)){ cont++; } } return cont; } void flip(vb &variaveis, int i){ if(variaveis[i]){ variaveis[i] = false; }else{ variaveis[i] = true; } } double calculateTemperature0(int i, int n, double t0, double tn){ double t = t0 - (double)i * ((t0 - tn) / n); // cout << t << endl; return t; } double calculateTemperature1(int i, int n, double t0, double tn){ double t = t0 * pow((tn / t0), ((double)i / n)); // cout << t << endl; return t; } double calculateTemperature2(int i, int n, double t0, double tn){ double a = (double)((double)(t0 - tn) * (double)(n + 1)) / (double)n; double b = (double)t0 - a; double t = ((double)a / (double)(i + 1)) + (double)b; // cout << t << endl; return t; } double calculateTemperature3(int i, int n, double t0, double tn){ double a = (double)log(t0 - tn) / log(n); double t = t0 - pow((double)i, a); // cout << t << endl; return t; } double calculateTemperature4(int i, int n, double t0, double tn){ double t = ((t0 - tn) / (1 + exp(3 * (i - ((double)n / 2))))) + tn; // cout << t << endl; return t; } double calculateTemperature5(int i, int n, double t0, double tn){ double t = ((double)1 / 2) * (t0 - tn) * (1 + cos((i * M_PI) / n)) + tn; // cout << t << endl; return t; } double calculateTemperature6(int i, int n, double t0, double tn){ double t = ((double)1 / 2) * (t0 - tn) * (1 - tanh( ((double)(10 * i) / n) - 5 )) + tn; // cout << t << endl; return t; } double calculateTemperature7(int i, int n, double t0, double tn){ double t = ((t0 - tn) / cosh((double)(10 * i) / n)) + tn; // cout << t << endl; return t; } double calculateTemperature8(int i, int n, double t0, double tn){ double a = ((double)1 / n) * log((double) t0 / tn); double t = t0 * exp(-a * i); // cout << t << endl; return t; } double calculateTemperature9(int i, int n, double t0, double tn){ double a = ((double)1 / pow(n, 2)) * log((double) t0 / tn); double t = t0 * exp(-a * pow(i, 2)); // cout << t << endl; return t; } double calculateTemperature(int i, int n, double t0, double tn, int cs){ switch(cs){ case 0: return calculateTemperature0(i, n, t0, tn); case 1: return calculateTemperature1(i, n, t0, tn); case 2: return calculateTemperature2(i, n, t0, tn); case 3: return calculateTemperature3(i, n, t0, tn); case 4: return calculateTemperature4(i, n, t0, tn); case 5: return calculateTemperature5(i, n, t0, tn); case 6: return calculateTemperature6(i, n, t0, tn); case 7: return calculateTemperature7(i, n, t0, tn); case 8: return calculateTemperature8(i, n, t0, tn); case 9: return calculateTemperature9(i, n, t0, tn); default: return calculateTemperature0(i, n, t0, tn); } } pair<int,int> annealing(vb &variaveis, vc &clausulas, int atual, int n, double t0, double tn, int cs, string arquivo, int iteracao){ int s = variaveis.size(), a, m = atual; double p, t, c; vb conf_candidata; vb conf_atual; string nome_arquivo = arquivo + "_" + to_string(cs) + "_" + to_string(iteracao); ofstream arq_saida(nome_arquivo); conf_atual = variaveis; for(int k = 0; k < n; k++){ arq_saida << atual << endl; // cout << atual << endl; conf_candidata = conf_atual; for(int i = 0; i < s; i++){ //FLIP 5% DAS VARIÁVEIS p = (double) rand() / RAND_MAX; if(p < 0.01){ flip(conf_candidata, i); } } a = avaliate(conf_candidata, clausulas); //VERIFICA SE CONFIGURAÇÃO GERADA É MELHOR QUE ATUAL if(a > atual){ conf_atual = conf_candidata; atual = a; m = max(m, a); }else if(a < atual){ t = calculateTemperature(k, n, t0, tn, cs); p = (double) rand() / RAND_MAX; c = exp((double)(a - atual) / t); if(p <= c){ conf_atual = conf_candidata; atual = a; } } } return make_pair(atual, m); } pair<int,int> random(vb &variaveis, vc &clausulas, int atual, int n, double t0, double tn, int cs, string arquivo, int iteracao){ // srand(time(NULL)); int s = variaveis.size(), a, m = atual, x; double p, t, c; string nome_arquivo = arquivo + "_" + to_string(cs) + "_" + to_string(iteracao) + "_random"; ofstream arq_saida(nome_arquivo); for(int k = 0; k < n; k++){ randomize(variaveis); a = avaliate(variaveis, clausulas); //VERIFICA SE CONFIGURAÇÃO GERADA É MELHOR QUE ATUAL arq_saida << a << endl; // cout << a << endl; if(a > m){ m = a; } } return make_pair(atual, m); } int main(int argc, char const *argv[]) { srand(time(NULL)); ifstream arquivo(argv[1]); vb variaveis; vc clausulas; int numero_iteracoes, atual, tipo_resfriamento = stoi(argv[2]); double temperatura_inicial, temperatura_final; string nome_arquivo = argv[1]; readFile(clausulas, variaveis, arquivo, numero_iteracoes, temperatura_inicial, temperatura_final); double media = 0; pair<int,int> x; // cout << "Arquivo: " << nome_arquivo << endl; // cout << "Tipo de resfriamento: " << argv[2] << endl; // cout << "t0: " << temperatura_inicial << "\ttn: " << temperatura_final << endl; for(int i = 0; i < 10; i++){ randomize(variaveis); atual = avaliate(variaveis, clausulas); x = annealing(variaveis, clausulas, atual, numero_iteracoes, temperatura_inicial, temperatura_final, tipo_resfriamento, nome_arquivo, i+1); media += x.second; cout << "Execucao " << i+1 << ": " << x.first << "\t (max: " << x.second << ")" << endl; } media /= 10; cout << "Media: " << media << endl; } <file_sep>/AntClust/ACO.cpp //g++ test.cpp -o s -lsfml-graphics -lsfml-window -lsfml-system #include <bits/stdc++.h> #include <SFML/Graphics.hpp> using namespace std; typedef vector<int> vi; typedef vector<vector<int> > vvi; #define WINDOW_SIZE 700 int dx[] = {-1, 0, 0, 1}; int dy[] = {0, -1, 1, 0}; struct Ant{ int x, y, raio; bool carregando; Ant(int a, int b, int r){ x = a, y = b, raio = r; carregando = false; } int countItens(vvi &grid){ int a, b, sg = grid.size(); int cont = 0; for(int i = -raio; i <= raio; i++){ for(int j = -raio; j <= raio; j++){ if(i == 0 and j == 0) continue; a = x + i; b = y + j; if(a < 0) a = sg - 1; else if(a >= sg) a = 0; if(b < 0) b = sg - 1; else if(b >= sg) b = 0; if(grid[a][b] == 1){ cont++; } } } return cont; } void move(int sg){ int r = rand() % 4; x += dx[r]; y += dy[r]; if(x < 0) x = sg -1; else if(x >= sg) x = 0; if(y < 0) y = sg - 1; else if(y >= sg) y = 0; } void drop(vvi &grid){ if(grid[x][y] == 1) return; int num_casas, num_itens; double prob_drop, prob_rand; num_casas = (2 * raio + 1) * (2 * raio + 1) - 1; num_itens = countItens(grid); prob_drop = (num_itens * 1.0 / num_casas); prob_drop *= prob_drop; prob_drop -= 0.0025; prob_rand = (double) rand() / RAND_MAX; if(prob_rand <= prob_drop){ grid[x][y] = 1; carregando = false; } } void pick(vvi &grid){ if(grid[x][y] == 0) return; int num_casas, num_itens; double prob_pick, prob_rand; num_casas = (2 * raio + 1) * (2 * raio + 1) - 1; num_itens = countItens(grid); prob_pick = 1 - (num_itens * 1.0 / num_casas); prob_pick *= prob_pick; prob_pick += 0.0025; prob_rand = (double) rand() / RAND_MAX; if(prob_rand <= prob_pick){ grid[x][y] = 0; carregando = true; } } void forceDrop(vvi &grid){ int k = 0, sg = grid.size(); while(carregando and k <= 1000000){ move(sg); drop(grid); k++; } if(carregando){ carregando = false; grid[x][y] = 1; } } }; void draw(vvi &grid, sf::RenderWindow &window){ int sx = grid.size(); int sy = grid[0].size(); sf::RectangleShape item(sf::Vector2f(WINDOW_SIZE / (double) sx, WINDOW_SIZE / (double) sx)); for(int i = 0; i < sx; i++){ for(int j = 0; j < sy; j++){ if(grid[i][j] == 1){ item.setFillColor(sf::Color(30,30,30)); }else{ item.setFillColor(sf::Color(255,255,255)); } item.setPosition(WINDOW_SIZE * i / (double)sx, WINDOW_SIZE * j / (double) sy); window.draw(item); } } window.display(); } void initGrid(vvi &grid, vector<Ant> &ants, int tam_grid, int num_formigas, int num_itens, int tam_raio){ srand(time(NULL)); grid = vvi(tam_grid, vi(tam_grid, 0)); int x, y; for(int i = 0; i < num_itens; i++){ do{ x = rand() % tam_grid; y = rand() % tam_grid; }while(grid[x][y] != 0); grid[x][y] = 1; } for(int i = 0; i < num_formigas; i++){ int x = rand() % tam_grid; int y = rand() % tam_grid; ants.push_back(Ant(x, y, tam_raio)); } } int main(){ sf::RenderWindow window(sf::VideoMode(WINDOW_SIZE, WINDOW_SIZE), "ACO"); int tam_grid, num_formigas, num_itens, num_iteracoes, tam_raio; ifstream in("input1.txt"); cout << "Lendo dados de entrada..." << endl; in >> tam_grid >> num_formigas >> num_itens >> tam_raio >> num_iteracoes; cout << "Dados de entrada lidos." << endl; cout << "Tamanho da Grid:\t" << tam_grid << " x " << tam_grid << endl; cout << "Numero de formigas:\t" << num_formigas << endl; cout << "Numero de itens:\t" << num_itens << endl; cout << "Tamanho do raio:\t" << tam_raio << endl; cout << "Numero de iteracoes:\t" << num_iteracoes << endl; vvi grid; vector<Ant> ants; initGrid(grid, ants, tam_grid, num_formigas, num_itens, tam_raio); int sa = ants.size(); int k = 0, kk = 0; while(num_iteracoes--){ for(int i = 0; i < sa; i++){ ants[i].move(tam_grid); if(ants[i].carregando){ ants[i].drop(grid); }else{ ants[i].pick(grid); } } k++; if(k == 10000){ sf::Event event; while(window.pollEvent(event)){ if(event.type == sf::Event::Closed) window.close(); } kk += k; k = 0; cout << "Numero de iteracoes: " << kk << endl; draw(grid, window); } } for(int i = 0; i < num_formigas; i++){ ants[i].forceDrop(grid); } cout << "Formigas paradas." << endl; draw(grid, window); bool pressed = false; while(pressed == false){ if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)){ pressed = true; } } window.close(); return 0; } <file_sep>/AntClust/makefile CC = g++ FILES = ACO.cpp LINKS = -Wall -lsfml-graphics -lsfml-window -lsfml-system -std=c++11 -O2 all: $(CC) -o s $(FILES) $(LINKS) -o s && ./s <file_sep>/README.md # IA0001 Implementação da meta-heurística Recozimento Simulado (Simulated Annealing) e Agrupamento por Colônia de Formigas (Ant Clustering) em C++. Algoritmos desenvolvidos na disciplina de Inteligência Artificial. <file_sep>/Anealling/inteiro.cpp #include <bits/stdc++.h> using namespace std; class AlgoritmoGeneticoReal{ public: vector< vector<double> > populacao; int tamanhoPopulacao, tamanhoIndividuo, chanceMutacao, chanceCrossOver, geracao; double low, high; bool elitismo; vector<double> geraIndividuo(){ random_device rd; mt19937 gen(rd()); uniform_real_distribution<double> dis(low, high); vector<double> individuo; for(int i = 0; i < tamanhoIndividuo; i++) individuo.push_back(dis(gen)); return individuo; } void printPopulacao(){ for(vector<double>& individuo : populacao){ for(double gene : individuo) cout << gene << " "; cout << endl; } cout << endl; } double func_objetivo(vector<double>& gene){ int res = 0; for(int i = 1; i < (int)gene.size(); i++) if(gene[i]%2 != gene[i-1]%2) res++; return res; } double func_penalidade(vector<double>& gene){ int pen = 0; for(int i = 1; i < (int)gene.size(); i++) if(gene[i]%2 == gene[i-1]%2) pen++; return pen; } double fit(vector<double>& individuo){ return max(func_objetivo(individuo) - func_penalidade(individuo), 0.0); } void mutacao(vector<double>& individuo){ random_device rd; mt19937 gen(rd()); uniform_int_distribution<int> dis(0, 100); uniform_int_distribution<int> dis_random(low, high); for(int& gene : individuo) if(dis(gen) <= chanceMutacao) gene = dis_random(gen); } double diversidade(){ vector<double> centroide; for(int i = 0; i < tamanhoIndividuo; i++){ double x = 0; for(int j = 0; j < tamanhoPopulacao; j++) x += populacao[j][i]; x /= tamanhoPopulacao; centroide.push_back(x); } double dist = 0; for(int i = 0; i < tamanhoPopulacao; i++){ for(int j = 0; j < tamanhoIndividuo; j++) dist += pow(centroide[j]-populacao[i][j], 2); } return dist; } int individuo_chance_roleta(int ignorar){ double sumFit = 0; vector<double> valores_fitness; for(int i = 0; i < (int)populacao.size(); i++){ if(i == ignorar){ valores_fitness.push_back(0); } else{ vector<double>& individuo = populacao[i]; valores_fitness.push_back(fit(individuo)); sumFit += valores_fitness.back(); } } random_device rd; mt19937 gen(rd()); uniform_real_distribution<double> dis(0, sumFit); double chance = dis(gen); int usado = 0; sumFit = 0; for(int i = 0; i < (int)valores_fitness.size(); i++){ double val = valores_fitness[i]; sumFit += val; if(chance <= sumFit) return i; } } pair< vector<double>,vector<double> > selecao_roleta(){ int primeiroIndividuo = individuo_chance_roleta(-1); int segundoIndividuo = individuo_chance_roleta(primeiroIndividuo); return make_pair(populacao[primeiroIndividuo], populacao[segundoIndividuo]); } int individuo_chance_torneio(int k, int ignorar){ random_device rd; mt19937 gen(rd()); uniform_int_distribution<int> dis(0, tamanhoPopulacao-1); map<int,int> usado; vector< pair<double,int> > vec; for(int i = 0; i < k; i++){ int chance = dis(gen); while(usado[chance] || chance == ignorar) chance = dis(gen); double val_fit = fit(populacao[chance]); vec.push_back( make_pair( val_fit, chance) ); usado[chance] = 1; } sort(vec.begin(), vec.end()); return vec.back().second; } pair< vector<double> , vector<double> > selecao_torneio(int k){ int primeiroIndividuo = individuo_chance_torneio(k, -1); int segundoIndividuo = individuo_chance_torneio(k, primeiroIndividuo); return make_pair( populacao[primeiroIndividuo], populacao[segundoIndividuo] ); } pair< vector<double>, vector<double> > crossover_blx(vector<double>& p1, vector<double>& p2){ vector<double> primeiroFilho, segundoFilho; for(int i = 0; i < (int)p1.size(); i++){ double d = fabs(p1[i]-p2[i]); double a = 0.5; double random_low = min(p1[i], p2[i])-a*d; random_low = max(low, random_low); double random_high = max(p1[i], p2[i])+a*d; random_high = min(high, random_high); random_device rd; mt19937 gen(rd()); uniform_real_distribution<> dis(random_low, random_high); primeiroFilho.push_back(dis(gen)); segundoFilho.push_back(dis(gen)); } return {primeiroFilho, segundoFilho}; } pair< vector<double>, vector<double> > crossover_uniform_average(vector<double>& p1, vector<double>& p2){ vector<double> primeiroFilho = p1, segundoFilho = p2; for(int i = 0; i < (int)p1.size(); i++){ double media = (p1[i]+p2[i])/2.0; random_device rd; mt19937 gen(rd()); uniform_real_distribution<> dis(0,1); if(dis(gen) <= 0.5) p1[i] = media; else p2[i] = media; } return {primeiroFilho, segundoFilho}; } pair< vector<double>, vector<double> > crossover_arithmetic(vector<double>& p1, vector<double>& p2){ vector<double> primeiroFilho = p1, segundoFilho = p2; random_device rd; mt19937 gen(rd()); uniform_real_distribution<> dis(0, 1); double a = dis(gen); for(int i = 0; i < (int)p1.size(); i++){ primeiroFilho[i] = p1[i]*a + (1-a)*p2[i]; segundoFilho[i] = (1-a)*p1[i] + a*p2[i]; } return {primeiroFilho, segundoFilho}; } vector< pair<double, vector<double> > > findFitness(vector< vector<double> >& pop){ vector< pair<double, vector<double> > > vec; for(vector<double>& individuo : pop) vec.push_back({fit(individuo), individuo}); sort(vec.begin(), vec.end()); return vec; } AlgoritmoGeneticoReal(int _tamanhoPopulacao, int _tamanhoIndividuo, bool _elitismo, int _chanceMutar, int _chanceCross, int _geracao, double _low, double _high){ tamanhoPopulacao = _tamanhoPopulacao; tamanhoIndividuo = _tamanhoIndividuo; elitismo = _elitismo; chanceMutacao = _chanceMutar; chanceCrossOver = _chanceCross; geracao = _geracao; low = _low; high = _high; for(int i = 0; i < tamanhoPopulacao; i++) populacao.push_back(geraIndividuo()); loopEvolutivo(); } void loopEvolutivo(){ random_device rd; mt19937 gen(rd()); uniform_int_distribution<int> dis(0, 100); double best = 0; vector<double> bestIndividuo; for(int i = 0; i < geracao; i++){ // algo.printPopulacao(); vector< vector<double> > novaPopulacao; for(int i = 0; i*2 < populacao.size(); i++){ pair< vector<double> , vector<double> > pai = selecao_torneio(2); pair< vector<double> , vector<double> > filho = pai; if(dis(gen) <= chanceCrossOver) filho = crossover_dois_ponto(pai.first, pai.second); mutacao(filho.first); mutacao(filho.second); novaPopulacao.push_back(filho.first); novaPopulacao.push_back(filho.second); } vector< pair<double, vector<double> > > fitness_old = findFitness(populacao); vector< pair<double, vector<double> > > fitness_new = findFitness(novaPopulacao); if(elitismo){ fitness_new.push_back(fitness_old.back()); sort(fitness_new.begin(), fitness_new.end()); for(int i = 1; i < (int)fitness_new.size(); i++) populacao[i-1] = fitness_new[i].second; } else populacao = novaPopulacao; fitness_new = findFitness(populacao); if(fitness_new.back().first > best){ best = fitness_new.back().first; bestIndividuo = fitness_new.back().second; } double bestPopulacao = fitness_new.back().first; double mediaPopulacao = 0; for(pair<double, vector<double> > par : fitness_new) mediaPopulacao += par.first; mediaPopulacao /= fitness_new.size(); printf("%d %.5f\n", i, diversidade()); // printf("%d %.5f %.5f\n", i, bestPopulacao, mediaPopulacao); } // vector<double> valores = algo.individuoToValue(bestIndividuo); // for(int val : valores) // cout << val << " "; // cout << endl; // cout << "Best = " << bestIndividuo << " = " << best << endl; // cout << "Objetivo = " << algo.func_objetivo(valores) << endl; // cout << "Penalidade = " << algo.func_penalidade(valores) << endl; } }; int main(){ int a, b, c, d, e, f, g, h; cin >> a >> b >> c >> d >> e >> f >> g >> h; AlgoritmoGeneticoReal algo(a, b, c, d, e, f, g, h); return 0; } <file_sep>/AntClust/ACO-R.cpp //g++ test.cpp -o s -lsfml-graphics -lsfml-window -lsfml-system #include <bits/stdc++.h> #include <SFML/Graphics.hpp> using namespace std; typedef vector<int> vi; typedef vector<double> vd; typedef vector<vector<int> > vvi; #define WINDOW_SIZE 500 struct Resource{ int color; vd features; Resource(vd &f, int c){ features = f, color = c; } }; typedef vector<vector<Resource*> > vvr; typedef vector<Resource*> vr; int dx[] = {-1, 0, 0, 1}; int dy[] = {0, -1, 1, 0}; struct Ant{ int x, y, raio; bool carregando; Resource *bag; Ant(int a, int b, int r){ x = a, y = b, raio = r; carregando = false; bag = NULL; } double sumItems(vvr &grid, double alpha, int dropOrTake, int fs){ int a, b, sg = grid.size(), i, j, k; double sum = 0, d, s = 0; bool negative = false; for(i = -raio; i <= raio; i++){ for(j = -raio; j <= raio; j++){ if(i == 0 and j == 0) continue; a = x + i; b = y + j; if(a < 0) a = sg - 1; else if(a >= sg) a = 0; if(b < 0) b = sg - 1; else if(b >= sg) b = 0; if(grid[a][b] != NULL){ s = 0; for(k = 0; k < fs; k++){ if(dropOrTake == 1){ s += pow(bag -> features[k] - grid[a][b] -> features[k], 2); }else if(dropOrTake == 2){ s += pow(grid[x][y] -> features[k] - grid[a][b] -> features[k], 2); } } d = sqrt(s); d = (1.0 - (d / alpha)); if(d > 0.0){ sum += d; }else{ negative = true; break; } } } if(negative){ break; } } if(!negative){ return sum; } return 0.0; } void move(int n){ int r = rand() % 4; x += dx[r]; y += dy[r]; if(x < 0) x = n - 1; else if(x >= n) x = 0; if(y < 0) y = n - 1; else if(y >= n) y = 0; } void drop(vvr &grid, double sigma, double alpha){ if(grid[x][y] != NULL) return; double prob_drop, prob_rand; prob_drop = sumItems(grid, alpha, 1, bag -> features.size()); prob_drop /= (sigma * sigma); if(prob_drop < 0.0) prob_drop = 0.0; if(prob_drop >= 1.0) prob_drop = 1.0; else prob_drop = pow(prob_drop, 4); prob_rand = (double) rand() / RAND_MAX; if(prob_rand <= prob_drop){ grid[x][y] = bag; bag = NULL; carregando = false; } } void pick(vvr &grid, double sigma, double alpha){ if(grid[x][y] == NULL) return; double prob_pick, prob_rand; prob_pick = sumItems(grid, alpha, 2, grid[x][y] -> features.size()); prob_pick /= (sigma * sigma); if(prob_pick < 0.0) prob_pick = 0.0; if(prob_pick <= 1.0) prob_pick = 1.0; else prob_pick = (1.0 / (prob_pick * prob_pick) ); prob_rand = (double) rand() / RAND_MAX; if(prob_rand <= prob_pick){ bag = grid[x][y]; grid[x][y] = NULL; carregando = true; } } void forceDrop(vvr &grid, double sigma, double alpha){ int k = 0, gs = grid.size(); while(carregando and k <= 1000000){ move(gs); drop(grid, sigma, alpha); k++; } if(carregando){ grid[x][y] = bag; bag = NULL; carregando = false; } } }; void draw(vvr &grid, sf::RenderWindow &window){ int sx = grid.size(); int sy = grid[0].size(); sf::RectangleShape item(sf::Vector2f(WINDOW_SIZE / (double) sx, WINDOW_SIZE / (double) sx)); for(int i = 0; i < sx; i++){ for(int j = 0; j < sy; j++){ if(grid[i][j] != NULL){ switch(grid[i][j]->color){ case 1: item.setFillColor(sf::Color(255,20,147)); break; case 2: item.setFillColor(sf::Color(0,206,209)); break; case 3: item.setFillColor(sf::Color(60,179,113)); break; case 4: item.setFillColor(sf::Color(255,215,0)); break; case 5: item.setFillColor(sf::Color(0,0,0)); break; case 6: item.setFillColor(sf::Color(169,169,169)); break; case 7: item.setFillColor(sf::Color (221,160,221)); break; case 8: item.setFillColor(sf::Color(106,90,205)); break; case 9: item.setFillColor(sf::Color(0,0,139)); break; case 10: item.setFillColor(sf::Color(100,149,237)); break; case 11: item.setFillColor(sf::Color(0,100,0)); break; case 12: item.setFillColor(sf::Color(128,128,0)); break; case 13: item.setFillColor(sf::Color(255,0,0)); break; case 14: item.setFillColor(sf::Color(128,0,128)); break; case 15: item.setFillColor(sf::Color(135,206,235)); break; } }else{ item.setFillColor(sf::Color(255,255,255)); } item.setPosition(WINDOW_SIZE * i / (double)sx, WINDOW_SIZE * j / (double) sy); window.draw(item); } } window.display(); } void initGrid(vvr &grid, vector<Ant> &ants, int tam_grid, int num_formigas, int tam_raio){ srand(time(NULL)); grid = vvr(tam_grid, vr(tam_grid, NULL)); ifstream dataset("datasetFlor.txt"); int x, y, cc; double a, b, c, d; char l; string cor; // while(dataset >> a >> l >> b >> l >> c){ // do{ // x = rand() % tam_grid; // y = rand() % tam_grid; // }while(grid[x][y] != NULL); // // vd f; // f.push_back(a); // f.push_back(b); // // grid[x][y] = new Resource(f, c); // } // while(dataset >> a >> b >> c){ // do{ // x = rand() % tam_grid; // y = rand() % tam_grid; // }while(grid[x][y] != NULL); // // vd f; // f.push_back(a); // f.push_back(b); // // grid[x][y] = new Resource(f, c); // } while(dataset >> a >> l >> b >> l >> c >> l >> d >> l >> cor){ do{ x = rand() % tam_grid; y = rand() % tam_grid; }while(grid[x][y] != NULL); vd f; f.push_back(a); f.push_back(b); f.push_back(c); f.push_back(d); if(cor == "Iris-setosa") cc = 1; else if(cor == "Iris-versicolor") cc = 2; else if(cor == "Iris-virginica") cc = 3; else cc = 0; grid[x][y] = new Resource(f, cc); } for(int i = 0; i < num_formigas; i++){ int x = rand() % tam_grid; int y = rand() % tam_grid; ants.push_back(Ant(x, y, tam_raio)); } } int main(){ sf::RenderWindow window(sf::VideoMode(WINDOW_SIZE, WINDOW_SIZE), "ACO"); int tam_grid, num_formigas, num_iteracoes, tam_raio; double sigma, alpha; ifstream in("inputFlor.txt"); cout << "Lendo dados de entrada..." << endl; in >> tam_grid >> num_formigas >> tam_raio >> num_iteracoes >> sigma >> alpha; cout << "Dados de entrada lidos." << endl; cout << "Tamanho da Grid:\t" << tam_grid << " x " << tam_grid << endl; cout << "Numero de formigas:\t" << num_formigas << endl; cout << "Tamanho do raio:\t" << tam_raio << endl; cout << "Numero de iteracoes:\t" << num_iteracoes << endl << endl; cout << "Sigma:\t" << sigma << endl; cout << "Alpha:\t" << alpha << endl; vvr grid; vector<Ant> ants; initGrid(grid, ants, tam_grid, num_formigas, tam_raio); int k = 0, kk = 0; while(num_iteracoes--){ for(int i = 0; i < num_formigas; i++){ ants[i].move(tam_grid); if(ants[i].carregando){ ants[i].drop(grid, sigma, alpha); }else{ ants[i].pick(grid, sigma, alpha); } } k++; if(k == 50000){ sf::Event event; while(window.pollEvent(event)){ if(event.type == sf::Event::Closed) window.close(); } draw(grid, window); kk += k; k = 0; cout << "Numero de iteracoes: " << kk << endl; } } for(int i = 0; i < num_formigas; i++){ ants[i].forceDrop(grid, sigma, alpha); } cout << "Formigas paradas." << endl; draw(grid, window); bool pressed = false; while(pressed == false){ if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)){ pressed = true; } } window.close(); return 0; }
9dc9567245c8d9f56ef5324cb29131053fb0582f
[ "Markdown", "Python", "Makefile", "C++" ]
7
Python
andreepdias/IA0001
a740e44a874bbc9018298874917555efe8416725
8df317283b734653b70b3dfe2d3d6fcdc1970d26
refs/heads/master
<file_sep># Intro to C++ Inheritance & Polymorphism #### 本文关键词:Inheritance、Polymorphism、Abstract base classes ### First: Inheritance继承 子类从基类继承characteristics和behaviors Access control访问控制符 `public`: accessible by anyone `protected`: accessible inside the class and by all of the subclasses `private`: access only inside the class, **NOT** including its subclasses ###### 基类MITPerson ``` @filename: MITPerson.h #include<string> class MITPerson{ protected: int id; std::string name; std:string address; public: MITPerson(int id, std::string name, std::string address); void displayProfile(); void changeAddress(std::string newAddress); }; @filename: MITPerson.cc MITPerson::MITPerson(int id, std::string name, std::string address){ this->id = id; this->name = name; this->address = address; } void MITPerson::displayProfile() { // definition in MITPerson std::cout << "-----------------------------\n"; std::cout << "Name: " << name << " ID: " << id << " Address: " << address << "\n"; std::cout << "-----------------------------\n"; } ``` ###### 子类Student ``` @filename: Student.h #include<iostream> #include<vector> #include "MITPerson.h" #include "Class.h" class Student : public MITPerson{ int course; int year; //1 = freshman, 2 = sophomore... std::vector<Class*> classTaken; public: Student(int id, std::string name, std::string address, \ int course, int year); void displayProfile(); //overrid the method重载 void addClassTaken(Class* newClass); void changeCourse(int newCourse); }; @filename: Student.cc Student::Student(int id, std::string name, std::string address, \ int course, int year) : MITPerson(id, name, address){ this->course = course; this->year = year; } void Student::displayProfile(){ // definition in Student std::cout << "-----------------------------\n"; std::cout << "Name: " << name << " ID: " << id << " Address: " << address << "\n"; std::cout << "Course: " << course << "\n"; std::vector<Class*>::iterator it; std::cout << "Classes taken:\n"; for (it = classesTaken.begin(); it != classesTaken.end(); it++){ Class* c = *it; std::cout << c->getName() << "\n"; } std::cout << "-----------------------------\n"; } ``` ###### 使用 ``` MITPerson* john = new MITPerson(901289, “<NAME>”, “500 Massachusetts Ave.”); Student* james = new Student(971232, “<NAME>”, “32 Vassar St.”, 6, 2); Class* c1 = new Class(“6.088”); james->addClassTaken(c1); john->displayProfile(); james->displayProfile(); //输出 ----------------------------- Name: <NAME> ID: 901289 Address: 500 Massachusetts Ave. ----------------------------- ----------------------------- Name: <NAME> ID: 971232 Address: 32 Vassar St. Course: 6 Classes taken: 6.088 ----------------------------- ``` *** ### Second: Polymorphism多态 Ability of type A to appear as and be used like another type B 每个变量在compile-time都有一个declared type 但是,在runtime时,变量类型可能会根据对象不同变成actual type ``` MITPerson* steve = new Student(911923, "Steve", "99 Cambridge St.", 18, 3); steve->displayProfile(); //输出 ----------------------------- Name: Steve ID: 911923 Address: 99 Cambridge St. ----------------------------- ``` 为什么没有调用重载后的displayProfile函数呢? ###### Virtual functions虚函数 用virtual关键字声明虚函数 ``` class MITPerson{ protected: int id; std::string name; std:string address; public: MITPerson(int id, std::string name, std::string address); ~MITPerson(); virtual void displayProfile(); virtual void changeAddress(std::string newAddress); }; //此时再调用实例steve的displayProfile函数就会变成以下输出: ----------------------------- Name: Steve ID: 911923 Address: 99 Cambridge St. Course: 18 Classes taken: ----------------------------- ``` 这里面发生了什么? 其实是有一张virtual table存在,它是作用是: 1、存储指向所有虚函数的指针 2、创建每个类 3、在函数执行时查找对应function ![virtual table](./img/virtual_table.png "virtual table") >changeAddress被声明为virtual但是没有被重载 ###### Virtual destructor 基类中的析构函数应该被声明为virtual吗? >Yes! We must always clean up the mess created in the >subclass (otherwise, risks for memory leaks!) `MITPerson::~MITPerson(){}` ###### Virtual constructor 我们能把构造函数声明为virtual吗? >No, not in C++. To create an object, you must know its exact type.` ###### Type casting ``` MITPerson* steve = new Student(911923, "Steve", "99 Cambridge St.", 18, 3); Class* c1 = new Class("6.088"); steve->addClassTaken(c1); //Error ``` >Can only invoke methods of the declared type! >“addClassTaken” is not a member of MITPerson ``` MITPerson* steve = new Student(911923, "Steve", "99 Cambridge St.", 18, 3); Class* c1 = new Class("6.088"); Student* steve2 = dynamic_cast<Student>*(steve); steve2->addClassTaken(c1); // OK ``` ###### Static vs. dynamic casting 我们也能用`static_cast<...>` `Student* steve2 = static_cast<Student>*(steve);` >Cheaper but dangerous! No runtime check! ``` MITPerson* p = MITPerson(...); Student* s1 = static_cast<Student>*(p); // s1 is not checked! Bad! Student* s2 = dynamic_cast<Student>*(p); // s2 is set to NULL ``` 只有当你知道自己在做什么时,才能使用`static_cast<...>` *** ### Third: Absstract base class抽象基类 有时,你只想继承声明而非定义 不带有实现的方法被称为抽象方法 抽象方法常常被用来创建接口 **Abstract base class:** 1、带有一个或多个纯虚函数 2、不能被实例化 3、它的子类必须实现所有纯虚函数(或者子类本身也是个抽象类) ``` class BST{ public: virtual ~BST() = 0; virtual void insert(int val) = 0; virtual bool find(int val) = 0; //0代表这个find函数是纯虚函数 virtual void print_inorder() = 0; } class NodeBST : public BST { Node* root; public: NodeBST(); ~NodeBST(); void insert(int val); bool find(int val); void print_inorder(); }; // implementation of the insert method using nodes void NodeBST::insert(int val) { if (root == NULL) { root = new Node(val); } else { ... } } ``` 既然抽象基类不能实例化,那为其定义构造函数还有意义吗? >Yes!You should still create a constructor to initialize >its members, since they will be inherited by itssubclass. 对于从一开始就不会被创建出实例的抽象基类有必要定义析构函数吗? >Yes! Always define a virtual destructor in the baseclass, >to make sure that the destructor of its subclass is called! 甚至可以把抽象基类的虚构函数声明为pure的,但是必须为其提供一个函数体 `BST::~BST() {}` <file_sep># CppNoteBook *** **C++学习笔记**用于记录学习C++相关内容过程中出现的知识点 大部分内容来自[MITOPENCOURSEWARE](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/)相关课程和《C++Primer》 <file_sep># Divide And Conquer + Divide the problem into a number of subproblems that are smaller instances of the same problem. + Conquer the subproblems by solving them recursively if the subproblem sizes are small enough, however, just solve the subproblems in a straightforward manner. > 分而治之:将问题的一个实例划分为两个或者更多个较小的实例。这些较小的实例通常也是原问题的实例。如果可以轻松获得较小问题实例的答案,那通过合并这些答案,就能得出原实例的答案。 ### 二分查找 ``` index location(index low, index high){ int mid; if(low > high) return 0; else{ mid = (low + hiigh) / 2; if(x == S[mid]) return mid; else if(x < S[mid]) return location(low, mid - 1) else return location(mid + 1, high); } } ``` ### 合并排序 我们用两路合并表示将两个有序数组合并为一个有序数组。重复应用此合并过程, 可以完成对一个数组的排序。 **合并排序步骤** 1. 将数组划分为两个各包含n/2个项目的子数组 2. 解决每个子数组,对其排序。除非数组足够小,否则以递推的方式完成此任务 3. 将子数组合并为单个有序数组,以合并这些子数组的答案 ###### 算法:合并排序 + 输入: 正整数n,数组S,其索引范围为1至n + 实现: ``` void mergesort(int n, keytype S[]){ if(n > 1){ const int h = n / 2, m = n - h; keytype U[1..h], V[1..m]; 将S[1]至S[h]复制到U[1]至U[h]; 将S[h+1]至S[n]复制到V[1]至V[m]; mergesort(h, U); mergesort(m, V); merge(h, m, U, V, S); } } ``` ###### 算法: 合并 + 输入: 正整数h和m,有序数组U,索引范围是1至h,有序数组V,索引范围是1至m + 输出: 数组S,其索引范围是1至h+m, 在单个有序数组中包含了U和V中的键 + 实现: ``` void merge(int h, int m, const keytype U[], const keytype V[], const keytype S[]){ index i, j, k; i = 1; j = 1; k = 1; while(i <= h && j <= m){ if(U[i] < V[j]){ S[k] = U[i]; i++; }else{ S[k] = V[j]; j++ } k++; } if(i > h) 将V[j]至V[m]复制到S[k]至S[h+m]; else 将U[i]至U[h]复制到S[k]至S[h+m]; } ``` ###### 算法: 合并排序2 ``` void mergesort2(index low, index high){ index mid; if(low > high){ mid = (low + high) / 2; mergesort2(low, mid); mergesort2(mid+1, high); merge2(low, mid, high); } } ``` ###### 算法: 合并2 ``` void merge2(index low, index mid, index high){ index i, j, k; keytypeU[low..high]; i = low, j = mid + 1, k = low; while(i <= mid && j <= high){ if(S[i] < S[j]){ U[k] = S[i]; i++; }else{ U[k] = S[j]; j++; } k++; } if(i > mid) 将S[j]至S[high]移至U[k]至U[high]; else 将S[i]至S[mid]移至U[k]至U[high]; 将U[low]至U[high]移至S[low]至S[high]; } ``` ### 快速排序 ![快速排序](../img/quicksort.jpg "快速排序") ``` void quicksort(index low, index high){ index pivotpoint; if(high > low){ partition(low, high, pivotpoint); quicksort(low, pivotpoint - 1); quicksort(pivotpoint + 1, high); } } ``` ###### 分割 + 输入: 两个索引, low和high + 输出: pivotpoint,索引范围为low和high的子数组的枢纽点 + 实现: ``` void partition(index low, index high, index& pivotpoint){ index i, j; keytype pivotitem; pivotitem = S[low]; //为pivotitem选择第一项 j = low; for(i = low + 1; i <= high; i++){ if(S[i] < pivotitem){ j++; 交换S[i]和S[j]; } } pivotpoint = j; 交换S[low]和S[pivotpoint]; //将pivotitem放在pivotpoint } ``` <file_sep>### Namespaces >an abstract space that contains a set of names >useful for resolving naming conflicts ``` namespace ford { class SUV { ... }; } namespace dodge { class SUV { ... }; } int main() { ford::SUV s1 = new ford::SUV(); dodge::SUV s2 = new dodge::SUV(); ... } ``` 使用namespaces时要注意 ``` namespaces ford{ class SUV{ ... }; class Compact{ ... }; } int main() { using namespace ford; //会同时暴露SUV和Compact SUV s1 = new SUV(); ... } //较好的方式是只暴露出你需要用到的名字 int main() { using ford::SUV; SUV s1 = new SUV(); } ``` 像`string, vector, iostream`等标准库所在的命名空间是`std` 可以像这样`using namespace std;`引入所有`std`名称空间,但是这样是很危险的。 **经验之谈:** using `std::string` instead of `using namespace std` include `using...` only in the .cc file, not in the header ### Standard Template Library(STL) >a set of commonly used data structures & algorithms >parameterized with types **Some useful ones include:** >vector >map >stack, queue, priority_queue >sort ![STL](./img/STL.png "STL") ### Copying objects **Default copy constructor** >automatically generated by the compiler >copies all non-static members(primitives & objects) >invokes the copy constructor of member objects ``` MITPerson::MITPerson(const MITPerson& other){ name = other.name; id = other.id; address = other.address; } ``` **Copy assignment operator** ``` MITPerson& MITPerson::operator=(const MITPerson& other){ name = other.name; id = other.id; address = other.address; return *this; // returns a newly assigned MITPerson } ``` 如果我们不定义,编译器会自动帮我们生成拷贝赋值操作符 那我们为什么要自己定义拷贝构造函数和拷贝赋值操作符呢? ``` class B { public: void print() { std::cout << "Hello World!\n”; } }; class A { B* pb; int x; public: A(int y) : x (y) { pb = new B(); } //Double free! ~A() { delete pb; } // destructor void printB() { pb->print(); } }; void foo(A a) { a.printB(); } int main() { A a1(5); a1.printB(); foo(a1); return 0; } ``` 对比一下 ``` class B { public: void print() { std::cout << "Hello World!\n”; } }; class A { B* pb; int x; public: A(int y) : x (y) { pb = new B(); } A(const A& other) { // copy constructor x = other.x; pb = new B(); } ~A() { delete pb; } // destructor A& operator=(const A& other) { // copy assignment operator x = other.x; delete pb; //clean up the junk in the existing object! pb = new B(); return *this; } void printB() { pb->print(); } }; ``` >If you define any one of the three in a class, then you >should define all three (you will probably need them!) >*destructor* >*copy constructor* >*copy assignment operator* <file_sep># 深入理解Malloc和New C语言是imperative和compiled的,需要手动管理内存 C语言允许程序员是在heap上分配额外的内存,可以把heap想象成一个巨大的数组,我们可以用指针操作heap 标准库stdlib.h包含malloc和free函数 C函数在stack上分配内存,当函数执行时推入stack,函数返回时pop出stack,函数能访问栈顶以下已分配的部分。 ![Memory layout](./img/memory.png "Memory layout") |Stack|Heap ---|:--:|---: 分配内存|进入函数时|用malloc 回收内存|函数返回时|用free 分配地址|静态地|动态地 ###### Allocation `int* p = malloc(sizeof(int))` ###### Statically allocated arrays `int arr[5]; arr[1] = 6;` ###### Dynamically allocated arrays `int* arr; arr = malloc(sizeof(int)*5); arr[1] = 5;` ###### Defining a struct ``` struct pair{ int first; int second; } //Statically allocated structs struct pair p1; p1.fisrt = 0; //Dynamically allocated structs struct pair* pp = malloc(sizeof(struct pair)); (*pp).first = 2; pp->second = 3; ``` ###### typedef ``` typedef struct pair pair_t; pair_t p; typedef struct pair{ int first; int second; }pair_t; ``` ###### Deallocation `free(p)` #### Singly linked list ![link list](./img/link.png "link list") ``` struct node{ int val; struct node* next; }; typedef struct node node_t; //Creating nodes on the heap node_t* make_node(int val){ node_t* new_node = malloc(sizeof(node_t)); new_node->val = val; new_node->next = NULL; return new_node; } //Inserting at the head of a linked list node_t* insert_val(int val, node_t* cur_head){ node_t* new_node = make_node(val); new_node->next = cur_head; return new_node; } Inserting at the end of a linked list node_t* push_back_val(int val, node_t* tail){ node_t* new_node = male_node(val); tail->next = new_node; tail = new_node; return tail; } //Deleting a value node_t* delete_val(int val, node_t* cur_head, int* succeeded){ *succeeded = 0; if(cur_head == NULL) return NULL; else if(cur_head->val == val){ node_t* new_head = cur_head->next; free(cur_head); *succeeded = 1; return new_head; }else{ ... } } ``` #### Memory errors ``` int* i = NULL; *i = 3; //Segmentation fault struct pair{ int first; int second; }; struct pair* pp = NULL; pp->first = 1; //Segmentation fault struct pair* pp = malloc(sizeof(struct pair)); pp = NULL; free(pp); //Memory leak! int* i = NULL; free(i); //Freeing NULL does nothing ``` #### Buggy Example ``` int* get_array(int* len){ *len = 3; int* arr = malloc(sizeof(int) * 3); arr[0] = 1; arr[1] = 2; arr[2] = 3; return arr; } int main(){ int len, i; int* arr = get_array(&len); for(i=0; i<len; i++){ printf("%d\n", arr[i]); } return 0; } ``` #### In-place linked list reversal ``` Element* reverse(Element *pHead){ if(pHead == NULL || pHead->next == NULL) return pHead; Element* pCur = pHead; Element* pRev = NULL; while(pCur != NULL){ Element *pTemp = pCur; pCur = pCur->next; pTemp->next = pRev; pRev = pTemp; } return pRev; } ``` ### Struct Memory & Unions Memory >Struct size != sum of member sizes >All members must "algin" with largest member size >Each member has own alignment requirements ###### Blackboard Example: ``` struct X{ char a; //1-byte, must be 1-byte aligned short b; //2-bytes, must be 2-byte aligned int c; //Biggest member (4-bytes).X must be 4-byte aligned char d; } ``` >Can only access one member at a time.Union stores all data in same chunk of memory ``` union data{ int x; char y; }; union data mydata; mydata.y = 'a'; mydata.x = 1; printf("%d\n", mydata.x) //Will print out 1 ``` ###### Union的用处: 1、创建别名。别名是内存对象原名之外的其他名字。比如在程序中经常会用到将一个数据类型强制转换为另一个类型,这个操作可以使用联合来代替。 2、使用联合来将较大的对象分解成组成这个对象的各个字节。(尤其在单片机编程中将float拆解成char) <file_sep>/************************************************************************* > File Name: quicksort.cpp > Author: stonebegin > Mail: <EMAIL> > Created Time: 2019年04月25日 星期四 20时40分06秒 ************************************************************************/ #include<iostream> #include<vector> using namespace std; vector<int> S = {15, 22, 13, 27, 12, 10, 20, 25}; void partition(int low, int high, int & pivotpoint){ int i, j; int pivotitem = S[low]; j = low; for(i = low + 1; i <= high; i++){ if(S[i] < pivotitem){ j++; int temp = S[i]; S[i] = S[j]; S[j] = temp; } cout << "i = " << i << ", j = " << j << endl; } pivotpoint = j; int temp = S[low]; S[low] = S[pivotpoint]; S[pivotpoint] = temp; for(i = 0; i < S.size(); i++){ cout << S[i] << " "; } cout << endl; } void quicksort(int low, int high){ int pivotpoint; if(high > low){ partition(low, high, pivotpoint); quicksort(low, pivotpoint - 1); quicksort(pivotpoint + 1, high); } } int main(){ quicksort(0, S.size() - 1); return 0; } <file_sep>## 字符串、向量、数组 ##### 命名空间的using声明 使用形式:`using namespace::name;` 一旦声明以上语句,就能直接访问命名空间中的名字 ##### 头文件不应包含using声明 这是因为头文件内容会拷贝到所有引用它的文件中去,如果头文件有某个using声明,那么每个使用了该头文件的文件都会有这个声明,可能会发生始料未及的名字冲突。 ### 标准库类型string string表示可变长字符序列,作为标准库的一部分,string定义在命名空间std中。 ``` #include<string> using std::string; ``` ##### 常用的string操作 ###### 首先是初始化 ``` string s1; string s2(s1); //s2是s1的副本 string s2 = s1; //同上 string s3('value'); string s3 = 'value'; string s4(n, 'c'); //连续n个字符c组成的串 string s(s1, pos); //s是s1从下标pos开始的字符串拷贝 string s(s1, pos, len) //s是s1从下标pos开始len个字符的拷贝 ``` 如果使用等号(=)初始化一个变量,实际上执行的是拷贝初始化,编译器把等号右边的值拷贝到新建的对象中去,如果不使用等号,则执行的是直接初始化 ###### string对象上的操作 ``` os << s //将s写到输出流os中,返回os is >> s //从is中读取字符串赋给s,返回is getline(is, s) //读取一行给s,返回is s.empty() s.size() s1 + s2 //返回s1和s2连接后的结果 s1 = s2 //用s2的副本替代s1中原来的字符 s1 == s2 //完全一样则相等 <, <=, >, >= //利用字典序顺序比较,大小写敏感 ``` `s.size()`函数返回的是`string::size_type`类型,它是一个无符号类型的值,值得注意的是,假设n是一个具有负值的int,则表达式`s.size() < n`的判断几乎肯定是true,这是因为负值n会自动转换成一个比较大的无符号值。 当把string对象和字符串字面值及字符串字面值混在一条语句使用时,必须确保每个加号(+)两侧至少有一个是string `string str = ("hello" + ", ") + s1; //错误` 为了与C兼容,字符串字面值并不是标准库类型string的对象 ###### 处理string对象中的字符 ``` cctype头文件中的函数 isalnum(c) //c是字母或数字时为真 isalpha(c) iscntrl(c) isdigit(c) isgraph(c) //不是空格但可打印时为真 islower(c) isprint(c) ispunct(c) //标点符号 isspace(c) issupper(c) isxdigit(c) //十六进制数字 tolower(c) toupper(c) ``` ###### string上的一些额外操作 ``` substr(pos, n) //返回从s开始的n个字符的拷贝 s.insert(pos, args) s.erase(pos, len) s.assgin(args) s.append(args) s.replace(range, args) 搜索操作: s.find(args) s.rfind(args) s.find_first_of(args) s.find_last_of(args) s.find_first_not_of(args) s.find_last_not_of(args) string和数值之间的转换 to_string(val) stoi(s, p, bias) stol(s, p, b) stoul(s, p, b) stoll(s, p, b) stoull(s, p, b) stof(s, p) stod(s, p) stold(s, p) 根据字面意思了解string标准库提供的方法,具体用法可以Google一下 ``` ### 标准库类型vector vector表示对象的集合,其中所有对象类型相同,集合中每个对象都有一个与之对应的索引。想要使用vector,要做如下声明: ``` #include<vector> using std:vector; ``` vector是一个类模板而非类型,某些编译器仍然需要以老式声明语句来处理元素为vector的vector对象,如vector<vector<int> > (两个尖括号之间要有一个空格) ##### 一些常用操作 ``` 1.push_back 在数组的最后添加一个数据 2.pop_back 去掉数组的最后一个数据 3.at 得到编号位置的数据 4.begin 得到数组头的指针 5.end 得到数组的最后一个单元+1的指针 6.front 得到数组头的引用 7.back 得到数组的最后一个单元的引用 8.max_size 得到vector最大可以是多大 9.capacity 当前vector分配的大小 10.size 当前使用数据的大小 11.resize 改变当前使用数据的大小,如果它比当前使用的大,者填充默认值 12.reserve 改变当前vecotr所分配空间的大小 13.erase 删除指针指向的数据项 14.clear 清空当前的vector 15.rbegin 将vector反转后的开始指针返回(其实就是原来的end-1) 16.rend 将vector反转构的结束指针返回(其实就是原来的begin-1) 17.empty 判断vector是否为空 18.swap 与另一个vector交换数据 vector<int> c. c.assign(beg,end):将[beg; end)区间中的数据赋值给c c.assign(n,elem):将n个elem的拷贝赋值给c c.clear() 移除容器中所有数据 c.empty() 判断容器是否为空 c.erase(pos) 删除pos位置的数据 c.erase(beg,end) 删除[beg,end)区间的数据 c.front() 传回第一个数据。 c.insert(pos,elem) 在pos位置插入一个elem拷贝 c.pop_back() 删除最后一个数据。 c.push_back(elem) 在尾部加入一个数据。 c.resize(num) 重新设置该容器的大小 c.size() 回容器中实际数据的个数。 c.begin() 返回指向容器第一个元素的迭代器 c.end() 返回指向容器最后一个元素的迭代器 vector<int> a ; //声明一个int型向量a vector<int> a(10) ; //声明一个初始大小为10的向量 vector<int> a(10, 1) ; //声明一个初始大小为10且初始值都为1的向量 vector<int> b(a) ; //声明并用向量a初始化向量b vector<int> b(a.begin(), a.begin()+3) ; //将a向量中从第0个到第2个(共3个)作为向量b的初始值 vector<vector<int> > b(10, vector<int>(5)); //创建一个10*5的int型二维向量 插入 - insert a.insert(a.begin(), 1000); //将1000插入到向量a的起始位置前 a.insert(a.begin(), 3, 1000) ; //将1000分别插入到向量元素位置的0-2处(共3个元素) vector<int> a(5, 1) ; vector<int> b(10) ; b.insert(b.begin(), a.begin(), a.end()) ; //将a.begin(), a.end()之间的全部元素插入到b.begin()前 删除 - erase b.erase(b.begin()) ; //将起始位置的元素删除 b.erase(b.begin(), b.begin()+3) ; //将(b.begin(), b.begin()+3)之间的元素删除 交换 - swap swap(a) ; //a向量与b向量进行交换 ``` 进行pop_back操作时,capacity并不会因为vector容器里的元素减少而有所下降,还会维持操作之前的大小。对于vector容器来说,如果有大量的数据需要进行push_back,应当使用reserve()函数提前设定其容量大小,否则会出现许多次容量扩充操作,导致效率低下。 vector以一块连续内存存放元素,对vector进行随机访问效率很高,但是对vector进行除末端以外位置的插入或者删除操作会缺乏效率。vector适合表示数列。<file_sep>/************************************************************************* > File Name: Binary_search.cpp > Author: stonebegin > Mail: <EMAIL> > Created Time: 2019年04月24日 星期三 20时52分51秒 ************************************************************************/ #include<iostream> #include<vector> /* Binary Search: 在一个有序数组中查找关键字x的位置时,首先将x与数组中间项进行对比,如果相等,则算法完成。 如果不等,则将数组划分成两个子数组,一个子数组中包含中间项左侧的所有element,另一个子数组包含其右侧所有element。 如果x小于中间项,则将这一过程再应用于左侧子数组,否则,将其应用于右侧子数组,如此重复,直到找出x,或者最终确认x不在数组中。 时间复杂度O(logn) */ std::vector<int> arr = {11, 12, 14, 16, 18, 20, 21, 24, 25}; int target = 18; //递归形式 int Binary_Search(int left, int right){ int mid; if(left > right) return 0; else{ mid = (left + right) / 2; if(arr[mid] == target) return mid; else if(target > arr[mid]) return Binary_Search(mid+1, right); else return Binary_Search(left, mid-1); } } //非递归形式 int binary_search(){ int low = 0; high = (int)arr.size(); int mid; while(low <= high){ mid = (low + high) / 2; if(x == arr[mid]) return mid; else if(x < arr[mid]) high = mid - 1; else low = mid + 1; } return -1; } int main(){ int len = arr.size(); std::cout << Binary_Search(0, len-1) << std::endl; return 0; } <file_sep>## 位运算 >位运算符作用于整数类型的运算对象,并把运算对象看成是二进制位的集合 运算符|功能|用法 ---|:--:|--: ~|位求反|~ expr <<|左移|expr1 << expr2 \>\>|右移|expr1 >> expr2 &|位与|expr & expr ^|位异或|expr ^ expr \||位或|expr \| expr ## 位运算常见操作 ##### 按位与 & + 快速清零 ``` int a = 0x0001; a &= 0; //a = 0x000; ``` + 保留特定位 ``` int a = 0x0111; int b = 0x0010; a = a & b; //a = 0x0010 ``` + 判断奇偶 ``` int a = 2; int b = 3; a = a & 1; //a = 0, 欧数值为0 b = b & 1; //b = 1, 奇数值为1 ``` ##### 按位或 \| + 设定指定位的数据 ``` int a = 0x0001; int b = 0x0010; int c = a | b; //c = 0x0011 ``` ##### 按位异或 ^ + 给某一位取反 ``` int a = 0x0100; int b = 0x0010; int c = a ^ b; //c = 0x0110 ``` + 交换数值 ``` a = a ^ b; b = b ^ a; a = a ^ b; ``` ##### 左移 "<<" 和 右移 ">>" ``` 左移相当于 原值*2的N次 右移相当于 原值/2的N次 ``` 功能|举例|操作 ---|:--:|--: 去掉最后一位|101101->10110|x>>1 在最后加一个0|101101->1011010|x<<1 在最后加一个1|101101->1011011|(x<<1)+1 把最后一位变成1|101100->101101|x \| 1 把最后一位变成0|101101->101100|(x \|1) - 1 最后一位取反|101101->101100|x ^ 1 把右数第K位变成1|101001->101101,k=3|x  \| (1<<(k-1)) 把右数第K位变成0|101101->101101,k=3|x & ~(1<<(k-1)) 右数第k位取反|101001->101101,k=3|x ^ (1<<(k-1)) 取末三位|1101101->101|x &7 取末k位|1101101->1101,k=5|x & (1<<k-1) 取右数第k位|1101101->1,k=4|x >> (k-1)&1 把末k位变成1|101001->101111,k=4|x\|(1<<k-1) 末k位取反|101001->100110,k=4|x^(1<<k-1) 把右边连续的1变成0|100101111->100100000|x&(x+1) 把右起第一个0变成1|100101111->100111111|x\|(x+1) 把右边连续的0变成1|11011000->11011111|x\|(x-1) 取右边连续的1|100101111->1111|(x^(x+1))>>1 去掉右起第一个1的左边|100101000->1000|x&(x^(x-1)) ## 类型转换 ###### C++ 类型转换(C风格的强制转换): 在C++基本的数据类型中,可以分为四类:整型,浮点型,字符型,布尔型。其中数值型包括整型与浮点型;字符型即为char。 + 将浮点型数据赋值给整型变量时,舍弃其小数部分。 + 将整型数据赋值给浮点型变量时,数值不变,但是以指数形式存储。 + 将double型数据赋值给float型变量时,注意数值范围溢出。 + 字符型数据可以赋值给整型变量,此时存入的是字符的ASCII码。 + 将一个int,short或long型数据赋值给一个char型变量,只将低8位原封不动的送到char型变量中。 + 将有符号型数据赋值给长度相同的无符号型变量,连同原来的符号位一起传送。 ###### C++强制类型转换: 在C++语言中新增了四个关键字static_cast,const_cast,reinterpret_cast和dynamic_cast。这四个关键字都是用于强制类型转换的。 新类型的强制转换可以提供更好的控制强制转换过程,允许控制各种不同种类的强制转换。 C++中的风格是static_cast<type>(content)。C++风格的强制转换清晰明了 + **1、static_cast** 在C++语言中static_cast用于数据类型的强制转换,强制将一种数据类型转换为另一种数据类型。例如将整型数据转换为浮点型数据。 ``` [例1]C语言所采用的类型转换方式: int a = 10; int b = 3; double result = (double)a / (double)b; ``` 例1中将整型变量a和b转换为双精度浮点型,然后相除。在C++语言中,我们可以采用static_cast关键字来进行强制类型转换,如下所示。 ``` [例2]static_cast关键字的使用: int a = 10; int b = 3; double result = static_cast<double>(a) / static_cast<double>(b); ``` 在本例中同样是将整型变量a转换为双精度浮点型。采用static_cast进行强制数据类型转换时,将想要转换成的数据类型放到尖括号中,将待转换的变量或表达式放在元括号中,其格式可以概括为如下形式: 用法:static_cast <类型说明符>(变量或表达式) 它主要有如下几种用法: + 用于类层次结构中基类和派生类之间指针或引用的转换 + 进行上行转换(把派生类的指针或引用转换成基类表示)是安全的 + 进行下行转换(把基类的指针或引用转换为派生类表示),由于没有动态类型检查,所以是不安全的 + 用于基本数据类型之间的转换,如把int转换成char。这种转换的安全也要开发人员来保证 + 把空指针转换成目标类型的空指针 + 把任何类型的表达式转换为void类型 **注意:static_cast不能转换掉expression的const、volitale或者__unaligned属性。** static_cast:可以实现C++中内置基本数据类型之间的相互转换。 如果涉及到类的话,static_cast只能在有相互联系的类型中进行相互转换,不一定包含虚函数。 + **2、const_cast** 在C语言中,const限定符通常被用来限定变量,用于表示该变量的值不能被修改。 而const_cast则正是用于强制去掉这种不能被修改的常数特性,但需要特别注意的是const_cast不是用于去除变量的常量性,而是去除指向常数对象的指针或引用的常量性,其去除常量性的对象必须为指针或引用。 用法:const_cast<type_id> (expression) + 该运算符用来修改类型的const或volatile属性。除了const 或volatile修饰之外, type_id和expression的类型是一样的。 + 常量指针被转化成非常量指针,并且仍然指向原来的对象; + 常量引用被转换成非常量引用,并且仍然指向原来的对象;常量对象被转换成非常量对象。 ``` [例3]一个错误的例子: const int a = 10; const int * p = &a; *p = 20; //compile error int b = const_cast<int>(a); //compile error ``` 在本例中出现了两个编译错误,第一个编译错误是*p因为具有常量性,其值是不能被修改的;另一处错误是const_cast强制转换对象必须为指针或引用,而例3中为一个变量,这是不允许的! ``` [例4]const_cast关键字的使用 #include<iostream> using namespace std; int main() { const int a = 10; const int * p = &a; int *q; q = const_cast<int *>(p); *q = 20; //fine cout <<a<<" "<<*p<<" "<<*q<<endl; cout <<&a<<" "<<p<<" "<<q<<endl; return 0; } ``` 在本例中,我们将变量a声明为常量变量,同时声明了一个const指针指向该变量。之后我们定义了一个普通的指针*q。将p指针通过const_cast去掉其常量性,并赋给q指针。之后我再修改q指针所指地址的值时,这是不会有问题的。 最后将结果打印出来,运行结果如下: 10 20 20 002CFAF4 002CFAF4 002CFAF4 查看运行结果,问题来了,指针p和指针q都是指向a变量的,指向地址相同,而且经过调试发现002CFAF4地址内的值确实由10被修改成了20,这是怎么一回事呢?为什么a的值打印出来还是10呢? 其实这是一件好事,我们要庆幸a变量最终的值没有变成20!变量a一开始就被声明为一个常量变量,不管后面的程序怎么处理,它就是一个常量,就是不会变化的。试想一下如果这个变量a最终变成了20会有什么后果呢?对于这些简短的程序而言,如果最后a变成了20,我们会一眼看出是q指针修改了,但是一旦一个项目工程非常庞大的时候,在程序某个地方出现了一个q这样的指针,它可以修改常量a,这是一件很可怕的事情的,可以说是一个程序的漏洞,毕竟将变量a声明为常量就是不希望修改它,如果后面能修改,这就太恐怖了。 在例4中我们称“*q=20”语句为未定义行为语句,所谓的未定义行为是指在标准的C++规范中并没有明确规定这种语句的具体行为,该语句的具体行为由编译器来自行决定如何处理。对于这种未定义行为的语句我们应该尽量予以避免! 从例4中我们可以看出我们是不想修改变量a的值的,既然如此,定义一个const_cast关键字强制去掉指针的常量性到底有什么用呢?我们接着来看下面的例子。 ``` 例5: #include<iostream> using namespace std; const int * Search(const int * a, int n, int val); int main() { int a[10] = {0,1,2,3,4,5,6,7,8,9}; int val = 5; int *p; p = const_cast<int *>(Search(a, 10, val)); if(p == NULL) cout<<"Not found the val in array a"<<endl; else cout<<"hvae found the val in array a and the val = "<<*p<<endl; return 0; } const int * Search(const int * a, int n, int val) { int i; for(i=0; i<n; i++) { if(a[i] == val) return &a[i]; } return NULL; } ``` 在例5中我们定义了一个函数,用于在a数组中寻找val值,如果找到了就返回该值的地址,如果没有找到则返回NULL。函数Search返回值是const指针,当我们在a数组中找到了val值的时候,我们会返回val的地址,最关键的是a数组在main函数中并不是const,因此即使我们去掉返回值的常量性有可能会造成a数组被修改,但是这也依然是安全的。 对于引用,我们同样能使用const_cast来强制去掉常量性,如例6所示。 ``` 例6: #include<iostream> using namespace std; const int & Search(const int * a, int n, int val); int main() { int a[10] = {0,1,2,3,4,5,6,7,8,9}; int val = 5; int &p = const_cast<int &>(Search(a, 10, val)); if(p == NULL) cout<<"Not found the val in array a"<<endl; else cout<<"hvae found the val in array a and the val = "<<p<<endl; return 0; } const int & Search(const int * a, int n, int val) { int i; for(i=0; i<n; i++) { if(a[i] == val) return a[i]; } return NULL; } ``` 了解了const_cast的使用场景后,可以知道使用const_cast通常是一种无奈之举,同时也建议大家在今后的C++程序设计过程中一定不要利用const_cast去掉指针或引用的常量性并且去修改原始变量的数值,这是一种非常不好的行为。 + **3、reinterpret_cast** 在C++语言中,reinterpret_cast主要有三种强制转换用途:改变指针或引用的类型、将指针或引用转换为一个足够长度的整形、将整型转换为指针或引用类型。 用法:reinterpret_cast<type_id> (expression) + type-id必须是一个指针、引用、算术类型、函数指针或者成员指针。 + 它可以把一个指针转换成一个整数,也可以把一个整数转换成一个指针(先把一个指针转换成一个整数,在把该整数转换成原类型的指针,还可以得到原先的指针值)。 + 在使用reinterpret_cast强制转换过程仅仅只是比特位的拷贝,因此在使用过程中需要特别谨慎! ``` 例7: int *a = new int; double *d = reinterpret_cast<double *>(a); ``` 在例7中,将整型指针通过reinterpret_cast强制转换成了双精度浮点型指针。 reinterpret_cast可以将指针或引用转换为一个足够长度的整形,此中的足够长度具体长度需要多少则取决于操作系统,如果是32位的操作系统,就需要4个字节及以上的整型,如果是64位的操作系统则需要8个字节及以上的整型。 + **4、dynamic_cast** 用法:dynamic_cast<type_id> (expression) + 其他三种都是编译时完成的,dynamic_cast是运行时处理的,运行时要进行类型检查。 + 不能用于内置的基本数据类型的强制转换。 + dynamic_cast转换如果成功的话返回的是指向类的指针或引用,转换失败的话则会返回NULL。 + 使用dynamic_cast进行转换的,基类中一定要有虚函数,否则编译不通过。 + 在类的转换时,在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的。在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全。 B中需要检测有虚函数的原因:类中存在虚函数,就说明它有想要让基类指针或引用指向派生类对象的情况,此时转换才有意义。 这是由于运行时类型检查需要运行时类型信息,而这个信息存储在类的虚函数表(关于虚函数表的概念,详细可见<Inside c++ object model>)中, 只有定义了虚函数的类才有虚函数表。 向上转换,即为子类指针指向父类指针(一般不会出问题);向下转换,即将父类指针转化子类指针。 向下转换的成功与否还与将要转换的类型有关,即要转换的指针指向的对象的实际类型与转换以后的对象类型一定要相同,否则转换失败。 在C++中,编译期的类型转换有可能会在运行时出现错误,特别是涉及到类对象的指针或引用操作时,更容易产生错误。Dynamic_cast操作符则可以在运行期对可能产生问题的类型转换进行测试。 ``` 例1: #include<iostream> using namespace std; class base { public : void m(){cout<<"m"<<endl;} }; class derived : public base { public: void f(){cout<<"f"<<endl;} }; int main() { derived * p; p = new base; p = static_cast<derived *>(new base); p->m(); p->f(); return 0; } ``` 本例中定义了两个类:base类和derived类,这两个类构成继承关系。在base类中定义了m函数,derived类中定义了f函数。在前面介绍多态时,我们一直是用基类指针指向派生类或基类对象,而本例则不同了。 本例主函数中定义的是一个派生类指针,当我们将其指向一个基类对象时,这是错误的,会导致编译错误。 但是通过强制类型转换我们可以将派生类指针指向一个基类对象,p = static_cast<derived *>(new base);语句实现的就是这样一个功能,这样的一种强制类型转换时合乎C++语法规定的,但是是非常不明智的,它会带来一定的危险。 在程序中p是一个派生类对象,我们将其强制指向一个基类对象,首先通过p指针调用m函数,因为基类中包含有m函数,这一句没有问题,之后通过p指针调用f函数。一般来讲,因为p指针是一个派生类类型的指针,而派生类中拥有f函数,因此p->f();这一语句不会有问题,但是本例中p指针指向的确实基类的对象,而基类中并没有声明f函数,虽然p->f();这一语句虽然仍没有语法错误,但是它却产生了一个运行时的错误。换言之,p指针是派生类指针,这表明程序设计人员可以通过p指针调用派生类的成员函数f,但是在实际的程序设计过程中却误将p指针指向了一个基类对象,这就导致了一个运行期错误。 产生这种运行期的错误原因在于static_cast强制类型转换时并不具有保证类型安全的功能,而C++提供的dynamic_cast却能解决这一问题,dynamic_cast可以在程序运行时检测类型转换是否类型安全。 当然dynamic_cast使用起来也是有条件的,它要求所转换的操作数必须包含多态类类型(即至少包含一个虚函数的类)。 ``` 例2: #include<iostream> using namespace std; class base { public : void m(){cout<<"m"<<endl;} }; class derived : public base { public: void f(){cout<<"f"<<endl;} }; int main() { derived * p; p = new base; p = dynamic_cast<derived *>(new base); p->m(); p->f(); return 0; } ``` 在本例中利用dynamic_cast进行强制类型转换,但是因为base类中并不存在虚函数,因此`p = dynamic_cast<derived *>(new base);`这一句会编译错误。 为了解决本例中的语法错误,我们可以将base类中的函数m声明为虚函数,`virtual void m(){cout<<"m"<<endl;}`。 dynamic_cast还要求<>内部所描述的目标类型必须为指针或引用。 <file_sep>/************************************************************************* > File Name: Majority_Element.cpp > Author: stonebegin > Mail: <EMAIL> > Created Time: 2019年04月24日 星期三 22时31分19秒 ************************************************************************/ #include<iostream> #include<vector> #include<string> #include<sstream> #include<algorithm> using namespace std; class Solution { private: int countInRange(vector<int>& nums, int num, int low, int high){ int count = 0; for(int i=low; i<=high; i++) if(nums[i] == num) count++; return count; } int majorityElementRec(vector<int>& nums, int low, int high){ //base case:the only element in an array of size 1 is the majority element if(low == high) return nums[low]; //recurse on left and right havles of this sile int mid = (low - high) / 2 + low; int left = majorityElementRec(nums, low, mid); int right = majorityElementRec(nums, mid+1, high); //if the two halves agree on the majority element, return it if(left == right) return left; //otherwise, count each element and return the "winner" int leftCount = countInRange(nums, left, low, high); int rightCount = countInRange(nums, right, low, high); return leftCount > rightCount ? left : right; } public: //Boyer-Moore Voting Algorithm int BMV_majorityElement(vector<int>& nums) { int count = 0; int candidate; for(int num : nums){ if(count == 0) candidate = num; count += (num == candidate) ? 1 : -1; } return candidate; } int majorityElement(vector<int>& nums){ return majorityElementRec(nums, 0, nums.size()-1); } }; void trimLeftTrailingSpaces(string &input) { input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) { return !isspace(ch); })); } void trimRightTrailingSpaces(string &input) { input.erase(find_if(input.rbegin(), input.rend(), [](int ch) { return !isspace(ch); }).base(), input.end()); } vector<int> stringToIntegerVector(string input) { vector<int> output; trimLeftTrailingSpaces(input); trimRightTrailingSpaces(input); input = input.substr(1, input.length() - 2); stringstream ss; ss.str(input); string item; char delim = ','; while (getline(ss, item, delim)) { output.push_back(stoi(item)); } return output; } int main() { string line; while (getline(cin, line)) { vector<int> nums = stringToIntegerVector(line); int ret = Solution().majorityElement(nums); string out = to_string(ret); cout << out << endl; } return 0; }
9abca6e4c00dbd783005d10a113057a91b0ba390
[ "Markdown", "C++" ]
10
Markdown
stonebegin/CppNotebook
bcf4c012913484c13ee3a31f33d783a51e168026
5d73dd9d3244ce9f5b9803b9133514d988230c05
refs/heads/master
<file_sep>import React, {Component} from 'react' import {connect} from 'react-redux' import Sub from './Sub.js' import Slide from './Slide.js' import load from '../../shared/actions/creators/load.js' import socketInit from '../../shared/actions/socketInit.js' import listenSocket from '../actions/creators/listenSocket.js' class Root extends Component { componentDidMount () { this.props.mounted() } render () { const {innerWidth, innerHeight} = window const style = { width: innerWidth, height: innerHeight, backgroundColor: '#000', position: 'relative' } const sub = this.props.info.mode === 'slide' ? pug`Slide` : pug`Sub` return pug` div(style='{style}') {sub} ` } } export default connect( ({info}) => { return {info} }, dispatch => { return { mounted: () => { dispatch(load()) dispatch(socketInit()) dispatch(listenSocket()) } } } )(Root) <file_sep>export default function slide () { return async (dispatch, getState) => { const {socket} = getState() socket.emit('slide') dispatch({ type: 'slide' }) } } <file_sep>import {rr} from 'redux-frr' import update from './update.js' import clearTimer from './clearTimer.js' import seekTime from './seekTime.js' import slide from './slide.js' import start from './start.js' export default rr( (state = { base: 0, startAt: null, time: 0, timer: null, index: 1, updateAt: null, mode: 'srt' }) => state, update, clearTimer, seekTime, slide, start ) <file_sep>import {frr} from 'redux-frr' export default frr('start', (state, action) => { const startAt = new Date().getTime() return { ...state, time: state.base, startAt } }) <file_sep>export default function listenSocket () { return async (dispatch, getState) => { const {socket} = getState() socket.on('toggle', msg => { const {timer} = getState().info if (timer === null) { const update = () => { const {subs, info} = getState() const t = setTimeout(update, 100) dispatch({ type: 'update', subs, info, timer: t }) } dispatch({ type: 'start' }) update() } else { clearTimeout(timer) dispatch({ type: 'clearTimer' }) } }) socket.on('editTime', time => { dispatch({ type: 'editTime', time }) }) socket.on('seekTime', dest => { dispatch({ type: 'seekTime', dest }) }) socket.on('slide', () => { dispatch({ type: 'slide' }) }) socket.on('next', () => { dispatch({ type: 'next' }) }) socket.on('prev', () => { dispatch({ type: 'prev' }) }) } } <file_sep>import {frr} from 'redux-frr' export default frr('next', (state, action) => { return {...state, index: state.index + 1} }) <file_sep>export default function toggle () { return async (dispatch, getState) => { const {socket} = getState() socket.emit('toggle') const {timer} = getState().info if (timer === null) { const update = () => { const {subs, info} = getState() const t = setTimeout(update, 100) dispatch({ type: 'update', subs, info, timer: t }) } dispatch({ type: 'start' }) update() } else { clearTimeout(timer) dispatch({ type: 'clearTimer' }) } } } <file_sep>import {combineReducers} from 'redux' import subs from '../../shared/reducers/subs/index.js' import socket from '../../shared/reducers/socket/index.js' import info from '../../shared/reducers/info/index.js' import slide from '../../shared/reducers/slide/index.js' export default combineReducers({ subs, socket, info, slide }) <file_sep>import {frr} from 'redux-frr' export default frr('seekTime', (state, action) => { const {dest} = action return {...state, base: dest, time: dest, updateAt: null, startAt: null} }) <file_sep>import getMS from '../../../utils/getMS.js' export default function seekTime ({hour, min, sec}) { return (dispatch, getState) => { const {socket} = getState() const dest = getMS(`${hour}:${min}:${sec},0`) socket.emit('seekTime', dest) dispatch({ type: 'seekTime', dest }) } } <file_sep>export default function socketInit () { return { type: 'socketInited', socket: io() } } <file_sep>export default function convertMS (n) { const d = new Date(n) const comp = (n) => n.toString().length === 1 ? `0${n}` : n return `${comp(d.getHours() - 9)}:${comp(d.getMinutes())}:${comp(d.getSeconds())}:${comp(d.getMilliseconds())}` } <file_sep>import {frr} from 'redux-frr' export default frr('slide', (state, action) => { const mode = state.mode === 'srt' ? 'slide' : 'srt' return {...state, mode} }) <file_sep>import {frr} from 'redux-frr' function split (srts) { const subs = {1: []} let key = 1 srts.replace(/\n\n\n/g, '\n\n').split('\n').forEach(str => { if (str.length === 0) { key += 1 subs[key] = [] } else { subs[key].push(str) } }) return subs } export default frr('bigload', (state, action) => { const subs = split(action.srt) const subs1 = split(action.en) return {...state, data: subs, data1: subs1} }) <file_sep>import React from 'react' import {connect} from 'react-redux' function Sub ({subs}) { if (subs.data === undefined || !subs.isShow) { return pug`span` } const strs = subs.data[subs.index].strs.map((str, i) => { const key = `sub-${subs.index}-${i}` let style = {} if (/<i>/.test(str) || /<\/i>/.test(str)) { str = str.replace(/<i>/, '') str = str.replace(/<\/i>/, '') style.fontStyle = 'italic' } return pug` div( key='{key}' style='{style}' ) {str} ` }).reverse() const style = { position: 'absolute', width: '100%', color: '#fff', fontSize: '5em', writingMode: 'vertical-lr' } return pug` div(style='{style}') {strs} ` } export default connect( ({subs}) => { return {subs} } )(Sub) <file_sep>import {frr} from 'redux-frr' export default frr('update', (state, action) => { const {info} = action if (info.time > state.data[state.index].time[0]) { state.isShow = true } if (info.time > state.data[state.index].time[1]) { state.isShow = false state.index += 1 } return {...state} }) <file_sep>import 'babel-polyfill' import {createElement} from 'react' import {render} from 'react-dom' import {Provider} from 'react-redux' import {applyMiddleware, createStore} from 'redux' import thunk from 'redux-thunk' import createLogger from 'redux-logger' import Root from './components/Root.js' import reducers from './reducers/store.js' const logger = createLogger({ collapsed: () => true }) const store = applyMiddleware(thunk, logger)(createStore)(reducers) render( createElement(Provider, {store}, createElement(Root)), document.getElementById('app') ) <file_sep>const {readFileSync, writeFileSync} = require('fs') const times = readFileSync('./assets/what_time.txt').toString().split('\n') const texts = readFileSync('./assets/what_text.utf8.txt').toString().split('\n') const comp = n => { return n.toString().length === 1 ? `0${n}` : n } const comp1 = n => { return n.toString().length !== 3 ? comp1(`0${n}`) : n } const ms2tc = ms => { const d = new Date(ms) const H = comp(d.getHours() - 9) const M = comp(d.getMinutes()) const s = comp(d.getSeconds()) const m = comp1(d.getMilliseconds()) return `${H}:${M}:${s}:${m}` } const nf = ns => ns !== null const srTimes = times.map((n, i) => { return i % 2 === 0 ? [parseInt(times[i]) * 100, parseInt(times[i + 1]) * 100] : null }).filter(nf).map((ns, i) => { return `${i + 1}\n${ms2tc(ns[0])} --> ${ms2tc(ns[1])}` }) const srTexts = texts.map((s, i) => { return i % 4 === 0 ? [texts[i], texts[i + 1], texts[i + 2], texts[i + 3]] : null }).filter(nf).map(ss => { return ss.filter(s => s !== '').join('\n') }) const srt = srTimes.map((t, i) => { return `${t}\n${srTexts[i]}\n` }).join('\n') writeFileSync('./assets/what_converted.srt', srt) <file_sep>import React from 'react' import {connect} from 'react-redux' import toggleAction from '../actions/creators/toggle.js' import slideAction from '../actions/creators/slide.js' function Switch ({toggle, slide}) { return pug` div button(onClick='{toggle}') スタート/ストップ button(onClick='{slide}') スライド/ srt ` } export default connect( state => { return {} }, dispatch => { return { toggle: event => dispatch(toggleAction()), slide: event => dispatch(slideAction()) } } )(Switch) <file_sep>import {frr} from 'redux-frr' export default frr('clearTimer', (state, action) => { const base = state.base + state.updateAt - state.startAt return {...state, timer: null, updateAt: null, startAt: null, base} }) <file_sep>export default function seekNext () { return (dispatch, getState) => { const {socket, subs, info} = getState() if (info.startAt === null) { const index = subs.isShow ? subs.index + 1 : subs.index const dest = subs.data[index].time[0] + 10 socket.emit('seekTime', dest) dispatch({ type: 'seekTime', dest }) } } } <file_sep>import React from 'react' import {connect} from 'react-redux' import Buttons from './Buttons.js' import Switch from './Switch.js' import convertMS from '../../utils/convertMS.js' function Subs ({info, subs}) { if (subs.data === undefined) { return pug`span` } let {index} = subs let nextTime = subs.data[index].time[0] - info.time let nextIndex = index let currentElement if (nextTime < 0) { nextIndex += 1 nextTime = subs.data[nextIndex].time[0] - info.time currentElement = pug` div span 今の字幕あと:&nbsp; span {convertMS(subs.data[index].time[1] - info.time)} ` } else { currentElement = pug`span` } const n = parseInt(index) const recently = Object.keys(subs.data).slice((n), (n + 20)).map(key => { const sub = subs.data[key] const k = `recent-${key}` return pug` tr(key='{k}') td {convertMS(sub.time[0])} td &nbsp;--&gt;&nbsp; td {convertMS(sub.time[1])} td {sub.strs} ` }) return pug` div div {convertMS(info.time)} div span 次の字幕:&nbsp; span {subs.data[nextIndex].strs} div span あと:&nbsp; span {convertMS(nextTime)} Buttons div {currentElement} table tbody {recently} Switch ` } export default connect( ({info, subs}) => { return {info, subs} } )(Subs) <file_sep>const webpack = require('webpack') const dirs = ['controller', 'viewer'] dirs.forEach(dir => { webpack({ context: process.cwd(), entry: `./src/${dir}/index.js`, output: { filename: 'index.js', path: `./build/${dir}` }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'stage-1'], plugins: ['transform-pug-to-react'], cacheDirectory: 'tmp' } } ] }, watch: true }, (err, stat) => { if (err) { console.log(err) } if (stat.compilation.errors.length > 0) { console.log(stat.compilation.errors) } const d = new Date() console.log(`${d.getHours()}:${d.getMinutes()}:${d.getSeconds()} ${dir} Compiled`) }) }) <file_sep>import {rr} from 'redux-frr' import load from './load.js' import next from './next.js' import prev from './prev.js' export default rr( (state = {index: 1, isShow: false}) => state, load, next, prev ) <file_sep>import {rr} from 'redux-frr' import init from './init.js' export default rr((state = {}) => state, init) <file_sep>import React, {Component} from 'react' import {connect} from 'react-redux' import Subs from './Subs.js' import Slide from './Slide.js' import keydown from '../actions/creators/keydown.js' import load from '../../shared/actions/creators/load.js' import socketInit from '../../shared/actions/socketInit.js' import convertMS from '../../utils/convertMS.js' class Root extends Component { componentDidMount () { this.props.mounted() document.addEventListener('keydown', this.props.keydown) } render () { const {info} = this.props if (info.mode === 'slide') { return pug`Slide` } else { return pug`Subs` } } } export default connect( ({info}) => { return {info} }, dispatch => { return { mounted: () => { dispatch(load()) dispatch(socketInit()) }, keydown: event => dispatch(keydown(event)) } } )(Root) <file_sep>import {frr} from 'redux-frr' export default frr('update', (state, action) => { const updateAt = new Date().getTime() const diff = updateAt - state.startAt return { ...state, time: state.base + diff, timer: action.timer, updateAt } }) <file_sep>import React, {Component} from 'react' import {connect} from 'react-redux' import editTime from '../actions/creators/editTime.js' import seekTime from '../actions/creators/seekTime.js' import seekNext from '../actions/creators/seekNext.js' class Buttons extends Component { seek () { const {hour, min, sec} = this.refs this.props.seek({hour: hour.value, min: min.value, sec: sec.value}) } render () { const {onClick} = this.props return pug` div div button(onClick='{onClick(1000)}') 1秒遅く button(onClick='{onClick(100)}') 0.1秒遅く button(onClick='{onClick(-100)}') 0.1秒早く button(onClick='{onClick(-1000)}') 1秒早く div input(size='2' ref='hour') span : input(size='2' ref='min') span : input(size='2' ref='sec') button(onClick='{this.seek.bind(this)}') シーク div button(onClick='{this.props.seekNext}') 次の字幕 ` } } export default connect( state => { return {} }, dispatch => { return { onClick: time => event => dispatch(editTime(time)), seek: time => dispatch(seekTime(time)), seekNext: event => dispatch(seekNext()) } } )(Buttons) <file_sep>import {prevHandler, nextHandler} from './slideHandler.js' export default function keydown (event) { return async (dispatch, getState) => { const {socket} = getState() switch (event.keyCode) { case 37: { dispatch(prevHandler()) break } case 39: { dispatch(nextHandler()) break } } } } <file_sep>import {frr} from 'redux-frr' export default frr('prev', (state, action) => { return {...state, index: state.index - 1} }) <file_sep>import {rr} from 'redux-frr' import load from './load.js' import editTime from './editTime.js' import update from './update.js' import seekTime from './seekTime.js' export default rr( (state = {index: 1, isShow: false}) => state, load, editTime, update, seekTime ) <file_sep>import {frr} from 'redux-frr' import getMS from '../../../utils/getMS.js' export default frr('load', (state, action) => { const subs = {} let key = null action.srt.split('\n').forEach(str => { if (str.length === 1) { key = null return } if (key === null) { key = parseInt(str) } else if (subs[key] === undefined) { subs[key] = { time: str.split(' --> ').map(getMS), strs: [] } } else { subs[key].strs.push(str) } }) return {...state, data: subs} }) <file_sep>import 'babel-polyfill' import Koa from 'koa' import Router from 'koa-router' import send from 'koa-send' import Socket from 'koa-socket' import {resolve} from 'path' const app = new Koa() const router = new Router() const socket = new Socket() router .get('/', ctx => { ctx.body = 'works' }) .get('/assets/socket.io.js', async ctx => { await send(ctx, 'socket.io.js', { root: resolve(__dirname, '../../node_modules/socket.io-client') }) }) .get('/assets/target.:ext', async ctx => { await send(ctx, `target.${ctx.params.ext}`, { root: resolve(__dirname, '../../build') }) }) .get('/assets/target_en.:ext', async ctx => { await send(ctx, `target_en.${ctx.params.ext}`, { root: resolve(__dirname, '../../build') }) }) .get('/controller/:filename', async ctx => { await send(ctx, ctx.params.filename, { root: resolve(__dirname, '../../build/controller') }) }) .get('/viewer/:filename', async ctx => { await send(ctx, ctx.params.filename, { root: resolve(__dirname, '../../build/viewer') }) }) app .use(router.routes()) .use(router.allowedMethods()) socket.attach(app) const keys = ['toggle', 'editTime', 'seekTime', 'slide', 'next', 'prev'] keys.forEach(key => { socket.on(key, (ctx, data) => { socket.broadcast(key, data) }) }) const PORT = process.env.PORT || 3000 app.listen(PORT, () => { console.log(`Listening port: ${PORT}`) }) <file_sep>import React from 'react' import {connect} from 'react-redux' function Slide ({slide}) { if (slide.data === undefined) { return pug`span` } const strs = slide.data[slide.index].map((str, i) => { const key = `sub-${slide.index}-${i}` return pug` div( key='{key}' ) {str} ` }).reverse() const style = { position: 'absolute', width: '100%', color: '#fff', fontSize: '5em', writingMode: 'vertical-lr' } return pug` div(style='{style}') {strs} ` } export default connect( ({slide}) => { return {slide} } )(Slide) <file_sep>import React from 'react' import {connect} from 'react-redux' import Switch from './Switch.js' import {nextHandler, prevHandler} from '../actions/creators/slideHandler.js' function getSub (ary) { return ary.length === 0 ? ['■'] : ary } function Slide ({info, slide, next, prev}) { if (slide.data === undefined) { return pug`span` } let {index} = slide const n = parseInt(index) const p1 = n - 1 < 0 ? 0 : n - 1 const p2 = n - 11 < 0 ? 0 : n - 11 const previosly = Object.keys(slide.data).slice(p2, p1).map(key => { const sub = getSub(slide.data[key]) const k = `prev-${key}` return pug` tr(key='{k}') td {sub} ` }) const recently = Object.keys(slide.data).slice((n + 1), (n + 11)).map(key => { const sub = getSub(slide.data[key]) const k = `recent-${key}` return pug` tr(key='{k}') td {sub} ` }) const previosly1 = Object.keys(slide.data1).slice(p2, p1).map(key => { const sub = getSub(slide.data1[key]) const k = `prev1-${key}` return pug` tr(key='{k}') td {sub} ` }) const recently1 = Object.keys(slide.data1).slice((n + 1), (n + 11)).map(key => { const sub = getSub(slide.data1[key]) const k = `recent1-${key}` return pug` tr(key='{k}') td {sub} ` }) const s1 = { color: '#f00', fontWeight: 'bold' } const s2 = { color: '#00f' } const root = { display: 'flex', flexDirection: 'colmun' } const child = { width: '50%' } return pug` div(style='{root}') div(style='{child}') table tbody {previosly} div(style='{s1}') span {getSub(slide.data[n])} div(style='{s2}') span {getSub(slide.data[n + 1])} table tbody {recently} div button(onClick='{prev}') 前へ button(onClick='{next}') 次へ Switch div(style='{child}') table tbody {previosly1} div(style='{s1}') span {slide.data1[n]} div(style='{s2}') span {slide.data1[n + 1]} table tbody {recently1} ` } export default connect( ({info, slide}) => { return {info, slide} }, dispatch => { return { next: () => dispatch(nextHandler()), prev: () => dispatch(prevHandler()) } } )(Slide) <file_sep>export default function (str) { const [t, m] = str.split(',') const [H, M, S] = t.split(':') return (parseInt(H) * 3600000) + (parseInt(M) * 60000) + (parseInt(S) * 1000) + parseInt(m) }
e42bdccda817cd7a6ec741de48654dd2ef0c8ca8
[ "JavaScript" ]
36
JavaScript
e-jigsaw/jim
f08955127d3412774ada4880a34f11d1d9e153c8
b2f717378fdb8c508ea3c4cd7a1947c93f7c19cf
refs/heads/master
<file_sep># LSTMStockPredictor A very simple implementation of a LSTM Neural Network that tries to predict the next day close price of a stock using data from Yahoo Finance. <file_sep>import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler from keras import models from keras import layers from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Reshape, LSTM from keras.utils import to_categorical import os from datetime import datetime, timedelta import bs4 import requests import json def getYahooData(ticker, startDate, endDate, interval): #get todays date today = datetime.now().date() tomorrow = today + timedelta(days=1) today = today.strftime('%d-%m-%Y') tomorrow = tomorrow.strftime('%d-%m-%Y') # have to convert each date to unix for the yahoo url # format for date will be 'DD-MM-YYYY' if startDate == endDate: startDateUnix = int(datetime.strptime(today, '%d-%m-%Y').timestamp()) endDateUnix = int(datetime.strptime(tomorrow, '%d-%m-%Y').timestamp()) else: startDateUnix = int(datetime.strptime(startDate, '%d-%m-%Y').timestamp()) endDateUnix = int(datetime.strptime(endDate, '%d-%m-%Y').timestamp()) url = 'https://query1.finance.yahoo.com/v8/finance/chart/' + ticker + '?symbol=' + ticker + '&period1=' + str(startDateUnix) + '&period2=' + str(endDateUnix) + '&interval=' + str(interval) res = requests.get(url, headers={"User-Agent":"Mozilla/5.0"}) soup = bs4.BeautifulSoup(res.text, 'html.parser') # sort through the nested dictionary mess and put each value in its own list newDictionary=json.loads(str(soup)) newDictionary2 = newDictionary['chart']['result'][0] unixDates = newDictionary2['timestamp'] dates = [] # turn the unix timestamps back into dates for item in unixDates: dateFormat = datetime.fromtimestamp(item).date().strftime('%Y-%m-%d') dates.append(dateFormat) newDictionary3 = newDictionary2['indicators']['quote'][0] # convert each value into float so that we can only keep two places after the decimal strOpens = newDictionary3['open'] opens = [] for item in strOpens: if item == None: number = 0.00 opens.append(number) else: number = round(float(item), 2) opens.append(number) strHighs = newDictionary3['high'] highs = [] for item in strHighs: if item == None: number = 0 highs.append(number) else: number = round(float(item), 2) highs.append(number) strLows = newDictionary3['low'] lows = [] for item in strLows: if item == None: number = 0 lows.append(number) else: number = round(float(item), 2) lows.append(number) strCloses = newDictionary3['close'] closes = [] for item in strCloses: if item == None: number = 0 closes.append(number) else: number = round(float(item), 2) closes.append(number) strVolumes = newDictionary3['volume'] volumes = [] for item in strVolumes: if item == None: number = 0 volumes.append(number) else: number = int(item) volumes.append(number) # only worry about adj. close if there is an interval 1d or more # have to make a new dictionary just for the adjClose prices if interval != '1m' and interval != '2m' and interval != '5m': newDictionary4 = newDictionary2['indicators']['adjclose'][0] strAdjCloses = newDictionary4['adjclose'] adjCloses = [] for item in strAdjCloses: if item == None: number = 0 else: number = round(float(item), 2) adjCloses.append(number) # append them all to their own list so that each entry in the list is a full OHLC entry for the day newList = [] finalList = [] for i in range(0, len(dates)): newList.append(dates[i]) newList.append(opens[i]) newList.append(highs[i]) newList.append(lows[i]) newList.append(closes[i]) if interval != '1m' and interval != '2m' and interval != '5m': newList.append(adjCloses[i]) newList.append(volumes[i]) finalList.append(newList) newList = [] return finalList def grabData(): stopData = False stockData = [] ticker = input("ticker:") tInterval = input("Time Interval(1m, 2m, 5m, 1d, 1w, 1m):") while(not stopData): startDate = input("Start Date:") endDate = input("End Date:") # get stock data newData = getYahooData(ticker, startDate, endDate, tInterval) for count in range(0, len(newData)-1): stockData.append(newData[count]) print('Data Retrieved.') print("Continue Grabbing Data? (y/n)") getMoreData = input(":") if getMoreData == 'n': break; os.system('cls') return[stockData, tInterval] def makePrediction(): data = grabData() # data[0] = stock data, data[1] = time interval if data[1] != '1m' and data[1] != '2m' and data[1] != '5m': stockData = pd.DataFrame(data[0], columns=['Date', 'Open', 'High', 'Low', 'Close', 'Adj. Close', 'Volume']) else: stockData = pd.DataFrame(data[0], columns=['Date', 'Open', 'High', 'Low', 'Close', 'Volume']) del(stockData['Date']) del(stockData['Open']) del(stockData['High']) del(stockData['Low']) del(stockData['Volume']) if data[1] != '1m' and data[1] != '2m' and data[1] != '5m': del(stockData['Adj. Close']) # 90% train, 10% test trainSize = int(len(stockData) * .9) trainStockData = stockData[:trainSize] testStockData = stockData[trainSize:] # UNCOMMENT FOR SMA PREDICTION #trainStockData['SMA'] = trainStockData['Close'].rolling(window=5).mean() #trainStockData = trainStockData.fillna(0) #del(trainStockData['Close']) trainStockData = np.array(trainStockData) # UNCOMMENT FOR SMA PREDICTION #testStockData['SMA'] = testStockData['Close'].rolling(window=5).mean() #testStockData = testStockData.fillna(0) #del(testStockData['Close']) testStockData = np.array(testStockData) scaler = MinMaxScaler(feature_range=(-1, 1)) # train data x_train = [] y_train = [] for count in range(0, len(trainStockData)): if count % 2 == 0: x_train.append(trainStockData[count]) else: y_train.append(trainStockData[count]) x_train = np.array(x_train) x_train = scaler.fit_transform(x_train) x_train = x_train.reshape(-1, 1, 1) y_train = np.array(y_train) y_train = scaler.fit_transform(y_train) y_train = y_train.reshape(-1, 1, 1) # make sure x_train and y_train are the same if(x_train.shape[0] != y_train.shape[0]): x_train = np.delete(x_train, len(x_train)-1, 0) # test data x_test = [] y_test = [] for count in range(0, len(testStockData)): if count % 2 == 0: x_test.append(testStockData[count]) else: y_test.append(testStockData[count]) x_test = np.array(x_test) x_test = scaler.fit_transform(x_test) x_test = x_test.reshape(-1, 1, 1) y_test = np.array(y_test) y_test = scaler.fit_transform(y_test) y_test = y_test.reshape(-1, 1, 1) # make sure x_train and y_train are the same if(x_test.shape[0] != y_test.shape[0]): x_test = np.delete(x_test, len(x_test)-1, 0) # build network network = Sequential() network.add(Dense(10000, activation='relu', input_shape=(x_train.shape[1], x_train.shape[2]))) network.add(LSTM(1000, activation='relu', return_sequences=True)) network.add(Dropout(.5)) network.add(Dense(1)) network.compile(optimizer='adam', loss='mse', metrics=['acc']) network.summary() history = network.fit(x_train, y_train, epochs=10, verbose=2) evaluation = network.evaluate(x_test, y_test) evalAcc = evaluation[1] # make a prediction on the last day for y_test actualData = y_test actualData = actualData.reshape(-1, 1) actualData = scaler.inverse_transform(actualData) newData = np.array(actualData[len(actualData)-1]) # last value in y_test which is now actualData previousValue = newData # store this value for later newData = newData.reshape(-1, 1) newData = scaler.fit_transform(newData) newData = newData.reshape(-1, 1, 1) prediction = network.predict(newData) prediction = prediction.reshape(-1, 1) prediction = scaler.inverse_transform(prediction) print('Previous Close: ', previousValue) print('Next Predicted Close: ', prediction) # add or subtract the accuracy to try and get a better predition if prediction > previousValue: print('Adjusted Prediction: ', prediction + round(evalAcc, 2)) else: print('Adjusted Prediction: ', prediction - round(evalAcc, 2)) if __name__ == '__main__': makePrediction();
43f5da61c7d7a4a5a6170717670c14fe11a72629
[ "Markdown", "Python" ]
2
Markdown
boydjc/LSTMStockPredictor
48cab268eeebe7176c99e210ad4b5915498254e1
be44e95f6911b1abb3ec44072f7c922904ee9ef0
refs/heads/master
<file_sep>from typing import List, Dict, Any, Tuple import string import random def n_partition(words: List[str], n_length: int) -> Dict[Tuple[str], List[str]]: """The function divides a given words list into different partitions of length n_length. Each partition will be set as a key from a dict wich maps to the word in the words list at the following index position n_length + 1. Since same word partitions may be followed by different words, all the possible following words will be stored in a list. This list collection with multiple following words is set as value to the partition key in the dict. Arguments: words {List[]str} -- words from a given text are stored in a list, ordered by occurence within the text n_length {int} -- length of the partition keys Returns: Dict[Tuple[str], List[str]] -- Dict mapping from partitions to valid next words """ part_dict = dict() for index, word in enumerate(words): try: # get next partition with length n_length as dict key partition_key = tuple(words[index + j] for j in range(n_length)) value = part_dict.setdefault(partition_key, []) # map the next word to the partition_key which is not contained # in the partition key itself as element value.append(words[index + n_length]) except IndexError: continue return part_dict def random_step( part_key: Tuple[str], partitions: Dict[Tuple[str], List[str]] ) -> List[str]: """Choose randomly from the next valid words. Arguments: part_key {Tuple} -- key in partitions partitions {List[Tuple]} -- dictionary with possible next steps for a key Returns: {List} -- next word, randomly chosen from a given set of valid answers """ next_walk = partitions.get(part_key, []) # choose randomly only if there are two choices at least if len(next_walk) > 1: next_walk = [random.choice(next_walk)] return part_key[1:] + tuple(next_walk), next_walk def random_walk( init_partition: Tuple[str], partitions: Dict[Tuple[str], List[str]] ) -> List[List[str]]: """Perform a random walk, according to a given partitions dict which maps from a given set of partitions to a valid set of possible next words. Within this set it will be choosen randomly. Arguments: init_partition {Tuple[str]} -- initial key to start the random walk partitions {Dict[Tuple[str], List[str]]} -- random walk map with possible choices Returns: List[List[str]] -- Randomly choosen words, gained through a random walk """ # modify structure of initial input to match the output structure walk_list = [word for word in init_partition] iter_tuple = init_partition next_word = [""] while next_word != []: iter_tuple, next_word = random_step(iter_tuple, partitions) # unpack List[str] to append only strings, except the empty list # which causes an IndexError try: walk_list.append(next_word[0]) except IndexError: continue return walk_list def read_file(filename): words = [] with open(filename, "r") as file: for line in file: line = line.replace("-", " ") for word in line.split(): word = word.strip(string.punctuation + string.whitespace) word = word.lower() words.append(word) return words def main(): # store words in list # TODO: imporove text preprocessing # words = read_file("test_text.txt") words = read_file("hudson.txt") # transform words in partitions which will serves as # keys for a random walk n_length = 2 partitions = n_partition(words, n_length) # choose an initial partition for the random walk init_part = random.choice(list(partitions.keys())) walk_list = random_walk(init_part, partitions) random_walk_text = " ".join(walk_list) print(random_walk_text) if __name__ == "__main__": main() <file_sep>import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer df = pd.read_csv("mail_data.csv") # preprocess mail strings df["emails_cleaned"] = df["emails"].str.replace(".", "") df["emails_cleaned"] = "_" + df["emails_cleaned"] + "_" mails = df["emails_cleaned"] def ngrams(string: str, n=3): ngrams = zip(*[string[i:] for i in range(n)]) return ["".join(ngram) for ngram in ngrams] vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams) tf_idf_matrix = vectorizer.fit_transform(mails) print("bla") import numpy as np from scipy.sparse import csr_matrix import sparse_dot_topn.sparse_dot_topn as ct def awesome_cossim_top(A, B, ntop, lower_bound=0): # force A and B as a CSR matrix. # If they have already been CSR, there is no overhead A = A.tocsr() B = B.tocsr() M, _ = A.shape _, N = B.shape idx_dtype = np.int32 nnz_max = M * ntop indptr = np.zeros(M + 1, dtype=idx_dtype) indices = np.zeros(nnz_max, dtype=idx_dtype) data = np.zeros(nnz_max, dtype=A.dtype) ct.sparse_dot_topn( M, N, np.asarray(A.indptr, dtype=idx_dtype), np.asarray(A.indices, dtype=idx_dtype), A.data, np.asarray(B.indptr, dtype=idx_dtype), np.asarray(B.indices, dtype=idx_dtype), B.data, ntop, lower_bound, indptr, indices, data, ) return csr_matrix((data, indices, indptr), shape=(M, N)) def get_matches_df(sparse_matrix, name_vector, top=100): non_zeros = sparse_matrix.nonzero() sparserows = non_zeros[0] sparsecols = non_zeros[1] if top: nr_matches = top else: nr_matches = sparsecols.size left_side = np.empty([nr_matches], dtype=object) right_side = np.empty([nr_matches], dtype=object) similairity = np.zeros(nr_matches) for index in range(0, nr_matches): left_side[index] = name_vector[sparserows[index]] right_side[index] = name_vector[sparsecols[index]] similairity[index] = sparse_matrix.data[index] return pd.DataFrame( {"left_side": left_side, "right_side": right_side, "similairity": similairity} ) import time t1 = time.time() matches = awesome_cossim_top(tf_idf_matrix, tf_idf_matrix.transpose(), 10, 0.8) t = time.time() - t1 print("SELFTIMED:", t) matches_df = get_matches_df(matches, company_names, top=100000) matches_df = matches_df[matches_df["similairity"] < 0.99999] # Remove all exact matches matches_df.sample(20)
c795f9630c0fb1b3344bf3c1ed614c897364b6ff
[ "Python" ]
2
Python
dstumPY/text_analysis
7cef07be194e7329aacbe1591117a680f173c3d6
63baeeaa52333db0bcb7a8f3093a2b0172bbec5d
refs/heads/master
<file_sep>import { ethers, Contract } from 'ethers'; import detectEthereumProvider from '@metamask/detect-provider'; import Wallet from './contracts/Wallet.json'; import addresses from './addresses.js'; // const getBlockchain = () => // new Promise(async (resolve, reject) => { // window.addEventListener('load', async () => { // if(window.ethereum) { // await window.ethereum.enable(); // const provider = new ethers.providers.Web3Provider(window.ethereum); // const signer = provider.getSigner(); // const wallet = new Contract( // Wallet.networks[window.ethereum.networkVersion].address, // Wallet.abi, // signer // ); // const dai = new Contract( // addresses.dai, // ['function approve(address spender, uint amount) external'], // signer // ); // resolve({signer, wallet, dai}); // } // resolve({signer: undefined, wallet: undefined, dai: undefined}); // }); // }); // const CONTRACT_ADDRESS = Wallet.networks[].address; const getBlockchain = () => new Promise( async (resolve, reject) => { let provider = await detectEthereumProvider(); if(provider) { await provider.request({ method: 'eth_requestAccounts' }); const networkId = await provider.request({ method: 'net_version' }) provider = new ethers.providers.Web3Provider(provider); const signer = provider.getSigner(); const wallet = new Contract( Wallet.networks[5777].address, // 0xda96CaF05d3241927a3b0e3DaFD82318E3d742Df, Wallet.abi, signer ); const dai = new Contract( addresses.dai, ['function approve(address spender, uint amount) external'], signer ); resolve({signer, wallet, dai}); return; } reject('Install Metamask'); }); export default getBlockchain; <file_sep>/** * @type import('hardhat/config').HardhatUserConfig */ require('@nomiclabs/hardhat-waffle'); // const INFURA_URL = 'https://eth-rinkeby.gateway.pokt.network/v1/5fff8b3c24d382002f2daeaa'; // const PRIVATE_KEY='' module.exports = { defaultNetwork: "rinkeby", networks: { hardhat: { }, rinkeby: { url: 'https://eth-rinkeby.gateway.pokt.network/v1/5fff8b3c24d382002f2daeaa', accounts: {mnemonic: ''} } }, solidity: { version: "0.7.3", settings: { optimizer: { enabled: true, runs: 200 } } }, paths: { sources: "./contracts", tests: "./test", cache: "./cache", artifacts: "./frontend/src/artifacts" }, mocha: { timeout: 20000 }, etherscan: { // Your API key for Etherscan // Obtain one at https://etherscan.io/ apiKey: "" } }
06748ef081c1e639ebaf142aa73809699cc73f6a
[ "JavaScript" ]
2
JavaScript
VictorONN/smart-contract-wallet-dapp
5d2dde81efdf5c54d76b6f9610f943abe283a30c
b0e0a7dfb4c4a9bfa986becf4c5c429a6c19ee11
refs/heads/master
<file_sep>/** * */ package cz.hanusova.fingerprintgame.service; import cz.hanusova.fingerprintgame.fingerprint.Fingerprint; /** * @author khanusova * */ public interface FingerprintService { /** * Saves new fingerprint to separate file <br/> * * @param fingerprint * {@link Fingerprint} sent from client */ void saveFingerprint(Fingerprint fingerprint); } <file_sep>package cz.hanusova.fingerprintgame.controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestParam; //@Controller //@RequestMapping(value = "/administration") public class AdministrationController { // @RequestMapping(value = "") public String getRequest(Model model) { model.addAttribute("floor", 1); model.addAttribute("imgsrc", "/resources/img/J1NP.jpg"); return "administration"; } // @RequestMapping("/maps") public String getMaps(@RequestParam("floor") String floor, Model model) { model.addAttribute("floor", floor); String imgSrc = "/resources/img/J" + floor + "NP.jpg"; model.addAttribute("imgsrc", imgSrc); return "administration"; } // @RequestMapping("/save") public String saveCircles(@ModelAttribute("floor") String floor) { return "administration"; } } <file_sep>/** * */ package cz.hanusova.fingerprintgame.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * @author khanusova * */ @Controller public class PolicyController { @RequestMapping("/policy") public String showPrivacyPolicy() { return "policy"; } } <file_sep>--liquibase formatted sql --changeset hanuska1:create-1 SET SQL_SAFE_UPDATES=0; create table MATERIAL( ID_MATERIAL bigint(19) not null auto_increment, NAME varchar(255), primary key (ID_MATERIAL) ); create table PLACE_TYPE( ID_PLACE_TYPE bigint(19) not null auto_increment, PLACE_TYPE varchar (255), IMG_URL varchar (255), ACTIVITY varchar (255), primary key (ID_PLACE_TYPE) ); --changeset hanuska1:create-2 create table USER_CHARACTER( ID_CHARACTER bigint(19) not null auto_increment, CHARISMA int, POWER int, XP int, primary key (ID_CHARACTER) ); create table APP_USER( ID_APP_USER bigint(19) not null auto_increment, USERNAME varchar(255), STAGNAME varchar(255), PASSWORD varchar(255), ID_CHARACTER bigint(19), primary key (ID_APP_USER), constraint fk_character foreign key (ID_CHARACTER) references USER_CHARACTER(ID_CHARACTER) ); create table INVENTORY( ID_INVENTORY bigint(19) not null auto_increment, ID_APP_USER bigint(19), ID_MATERIAL bigint(19), AMOUNT numeric(19,2), primary key (ID_INVENTORY), constraint fk_inventory_user foreign key fk_inventory_user(ID_APP_USER) references APP_USER(ID_APP_USER), constraint fk_inventory_material foreign key fk_inventory_material(ID_MATERIAL) references material (ID_MATERIAL) ); create table PLACE( ID_PLACE bigint(19) not null auto_increment, CODE varchar(255), NAME varchar(50), DESCRIPTION varchar(255), FLOOR int, X_COORD int, Y_COORD int, ID_PLACE_TYPE bigint(19), ID_MATERIAL bigint(19), primary key (ID_PLACE), constraint fk_place_place_type foreign key fk_place_place_type(ID_PLACE_TYPE) references PLACE_TYPE(ID_PLACE_TYPE), constraint fk_place_material foreign key fk_place_material (ID_MATERIAL) references MATERIAL(ID_MATERIAL) ); create table USER_ACTIVITY( ID_USER_ACTIVITY BIGINT(19) NOT NULL AUTO_INCREMENT, ID_APP_USER BIGINT(19), ACTIVITY varchar(255), ID_MATERIAL bigint(19), MATERIAL_AMOUNT numeric(19,2), START_TIME DATETIME, PRIMARY KEY (ID_USER_ACTIVITY), constraint fk_user_user_activity foreign key fk_user_user_activity (ID_APP_USER) references APP_USER (ID_APP_USER), constraint fk_activity_material foreign key fk_activity_material (ID_MATERIAL) references MATERIAL (ID_MATERIAL) ); create table USER_ROLE( ID_USER_ROLE bigint(19) not null auto_increment, ID_APP_USER bigint (19), ROLE varchar(255), primary key (ID_USER_ROLE), constraint fk_user_user_role foreign key fk_user_user_role (ID_APP_USER) references APP_USER(ID_APP_USER) ); --changeset hanuska1:insert-data insert into material (name) values ("GOLD"), ("FOOD"), ("WOOD"), ("STONE"), ("WORKER"); insert into place_type (place_type, img_url, activity) values ("Naleziště", null, "MINE"), ("Obchod", "money_icon.png", null), ("Tržiště", null, null); --changeset hanuska1:create-3 alter table material add column DEFAULT_AMOUNT int; update material set default_amount = 100; --changeset hanuska1:create-4 alter table user_activity add column ID_PLACE bigint(19); alter table user_activity add column STOP_TIME datetime; alter table user_activity add constraint fk_user_activity_place foreign key fk_user_activity_place (ID_PLACE) references PLACE(ID_PLACE); --changeset hanuska1:create-5 create table USER_PLACE( ID_USER_PLACE bigint(19) not null auto_increment, ID_APP_USER bigint(19), ID_PLACE bigint(19), primary key (ID_USER_PLACE), constraint fk_user_place_user foreign key fk_user_place_user (ID_APP_USER) references app_user(id_app_user), constraint fk_user_place_place foreign key fk_user_place_place(ID_PLACE) references PLACE(ID_PLACE) ); --changeset hanuska1:insert-2 update place_type set activity = "BUY", img_url = "shop_icon.png" where id_place_type=2; update place_type set activity = "CHANGE", img_url="stall_icon.png" where id_place_type = 3; insert into place_type (place_type, img_url, activity) values ("Staveniště", "house_icon.png", "BUILD"); alter table material add column ICON_NAME varchar(255); update material set icon_name = "money_icon.png" where id_material = 2; update material set icon_name = "apple_icon.png" where ID_MATERIAL = 2; update material set icon_name = "tree_icon.png" where id_material = 3; update material set icon_name = "mountain_icon.png" where id_material = 4; update material set icon_name = "worker_icon.png" where id_material = 5; <file_sep>/** * */ package cz.hanusova.fingerprintgame.builder; import cz.hanusova.fingerprintgame.model.Item; import cz.hanusova.fingerprintgame.model.ItemType; /** * @author khanusova * */ public class ItemBuilder { public Item build(int level) { Item item = new Item(); item.setLevel(level); item.setItemType(createType()); return item; } private ItemType createType() { ItemType type = new ItemType(); type.setIdItemType(1l); type.setPrice(100); return type; } } <file_sep>package cz.hanusova.fingerprintgame.utils; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; public final class UserUtils { private UserUtils() { } /** * @return Uzivatelske jmeno aktualne prihlaseneho uzivatele */ public static String getActualUsername() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); return auth.getName(); } /** * @return Aktualne prihlaseny uzivatel */ public static User getActualUser() { User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return user; } } <file_sep>/** * */ package cz.hanusova.fingerprintgame.builder; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import cz.hanusova.fingerprintgame.model.AppUser; import cz.hanusova.fingerprintgame.model.Character; import cz.hanusova.fingerprintgame.model.Inventory; import cz.hanusova.fingerprintgame.model.Material; /** * @author khanusova * * Class for creating new {@link AppUser} entities for testing purposes * */ public class UserBuilder { /** * * @return new {@link AppUser} with: * <ul> * <li>100 workers in inventory</li> * <li>10XP</li> * </ul> */ public AppUser build() { AppUser user = new AppUser(); user.setIdUser(1L); user.setInventory(createInventory()); user.setCharacter(createCharacter()); return user; } private List<Inventory> createInventory() { List<Inventory> inventory = new ArrayList<>(); Material worker = new Material(); worker.setName("WORKER"); inventory.add(new Inventory(worker, new BigDecimal("100"))); return inventory; } private Character createCharacter() { Character character = new Character(); character.setXp(50); return character; } } <file_sep>package cz.hanusova.fingerprintgame.controller.rest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import cz.hanusova.fingerprintgame.model.Place; import cz.hanusova.fingerprintgame.service.PlaceService; @RestController @RequestMapping("/android/1.0/qr") public class QrController { private static final Log logger = LogFactory.getLog(QrController.class); @Autowired private PlaceService placeService; @RequestMapping(value = "/{code}", produces = "application/json") public Place getPlaceByCode(@PathVariable("code") String code) { logger.info("Getting place with code " + code); Place place = placeService.getPlaceByCode(code); placeService.checkUserPlace(place); return place; } } <file_sep>package cz.hanusova.fingerprintgame.controller; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import cz.hanusova.fingerprintgame.model.AppUser; import cz.hanusova.fingerprintgame.service.UserService; //@Controller public class RegistrationController { @Autowired private UserService userService; @Autowired private MessageSource messageSource; // @RequestMapping(value = "/registration", method = RequestMethod.GET) public String getRequest(Model model) { AppUser user = new AppUser(); model.addAttribute("newUser", user); return "registration"; } // @RequestMapping(value = "/registration", method = RequestMethod.POST) public String registerUser(@ModelAttribute("newUser") AppUser user, Model model, Locale locale) { Boolean success = userService.saveUser(user); if (success) { model.addAttribute("message", messageSource.getMessage("login.user.added", null, locale)); return "login"; } else { model.addAttribute("errMsg", messageSource.getMessage("validation.login.exists", null, locale)); return "registration"; } } } <file_sep>/** * */ package cz.hanusova.fingerprintgame.service; import java.math.BigDecimal; import cz.hanusova.fingerprintgame.model.AppUser; import cz.hanusova.fingerprintgame.model.Material; import cz.hanusova.fingerprintgame.model.Place; import cz.hanusova.fingerprintgame.model.UserActivity; /** * @author khanusova * */ public interface InventoryService { /** * Subtracts given worker amount from user's repository * * @param workerAmount * amount of workers that user has started to use. If user has * stopped some activity, this parameter should be negative so as * amount is added * @param user * @return actual worker amount */ public BigDecimal updateWorkerAmount(Float workerAmount, AppUser user); /** * @param amount * amount of stone that user used. Pass negative parameter value * to increase stone amount in inventory * @param user * @return actual stone amount */ public BigDecimal updateStoneAmount(Float amount, AppUser user); /** * @param amount * amount of wood that user used. Pass negative parameter value * to increase wood amount in inventory * @param user * @return actual wood amount */ public BigDecimal updateWoodAmount(Float amount, AppUser user); /** * @param amount * amount of food that user used. Pass negative parameter value * to increase food amount in inventory * @param user * @return actual food amount */ public BigDecimal updateFoodAmount(Float amount, AppUser user); /** * @param amount * amount of gold that user used. Pass negative parameter value * to increase gold amount in inventory * @param user * @return actual gold amount */ public BigDecimal updateGoldAmount(Float amount, AppUser user); // /** // * Adds mined material // * // * @param place // * {@link Place} where mining takes place // * @param user // * {@link AppUser} who is mining // * @param workers // * amount of workers mining // */ // public void addMining(Place place, AppUser user, float workers); /** * Subtracts material as rent for houses that user has built * * @param activity * currently running building {@link UserActivity} * @param user * {@link AppUser} */ public void payRent(UserActivity activity, AppUser user); /** * Starts mining with given amount of workers and subtracts food for them * * @param place * @param user * @param workers */ void mine(Place place, AppUser user, float workers); // /** // * Subtracts food for actually mining workers // * // * @param workers // * number of workers mining // * @param user // * {@link AppUser} // * @return <code>true</code> if user has enough food for workers otherwise // * returns <code>false</code> // */ // boolean feedWorkers(float workers, AppUser user); /** * Finds out if user has enough food to feed workers * * @param workers * float value of workers amount * @param user * {@link AppUser} * @return <code>true</code> if user has enough food for given amount of * workers */ boolean hasEnoughFood(float workers, AppUser user); /** * Finds out if user has enough gold to pay rent for his workers * * @param workers * float value of workers amount * @param user * @return <code>true</code> if user has enough gold to pay rent */ boolean hasEnoughGold(float workers, AppUser user); /** * Stops activity for building houses and subtracts workers from user's * inventory * * @param activity * {@link UserActivity} for building houses * @param user */ void stopBuilding(UserActivity activity, AppUser user); /** * Updates material amount for user * * @param material * {@link Material} that should be updated * @param user * {@link AppUser} * @param workers * amount of workers that mine this material */ void updateMaterial(Material material, AppUser user, float workers); }<file_sep>jdbc.url=jdbc:mysql://localhost:3306/fingerprint_game jdbc.username=root jdbc.password=<PASSWORD> jdbc.driver=com.mysql.jdbc.Driver hibernate.dialect=org.hibernate.dialect.MySQLDialect <file_sep>/** * */ package cz.hanusova.fingerprintgame.dto; import java.util.ArrayList; import java.util.List; import cz.hanusova.fingerprintgame.model.Character; import cz.hanusova.fingerprintgame.model.Inventory; import cz.hanusova.fingerprintgame.model.Item; import cz.hanusova.fingerprintgame.model.Place; import cz.hanusova.fingerprintgame.model.Role; import cz.hanusova.fingerprintgame.model.UserActivity; /** * @author khanusova * */ public class UserDTO { private Long idUser; private String username; private String password; private String stagname; private Character character; private List<Inventory> inventory = new ArrayList<>(); private List<Role> roles = new ArrayList<>(); private List<UserActivity> activities = new ArrayList<>(); private List<Place> places = new ArrayList<>(); private List<Item> items = new ArrayList<>(); /* * Information to send to client */ private int placeProgress; private int level = 1; private int levelProgress; /* * Getters and setters */ /** * @return the idUser */ public Long getIdUser() { return idUser; } /** * @param idUser * the idUser to set */ public void setIdUser(Long idUser) { this.idUser = idUser; } /** * @return the username */ public String getUsername() { return username; } /** * @param username * the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the password */ public String getPassword() { return password; } /** * @param password * the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the stagName */ public String getStagname() { return stagname; } /** * @param stagname * the stagname to set */ public void setStagname(String stagName) { this.stagname = stagName; } /** * @return the character */ public Character getCharacter() { return character; } /** * @param character * the character to set */ public void setCharacter(Character character) { this.character = character; } /** * @return the inventory */ public List<Inventory> getInventory() { return inventory; } /** * @param inventory * the inventory to set */ public void setInventory(List<Inventory> inventory) { this.inventory = inventory; } /** * @return the activities */ public List<UserActivity> getActivities() { return activities; } /** * @param activities * the activities to set */ public void setActivities(List<UserActivity> activities) { this.activities = activities; } /** * @return the roles */ public List<Role> getRoles() { return roles; } /** * @param roles * the roles to set */ public void setRoles(List<Role> roles) { this.roles = roles; } /** * @return the places */ public List<Place> getPlaces() { return places; } /** * @param places * the places to set */ public void setPlaces(List<Place> places) { this.places = places; } /** * @return the items */ public List<Item> getItems() { return items; } /** * @param items * the items to set */ public void setItems(List<Item> items) { this.items = items; } /** * @return the placeProgress */ public int getPlaceProgress() { return placeProgress; } /** * @param placeProgress * the placeProgress to set */ public void setPlaceProgress(int placeProgress) { this.placeProgress = placeProgress; } /** * @return the level */ public int getLevel() { return level; } /** * @param level * the level to set */ public void setLevel(int level) { this.level = level; } /** * @return the levelProgress */ public int getLevelProgress() { return levelProgress; } /** * @param levelProgress * the levelProgress to set */ public void setLevelProgress(int levelProgress) { this.levelProgress = levelProgress; } } <file_sep>package cz.hanusova.fingerprintgame.service.impl; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cz.hanusova.fingerprintgame.model.AppUser; import cz.hanusova.fingerprintgame.model.Place; import cz.hanusova.fingerprintgame.model.UserActivity; import cz.hanusova.fingerprintgame.repository.PlaceRepository; import cz.hanusova.fingerprintgame.repository.UserRepository; import cz.hanusova.fingerprintgame.service.ActivityService; import cz.hanusova.fingerprintgame.service.PlaceService; import cz.hanusova.fingerprintgame.utils.UserUtils; @Service public class PlaceServiceImpl implements PlaceService { private static final Log logger = LogFactory.getLog(PlaceServiceImpl.class); private PlaceRepository placeRepository; private ActivityService activityService; private UserRepository userRepository; @Autowired public PlaceServiceImpl(PlaceRepository placeRepository, ActivityService activityService, UserRepository userRepository) { this.placeRepository = placeRepository; this.activityService = activityService; this.userRepository = userRepository; } @Override @Transactional public Place getPlaceByCode(String code) { return placeRepository.findFirstByCode(code); } @Override @Transactional public void checkUserPlace(Place place) { String username = UserUtils.getActualUsername(); AppUser user = userRepository.findByUsername(username); List<Place> userPlaces = user.getPlaces(); Place userPlace = userPlaces.stream().filter(p -> p.equals(place)).findAny().orElse(null); if (userPlace == null) { logger.info("Adding place ID " + place.getIdPlace() + " to user " + username); userPlaces.add(place); userRepository.save(user); } } @Override @Transactional public AppUser startActivity(AppUser user, Place place, Float workerAmount) { logger.info("Starting activity for user " + user.getUsername() + " at place ID " + place.getIdPlace() + " with " + workerAmount + " workers"); List<UserActivity> activities = user.getActivities(); UserActivity existingActivity = null; if (activities != null && !activities.isEmpty()) { existingActivity = activities.stream().filter(a -> a.getPlace().equals(place)).findAny().orElse(null); } if (existingActivity == null && workerAmount != 0) { activityService.startNewActivity(place, workerAmount, user); } else if (workerAmount == 0) { activityService.removeActivity(existingActivity, user); } else if (!workerAmount.equals(existingActivity.getMaterialAmount())) { activityService.changeActivity(existingActivity, workerAmount, user); } return user; } } <file_sep>/** * */ package cz.hanusova.fingerprintgame.service; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import cz.hanusova.fingerprintgame.builder.UserBuilder; import cz.hanusova.fingerprintgame.dto.UserDTO; import cz.hanusova.fingerprintgame.model.AppUser; import cz.hanusova.fingerprintgame.repository.MaterialRepository; import cz.hanusova.fingerprintgame.repository.PlaceRepository; import cz.hanusova.fingerprintgame.repository.UserRepository; import cz.hanusova.fingerprintgame.service.impl.UserServiceImpl; /** * @author khanusova * */ public class UserServiceTest { private UserService userService; private UserBuilder userBuilder = new UserBuilder(); @Mock UserRepository userRepositoryMock; @Mock MaterialRepository materialRepositoryMock; @Mock PlaceRepository placeRepositoryMock; AppUser userMock; @Before public void init() { MockitoAnnotations.initMocks(this); userService = new UserServiceImpl(userRepositoryMock, materialRepositoryMock, placeRepositoryMock); userMock = userBuilder.build(); Mockito.when(userRepositoryMock.findByUsername(Mockito.anyString())).thenReturn(userMock); } @Test public void fillPropertiesTest() { UserDTO user = userService.getUserDTOByUsername("username"); Assert.assertNotEquals("Level should be calculated", 0, user.getLevel()); Assert.assertNotEquals("Level progress should be calculated", 0, user.getLevelProgress()); Assert.assertNotEquals("Place progress should be calculated", 0, user.getPlaceProgress()); } @Test public void testUserLevel() { userMock.getCharacter().setXp(6); UserDTO user = userService.getUserDTOByUsername("username"); Assert.assertEquals("User with 6 XP should be in second level", 2, user.getLevel()); Assert.assertNotEquals("Level progress should be set", 0, user.getLevelProgress()); } } <file_sep>/** * */ package cz.hanusova.fingerprintgame.service.impl; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import cz.hanusova.fingerprintgame.model.ActivityEnum; import cz.hanusova.fingerprintgame.model.AppUser; import cz.hanusova.fingerprintgame.model.Place; import cz.hanusova.fingerprintgame.model.UserActivity; import cz.hanusova.fingerprintgame.repository.UserActivityRepository; import cz.hanusova.fingerprintgame.repository.UserRepository; import cz.hanusova.fingerprintgame.service.ActivityService; import cz.hanusova.fingerprintgame.service.InventoryService; /** * @author khanusova * */ @Service public class ActivityServiceImpl implements ActivityService { private static final Log logger = LogFactory.getLog(ActivityServiceImpl.class); private UserActivityRepository userActivityRepository; private UserRepository userRepository; private InventoryService inventoryService; @Autowired public ActivityServiceImpl(UserActivityRepository userActivityRepository, UserRepository userRepository, InventoryService inventoryService) { this.userActivityRepository = userActivityRepository; this.userRepository = userRepository; this.inventoryService = inventoryService; } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public void startNewActivity(Place place, Float amount, AppUser user) { user = userRepository.findOne(user.getIdUser()); // Refresh user for // this transaction UserActivity activity = new UserActivity(place, amount); userActivityRepository.save(activity); user.getActivities().add(activity); int xp = user.getCharacter().getXp(); user.getCharacter().setXp(xp + 1); updateInventory(place, user, amount); userRepository.save(user); } private void updateInventory(Place place, AppUser user, Float amount) { ActivityEnum placeActivity = place.getPlaceType().getActivity(); switch (placeActivity) { case MINE: inventoryService.updateWorkerAmount(amount, user); inventoryService.updateMaterial(place.getMaterial(), user, amount); break; case BUILD: inventoryService.updateStoneAmount(amount * 10, user); inventoryService.updateWoodAmount(amount * 10, user); inventoryService.updateWorkerAmount(amount * -1, user); break; default: break; } } @Override @Transactional public void removeActivity(UserActivity activity, AppUser user) { ActivityEnum placeActivity = activity.getPlace().getPlaceType().getActivity(); switch (placeActivity) { case MINE: inventoryService.updateWorkerAmount(activity.getMaterialAmount() * -1, user); user.getActivities().remove(activity); userActivityRepository.delete(activity); break; case BUILD: inventoryService.stopBuilding(activity, user); break; default: break; } userRepository.save(user); } @Override @Transactional public void changeActivity(UserActivity activity, Float workersAmount, AppUser user) { ActivityEnum placeActivity = activity.getPlace().getPlaceType().getActivity(); switch (placeActivity) { case MINE: inventoryService.updateWorkerAmount(activity.getMaterialAmount() * -1, user); activity.setMaterialAmount(workersAmount); activity.setStartTime(new Date()); inventoryService.updateWorkerAmount(workersAmount, user); break; case BUILD: inventoryService.stopBuilding(activity, user); startNewActivity(activity.getPlace(), workersAmount, user); break; default: break; } } @Scheduled(fixedRate = 60_000) @Override @Transactional public void checkRunningActivities() { logger.info("Checking activities"); List<AppUser> users = userRepository.findAll(); for (AppUser user : users) { for (UserActivity activity : user.getActivities()) { Place place = activity.getPlace(); ActivityEnum activityType = place.getPlaceType().getActivity(); switch (activityType) { case MINE: float workers = activity.getMaterialAmount(); if (inventoryService.hasEnoughFood(workers, user)) { inventoryService.mine(place, user, workers); } else { inventoryService.updateWorkerAmount(workers * -1, user); userActivityRepository.delete(activity); logger.info("User " + user.getUsername() + " does not have enough food to feed workers. Stopping activity at place ID " + place.getIdPlace()); } break; case BUILD: if (inventoryService.hasEnoughGold(activity.getMaterialAmount(), user)) { inventoryService.payRent(activity, user); } else { logger.info("User " + user.getUsername() + " does not have enough gold to pay workers living at place ID " + place.getIdPlace() + ". "); inventoryService.stopBuilding(activity, user); } break; default: break; } } } } } <file_sep>package cz.hanusova.fingerprintgame.model; import cz.hanusova.fingerprintgame.utils.EnumTranslator; public enum ActivityEnum { MINE, CHANGE, BUILD, BUY; public String getKey() { return EnumTranslator.getMessageKey(this); } } <file_sep>package cz.hanusova.fingerprintgame.repository; import org.springframework.data.jpa.repository.JpaRepository; import cz.hanusova.fingerprintgame.model.Place; public interface PlaceRepository extends JpaRepository<Place, Long> { public Place findFirstByCode(String code); // @Query("select p from Place p left join fetch p.resources r where p.code // = :code") // public Place findFirstByCodeFetch(@Param("code")String code); } <file_sep>/** * */ package cz.hanusova.fingerprintgame.controller.rest; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import cz.hanusova.fingerprintgame.dto.UserDTO; import cz.hanusova.fingerprintgame.model.AppUser; import cz.hanusova.fingerprintgame.model.Item; import cz.hanusova.fingerprintgame.model.Place; import cz.hanusova.fingerprintgame.repository.UserRepository; import cz.hanusova.fingerprintgame.service.ItemService; import cz.hanusova.fingerprintgame.service.PlaceService; import cz.hanusova.fingerprintgame.service.UserService; import cz.hanusova.fingerprintgame.utils.UserUtils; /** * @author khanusova * * Controller for handling activities from mobile application * */ @RestController @RequestMapping("/android/1.0/activity") public class ActivityController { @Autowired private UserRepository userRepository; @Autowired private ItemService itemService; @Autowired private PlaceService placeService; @Autowired private UserService userService; @RequestMapping("/start") public UserDTO startActivity(@RequestParam Integer materialAmount, @RequestBody Place place) { String username = UserUtils.getActualUsername(); AppUser user = userRepository.findByUsername(username); user = placeService.startActivity(user, place, Float.valueOf(materialAmount)); return userService.getUserDTOByUsername(user.getUsername()); } @RequestMapping("/buy") public UserDTO buyItem(@RequestBody List<Item> items) { return userService.getUserDTOByUsername(itemService.addItem(items).getUsername()); } @RequestMapping("/getItems") public List<Item> getPossibleItems() { return itemService.getItemsForActualUser(); } } <file_sep>/** * */ package cz.hanusova.fingerprintgame.dto; /** * DTO class for sending ranking info * * @author khanusova * */ public class RankingDTO { private String username; private int xp; /** * */ public RankingDTO(String username, int xp) { this.username = username; this.xp = xp; } /** * @return the username */ public String getUsername() { return username; } /** * @param username * the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the xp */ public int getXp() { return xp; } /** * @param xp * the xp to set */ public void setXp(int xp) { this.xp = xp; } } <file_sep>/** * */ package cz.hanusova.fingerprintgame.service.impl; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.RawJsonDocument; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import cz.hanusova.fingerprintgame.fingerprint.Fingerprint; import cz.hanusova.fingerprintgame.service.FingerprintService; /** * Service class for handling fingerprints * * @author khanusova * */ @Service public class FingerprintServiceImpl implements FingerprintService { private static final Log logger = LogFactory.getLog(FingerprintServiceImpl.class); private static final SimpleDateFormat SDF = new SimpleDateFormat("ddMMyyyy_HHmmssSSS"); private static final String SEPARATOR = "_"; private static final String APP_NAME = "fingerprint-game"; @Value("${file.fingerprint.name}") private String fileName; @Value("${file.fingerprint.path}") private String path; @Value("${profile.name}") private String profile; @Override public void saveFingerprint(Fingerprint fingerprint) { fingerprint.setAppName(APP_NAME); Date now = new Date(); String name = fileName + SEPARATOR + SDF.format(now); saveToFile(fingerprint, name); saveToCouchbase(fingerprint); } /** * Saves fingerprint to new separate file * * @param fingerprint */ private void saveToFile(Fingerprint fingerprint, String fileName) { String name = path + fileName; logger.info("Saving new fingerprint to file " + name); try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(name))) { writer.write(fingerprint.toString()); logger.info("Fingerprint successfully saved"); } catch (IOException e) { logger.error("Could not save fingerprint to file", e); } } private void saveToCouchbase(Fingerprint fingerprint) { CouchbaseCluster cluster = CouchbaseCluster.create(); try { ObjectMapper mapper = new ObjectMapper(); String fpString = mapper.writeValueAsString(fingerprint); Bucket bucket = cluster.openBucket("beacon"); bucket.upsert(RawJsonDocument.create(UUID.randomUUID().toString(), fpString)); } catch (JsonProcessingException e) { logger.error("could not deserialize fingerprint", e); } cluster.disconnect(); } } <file_sep>/** * */ package cz.hanusova.fingerprintgame.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.Immutable; /** * Type of item to increase material gaining * * @author khanusova * */ @Entity @Immutable @Table(name = "ITEM_TYPE") public class ItemType implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID_ITEM_TYPE") private Long idItemType; @Column(name = "NAME") private String name; @Enumerated(EnumType.STRING) private ActivityEnum activity; @ManyToOne @JoinColumn(name = "ID_MATERIAL") private Material material; @Column(name = "PRICE") private Integer price; /** * @return the idItemType */ public Long getIdItemType() { return idItemType; } /** * @param idItemType * the idItemType to set */ public void setIdItemType(Long idItemType) { this.idItemType = idItemType; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the activity */ public ActivityEnum getActivity() { return activity; } /** * @param activity * the activity to set */ public void setActivity(ActivityEnum activity) { this.activity = activity; } /** * @return the material */ public Material getMaterial() { return material; } /** * @param material * the material to set */ public void setMaterial(Material material) { this.material = material; } /** * @return the price */ public Integer getPrice() { return price; } /** * @param price * the price to set */ public void setPrice(Integer price) { this.price = price; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (!(obj instanceof ItemType)) { return false; } ItemType objItemType = (ItemType) obj; return objItemType.getIdItemType() == this.getIdItemType(); } } <file_sep>/** * */ package cz.hanusova.fingerprintgame.service; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import cz.hanusova.fingerprintgame.builder.ItemBuilder; import cz.hanusova.fingerprintgame.builder.UserBuilder; import cz.hanusova.fingerprintgame.model.AppUser; import cz.hanusova.fingerprintgame.model.Item; import cz.hanusova.fingerprintgame.repository.ItemRepository; import cz.hanusova.fingerprintgame.repository.ItemTypeRepository; import cz.hanusova.fingerprintgame.repository.UserRepository; import cz.hanusova.fingerprintgame.service.impl.ItemServiceImpl; /** * @author khanusova * */ public class ItemServiceTest { private ItemService itemService; @Mock private UserRepository userRepositoryMock; @Mock private ItemRepository itemRepositoryMock; @Mock private ItemTypeRepository itemTypeRepositoryMock; @Mock private InventoryService inventoryServiceMock; @Mock private UserService userServiceMock; private UserBuilder userBuilder; private ItemBuilder itemBuilder; @Before public void init() { MockitoAnnotations.initMocks(this); itemService = new ItemServiceImpl(userRepositoryMock, itemTypeRepositoryMock, itemRepositoryMock, inventoryServiceMock, userServiceMock); userBuilder = new UserBuilder(); itemBuilder = new ItemBuilder(); } @Test public void addItemTest() { AppUser user = userBuilder.build(); signInUser(user); int itemSize = user.getItems().size(); List<Item> items = new ArrayList<>(); items.add(itemBuilder.build(1)); itemService.addItem(items); Assert.assertNotEquals("User should get new item to his item list", itemSize, user.getItems().size()); } @Test public void addItemUpdateTest() { AppUser user = userBuilder.build(); signInUser(user); Item item1 = itemBuilder.build(1); user.getItems().add(item1); Assert.assertEquals("User should have only one item", 1, user.getItems().size()); List<Item> items = new ArrayList<>(); items.add(itemBuilder.build(2)); itemService.addItem(items); Assert.assertEquals("Size of item list should not change", 1, user.getItems().size()); } @Test public void addItemInventoryUpdateTest() { AppUser user = userBuilder.build(); signInUser(user); List<Item> items = new ArrayList<>(); items.add(itemBuilder.build(1)); itemService.addItem(items); Mockito.verify(inventoryServiceMock, Mockito.times(1)).updateGoldAmount(Mockito.anyFloat(), Mockito.any()); } private void signInUser(AppUser user) { Mockito.when(userServiceMock.getActualUser()).thenReturn(user); } } <file_sep>/** * */ package cz.hanusova.fingerprintgame.controller.rest; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import cz.hanusova.fingerprintgame.dto.RankingDTO; import cz.hanusova.fingerprintgame.service.RankingService; /** * @author khanusova * */ @RestController @RequestMapping("/android/1.0/ranking") public class RankingController { @Autowired private RankingService rankingService; @RequestMapping("/get") public List<RankingDTO> getRanking() { return rankingService.getRankings(); } } <file_sep>/** * */ package cz.hanusova.fingerprintgame.service; import java.util.List; import cz.hanusova.fingerprintgame.model.AppUser; import cz.hanusova.fingerprintgame.model.Item; /** * @author khanusova * */ public interface ItemService { /** * Adds {@link Item}s to user's item list. If user actually has some item of * the same type, this method deletes it * * @param items * @return updated {@link AppUser} */ AppUser addItem(List<Item> items); /** * Gets items that user can buy * * @return */ List<Item> getItemsForActualUser(); } <file_sep>package cz.hanusova.fingerprintgame.model; import cz.hanusova.fingerprintgame.utils.EnumTranslator; @Deprecated public enum MaterialEnum { GOLD("GOLD"), FOOD("FOOD"), WOOD("WOOD"), STONE("STONE"), WORKER("WORKER"); private String name; private MaterialEnum(String name) { this.name = name; } @Override public String toString() { return this.name; } public String getKey() { return EnumTranslator.getMessageKey(this); } } <file_sep>logout=Odhl�sit save=Ulo\u017Eit administration.header=Administrace administration.list=Seznam u\u017Eivatel\u016F administration.maps=Mapy administration.materials.add=P\u0159�idat suroviny login.error=\u0160patn\u011B zadan� u\u017Eivatelsk� jm�no nebo heslo login.header=P\u0159ihl�\u0161en� login.login=P\u0159ihl�sit login.logout=Odhl�sit login.denied=P\u0159�stup odep\u0159en login.password=<PASSWORD> login.register=Registrovat login.username=U\u017Eivatelsk� jm�no login.user.added=U\u017Eivatel �sp\u011B\u0161n\u011B p\u0159id�n Material.GOLD=Zlato Material.FOOD=J�dlo Material.WOOD=D\u0159evo Material.STONE=K�men Material.WORKER=Pracovn�ci overview.header=P�\u0159ehled overview.floor.map=Mapa - {0}. patro overview.maps=Mapy overview.maps.1=1. patro overview.maps.2=2. patro overview.maps.3=3. patro overview.maps.4=4. patro overview.inventory=Suroviny policy.header=Zásady ochrany osobních údajů policy.text=Aplikace všechny údaje zadané uživatelem používá pouze pro svůj chod a nikomu dalšímu nejsou poskytovány. Anonymní údaje uživatelů budou dále zpracovány v diplomové práci na téma gamifikace sběru rádiových fingerprintů. registration.header=Registrace nového uživatele registration.username=Uživatelské jméno registration.password1=<PASSWORD> registration.password2=<PASSWORD> registration.stagname=UHK login registration.save=Registrovat validation.email.invalid=\u0160patn\u011B zadaný e-mail validation.password=<PASSWORD> validation.login.exists=Zadan� u\u017Eivatelsk� jm�no ji\u017E existuje<file_sep>profile.name=local app.default.food=100 app.default.gold=100 app.default.stone=100 app.default.wood=100 app.default.worker=50<file_sep>package cz.hanusova.fingerprintgame.service; import cz.hanusova.fingerprintgame.model.AppUser; import cz.hanusova.fingerprintgame.model.Place; public interface PlaceService { /** * Finds place by given code saved in QR code * * @param code * String code from URL * @return {@link Place} with given code */ public Place getPlaceByCode(String code); /** * Starts new activity and updates user's amount of workers in inventory * * @param user * {@link AppUser} who is starting new activity * @param place * {@link Place} where new activity is * @param workerAmount * amount of workers for activity * @return updated {@link AppUser} */ public AppUser startActivity(AppUser user, Place place, Float workerAmount); /** * Checks if given place is already in user's list. If not, adds it there * * @param place * {@link Place} actually found by user */ public void checkUserPlace(Place place); } <file_sep>package cz.hanusova.fingerprintgame.security; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import cz.hanusova.fingerprintgame.model.AppUser; import cz.hanusova.fingerprintgame.model.Role; class CustomUserDetails implements UserDetails { private List<GrantedAuthority> authorities; private String password; private String username; public CustomUserDetails(AppUser user) { this.username = user.getUsername(); this.password = <PASSWORD>(); this.authorities = getUserAuthorities(user); } private List<GrantedAuthority> getUserAuthorities(AppUser user) { List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); for (Role role : user.getRoles()) { grantedAuthorities.add(new SimpleGrantedAuthority(role.toString())); } return grantedAuthorities; } public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } public String getPassword() { return <PASSWORD>; } public String getUsername() { return username; } public boolean isAccountNonExpired() { return true; } public boolean isAccountNonLocked() { return true; } public boolean isCredentialsNonExpired() { return true; } public boolean isEnabled() { return true; } } <file_sep>--liquibase formatted sql --changeset hanuska1:items-1 CREATE TABLE ITEM_TYPE( ID_ITEM_TYPE BIGINT(19) NOT NULL AUTO_INCREMENT, NAME VARCHAR(255), ACTIVITY VARCHAR(255), ID_MATERIAL BIGINT(19), PRIMARY KEY (ID_ITEM_TYPE), CONSTRAINT FK_ITEMTYPE_MATERIAL FOREIGN KEY (ID_MATERIAL) REFERENCES MATERIAL(ID_MATERIAL) ); CREATE TABLE ITEM( ID_ITEM BIGINT(19) NOT NULL AUTO_INCREMENT, NAME VARCHAR(255), ID_ITEM_TYPE BIGINT(19), LEVEL INT, IMG_URL VARCHAR(255), PRIMARY KEY (ID_ITEM), CONSTRAINT FK_ITEM_ITEMTYPE FOREIGN KEY (ID_ITEM_TYPE) REFERENCES ITEM_TYPE(ID_ITEM_TYPE) ); CREATE TABLE USER_ITEM( ID_USER_ITEM BIGINT(19) NOT NULL AUTO_INCREMENT, ID_APP_USER BIGINT(19), ID_ITEM BIGINT(19), PRIMARY KEY (ID_USER_ITEM), CONSTRAINT FK_USERITEM_USER FOREIGN KEY (ID_APP_USER) REFERENCES APP_USER(ID_APP_USER), CONSTRAINT FK_USERITEM_ITEM FOREIGN KEY (ID_ITEM) REFERENCES ITEM(ID_ITEM) ); --changeset hanuska1:items-2 insert into item_type (name, activity, id_material) values ("AXE", "MINE", 3), ("PICKAXE", "MINE", 4), ("LADDER", "MINE", 2); insert into item(name, id_item_type, level, img_url) values ("Sekera", 1, 1, "axe.jpg"), ("Bronzová sekera", 1, 2, "bronze_axe.jpg"), ("Stříbrná sekera", 1, 3, "siver_axe.jpg"), ("Zlatá sekyra", 1, 4, "gold_axe.jpg"), ("Krumpáč", 2, 1, "pickaxe.jpg"), ("Bronzový krumpáč", 2, 2, "bronze_pickaxe.jpg"), ("Stříbrný krumpáč", 2, 3, "silver_pickaxe.jpg"), ("Zlatý krumpáč", 2, 4, "gold_pickaxe.jpg"), ("Žebřík", 3, 1, "ladder.jpg"), ("Bronzový žebřík", 3, 2, "bronze_ladder.jpg"), ("Stříbrný žebřík", 3, 3, "silver_ladder.jpg"), ("Zlatý žebřík", 3, 4, "gold_ladder.jpg"); --changeset hanuska1:items-3 alter table item_type add PRICE bigint(19) default 100; <file_sep> /** * */ package cz.hanusova.fingerprintgame.model; import java.io.Serializable; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author khanusova * */ public class StagUser implements Serializable { @JsonProperty("osCislo") private List<String> userNumbers; private String userName; private String role; private String ucitIdNo; public List<String> getUserNumbers() { return userNumbers; } public void setUserNumbers(List<String> userNumbers) { this.userNumbers = userNumbers; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName * the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the role */ public String getRole() { return role; } /** * @param role * the role to set */ public void setRole(String role) { this.role = role; } /** * @return the ucitIdNo */ public String getUcitIdNo() { return ucitIdNo; } /** * @param ucitIdNo * the ucitIdNo to set */ public void setUcitIdNo(String ucitIdNo) { this.ucitIdNo = ucitIdNo; } } <file_sep>url=jdbc:mysql://localhost:3306/fingerprint_game changeLogFile=src/main/resources/liquibase/0.0.1/changelog-master.xml username=root password=<PASSWORD><file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cz.uhk.hanusova</groupId> <artifactId>fingerprint-game</artifactId> <packaging>war</packaging> <version>0.0.1</version> <name>Fingerprint game</name> <url>http://maven.apache.org</url> <developers> <developer> <id>hanuska1</id> <name><NAME></name> <email><EMAIL></email> <timezone>GMT+1</timezone> <organization>UHK</organization> <roles> <role>Developer</role> </roles> </developer> </developers> <!-- <scm> --> <!-- <developerConnection>scm:git:https://github.com/khanusova90/fingerprint-game</developerConnection> --> <!-- <tag>fingerprint-game-0.0.1</tag> --> <!-- </scm> --> <properties> <spring.version>4.2.3.RELEASE</spring.version> <spring.data>1.9.2.RELEASE</spring.data> <spring.data.commons>1.11.2.RELEASE</spring.data.commons> <spring.data.couchbase>2.2.3.RELEASE</spring.data.couchbase> <spring-sec.version>4.0.3.RELEASE</spring-sec.version> <spring.batch.version>3.0.7.RELEASE</spring.batch.version> <liquibase.version>3.4.1</liquibase.version> <mysql.version>5.1.37</mysql.version> <couchbase.version>2.4.4</couchbase.version> <log4j.version>1.2.17</log4j.version> <slf4j.version>1.7.13</slf4j.version> <hibernate.version>5.0.7.Final</hibernate.version> <thymeleaf.version>2.1.4.RELEASE</thymeleaf.version> <gson.version>2.6.2</gson.version> <json.version>20160212</json.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>2.0.2-beta</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.0-b01</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>el-impl</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.codehaus.mojo</groupId> <artifactId>properties-maven-plugin</artifactId> <version>1.0.0</version> </dependency> <!-- S P R I N G --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>${spring.data}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> <version>${spring.data.commons}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-couchbase</artifactId> <version>${spring.data.couchbase}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${spring-sec.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring-sec.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring-sec.version}</version> </dependency> <dependency> <groupId>org.springframework.batch</groupId> <artifactId>spring-batch-core</artifactId> <version>${spring.batch.version}</version> </dependency> <!-- Thymeleaf --> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring4</artifactId> <version>${thymeleaf.version}</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>${thymeleaf.version}</version> <exclusions> <exclusion> <artifactId>javassist</artifactId> <groupId>org.javassist</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> <version>2.1.2.RELEASE</version> </dependency> <!-- J S O N --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.7.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.3</version> </dependency> <!-- C O U C H B A S E --> <dependency> <groupId>com.couchbase.client</groupId> <artifactId>java-client</artifactId> <version>${couchbase.version}</version> </dependency> <!-- D A T A B A S E --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.3.4.Final</version> </dependency> <!-- Liquibase --> <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>${liquibase.version}</version> </dependency> <!-- Logging --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <!-- Mapping --> <dependency> <groupId>org.modelmapper</groupId> <artifactId>modelmapper</artifactId> <version>0.7.7</version> </dependency> </dependencies> <build> <finalName>fingerprint-game</finalName> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.liquibase</groupId> <artifactId>liquibase-maven-plugin</artifactId> <version>${liquibase.version}</version> <configuration> <propertyFile>src/main/config/${build.profile.id}/liquibase.properties</propertyFile> <!-- <logging>debug</logging> --> </configuration> <executions> <execution> <id>update</id> <goals> <goal>update</goal> </goals> </execution> <execution> <id>rollback</id> <goals> <goal>rollback</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.5.3</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <profiles> <profile> <id>local</id> <activation> <activeByDefault>true</activeByDefault> </activation> <build> <resources> <resource> <directory>src/main/config/local</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <filtering>true</filtering> </resource> </resources> </build> <properties> <build.profile.id>local</build.profile.id> </properties> </profile> <profile> <id>test</id> <build> <resources> <resource> <directory>src/main/config/test</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <filtering>true</filtering> </resource> </resources> </build> <properties> <build.profile.id>test</build.profile.id> </properties> </profile> <profile> <id>production</id> <build> <resources> <resource> <directory>src/main/config/production</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <filtering>true</filtering> </resource> </resources> </build> <properties> <build.profile.id>production</build.profile.id> </properties> </profile> </profiles> </project> <file_sep>package cz.hanusova.fingerprintgame.model; import java.math.BigDecimal; 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.validation.constraints.Min; import javax.validation.constraints.NotNull; /** * Trida reprezentujici inventar uzivatele. Ke kazdemu typu zdroje ma ulozene * mnozstvi * * @author <NAME> * */ @Entity(name = "INVENTORY") public class Inventory { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID_INVENTORY") private Long idInventory; @NotNull @Min(value = 0) private BigDecimal amount = BigDecimal.ZERO; @ManyToOne @JoinColumn(name = "ID_MATERIAL") private Material material; public Inventory(Material material, BigDecimal amount) { this.material = material; this.amount = amount; } /** * Creates Inventory for given {@link Material} with its default value * defined by {@link Material#getDefaultAmount()} * * @param material */ public Inventory(Material material) { this.material = material; this.amount = new BigDecimal(material.getDefaultAmount()); } public Inventory() { } public Long getIdInventory() { return idInventory; } public void setIdInventory(Long idInventory) { this.idInventory = idInventory; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } /** * @return the material */ public Material getMaterial() { return material; } /** * @param material * the material to set */ public void setMaterial(Material material) { this.material = material; } } <file_sep>url=jdbc:mysql://localhost:3306/fingerprint-game?useUnicode=true&characterEncoding=utf-8 changeLogFile=src/main/resources/liquibase/0.0.1/changelog-master.xml username=root password=<file_sep>function f1() { var token1 = $('input#csrf-token').attr("content"); $.ajax({ type: "POST", beforeSend: function (request) { request.setRequestHeader("X-CSRF-TOKEN", token1); } }); }<file_sep>profile.name=production app.default.food=100 app.default.gold=100 app.default.stone=100 app.default.wood=100 app.default.worker=50<file_sep>window.onload = function () { document.getElementById("password").onchange = validatePassword; document.getElementById("password2").onchange = validatePassword; } function validatePassword(){ var pass2=document.getElementById("password2").value; var pass1=document.getElementById("password").value; if(pass1!=pass2) document.getElementById("password2").setCustomValidity(/*[[${#validation.password}]]*/ "<PASSWORD>"); else document.getElementById("password2").setCustomValidity(''); }
a612ff1fafc88d2a45b975fb32d73a95a31248d6
[ "SQL", "JavaScript", "Maven POM", "INI", "Java" ]
38
Java
khanusova90/fingerprint-game
d12808e6a8795f5259f5874a285b8b79d9def537
e2d3229c04cf39428187123d8491f94f029fc3a3
refs/heads/master
<repo_name>NickoManu/manuel<file_sep>/Esercitazioni 1.1/Es1_1_4/src/Es1_1_4.java /*Data una matrice effettuare la trasposta della stessa.*/ import java.util.Scanner; public class Es1_1_4 { public static void main(String [] args) { Scanner kb = new Scanner (System.in); int r=0, c=0, n=0; System.out.println("inserire il numero di righe della matrice: "); r = kb.nextInt(); System.out.println("inserire il numero di colonne della matrice: "); c = kb.nextInt(); int[][] matrix = new int[r][c]; int[][] matrixT = new int [c][r]; System.out.println("Riempimento Matrice"); for(int i=0; i<r; i++) { for(int j=0; j<c; j++) { System.out.println("Riga: " + i + " Colonna: " + j); System.out.println("inserisci numero: "); n=kb.nextInt(); matrix[i][j]=n; } } System.out.println(""); System.out.println("La Matrice inserita e': "); for(int i=0; i<r; i++) { System.out.println(""); for(int j=0; j<c; j++) { System.out.print(matrix[i][j] + " "); } } for(int i=0; i<r; i++) { for(int j=0;j<c;j++) { matrixT[j][i]=matrix[i][j]; } } System.out.println(""); System.out.println("La Matrice trasposta e': "); for(int i=0; i<c; i++) { System.out.println(""); for(int j=0; j<r; j++) { System.out.print(matrixT[i][j] + " "); } } kb.close(); } } <file_sep>/ClientServer/src/DatagramSender.java import java.net.*; import java.io.*; import java.util.Scanner; public class DatagramSender { public static void main(String [] args) { System.out.println("Client"); try { InetAddress receiverHost = InetAddress.getByName("localhost"); int receiverPort = 2000; String message = "messaggio protocollo udp"; DatagramSocket mySocket = new DatagramSocket(); byte [] buffer = message.getBytes(); DatagramPacket datagram = new DatagramPacket(buffer, buffer.length,receiverHost,receiverPort); // mySocket.send(datagram); Scanner k=new Scanner (System.in); String m=null; do { System.out.println("Inserisci messaggio da inviare al server:"); m = k.next(); buffer = m.getBytes(); datagram = new DatagramPacket(buffer, buffer.length,receiverHost,receiverPort); mySocket.send(datagram); }while(m.equals("end")); k.close(); mySocket.close(); }catch(Exception e){ e.printStackTrace(); } } } <file_sep>/Esercitazioni_2/Es2_1/src/Stagista.java public class Stagista extends Person { private int numberOfPresence; private int idNumber; public Stagista() { super(); numberOfPresence=0; idNumber=0; } public Stagista (String s, String n, String tc, String c, int nop, int id) { super(s,n, tc, c); numberOfPresence=nop; idNumber=id; } public int getNumberOfPresence() { return numberOfPresence; } public void setNumberOfPresence(int numberOfPresence) { this.numberOfPresence = numberOfPresence; } public int getIdNumber() { return idNumber; } public void setIdNumber(int idNumber) { this.idNumber = idNumber; } public String toString() { return super.toString() + " NumberOfPresence: " + this.getNumberOfPresence() + " IdNumber: " + this.getIdNumber(); } } <file_sep>/Esercitazioni2_1/Es_2_1_2/src/Luminosita.java public interface Luminosita { public void setLuminosita(int l); public void brighter(); public void darker(); } <file_sep>/Esercitazioni_2/Es2_3/src/Vehicle.java public class Vehicle { private String targa; private String marca; private String modello; private boolean guasto; public Vehicle() { targa=null; marca=null; modello=null; guasto=false; } public Vehicle(String t, String m, String mo, boolean g) { targa=t; marca=m; modello=mo; guasto=g; } public String getTarga() { return targa; } public void setTarga(String targa) { this.targa = targa; } public String getMarca() { return marca; } public void setMarca(String marca) { this.marca = marca; } public String getModello() { return modello; } public void setModello(String modello) { this.modello = modello; } public boolean getGuasto() { return guasto; } public void setGuasto(boolean guasto) { this.guasto = guasto; } public String toString() { return "Targa: " + this.getTarga() + " Marca: " + this.getMarca() + " Modello: " + this.getModello() + " Guasto: " + this.getGuasto(); } } <file_sep>/Esercizi_Classi_Astratte_Interfacce/Cl_As_2_con_CA/src/Cl_As_2_con_CA.java /*Esercizio 2 Con Classe Astratta Scrivere un programma che simuli il lancio di un dado e di una moneta stampandone il risultato; con e senza l'utilizzo di una classe astratta che rappresenti i comportamenti comuni degli oggetti dado e moneta istanziati. */ public class Cl_As_2_con_CA { public static void main(String [] args) { Dado d= new Dado(); System.out.println("Lancio dado: " + d.lancio()); Moneta m= new Moneta(); System.out.println("Lancio Moneta: " + m.lancio()); } } <file_sep>/Esercitazioni2_1/Es_2_1_2/src/Riproducibile.java public interface Riproducibile { public void setDurata(int d); public void play(); public void setVolume(int v); public void weaker(); public void louder(); } <file_sep>/Esercizi_da_finire/Esercitazioni 3_1/Es3_1_1/src/Es3_1_1.java /*Esercizio 1 Realizzare il metodo static LinkedList<Integer> creaRandom(int n, int max) che genera una lista costituita da n valori interi random tra 0 e max-1. Suggerimento : Per la generazione dei valori casuali far riferimento alla classe java.util.Random ed in particolare al metodo nextInt(int). In alternativa si può usare il metodo Math.random() che però restituisce un valore double tra 0 e 1 che andrà opportunamente scalato e convertito ad intero. Parte 2 Realizzare il metodo static void stampa(Iterator<Integer> i) che stampa gli elementi dell’iteratore nella forma <elem1>,<elem2>,…., <elemN> Parte 3 Realizzare il metodo static void provaEx1() che, utilizzando i metodi appena creati, crei un vettore di 20 elementi random (sia ordinato che non) e li stampa. Questo metodo andrà poi chiamato dal main per i test di correttezza. Riassunto : ripetere gli esercizi utilizzando l’ArrayList al posto della LinkedList. */ import java.util.*; public class Es3_1_1 { public static LinkedList<Integer> creaRandom(int n, int max){ LinkedList<Integer> lista = new LinkedList<Integer>(); int num=0; Random ran = new Random(); for(int i=0; i<n; i++) { num=ran.nextInt(max-1); lista.add(num); } return lista; } public static void stampa(Iterator<Integer> i) { while(i.hasNext()) { System.out.print(i.next() + ","); } System.out.println(""); } public static void provaEx1() { LinkedList<Integer> lista = creaRandom(20, 100); Iterator<Integer> i = lista.iterator(); //stampa lista non ordinata System.out.println("Lista Non Ordinata"); stampa(i); //ordina lista e stampa lista ordinata System.out.println("Lista Ordinata"); Collections.sort(lista); i=lista.iterator(); stampa(i); } public static void main(String [] args) { provaEx1(); } } <file_sep>/Esercitazioni 1/EsArray4/src/EsArray4.java /* Scrivere un programma / metodo che date due sequenze di stringhe, ciascuna di 5 elementi, * stampi il messaggio "OK" se almeno una stringa della prima sequenza compare anche nella seconda, * altrimenti sarÓ stampato il messaggio "KO". Qualora vengano trovate due stringhe uguali i confronti tra le sequenze * devono essere interrotti. */ public class EsArray4 { public static void main (String [] args) { String[] s1 = {"ciao" , " mare" , "casa" , "giardino" , "fiori"}; String[] s2 = {"sole" , "estate", "casa" , "parco" , "ciaof" }; int n=0; for(int i = 0; i < s1.length; i++) { for(int j = 0; j < s2.length; j++) { if(s1[i].equals(s2[j])) { n = 1; break; } } } if(n==1) System.out.println("OK"); else System.out.println("KO"); } } <file_sep>/Esercitazioni_2/Es2_1/src/Person.java public class Person { private String surname; private String name; private String taxCode; private String city; public Person () { surname=null; name=null; taxCode=null; city=null; } public Person (String s, String n, String tc, String c) { surname=s; name=n; taxCode=tc; city=c; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTaxCode() { return taxCode; } public void setTaxCode(String taxCode) { this.taxCode = taxCode; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String toString() { return "Nome: "+ this.getName() + " Cognome: " + this.getSurname() + " CodiceFiscale: " + this.getTaxCode() + " Citta': " + this.getCity(); } public int bornYear () { int by=0; String age; if(taxCode != null) { age = taxCode.substring(6, 8); by=Integer.parseInt(age); if(by>=0 && by <= 20) by=by+2000; else by=by+1900; } else { by=0; System.out.println("il codice fiscale non e' presente"); } return by; } } <file_sep>/Esercitazioni_2/Es2_2/src/TestEmployee.java /*Esercizio - 2. Scrivere una classe Employee (dipendente) che estende la classe Person. Ogni dipendente ha un proprio anno di assunzione e un proprio stipendio. Si definiscano costruttori e vari metodi get e set opportuni. Si ridefinisca inoltre il metodo visualize() opportunamente. Si definisca inoltre un metodo gainsMore che prende come parametro un altro oggetto Employee e restituisce true se l’oggetto corrente ha uno stipendio maggiore di quello ricevuto come parametro, o false altrimenti. Per testare la classe, scrivere un programma TestEmployee che crea tre oggetti della classe Employee e li visualizza in ordine di stipendio (usando il nuovo metodo per confrontare gli stipendi). */ import java.util.Scanner; public class TestEmployee { //controllo che la stringa inserita è un numero intero public static boolean isNumeric(String s) { if(s != null) { try { Integer.parseInt(s); return true; } catch(Exception e) { return false; } } else return false; } public static void main (String [] args) { Scanner kb = new Scanner(System.in); Employee [] e= new Employee [3]; String s; boolean control=false; System.out.println("Inserimento di 3 Dipendenti"); for(int i=0; i<e.length; i++) { e[i]=new Employee(); System.out.println("Inserimento Dipendente n°" + (i+1)); System.out.println("Nome: "); s = kb.next(); e[i].setName(s); System.out.println("Cognome: "); s = kb.next(); e[i].setSurname(s); do { System.out.println("CodiceFiscale: "); s = kb.next(); if(s.length()==16 && isNumeric(s.substring(6, 8)) ) control = true; else { control=false; System.out.println("Errore: il codice fiscale non e' corretto."); System.out.println("inserire il codice fiscale reale di 16 caratteri alfanumerici"); } }while(control != true); e[i].setTaxCode(s); System.out.println("Citta': "); s = kb.next(); e[i].setCity(s); do { System.out.println("Anno di Assunzione: "); s=kb.next(); if(isNumeric(s)) { e[i].setAnnoAssunzione(Integer.parseInt(s)); control=true; } else { System.out.println("Errore: L'anno di assunzione deve essere un numero intero"); control=false; } }while(control != true); do { System.out.println("Stipendio: "); s=kb.next(); if(isNumeric(s)) { e[i].setStipendio(Integer.parseInt(s)); control=true; } else { System.out.println("Errore: Lo stipendio deve essere un numero intero"); control=false; } }while(control != true); } //ordinamento crescente dei dipendenti in base allo stipendio Employee supp=new Employee(); for(int i=0; i<e.length-1;i++) { for(int j=i+1; j<e.length;j++) { if(e[i].gainsMore(e[j])) { supp=e[i]; e[i]=e[j]; e[j]=supp; } } } System.out.println("La lista dei dipendenti in ordine di stipendio: "); for(int i=0; i<e.length; i++){ System.out.println(e[i].visualize()); } kb.close(); } } <file_sep>/Esercizi_da_finire/Es3_1/src/Tessera.java public class Tessera { private int codice; private double credito; public int getCodice() { return codice; } public void setCodice(int codice) { this.codice = codice; } public double getCredito() { return credito; } public void setCredito(double credito) { this.credito = credito; } public String toString() { return "Codice: " + this.getCodice() + " Credito: " + this.getCredito(); } public void caricaTessera(double c) { this.setCredito((this.getCredito())+c); } public void leggiCredito(int c) { if(this.getCodice()==c) { System.out.println("il credito e': " + this.getCredito()); } else System.out.println("TesseraNonValida"); } } <file_sep>/Esercitazioni_2/Es2_4/src/Car.java public class Car extends Vehicle{ private String tipologia; public Car() { super(); tipologia=null; } public Car(String t, String m, String mo, boolean g, String tipo) { super(t,m,mo,g); tipologia=tipo; } public String getTipologia() { return tipologia; } public void setTipologia(String tipologia) { this.tipologia = tipologia; } public String toString() { return super.toString() + " Tipologia: " + this.getTipologia(); } } <file_sep>/Esercitazioni 1.1/Es1_1_1/src/Es1_1_1.java /*dato un array di interi, popolato casualmente, ordinarlo in ordine crescente e stampare a video * il risultato di tale ordinamento. */ public class Es1_1_1 { public static void main(String [] args) { int [] array = new int [20]; int supp=0; for(int i=0; i<array.length; i++) array[i]=(int)(Math.random()*100); for(int i=0; i<array.length-1; i++) { for(int j=i+1; j<array.length; j++) { if(array[i]>array[j]) { supp=array[i]; array[i]=array[j]; array[j]=supp; } } } for(int i=0; i<array.length; i++) System.out.print(array[i] + " "); } } <file_sep>/Esercitazioni 1/EsCicli3/src/EsCicli3.java /*Scrivere un programma / metodo che chiede all’utente di inserire una sequenza di caratteri * (chiedendo prima quanti caratteri voglia inserire) e li ristampa man mano che vengono inseriti. * L’intero procedimento (chiedere quanti caratteri voglia inserire, leggere i caratteri e man mano stamparli) * dovrà essere ripetuto 5 volte. Risolvere questo esercizio senza usare array. */ import java.util.Scanner; public class EsCicli3 { public static void main(String [] args) { Scanner kb = new Scanner(System.in); int i=0, max=0; String c=""; char car; while(i<5){ System.out.println("Quanti caratteri vuoi inserire? "); max=kb.nextInt(); while(max>0){ System.out.println("inserire carattere: "); c = kb.next(); car=c.charAt(0); System.out.println(car); max--; } i++; } kb.close(); } } <file_sep>/Esercizi_Classi_Astratte_Interfacce/Cl_As_2_no_CA/src/Moneta.java public class Moneta extends Sorte{ public int lancio() { int l= 1 + (int)(Math.random()*2); return l; } } <file_sep>/Esercitazioni_2/Es2_5/src/Question.java import java.util.Scanner; public class Question { private String domanda; private String rispostaCorretta; private int punteggio; public Question() { domanda=null; rispostaCorretta=null; punteggio=0; } public Question(String s, String c, int p) { domanda=s; rispostaCorretta=c; punteggio=p; } public String getDomanda() { return domanda; } public void setDomanda(String domanda) { this.domanda = domanda; } public String getRispostaCorretta() { return rispostaCorretta; } public void setRispostaCorretta(String rispostaCorretta) { this.rispostaCorretta = rispostaCorretta; } public int getPunteggio() { return punteggio; } public void setPunteggio(int punteggio) { this.punteggio = punteggio; } public int ask() { System.out.println(this.getDomanda()); Scanner kb=new Scanner (System.in); System.out.println("Inserisci la Risposta: "); String risposta=kb.next(); if(risposta.equalsIgnoreCase(this.rispostaCorretta)) this.punteggio=this.punteggio; else this.punteggio=0; kb.close(); return this.punteggio; } } <file_sep>/Esercizi_Classi_Astratte_Interfacce/Es_I_2/src/Comparable.java public interface Comparable { public int compare(Distributore d); } <file_sep>/Esercitazioni2_1/Es_2_1_2/src/RegistrazioneAudio.java public class RegistrazioneAudio extends ElementoMultimediale implements Riproducibile{ private int durata; private int volume; public RegistrazioneAudio(String t, int d, int v) { super(t); durata=d; volume=v; } public int getDurata() { return durata; } public void setDurata(int durata) { this.durata = durata; } public int getVolume() { return volume; } public void setVolume(int volume) { this.volume = volume; } public String toString() { return super.toString() + " Durata: " + this.getDurata() + " Volume: " + this.getVolume(); } //suppongo che il volume sia un valore compreso tra 0 e 100 //i metodi louder e weaker rispettivamente aumentano e diminuiscono il //valore del volume di 1; public void weaker() { if(this.getVolume()>0) this.setVolume((this.getVolume())-1); else System.out.println("Il volume e' al minimo"); System.out.println("Il volume attuale e': " + this.getVolume()); } public void louder() { if(this.getVolume()<100) this.setVolume((this.getVolume())+1); else System.out.println("Il volume e' al massimo"); System.out.println("Il volume attuale e': " + this.getVolume()); } public void play() { for(int i=0; i<this.getDurata(); i++) { System.out.print(this.getTitolo()); } for(int i=0; i<this.getVolume(); i++) { System.out.print("!"); } System.out.println(" "); } } <file_sep>/Esercitazioni_2/Es2_4/src/TestGarage.java /*Esercizio - 4. Scrivere una classe Garage che prevede solo un metodo repair() che utilizza veicoli (come definiti nell’esercizio precedente). Tale metodo prende un veicolo come parametro, ne cambia (se necessario) il valore della variabile booleana che descrive lo stato di guasto e restituisce come risultato il prezzo dell’intervento. Il prezzo deve variare a seconda che il veicolo fosse guasto o meno, e a seconda della tipologia di veicolo. Per testare le classi, scrivere un programma TestGarage che crea un certo numero di veicoli e un oggetto di tipo Garage, e usa il metodo repair() varie volte su oggetti diversi (guasti o meno) stampando i prezzi ottenuti. */ import java.util.Scanner; public class TestGarage { public static boolean isNumber(String s) { if(s!=null) { try { Integer.parseInt(s); return true; }catch(Exception e) { return false; } }else return false; } public static void main(String [] args) { Scanner kb = new Scanner(System.in); int scelta=0,cilindrata=0, m=10; boolean controllo=false, guasto=false; String targa,marca,modello,tipologia,s; do { System.out.println("Quanti veicoli vuoi inserire? - puoi inserire al max 10 veicoli"); s=kb.next(); if(isNumber(s)) { m=Integer.parseInt(s); if(m>0 && m<=10) controllo=true; else { System.out.println("Errore: puoi inserire da 1 a 10 veicoli"); controllo=false; } }else { System.out.println("Errore: il valore deve essere un numero intero"); controllo=false; } }while(controllo==false); Vehicle [] v= new Vehicle[m]; for(int i=0;i<v.length;i++) { do { System.out.println("che tipo di veicolo vuoi inserire?"); System.out.println("1 - Car"); System.out.println("2 - Motocycle"); s=kb.next(); if(isNumber(s)) { scelta=Integer.parseInt(s); if(scelta>0 && scelta<=2) controllo=true; else { System.out.println("Errore: scelta non disponibile"); controllo=false; } }else{ controllo=false; System.out.println("Errore: scelta errata, inserire scelta corretta"); } }while(controllo==false); System.out.println("Targa: "); targa=kb.next(); System.out.println("Marca: "); marca=kb.next(); System.out.println("Modello: "); modello=kb.next(); do { System.out.println("Guasto? - inserire true o false "); s=kb.next(); if(s.equalsIgnoreCase("true")) { guasto=true; controllo=true; } else { if(s.equalsIgnoreCase("false")) { guasto=false; controllo=true; } else { System.out.println("Errore: inserire true o false"); controllo=false; } } }while(controllo==false); switch(scelta) { case 1: System.out.println("Tipologia: "); tipologia=kb.next(); v[i] = new Car(targa,marca,modello,guasto,tipologia); break; case 2: do { System.out.println("Cilindrata: "); s=kb.next(); if(isNumber(s)) { controllo=true; cilindrata=Integer.parseInt(s); }else { System.out.println("Errore: La cilindrata deve essere un numero intero"); controllo=false; } }while(controllo==false); v[i] = new Motocycle(targa,marca,modello,guasto,cilindrata); break; default: System.out.println("scelta non consentita"); } } Garage g=new Garage(); //applico il metodo repair di Garage su tutti i veicoli for(int i=0; i<v.length;i++) { System.out.println("VEICOLO N° :" + i); System.out.println("Marca: " + v[i].getMarca()); System.out.println("Modello: " + v[i].getModello()); System.out.println("Targa: " + v[i].getTarga()); System.out.println("Guasto: " + v[i].getGuasto()); System.out.println("Costo riparazione veicolo: " + g.repair(v[i])); } kb.close(); } } <file_sep>/Esercizi_Classi_Astratte_Interfacce/Cl_As_2_no_CA/src/Dado.java public class Dado extends Sorte{ public int lancio() { int l= 1 + (int)(Math.random()*6); return l; } }<file_sep>/Esercitazioni_2/Es2_1/src/Es2_1.java /*Esercizio - 1. Creare una classe di nome Person con le variabili di istanza: surname, name, tax code e city di tipo stringa. La classe deve contenere un costruttore di default che inizializzi le variabili di istanza con NULL; un costruttore parametrico; i metodi set e get ed un metodo chiamato bornYear che a partire dal codice fiscale ricavi e restituisca l'anno di nascita di una persona. Creare un'applicazione Java che istanzi un oggetto della classe Person e ne visualizzi in seguito nome, cognome ed anno di nascita. Costruire una sottoclasse di Person, chiamata Stagista, che contiene 2 variabili di istanza entrambe di tipo intero: • numberOfPresence, che registra il numero di ore di presenza • idNumber (numero identificativo). La sottoclasse deve contenere un costruttore parametrico ed i metodi set e get. Creare tre oggetti di tipo Stagista memorizzarli in un array e visualizzare lo Stagista più giovane. */ import java.util.Scanner; public class Es2_1 { //con il metodo isNumeric verifico se la stringa s contiene un numero private static boolean isNumeric(String s) { if(s != null) { try { Integer.parseInt(s); return true; } catch(Exception e) { return false; } } else return false; } public static void main (String [] args) { Scanner kb=new Scanner (System.in); //istanzio oggetto della classe Person e ne visualizzo nome,cognome e anno di nascita Person p = new Person ("Rossi","Luca","RSSLCA97T06F205S","Milano"); System.out.println("Nome: " + p.getName()); System.out.println("Cognome: " + p.getSurname()); System.out.println("Anno di nascita: " + p.bornYear()); System.out.println(" "); String name, surname, tc, city, str; int st=0; boolean control=false; Stagista [] arrayS = new Stagista [3]; int j=0,age=0,aM=0; for(int i=0; i<arrayS.length; i++) { arrayS[i]=new Stagista(); System.out.println("Inserimento stagista n°" + (i+1)); System.out.println("Nome: "); name = kb.next(); arrayS[i].setName(name); System.out.println("Cognome: "); surname = kb.next(); arrayS[i].setSurname(surname); do { System.out.println("CodiceFiscale: "); tc = kb.next(); if(tc.length()==16 && isNumeric(tc.substring(6, 8)) ) control = true; else { control=false; System.out.println("il codice fiscale non e' corretto."); System.out.println("inserire il codice fiscale reale di 16 caratteri alfanumerici"); } }while(control != true); arrayS[i].setTaxCode(tc); System.out.println("Citta': "); city = kb.next(); arrayS[i].setCity(city); do { System.out.println("Numero ore di presenza: "); str=kb.next(); if(isNumeric(str)) { arrayS[i].setNumberOfPresence(Integer.parseInt(str)); control=true; } else { System.out.println("Le ore inserite devono essere un numero intero"); control=false; } }while(control != true); do { System.out.println("Numero identificativo: "); str=kb.next(); if(isNumeric(str)) { arrayS[i].setIdNumber(Integer.parseInt(str)); control=true; } else { System.out.println("l'ID deve essere un numero intero"); control=false; } }while(control != true); } j=1; aM=arrayS[0].bornYear(); st=0; while(j<arrayS.length) { age=arrayS[j].bornYear(); if(aM<age) { aM=age; st=j; } j++; } System.out.println("lo stagista più giovane e': "); System.out.println("Cognome: " + arrayS[st].getSurname()); System.out.println("Nome: " + arrayS[st].getName()); System.out.println("Anno: " + arrayS[st].bornYear()); kb.close(); } } <file_sep>/readme.md my app is my app<file_sep>/Esercitazioni_2/Es2_5/src/NumericQuestion.java import java.util.Scanner; public class NumericQuestion extends Question{ public NumericQuestion() { super(); } public NumericQuestion(String d, String r, int p) { super(d,r,p); } public int ask() { System.out.println(this.getDomanda()); Scanner kb=new Scanner (System.in); boolean controllo=false; String risposta; do { System.out.println("Inserisci il risultato numerico intero"); System.out.print("Risposta: "); risposta=kb.next(); System.out.println(" "); if(risposta!=null) { try { Integer.parseInt(risposta); controllo=true; } catch(Exception e) { System.out.println("Errore: inserire un valore numerico intero"); controllo=false; } }else { System.out.println("Inserire un valore numerico intero"); controllo=false; } }while(controllo==false); if(risposta.equals(this.getRispostaCorretta())) this.setPunteggio(this.getPunteggio()); else this.setPunteggio(0); return this.getPunteggio(); } } <file_sep>/Esercizi_Classi_Astratte_Interfacce/Cl_As_2_con_CA/src/Sorte.java public abstract class Sorte { //il metodo lancio restituisce l'esito intero del lancio public abstract int lancio(); } <file_sep>/javaIO/src/javaIO/java_IO.java package javaIO; import java.io.*; import java.util.Scanner; public class java_IO { public static void main(String [] args) throws IOException{ FileReader file = new FileReader("C:\\Users\\Manuel\\Desktop\\prova.txt"); BufferedReader b = new BufferedReader(file); String s; s=b.readLine(); System.out.println("Lettura da file: "); while(s!=null) { System.out.println(s); s=b.readLine(); } file.close(); System.out.println("Scrittura di double su file"); OutputStream stream = new FileOutputStream("C:\\Users\\Manuel\\Desktop\\provaScrittura.txt"); PrintWriter pw = new PrintWriter(stream,true); double num=42.42; pw.println(num); stream.close(); System.out.println("lettura da file double: "); FileReader fileR = new FileReader("C:\\Users\\Manuel\\Desktop\\provaScrittura.txt"); Scanner scan; scan= new Scanner(fileR); while(scan.hasNextDouble()) { System.out.println(scan.nextDouble()); } fileR.close(); } } <file_sep>/Esercitazioni_2/Es2_3/src/TestVehicles.java /*Esercizio - 3. Scrivere una classe Vehicle (veicolo) che prevede una targa, una marca e un modello. La classe prevede anche una variabile booleana che descrive se il veicolo è guasto. Aggiungere un costruttore opportuno e vari metodi get e set opportuni. Scrivere la classi Car e Motocycle che estendono la classe Vehicle. La classe Car prevede una stringa che ne descrive la tipologia ("utilitaria","station wagon", "SUV",....) mentre la classe Motocycle prevede un numero che ne descrive la cilindrata (50, 125, ....). Per testare le classi, scrivere un programma TestVehicles che crea un array inizializzato con veicoli delle varie tipologie. Alcuni dei veicoli inseriti nell’array dovranno diventare guasti. Il programma deve stampare la lista delle targhe dei veicoli guasti. */ import java.util.Scanner; public class TestVehicles { //verifico se una stringa passata come input è un numero public static boolean isNumber(String s) { if(s != null) { try { Integer.parseInt(s); return true; }catch(Exception e) { return false; } }else return false; } public static void main(String [] args) { Scanner kb = new Scanner(System.in); int scelta=0,cilindrata=0, m=10,pos=0; boolean controllo=false, guasto=false; String targa,marca,modello,tipologia,s; do { System.out.println("Quanti veicoli vuoi inserire? - puoi inserire al max 10 veicoli"); s=kb.next(); if(isNumber(s)) { m=Integer.parseInt(s); if(m>0 && m<=10) controllo=true; else { System.out.println("Errore: puoi inserire da 1 a 10 veicoli"); controllo=false; } }else { System.out.println("Errore: il valore deve essere un numero intero"); controllo=false; } }while(controllo==false); Vehicle [] v= new Vehicle[m]; for(int i=0;i<v.length;i++) { do { System.out.println("che tipo di veicolo vuoi inserire?"); System.out.println("1 - Car"); System.out.println("2 - Motocycle"); s=kb.next(); if(isNumber(s)) { scelta=Integer.parseInt(s); if(scelta>0 && scelta<=2) controllo=true; else { System.out.println("Errore: inserire o 1 o 2"); controllo=false; } }else{ controllo=false; System.out.println("Errore: scelta errata, inserire scelta corretta"); } }while(controllo==false); System.out.println("Targa: "); targa=kb.next(); System.out.println("Marca: "); marca=kb.next(); System.out.println("Modello: "); modello=kb.next(); do { System.out.println("Guasto? - inserire true o false "); s=kb.next(); if(s.equalsIgnoreCase("true")) { guasto=true; controllo=true; } else { if(s.equalsIgnoreCase("false")) { guasto=false; controllo=true; } else { System.out.println("Errore: inserire true o false"); controllo=false; } } }while(controllo==false); switch(scelta) { case 1: System.out.println("Tipologia: "); tipologia=kb.next(); v[i] = new Car(targa,marca,modello,guasto,tipologia); break; case 2: do { System.out.println("Cilindrata: "); s=kb.next(); if(isNumber(s)) { controllo=true; cilindrata=Integer.parseInt(s); }else { System.out.println("Errore: La cilindrata deve essere un numero intero"); controllo=false; } }while(controllo==false); v[i] = new Motocycle(targa,marca,modello,guasto,cilindrata); break; default: System.out.println("scelta non consentita"); } } //l'utente può scegliere quale veicolo rendere guasto o no do { do { System.out.println("Vuoi cambiare lo stato ''Guasto'' di un veicolo? "); System.out.println("1 - si"); System.out.println("2 - no"); s=kb.next(); if(isNumber(s)) { scelta=Integer.parseInt(s); if(scelta==1) { do { System.out.println("Inserire la posizione del veicolo da modificare"); s=kb.next(); if(isNumber(s)) { pos=Integer.parseInt(s); if(pos>=0 && pos<m) { System.out.println("lo stato del veicolo alla posizione " + pos + " e': " + v[pos].getGuasto()); if(v[pos].getGuasto()) v[pos].setGuasto(false); else v[pos].setGuasto(true); System.out.println("Il nuovo stato del veicolo alla posizione " + pos + " e': " + v[pos].getGuasto()); controllo=true; }else { System.out.println("Errore: inserire un numero intero da 0 a " + (m-1)); controllo=false; } }else { System.out.println("Errore: inserire un numero intero da 0 a " + (m-1)); controllo=false; } }while(controllo==false); }else { if(scelta==2) { System.out.println("Fine"); controllo=true; } else { System.out.println("Errore: Scelta non accettabile"); controllo=false; } } }else { System.out.println("Errore: la scelta deve essere 1 o 2"); controllo=false; } }while(controllo==false); }while(scelta!=2); //stampa la lista dei veicoli guasti System.out.println("Lista dei veicoli guasti: "); for(int i=0;i<v.length;i++) { if(v[i].getGuasto()) { System.out.println("Targa: " + v[i].getTarga()); System.out.println("Marca: " + v[i].getMarca()); System.out.println("Modello: " + v[i].getModello()); } } kb.close(); } } <file_sep>/Esercizi_Classi_Astratte_Interfacce/Cl_As_1/src/Parallelepipedo.java public class Parallelepipedo extends Oggetti{ public Parallelepipedo() { super(); } public Parallelepipedo(double area, double altezza) { super(area,altezza); } } <file_sep>/Esercitazioni2_1/Es2_1_1/src/ListaSpesa.java /*ESERCIZIO 1 Il gestore di un negozio associa a tutti i suoi Prodotti un codice a barre univoco, una descrizione sintetica del prodotto e il suo prezzo unitario. Realizzare una classe Prodotti con le opportune variabili d'istanza e metodi get. Aggiungere alla classe Prodotti un metodo applicaSconto che modifica il prezzo del prodotto diminuendolo del 5%. Aggiungere alla classe Prodotti un'implementazione specifica dei metodi ereditati dalla classe Object. Il gestore del negozio vuole fare una distinzione tra i prodotti Alimentari e quelli Non Alimentari . Ai prodotti Alimentari viene infatti associata una data di scadenza (si veda la classe Data), mentre a quelli Non Alimentari il materiale principale di cui sono fatti. Realizzare le sottoclassi Alimentari e NonAlimentari estendendo opportunamente la classe Prodotti. Modificare le due sottoclassi dell'esercizio specializzando il metodo applicaSconto in modo che nel caso dei prodotti Alimentari venga applicato uno sconto del 20% se la data di scadenza Ŕ a meno di 10 giorni dalla data attuale (si usi il metodo getDifference della classe Data), mentre nel caso dei prodotti Non Alimentari venga applicato uno sconto del 10% se il prodotto Ŕ composto da un materiale riciclabile (carta, vetro o plastica). Realizzare una classe ListaSpesa che chieda all'utente di inserire i prodotti acquistati e calcoli il totale della spesa applicando gli opportuni sconti se il cliente ha la tessera fedeltÓ. */ import java.util.Scanner; import java.util.Date; import java.text.SimpleDateFormat; import java.text.DateFormat; import java.text.ParseException; import java.util.Locale; public class ListaSpesa { public static boolean isNumber(String s) { if(s!=null) { try { Integer.parseInt(s); return true; }catch(Exception e) { return false; } }else { System.out.println("Inserire valore"); return false; } } public static void main(String [] args) { Scanner kb = new Scanner(System.in); int scelta=0, prodotto=0; double conto=0; boolean cartaFedelta=false, controllo=false; String s; Date d; //controllo carta fedeltÓ do { System.out.println("Hai la carta Fedelta' ? "); System.out.println("rispondere si o no"); s=kb.next(); if(s.equalsIgnoreCase("si")) { cartaFedelta=true; controllo=true; }else { if(s.equalsIgnoreCase("no")) { cartaFedelta=false; controllo=true; } else { System.out.println("Errore: puoi inserire solo si o no"); controllo=false; } } }while(controllo == false); Alimentari a1 = new Alimentari("PRSCCRD", "Prosciutto Crudo", 10.5, "23/9/2020"); Alimentari a2 = new Alimentari("PRSCCT", "Prosciutto Cotto", 10.7, "22/9/2020"); Alimentari a3 = new Alimentari("MSSCL", "Mais in scatola", 10.5, "20/9/2020"); NonAlimentari na1 = new NonAlimentari("BTTGLVTR", "Bottiglia di vetro", 1, "vetro"); NonAlimentari na2 = new NonAlimentari("RSMCRT", "<NAME>", 2.5, "carta"); NonAlimentari na3 = new NonAlimentari("BSTNLGN", "<NAME>", 1.5, "legno"); Prodotti [] p = {a1,a2,a3,na1,na2,na3}; //inserimento prodotti da parte del cliente do { System.out.println("1 - Inserisci Prodotto"); System.out.println("0 - Termina"); //controllo che la scelta sia corretta do { s=kb.next(); if(isNumber(s)) { scelta=Integer.parseInt(s); controllo=true; }else { System.out.println("Errore: inserire uno dei valori disponibili"); controllo=false; } }while(controllo==false); if(scelta==1) { //stampo la lista dei prodotti disponibili System.out.println("lista prodotti disponibili: "); for(int i=0; i<p.length; i++) { System.out.println("Prodotto n░: " + i + " Nome: " + p[i].getDescrizione() + " Prezzo: " + p[i].getPrezzo()); } //richiedo all'utente di inserire il numero corrispondente al prodotto do { System.out.println("inserire il numero del prodotto da 0 a " + (p.length-1)); s=kb.next(); if(isNumber(s)) { prodotto=Integer.parseInt(s); if(prodotto>=0 && prodotto<=(p.length-1)) controllo=true; else { System.out.println("Errore: scegliere uno dei prodotti dalla lista"); controllo=false; } }else { System.out.println("Errore: inserire una delle scelte disponibili"); controllo=false; } }while(controllo==false); //verifica sconto applicabile if(cartaFedelta) conto = conto + p[prodotto].applicaSconto(); else conto= conto + p[prodotto].getPrezzo(); }else { if(scelta==0) System.out.println("il conto totale e': " + conto); else { System.out.println("Errore"); } } }while(scelta!=0); kb.close(); } } <file_sep>/Esercizi_Classi_Astratte_Interfacce/Es_I_2/src/Distributore.java public class Distributore implements Comparable{ private String citta; private String proprietario; private int capacita; private double benzinaAttuale; public Distributore() { citta=null; proprietario=null; capacita=0; benzinaAttuale=0; } public Distributore(String citta, String proprietario, int capacita, double benzinaAttuale) { this.citta=citta; this.proprietario=proprietario; this.capacita=capacita; this.benzinaAttuale=benzinaAttuale; } public String getCitta() { return citta; } public void setCitta(String citta) { this.citta = citta; } public String getProprietario() { return proprietario; } public void setProprietario(String proprietario) { this.proprietario = proprietario; } public int getCapacita() { return capacita; } public void setCapacita(int capacita) { this.capacita = capacita; } public double getBenzinaAttuale() { return benzinaAttuale; } public void setBenzinaAttuale(double benzinaAttuale) { this.benzinaAttuale = benzinaAttuale; } public String toString() { return "Citta: "+ this.getCitta() + "Proprietario: " + this.getProprietario() + "Capacita: " + this.getCapacita() + "benzinaAttuale: " + this.getBenzinaAttuale(); } public double erogazione(double litri) { double prezzo=1.5; if(this.getBenzinaAttuale()>=litri) { this.setBenzinaAttuale((this.getBenzinaAttuale())-litri); System.out.println("Il conto e': " + (prezzo*litri)); return prezzo*litri; }else { System.out.println("Non c'e abbastanza benzina da erogare"); return 0; } } //il compare ritorna 0 se i distributori hanno la stessa capacita, 1 se l'attuale ha una capacitÓ maggiore di quello con //cui viene confrontato, -1 altrimenti public int compare(Distributore d) { if(this.getCapacita() > d.getCapacita()) return 1; else { if(this.getCapacita() < d.getCapacita()) return -1; else return 0; } } } <file_sep>/Esercitazioni_2/Es2_4/src/Garage.java //NB lo scopo del meccanico e' quello di farti pagare sempre quindi che il veicolo sia guasto o meno tu paghi qualcosa sempre public class Garage { public double repair(Vehicle v) { double prezzo=0; String classe = v.getClass().toString(); //imposto dei prezzi di base a seconda del tipo di veicolo if(classe.equals("class Car")) { prezzo = prezzo + 50; }else { if(classe.equals("class Motocycle")) prezzo = prezzo + 30; else System.out.println("il veicolo non e' ne un auto ne una moto"); } if(v.getGuasto()) { v.setGuasto(false); prezzo = prezzo + 100; }else prezzo=prezzo+20; return prezzo; } } <file_sep>/Esercitazioni 1/EsStringhe3/src/EsStringhe3.java /* Scrivere un programma / metodo che data una sequenza di stringhe, conclusa dalla stringa vuota, * stampi la somma delle lunghezze delle stringhe che iniziano con una lettera maiuscola. Per esempio, * se si immettono le stringhe "Albero", "foglia", "Radici", "Ramo", "fiore" (e poi "" per finire), il programma stampa 16. */ import java.util.Scanner; public class EsStringhe3 { public static void main(String [] args) { Scanner kb = new Scanner (System.in) ; String[] array = new String [20]; String s = ""; int i = 0, lunghezza=0, n=0; System.out.println("Il numero massimo di stringhe inseribili e' 20"); System.out.println("Per terminare premere invio"); System.out.println("inserisci una stringa: "); s = kb.nextLine(); while(s.length()!=0 && i<array.length) { n++; //incremento n ogni volta che inserisce una stringa diversa da quella vuota array[i] = s; i++; System.out.println("inserisci una stringa: "); s = kb.nextLine(); } for(int j=0; j <n; j++){ if(Character.isUpperCase(array[j].charAt(0))) { lunghezza = lunghezza + (array[j].length()); } } System.out.println(lunghezza); kb.close(); } } <file_sep>/Esercitazioni 1/EsCicli1/src/EsCicli1.java /*Scrivere un programma / metodo che data una sequenza di interi stampi "Tutti positivi e pari" se i numeri inseriti * sono tutti positivi e pari, altrimenti stampa "NO". Risolvere questo esercizio senza usare array. */ import java.util.Scanner; public class EsCicli1 { public static void main(String [] args) { Scanner kb = new Scanner (System.in); boolean pp = true; int num=0; System.out.println("Per terminare inserire 0"); do { System.out.println("inserisci un numero: "); num = kb.nextInt(); if(num < 0 || num%2 != 0) pp=false; }while(num!=0); if(pp) System.out.println("Tutti positivi e pari"); else System.out.println("NO"); kb.close(); } } <file_sep>/Esercizi_Classi_Astratte_Interfacce/Es_I_3/src/Operazione.java public interface Operazione { public void setNumA(int numA); public void setNumB(int numB); }
925b86570e59aefd3c23f719bfa285c66b52d1f1
[ "Markdown", "Java" ]
34
Java
NickoManu/manuel
d703b8969aa0b894bdd433592edc5230388520d0
74fc87f265a37c5b8e62c371f6e7ead679bc983c
refs/heads/master
<repo_name>4p00rv/affiliates<file_sep>/README.md # Affiliates [![Build Status](https://travis-ci.org/binary-com/affiliates.svg?branch=master)](https://travis-ci.org/binary-com/affiliates)<file_sep>/assets/js/code.js function collapseNavbar(){$(".navbar").offset().top>50?$(".navbar-fixed-top").addClass("top-nav-collapse"):$(".navbar-fixed-top").removeClass("top-nav-collapse")}$(window).scroll(collapseNavbar),$(document).ready(collapseNavbar),$(function(){document.documentElement.lang;$("#language_select select").on("change",function(){var a=$(this).val();window.location.href="/"+("en"===a?"":a)}),$(".nav-button").click(function(){$(".nav-button,.primary-nav").toggleClass("open")})}),$(function(){$("a.page-scroll").bind("click",function(a){var n=$(this);$("html, body").stop().animate({scrollTop:$(n.attr("href")).offset().top},800,"easeInOutExpo"),a.preventDefault()})}); var images = document.querySelectorAll("img"), options = { root: null, rootMargin: "0px", threshold: 0.1 }, fetchImage = function(a) { return ( console.log(a), new Promise(function(b, c) { var d = new Image(); (d.src = a), (d.onload = b), (d.onerror = c); }) ); }, loadImage = function(a) { var b = a.dataset.src; fetchImage(b).then(function() { a.src = b; }); }, handleIntersection = function(a) { a.forEach(function(c) { 0 < c.intersectionRatio && (console.log(c.intersectionRatio), loadImage(c.target)); }); }, observer = new IntersectionObserver(handleIntersection, options); if ( (images.forEach(function(a) { observer.observe(a); }), "IntersectionObserver" in window) ) var _observer = new IntersectionObserver(handleIntersection, options); else Array.from(images).forEach(function(a) { return loadImage(a); });
fee9b0931de515a4ee7504d8f1162dbb81c3daec
[ "Markdown", "JavaScript" ]
2
Markdown
4p00rv/affiliates
a67c87ca67901d40f6166baedd69ebf482dbfff4
9a57103a9d99017c81f66b6f0ebdebf977910238
refs/heads/main
<repo_name>babycake-swap/babycake-uikit<file_sep>/dist/widgets/Menu/components/NavMenu.d.ts import React from "react"; import { MenuEntry as MenuEntryType } from "../types"; interface Props { isPushed: boolean; links: Array<MenuEntryType>; } declare const NavMenu: React.FC<Props>; export default NavMenu;
ab2f7465b18b83d28261b11df2ad6432b47e876d
[ "TypeScript" ]
1
TypeScript
babycake-swap/babycake-uikit
ed1b12ef3e27905b1765f7beb1760d06d24f97f6
0b0dbb7ab8e9f8ca919d084abb8453ec165f2367
refs/heads/master
<file_sep>import { Context } from "koa"; import { employees } from '../data/employees'; const Vue = require('vue') const renderer = require('vue-server-renderer').createRenderer(); const app = new Vue({ data: { employees: employees }, template: ` <div> <table> <tbody> <tr> <th>UUID</th> <th>Name</th> <th>Address</th> <th>Age</th> </tr> <tr v-for="employee in employees"> <td>{{ employee.uuid }}</td> <td>{{ employee.name }}</td> <td>{{ employee.address }}</td> <td>{{ employee.age }}</td> </tr> </tbody> </table> </div> ` }); export default async (context: Context) => { // if(typeof context.request.query.nocompile == 'undefined'){ renderer.renderToString(app, (err, html) => { if (err) throw err context.body = html }) // } else { // context.set('content-type','text/html'); // context.body = renderer.renderToStream(app) // } }
fdb1235a3781a971aad3bb2c3a3b0b042c38bb09
[ "TypeScript" ]
1
TypeScript
xvaara/node-templating-benchmark
2d83001e37bb9365d667460eaa837d408e8a9f14
c8f5f15db8daa69cdb6a0d52e1237cb703df460d
refs/heads/master
<file_sep>import asyncio import time from PIL import Image import yaml from pyocr import pyocr from pyocr import builders from ADBlib import ADBlib import sys import re friends = int(input("Barátok:")) class Main: def __init__(self): with open("config.yaml", "r") as f: self.config = yaml.load(f, Loader=yaml.FullLoader) tools = pyocr.get_available_tools() self.tool = tools[0] self.friends = friends async def cap_and_crop(self, box_location): screencap = await self.p.screencap() crop = screencap.crop(self.config['locations'][box_location]) text = self.tool.image_to_string(crop).replace("\n", " ").replace(" ","").replace("|","l") return text async def tap(self, location): coordinates = self.config['locations'][location] await self.p.tap(*coordinates) async def start(self): friendfile = open('friends.txt', 'a') self.p = ADBlib() for i in range(self.friends): try: name = await self.cap_and_crop("friendname") await self.tap('tap') friendfile.write(name+'\n') except: print("Error") friendfile.close() if __name__ == '__main__': start_time = time.time() asyncio.run(Main().start()) runtime = time.time() - start_time print("--- %s Barát lementve. Lefutási idő: %s másodperc. SPF(Second Per Friend): %s ---" % (friends,runtime, runtime/friends)) <file_sep># PokeFriends This little python-adb script iterates over your pokemon go friends, gets its name, and saves it to the [friends.txt](https://github.com/davidfegyver/Pokefriends/blob/master/friends.txt) file. ## Installation Use the package manager [pip](https://pip.pypa.io/en/stable/) to install the requirements. ```bash pip install -r requirements.txt ``` You need the [Tesseract-OCR](https://tesseract-ocr.github.io/tessdoc/Downloads) too. ## Usage Edit the config.yaml They are the coordinates where the name/tap point is. ``` [x1,y1,x2,y2]: gives a box or [x,y]: gives a point ``` Enable USB debugging on your phone Open Pokemon Go Go to your friend list Tap your first friend Run the pokefriends.py ## Contributing Pull requests are welcome. ## TODO Auto config Comments for easier learning Auto friend count get Level + team <file_sep>from PIL import Image import asyncio import subprocess class ADBlib(object): async def screencap(self): await self.run("adb shell screencap -p /sdcard/screen.png") await self.run("adb pull /sdcard/screen.png .") image = Image.open("screen.png") return image async def run(self, args): args = args.split(" ") p = subprocess.Popen(args) stdout, stderr = p.communicate() return (stdout, stderr) async def tap(self, x, y): await self.run("adb shell input tap {} {} ".format(x,y)) async def swipe(self, x1, y1, x2, y2, duration=None): args = "adb shell input swipe {} {} {} {} ".format(x1,y1,x2,y2) if duration: args += duration await self.run(args)
16220104ec3b377765cd730958e7ab788e1d0683
[ "Markdown", "Python" ]
3
Python
davidfegyver/Pokefriends
8b9b445d68df4115a6b2d81ddd1350c53bebcc8e
4ac4266d5ec799c247aff3d352beb5d9ed48547c
refs/heads/master
<repo_name>lnsantos/panel-player-lineague-dragon<file_sep>/app/src/main/java/com/powernepo/lineaguedragon/MainActivity.kt package com.powernepo.lineaguedragon import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.databinding.DataBindingUtil import com.powernepo.lineaguedragon.dataBinding.ComponentNamesDataObservable import com.powernepo.lineaguedragon.databinding.ActivityMainBinding import com.powernepo.lineaguedragon.databinding.ComponentNamesBinding class MainActivity : AppCompatActivity() { private lateinit var binding : ActivityMainBinding private lateinit var componentBinding : ComponentNamesBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setupBinding() } override fun onResume() { super.onResume() componentBinding.data = ComponentNamesDataObservable("Lineague","Dragons") } private fun setupBinding(){ binding = DataBindingUtil.setContentView(this,R.layout.activity_main) componentBinding = binding.componentNameBinding } private fun startAnimationUpScreen(){ } }<file_sep>/app/src/main/java/com/powernepo/lineaguedragon/dataBinding/ComponentNamesDataObservable.kt package com.powernepo.lineaguedragon.dataBinding import androidx.databinding.BaseObservable import androidx.databinding.Bindable import com.powernepo.lineaguedragon.BR data class ComponentNamesDataObservable( private var _title: String?, private var _subTitle: String?) : BaseObservable(){ @Bindable var title: String? = _title set(value) { _title = value ?: "Error 404" notifyPropertyChanged(BR.title) } @Bindable var subTitle: String? = _subTitle set(value) { _subTitle = value ?: "Error 404" notifyPropertyChanged(BR.subTitle) } } <file_sep>/settings.gradle include ':app' rootProject.name = "Lineague Dragon"
290732f7aad84a2cc5ffa73f8329ef0d6495f4a9
[ "Kotlin", "Gradle" ]
3
Kotlin
lnsantos/panel-player-lineague-dragon
e06195049d37a4c9c7ecbf0502e2b728c67c1349
5b0a738fd3a1189110233eed1e8f7d8ecf044cb0
refs/heads/master
<repo_name>mkotsabiuk/PolisGarant<file_sep>/PolisGarant/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using MailKit.Net.Smtp; using Microsoft.AspNetCore.Mvc; using MimeKit; using PolisGarant.Models; namespace PolisGarant.Controllers { public class HomeController : Controller { public IActionResult Index() { ViewBag.Tab = "About"; return View(); } public IActionResult Purchase() { ViewBag.Tab = "Purchase"; return View(); } public IActionResult Contacts(string serviceType) { switch (serviceType) { case "standart": ViewBag.Message = "Мене зацікавило страхування \"Стандарт\". Прошу зв'язатися зі мною для подальшої взаємодії."; break; case "complex": ViewBag.Message = "Мене зацікавило комплексне страхування. Прошу зв'язатися зі мною для подальшої взаємодії."; break; case "travel": ViewBag.Message = "Мене зацікавило туристичне страхування. Прошу зв'язатися зі мною для подальшої взаємодії."; break; case "car": ViewBag.Message = "Мене зацікавило автострахування. Прошу зв'язатися зі мною для подальшої взаємодії."; break; case "property": ViewBag.Message = "Мене зацікавило страхування житла та нерухомості. Прошу зв'язатися зі мною для подальшої взаємодії."; break; case "document": ViewBag.Message = "Мене зацікавила нострифікація документів. Прошу зв'язатися зі мною для подальшої взаємодії."; break; case "job": ViewBag.Message = "Мене зацікавило працевлаштування в Чехії. Прошу зв'язатися зі мною для подальшої взаємодії."; break; case "certificates": ViewBag.Message = "Мене зацікавили довідки про несудимість з Польщі. Прошу зв'язатися зі мною для подальшої взаємодії."; break; default: ViewBag.Message = ""; break; } ViewBag.Tab = "Contacts"; return View(); } [HttpPost] public IActionResult SendMessage(string name, string email, string message, string number) { return View(@"~/Views/Home/Index.cshtml"); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } } <file_sep>/PolisGarant/Controllers/ServicesController.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using PolisGarant.Models; namespace PolisGarant.Controllers { public class ServicesController : Controller { public IActionResult Career() { ViewBag.Tab = "Services"; return View(); } public IActionResult CarInsurance() { ViewBag.Tab = "Services"; return View(); } public IActionResult ComplexInsurance() { ViewBag.Tab = "Services"; return View(); } public IActionResult Diploma() { ViewBag.Tab = "Services"; return View(); } public IActionResult PropertyInsurance() { ViewBag.Tab = "Services"; return View(); } public IActionResult StandardInsurance() { ViewBag.Tab = "Services"; return View(); } public IActionResult TravelInsurance() { ViewBag.Tab = "Services"; return View(); } public IActionResult Certificates() { ViewBag.Tab = "Services"; return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } } <file_sep>/README.md # PolisGarant Site for advertising services related to insurance, career and documents stratification. You can visit it [here](https://polisgarant.azurewebsites.net/) Wrote using `dotnet core 2.2 ASP.NET MVC` ## Demo ![](PolisGarant/wwwroot/img/polisgarant.gif) ## Run it locally Run command below one-by-one to start project locally `git clone https://github.com/mkotsabiuk/PolisGarant.git` `cd .\PolisGarant\PolisGarant\` `dotnet run` After that project will be running on the address https://localhost:5001
dee630a3c53517777902ebf82bc628a908c4cf22
[ "Markdown", "C#" ]
3
C#
mkotsabiuk/PolisGarant
9a09344c513a6ce63cd1e08867d7d908e6fb2553
612610f267ffa6096619170a3cfded7d077604ec
refs/heads/master
<file_sep># cerebro-npms > Cerebro plugin to search NPM packages via NPMS API <div align="center"> <img src="https://github.com/FreaKzero/cerebro-npms/raw/master/readme.gif" /> </div> ## Features - Shows Quality, Maintenance and Popularity Scores from NPMS - Shows if Package is deprecated, insecure or has a unstable version - All given package.json links can be visited ## Usage Search for NPM packages using `**npms** [search term]` - <kbd>Return</kbd> - Open a package on the NPM website. - <kbd>Alt+Return</kbd> - Copies `npm install $PACKAGE_NAME --save` to your clipboard <file_sep>import React from 'react'; import Preview from './Components/Preview'; import Subtitle from './Components/Subtitle'; import icon from './assets/npms-logo.png'; import {getPackages, termFilter} from './lib'; import {CONFIG_META_DISPLAY_ID} from './constants'; export const fn = ({ term, display, actions, hide }) => { const npmsTerm = termFilter(term); if (npmsTerm.hasTerm) { display({ icon, id: CONFIG_META_DISPLAY_ID, title: `Searching npms for ${npmsTerm.term}`, onSelect: event => { actions.open(`https://npms.io/search?q=${npmsTerm.term}`); } }); getPackages(npmsTerm.term).then(data => { hide(CONFIG_META_DISPLAY_ID) if (data.length > 0) { data.forEach(item => { display({ icon, title: item.package.name, subtitle: <Subtitle item={item} />, getPreview: () => <Preview item={item} actions={actions} />, onSelect: event => { (event.altKey) ? actions.copyToClipboard(`npm install ${item.package.name} --save`) : actions.open(item.package.links.npm); } }) }); } else { display({ icon, id: CONFIG_META_DISPLAY_ID, title: `No packages found` }); } }); } }<file_sep>import React, { Component, PropTypes } from 'react'; import Scores from '../Scores'; import Flags from '../Flags'; import Links from '../Links'; import Tags from '../Tags'; import ReactMarkdown from 'react-markdown'; import styles from './styles.css' export default ({ item, actions }) => ( <div className={styles.main}> <div className={styles.card} tabIndex='1'> <div className={styles.cardHeader}> <span className={styles.cardHeaderTitle}> <div className={styles.headline}> <div className={styles.left}> <h3>{item.package.name}</h3> <span className={styles.version}>({item.package.version})</span> <br /> <a className={styles.author} onClick={() => actions.open(`https://www.npmjs.com/~${item.package.publisher.username}`)} > {item.package.publisher.username} &lt;{item.package.publisher.email}&gt; </a> </div> <div className={styles.right}> <Flags flags={item.flags || {}} size='big' /> </div> </div> </span> </div> <div className={styles.cardContent}> <div className='content'> <div className={styles.markdown}> {item.package.description ? <ReactMarkdown source={item.package.description} /> : <p>No Description given</p> } </div> <Scores popularity={Math.trunc(item.score.detail.popularity * 100)} maintenance={Math.trunc(item.score.detail.maintenance * 100)} quality={Math.trunc(item.score.detail.quality * 100)} /> <Tags item={item} /> </div> </div> <Links item={item} actions={actions} /> </div> </div> )<file_sep>import React, { Component, PropTypes } from 'react'; import {getColor} from '../../lib'; import Flags from '../Flags'; import styles from './styles.css'; export default ({ item }) => ( <div> <span className={styles.mainscore} style={{ backgroundColor: getColor(Math.trunc(item.score.final * 100)) }}> {Math.trunc(item.score.final * 100)} </span> <Flags flags={item.flags || {}} size='small' /> </div> )<file_sep>import React, { Component, PropTypes } from 'react'; import {Circle} from 'rc-progress'; import {getColor} from '../../lib'; import styles from './styles.css' export default ({ popularity, maintenance, quality }) => ( <div className={styles.scores}> <div> <p>Quality</p> <h4 style={{color: getColor(quality)}}>{quality}%</h4> <Circle percent={quality} strokeWidth="10" strokeColor={getColor(quality)} strokeLinecap="butt" /> </div> <div> <p>Maintenance</p> <h4 style={{color: getColor(maintenance)}}>{maintenance}%</h4> <Circle percent={maintenance} strokeWidth="10" strokeColor={getColor(maintenance)} strokeLinecap="butt" /> </div> <div> <p>Popularity</p> <h4 style={{color: getColor(popularity)}}>{popularity}%</h4> <Circle percent={popularity} strokeWidth="10" strokeColor={getColor(popularity)} strokeLinecap="butt" /> </div> </div> )<file_sep>import React, { Component, PropTypes } from 'react'; import styles from './styles.css' export default ({flags, size}) => ( <span className={size === 'big' ? styles.big : styles.small}> <span className={styles.flags}> {flags.deprecated ? <span className={styles.flagDeprecated}>Deprecated</span> : null} {flags.insecure ? <span className={styles.flagInsecure}>insecure</span> : null} {flags.unstable ? <span className={styles.flagUnstable}>unstable</span> : null} </span> </span> )<file_sep>import debounce from 'p-debounce'; import request from 'request-promise-native'; import {memoize} from 'cerebro-tools'; import { CONFIG_MEMOIZE, CONFIG_DEBOUNCE } from './constants'; const packagesRequest = (query) => request({ url: 'https://api.npms.io/v2/search', qs: { q: query }, json: true }).then(data => data.results); export const termFilter = (term) => { const match = term.match(new RegExp(/^npms\s*(.*)/, 'i')); return { hasTerm: Boolean((match && match[1])) || false, term: Array.isArray(match) ? match[1].replace(/"/g, '\\"') : '', match: match } } export const getPackages = debounce( memoize( packagesRequest, CONFIG_MEMOIZE ), CONFIG_DEBOUNCE ); export const getColor = (percentage) => { // red #BE1C1C // orange #FFA500 // green #77ab59 let color; if (percentage < 30) { color = '#d41243' } else if (percentage < 60) { color = '#FFA500' } else { color = '#77ab59' } return color; }<file_sep>import React, { Component, PropTypes } from 'react'; import tagImg from '../../assets/tag.png'; import styles from './styles.css'; export default ({ item, actions }) => ( <div className={styles.tags}> {item.package.keywords ? item.package.keywords.map(item => ( <span className={styles.tag}> <img src={tagImg} className={styles.tagIcon} />&nbsp; {item} </span> )): ''} </div> )<file_sep>import React, { Component, PropTypes } from 'react'; import { KeyboardNav, KeyboardNavItem } from 'cerebro-ui' import styles from './styles.css'; export default ({ item, actions }) => ( <footer className={styles.cardFooter}> {item.package.links ? Object.keys(item.package.links).map((name, idx) => <KeyboardNavItem key={idx} className={styles.cardFooterItem} onSelect={() => { actions.open(item.package.links[name]); return actions.hideWindow(); }} > <a>{name}</a> </KeyboardNavItem> ): ''} </footer> )
2056ee1b41dd63a0ae0b3e75afd5a7c827a8a0fa
[ "Markdown", "JavaScript" ]
9
Markdown
FreaKzero/cerebro-npms
a34c0d34b27f8a482254c87be6789390ef77053b
9d677ef5cd28ae3bb203946143fd6771507283f2
refs/heads/master
<repo_name>donbalon4/API_Alfresco<file_sep>/APIAlfresco.php <?php /** * @author: <NAME> * @Version: 1.2 */ /** * @usage: * $conexion = APIAlfresco::getInstance(); * $conexion->connect($urlRepository,$User,$Pass); * $conexion->checkResponse(); * $conexion->setFolderByPath($folder); * * This API uses the files listed below, distributed by Apache Chemistry * for more info visit: https://chemistry.apache.org/php/phpclient.html */ require_once 'cmis_repository_wrapper.php'; require_once 'cmis_service.php'; class APIAlfresco { /** * @var APIALfresco */ private static $instance; /** * @var string */ public $urlRepository; /** * @var string */ public $user; /** * @var string */ public $pass; /** * @var CmisService */ public $repository; /** * @var string */ public $parentFolder; // Singleton public static function getInstance() { if (!isset(self::$instance)) { $obj = __CLASS__; self::$instance = new $obj(); } return self::$instance; } public function __clone() { trigger_error('Clone not allowed.', E_USER_ERROR); } /** * Function to connect to alfresco. * * @example $url = "http://127.0.0.1:8080/alfresco/cmisatom"; * * @param string $url * @param string $user * @param string $pass */ public function connect($url, $user, $pass) { $this->urlRepository = (string) $url; $this->user = (string) $user; $this->pass = (string) $pass; try { $this->repository = new CMISService($url, $user, $pass); } catch (CmisRuntimeException $e) { $this->processException($e); } } /** * Gets noderef (id) of a file in a path. * * @example $path = "/mySite/documentLibrary/myFolder/document.pdf"; * * @param string $path * @param array $options */ public function getObjectId($path, array $options = array()){ $path = $this->extractSpecialCharacters($path); $obj = $this->repository->getObjectByPath($path, $options); return $obj->id; } /** * Sets working folder. * * @example $folder = "/folder"; * * @param string $folder * @param array $options */ public function setFolderByPath($folder, array $options = array()) { try { $folder = $this->extractSpecialCharacters($folder); $obj = $this->repository->getObjectByPath($folder, $options); $properties = $obj->properties['cmis:baseTypeId']; if ($properties != 'cmis:folder') { throw new UnexpectedValueException('The object is not a folder'); } $this->parentFolder = $obj; } catch (Exception $e) { $this->processException($e); } } /** * Sets working folder by id. * * @example $id = "workspace://SpacesStore/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"; * * @param string $id * @param array $options */ public function setFolderById($id, array $options = array()) { try { $obj = $this->repository->getObject($id, $options); $properties = $obj->properties['cmis:baseTypeId']; if ($properties != 'cmis:folder') { throw new UnexpectedValueException('The object is not a folder', 1); } $this->parentFolder = $obj; } catch (Exception $e) { $this->processException($e); } } /** * Creates a folder inside workspace folder. * * @example $name = "folder"; * * @param string $name * @param array $properties * @param array $options * * @return stdClass */ public function createFolder($name, array $properties = array(), array $options = array()) { $name = $this->extractSpecialCharacters($name); $exists = $this->existsFolder($name); if ($exists) { throw new Exception('Error:->The folder named '.$name.' already exists', 1); } $name = $this->getBlankSpacesBack($name); return $this->repository->createFolder($this->parentFolder->id, $name); } /* * Method extractSpecialCharacters(name) replaces spaces with sybmol '%20'. * But then in some cases we need to ensure that folder or files * contain ' ' and not '%20'. Otherwise, i.e., we'd be creating "My%20Folder" * instead of "My Folder" (same with files). * * With proper use of this method, users will be able to create folders * or files with blank spaces. * * @example $name = "My%20Folder%20With%20Spaces"; * * @param string $name * * @return string $name ()= "My Folder With Spaces") */ private function getBlankSpacesBack($name){ $name = str_replace('%20', ' ', $name); return $name; } /** * Creates a file inside the folder previously setted ($this->parentFolder) * $name = name of the file to create. * * @example $name = "file.txt"; * @example $content = "hi this is a file"; * * @param string $name * @param string $content * @param string $content_type * @param array $option * * @return stdClass */ public function createFile($name, array $properties = array(), $content = null, $content_type = 'application/octet-stream', array $options = array()){ $name = $this->extractSpecialCharacters($name); $exists = $this->FileExists($name); if ($exists) { throw new Exception('Error:->the file named '.$name.' already exists', 1); } $name = $this->getBlankSpacesBack($name); return $this->repository->createDocument($this->parentFolder->id, $name, $properties, $content, $content_type, $options); } /** * Uploads a file. * * @example $file = "c:/temp/hello.pdf"; * * @param string $file * * @return stdClass */ public function uploadFile($file) { $name = basename($file); $name = $this->extractSpecialCharacters($name); $name = $this->getBlankSpacesBack($name); $openFile = fopen($file, 'r'); $content = fread($openFile, filesize($file)); //You need to activate fileinfo $content_type = mime_content_type($file); $newFile = $this->createFile($name, array(), $content, $content_type, array()); if ($newFile) { return $newFile; } } /** * Downloads a file into temp directory and display the content by the browser. * * @param string $id */ public function displayFile($id) { $file = $this->getObjectById($id); $name = $file->properties['cmis:name']; $mime = $file->properties['cmis:contentStreamMimeType']; $mime = str_replace("\t", '', $mime); $mime = str_replace("\n", '', $mime); $length = $file->properties['cmis:contentStreamLength']; $content = $this->repository->getContentStream($id); $name = str_replace(' ', '_', $name); $tempFile = fopen($name, 'wb'); fwrite($tempFile, $content); fclose($tempFile); $domain = $_SERVER['SERVER_NAME']; $path = getcwd().'/'.$name; header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Content-type: '.$mime); header('Content-Transfer-Encoding: Binary'); header('Expires: 0'); header('Pragma: public'); header('Content-Length: '.filesize($name)); if (ob_get_contents()) { ob_end_clean(); } flush(); readfile($path); unlink($name); exit(); } /** * Downloads a file by its id. * * @param string $id */ public function downloadFile($id) { $file = $this->getObjectById($id); $name = $file->properties['cmis:name']; $mime = $file->properties['cmis:contentStreamMimeType']; $mime = str_replace("\t", '', $mime); $mime = str_replace("\n", '', $mime); $length = $file->properties['cmis:contentStreamLength']; $content = $this->repository->getContentStream($id); $name = str_replace(' ', '_', $name); $tempFile = fopen($name, 'wb'); fwrite($tempFile, $content); fclose($tempFile); $domain = $_SERVER['SERVER_NAME']; $path = getcwd().'/'.$name; header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Content-Description: File Transfer'); header('Content-type: '.$mime); header('Content-Disposition: attachment; filename="'.$name."\"\n"); header('Content-Transfer-Encoding: Binary'); header('Expires: 0'); header('Pragma: public'); header('Content-Length: '.filesize($name)); if (ob_get_contents()) { ob_end_clean(); } flush(); readfile($path); unlink($name); exit(); } /** * Downloads a file by its id to a temp folder. * * @param string $id * * @return string */ public function moveFile($id) { $file = $this->getObjectById($id); $name = $file->properties['cmis:name']; $length = $file->properties['cmis:contentStreamLength']; $content = $this->repository->getContentStream($id); $name = str_replace(' ', '_', $name); $tempFile = fopen($name, 'wb'); fwrite($tempFile, $content); fclose($tempFile); $domain = $_SERVER['SERVER_NAME']; $path = getcwd().'/'.$name; return $path; } /** * Downloads a folder as zip. * * @param string $id */ public function downloadFolder($id, $previousPath = null, $zip = null, $firstPath = null) { $path = $previousPath; $obj = $this->getObjectById($id); if ($obj->properties['cmis:baseTypeId'] != 'cmis:folder') { throw new UnexpectedValueException('The object is not a folder', 1); } $folderName = $obj->properties['cmis:name']; if (!is_null($path)) { $path = $path.'/'.$folderName; $zip->addEmptyDir(str_replace($firstPath, '', $path)); } else { $createFolder = false; $path = getcwd().'/'.$folderName; $firstPath = $path; } if (!file_exists($path)) { $createFolder = mkdir($path, 0777, true); } else { $createFolder = true; } if ($createFolder) { if (is_null($zip)) { $zip = new ZipArchive(); $zipName = $folderName.'.zip'; if ($zip->open($path.'/'.$zipName, ZipArchive::CREATE) !== true) { throw new RuntimeException("could not open <$zipName>\n", 1); } } $children = $this->getChildrenId($id); $files = array(); $c = 0; for ($i = 0; $i < count($children->objectList); ++$i) { if ($children->objectList[$i]->properties['cmis:baseTypeId'] == 'cmis:folder') { $this->downloadFolder($children->objectList[$i]->id, $path, $zip, $firstPath); } else { $fileName = $children->objectList[$i]->properties['cmis:name']; $length = $children->objectList[$i]->properties['cmis:contentStreamLength']; $content = $this->repository->getContentStream($children->objectList[$i]->id); $tempFile = fopen($path.'/'.$fileName, 'wb'); fwrite($tempFile, $content); fclose($tempFile); $files[$c] = $path.'/'.$fileName; ++$c; } } for ($i = 0; $i < count($files); ++$i) { $zip->addFile($files[$i], str_replace($firstPath, '', $files[$i])); } if (is_null($previousPath)) { $zip->close(); $zipPath = $path.'/'.$zipName; header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Content-Description: File Transfer'); header('Content-type: application/zip'); header('Content-Disposition: attachment; filename="'.$zipName."\"\n"); header('Content-Transfer-Encoding: Binary'); header('Expires: 0'); header('Pragma: public'); header('Content-Length: '.filesize($zipPath)); if (ob_get_contents()) { ob_end_clean(); } flush(); readfile($zipPath); exit(); } } else { throw new RuntimeException('Could not create temporal folder', 1); } } /** * Gets the children of the folder previously setted. * * @return stdClass */ public function getChildrenFolder() { if (is_null($this->parentFolder)) { throw new Exception('You must set a workspace folder', 1); } return $this->repository->getChildren($this->parentFolder->id); } /** * Gets the children of a folder by its Id. * * @param string $id * * @return stdClass */ public function getChildrenId($id) { return $this->repository->getChildren($id); } /** * Gets an object by its Id. * * @param string $id * * @return stdClass */ public function getObjectById($id) { return $this->repository->getObject($id); } /** * Deletes Object by its id. * * @param string $id * @param array $options * * @return stdClass */ public function delete($id, $options = array()) { return $this->repository->deleteObject($id, $options); } /** * Executes a query to repository. * * @param string $query * * @example $query = 'SELECT * FROM cmis:document'; * * @return stdClass */ public function query($query) { return $this->repository->query($query); } /* * * Check if folder already exists before creating it * */ /** * Determines if it exists folder. * * @param string $name * * @return bool True if exists folder, False otherwise. */ public function existsFolder($name) { $name = $this->extractSpecialCharacters($name); //remove special chars (keep in mind spaces are now "%20") $name = $this->getBlankSpacesBack($name); //Ensure name is something like "My Folder" and not "My%20Folder" $obj = $this->repository->getChildren($this->parentFolder->id); $name = str_replace('(', '', $name); $name = str_replace(')', '', $name); $continue = true; $c = 0; while ($continue and $c < count($obj->objectList)) { if ($obj->objectList[$c]->properties['cmis:objectTypeId'] == 'cmis:folder') { //repo folder names and $name parameter will be forced to be lower case (Alfresco folder names aren't case-sensitive) if (strtolower($obj->objectList[$c]->properties['cmis:name']) == strtolower($name)) { $continue = false; } } $c = $c + 1; } if (!$continue) { return true; } else { return false; } } /** * Determines if file exists. * * @param string $name * * @return bool */ public function FileExists($name) { $name = $this->extractSpecialCharacters($name); //remove special chars (keep in mind spaces are now "%20") $name = $this->getBlankSpacesBack($name); //Ensure name is something like "My Folder" and not "My%20Folder" $nameToLower = strtolower($name); $obj = $this->repository->getChildren($this->parentFolder->id); $name = str_replace('(', '', $name); $name = str_replace(')', '', $name); $continue = true; $c = 0; while ($continue and $c < count($obj->objectList)) { if ($obj->objectList[$c]->properties['cmis:objectTypeId'] == 'cmis:document') { //repo file names and $name parameter will be forced to be lower case (Alfresco file names aren't case-sensitive) if (strtolower($obj->objectList[$c]->properties['cmis:name']) == strtolower($name)) { $continue = false; } } $c = $c + 1; } if (!$continue) { return true; } else { return false; } } /** * Determines if it has folders. * * @param string $id * * @return bool True if has folders, False otherwise. */ private function hasFolders($id) { $obj = $this->repository->getChildren($id); $continue = true; $c = 0; while ($continue and $c < count($obj->objectList)) { if ($obj->objectList[$c]->properties['cmis:objectTypeId'] == 'cmis:folder') { $continue = false; } $c = $c + 1; } if (!$continue) { return true; } else { return false; } } /** * Deletes a directory. * * @param string $dir The dir * * @return bool */ private function deleteDir($dir) { $current_dir = opendir($dir); while ($entryname = readdir($current_dir)) { if (is_dir("$dir/$entryname") and ($entryname != '.' and $entryname != '..')) { $this->deleteDir("${dir}/${entryname}"); } elseif ($entryname != '.' and $entryname != '..') { unlink("${dir}/${entryname}"); } } closedir($current_dir); return rmdir(${'dir'}); } /** * Extracts Special characters. * * @param string $word * * @return string */ private function extractSpecialCharacters($word) { $word = trim($word); $word = str_replace( array('á', 'à', 'ä', 'â', 'ª', 'Á', 'À', 'Â', 'Ä'), array('a', 'a', 'a', 'a', 'a', 'A', 'A', 'A', 'A'), $word ); $word = str_replace( array('é', 'è', 'ë', 'ê', 'É', 'È', 'Ê', 'Ë'), array('e', 'e', 'e', 'e', 'E', 'E', 'E', 'E'), $word ); $word = str_replace( array('í', 'ì', 'ï', 'î', 'Í', 'Ì', 'Ï', 'Î'), array('i', 'i', 'i', 'i', 'I', 'I', 'I', 'I'), $word ); $word = str_replace( array('ó', 'ò', 'ö', 'ô', 'Ó', 'Ò', 'Ö', 'Ô'), array('o', 'o', 'o', 'o', 'O', 'O', 'O', 'O'), $word ); $word = str_replace( array('ú', 'ù', 'ü', 'û', 'Ú', 'Ù', 'Û', 'Ü'), array('u', 'u', 'u', 'u', 'U', 'U', 'U', 'U'), $word ); $word = str_replace( array('ñ', 'Ñ', 'ç', 'Ç'), array('n', 'N', 'c', 'C'), $word ); $word = str_replace( array('\\', '¨', 'º', '~', '#', '@', '|', '!', '"', '$', '%', '&', /*'/',*/ '(', ')', '?', "'", '¡', '¿', '[', '^', '`', ']', '+', '}', '{', '¨', '´', '>', '< ', ';', ',', ':', '-', '·', '¬', '_'), '', $word ); $word = str_replace(' ', '%20', $word); //HTTP request accept blank spaces as '%20' symbol. Literal blank space is invalid return $word; } /** * Proccess errors coming from cmis_wrapper. * * @param Exception $e */ private function processException($e) { switch ($e->getCode()) { case '401': throw new Exception('Wrong user or password', 401); case '0': throw new Exception('Wrong url', 0); case '404': throw new Exception('Object not found', 404); case '400': throw new Exception('Invalid Argument', 404); default: throw $e; } } } <file_sep>/cmis_repository_wrapper.php <?php # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. define("HTTP_OK", 200); define("HTTP_CREATED", 201); define("HTTP_ACCEPTED", 202); define("HTTP_NONAUTHORITATIVE_INFORMATION", 203); define("HTTP_NO_CONTENT", 204); define("HTTP_RESET_CONTENT", 205); define("HTTP_PARTIAL_CONTENT", 206); define("HTTP_MULTIPLE_CHOICES", 300); define("HTTP_BAD_REQUEST", 400); // invalidArgument, filterNotValid define("HTTP_UNAUTHORIZED", 401); define("HTTP_FORBIDDEN", 403); // permissionDenied, streamNotSupported define("HTTP_NOT_FOUND", 404); // objectNotFound define("HTTP_METHOD_NOT_ALLOWED", 405); // notSupported define("HTTP_NOT_ACCEPTABLE", 406); define("HTTP_PROXY_AUTHENTICATION_REQUIRED", 407); define("xHTTP_REQUEST_TIMEOUT", 408); //Had to change this b/c HTTP_REQUEST_TIMEOUT conflicts with definition in Drupal 7 define("HTTP_CONFLICT", 409); // constraint, contentAlreadyExists, versioning, updateConflict, nameConstraintViolation define("HTTP_UNSUPPORTED_MEDIA_TYPE", 415); define("HTTP_UNPROCESSABLE_ENTITY", 422); define("HTTP_INTERNAL_SERVER_ERROR", 500); // runtime, storage class CmisInvalidArgumentException extends Exception {} class CmisObjectNotFoundException extends Exception {} class CmisPermissionDeniedException extends Exception {} class CmisNotSupportedException extends Exception {} class CmisNotImplementedException extends Exception {} class CmisConstraintException extends Exception {} class CmisRuntimeException extends Exception {} /** * @internal */ class CMISRepositoryWrapper { // Handles -- // Workspace -- but only endpoints with a single repo // Entry -- but only for objects // Feeds -- but only for non-hierarchical feeds // Does not handle -- // -- Hierarchical Feeds // -- Types // -- Others? // Only Handles Basic Auth // Very Little Error Checking // Does not work against pre CMIS 1.0 Repos /** * @internal */ var $url; /** * @internal */ var $username; /** * @internal */ var $password; /** * @internal */ var $authenticated; /** * @internal */ var $workspace; /** * @internal */ var $last_request; /** * @internal */ var $do_not_urlencode; /** * @internal */ protected $_addlCurlOptions = array(); /** * @internal */ static $namespaces = array ( "cmis" => "http://docs.oasis-open.org/ns/cmis/core/200908/", "cmisra" => "http://docs.oasis-open.org/ns/cmis/restatom/200908/", "atom" => "http://www.w3.org/2005/Atom", "app" => "http://www.w3.org/2007/app", ); /** * @internal */ function __construct($url, $username = null, $password = <PASSWORD>, $options = null, array $addlCurlOptions = array()) { if (is_array($options) && $options["config:do_not_urlencode"]) { $this->do_not_urlencode=true; } $this->_addlCurlOptions = $addlCurlOptions; // additional cURL options $this->connect($url, $username, $password, $options); } /** * @internal */ static function getAsArray($prop) { if ($prop == null) { return array(); } elseif (!is_array($prop)) { return array($prop); } else { return($prop); } } /** * @internal */ static function getOpUrl($url, $options = null) { if (is_array($options) && (count($options) > 0)) { $needs_question = strstr($url, "?") === false; return $url . ($needs_question ? "?" : "&") . http_build_query($options); } else { return $url; } } /** * @internal */ function convertStatusCode($code, $message) { switch ($code) { case HTTP_BAD_REQUEST: return new CmisInvalidArgumentException($message, $code); case HTTP_NOT_FOUND: return new CmisObjectNotFoundException($message, $code); case HTTP_FORBIDDEN: return new CmisPermissionDeniedException($message, $code); case HTTP_METHOD_NOT_ALLOWED: return new CmisNotSupportedException($message, $code); case HTTP_CONFLICT: return new CmisConstraintException($message, $code); default: return new CmisRuntimeException($message, $code); } } /** * @internal */ function connect($url, $username, $password, $options) { // TODO: Make this work with cookies $this->url = $url; $this->username = $username; $this->password = $<PASSWORD>; $this->auth_options = $options; $this->authenticated = false; $retval = $this->doGet($this->url); if ($retval->code == HTTP_OK || $retval->code == HTTP_CREATED) { $this->authenticated = true; $this->workspace = CMISRepositoryWrapper :: extractWorkspace($retval->body); } } /** * @internal */ function doGet($url) { $retval = $this->doRequest($url); if ($retval->code != HTTP_OK) { throw $this->convertStatusCode($retval->code, $retval->body); } return $retval; } /** * @internal */ function doDelete($url) { $retval = $this->doRequest($url, "DELETE"); if ($retval->code != HTTP_NO_CONTENT) { throw $this->convertStatusCode($retval->code, $retval->body); } return $retval; } /** * @internal */ function doPost($url, $content, $contentType, $charset = null) { $retval = $this->doRequest($url, "POST", $content, $contentType); if ($retval->code != HTTP_CREATED) { throw $this->convertStatusCode($retval->code, $retval->body); } return $retval; } /** * @internal */ function doPut($url, $content, $contentType, $charset = null) { $retval = $this->doRequest($url, "PUT", $content, $contentType); if (($retval->code < HTTP_OK) || ($retval->code >= HTTP_MULTIPLE_CHOICES)) { throw $this->convertStatusCode($retval->code, $retval->body); } return $retval; } /** * @internal */ function doRequest($url, $method = "GET", $content = null, $contentType = null, $charset = null) { // Process the HTTP request // 'til now only the GET request has been tested // Does not URL encode any inputs yet if (is_array($this->auth_options)) { $url = CMISRepositoryWrapper :: getOpUrl($url, $this->auth_options); } $session = curl_init($url); curl_setopt($session, CURLOPT_HEADER, false); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); if ($this->username) { curl_setopt($session, CURLOPT_USERPWD, $this->username . ":" . $this->password); } curl_setopt($session, CURLOPT_CUSTOMREQUEST, $method); if ($contentType) { curl_setopt($session, CURLOPT_HTTPHEADER, array ( "Content-Type: " . $contentType )); } if ($content) { curl_setopt($session, CURLOPT_POSTFIELDS, $content); } if ($method == "POST") { curl_setopt($session, CURLOPT_POST, true); } // apply addl. cURL options // WARNING: this may override previously set options if (count($this->_addlCurlOptions)) { foreach ($this->_addlCurlOptions as $key => $value) { curl_setopt($session, $key, $value); } } //TODO: Make this storage optional $retval = new stdClass(); $retval->url = $url; $retval->method = $method; $retval->content_sent = $content; $retval->content_type_sent = $contentType; $retval->body = curl_exec($session); $retval->code = curl_getinfo($session, CURLINFO_HTTP_CODE); $retval->content_type = curl_getinfo($session, CURLINFO_CONTENT_TYPE); $retval->content_length = curl_getinfo($session, CURLINFO_CONTENT_LENGTH_DOWNLOAD); curl_close($session); $this->last_request = $retval; return $retval; } function getLastRequest() { return $this->last_request; } function getLastRequestBody() { return $this->last_request->body; } function getLastRequestCode() { return $this->last_request->code; } function getLastRequestContentType() { return $this->last_request->content_type; } function getLastRequestContentLength() { return $this->last_request->content_length; } function getLastRequestURL() { return $this->last_request->url; } function getLastRequestMethod() { return $this->last_request->method; } function getLastRequestContentTypeSent() { return $this->last_request->content_type_sent; } function getLastRequestContentSent() { return $this->last_request->content_sent; } // Static Utility Functions /** * @internal */ static function processTemplate($template, $values = array ()) { // Fill in the blanks -- $retval = $template; if (is_array($values)) { foreach ($values as $name => $value) { $retval = str_replace("{" . $name . "}", $value, $retval); } } // Fill in any unpoupated variables with "" return preg_replace("/{[a-zA-Z0-9_]+}/", "", $retval); } /** * @internal */ static function doXQuery($xmldata, $xquery) { $doc = new DOMDocument(); $doc->loadXML($xmldata); return CMISRepositoryWrapper :: doXQueryFromNode($doc, $xquery); } /** * @internal */ static function doXQueryFromNode($xmlnode, $xquery) { // Perform an XQUERY on a NODE // Register the 4 CMIS namespaces //THis may be a hopeless HACK! //TODO: Review if (!($xmlnode instanceof DOMDocument)) { $xdoc=new DOMDocument(); $xnode = $xdoc->importNode($xmlnode,true); $xdoc->appendChild($xnode); $xpath = new DomXPath($xdoc); } else { $xpath = new DomXPath($xmlnode); } foreach (CMISRepositoryWrapper :: $namespaces as $nspre => $nsuri) { $xpath->registerNamespace($nspre, $nsuri); } return $xpath->query($xquery); } /** * @internal */ static function getLinksArray($xmlnode) { // Gets the links of an object or a workspace // Distinguishes between the two "down" links // -- the children link is put into the associative array with the "down" index // -- the descendants link is put into the associative array with the "down-tree" index // These links are distinquished by the mime type attribute, but these are probably the only two links that share the same rel .. // so this was done as a one off $links = array (); $link_nodes = $xmlnode->getElementsByTagName("link"); foreach ($link_nodes as $ln) { if ($ln->attributes->getNamedItem("rel")->nodeValue == "down" && $ln->attributes->getNamedItem("type")->nodeValue == "application/cmistree+xml") { //Descendents and Childredn share same "rel" but different document type $links["down-tree"] = $ln->attributes->getNamedItem("href")->nodeValue; } else { $links[$ln->attributes->getNamedItem("rel")->nodeValue] = $ln->attributes->getNamedItem("href")->nodeValue; } } return $links; } /** * @internal */ static function extractAllowableActions($xmldata) { $doc = new DOMDocument(); $doc->loadXML($xmldata); return CMISRepositoryWrapper :: extractAllowableActionsFromNode($doc); } /** * @internal */ static function extractAllowableActionsFromNode($xmlnode) { $result = array(); $allowableActions = $xmlnode->getElementsByTagName("allowableActions"); if ($allowableActions->length > 0) { foreach($allowableActions->item(0)->childNodes as $action) { if (isset($action->localName)) { $result[$action->localName] = (preg_match("/^true$/i", $action->nodeValue) > 0); } } } return $result; } /** * @internal */ static function extractObject($xmldata) { $doc = new DOMDocument(); $doc->loadXML($xmldata); return CMISRepositoryWrapper :: extractObjectFromNode($doc); } /** * @internal */ static function extractObjectFromNode($xmlnode) { // Extracts the contents of an Object and organizes them into: // -- Links // -- Properties // -- the Object ID // RRM -- NEED TO ADD ALLOWABLEACTIONS $retval = new stdClass(); $retval->links = CMISRepositoryWrapper :: getLinksArray($xmlnode); $retval->properties = array (); $renditions = $xmlnode->getElementsByTagName("object")->item(0)->getElementsByTagName("rendition"); // Add renditions to CMIS object $renditionArray = array(); if($renditions->length > 0){ $i = 0; foreach ($renditions as $rendition) { $rend_nodes = $rendition->childNodes; foreach ($rend_nodes as $rend){ if ($rend->localName != NULL){ $renditionArray[$i][$rend->localName] = $rend->nodeValue; } } $i++; } } $retval->renditions = $renditionArray; $prop_nodes = $xmlnode->getElementsByTagName("object")->item(0)->getElementsByTagName("properties")->item(0)->childNodes; foreach ($prop_nodes as $pn) { if ($pn->attributes) { //supressing errors since PHP sometimes sees DOM elements as "non-objects" @$retval->properties[$pn->attributes->getNamedItem("propertyDefinitionId")->nodeValue] = $pn->getElementsByTagName("value")->item(0)->nodeValue; } } $retval->uuid = $xmlnode->getElementsByTagName("id")->item(0)->nodeValue; $retval->id = $retval->properties["cmis:objectId"]; //TODO: RRM FIX THIS $children_node = $xmlnode->getElementsByTagName("children"); if (is_object($children_node)) { $children_feed_c = $children_node->item(0); } if (is_object($children_feed_c)) { $children_feed_l = $children_feed_c->getElementsByTagName("feed"); } if (isset($children_feed_l) && is_object($children_feed_l) && is_object($children_feed_l->item(0))) { $children_feed = $children_feed_l->item(0); $children_doc = new DOMDocument(); $xnode = $children_doc->importNode($children_feed,true); // Avoid Wrong Document Error $children_doc->appendChild($xnode); $retval->children = CMISRepositoryWrapper :: extractObjectFeedFromNode($children_doc); } $retval->allowableActions = CMISRepositoryWrapper :: extractAllowableActionsFromNode($xmlnode); return $retval; } /** * @internal */ static function extractTypeDef($xmldata) { $doc = new DOMDocument(); $doc->loadXML($xmldata); return CMISRepositoryWrapper :: extractTypeDefFromNode($doc); } /** * @internal */ static function extractTypeDefFromNode($xmlnode) { // Extracts the contents of an Object and organizes them into: // -- Links // -- Properties // -- the Object ID // RRM -- NEED TO ADD ALLOWABLEACTIONS $retval = new stdClass(); $retval->links = CMISRepositoryWrapper :: getLinksArray($xmlnode); $retval->properties = array (); $retval->attributes = array (); $result = CMISRepositoryWrapper :: doXQueryFromNode($xmlnode, "//cmisra:type/*"); foreach ($result as $node) { if ((substr($node->nodeName, 0, 13) == "cmis:property") && (substr($node->nodeName, -10) == "Definition")) { $id = $node->getElementsByTagName("id")->item(0)->nodeValue; $cardinality = $node->getElementsByTagName("cardinality")->item(0)->nodeValue; $propertyType = $node->getElementsByTagName("propertyType")->item(0)->nodeValue; // Stop Gap for now $retval->properties[$id] = array ( "cmis:propertyType" => $propertyType, "cmis:cardinality" => $cardinality, ); } else { $retval->attributes[$node->nodeName] = $node->nodeValue; } $retval->id = $retval->attributes["cmis:id"]; } //TODO: RRM FIX THIS $children_node = $xmlnode->getElementsByTagName("children"); if (is_object($children_node)) { $children_feed_c = $children_node->item(0); } if (is_object($children_feed_c)) { $children_feed_l = $children_feed_c->getElementsByTagName("feed"); } if (isset($childern_feed_l) && is_object($children_feed_l) && is_object($children_feed_l->item(0))) { $children_feed = $children_feed_l->item(0); $children_doc = new DOMDocument(); $xnode = $children_doc->importNode($children_feed,true); // Avoid Wrong Document Error $children_doc->appendChild($xnode); $retval->children = CMISRepositoryWrapper :: extractTypeFeedFromNode($children_doc); } /* * $prop_nodes = $xmlnode->getElementsByTagName("object")->item(0)->getElementsByTagName("properties")->item(0)->childNodes; foreach ($prop_nodes as $pn) { if ($pn->attributes) { $retval->properties[$pn->attributes->getNamedItem("propertyDefinitionId")->nodeValue] = $pn->getElementsByTagName("value")->item(0)->nodeValue; } } $retval->uuid=$xmlnode->getElementsByTagName("id")->item(0)->nodeValue; $retval->id=$retval->properties["cmis:objectId"]; */ return $retval; } /** * @internal */ static function extractObjectFeed($xmldata) { //Assumes only one workspace for now $doc = new DOMDocument(); $doc->loadXML($xmldata); return CMISRepositoryWrapper :: extractObjectFeedFromNode($doc); } /** * @internal */ static function extractObjectFeedFromNode($xmlnode) { // Process a feed and extract the objects // Does not handle hierarchy // Provides two arrays // -- one sequential array (a list) // -- one hash table indexed by objectID // and a property "numItems" that holds the total number of items available. $retval = new stdClass(); // extract total number of items $numItemsNode = CMISRepositoryWrapper::doXQueryFromNode($xmlnode, "/atom:feed/cmisra:numItems"); $retval->numItems = $numItemsNode->length ? (int) $numItemsNode->item(0)->nodeValue : -1; // set to negative value if info is not available $retval->objectList = array (); $retval->objectsById = array (); $result = CMISRepositoryWrapper :: doXQueryFromNode($xmlnode, "/atom:feed/atom:entry"); foreach ($result as $node) { $obj = CMISRepositoryWrapper :: extractObjectFromNode($node); $retval->objectsById[$obj->id] = $obj; $retval->objectList[] = & $retval->objectsById[$obj->id]; } return $retval; } /** * @internal */ static function extractTypeFeed($xmldata) { //Assumes only one workspace for now $doc = new DOMDocument(); $doc->loadXML($xmldata); return CMISRepositoryWrapper :: extractTypeFeedFromNode($doc); } /** * @internal */ static function extractTypeFeedFromNode($xmlnode) { // Process a feed and extract the objects // Does not handle hierarchy // Provides two arrays // -- one sequential array (a list) // -- one hash table indexed by objectID $retval = new stdClass(); $retval->objectList = array (); $retval->objectsById = array (); $result = CMISRepositoryWrapper :: doXQueryFromNode($xmlnode, "/atom:feed/atom:entry"); foreach ($result as $node) { $obj = CMISRepositoryWrapper :: extractTypeDefFromNode($node); $retval->objectsById[$obj->id] = $obj; $retval->objectList[] = & $retval->objectsById[$obj->id]; } return $retval; } /** * @internal */ static function extractWorkspace($xmldata) { //Assumes only one workspace for now $doc = new DOMDocument(); $doc->loadXML($xmldata); return CMISRepositoryWrapper :: extractWorkspaceFromNode($doc); } /** * @internal */ static function extractWorkspaceFromNode($xmlnode) { // Assumes only one workspace for now // Load up the workspace object with arrays of // links // URI Templates // Collections // Capabilities // General Repository Information $retval = new stdClass(); $retval->links = CMISRepositoryWrapper :: getLinksArray($xmlnode); $retval->uritemplates = array (); $retval->collections = array (); $retval->capabilities = array (); $retval->repositoryInfo = array (); $retval->permissions = array(); $retval->permissionsMapping = array(); $result = CMISRepositoryWrapper :: doXQueryFromNode($xmlnode, "//cmisra:uritemplate"); foreach ($result as $node) { $retval->uritemplates[$node->getElementsByTagName("type")->item(0)->nodeValue] = $node->getElementsByTagName("template")->item(0)->nodeValue; } $result = CMISRepositoryWrapper :: doXQueryFromNode($xmlnode, "//app:collection"); foreach ($result as $node) { $retval->collections[$node->getElementsByTagName("collectionType")->item(0)->nodeValue] = $node->attributes->getNamedItem("href")->nodeValue; } $result = CMISRepositoryWrapper :: doXQueryFromNode($xmlnode, "//cmis:capabilities/*"); foreach ($result as $node) { $retval->capabilities[$node->nodeName] = $node->nodeValue; } $result = CMISRepositoryWrapper :: doXQueryFromNode($xmlnode, "//cmisra:repositoryInfo/*[name()!='cmis:capabilities' and name()!='cmis:aclCapability']"); foreach ($result as $node) { $retval->repositoryInfo[$node->nodeName] = $node->nodeValue; } $result = CMISRepositoryWrapper :: doXQueryFromNode($xmlnode, "//cmis:aclCapability/cmis:permissions"); foreach ($result as $node) { $retval->permissions[$node->getElementsByTagName("permission")->item(0)->nodeValue] = $node->getElementsByTagName("description")->item(0)->nodeValue; } $result = CMISRepositoryWrapper :: doXQueryFromNode($xmlnode, "//cmis:aclCapability/cmis:mapping"); foreach ($result as $node) { $key = $node->getElementsByTagName("key")->item(0)->nodeValue; $values = array(); foreach ($node->getElementsByTagName("permission") as $value) { array_push($values, $value->nodeValue); } $retval->permissionsMapping[$key] = $values; } $result = CMISRepositoryWrapper :: doXQueryFromNode($xmlnode, "//cmis:aclCapability/*[name()!='cmis:permissions' and name()!='cmis:mapping']"); foreach ($result as $node) { $retval->repositoryInfo[$node->nodeName] = $node->nodeValue; } return $retval; } } <file_sep>/README.md # API_Alfresco This API is a collection of useful custom functions that works with the files distributed by [Apache Chemistry](https://chemistry.apache.org/php/phpclient.html) based on the CMIS standar. The aim of this is offer an easy way to communicate your PHP app with Alfresco. ## Requirements 1. PHP >= 5.4 2. Alfresco Community Edition V 5.0 ## USAGE clone this repository and put the files together in your project. ### Example of Use: require '/path/to/APIAlfresco.php';` $urlRepository = 'http://xx.xxx.xx.xx:xxxx/alfresco/cmisatom'; $user = 'user'; $pass = '<PASSWORD>'; $folder = '/Shared'; $folderId = 'workspace://SpacesStore/xxx-xxx-xxx-xxx-xxx'; $fileId = 'workspace://SpacesStore/xxx-xxx-xxx-xx-xxxx;`x.X'; $childrenId = 'workspace://SpacesStore/xxx-xxx-Xxx-xxx-xxx'; * Connect to repository: ``` $conexion = APIAlfresco::getInstance(); try { $conexion->connect($urlRepository,$user,$pass); } catch (Exception $e) { //do something } ``` * Set Workspace directory: `$conexion->setFolderByPath($folder);` or `$conexion->setFolderById($folderId);` * Create Folder: `$conexion->createFolder('new_folder');` * Create File: `$conexion->createFile('file',[],'hola soy un archivo');` * Upload File: `$conexion->uploadFile('new_file.txt');` * Display File in the browser: `$conexion->displayFile($fileId);` * Download a File `$conexion->downloadFile($fileId);` * Move a File to a local folder `$conexion->moveFile($fileId);` * Download a folder `$conexion->downloadFolder($folderId);` * Get Children of workspace folder `$conexion->getChildrenFolder();` * Get Children of a folder by its id `$conexion->getChildrenId($childrenId);` * Get Object by Id `$conexion->getObjectById($childrenId);` * Delete an object `$conexion->delete(`$childrenId);` * Perform a [query](https://wiki.alfresco.com/wiki/CMIS_Query_Language) `$conexion->query("SELECT * FROM cmis:document");` ##Contribute We (I) appreciate if you have any other custom function that you want to add to this repository and share with the community. :D <file_sep>/cmis_service.php <?php # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. require_once ('cmis_repository_wrapper.php'); // Option Contants for Array Indexing // -- Generally optional flags that control how much information is returned // -- Change log token is an anomoly -- but included in URL as parameter define("OPT_MAX_ITEMS", "maxItems"); define("OPT_SKIP_COUNT", "skipCount"); define("OPT_FILTER", "filter"); define("OPT_INCLUDE_PROPERTY_DEFINITIONS", "includePropertyDefinitions"); define("OPT_INCLUDE_RELATIONSHIPS", "includeRelationships"); define("OPT_INCLUDE_POLICY_IDS", "includePolicyIds"); define("OPT_RENDITION_FILTER", "renditionFilter"); define("OPT_INCLUDE_ACL", "includeACL"); define("OPT_INCLUDE_ALLOWABLE_ACTIONS", "includeAllowableActions"); define("OPT_DEPTH", "depth"); define("OPT_CHANGE_LOG_TOKEN", "changeLogToken"); define("OPT_CHECK_IN_COMMENT", "checkinComment"); define("OPT_CHECK_IN", "checkin"); define("OPT_MAJOR_VERSION", "major"); define("COLLECTION_ROOT_FOLDER","root"); define("COLLECTION_TYPES","types"); define("COLLECTION_CHECKED_OUT","checkedout"); define("COLLECTION_QUERY","query"); define("COLLECTION_UNFILED","unfiled"); define("URI_TEMPLATE_OBJECT_BY_ID","objectbyid"); define("URI_TEMPLATE_OBJECT_BY_PATH","objectbypath"); define("URI_TEMPLATE_TYPE_BY_ID","typebyid"); define("URI_TEMPLATE_QUERY","query"); define("LINK_SELF", "self"); define("LINK_SERVICE","service"); define("LINK_DESCRIBED_BY", "describedby"); define("LINK_VIA","via"); define("LINK_EDIT_MEDIA", "edit-media"); define("LINK_EDIT","edit"); define("LINK_ALTERNATE", "alternate"); define("LINK_FIRST","first"); define("LINK_PREVIOUS", "previous"); define("LINK_NEXT","next"); define("LINK_LAST", "last"); define("LINK_UP","up"); define("LINK_DOWN", "down"); define("LINK_DOWN_TREE","down-tree"); define("LINK_VERSION_HISTORY","version-history"); define("LINK_CURRENT_VERSION", "current-version"); define("LINK_ALLOWABLE_ACTIONS", "http://docs.oasis-open.org/ns/cmis/link/200908/allowableactions"); define("LINK_RELATIONSHIPS","http://docs.oasis-open.org/ns/cmis/link/200908/relationships"); define("LINK_SOURCE","http://docs.oasis-open.org/ns/cmis/link/200908/source"); define("LINK_TARGET","http://docs.oasis-open.org/ns/cmis/link/200908/target"); define("LINK_POLICIES", "http://docs.oasis-open.org/ns/cmis/link/200908/policies"); define("LINK_ACL","http://docs.oasis-open.org/ns/cmis/link/200908/acl"); define("LINK_CHANGES","http://docs.oasis-open.org/ns/cmis/link/200908/changes"); define("LINK_FOLDER_TREE","http://docs.oasis-open.org/ns/cmis/link/200908/foldertree"); define("LINK_ROOT_DESCENDANTS","http://docs.oasis-open.org/ns/cmis/link/200908/rootdescendants"); define("LINK_TYPE_DESCENDANTS","http://docs.oasis-open.org/ns/cmis/link/200908/typedescendants"); define("MIME_ATOM_XML", 'application/atom+xml'); define("MIME_ATOM_XML_ENTRY", 'application/atom+xml;type=entry'); define("MIME_ATOM_XML_FEED", 'application/atom+xml;type=feed'); define("MIME_CMIS_TREE", 'application/cmistree+xml'); define("MIME_CMIS_QUERY", 'application/cmisquery+xml'); // Many Links have a pattern to them based upon objectId -- but can that be depended upon? /** * CMIS Service * * @api CMIS * @since CMIS-1.0 */ class CMISService extends CMISRepositoryWrapper { /** * @internal */ var $_link_cache; /** * @internal */ var $_title_cache; /** * @internal */ var $_objTypeId_cache; /** * @internal */ var $_type_cache; /** * @internal */ var $_changeToken_cache; /** * Construct a new CMISService Connector * * @param String $url Endpoint URL * @param String $username Username * @param String $password <PASSWORD> * @param mixed[] $options Connection Options * @param mixed[] $addlCurlOptions Additional CURL Options * @api CMIS-Service * @since CMIS-1.0 */ /* Utility functions */ function GenURLQueryString($options) { if (count($options) > 0) { return '&'.urldecode(http_build_query($options)); }else{ return null; } } function __construct($url, $username, $password, $options = null, array $addlCurlOptions = array ()) { parent :: __construct($url, $username, $password, $options, $addlCurlOptions); $this->_link_cache = array (); $this->_title_cache = array (); $this->_objTypeId_cache = array (); $this->_type_cache = array (); $this->_changeToken_cache = array (); } // Utility Methods -- Added Titles /** * @internal */ function cacheObjectInfo($obj) { $this->_link_cache[$obj->id] = $obj->links; $this->_title_cache[$obj->id] = $obj->properties["cmis:name"]; // Broad Assumption Here? $this->_objTypeId_cache[$obj->id] = $obj->properties["cmis:objectTypeId"]; if (isset($obj->properties["cmis:changeToken"])) { $this->_changeToken_cache[$obj->id] = $obj->properties["cmis:changeToken"]; } } /** * Get an Object's property and return it as an array * * This returns an array even if it is a scalar or null * * @todo Allow the getProperty method to query the object type information and * return multivalue properties as arrays even if empty or if only a single value * is present. * @param Object $obj Object * @param String $propName Property Name * @returns mixed[] * @api CMIS-Helper * @since CMIS-1.0 */ function getMultiValuedProp($obj,$propName) { if (isset($obj->properties[$propName])) { return CMISRepositoryWrapper::getAsArray($obj->properties[$propName]); } return array(); } /** * @internal */ function cacheFeedInfo($objs) { foreach ($objs->objectList as $obj) { $this->cacheObjectInfo($obj); } } /** * @internal */ function cacheTypeFeedInfo($typs) { foreach ($typs->objectList as $typ) { $this->cacheTypeInfo($typ); } } /** * @internal */ function cacheTypeInfo($tDef) { // TODO: Fix Type Caching with missing properties $this->_type_cache[$tDef->id] = $tDef; } /** * @internal */ function getPropertyType($typeId, $propertyId) { if (isset($this->_type_cache[$typeId])) { if ($this->_type_cache[$typeId]->properties) { return $this->_type_cache[$typeId]->properties[$propertyId]["cmis:propertyType"]; } } $obj = $this->getTypeDefinition($typeId); return $obj->properties[$propertyId]["cmis:propertyType"]; } /** * @internal */ function getObjectType($objectId) { if ($this->_objTypeId_cache[$objectId]) { return $this->_objTypeId_cache[$objectId]; } $obj = $this->getObject($objectId); return $obj->properties["cmis:objectTypeId"]; } /** * @internal */ function getTitle($objectId) { if ($this->_title_cache[$objectId]) { return $this->_title_cache[$objectId]; } $obj = $this->getObject($objectId); return $obj->properties["cmis:name"]; } /** * @internal */ function getTypeLink($typeId, $linkName) { if ($this->_type_cache[$typeId]->links) { return $this->_type_cache[$typeId]->links[$linkName]; } $typ = $this->getTypeDefinition($typeId); return $typ->links[$linkName]; } /** * @internal */ function getLink($objectId, $linkName) { if (array_key_exists($objectId, $this->_link_cache)) { return $this->_link_cache[$objectId][$linkName]; } $obj = $this->getObject($objectId); return $obj->links[$linkName]; } // Repository Services // TODO: Need to fix this for multiple repositories /** * Get an Object by Object Id * @api CMIS-RepositoryServices-NotImplemented * @since CMIS-1.0 */ function getRepositories() { throw new CmisNotImplementedException("getRepositories"); } /** * Get Repository Information * @returns Object * @api CMIS-RepositoryServices * @since CMIS-1.0 */ function getRepositoryInfo() { return $this->workspace; } /** * Get a set of object-types that are descendants of the specified type * * If typeId is null, then the repository MUST return all types and ignore the depth parameter. * * @param String $typeId The typeId of an object-type specified in the repository * @param $depth the number of levels in the hierarchy to return (-1 == all) * @returns Object The set of descendant object-types defined for the given typeId. * @api CMIS-RepositoryServices * @since CMIS-1.0 */ function getTypeDescendants($typeId = null, $depth, $options = array ()) { // TODO: Refactor Type Entries Caching $varmap = $options; if ($typeId) { $hash_values = $options; $hash_values[OPT_DEPTH] = $depth; $myURL = $this->getTypeLink($typeId, LINK_DOWN_TREE); $myURL = CMISRepositoryWrapper :: getOpUrl($myURL, $hash_values); } else { $myURL = $this->processTemplate($this->workspace->links[LINK_TYPE_DESCENDANTS], $varmap); } $ret = $this->doGet($myURL); $typs = $this->extractTypeFeed($ret->body); $this->cacheTypeFeedInfo($typs); return $typs; } /** * Get a list of object-types that are children of the specified type * * If typeId is null, then the repository MUST return all base object-types. * * @param String $typeId The typeId of an object-type specified in the repository * @returns Object The list of child object-types defined for the given typeId. * @api CMIS-RepositoryServices * @since CMIS-1.0 */ function getTypeChildren($typeId = null, $options = array ()) { // TODO: Refactor Type Entries Caching $varmap = $options; if ($typeId) { $myURL = $this->getTypeLink($typeId, "down"); $myURL.= $this->GenURLQueryString($options); } else { //TODO: Need right URL $myURL = $this->processTemplate($this->workspace->collections['types'], $varmap); } $ret = $this->doGet($myURL); $typs = $this->extractTypeFeed($ret->body); $this->cacheTypeFeedInfo($typs); return $typs; } /** * Gets the definition of the specified object-type. * * @param String $typeId Object Type Id * @returns Object Type Definition of the Specified Object * @api CMIS-RepositoryServices * @since CMIS-1.0 */ function getTypeDefinition($typeId, $options = array ()) { // Nice to have $varmap = $options; $varmap["id"] = $typeId; $myURL = $this->processTemplate($this->workspace->uritemplates['typebyid'], $varmap); $ret = $this->doGet($myURL); $obj = $this->extractTypeDef($ret->body); $this->cacheTypeInfo($obj); return $obj; } /** * Get an Object's Property Type by Object Id * @param String $objectId Object Id * @returns Object Type Definition of the Specified Object * @api CMIS-Helper * @since CMIS-1.0 */ function getObjectTypeDefinition($objectId) { // Nice to have $myURL = $this->getLink($objectId, "describedby"); $ret = $this->doGet($myURL); $obj = $this->extractTypeDef($ret->body); $this->cacheTypeInfo($obj); return $obj; } //Repository Services -- New for 1.1 /** * Creates a new type definition. * * Creates a new type definition that is a subtype of an existing specified parent type. * Only properties that are new to this type (not inherited) are passed to this service. * * @param String $objectType A type definition object with the property definitions that are to change. * @returns Object Type Definition of the Specified Object * @api CMIS-RepositoryServices-NotImplemented * @since CMIS-1.1 */ function createType($objectType) { throw new CmisNotImplementedException("createType"); } /** * Updates a type definition * * If you add an optional property to a type in error. There is no way to remove it/correct it - without * deleting the type. * * @param String $objectType A type definition object with the property definitions that are to change. * @returns Object The updated object-type including all property definitions. * @api CMIS-RepositoryServices-NotImplemented * @since CMIS-1.1 */ function updateType($objectType) { throw new CmisNotImplementedException("updateType"); } /** * Deletes a type definition * * If there are object instances present of the type being deleted then this operation MUST fail. * * @param String $typeId The typeId of an object-type specified in the repository. * @api CMIS-RepositoryServices-NotImplemented * @since CMIS-1.1 */ function deleteType($typeId) { throw new CmisNotImplementedException("deleteType"); } //Navigation Services /** * Get the list of descendant folders contained in the specified folder. * * @param String $folderId the Object ID of the folder * @param String $depth The number of levels of depth in the folder hierarchy from which to return results (-1 == ALL). * @returns Object[] A tree of the child objects for the specified folder. * @api CMIS-NavigationServices * @since CMIS-1.0 */ function getFolderTree($folderId, $depth, $options = array ()) { $hash_values = $options; $hash_values[OPT_DEPTH] = $depth; $myURL = $this->getLink($folderId, "http://docs.oasis-open.org/ns/cmis/link/200908/foldertree"); $myURL = CMISRepositoryWrapper :: getOpUrl($myURL, $hash_values); $ret = $this->doGet($myURL); $objs = $this->extractObjectFeed($ret->body); $this->cacheFeedInfo($objs); return $objs; } /** * Get the list of descendant objects contained in the specified folder. * * @param String $folderId the Object ID of the folder * @param String $depth The number of levels of depth in the folder hierarchy from which to return results (-1 == ALL). * @returns Object[] A tree of the child objects for the specified folder. * @api CMIS-NavigationServices * @since CMIS-1.0 */ function getDescendants($folderId, $depth, $options = array ()) { // Nice to have $hash_values = $options; $hash_values[OPT_DEPTH] = $depth; $myURL = $this->getLink($folderId, LINK_DOWN_TREE); $myURL = CMISRepositoryWrapper :: getOpUrl($myURL, $hash_values); $ret = $this->doGet($myURL); $objs = $this->extractObjectFeed($ret->body); $this->cacheFeedInfo($objs); return $objs; } /** * Get the list of child objects contained in the specified folder. * * @param String $folderId the Object ID of the folder * @returns Object[] A list of the child objects for the specified folder. * @api CMIS-NavigationServices * @since CMIS-1.0 */ function getChildren($folderId, $options = array ()) { $myURL = $this->getLink($folderId, LINK_DOWN); $myURL.= $this->GenURLQueryString($options); $ret = $this->doGet($myURL); $objs = $this->extractObjectFeed($ret->body); $this->cacheFeedInfo($objs); return $objs; } /** * Get the parent folder of the specified folder. * * @param String $folderId the Object ID of the folder * @returns Object the parent folder. * @api CMIS-NavigationServices * @since CMIS-1.0 */ function getFolderParent($folderId, $options = array ()) { //yes $myURL = $this->getLink($folderId, LINK_UP); $myURL.= $this->GenURLQueryString($options); $ret = $this->doGet($myURL); $obj = CMISRepositoryWrapper::extractObject($ret->body); $this->cacheObjectInfo($obj); return $obj; } /** * Get the parent folder(s) for the specified fileable object. * * @param String $objectId the Object ID of the Object * @returns Object[] list of the parent folder(s) of the specified object. * @api CMIS-NavigationServices * @since CMIS-1.0 */ function getObjectParents($objectId, $options = array ()) { // yes $myURL = $this->getLink($objectId, LINK_UP); $myURL.= $this->GenURLQueryString($options); $ret = $this->doGet($myURL); $objs = $this->extractObjectFeed($ret->body); $this->cacheFeedInfo($objs); return $objs; } /** * Get the list of documents that are checked out that the user has access to.. * * @returns Object[] list of checked out documents. * @api CMIS-NavigationServices * @since CMIS-1.0 */ function getCheckedOutDocs($options = array ()) { $obj_url = $this->workspace->collections[COLLECTION_CHECKED_OUT]; $ret = $this->doGet($obj_url); $objs = $this->extractObjectFeed($ret->body); $this->cacheFeedInfo($objs); return $objs; } //Discovery Services /** * @internal */ static function getQueryTemplate() { ob_start(); echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n"; ?> <cmis:query xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/" xmlns:cmism="http://docs.oasis-open.org/ns/cmis/messaging/200908/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns:cmisra="http://docs.oasisopen.org/ns/cmis/restatom/200908/"> <cmis:statement><![CDATA[{q}]]></cmis:statement> <cmis:searchAllVersions>{searchAllVersions}</cmis:searchAllVersions> <cmis:includeAllowableActions>{includeAllowableActions}</cmis:includeAllowableActions> <cmis:includeRelationships>{includeRelationships}</cmis:includeRelationships> <cmis:renditionFilter>{renditionFilter}</cmis:renditionFilter> <cmis:maxItems>{maxItems}</cmis:maxItems> <cmis:skipCount>{skipCount}</cmis:skipCount> </cmis:query> <?php return ob_get_clean(); } /** * Execute a CMIS Query * @param String $statement Query Statement * @param mixed[] $options Options * @returns Object[] List of object propery values from query * @api CMIS-DiscoveryServices * @since CMIS-1.0 */ function query($q,$options=array()) { static $query_template; if (!isset($query_template)) { $query_template = CMISService::getQueryTemplate(); } $default_hash_values = array( "includeAllowableActions" => "true", "searchAllVersions" => "false", "maxItems" => 10, "skipCount" => 0 ); //print_r($default_hash_values); //print_r($options); $hash_values=array_merge($default_hash_values, $options); $hash_values['q'] = $q; $post_value = CMISRepositoryWrapper::processTemplate($query_template,$hash_values); $ret = $this->doPost($this->workspace->collections['query'],$post_value,MIME_CMIS_QUERY); $objs = $this->extractObjectFeed($ret->body); $this->cacheFeedInfo($objs); return $objs; } /** * @internal */ function checkURL($url,$functionName=null) { if (!$url) { throw new CmisNotSupportedException($functionName?$functionName:"UnspecifiedMethod"); } } /** * Get Content Changes * @param mixed[] $options Options * @returns Object[] List of Change Events * @api CMIS-DiscoveryServices * @since CMIS-1.0 */ function getContentChanges($options = array()) { $myURL = CMISRepositoryWrapper :: processTemplate($this->workspace->links[LINK_CHANGES],$options); $this->checkURL($myURL,"getContentChanges"); $ret = $this->doGet($myURL); $objs = $this->extractObjectFeed($ret->body); $this->cacheFeedInfo($objs); return $objs; } //Object Services /** * @internal */ static function getEntryTemplate() { ob_start(); echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n"; ?> <atom:entry xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/" xmlns:cmism="http://docs.oasis-open.org/ns/cmis/messaging/200908/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/"> <atom:title>{title}</atom:title> {SUMMARY} {CONTENT} <cmisra:object><cmis:properties>{PROPERTIES}</cmis:properties></cmisra:object> </atom:entry> <?php return ob_get_clean(); } /** * @internal */ static function getPropertyTemplate() { ob_start(); ?> <cmis:property{propertyType} propertyDefinitionId="{propertyId}"> <cmis:value>{properties}</cmis:value> </cmis:property{propertyType}> <?php return ob_get_clean(); } /** * @internal */ function processPropertyTemplates($objectType, $propMap) { static $propTemplate; static $propertyTypeMap; if (!isset ($propTemplate)) { $propTemplate = CMISService :: getPropertyTemplate(); } if (!isset ($propertyTypeMap)) { // Not sure if I need to do this like this $propertyTypeMap = array ( "integer" => "Integer", "boolean" => "Boolean", "datetime" => "DateTime", "decimal" => "Decimal", "html" => "Html", "id" => "Id", "string" => "String", "url" => "Url", "xml" => "Xml", ); } $propertyContent = ""; $hash_values = array (); foreach ($propMap as $propId => $propValue) { $hash_values['propertyType'] = $propertyTypeMap[$this->getPropertyType($objectType, $propId)]; $hash_values['propertyId'] = $propId; if (is_array($propValue)) { $first_one = true; $hash_values['properties'] = ""; foreach ($propValue as $val) { //This is a bit of a hack if ($first_one) { $first_one = false; } else { $hash_values['properties'] .= "</cmis:value>\n<cmis:value>"; } $hash_values['properties'] .= $val; } } else { $hash_values['properties'] = $propValue; } //echo "HASH:\n"; //print_r(array("template" =>$propTemplate, "Hash" => $hash_values)); $propertyContent .= CMISRepositoryWrapper :: processTemplate($propTemplate, $hash_values); } return $propertyContent; } /** * @internal */ static function getContentEntry($content, $content_type = "application/octet-stream") { static $contentTemplate; if (!isset ($contentTemplate)) { $contentTemplate = CMISService :: getContentTemplate(); } if ($content) { return CMISRepositoryWrapper :: processTemplate($contentTemplate, array ( "content" => base64_encode($content), "content_type" => $content_type )); } else { return ""; } } /** * @internal */ static function getSummaryTemplate() { ob_start(); ?> <atom:summary>{summary}</atom:summary> <?php return ob_get_clean(); } /** * @internal */ static function getContentTemplate() { ob_start(); ?> <cmisra:content> <cmisra:mediatype>{content_type}</cmisra:mediatype> <cmisra:base64> {content} </cmisra:base64> </cmisra:content> <?php return ob_get_clean(); } /** * @internal */ static function createAtomEntry($name, $properties) { } /** * Get an Object by Object Id * @param String $objectId Object ID * @param mixed[] $options Options * @returns Object * @api CMIS-ObjectServices * @since CMIS-1.0 */ function getObject($objectId, $options = array ()) { $varmap = $options; $varmap["id"] = $objectId; $obj_url = $this->processTemplate($this->workspace->uritemplates['objectbyid'], $varmap); $ret = $this->doGet($obj_url); $obj = $this->extractObject($ret->body); $this->cacheObjectInfo($obj); return $obj; } /** * Get an Object by its Path * @param String $path Path To Object * @param mixed[] $options Options * @returns Object * @api CMIS-ObjectServices * @since CMIS-1.0 */ function getObjectByPath($path, $options = array ()) { $varmap = $options; $varmap["path"] = $path; $obj_url = $this->processTemplate($this->workspace->uritemplates['objectbypath'], $varmap); $ret = $this->doGet($obj_url); $obj = $this->extractObject($ret->body); $this->cacheObjectInfo($obj); return $obj; } /** * Get an Object's Properties by Object Id * @param String $objectId Object Id * @param mixed[] $options Options * @returns Object * @api CMIS-ObjectServices * @since CMIS-1.0 */ function getProperties($objectId, $options = array ()) { // May need to set the options array default -- return $this->getObject($objectId, $options); } /** * Get an Object's Allowable Actions * @param String $objectId Object Id * @param mixed[] $options Options * @returns mixed[] * @api CMIS-ObjectServices * @since CMIS-1.0 */ function getAllowableActions($objectId, $options = array ()) { $myURL = $this->getLink($objectId, LINK_ALLOWABLE_ACTIONS); $ret = $this->doGet($myURL); $result = $this->extractAllowableActions($ret->body); return $result; } /** * Get the list of associated renditions for the specified object * * Only rendition attributes are returned, not rendition stream. * @param String $objectId Object Id * @param mixed[] $options Options * @returns Object[] * @api CMIS-ObjectServices * @since CMIS-1.0 */ function getRenditions($objectId, $options = array ( OPT_RENDITION_FILTER => "*" )) { return getObject($objectId, $options); } /** * Get an Object's Allowable Actions * @param String $objectId Object Id * @param mixed[] $options Options * @returns String * @api CMIS-ObjectServices * @since CMIS-1.0 */ function getContentStream($objectId, $options = array ()) { // Yes $myURL = $this->getLink($objectId, "edit-media"); $ret = $this->doGet($myURL); // doRequest stores the last request information in this object return $ret->body; } /** * @internal */ function legacyPostObject($folderId, $objectName, $objectType, $properties = array (), $content = null, $content_type = "application/octet-stream", $options = array ()) { // Yes $myURL = $this->getLink($folderId, "down"); // TODO: Need Proper Query String Handling // Assumes that the 'down' link does not have a querystring in it $myURL = CMISRepositoryWrapper :: getOpUrl($myURL, $options); static $entry_template; if (!isset ($entry_template)) { $entry_template = CMISService :: getEntryTemplate(); } if (is_array($properties)) { $hash_values = $properties; } else { $hash_values = array (); } if (!isset ($hash_values["cmis:objectTypeId"])) { $hash_values["cmis:objectTypeId"] = $objectType; } $properties_xml = $this->processPropertyTemplates($hash_values["cmis:objectTypeId"], $hash_values); if (is_array($options)) { $hash_values = $options; } else { $hash_values = array (); } $hash_values["PROPERTIES"] = $properties_xml; $hash_values["SUMMARY"] = CMISService :: getSummaryTemplate(); if ($content) { $hash_values["CONTENT"] = CMISService :: getContentEntry($content, $content_type); } if (!isset ($hash_values['title'])) { $hash_values['title'] = preg_replace("/[^A-Za-z0-9\s.&; ]/", '', htmlentities($objectName)); } if (!isset ($hash_values['summary'])) { $hash_values['summary'] = preg_replace("/[^A-Za-z0-9\s.&; ]/", '', htmlentities($objectName)); } /*if (!isset ($hash_values['cmis:name'])) { $hash_values['cmis:name'] = preg_replace("/[^A-Za-z0-9\s.&; ]/", '', htmlentities($objectName)); }*/ $post_value = CMISRepositoryWrapper :: processTemplate($entry_template, $hash_values); $ret = $this->doPost($myURL, $post_value, MIME_ATOM_XML_ENTRY); // print "DO_POST\n"; // print_r($ret); $obj = $this->extractObject($ret->body); $this->cacheObjectInfo($obj); return $obj; } /** * @internal */ function postObject($folderId,$objectName,$objectType,$properties=array(),$content=null,$content_type="application/octet-stream",$options=array()) { // Yes $myURL = $this->getLink($folderId,"down"); // TODO: Need Proper Query String Handling // Assumes that the 'down' link does not have a querystring in it $myURL = CMISRepositoryWrapper::getOpUrl($myURL,$options); static $entry_template; if (!isset($entry_template)) { $entry_template = CMISService::getEntryTemplate(); } if (is_array($properties)) { $hash_values=$properties; } else { $hash_values=array(); } if (!isset($hash_values["cmis:objectTypeId"])) { $hash_values["cmis:objectTypeId"]=$objectType; } $properties_xml = $this->processPropertyTemplates($objectType,$hash_values); if (is_array($options)) { $hash_values=$options; } else { $hash_values=array(); } $hash_values["PROPERTIES"]=$properties_xml; $hash_values["SUMMARY"]=CMISService::getSummaryTemplate(); if ($content) { $hash_values["CONTENT"]=CMISService::getContentEntry($content,$content_type); } if (!isset($hash_values['title'])) { $hash_values['title'] = preg_replace("/[^A-Za-z0-9\s.&; ]/", '', htmlentities($objectName)); } if (!isset($hash_values['summary'])) { $hash_values['summary'] = preg_replace("/[^A-Za-z0-9\s.&; ]/", '', htmlentities($objectName)); } $post_value = CMISRepositoryWrapper::processTemplate($entry_template,$hash_values); $ret = $this->doPost($myURL,$post_value,MIME_ATOM_XML_ENTRY); // print "DO_POST\n"; // print_r($ret); $obj=$this->extractObject($ret->body); $this->cacheObjectInfo($obj); return $obj; } /** * @internal */ function postEntry($url, $properties = array (), $content = null, $content_type = "application/octet-stream", $options = array ()) { // TODO: Fix Hack HERE -- get type if it is there otherwise retrieve it -- $objectType =""; if (isset($properties['cmis:objectTypeId'])) { $objType = $properties['cmis:objectTypeId']; } else if (isset($properties["cmis:objectId"])) { $objType=$this->getObjectType($properties["cmis:objectId"]); } $myURL = CMISRepositoryWrapper :: getOpUrl($url, $options); //DEBUG print("DEBUG: postEntry: myURL = " . $myURL); static $entry_template; if (!isset ($entry_template)) { $entry_template = CMISService :: getEntryTemplate(); } print("DEBUG: postEntry: entry_template = " . $entry_template); $properties_xml = $this->processPropertyTemplates($objType, $properties); print("DEBUG: postEntry: properties_xml = " . $properties_xml); if (is_array($options)) { $hash_values = $options; } else { $hash_values = array (); } $hash_values["PROPERTIES"] = $properties_xml; $hash_values["SUMMARY"] = CMISService :: getSummaryTemplate(); if ($content) { $hash_values["CONTENT"] = CMISService :: getContentEntry($content, $content_type); } print("DEBUG: postEntry: hash_values = " . print_r($hash_values,true)); $post_value = CMISRepositoryWrapper :: processTemplate($entry_template, $hash_values); print("DEBUG: postEntry: post_value = " . $post_value); $ret = $this->doPost($myURL, $post_value, MIME_ATOM_XML_ENTRY); $obj = $this->extractObject($ret->body); $this->cacheObjectInfo($obj); return $obj; } function createDocument($folderId, $fileName, $properties = array (), $content = null, $content_type = "application/octet-stream", $options = array ()) { // Yes return $this->postObject($folderId, $fileName, "cmis:document", $properties, $content, $content_type, $options); } function createDocumentFromSource() { //Yes? throw new CmisNotSupportedException("createDocumentFromSource is not supported by the AtomPub binding!"); } function createFolder($folderId, $folderName, $properties = array (), $options = array ()) { // Yes return $this->legacyPostObject($folderId, $folderName, "cmis:folder", $properties, null, null, $options); } function createRelationship() { // Not in first Release throw new CmisNotImplementedException("createRelationship"); } function createPolicy() { // Not in first Release throw new CmisNotImplementedException("createPolicy"); } function createItem() { throw new CmisNotImplementedException("createItem"); } function updateProperties($objectId, $properties = array (), $options = array ()) { // Yes $varmap = $options; $varmap["id"] = $objectId; $objectName = $this->getTitle($objectId); $objectType = $this->getObjectType($objectId); $obj_url = $this->getLink($objectId, "edit"); $obj_url = CMISRepositoryWrapper :: getOpUrl($obj_url, $options); static $entry_template; if (!isset ($entry_template)) { $entry_template = CMISService :: getEntryTemplate(); } if (is_array($properties)) { $hash_values = $properties; } else { $hash_values = array (); } if (isset($this->_changeToken_cache[$objectId])) { $properties['cmis:changeToken'] = $this->_changeToken_cache[$objectId]; } $properties_xml = $this->processPropertyTemplates($objectType, $hash_values); if (is_array($options)) { $hash_values = $options; } else { $hash_values = array (); } $fixed_hash_values = array( "PROPERTIES" => $properties_xml, "SUMMARY" => CMISService::getSummaryTemplate(), ); // merge the fixes hash values first so that the processing order is correct $hash_values = array_merge($fixed_hash_values, $hash_values); if (!isset($hash_values['title'])) { $hash_values['title'] = $objectName; } if (!isset($hash_values['summary'])) { $hash_values['summary'] = $objectName; } $put_value = CMISRepositoryWrapper :: processTemplate($entry_template, $hash_values); $ret = $this->doPut($obj_url, $put_value, MIME_ATOM_XML_ENTRY); $obj = $this->extractObject($ret->body); $this->cacheObjectInfo($obj); return $obj; } // New for 1.1 function bulkUpdateProperties() { throw new CmisNotImplementedException("bulkUpdateProperties"); } function moveObject($objectId, $targetFolderId, $sourceFolderId, $options = array ()) { //yes $options['sourceFolderId'] = $sourceFolderId; return $this->postObject($targetFolderId, $this->getTitle($objectId), $this->getObjectType($objectId), array ( "cmis:objectId" => $objectId ), null, null, $options); } /** * Delete an Object * @param String $objectId Object ID * @param mixed[] $options Options * @api CMIS-ObjectServices * @since CMIS-1.0 */ function deleteObject($objectId, $options = array ()) { //Yes $varmap = $options; $varmap["id"] = $objectId; $obj_url = $this->getLink($objectId, "edit"); $ret = $this->doDelete($obj_url); return $ret; } /** * Delete an Object Tree * @param String $folderId Folder Object ID * @param mixed[] $options Options * @return Object[] Array of problem objects * @api CMIS-ObjectServices * @since CMIS-1.0 */ function deleteTree($folderId, $options = array ()) { // Nice to have $hash_values = $options; $myURL = $this->getLink($folderId, LINK_DOWN_TREE); $myURL = CMISRepositoryWrapper :: getOpUrl($myURL, $hash_values); $ret = $this->doDelete($myURL); //List of problem objects $objs = $this->extractObjectFeed($ret->body); $this->cacheFeedInfo($objs); return $objs; } /** * Set an Objects Content Stream * @param String $objectId Object ID * @param String $content Content to be appended * @param String $content_type Content Mime Type * @param mixed[] $options Options * @returns Object * @api CMIS-ObjectServices * @since CMIS-1.0 */ function setContentStream($objectId, $content, $content_type, $options = array ()) { //Yes $myURL = $this->getLink($objectId, "edit-media"); $ret = $this->doPut($myURL, $content, $content_type); } // New for 1.1 /** * Append Content to an Objects Content Stream * @param String $objectId Object ID * @param String $content Content to be appended * @param String $content_type Content Mime Type * @param mixed[] $options Options * @returns Object * @api CMIS-ObjectServices-NotImplemented * @since CMIS-1.0 */ function appendContentStream($objectId, $content, $content_type, $options = array ()) { //Yes throw new CmisNotImplementedException("appendContentStream"); } /** * Delete an Objects Content Stream * @param String $objectId Object ID * @param mixed[] $options Options * @api CMIS-ObjectServices * @since CMIS-1.0 */ function deleteContentStream($objectId, $options = array ()) { //yes $myURL = $this->getLink($objectId, "edit-media"); $ret = $this->doDelete($myURL); return; } //Versioning Services function getPropertiesOfLatestVersion($objectId, $major = false, $options = array ()) { return $this->getObjectOfLatestVersion($objectId, $major, $options); } function getObjectOfLatestVersion($objectId, $major = false, $options = array ()) { return $this->getObject($objectId, $options); // Won't be able to handle major/minor distinction // Need to add this -- "current-version" /* * Headers: CMIS-filter, CMIS-returnVersion (enumReturnVersion) * HTTP Arguments: filter, returnVersion * Enum returnVersion: This, Latest, Major */ } function getAllVersions() { throw new CmisNotImplementedException("getAllVersions"); } /** * Checkout * @param String $objectId Object ID * @param mixed[] $options Options * @return Object The working copy * @api CMIS-VersionServices * @since CMIS-1.0 */ function checkOut($objectId,$options = array()) { $myURL = $this->workspace->collections[COLLECTION_CHECKED_OUT]; $myURL = CMISRepositoryWrapper :: getOpUrl($myURL, $options); $ret = $this->postEntry($myURL, array ("cmis:objectId" => $objectId)); $obj = $this->extractObject($ret->body); $this->cacheObjectInfo($obj); return $obj; } /** * Checkin * @param String $objectId Object ID * @param mixed[] $options Options * @return Object The checked in object * @api CMIS-VersionServices * @since CMIS-1.0 */ function checkIn($objectId,$options = array()) { $myURL = $this->workspace->collections[COLLECTION_CHECKED_OUT]; $myURL = CMISRepositoryWrapper :: getOpUrl($myURL, $options); $ret = $this->postEntry($myURL, array ("cmis:objectId" => $objectId)); $obj = $this->extractObject($ret->body); $this->cacheObjectInfo($obj); return $obj; } /** * Cancel Checkout * @param String $objectId Object ID * @param mixed[] $options Options * @api CMIS-VersionServices * @since CMIS-1.0 */ function cancelCheckOut($objectId,$options = array()) { // TODO: Look at links "via" and "working-copy" $varmap = $options; $varmap["id"] = $objectId; $via = $this->getLink($objectId,"via"); print("DEBUG: cancelCheckOut VIA="+$via); if (!$via) { throw new CmisInvalidArgumentException("Not a WORKING COPY!"); } $obj_url = $this->getLink($objectId, "edit"); $ret = $this->doDelete($obj_url); return; } function deleteAllVersions() { throw new CmisNotImplementedException("deleteAllVersions"); } //Relationship Services function getObjectRelationships() { // get stripped down version of object (for the links) and then get the relationships? // Low priority -- can get all information when getting object throw new CmisNotImplementedException("getObjectRelationships"); } //Multi-Filing ServicesRelation function addObjectToFolder($objectId, $targetFolderId, $options = array ()) { // Probably return $this->postObject($targetFolderId, $this->getTitle($objectId), $this->getObjectType($objectId), array ( "cmis:objectId" => $objectId ), null, null, $options); } function removeObjectFromFolder($objectId, $targetFolderId, $options = array ()) { //Probably $hash_values = $options; $myURL = $this->workspace->collections['unfiled']; $myURL = CMISRepositoryWrapper :: getOpUrl($myURL, $hash_values); $ret = $this->postEntry($myURL, array ("cmis:objectId" => $objectId),null,null,array("removeFrom" => $targetFolderId)); $obj = $this->extractObject($ret->body); $this->cacheObjectInfo($obj); return $obj; } //Policy Services function getAppliedPolicies() { throw new CmisNotImplementedException("getAppliedPolicies"); } function applyPolicy() { throw new CmisNotImplementedException("applyPolicy"); } function removePolicy() { throw new CmisNotImplementedException("removePolicy"); } //ACL Services function getACL() { throw new CmisNotImplementedException("getACL"); } function applyACL() { throw new CmisNotImplementedException("applyACL"); } }
b472539d89de4a3bdb14e7626a89977d4b82c364
[ "Markdown", "PHP" ]
4
PHP
donbalon4/API_Alfresco
d35b6488f229d54f1934a90ea311db801407cc88
b178a3d4c80af799dfd8ef3b55a897f285dba2a9
refs/heads/master
<repo_name>markanator/lireddit<file_sep>/client/src/hooks/useGetPostFromUrl.ts import { usePostDetailsQuery } from "../generated/graphql"; import { useGetPostId } from "./useGetPostId"; export const useGetPostFromUrl = () => { const intId = useGetPostId(); return usePostDetailsQuery({ variables: { id: intId, }, }); }; <file_sep>/README.md # lite-reddit A smallscale clone of reddit made with, NextJS ChakraUI on the front end and TypeORM, GraphQL, and PostgreSQL for the backend. Focus on learning Typescript, GraphQL, Docker and DevOps. <file_sep>/client/src/components/DarkModeSwitch.tsx import { useColorMode, Switch } from "@chakra-ui/react"; export const DarkModeSwitch = () => { const { colorMode, toggleColorMode } = useColorMode(); const isDark = colorMode === "dark"; return <Switch color="green" isChecked={isDark} onChange={toggleColorMode} />; }; <file_sep>/server/src/utils/createUpvoteLoader.ts import DataLoader from "dataloader"; import { Upvote } from "../entities/Upvote"; export const createUpvoteLoader = () => new DataLoader<{ postId: number; userId: number }, Upvote | null>( async (keys) => { // get all user in one query const upvotes = await Upvote.findByIds(keys as any); // need to return data const upvoteIdsToUpvote: Record<string, Upvote> = {}; upvotes.forEach((vote) => { upvoteIdsToUpvote[`${vote.userId} | ${vote.postId}`] = vote; }); return keys.map( (key) => upvoteIdsToUpvote[`${key.userId} | ${key.postId}`] ); } );
d756d16b13bf40ccdda0d191e57412b5e1bb6ca8
[ "Markdown", "TypeScript", "JavaScript" ]
4
TypeScript
markanator/lireddit
e3dcc776b0ee18606ed97d92379512b9264d4ccb
21170ecad1deffc3625e994b83ba6a045ac94de2
refs/heads/master
<repo_name>SoroushMehraban/Jpotify<file_sep>/src/com/GUIFrame/GUIFrame.java package com.GUIFrame; import com.Interfaces.PlaylistOptionLinker; import com.Interfaces.ShowSongsLinker; import com.Interfaces.SongPanelsLinker; import com.MP3.AppStorage; import com.MP3.MP3Info; import com.Panels.CenterPanelSections.SharedSongPanel; import com.Panels.CenterPanelSections.SongPanel; import com.Panels.NorthPanelSections.EastPanelServerThread; import com.Panels.GeneralPanels.*; import com.Panels.NorthPanelSections.EastPanelClientThread; import com.mpatric.mp3agic.InvalidDataException; import com.mpatric.mp3agic.UnsupportedTagException; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.plaf.basic.BasicScrollBarUI; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER; /** * the window GUI where User can play a music. * when user run this program, its only create one instance of this class, so it's a singleton class. * * @author <NAME> & <NAME> * @version 1.0 */ public class GUIFrame extends JFrame implements Serializable { private static GUIFrame guiFrame; private static SouthPanel southPanel; private static CenterPanel centerPanel; private static WestPanel westPanel; private static EastPanel eastPanel; private static JPanel artworkPanel; private static String username; private static EastPanelServerThread mainServerThread; private static EastPanelClientThread mainClientThread; //private static transient ScrollerPlusIconListener mainClientThread; /** * Class Constructor */ private GUIFrame() throws IOException { JTextField usernameField = new JTextField(10);//creating a field to input user name. JPanel myPanel = new JPanel();//creating a label to hold that field. myPanel.add(new JLabel("Username:"));//creating a label to show user should input username and adding it to myPanel myPanel.add(usernameField);//adding text field to myPanel int result = JOptionPane.showConfirmDialog(null, myPanel, "Please Enter Your Username", JOptionPane.OK_CANCEL_OPTION);//showing a JOptionPane to enter input if (result == JOptionPane.OK_OPTION) {//if user pressed enter guiFrame = this; username = usernameField.getText();//setting program username. Image frameIcon = ImageIO.read(new File("Icons/frameIcon.png")); this.setIconImage(frameIcon); this.setLayout(new BorderLayout()); //frame layout this.setSize(1050, 512); //frame length : 940 * 512 this.setLocationRelativeTo(null); //setting frame at the center of screen this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //closing the program when user close the window. this.setMinimumSize(new Dimension(1050, 512)); centerPanel = new CenterPanel(); this.add(centerPanel, BorderLayout.CENTER); southPanel = new SouthPanel(); southPanel.setLyricsLinker(centerPanel.getCenterPart()); this.add(southPanel, BorderLayout.SOUTH); westPanel = new WestPanel(); artworkPanel = new JPanel(); artworkPanel.setLayout(new BoxLayout(artworkPanel, BoxLayout.LINE_AXIS)); JPanel westContainer = createWestContainer(westPanel, artworkPanel); this.add(westContainer, BorderLayout.WEST); eastPanel = new EastPanel(); JScrollPane eastPanelJScrollPane = new JScrollPane(eastPanel); eastPanelJScrollPane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER); customizeJScrollPane(eastPanelJScrollPane); this.add(eastPanelJScrollPane, BorderLayout.EAST); this.setVisible(true); //setting like linker between playPanel in southPanel and centerPart in centerPanel: southPanel.getPlayPanel().setLikeLinker(centerPanel.getCenterPart()); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { AppStorage.saveSongs(); } }); AppStorage.loadSongs();//loading songs if user has from previous run showHome();//showing home by default mainServerThread = new EastPanelServerThread(); mainServerThread.start(); //mainClientThread=new ScrollerPlusIconListener(); //Thread clientThread=new Thread(mainClientThread); //clientThread.start(); //RadioClient radioClient = new RadioClient(); } } /** * getting instance of class. * * @return a unique com.GUIFrame.GUIFrame object. */ public static GUIFrame getInstance() { if (guiFrame == null) { try { guiFrame = new GUIFrame(); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Error creating GUIFrame","an error occurred",JOptionPane.ERROR_MESSAGE); } } return guiFrame; } /** * reloading com.GUIFrame.GUIFrame when components changes. */ public static void reload() { if (guiFrame != null) { guiFrame.repaint(); guiFrame.revalidate(); } } /** * This method works as a linker and link RadioClient with center part of centeral panel to add radio songs. * * @param songTitle given song title * @param artist given song artist */ public static void addRadioSong(String songTitle, String artist) { centerPanel.getCenterPart().addRadioSong(songTitle, artist); centerPanel.getCenterPart().showRadioSongs(); } /** * This method works as a linker and show home after Home clicked in west panel. */ public static void showHome() { centerPanel.getCenterPart().showHome(); } /** * this method play clicked music and then can be controlled in south panel. * it also reload artwork panel and shows new artwork of playing music. * * @param songPanel song we want to play. */ public static void playClickedMusic(SongPanel songPanel) { try { Image playingArtwork = songPanel.getMp3Info().getImage().getScaledInstance(150, 150, Image.SCALE_SMOOTH); artworkPanel.removeAll();//removing previous artwork in artwork panel artworkPanel.add(new JLabel(new ImageIcon(playingArtwork)));//adding new artwork to show reload();//reload to show the changes southPanel.play(songPanel, centerPanel.getCenterPart().getCurrentPlaying()); ArrayList<SongPanel> sharedSongs = centerPanel.getCenterPart().getSharedSongs(); for (SongPanel sharedSong : sharedSongs) { if (sharedSong.getMp3Info().getTitle().equals(songPanel.getMp3Info().getTitle())) { if (mainClientThread != null) { mainClientThread.setSongArtist(sharedSong.getMp3Info().getArtist()); mainClientThread.setSongTitle(sharedSong.getMp3Info().getTitle()); } mainServerThread.setSongTitle(sharedSong.getMp3Info().getTitle()); mainServerThread.setSongArtist(sharedSong.getMp3Info().getArtist()); break; } } } catch (InvalidDataException | IOException | UnsupportedTagException e) { JOptionPane.showMessageDialog(null, "Error reading artwork image for showing in west panel", "An Error Occurred", JOptionPane.ERROR_MESSAGE); } } public static String getUsername() { return username; } /** * This method is a linker between socketTreads and center part of center panel and give socket threads shared songs. * * @return shared songs of this user. */ public static ArrayList<SongPanel> getSharedSongs() { return centerPanel.getCenterPart().getSharedSongs(); } /** * a linker between socket threads and center part of center panel. * * @param sharedSongPanels sharedSongs to show. */ public static void showSharedSongs(ArrayList<SharedSongPanel> sharedSongPanels) { centerPanel.getCenterPart().showSharedSongs(sharedSongPanels); } /** * this method add an album which is selected in library. * * @param albumTitle title of album to be shown. * @param albumMusicsInfo list of all musics info which related to a album. */ public static void addAlbum(String albumTitle, ArrayList<MP3Info> albumMusicsInfo) { centerPanel.getCenterPart().addAlbum(albumTitle, albumMusicsInfo); } /** * Creating playlist which is implemented in center part of centerPanel(this method works as a linker) * * @param title title of play list. * @param description description to show under the title. */ public static void createPlayList(String title, String description) { centerPanel.getCenterPart().createPlayList(title, description); showHome(); } /** * this method adds a song to given playlist.(works as a linker) * * @param playListTitle title of playlist as a key of HashMap. * @param description description of playlist(helps us to create one if it doesn't exist) * @param songDirectory directory of music to add. */ public static void addSongToPlayList(String playListTitle, String description, String songDirectory) { centerPanel.getCenterPart().addSongToPlayList(playListTitle, description, songDirectory); } /** * This method works as a linker between west panel and center panel and shows all songs existing in library. */ public static void showAllSongs() { centerPanel.getCenterPart().showAllSongs(); } /** * this method works as a linker between west part panel and center panel and shows all songs related to an album * * @param albumTitle album title as a key. */ public static void showAlbumSongs(String albumTitle) { centerPanel.getCenterPart().showAlbumSongs(albumTitle); } /** * this method works as a linker between west part panel and center panel and shows all songs related to a playList * * @param playlistTitle playlist title as a key. */ public static void showPlaylistSongs(String playlistTitle) { centerPanel.getCenterPart().showPlayListSongs(playlistTitle); } /** * This method work as a linker. * * @return list of playlist titles. */ public static ArrayList<String> getPlayistTitles() { return centerPanel.getCenterPart().getPlayistTitles(); } /** * this method work as a linker * * @return list of album titles. */ public static ArrayList<String> getAlbumTitles() { return centerPanel.getCenterPart().getAlbumTitles(); } public static PlaylistOptionLinker getPlaylistOptionLinker() { return centerPanel.getCenterPart(); } public static WestPanel getWestPanel() { return westPanel; } public static ShowSongsLinker getShowSongsLinker() { return centerPanel.getCenterPart(); } /** * getting this helps us to control song panels in AppStorage and playlist panels. */ public static SongPanelsLinker getSongPanelsLinker() { return centerPanel.getCenterPart(); } /** * this method customize JScrollPane's color to fit in center part theme. * * @param jScrollPane our jScrollPane to to be customized. */ public static void customizeJScrollPane(JScrollPane jScrollPane) { jScrollPane.getHorizontalScrollBar().setUI(createBasicScrollBarUI()); jScrollPane.getVerticalScrollBar().setUI(createBasicScrollBarUI()); jScrollPane.setBackground(new Color(23, 23, 23)); } /** * This method create Basic Scroll Bar UI which sets color of JScroll bar. * * @return desired basic scroll bar UI. */ private static BasicScrollBarUI createBasicScrollBarUI() { return new BasicScrollBarUI() { @Override protected void configureScrollBarColors() { this.thumbColor = new Color(84, 84, 84); this.trackColor = new Color(23, 23, 23); } @Override protected JButton createIncreaseButton(int orientation) { return new BasicArrowButton(orientation, new Color(23, 23, 23), new Color(23, 23, 23), new Color(84, 84, 84), new Color(23, 23, 23)); } protected JButton createDecreaseButton(int orientation) { return new BasicArrowButton(orientation, new Color(23, 23, 23), new Color(23, 23, 23), new Color(84, 84, 84), new Color(23, 23, 23)); } }; } /** * this private method creates a container which holds west panel and artwork panel * * @param westPanel program west panel * @param artworkPanel artwork panel which shows artworks after playing song. * @return desired container */ private JPanel createWestContainer(WestPanel westPanel, JPanel artworkPanel) { JPanel westContainer = new JPanel(); westContainer.setLayout(new BoxLayout(westContainer, BoxLayout.PAGE_AXIS)); JScrollPane leftJScrollPane = new JScrollPane(westPanel); leftJScrollPane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER); leftJScrollPane.setPreferredSize(new Dimension(150, 512)); customizeJScrollPane(leftJScrollPane); westContainer.add(leftJScrollPane); westContainer.add(artworkPanel); westContainer.setPreferredSize(new Dimension(150, 100)); return westContainer; } public static EastPanelServerThread getMainThread() { return mainServerThread; } public static String getUserName() { return username; } public static EastPanel getEastPanel() { return eastPanel; } public static GUIFrame getGUIFrame() { return guiFrame; } public static void setMainServerThread(EastPanelServerThread mainServerThread) { GUIFrame.mainServerThread = mainServerThread; } public static void setMainClientThread(EastPanelClientThread mainClientThread) { GUIFrame.mainClientThread = mainClientThread; } /** * This method works as a linker to add new user to north part JCombobox. * * @param newUser new user to add. */ public static void addConnectedUserNameJCombobox(String newUser) { centerPanel.getNorthPart().addUser(newUser); } /** * * This method works as a linker to remove user from north part JCombobox. * * @param user new user to remove. */ public static void removeUserNameExited(String user){ centerPanel.getNorthPart().removeUser(user); } /** * this method works as a linker and set true value to hash map of showSharedSongs in mainThreads. * so in pear to pear socket threads, our client/server order to given parameter user to let us see user's shared songs. * * @param user given user */ public static void setShowSharedSongs(String user) { if (mainServerThread != null) { mainServerThread.setShowSharedSongsRequest(user); } if (mainClientThread != null) { mainClientThread.setShowSharedSongsReqest(user); } } /** * it sets the sizes of different images used in different parts of the program. * * @param directory the directory of the image. * @param scale the scale of the image. * @return a preferred size image. */ public static ImageIcon setIconSize(String directory, int scale) { ImageIcon output = new ImageIcon(directory); Image newImage = output.getImage(); Image newimg = newImage.getScaledInstance(scale, scale, Image.SCALE_SMOOTH); output = new ImageIcon(newimg); return output; } }<file_sep>/src/com/Panels/GeneralPanels/WestPanel.java package com.Panels.GeneralPanels; import com.GUIFrame.GUIFrame; import com.Panels.WestPanelSections.WestPanelListeners.*; import javax.swing.*; import java.awt.*; /** * This Class is about west panel of our program,It has features: * HOME: it shows list of albums and playlist in center panel. * Library: it opens a file chooser to select desired mp3 files. * Songs: it shows all songs based on last playing. * Albums: it opens list of albums and user can open them. * Playlist: it opens list of playlist and user can open them. */ public class WestPanel extends JPanel { private static WestPanel westPanel; private static JPanel albumsPanel; private static JPanel homePanel; private static JPanel songsPanel; private static JPanel libraryPanel; private static JPanel playListsPanel; public WestPanel() { westPanel = this; JLabel homeLabel; JLabel homeIcon; JLabel libraryLabel; JLabel libraryIcon; JLabel addToLibraryIcon; JLabel songsLabel; JLabel songsIcon; JLabel albumsLabel; JLabel albumsIcon; JLabel playListsLabel; JLabel playListsIcon; JLabel addToPlaylistsIcon; this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); this.setBackground(new Color(23, 23, 23)); //designing home panel: homePanel = new JPanel(); homePanel.setBackground(new Color(23, 23, 23)); homePanel.setLayout(new BoxLayout(homePanel, BoxLayout.LINE_AXIS)); homeIcon = new JLabel(); homeIcon.setIcon(setIconSize("Icons/Home-no-select.png", 20)); homeLabel = new JLabel(" HOME"); homeIcon.addMouseListener(new HomePanelListener(homeIcon, homeLabel)); homeLabel.addMouseListener(new HomePanelListener(homeIcon, homeLabel)); homeLabel.setForeground(Color.WHITE); homePanel.add(homeIcon); homePanel.add(homeLabel); this.add(Box.createVerticalStrut(20)); this.add(homePanel); this.add(Box.createVerticalStrut(50)); //designing library panel: libraryPanel = new JPanel(); libraryPanel.setBackground(new Color(23, 23, 23)); libraryPanel.setLayout(new BoxLayout(libraryPanel, BoxLayout.LINE_AXIS)); libraryLabel = new JLabel(" Library "); libraryLabel.setForeground(Color.WHITE); libraryIcon = new JLabel(); libraryIcon.setIcon(setIconSize("Icons/Library-no-select.PNG", 20)); addToLibraryIcon = new JLabel(); addToLibraryIcon.setIcon(setIconSize("Icons/Plus-no-select.PNG", 10)); libraryLabel.addMouseListener(new LibraryPanelListener(libraryIcon, libraryLabel, addToLibraryIcon)); libraryIcon.addMouseListener(new LibraryPanelListener(libraryIcon, libraryLabel, addToLibraryIcon)); addToLibraryIcon.addMouseListener(new LibraryPanelListener(libraryIcon, libraryLabel, addToLibraryIcon)); libraryPanel.add(libraryIcon); libraryPanel.add(libraryLabel); libraryPanel.add(addToLibraryIcon); this.add(libraryPanel); this.add(Box.createVerticalStrut(30)); //designing song panel: songsPanel = new JPanel(); songsPanel.setBackground(new Color(23, 23, 23)); songsPanel.setLayout(new BoxLayout(songsPanel, BoxLayout.LINE_AXIS)); songsIcon = new JLabel(); songsIcon.setIcon(setIconSize("Icons/Song-no-selected.png", 20)); songsPanel.add(songsIcon); songsLabel = new JLabel(" Songs"); songsIcon.addMouseListener(new SongsPanelListener(songsIcon, songsLabel)); songsLabel.addMouseListener(new SongsPanelListener(songsIcon, songsLabel)); songsLabel.setForeground(Color.WHITE); songsPanel.add(songsLabel); this.add(songsPanel); this.add(Box.createVerticalStrut(30)); //designing albums panel: albumsPanel = new JPanel(); albumsPanel.setBackground(new Color(23, 23, 23)); albumsPanel.setLayout(new BoxLayout(albumsPanel, BoxLayout.LINE_AXIS)); albumsIcon = new JLabel(); albumsIcon.setIcon(setIconSize("Icons/Album-no-selected.png", 20)); albumsPanel.add(albumsIcon); albumsLabel = new JLabel(" Albums"); AlbumsPanelListener AlbumsTempListener = new AlbumsPanelListener(albumsIcon, albumsLabel); albumsIcon.addMouseListener(AlbumsTempListener); albumsLabel.addMouseListener(AlbumsTempListener); albumsLabel.setForeground(Color.WHITE); albumsPanel.add(albumsLabel); this.add(albumsPanel); this.add(Box.createVerticalStrut(30)); //designing playlist panel: playListsPanel = new JPanel(); playListsPanel.setBackground(new Color(23, 23, 23)); playListsPanel.setLayout(new BoxLayout(playListsPanel, BoxLayout.LINE_AXIS)); playListsIcon = new JLabel(); playListsIcon.setIcon(setIconSize("Icons/p-no-selected.png", 20)); playListsPanel.add(playListsIcon); playListsLabel = new JLabel(" Playlists "); playListsLabel.setForeground(Color.WHITE); playListsPanel.add(playListsLabel); PlaylistsListener playlistsTempListener = new PlaylistsListener(playListsIcon, playListsLabel); playListsIcon.addMouseListener(playlistsTempListener); playListsLabel.addMouseListener(playlistsTempListener); addToPlaylistsIcon = new JLabel(); addToPlaylistsIcon.setIcon(setIconSize("Icons/Plus-no-select.PNG", 10)); playListsPanel.add(addToPlaylistsIcon); addToPlaylistsIcon.addMouseListener(new PlaylistsPlusIconListener(addToPlaylistsIcon)); this.add(playListsPanel); } /** * This method changes size of icons. * * @param directory directory of image to change * @param scale scale we want to resize. * @return resized image icon. */ public static ImageIcon setIconSize(String directory, int scale) { ImageIcon output = GUIFrame.setIconSize(directory, scale); return output; } public static JPanel getAlbumsPanel() { return albumsPanel; } public static void setAlbumsPanel(JPanel changedAlbums) { albumsPanel = changedAlbums; } public static JPanel getPlayListsPanel() { return playListsPanel; } public static void setPlayListsPanel(JPanel changedPlaylists) { playListsPanel = changedPlaylists; } } <file_sep>/src/com/Panels/NorthPanelSections/EastPanelServerThread.java package com.Panels.NorthPanelSections; import java.util.ArrayList; /** * This class handles the operations which are related to the server thread. * * @author <NAME> & <NAME> * @version 1.0 */ public class EastPanelServerThread extends Thread { private ArrayList<ServerThread> serverThreads; private int requestDownloadIndex; public EastPanelServerThread() { serverThreads = new ArrayList<>(); } /** * this method send a request to given user to turn back all songs user has in shared songs. * * @param user user we want to get him/her his/her shared songs. */ public void setShowSharedSongsRequest(String user) { for (ServerThread serverThread : serverThreads) if (serverThread.getConnectedUser().equals(user)) { serverThread.setRequestMade(true); break; } } @Override public void run() { while (true) { //System.out.println("Trying to connect.."); ServerThread serverThread = new ServerThread(); // System.out.println("Connected!"); serverThread.start(); serverThreads.add(serverThread); } } public void setSongTitle(String songTitle) { for (ServerThread serverThread : serverThreads) serverThread.setSongTitle(songTitle); } public void setSongArtist(String songArtist) { for (ServerThread serverThread : serverThreads) serverThread.setSongArtist(songArtist); } } <file_sep>/src/com/Panels/SouthPanelSections/EastPartPanel.java package com.Panels.SouthPanelSections; import com.GUIFrame.GUIFrame; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.FloatControl; import javax.sound.sampled.Line.Info; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.Port; /** * This class is about east part of south panel * it has a Sound Bar where user can change volume of music * * @author <NAME> & <NAME> * @version 1.0 */ public class EastPartPanel extends JPanel { private JProgressBar soundBar; private JProgressBar sound; private BufferedImage soundImageOff; private BufferedImage soundImageLow; private BufferedImage soundImageMed; private BufferedImage soundImageHigh; private JLabel soundLabel; private int lastSoundBarValue; /** * class constuctor, * it creates a sound bar which is a JProgressBar and creates a volume image label beside of it * * @throws IOException if fails opening image icons. */ public EastPartPanel() throws IOException { //setting layout to Box layout and Line axis: this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); //setting background: this.setBackground(new Color(41, 41, 41)); //loading icons: soundImageOff = ImageIO.read(new File("Icons/No-Sound-no-select.png")); soundImageLow = ImageIO.read(new File("Icons/Low-Sound-no-select.png")); soundImageMed = ImageIO.read(new File("Icons/Med-Sound-no-select.png")); soundImageHigh = ImageIO.read(new File("Icons/High-Sound-no-select.png")); //creating soundlabel: soundLabel = new JLabel(new ImageIcon(soundImageMed)); createSoundLabelAction(); //creating soundBar: soundBar = new JProgressBar(); soundBar.setBorder(javax.swing.BorderFactory.createEmptyBorder()); soundBar.setPreferredSize(new Dimension(40, 7)); soundBar.setMaximumSize(soundBar.getPreferredSize()); soundBar.setMinimumSize(soundBar.getPreferredSize()); createSoundBarAction(); soundBar.setValue(50); lastSoundBarValue = 50; changeVolumeSystem(50); //adding components to panel: this.add(soundLabel); this.add(Box.createHorizontalStrut(5)); this.add(soundBar); this.add(Box.createHorizontalStrut(20)); } /** * This method demonstrate what happens if mouse pressed or dragged on sound bar. * when mouse pressed: it changes volume to time where user clicks. * when mouse dragged: it drags sound bar with mouse and after that,changes volume to that point. */ private void createSoundBarAction() { soundBar.addMouseMotionListener(new MouseAdapter() { @Override public void mouseDragged(MouseEvent e) { soundBar.setValue((int) (e.getX() / ((double) soundBar.getWidth()) * 100)); changeVolumeSystem((float) (e.getX() / ((double) soundBar.getWidth()))); lastSoundBarValue = soundBar.getValue(); setSoundIcon(); } }); soundBar.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { changeVolumeSystem((float) (e.getX() / ((double) soundBar.getWidth()))); soundBar.setValue((int) (e.getX() / ((double) soundBar.getWidth()) * 100)); lastSoundBarValue = soundBar.getValue(); setSoundIcon(); } }); } /** * this method changes image icon beside sound bar parallel with changing it. */ private void setSoundIcon() { if (soundBar.getValue() >= 75) soundLabel.setIcon(new ImageIcon(soundImageHigh)); else if (soundBar.getValue() >= 25) soundLabel.setIcon(new ImageIcon(soundImageMed)); else if (soundBar.getValue() > 0) soundLabel.setIcon(new ImageIcon(soundImageLow)); else soundLabel.setIcon(new ImageIcon(soundImageOff)); GUIFrame.reload(); } /** * This method demonstrate what happens if mouse pressed,entered or exited from sound Icon beside sound bar. * when mouse pressed: if volume is >0 it cuts it off but when is =0 it changes to previous volume or 0.5 if it's recent value is 0. * when mouse entered: it made that bottom look brighter. * when mouse exited: it changes to previous form. */ private void createSoundLabelAction() { soundLabel.addMouseListener(new MouseAdapter( ) { @Override public void mousePressed(MouseEvent e) { if (soundBar.getValue() > 0) { changeVolumeSystem(0); soundBar.setValue(0); soundLabel.setIcon(new ImageIcon(soundImageOff)); } else { if (lastSoundBarValue > 0) soundBar.setValue(lastSoundBarValue); else soundBar.setValue(50); changeVolumeSystem((float) (soundBar.getValue() / 100.0)); setSoundIcon(); } } @Override public void mouseEntered(MouseEvent e) { try { if (soundBar.getValue() >= 75) soundImageHigh = ImageIO.read(new File("Icons/High-Sound.png")); else if (soundBar.getValue() >= 25) soundImageMed = ImageIO.read(new File("Icons/Med-Sound.png")); else if (soundBar.getValue() > 0) soundImageLow = ImageIO.read(new File("Icons/Low-Sound.png")); else soundImageOff = ImageIO.read(new File("Icons/No-Sound.png")); setSoundIcon(); } catch (IOException e1) { e1.printStackTrace(); } } @Override public void mouseExited(MouseEvent e) { try { if (soundBar.getValue() >= 75) soundImageHigh = ImageIO.read(new File("Icons/High-Sound-no-select.png")); else if (soundBar.getValue() >= 25) soundImageMed = ImageIO.read(new File("Icons/Med-Sound-no-select.png")); else if (soundBar.getValue() > 0) soundImageLow = ImageIO.read(new File("Icons/Low-Sound-no-select.png")); else soundImageOff = ImageIO.read(new File("Icons/No-Sound-no-select.png")); setSoundIcon(); } catch (IOException e1) { e1.printStackTrace(); } super.mouseExited(e); } }); } /** * Changing volume to where user desired. * this method doesn't change volume which shows at right corner of task bar of windows and just change music volume. * * @param volume desired value of volume */ private void changeVolumeSystem(float volume) { Info source = Port.Info.SPEAKER;//getting speaker's source if (AudioSystem.isLineSupported(source))//if AudioSystem support it and we can change it { try { Port outline = (Port) AudioSystem.getLine(source); outline.open(); FloatControl volumeControl = (FloatControl) outline.getControl(FloatControl.Type.VOLUME); if (volume > 0.02f) volumeControl.setValue(volume); else volumeControl.setValue(0); } catch (LineUnavailableException ex) { JOptionPane.showMessageDialog(null, "source not supported"); } } } } <file_sep>/src/com/Panels/WestPanelSections/WestPanelListeners/PlaylistsPlusIconListener.java package com.Panels.WestPanelSections.WestPanelListeners; import com.GUIFrame.GUIFrame; import com.Panels.GeneralPanels.WestPanel; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * playlist plus icon listener does this jobs: * -when mouse Clicked: * it shows a JOptionPane for user to enter playlist title and description * if user pressed ok after that, it creates one,else it doesn't create anything. * -when mouse Entered: * it updates playlist plus icon to become brighter * -when mouse Exited: * it updates playlist plus icon and turn to previous form. * * @author <NAME> & <NAME> * @version 1.0 */ public class PlaylistsPlusIconListener extends MouseAdapter { private JLabel icon; /** * Class constructor, only sets plus icon * * @param icon plus icon. */ public PlaylistsPlusIconListener(JLabel icon) { this.icon = icon; } @Override public void mouseClicked(MouseEvent e) {//showing a JOptionPane to enter playlist title and description: JTextField titleField = new JTextField(10); JTextField descriptionField = new JTextField(10); JPanel myPanel = new JPanel(); myPanel.add(new JLabel("Title:")); myPanel.add(titleField); myPanel.add(Box.createHorizontalStrut(50)); myPanel.add(Box.createVerticalStrut(100)); myPanel.add(new JLabel("Description:")); myPanel.add(descriptionField); int result = JOptionPane.showConfirmDialog(null, myPanel, "Please Enter Title and Description", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) {//if user pressed ok GUIFrame.createPlayList(titleField.getText(), descriptionField.getText());//creating new playlist GUIFrame.reload(); } } @Override public void mouseEntered(MouseEvent e) { icon.setIcon(WestPanel.setIconSize("Icons/Plus.png", 10)); } @Override public void mouseExited(MouseEvent e) { icon.setIcon(WestPanel.setIconSize("Icons/Plus-no-select.PNG", 10)); } } <file_sep>/src/com/Interfaces/LikeLinker.java package com.Interfaces; /** * and interface that links center part of center panel with play panel in south panel. * * @author <NAME> & <NAME> * @version 1.0 */ public interface LikeLinker { /** * when like button pressed. if it wasn't press before, this method adds music to favorite play list. * * @param directory directory of current music. */ void addToFavoritePlayList(String directory); /** * when like button pressed. if it was press before, this method adds music to favorite play list. * * @param directory directory of current music. */ void removeFromFavoritePlayList(String directory); /** * determine if song is liked before or not. * * @param directory directory of song */ boolean isSongLiked(String directory); } <file_sep>/src/com/Panels/NorthPanelSections/UserThread.java package com.Panels.NorthPanelSections; import com.GUIFrame.GUIFrame; import com.Panels.CenterPanelSections.SharedSongPanel; import com.Panels.CenterPanelSections.SongPanel; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.image.BufferedImage; import java.io.*; import java.net.Socket; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Scanner; /** * in our program user is server and client in same time, as a client for each server we want to connect, * we create a UserThread to handle operations needed to handle with connected server, this class does that. * * @author <NAME> & <NAME> * @version 1.0 */ public class UserThread extends Thread { private OutputStream clientSocketOutputStream; private InputStream clientSocketInputStream; private PrintWriter clientSocketWriter; private Scanner clientSocketReader; private String songTitle; private String songArtist; private String previousTitleReceived; private String previousArtistReceived; private ArrayList<ConnectedUserPanel> connectedUserPanels; private boolean gettingSharedSongsList; private boolean requestMade; private String connectedUser; private String IPv4; /** * class constructor, gets IPv4 to make a connection. * @param IPv4 IP address of server we want to connect to(works as a hostname too) */ UserThread(String IPv4) { // requestDownloadIndex = -1; //default invalid index; this.IPv4 = IPv4; connectedUserPanels = new ArrayList<>(); } String getConnectedUser() { return connectedUser; } String getIPv4() { return IPv4; } /** * when this method is called, we set a request to connected user to get shared songs of him/her * @param requestMade given request made. */ void setRequestMade(boolean requestMade) { this.requestMade = requestMade; } @Override public void run() { try { Socket clientSocket = new Socket(IPv4, 2019);//making a connection to server createIO(clientSocket);//creating IO streams. //System.out.println("I am Client!"); connectedUser = clientSocketReader.nextLine();//reading server user name clientSocketWriter.println("user Received");//telling server that we received the name //System.out.println("I connect to:" + connectedUser); //System.out.println("sending username..."); clientSocketWriter.println(GUIFrame.getUsername());//sending server our username //System.out.println("sent"); if (clientSocketReader.nextLine().equals("user Received")) {//if server received our user //System.out.println("getting connected username..."); GUIFrame.addConnectedUserNameJCombobox(connectedUser);//setting connected user to show in JCombobox. //System.out.println("Username connected setted"); while (true) { //System.out.println("First of loop"); if (gettingSharedSongsList) {//if we suppose to get shared Songs. createAndShowSharedSongs(); } else { if (songTitle == null && songArtist == null) { clientSocketWriter.println("nothingPlayed"); clientSocketWriter.println("nothingPlayed"); //System.out.println("Default sent"); } else { clientSocketWriter.println(songTitle); clientSocketWriter.println(songArtist); //System.out.println("Artist: " + songArtist); } String firstInputSocket = clientSocketReader.nextLine();////expected to be song title //System.out.println("First input received:" + firstInputSocket); if (firstInputSocket.equals("get Shared Songs")) { for (SongPanel sharedSong : GUIFrame.getSharedSongs()) { //System.out.println("Sending a shared songs......."); clientSocketWriter.println(sharedSong.getMp3Info().getTitle()); clientSocketWriter.println(sharedSong.getMp3Info().getArtist()); if (!clientSocketReader.nextLine().equals("song received")) JOptionPane.showMessageDialog(null, "Error getting shared songs", "An Error Occurred", JOptionPane.ERROR_MESSAGE); } clientSocketWriter.println("completed !"); //System.out.println("Done sending shared songs!"); } else if(firstInputSocket.contains("index")){ clientSocketWriter.println("Index Received");//saying to other pear that received index int index = Integer.parseInt(firstInputSocket.split(" ")[1]); //System.out.println("index received to send mp3:"+index); String inputDirectory = GUIFrame.getSharedSongs().get(index).getMp3Info().getInputFileDirectory(); FileInputStream fis = new FileInputStream(inputDirectory); //System.out.println("sending mp3 file..."); int count; while ((count = fis.read()) != -1) { clientSocketOutputStream.write(count); } fis.close(); //System.out.println("Sent!"); while(!clientSocketReader.nextLine().equals("downloaded")){ clientSocketOutputStream.flush(); } //clientSocketOutputStream.write(-1);//for saying other pear it sent } else { String secondInputSocket = clientSocketReader.nextLine();//expected to be song artist JLabel titleLabel = new JLabel(firstInputSocket); JLabel artistLabel = new JLabel(secondInputSocket); if (!firstInputSocket.equals("nothingPlayed") && !firstInputSocket.equals("song received")) { if (previousArtistReceived == null || (!previousTitleReceived.equals(firstInputSocket) && !previousArtistReceived.equals(secondInputSocket))) { previousArtistReceived = secondInputSocket; previousTitleReceived = firstInputSocket; ConnectedUserPanel connectedUserPanel = new ConnectedUserPanel(connectedUser, firstInputSocket, secondInputSocket); if (connectedUserPanels.size() > 0) { ConnectedUserPanel lastConnectedUserPanel = connectedUserPanels.get(connectedUserPanels.size() - 1); lastConnectedUserPanel.setStopped();//stop last one (changing playing label) } connectedUserPanels.add(connectedUserPanel); GUIFrame.getEastPanel().addToNorth(connectedUserPanel); } } if (requestMade) {//if we made a request from one user to get shared songs //System.out.println("a request made"); clientSocketWriter.println("get Shared Songs");//sending a request requestMade = false; gettingSharedSongsList = true; } } } GUIFrame.reload(); Thread.sleep(2000); } } } catch (InterruptedException | NoSuchElementException e1) { connectedUserPanels.get(0).setOffline(); GUIFrame.removeUserNameExited(connectedUser); GUIFrame.reload(); } catch (IOException e2) { JOptionPane.showMessageDialog(null, "socket connection error", "An Error Occurred", JOptionPane.ERROR_MESSAGE); } } private void createAndShowSharedSongs() { //System.out.println("Trying to get shared songs..."); ArrayList<SharedSongPanel> sharedSongPanels = new ArrayList<>(); gettingSharedSongsList = false; String firstInput; String secondInput; BufferedImage defaultImage = null; try { defaultImage = ImageIO.read(new File("SharedSongs/defaultImage.png")); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Error reading shared default image", "An Error Occurred", JOptionPane.ERROR_MESSAGE); } //System.out.println("image loaded"); while (true) { firstInput = clientSocketReader.nextLine();//expect to be song title if (firstInput.equals("completed !")) break; // System.out.println(firstInput); secondInput = clientSocketReader.nextLine();//expect to be song artist // System.out.println(secondInput); clientSocketWriter.println("song received"); SharedSongPanel newSharedSong = new SharedSongPanel(defaultImage, firstInput, secondInput, sharedSongPanels, connectedUser); sharedSongPanels.add(newSharedSong); } sharedSongPanels.remove(0);//it's invalid GUIFrame.showSharedSongs(sharedSongPanels); } /*private void downloadNewSharedSong() { gettingSharedSong = false;//changing to default for next time, until it is set by our user. try { FileOutputStream fos = new FileOutputStream("SharedSongs/test.mp3"); System.out.println("Downloading..."); int count; while ((count = clientSocketInputStream.read()) != -1) { fos.write(count); } fos.close(); System.out.println("downloaded!"); } catch (FileNotFoundException e) { System.err.println("error creating output file"); } catch (IOException e) { System.out.println("error writing output file"); } }*/ /** * creating input output streams. * @param clientSocket socket of server we connected to */ private void createIO(Socket clientSocket) { try { clientSocketOutputStream = clientSocket.getOutputStream(); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Error getting input stream", "An Error Occurred", JOptionPane.ERROR_MESSAGE); } try { clientSocketInputStream = clientSocket.getInputStream(); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Error getting output stream ", "An Error Occurred", JOptionPane.ERROR_MESSAGE); } clientSocketWriter = new PrintWriter(clientSocketOutputStream, true); clientSocketReader = new Scanner(clientSocketInputStream); } /** * when we played a new song in shared songs, this method called and set song title to show to our connected user * @param songTitle title of song to send */ void setSongTitle(String songTitle) { this.songTitle = songTitle; } /** * when we played a new song in shared songs, this method called and set song artist to show to our connected user * @param songArtist artist of song to send */ void setSongArtist(String songArtist) { this.songArtist = songArtist; } } <file_sep>/src/com/MP3/CustomPlayer.java package com.MP3; import com.mpatric.mp3agic.InvalidDataException; import com.mpatric.mp3agic.Mp3File; import com.mpatric.mp3agic.UnsupportedTagException; import javazoom.jl.player.Player; import javax.swing.*; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; /** * This class is program player created with help of Jlayer. * it has extra features compatible with our programs. * it can play,pause and resume selected music. * * @author <NAME> & <NAME> * @version 1.0 */ public class CustomPlayer { public static final int START_TIME = 0; private Player player; private FileInputStream fileInputStream; private boolean isPlaying; private boolean firstPlaying; private String directory; private int stopped; private int startOffset; private int endOffset; /** * Class constructor, it only gives mp3 file directory from user. * * @param directory directory of mp3 file. */ public CustomPlayer(String directory) { this.directory = directory; } public String getDirectory() { return directory; } /** * this method happens if user pause playing music. * it store remaining bytes to stopped variable so next time if it wants to resume, it start with total - stopped bytes. */ public void pause() { if (isPlaying) {//if music is playing try { stopped = fileInputStream.available();//storing remaining bytes to play later. player.close();//close the entire player. isPlaying = false; } catch (IOException e) { JOptionPane.showMessageDialog(null, "Error pausing mp3 file", "An Error Occured", JOptionPane.ERROR_MESSAGE); } } } /** * this method resume current music if user paused it before. */ public void resume() { if (!isPlaying) {//if musing is not playing play(endOffset - stopped);//play from remaining bytes. isPlaying = true; } } /** * overloaded method created to work with JProgressbar. * it changes stopped variable to where JProgressbar located. * * @param startingTimeDegree a number between 0 and 1 indicates how much time spends. */ public void resume(double startingTimeDegree) { stopped = (int) ((endOffset - startOffset) - (endOffset - startOffset) * startingTimeDegree);//generating remaining bytes amounts from point of start close();//closing current music(if we didn't close it plays beside previous one) play(endOffset - stopped);//play from beginning point of JProgressbar } /** * this method plays music from wherever we want to. * * @param pos point of start(CustomPlayer.START_TIME if we want to play from the beginning) */ public void play(int pos) { try { isPlaying = true; fileInputStream = new FileInputStream(directory); if (pos > 0) { fileInputStream.skip(pos);//skipping additional bytes firstPlaying = false;//it's not playing at first(help us to get current time) } else firstPlaying = true;//it's playing at first player = new Player(new BufferedInputStream(fileInputStream)); new Thread(//creating thread to play parallel with our program. new Runnable() { public void run() { try { player.play(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error playing mp3 file"); } } } ).start(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error reading mp3 file"); } } /** * @return total Time of music */ public int getTotalSeconds() { int totalSeconds = 0; try { totalSeconds = (int) new Mp3File(directory).getLengthInSeconds(); } catch (IOException | UnsupportedTagException | InvalidDataException e) { JOptionPane.showMessageDialog(null, "Error reading total seconds"); } return totalSeconds; } /** * @return current time of music while playing(not necessary is playing,it can be paused) * @throws IOException if stream is closed. */ public int getCurrentSeconds() throws IOException { if (firstPlaying) { startOffset = getStartOffset(); endOffset = getEndOffset(); } int passedBytes = endOffset - fileInputStream.available() - startOffset;//amount of bytes which played. return (int) ((passedBytes / (double) endOffset) * getTotalSeconds()); } public boolean isPlaying() { return isPlaying; } public boolean isComplete() { if (player != null) return player.isComplete(); else return true; } /** * closing player(helps us when another music is going to start in our program) */ public void close() { player.close(); } private int getStartOffset() { try { Mp3File mp3File = new Mp3File(directory); return mp3File.getStartOffset(); } catch (IOException | UnsupportedTagException | InvalidDataException e) { JOptionPane.showMessageDialog(null, "Error pausing mp3 file", "An Error Occured", JOptionPane.ERROR_MESSAGE); } return 0; } private int getEndOffset() { try { Mp3File mp3File = new Mp3File(directory); return mp3File.getEndOffset(); } catch (IOException | UnsupportedTagException | InvalidDataException e) { JOptionPane.showMessageDialog(null, "Error pausing mp3 file", "An Error Occured", JOptionPane.ERROR_MESSAGE); } return 0; } }<file_sep>/src/com/Panels/WestPanelSections/WestPanelListeners/PlaylistsTitlesListener.java package com.Panels.WestPanelSections.WestPanelListeners; import com.GUIFrame.GUIFrame; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * this listener is for every playlist title shows as a list under playlist button: * when mouse Clicked: it opens chosen playlist in center panel * when mouse Entered: it becomes bolder * when mouse Exited: it turns to previous form */ public class PlaylistsTitlesListener extends MouseAdapter { private JLabel titleTextLabel; private Font font; /** * class constructor, it sets title of playlist as a label and sets default font. * * @param titleTextLabel title of playlist */ PlaylistsTitlesListener(JLabel titleTextLabel) { this.titleTextLabel = titleTextLabel; font = titleTextLabel.getFont(); } @Override public void mouseClicked(MouseEvent e) { GUIFrame.showPlaylistSongs(titleTextLabel.getText()); } @Override public void mouseEntered(MouseEvent e) { titleTextLabel.setFont(new Font("Serif", Font.BOLD, 16)); } @Override public void mouseExited(MouseEvent e) { titleTextLabel.setFont(font); } } <file_sep>/src/com/Panels/CenterPanelSections/SongPanel.java package com.Panels.CenterPanelSections; import com.GUIFrame.GUIFrame; import com.Interfaces.PlaylistOptionLinker; import com.Interfaces.ShowSongsLinker; import com.MP3.MP3Info; import com.mpatric.mp3agic.InvalidDataException; import com.mpatric.mp3agic.UnsupportedTagException; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; /** * This subclass created if the music panel we want is a song and if user click on that, it plays desired song. * * @author <NAME> & <NAME> * @version 1.0 */ public class SongPanel extends MusicPanel { private MP3Info mp3Info; private String songTitle; private PlaylistOptionLinker playlistOptionLinker; private ShowSongsLinker showSongsLinker; private boolean selected;//helps for adding song to playlist. /** * Constructor which set information need to show in super class and create a listener for song * * @param mp3Info information about mp3 we want to play * @param description description to show under the title. */ SongPanel(MP3Info mp3Info, String description) throws InvalidDataException, IOException, UnsupportedTagException { super(mp3Info.getImage(), mp3Info.getTitle(), description); songTitle = mp3Info.getTitle(); this.mp3Info = mp3Info; playlistOptionLinker = GUIFrame.getPlaylistOptionLinker(); showSongsLinker = GUIFrame.getShowSongsLinker(); createSongListener(); } /** * This method only calls if new adding panel appears and unselect song panel if it's selected in previous panel. */ void unSelect() { this.selected = false; } public String getInputFileDirectory() { return mp3Info.getInputFileDirectory(); } public MP3Info getMp3Info() { return mp3Info; } /** * this method creates a Mouse listener for song panel * it does two things: * -when mouse entered: it changes to a brighter color. * -when mouse exited: it backs to previous color it had. * -when mouse pressed: it shows lyrics of song if exists and play given song. */ private void createSongListener() { this.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { SongPanel source = (SongPanel) e.getSource();//source is a song panel which mouse clicked on it. if (playlistOptionLinker.isAddingSongToPlaylist()) {//if clicked in order to add song to playlist if (!selected) {//if it's not selected before, we add it to addingSongPanel and make it look brighter selected = true; source.setBackground(new Color(41, 41, 41)); playlistOptionLinker.getAddingSongPanel().add(0, source);//(it changes playlist after done button clicked!) } else {//else we make look like previous form and remove from addingSongPanel selected = false; source.setBackground(new Color(23, 23, 23)); playlistOptionLinker.getAddingSongPanel().remove(source); } } else if (playlistOptionLinker.isRemoveSongFromPlaylist()) {//if clicked in order to remove song from playylist. if (!selected) {//if it's not selected we add it to removingSongPanels and make it look brighter. selected = true; playlistOptionLinker.getRemovingSongPanels().add(source); source.setBackground(new Color(41, 41, 41)); } else {//else we make look like previous form and removing from removingSongPanels selected = false; source.setBackground(new Color(23, 23, 23)); playlistOptionLinker.getRemovingSongPanels().add(source);// it changes playlist after clicking Done! } } else if (playlistOptionLinker.isSwaping()) {//in case if we want to swap: if (!selected) {//if this song panel is not selected before selected = true;//changing state to select if (playlistOptionLinker.getFirstSelectedSwaping() == null)//if we didn't select anything playlistOptionLinker.setFirstSelectedSwaping(source);//set this panel as first panel to swap else {//if we choose a song panel to swap with before playlistOptionLinker.setSecondSelectedSwaping(source);//set this panel as second panel to swap playlistOptionLinker.swapPlayList();//swap them! } source.setBackground(new Color(41, 41, 41)); } else {// if this song panel is selected before selected = false;//changing state to unselect if (playlistOptionLinker.getFirstSelectedSwaping() == source)//if it's first panel to swap playlistOptionLinker.setFirstSelectedSwaping(null);//we unselect this as a first one else//it's never gonna happen(due to swapping after second one selected) playlistOptionLinker.setSecondSelectedSwaping(null); } } else {//if clicked in order to play song //changing playing song index to first: showSongsLinker.getAllSongsPanel().remove(source); showSongsLinker.getAllSongsPanel().add(0, source); //play clicked music: GUIFrame.playClickedMusic(source);//playing music } } @Override public void mouseExited(MouseEvent e) { if (!selected || (!playlistOptionLinker.isAddingSongToPlaylist() && !playlistOptionLinker.isRemoveSongFromPlaylist() && !playlistOptionLinker.isSwaping())) { MusicPanel source = (MusicPanel) e.getSource(); source.setBackground(new Color(23, 23, 23)); } } @Override public void mouseEntered(MouseEvent e) { MusicPanel source = (MusicPanel) e.getSource(); source.setBackground(new Color(41, 41, 41)); } }); } /** * this method is called when a message is searched in searchbox, it indicate that it match to this song or not. * * @param message given search message * @return true if matched or false if it's not. */ boolean hasThisName(String message) { //creating Strings to compare, with ignoring lower or upper case: String songTitle = mp3Info.getTitle().toLowerCase(); String albumTitle = mp3Info.getAlbum().toLowerCase(); String artistTtile = mp3Info.getArtist().toLowerCase(); String searchingMessage = message.toLowerCase(); //comparing: return songTitle.contains(searchingMessage) || albumTitle.contains(searchingMessage) || artistTtile.contains(searchingMessage); } } <file_sep>/src/com/Panels/SouthPanelSections/ProgressPanel.java package com.Panels.SouthPanelSections; import com.MP3.CustomPlayer; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; /** * this class is about Music Player bar which located on south panel. * it has a ProgressBar which goes forward parallel with playing music. * and has a two label revealing current time and total time of music. * * @author <NAME> & <NAME> * @version 1.0 */ public class ProgressPanel extends JPanel { private JProgressBar musicPlayerBar; private JLabel currentTimeLabel; private JLabel totalTimeLabel; private CustomPlayer player; /** * Class Constructor. */ public ProgressPanel() { //setting layout to Box layout and Line axis: this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); //setting background: this.setBackground(new Color(41, 41, 41)); //creating time labels: currentTimeLabel = new JLabel("00:00"); currentTimeLabel.setForeground(new Color(179, 179, 179)); totalTimeLabel = new JLabel("00:00"); totalTimeLabel.setForeground(new Color(179, 179, 179)); //customizing progress bar colors: UIManager.put("ProgressBar.background", new Color(92, 84, 84)); UIManager.put("ProgressBar.foreground", new Color(179, 179, 179)); //creating music player bar: musicPlayerBar = new JProgressBar(); musicPlayerBar.setBorder(javax.swing.BorderFactory.createEmptyBorder()); musicPlayerBar.setPreferredSize(new Dimension(430, 7)); musicPlayerBar.setMaximumSize(musicPlayerBar.getPreferredSize()); musicPlayerBar.setMinimumSize(musicPlayerBar.getPreferredSize()); musicPlayerBar.setBackground(new Color(92, 84, 84)); //adding components to pannel: this.add(currentTimeLabel); this.add(Box.createHorizontalStrut(10)); this.add(musicPlayerBar); createMusicPlayerBarAction(); this.add(Box.createHorizontalStrut(10)); this.add(totalTimeLabel); } /** * This method demonstrate what happens if mouse pressed or dragged on music player bar. * when mouse pressed: it changes music to time where user clicks. * when mouse dragged: it drags progress bar with mouse and after that,plays music from that point. */ private void createMusicPlayerBarAction() { musicPlayerBar.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { mouseAction(e); } }); musicPlayerBar.addMouseMotionListener(new MouseAdapter() { @Override public void mouseDragged(MouseEvent e) { mouseAction(e); } }); } /** * this method update progressbar and do necessary actions. * if music is playing, it resume from given point chosen by user * else it resume only a moment to update where it is, then it become pause. * after all it set current time no matter playing or not. */ private void mouseAction(MouseEvent e) { if (player != null) { musicPlayerBar.setValue((int) (e.getX() / ((double) musicPlayerBar.getWidth()) * 100)); if (player.isPlaying()) player.resume(e.getX() / ((double) musicPlayerBar.getWidth())); else { player.resume(e.getX() / ((double) musicPlayerBar.getWidth())); player.pause(); } setMusicCurrentTime(); } } /** * this method set current time to time which music player bar points on it. */ private void setMusicCurrentTime() { int currentTime; try { currentTime = player.getCurrentSeconds(); } catch (IOException e) {//if stream is closed, our method then do nothing return; } int min = currentTime / 60; int sec = currentTime % 60; String currentTimeString = String.format("%02d:%02d", min, sec); currentTimeLabel.setText(currentTimeString); } /** * this method called when a musicPanel clicked. it control the playing music by changing MusicPlayerBar. * * @param player player we want to control. */ public void controlMusic(CustomPlayer player) { this.player = player;//setting player to control it in listeners int totalmin = player.getTotalSeconds() / 60;//getting music's total minutes. int totalSec = player.getTotalSeconds() % 60;//getting music's total seconds. String totalTimeString = String.format("%02d:%02d", totalmin, totalSec);//creating a formatted String to show in jlabel totalTimeLabel.setText(totalTimeString);//setting JLabel's text Thread t = new Thread(new Runnable() {//creating thread @Override public void run() {//creating thread to control player parallel with our program. while (true) {//this loop runs until music's fileInputStream closed (music finished). if (player.isPlaying()) {//changing progressbar if music is playing try { musicPlayerBar.setValue((int) ((player.getCurrentSeconds() / (double) player.getTotalSeconds()) * 100)); } catch (IOException e) {//if music finished. our job is done and thread is going to be terminated. break; } } setMusicCurrentTime(); try { Thread.sleep(500);//sleep like 0.5 sec to perform better } catch (InterruptedException e) { JOptionPane.showMessageDialog(null, "Error controlling mp3 file"); } } } }); t.start(); } } <file_sep>/README.md # Jpotify In this project, we built a application like spotify, however for network part you can only make a P2P connection and see what your friend is playing right now or have played last time. ![Screenshot of Program](http://uupload.ir/files/ns83_screenshot.jpg) Application features: - Playing music after you've chosen the directory. - Searching through Music list - Sorting music list - Creating a playlist - Liking your favorite song - Making a P2P connection to see what song your friend is playing or have played. - Shuffle through music list or repeat a song after finishing it <file_sep>/src/com/Interfaces/SearchLinker.java package com.Interfaces; /** * This interface link center part of center panel with search box. * * @author <NAME> * @version 1.0 */ public interface SearchLinker { /** * This method searches in every songs in library and show song panels that it found it. * * @param searchingMessage given text to search. */ void doSearch(String searchingMessage); } <file_sep>/src/com/Panels/WestPanelSections/WestPanelListeners/HomePanelListener.java package com.Panels.WestPanelSections.WestPanelListeners; import com.GUIFrame.GUIFrame; import com.Panels.GeneralPanels.WestPanel; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * this album title listener has this jobs to do: * when mouse clicked: it show homes which shows albums and playlist * when mouse entered: it become bolder and bigger * when mouse exited: it turn to previous form * * @author <NAME> & <NAME> * @version 1.0 */ public class HomePanelListener extends MouseAdapter { private JLabel icon; private JLabel label; private Font font; /** * Class Constructor which sets given parameters. * * @param icon icon of Home label * @param text a text label which it is " HOME" */ public HomePanelListener(JLabel icon, JLabel text) { this.icon = icon; this.label = text; font = text.getFont(); } @Override public void mouseClicked(MouseEvent e) { GUIFrame.showHome(); } @Override public void mouseEntered(MouseEvent e) { icon.setIcon(WestPanel.setIconSize("Icons/Home.png", 20)); label.setFont(new Font("Serif", Font.BOLD, 16)); } @Override public void mouseExited(MouseEvent e) { icon.setIcon(WestPanel.setIconSize("Icons/Home-no-select.png", 20)); label.setFont(font); } } <file_sep>/src/com/Panels/NorthPanelSections/ScrollerPlusIconListener.java package com.Panels.NorthPanelSections; import com.GUIFrame.GUIFrame; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * it implements the action of clicking the plus button near the JCombo box. * * @author <NAME> & <NAME> * @version 1.0 */ public class ScrollerPlusIconListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { EastPanelClientThread mainClientThread = new EastPanelClientThread(); mainClientThread.start(); GUIFrame.setMainClientThread(mainClientThread); } } <file_sep>/src/com/MP3/AppStorage.java package com.MP3; import com.GUIFrame.GUIFrame; import com.Interfaces.SongPanelsLinker; import com.Panels.CenterPanelSections.AlbumPanel; import com.Panels.CenterPanelSections.PlayListPanel; import com.Panels.CenterPanelSections.SongPanel; import javax.swing.*; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Formatter; import java.util.HashMap; import java.util.Scanner; /** * This class has two static method to save and load songs which user added to library. * * @author <NAME> & <NAME> * @version 1.0 */ public class AppStorage { /** * This method save current songs existing in library when user close jpotify. * for doing so, it creates a txt file to SavedDirectories folder(folder should exist) * then at first it saves all album directories * at the end it saves all songs existing in playlists. */ public static void saveSongs() { SongPanelsLinker songPanelsLinker = GUIFrame.getSongPanelsLinker(); try { String currentUser = GUIFrame.getUsername().replace(" ", "-"); Formatter out = new Formatter("SavedDirectories/SavedSongsOf" + currentUser + ".txt"); String albumName; String directory; for (SongPanel songPanel : songPanelsLinker.getAllSongPanels()) { albumName = songPanel.getMp3Info().getAlbum(); directory = songPanel.getInputFileDirectory(); out.format("Album^%s^%s%n", albumName, directory); } HashMap<String, PlayListPanel> playListPanels = songPanelsLinker.getPlayListPanels(); String playlistName; String playlistDescription; for (PlayListPanel playListPanel : playListPanels.values()) { playlistName = playListPanel.getTitle(); playlistDescription = playListPanel.getDescription(); for (SongPanel songPanel : playListPanel.getPlayListSongs()) { directory = songPanel.getInputFileDirectory(); out.format("Playlist^%s^%s^%s%n", playlistName, playlistDescription, directory); } if (playListPanel.getPlayListSongs().size() == 0)//if it's a empty playlist out.format("Playlist^%s^%s%n", playlistName, playlistDescription); } out.close(); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Error saving songs", "An Error Occurred", JOptionPane.ERROR_MESSAGE); } } /** * this method is called at first running of program, after entering username, it searches for his/her directory files. * if exists, it will add albums, then will add playlists. */ public static void loadSongs() { String currentUser = GUIFrame.getUsername().replace(" ", "-"); File file = new File("SavedDirectories/SavedSongsOf" + currentUser + ".txt"); if (file.exists()) { try { FileReader fileReader = new FileReader(file.getAbsolutePath()); Scanner scanner = new Scanner(fileReader); String line; ArrayList<MP3Info> currentMP3info; while (scanner.hasNext()) { line = scanner.nextLine(); String[] parts = lineSeprator(line); switch (parts[0]) { case "Album": currentMP3info = new ArrayList<>(); currentMP3info.add(new MP3Info(parts[2])); GUIFrame.addAlbum(parts[1], currentMP3info); break; case "Playlist": currentMP3info = new ArrayList<>(); if (parts.length == 4) { currentMP3info.add(new MP3Info(parts[3])); GUIFrame.addSongToPlayList(parts[1], parts[2], parts[3]); } else {//if playlist is empty GUIFrame.createPlayList(parts[1], parts[2]); } break; } } } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "Error loading songs", "An Error Occurred", JOptionPane.ERROR_MESSAGE); } catch (NoSuchFieldException | IOException e) { JOptionPane.showMessageDialog(null, "Error reading mp3 file", "An Error Occurred", JOptionPane.ERROR_MESSAGE); } } } /** * This private static method, separate every line read by scanner to part of strings. * * @param line read line by scanner. * @return parts of line splitted by ^; */ private static String[] lineSeprator(String line) { return line.split("[\\^]"); } } <file_sep>/src/com/Interfaces/LyricsLinker.java package com.Interfaces; import java.util.ArrayList; public interface LyricsLinker { /** * This method shows chosen song lyrics if exists or shows list of reasons why it couldn't shows. * * @param lyricsLines line of lyrics. */ void showLyrics(ArrayList<String> lyricsLines); } <file_sep>/src/com/Panels/WestPanelSections/WestPanelListeners/PlaylistsListener.java package com.Panels.WestPanelSections.WestPanelListeners; import com.GUIFrame.GUIFrame; import com.Panels.GeneralPanels.WestPanel; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; /** * playlist panel's listener does this jobs: * -when mouse Clicked: * if mouse clicked in odd times, it shows playlist titles and if user click on them, it show that playlist in center panel. * if mouse clicked in even times, it close playlist titles and only shows playlist button. * -when mouse Entered: * it updates playlist image and become bolder. * -when mouse Exited: * it updates playlist image and turn to previous form. * * @author <NAME> & <NAME> * @version 1.0 */ public class PlaylistsListener extends MouseAdapter { private JLabel textLabel; private JLabel icon; private Font font; private JPanel playlistsPanel;//not necessary(press alt + enter after deleting this comment) private int numberOfClicks; /** * Class constructor. * setting given parameters and default font. * * @param icon icon of playlist * @param textLabel a text label which it is : " Playlists " */ public PlaylistsListener(JLabel icon, JLabel textLabel) { this.icon = icon; this.textLabel = textLabel; font = textLabel.getFont(); } @Override public void mouseClicked(MouseEvent e) { ++numberOfClicks; if (numberOfClicks % 2 == 1) {//if it's clicked in odd times: ArrayList<String> playlistTitles = GUIFrame.getPlayistTitles(); playlistsPanel = WestPanel.getPlayListsPanel(); playlistsPanel.setBackground(new Color(23, 23, 23));//not necessary, it set in west panel playlistsPanel.setLayout(new BoxLayout(playlistsPanel, BoxLayout.PAGE_AXIS)); playlistsPanel.add(Box.createVerticalStrut(10)); JLabel playlistTitle; for (int i = 0; i <= playlistTitles.size() - 1; ++i) {//creating playlist title labels playlistTitle = new JLabel(playlistTitles.get(i)); playlistTitle.setForeground(Color.WHITE); playlistTitle.addMouseListener(new PlaylistsTitlesListener(playlistTitle));//adding listener as a UI playlistsPanel.add(playlistTitle); playlistsPanel.add(Box.createVerticalStrut(10)); } WestPanel.setPlayListsPanel(playlistsPanel);//not necessary GUIFrame.reload();//not necessary } else { playlistsPanel = WestPanel.getPlayListsPanel(); playlistsPanel.setLayout(new BoxLayout(playlistsPanel, BoxLayout.LINE_AXIS)); while (playlistsPanel.getComponentCount() >= 4) {//removing playlist titles playlistsPanel.remove(3); } WestPanel.setPlayListsPanel(playlistsPanel);//not necessary GUIFrame.reload();//not necessary } } @Override public void mouseEntered(MouseEvent e) { icon.setIcon(WestPanel.setIconSize("Icons/p-selected.png", 20)); textLabel.setFont(new Font("Serif", Font.BOLD, 16)); } @Override public void mouseExited(MouseEvent e) { icon.setIcon(WestPanel.setIconSize("Icons/p-no-selected.png", 20)); textLabel.setFont(font); } }
d2bf5ece439ad04ab25cfda01026b72aaf1fd52f
[ "Markdown", "Java" ]
18
Java
SoroushMehraban/Jpotify
6ec563bd5956194306ee3d98ecfc217dcdb9c527
2d1d4da1c6fea593c2fbc66082b9a3f421db3d9a
refs/heads/master
<file_sep>#define _GNU_SOURCE #include <dlfcn.h> #include <stdio.h> #include <link.h> typedef void* (*dlopen_fcn)(const char *, int); static dlopen_fcn real_dlopen = NULL; void *dlopen(const char *filename, int flag) { if (!real_dlopen) { real_dlopen = dlsym(RTLD_NEXT, "dlopen"); } fprintf(stderr, "dlopen(\"%s\", %d): ", filename, flag); void *handle = real_dlopen(filename, flag); if (handle) { struct link_map *map = (struct link_map *)handle; fprintf(stderr, "OK\nLoaded %s\n\n", map->l_name); } else { fprintf(stderr, "Not found\n"); } return handle; } <file_sep>logdlopen.so: logdlopen.c gcc -Wall -fPIC -shared -o logdlopen.so logdlopen.c <file_sep>#!/usr/bin/env python3 import argparse import fnmatch import os import shutil import subprocess import sys DESCRIPTION = """\ Copy dependencies required by an executable to the specified dir """ def load_blacklist(filename): with open(filename, 'rt') as f: for line in f.readlines(): line = line.strip() if not line or line[0] == '#': continue yield line def list_dependencies(executable): out = subprocess.check_output(('ldd', executable)) for line in out.splitlines(): line = line.strip().decode('ascii') # line can be one of: # 1. linux-vdso.so.1 => (0x00007ffd6f3cd000) # 2. libcrypto.so.1.0.0 => /home/agateau/tmp/genymotion/./libcrypto.so.1.0.0 (0x00007f5ea40b6000) # 3. /lib64/ld-linux-x86-64.so.2 (0x0000562cf1094000) if '=> (' in line: # Format #1, skip it continue tokens = line.split(' ') if tokens[1] == '=>': # Format #2 yield tokens[2] else: # Format #3 yield tokens[0] def is_blacklisted(dependency, blacklist): name = os.path.basename(dependency) for pattern in blacklist: if fnmatch.fnmatch(name, pattern): return True return False def copy(dependency, destdir, dry_run=False): destpath = os.path.join(destdir, os.path.basename(dependency)) if not os.path.exists(destpath): print('Copying {}'.format(dependency)) if not dry_run: shutil.copy(dependency, destpath) def main(): parser = argparse.ArgumentParser() parser.description = DESCRIPTION parser.add_argument('-d', '--destdir', help='Copy to DESTDIR, defaults to the executable dir', metavar='DESTDIR') parser.add_argument('--exclude', help='Do not copy files whose name matches a line from FILE', metavar='FILE') parser.add_argument('-n', '--dry-run', action='store_true', help='Simulate') parser.add_argument('executable') args = parser.parse_args() if args.exclude: blacklist = list(load_blacklist(args.exclude)) else: blacklist = [] dependencies = list_dependencies(args.executable) destdir = args.destdir or os.path.dirname(args.executable) for dependency in dependencies: if is_blacklisted(dependency, blacklist): continue copy(dependency, destdir, dry_run=args.dry_run) return 0 if __name__ == '__main__': sys.exit(main()) # vi: ts=4 sw=4 et <file_sep>## copydeps copydeps runs ldd on a binary and copies all required libs to the current directory or the specified destination directory. ## logdlopen logdlopen can be used to log the full paths of libs which are dlopened by an executable. You must first build it: cd logdlopen make Then you can using it with: LD_PRELOAD=/path/to/logdlopen.so /path/to/executable <file_sep>#!/usr/bin/env python3 import argparse import re import subprocess import sys DESCRIPTION = """\ Use ld to find the full path to a library, given its name """ def main(): parser = argparse.ArgumentParser() parser.description = DESCRIPTION parser.add_argument('name', description='Name of the library, like it would be passed to the linker (ie, foo, not libfoo.so)') args = parser.parse_args() loption = '-l' + args.name cmd = ['ld', '--trace', loption, '-o', '/dev/null'] out = subprocess.check_output(cmd, stderr=subprocess.STDOUT) for line in out.splitlines(): line = line.decode('utf-8') if line.startswith(loption): match = re.search('\((.*)\)', line) assert match path = match.group(1) print(path) return 0 return 1 if __name__ == '__main__': sys.exit(main()) # vi: ts=4 sw=4 et
a3e84de5db76b02b6275fc753952f5e8cab0614d
[ "Markdown", "C", "Python", "Makefile" ]
5
C
agateau-g/copydeps
9d93a7d5bc7659b199eb6f79177024a1f67b032f
6cf3e80f748714eaa0dfa41297b41b3a8aeaa269
refs/heads/main
<repo_name>RakeshKrGorai/Python-File-Handling-MySQL<file_sep>/Hotel Management System.py #Project For Hotel Management System Using Python,File Handling and SQL Database #Importing Required Modules import csv import random import os import mysql.connector as c con=c.connect(host='localhost',user='root',passwd='<PASSWORD>',database='hotel') #To connect to MySQL via Python cursor=con.cursor() cursor.execute("use hotel") #Selecting Database where table is created. #Defining Global Variables hotel_database="hotel.csv" name=phno=add=checkin=checkout=room=price=rc=p=roomno=customer_Id=day=[] hotel=[] services=[] fields=['Name','Phone No','Email','Check-In','Check-Out','Room Type','Price','Room Number',"Customer Id","Days"] i=0 days=0 room_type="" #Home Function def Home(): print("--------------------------------------------------") print("GREETINGS!\n") print("WELCOME TO HOTEL PARADISE") print("--------------------------------------------------") print("\t\t\t 1 Booking A Room\n") print("\t\t\t 2 Rooms Info\n") print("\t\t\t 3 Room service(Food Menu)\n") print("\t\t\t 4 Pay Bill\n") print("\t\t\t 5 Search A Record\n") print("\t\t\t 6 Delete Record\n") print("\t\t\t 7 Contact Us\n") print("\t\t\t 0 Exit\n") print("--------------------------------------------------") choice=int(input("What Would You Like To Do? Enter Your Choice :")) if choice == 1: print(" ") booking() elif choice == 2: print(" ") info_rooms() elif choice == 3: print(" ") restaurant() elif choice == 4: print(" ") payment() elif choice == 5: print(" ") search_record() elif choice == 6: print(" ") delete_record() elif choice==7: print(" ") contact() elif choice==0: print(" ") exit() else: print("Invalid Option") #Defining Different Functions For The Program #BOOKING FUNCTION def booking(): days=0 openfile=open(hotel_database,'a') fw=open('services.csv','a') global i global hotel print("-----------------------") print("BOOKING ROOMS") print("-----------------------") print(" ") global fields Booking_data=[] csvfile=csv.writer(openfile) csvfile1=csv.writer(fw) while True: n=input("Name :") while n=="": print("Name can't be empty") n=input("Name :") p1=input("Phone :") while len(p1)!=10: print("Invalid Phone Number") p1=input("Phone :") a=input("email :") while "@" not in a: print("Invalid Email") a=input("email :") if n!="" and p1!="" and a!="": name.append(n) phno.append(p1) add.append(a) break checkindate=input("Check-In Date(YYYY-MM-DD) :") #copy of data for file management indate=checkindate checkin.append(checkindate) checkindate=checkindate.split('-') ci=checkindate ci[0]=int(ci[0]) ci[1]=int(ci[1]) ci[2]=int(ci[2]) checkoutdate=input("Check-Out Date(YYYY-MM-DD) :") #copy of date for file management outdate=checkoutdate checkout.append(checkoutdate) checkoutdate=checkoutdate.split('-') co=checkoutdate co[0]=int(co[0]) co[1]=int(co[1]) co[2]=int(co[2]) if co[1]<ci[1] and co[2]<ci[2]: print("\n\tErr..!!\n\tCheck-Out date must fall after Check-In\n") name.pop(i) add.pop(i) checkin.pop(i) checkout.pop(i) booking() elif co[1]==ci[1] and co[0]>=ci[0] and co[2]<=ci[2]: print("\n\tErr..!!\n\tCheck-Out date must fall after Check-In\n") name.pop(i) add.pop(i) checkin.pop(i) checkout.pop(i) booking() else: month = { 1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31 } d=0 #Checking Right Credentials if (0<ci[1]<13 and 0<co[1]<13 and ci[2]<=month[ci[1]] and co[2]<=month[co[1]]): #if month are same if(ci[1]==co[1]): days=co[2]-ci[2] else: for i in range(ci[1],co[1]): #print(month[i]) days+=(month[ci[1]]-ci[2])+co[2] print('Booking for ',days+1,'days') else: print('Wrong Value') print("----SELECT ROOM TYPE----") print(" 1. Standard") print(" 2. Standard Plus") print(" 3. Suites") print(" 4. Cottages") print(("\t\tPress 0 for Room Prices")) choice=int(input("->")) # if-conditions to display alloted room type and it's price if choice==0: print(" 1. Standard- Rs. 4000") print(" 2. Standard Plus - Rs. 4500") print(" 3. Suites - Rs. 5000") print(" 4. Cottages- Rs. 5500") choice=int(input("->")) elif choice==1: room.append('Standard') print("Room Type- Standard") room_type="Standard" price.append(4000) p=4000 print("Price- 4000") bill=(days+1)*p elif choice==2: room.append('Standard Plus') print("Room Type-Standard Plus ") price.append(4500) print("Price- 4500") room_type="Standard Plus" p=4500 bill=(days+1)*p elif choice==3: room.append('Suites') print("Room Type- Suites") price.append(5000) print("Price- 5000") room_type='Suites' p=5000 bill=(days+1)*p elif choice==4: room.append('Cottages') print("Room Type- Cottages") price.append(5500) print("Price- 5500") room_type="Cottages" p=5500 bill=(days+1)*p else: print(" Wrong choice..!!") # randomly generating room no. and customer id for customer room_no = random.randrange(40)+300 customer_id = random.randrange(60)+10 print("") roomno.append(room_no) customer_Id.append(customer_id) i=i+1 hotel.extend([n,p1,a,indate,outdate,room_type,p,room_no,customer_id,days+1]) csvfile.writerow(hotel) print("\t\t\t---ROOM BOOKED SUCCESSFULLY---\n") print("Room No. - ",room_no) print("Customer Id - ",customer_id) print("Successfully Saved into Our Database") data=str(hotel) sql="insert into booking(Name,Phone_Number,Email,Check_In,Check_Out,Room_Type,Price,Room_Number,Customer_id,Days)values('{}',{},'{}','{}','{}','{}',{},{},{},{})".format(n,str(p1),a,str(indate),str(outdate),room_type,p,room_no,customer_id,days+1) cursor.execute(sql) service_charge=0 services.extend([n,customer_id,service_charge,bill]) csvfile1.writerow(services) sql1="insert into service(Name,Customer_id,Room_Bill)values('{}',{},{})".format(n,customer_id,bill) cursor.execute(sql1) con.commit() hotel=[] openfile.close() n=int(input("0-BACK\n -->")) if n==0: Home() else: exit() #ROOM INFO FUNCTION def standard(): print("\t\t\tSTANDARD") print("---------------------------------------------------------------") print("Find sanctuary in our serene Standard room. A cosy double bedroom complete with an ensuite with rainfall shower and private balcony.\n") print("This cosy room has everything you need for R&R, including crisp 300 thread count cotton sheets, a hypoallergenic mattress, ensuite bathroom, a private balcony and, of course, superfast WiFi connection. Decorated with classic interior that complements the Algarve’s natural beauty, this room has everything you need for a relaxing stay.") print("\nThis room includes\n") print("1.Air Conditioning") print("2.High Speed WiFi") print("3.Multi-Line Telephone") print("4.Flat Screen TV with International Channels") print("5.Daily Maid Service") print("") def standard_plus(): print("\t\t\tSTANDARD PLUS") print("---------------------------------------------------------------") print("Enjoy all the comfort and style of the Standard but in our larger room. With a size of 26m², the Standard Plus is ideal for longer stays.") print("\nWith a private entrance and ground floor access, our Standard Plus rooms have all the comfort and style of the Standard but with added space. With a size of 26m², and a private balcony perfect for sipping a cocktail at sunset, the Standard Plus is ideal for longer stays at The Paradise Hotel. Complete with a divinely comfortable twin or double bed, crisp 300 thread count cotton sheets and modern en suite bathroom fitted with all amenities, oversized 600 tog bath towels, hairdryer, vanity sink and magnifying make-up mirror.") print("\nThis room includes\n") print("1.Air Conditioning") print("2.High Speed WiFi") print("3.Multi-Line Telephone") print("4.Flat Screen TV with International Channels") print("5.Daily Maid Service") print("") def suites(): print("\t\t\tSUITES") print("---------------------------------------------------------------") print("Our stylish suites are complete with a double bedroom, living space with cosy couches, ensuite and private balcony. Dreamy.") print("\nBright and airy, our stylish suites feature separate living areas with cosy couches to lounge on, as well as a divine double bedroom for the ultimate R&R. In the bathroom, a glorious shower awaits, with a vanity sink and mirror equipped with hairdryer, magnifying make-up mirror, and signature Paradise slides.") print("\nThis room includes\n") print("1.Air Conditioning") print("2.High Speed WiFi") print("3.Multi-Line Telephone") print("4.Flat Screen TV with International Channels") print("5.Daily Maid Service") print("") def cottages(): print("\t\t\tCOTTAGES") print("---------------------------------------------------------------") print("Our charming two-bedroom cottages each have their own living room, kitchenette, bathroom and patio. Great for couples and families looking for a blissful getaway.") print("\nThe perfect retreat. Situated among the pine trees, our two-bedroom cottages each have their own living room, kitchenette, bathroom and patio. Great for couples and families, with modern and luxurious style and all The Paradise Hotel action on the doorstep, it’s ideal for a dreamy getaway.") print("\nThis room includes\n") print("1.Air Conditioning") print("2.High Speed WiFi") print("3.Multi-Line Telephone") print("4.Flat Screen TV with International Channels") print("5.Daily Maid Service") print("") def info_rooms(): print() print(" ------ HOTEL ROOMS INFO ------") print("") standard() standard_plus() suites() cottages() n=int(input("0-BACK\n ->")) if n==0: Home() else: exit() # RESTAURANT FUNCTION def restaurant(): id=int(input("Customer Id: ")) k=0 counter=0 fw=open('services.csv','a') csvfile=csv.writer(fw) global i with open('hotel.csv','r') as csvfiler: csvr=csv.reader(csvfiler) for row in csvr: #print(len(row)) for i in range(0,len(row)): #print(i) if row[8]==str(id): k=k+1 x=row[8] name=row[0] customerid=row[8] print(' ') print('Welcome',row[0],".What would you like to have today?") print("----------------------------------------------------------------") print("----------------------------------------------------------------") print("\t\tHotel Paradise Menu Card") print("----------------------------------------------------------------") print("----------------------------------------------------------------") print("\n BREADS THALI MEAL DEALS") print("---------------------------------- -----------------------------------") print(" 1 Toast X2................ 25.00 36.Chana and Puri..............50.00 ") print(" 2 French Toasts........... 30.00 37.Halwa and Puri..............40.00") print("-------------------------- 38.Chana Halwa Puri............65.00") print(" ROTIS AND PARATHAS -----------------------------------") print(" ------------------------- CHINESE") print(" 3.Plain Roti X1............... 10.00 -----------------------------------") print(" 4.Butter Roti X1.............. 20.00 39.Veg Chowmein..................80.00") print(" 5.Butter Nan.................. 25.00 40.Butter Chowmein..............100.00") print(" 6.Aaloo Paratha X1.............25.00 41.Noodles.......................40.00") print(" 7.Aaloo and Onion Paratha X1...30.00 42.Ramen.........................60.00") print(" 8.Paneer Paratha X1............45.00 43.Veg Spring Rolls.............100.00") print(" ------------------------------------ 44.Mixed Spring Rolls...........150.00") print(" SABJI -----------------------------------") print(" ------------------------------------ DALS") print(" 9.Aaloo Gobi..................90.00 ------------------------------------") print(" 10.Bhindi Fry................ 90.00 45.Dal Tadka.....................80.00") print(" 11.Mix Veg....................90.00 46.Dal Fry.......................80.00") print(" 12.Mushroom Masala...........120.00 47.Dal Makhni...................100.00") print(" 13.Aaloo Matar...............100.00 48.Rajma........................100.00") print(" 14.Matar Paneer..............120.00 49.Chhole.......................100.00") print(" 15.Kadai Paneer..............120.00 -----------------------------------") print(" 16.Shahi Paneer..............120.00 RICE") print(" ----------------------------------- -----------------------------------") print(" SOUPS 50.Plain Rice....................90.00") print("------------------------------------ 51.Jeera Rice....................90.00") print(" 17.Tomato Soup................50.00 52.Fried Rice...................120.00") print(" 18.Manchow Soup...............55.00 53.Paneer Fried Rice............165.00") print(" 19.Hot Sour Soup..............55.00 54.Veg Pulao....................130.00") print(" 20.Palak Soup.................55.00 55.Matar Pulao..................140.00") print("------------------------------------ -----------------------------------") print(" SOUTH INDIAN DISHES SANDWICHES") print("------------------------------------ -----------------------------------") print(" 21.Plain Dosa.................70.00 56.Veg Sandwich..................45.00") print(" 22.Masala Dosa................80.00 57.Cheese Sandwich...............65.00") print(" 23.Paneer Masala Dosa........100.00 58.Grilled Sandwich.............120.00") print(" 24.Dahi Vada..................55.00 59.Club Sandwich................120.00") print(" 25.Idli Sambhar...............30.00 60.Veg Cheese Grilled Sandwich..140.00") print(" 26.Idli Fried.................40.00 61.Veg Toasted Sandwich..........70.00") print("------------------------------------ -----------------------------------") print(" PIZZA ICE CREAMS") print("------------------------------------ -----------------------------------") print(" 27.Cheese Pizza..............140.00 62.Vanilla Ice cream.............60.00") print(" 28.Mushroom Pizza............160.00 63.Strawberry Ice cream..........60.00") print(" 29.Margherita................130.00 64.Chocolate Ice cream...........60.00") print(" 30.Paneer Pizza..............160.00 65.Pineapple Ice cream...........60.00") print(" 31.Tomato Pasta Pizza........150.00 66.Butterscotch Ice cream........60.00") print("------------------------------------ -----------------------------------") print(" BEVERAGES DESSERTS") print("------------------------------------ -----------------------------------") print(" 32.Pepsi(500 ml)..............60.00 67.Choco Lava Cake..............100.00") print(" 33.Slice(350 ml)..............50.00 68.Butterscotch Mousse Cake.....100.00") print(" 34.7Up(500 ml)................60.00 69.Red Velvet Lava Cake.........130.00") print(" 35.Mirinda(500 ml)............60.00 70.Blueberry Cheese Lava Cake...130.00") print("------------------------------------ -----------------------------------") print("Press 0 -to end ") choice=1 while(choice!=0): choice=int(input(" -> ")) # if-elif-conditions to assign item # prices listed in menu card if choice==1 or choice==5 or choice==6: cost=25 counter=counter+cost elif choice==2 or choice==7 or choice==25: cost=30 counter=counter+cost elif choice==3: cost=10 counter=counter+cost elif choice==4: cost=20 counter=counter+cost elif choice==8 or choice==56: cost=45 counter=counter+cost elif (choice<=11 and choice>=9) or choice==50 or choice==51: cost=90 counter=counter+cost elif (choice<=16 and choice>=14) or choice==12 or choice==52 or choice==58 or choice==59: cost=120 counter=counter+cost elif (choice<=20 and choice>=18) or choice==24: cost=55 counter=counter+cost elif choice==21 or choice==61: cost=70 counter=counter+cost elif choice==17 or choice==33 or choice==36: cost=50 counter=counter+cost elif choice==22 or choice==39 or choice==45 or choice==46: cost=80 counter=counter+cost elif choice==26 or choice==37 or choice==41: cost=40 counter=counter+cost elif choice==27 or choice==55 or choice==60: cost=140 counter=counter+cost elif choice==28 or choice==30: cost=160 counter=counter+cost elif choice==31 or choice==44: cost=150 counter=counter+cost elif choice==32 or choice==34 or choice==35 or choice==42 or(choice>=62 and choice<=66): cost=60 counter=counter+cost elif choice==38 or choice==57: cost=65 counter=counter+cost elif choice==53: cost=165 counter=counter+cost elif choice==13 or choice==23 or choice==40 or choice==43 or (choice>=47 and choice<=49) or choice==68 or choice==67: cost=100 counter=counter+cost elif choice==29 or choice==54 or choice==70 or choice==69: cost=130 counter=counter+cost elif choice==0: pass else: print("Wrong Choice..!!") if counter!=0: print("Total Bill: ",counter) service=[] bill=str(counter) service.extend([name,customerid,bill]) csvfile.writerow(service) service=[] print('Order Placed.Coming Right Up') sql="update service set Service_Charge ={} where Customer_id={};".format(counter,x) cursor.execute(sql) con.commit() z='NO' sql1="update booking set Payment='{}' where Customer_id={}".format(z,x) cursor.execute(sql1) con.commit() break else: print("Order Not Placed") break else: pass if k==0: print("User with the given Customer id is not registered.") n=int(input("0-BACK\n ->")) if n==0: Home() else: exit() #PAYMENT FUNCTION def payment(): id=int(input('Enter customer id-->')) k=0 with open('hotel.csv','r') as csvfiler: csvr=csv.reader(csvfiler) for row in csvr: for i in range(0,len(row)): if row[8]==str(id): k=k+1 print("Yo") print("Welcome",row[0],". Here is your bill:") sql='select * from service where Customer_id={}'.format(id) cursor.execute(sql) rows=cursor.fetchall() for x in rows: hotel_service=x[2] room_chrg=x[3] print('Hotel Service',hotel_service) print('Room Charge',room_chrg) sql1='select Payment from booking where Customer_id={}'.format(id) cursor.execute(sql1) row1=cursor.fetchall() print("Your Total bill is:",hotel_service+room_chrg) if row1==[('NO',)]: choice=input("Do you wish to make your payment now? y-yes,or any other character to exit-->") if choice=='y' or choice=='Y': print("Enter mode of payment") print(" 1- Credit/Debit Card") print(" 2- Paytm/PhonePe") print(" 3- Using UPI") print(" 4- Cash") x=int(input("-> ")) if 1<=x<=4: print("\n\n --------------------------------") print(" Hotel Paradise") print(" --------------------------------") print(" Bill") print(" --------------------------------") print(" Name: ",row[0],"\t\n") print("\n\t\n Room Charges:",room_chrg) print(" Restaurant Charges: \t",hotel_service) print(" --------------------------------") print("\n Total Amount: ",(hotel_service+room_chrg)) print(" --------------------------------") print(" Thank You") print(" Visit Again :)") print(" --------------------------------\n") z="YES" sql2="update booking set payment='{}' where Customer_id={};".format(z,id) cursor.execute(sql2) con.commit() else: print("Wrong Choice,please retry") else: print("\n\nYour Payment is already done") n = int(input("0-BACK\n ->")) if n==0: Home() break else: exit() # RECORD FUNCTION def search_record(): id=int(input('Enter customer id-->')) k=0 with open('hotel.csv','r') as csvfiler: csvr=csv.reader(csvfiler) for row in csvr: for i in range(0,len(row)): if row[8]==str(id): k=k+1 print("----------------------------------------------------------------------------------------------------------------------") print('Name:',row[0]) print('\nPhone Number:',row[1]) print("\nEmail:",row[2]) print("\nCheck-In Date:",row[3]) print("\nCheck-Out Date",row[4]) print("\nRoom Type:",row[5]) print("\nPrice:",row[6]) print("\nRoom Number:",row[7]) print('\nCustomer Id:',row[8]) print('\nBooked for:',row[9],'days') print("----------------------------------------------------------------------------------------------------------------------") break else: pass if k==0: print("Record with the given customer id is not registered.Please retry!!") csvfiler.close() n = int(input("0-BACK\n ->")) if n == 0: Home() else: exit() #DELETE RECORD FUNCTION def delete_record(): csvfilew1=open("new.csv","w") csvw=csv.writer(csvfilew1) cid=int(input("Enter Your Customer Id :")) k=0 l=[] with open(hotel_database,'r')as csvfiler: csvr=csv.reader(csvfiler) #print(csvr) for row in csvr: for i in range(0,len(row)): if str(cid)==row[8]: k=k+1 print("Record Found,Deleting It.......") print("............") print(".........") print(".....") print("Record Deleted!!") break elif str(cid)!=row[8]: csvw.writerow(row) break if k==0: print("Record with the given customer id is not registered.Please retry!!") csvfilew1.close() csvfiler.close() os.remove("hotel.csv") os.rename("new.csv","hotel.csv") st="delete from booking where Customer_id={}".format(cid) cursor.execute(st) con.commit() n = int(input("0-BACK\n ->")) if n == 0: Home() else: exit() #CONTACT FUNCTION def contact(): print("------------------------------------------") print("\t\tHotel Paradise") print("------------------------------------------") print("\nHere's how you can contact us") print("\nTELEPHONE:") print("\n\t+91 612 2203040") print("\nFAX:") print("\n\t+91 612 2203060") print("\nADDRESS:") print("\n\tHotel Paradise, South Gandhi Maidan, Mumbai , Maharashtra - 400029, India") print('\nGENERAL ENQUIRIES:') print('\n\t+91 612 2203040') print('\n\<EMAIL>') n = int(input("0-BACK\n ->")) if n == 0: Home() else: exit() def exit(): print("\nThank You for using our services") Home() con.close() <file_sep>/README.md # Hotel Management System This is a basic Hotel Management System Project which uses the concepts of MySQL and File Handling. It stores the data in sql tables and csv files. ## Steps To Run Project - You need to have `Python` installed in your device. Can be easily downloaded from [here](https://www.python.org/downloads/) . - You need to have `MySQL` installed in your device. Can be easily installed from [here](https://dev.mysql.com/downloads/mysql/) . - Install `mysql-connector-python` from the command prompt : ``` pip install mysql-connector-python ``` - In MySQL, create a database named `hotel` . Now select that database to use. ``` create database hotel; ``` ``` use hotel; ``` - Inside that database, create two tables namely `booking` and `service`. Use the syntax given below to create tables. For table booking: ``` create table booking( Name Varchar(20), Phone_Number varchar(10), Email varchar(30), Check_In date, Check_Out date, Room_Type varchar(15), Price int, Room_Number int, Customer_id int, Payment varchar(3) default "No", Days int); ``` For table service: ``` create table service( Name varchar(20), Customer_id int, Service_Charge int default 0, Room_Bill int); ``` - Clone this repository (Download this repository). - Now run "Hotel Management System.py". It should be working well. <hr> PS- Deleting record might give error if you try to delete data in same terminal where you booked your room. It will work if you close and re run the program and enter customer id for the customer you want to delete. <br> I have found a fix to that, will push that update later. <hr>
2e1fbbaaa5fdcaa897f1090ffb1b057ea93d34dc
[ "Markdown", "Python" ]
2
Python
RakeshKrGorai/Python-File-Handling-MySQL
e98c644278bda4ec494131a8a854f4d848a9f207
d45c6e9a0d5a721c708f6b8391f438161e5d874e
refs/heads/master
<file_sep>const express = require('express') const router = express.Router() const busboyPromise = require('./busboy-promise') const processRows = require('../data/process') const {collectionName} = require('../data/scheme/util') const schemeMap = require('../data/scheme') const getScheme = filename => { const matches = filename.toLowerCase().match(/hospital_(\d+)_([^\.]+)/) if (matches) { const [all, hospitalId, dataType] = matches return schemeMap[`${dataType}${hospitalId}`] } return null } router.post('/', async (req, res) => { try { const data = await busboyPromise(req) res.end() for (const item of data) { const {filename, streamReader} = item const scheme = getScheme(filename) if (scheme) { const rows = [] // TODO: write to database in batch of some number and not one by one for await (const chunk of streamReader) { rows.push(chunk) } console.log('Write to DB:', scheme[collectionName]) console.log(processRows(rows, scheme)) } else { // log some error } } } catch (ex) { res.status(501) throw ex } }) module.exports = router <file_sep>const moment = require('moment') module.exports = { collectionName: Symbol(), date1: value => { return moment(value, 'M/D/YYYY').format('YYYY-MM-DD') }, } <file_sep>const moment = require('moment') const {collectionName, date1} = require('../util') const PatientBaseScheme = { [collectionName]: 'patients', patientId: { readKey: 'PatientID', type: Number, }, MRN: { readKey: 'MRN', type: Number, }, patientDOB: { readKey: 'PatientDOB', process: date1, }, deceased: { readKey: 'IsDeceased', process: value => (value === 'Active' ? true : false), }, lastName: { readKey: 'LastName', }, firstName: { readKey: 'FirstName', }, address: { readKey: 'Address', }, city: { readKey: 'City', }, } module.exports = PatientBaseScheme <file_sep>const moment = require('moment') const merge = require('lodash/merge') const {collectionName, date1} = require('../util') const TreatmentBaseScheme = { [collectionName]: 'treatments', treatmentId: { readKey: 'TreatmentID', }, patientId: { readKey: 'PatientID', type: Number, }, startDate: { readKey: 'StartDate', process: date1, }, endDate: { readKey: 'EndDate', process: date1, }, displayName: { readKey: 'DisplayName', }, cyclesDays: { // just an example to process complex data (i dont know what cycleXDays really means :)) readKey: 'CyclesXDays', process: value => { if (typeof value !== 'string') { return '' } return value.replace(/(\d+)X(\d+)/g, (m, g1, g2) => { return Number(g1) * Number(g2) }) }, type: Number, }, } module.exports = TreatmentBaseScheme <file_sep>const merge = require('lodash/merge') const PatientBaseScheme = require('./base') module.exports = merge({}, PatientBaseScheme) <file_sep>const merge = require('lodash/merge') const PatientBaseScheme = require('./base') const Hospital2PatientScheme = { patientId: { readKey: 'PatientId', }, deceased: { readKey: 'IsPatientDeceased', process: value => (value === 'Y' ? true : false), }, address: { readKey: 'AddressLine', }, city: { readKey: 'AddressCity', }, } module.exports = merge(PatientBaseScheme, Hospital2PatientScheme) <file_sep>const hospitals = [1, 2] module.exports = hospitals.reduce((map, hospitalId) => { map[`patient${hospitalId}`] = require(`./patient/hospital${hospitalId}`) map[`treatment${hospitalId}`] = require(`./treatment/hospital${hospitalId}`) return map }, {}) <file_sep>const merge = require('lodash/merge') const TreatmentBaseScheme = require('./base') const Hospital2TreatmentScheme = { treatmentId: { readKey: 'TreatmentId', }, patientId: { readKey: 'PatientId', }, cyclesDays: { readKey: 'NumberOfCycles', }, } module.exports = merge(TreatmentBaseScheme, Hospital2TreatmentScheme)
013337bf9e8bb785d9e8b5fdb7e43522cc2fcea9
[ "JavaScript" ]
8
JavaScript
Adidi/tm
05e4edbbb0d08cc1b75c2d0d041bc284275039cb
98a8e5ef3c8f0dc693ed3c72964db3acc4202cf5
refs/heads/master
<repo_name>Ioie/linterna<file_sep>/app/src/main/java/com/example/user/faruleti/MainActivity.java package com.example.user.faruleti; import android.content.pm.PackageManager; import android.hardware.Camera; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button boton_encender; private boolean linternaEncendida = false; private boolean linternaflash = false; private Camera camera; Camera.Parameters parametersCamera; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); linternaflash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH); //revisa si el equipo tiene fla boton_encender = (Button) findViewById(R.id.boton_encender); if (!linternaflash){ boton_encender.setEnabled(false);// si el equipo no tiene fla se deshabilita el button return;// = a hagammos de cuenta que no paso nada } boton_encender.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (linternaEncendida){ apagaflash(); } else { prenderflash(); } } }); } private void prenderflash() { if(camera == null){ try{ camera = camera.open(); } catch (RuntimeException e){ Log.e("Error al abrir la CAM",e.getMessage()); boton_encender.setEnabled(false); } } parametersCamera = camera.getParameters(); parametersCamera.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); camera.setParameters(parametersCamera); camera.startPreview(); linternaEncendida = true; } private void apagaflash() { if(linternaEncendida){ parametersCamera = camera.getParameters(); parametersCamera.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); camera.setParameters(parametersCamera); camera.stopPreview(); linternaEncendida = false; } } }
840732427057adc7482095c03b78c40021d2428f
[ "Java" ]
1
Java
Ioie/linterna
4f97c210d64bb2b27f2cba50165e4f28ef7c5a19
13eb45b1704e7dac79f3c00ee5de0efc1f388f3e
refs/heads/master
<file_sep>using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace NewsWebsite.DataAccess.Entities { public class News { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public string TitleImagePath { get; set; } public DateTime DateAdded { get; set; } public string TagIds { get; set; } } } <file_sep>using Microsoft.EntityFrameworkCore; using NewsWebsite.DataAccess.Entities; namespace NewsWebsite.DataAccess { public class ApplicationDbContext : DbContext { public DbSet<User> Users { get; set; } public DbSet<Tag> Tags { get; set; } public DbSet<News> News { get; set; } public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } } <file_sep>using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using NewsWebsite.DataAccess; using NewsWebsite.DataAccess.Entities; using System; using System.Collections.Generic; using System.Linq; namespace NewsWebsite { public class Program { public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); CreateDbIfNotExists(host); host.Run(); } private static void CreateDbIfNotExists(IHost host) { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService<ApplicationDbContext>(); context.Database.EnsureCreated(); SetDefaultValue(context); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred creating the DB."); } } } private static void SetDefaultValue(ApplicationDbContext context) { if (!context.Tags.ToList().Any()) { context.Tags.AddRange(new List<Tag>() { new Tag() { Id = 1, Name = "Суспільство" }, new Tag() { Id = 2, Name = "Політика" }, new Tag() { Id = 3, Name = "Економіка" }, new Tag() { Id = 4, Name = "За кордоном" }, new Tag() { Id = 5, Name = "Курйози" }, }); context.SaveChanges(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } } <file_sep>using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using NewsWebsite.DataAccess; using NewsWebsite.Models; using NewsWebsite.Services; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.IO; using Microsoft.AspNetCore.Hosting; namespace NewsWebsite.Controllers { [Authorize] public class AdminPanelController : Controller { private readonly string _imagesDirectory; private readonly ApplicationDbContext _context; private readonly TagService _tagService; public AdminPanelController(ApplicationDbContext context, TagService tagService, IWebHostEnvironment hostingEnviroment) { _tagService = tagService; _context = context; _imagesDirectory = Path.Combine(hostingEnviroment.WebRootPath, "NewsData"); } // GET: AdminPanel public async Task<IActionResult> Index() { var news = await _context.News.ToListAsync(); var newsViewModels = news.Select(_ => new NewsViewModel(_)).ToList(); await MapTags(newsViewModels); return View(newsViewModels); } // GET: AdminPanel/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var news = await _context.News .FirstOrDefaultAsync(m => m.Id == id); if (news == null) { return NotFound(); } var vm = new NewsViewModel(news); await _tagService.MapName(vm.Tags); return View(vm); } // GET: AdminPanel/Create public async Task<IActionResult> Create() { var vm = new NewsWithImageViewModel(); await _tagService.MapName(vm.Tags); return View(vm); } // GET: AdminPanel/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var news = await _context.News.FindAsync(id); if (news == null) { return NotFound(); } var vm = new NewsViewModel(news); await _tagService.MapName(vm.Tags); return View(vm); } // POST: AdminPanel/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, NewsWithImageViewModel news) { if (id != news.Id) { return NotFound(); } if (ModelState.IsValid) { try { var filePath = SaveFileLocaly(news); _context.Update(news.ToNewsViewModel(@$"/NewsData/{news.File.FileName}").ToEntity()); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!NewsExists(news.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(news); } // POST: AdminPanel/DeleteConfirmed/5 public async Task<IActionResult> DeleteConfirmed(int id) { var news = await _context.News.FindAsync(id); _context.News.Remove(news); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool NewsExists(int id) { return _context.News.Any(e => e.Id == id); } private async Task MapTags(List<NewsViewModel> newsViewModels) { foreach (var newsViewModel in newsViewModels) { await _tagService.MapName(newsViewModel.Tags); } } private string SaveFileLocaly(NewsWithImageViewModel news) { var filePath = Path.Combine(_imagesDirectory, news.File.FileName); using (var stream = System.IO.File.Create(filePath)) { news.File.CopyTo(stream); } return filePath; } } } <file_sep>using Microsoft.AspNetCore.Http; using NewsWebsite.DataAccess.Entities; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; namespace NewsWebsite.Models { public class NewsWithImageViewModel { public int Id { get; set; } [Required] [DisplayName("Заголовок")] public string Title { get; set; } [Required] [DisplayName("Текст")] public string Content { get; set; } [DisplayName("Зображення")] public IFormFile File { get; set; } [DisplayName("Дата і час виходу")] public DateTime DateAdded { get; set; } public List<TagViewModel> Tags { get; set; } public NewsWithImageViewModel() { Tags = new List<TagViewModel>(); } public NewsViewModel ToNewsViewModel(string imagePath) { return new NewsViewModel() { Id = Id, Title = Title, Content = Content, TitleImagePath = imagePath, DateAdded = DateAdded == new DateTime() ? DateTime.Now : DateAdded, Tags = Tags }; } } } <file_sep>using NewsWebsite.DataAccess.Entities; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; namespace NewsWebsite.Models { public class NewsViewModel { public int Id { get; set; } [Required] [DisplayName("Заголовок")] public string Title { get; set; } [Required] [DisplayName("Текст")] public string Content { get; set; } [DisplayName("Зображення")] public string TitleImagePath { get; set; } [DisplayName("Дата і час виходу")] public DateTime DateAdded { get; set; } public List<TagViewModel> Tags { get; set; } public NewsViewModel() { Tags = new List<TagViewModel>(); } public NewsViewModel(News news) { Id = news.Id; Title = news.Title; Content = news.Content; TitleImagePath = news.TitleImagePath; DateAdded = news.DateAdded; if (!string.IsNullOrEmpty(news.TagIds)) { Tags = news.TagIds .Split(',') .Select(n => new TagViewModel() { Id = Convert.ToInt32(n), IsSelected = true }) .ToList(); } else { Tags = new List<TagViewModel>(); } } public News ToEntity() { return new News() { Id = Id, Title = Title, Content = Content, TitleImagePath = TitleImagePath, DateAdded = DateAdded == new DateTime() ? DateTime.Now : DateAdded, TagIds = string.Join(',', Tags.Where(_ => _.IsSelected).Select(_ => _.Id)) }; } } } <file_sep>using System.Collections.Generic; namespace NewsWebsite.Models { public class NewsIndexViewModel { public List<NewsViewModel> FiveLatestNews { get; set; } public List<NewsViewModel> TenLatestNews { get; set; } public List<TagViewModel> FiveTags { get; set; } } } <file_sep>using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using NewsWebsite.DataAccess; using NewsWebsite.Models; using NewsWebsite.Services; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NewsWebsite.Controllers { public class NewsController : Controller { private int _allowedSymbol = 280; private readonly ApplicationDbContext _context; private readonly TagService _tagService; public NewsController(ApplicationDbContext context, TagService tagService) { _tagService = tagService; _context = context; } public async Task<IActionResult> Index() { var vm = new NewsIndexViewModel(); var tenLatestNews = await GetTenLatestNews(); vm.TenLatestNews = tenLatestNews.ToList(); vm.FiveLatestNews = tenLatestNews.Take(5).ToList(); vm.FiveTags = (await _tagService.GetTags()).Take(5).ToList(); return View(vm); } public async Task<IActionResult> News(int newsId) { var vm = new SpecificNewsViewModel(); vm.News = new NewsViewModel(await _context.News.FirstOrDefaultAsync(_ => _.Id == newsId)); vm.TenLatestNews = await GetTenLatestNews(); await _tagService.MapName(vm.News.Tags); vm.RelatedTags = vm.News.Tags.Where(_ => _.IsSelected).ToList(); return View(vm); } public async Task<IActionResult> AllNews(int tagId) { var allNewsViewModel = await GetAllNews(); if (tagId != default) { allNewsViewModel = allNewsViewModel.Where(_ => _.Tags.Any(_ => _.Id == tagId)).ToList(); } foreach (var item in allNewsViewModel) { if (item.Content.Length > _allowedSymbol) { item.Content = item.Content.Substring(0, _allowedSymbol) + " ..."; } } return View(allNewsViewModel); } private async Task<List<NewsViewModel>> GetTenLatestNews() { return (await _context.News .OrderBy(_ => _.DateAdded) .Take(10) .ToListAsync()).Select(_ => new NewsViewModel(_)).ToList(); } private async Task<List<NewsViewModel>> GetAllNews() { return (await _context.News .OrderBy(_ => _.DateAdded) .ToListAsync()).Select(_ => new NewsViewModel(_)).ToList(); } } } <file_sep>using NewsWebsite.DataAccess.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NewsWebsite.Models { public class TagViewModel { public int Id { get; set; } public string Name { get; set; } public bool IsSelected { get; set; } public TagViewModel() { } public TagViewModel(Tag tag) { Id = tag.Id; Name = tag.Name; } } } <file_sep>using Microsoft.EntityFrameworkCore; using NewsWebsite.DataAccess; using NewsWebsite.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NewsWebsite.Services { public class TagService { private readonly ApplicationDbContext _context; public TagService(ApplicationDbContext context) { _context = context; } public async Task<List<TagViewModel>> GetTags() { var tags = await _context.Tags.ToListAsync(); return tags.Select(_ => new TagViewModel(_)).ToList(); } public async Task MapName(List<TagViewModel> tagViewModels) { var tags = await _context.Tags.ToListAsync(); foreach (var tag in tags) { var tagViewModel = tagViewModels.FirstOrDefault(_ => _.Id == tag.Id); if (tagViewModel == null) { tagViewModels.Add(new TagViewModel(tag)); continue; } tagViewModel.Name = tag.Name; } } } } <file_sep>using System.Collections.Generic; namespace NewsWebsite.Models { public class SpecificNewsViewModel { public List<NewsViewModel> TenLatestNews { get; set; } public List<TagViewModel> RelatedTags { get; set; } public NewsViewModel News { get; set; } } }
7411f77de16d1663df81cd03a0ec9c2db531dfc9
[ "C#" ]
11
C#
bogdansadoviy/NewsWebsiteSolution
04e35df7d00a2a86c11a131ab8c0c69cf0db5479
70aa3d204069481008d1a16b71e6eb1962603cf6
refs/heads/main
<file_sep>import { createApp } from 'vue' import App from './App.vue' import './index.css' // TODO 导入vuex import store from './store/index.js' // app.use(store) 可以写在下面一起注册 // TODO 导入 vue-router import router from './router/index.js' // app.use(router) 可以写在下面一起注册 // Soumns 导入ant-designUI框架 import Antd from 'ant-design-vue'; // Soumns 导入ant-design样式文件 import 'ant-design-vue/dist/antd.css'; const app = createApp(App) // FIXME 注册全局变量 import { message } from 'ant-design-vue' app.config.globalProperties.$message = message // FIXME 注册store、router、Antd app.use(store).use(router).use(Antd).mount('#app') <file_sep>// src目录下创建 store 文件夹,里面放入 index.js // store/index.js目录下 // TODO createStore 创建一个store状态管理库 import { createStore } from "vuex"; // 将store管理库的几个模块导出,以便于导入到 main.js(入口) 文件里 // TODO 导入axios import axios from "axios"; export default createStore({ state: { // Soumns 渲染列表的数据 listData: JSON.parse(window.sessionStorage.getItem("listData")) || [], // Soumns input框输入内容(从本地拉取数据) inputValue: JSON.parse(window.sessionStorage.getItem("inputValue")) || "", // Soumns 下一个id nextId: 5, }, mutations: { // TODO 获取初始数据 getListData(state, info) { // 更新到vuex state.listData = info; // 保存到本地 window.sessionStorage.setItem("listData", JSON.stringify(state.listData)); }, // TODO 改变表单数据 changeTodo(state, info) { state.inputValue = info; }, // TODO 添加数据 addTodo(state, info) { // 保存到vuex state.inputValue = info; // 将数据保存到本地,实现永久存储 window.sessionStorage.setItem( "inputValue", JSON.stringify(state.inputValue) ); // 往state的listData中推一条数据,模拟调用接口增加数据 const obj = { id: state.nextId - 1, done: false, content: info, }; console.log(state.nextId); // 追加一条数据 state.listData.push(obj); // 将下一条数据的nextId自增 state.nextId++; // 清空表单数据 state.inputValue = ""; }, // TODO 删除数据 delTodos(state, info) { // console.log(77777) state.listData = state.listData.filter((item) => { return item.id !== info; }); }, // TODO 改变数据 changeStatus(state, info) { // 找到对应修改的那一条todo const i = state.listData.findIndex((item) => item.id === info); // 修改对应的数据 state.listData[i].done = !state.listData[i].done; }, }, actions: { // FIXME 调用接口获取数据 async getListDataSync(context) { const { data: res } = await axios.post( "https://easy-mock.bookset.io/mock/6050b5a9aefff2657c6dae3d/soumns777/getContent" ); console.log(res); // console.log(context) // 将数据传给mutations的方法 context.commit("getListData", res); }, }, getters: {}, });
a75f926ce1667310633a18ab261fb5fb4160867b
[ "JavaScript" ]
2
JavaScript
Soumns777/vue3TodoList
e11bcda0b944a2eafa8bd8e7147abd20cc043673
03cb979869702e3a14a663151cd166fb6dc78680
refs/heads/main
<file_sep>// MIT License // // Copyright (c) 2021 cocodding0723 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Maze { public class MazeGenerator : MonoBehaviour { public Vector2Int mazeSize = new Vector2Int(25, 25); private Vector2Int BlockSize => mazeSize / 2; private Block[,] _blocks; private bool[,] _existWalls; private DisjointSet _disjointSet; private readonly Dictionary<int, List<int>> _lastRowBlocks = new Dictionary<int, List<int>>(); [SerializeField] private float delayCreateTime = 0.25f; [SerializeField] private bool isDelayCreate; [SerializeField] private bool isDrawGizmo; [SerializeField] private GameObject wallPrefab; private void Awake() { var size = BlockSize; var disjointSetSize = BlockSize.x * BlockSize.y; _blocks = new Block[size.x, size.y]; _existWalls = new bool[mazeSize.x, mazeSize.y]; _disjointSet = new DisjointSet(disjointSetSize); } private void Start() { InitBlocks(); if (isDelayCreate && isDrawGizmo) { StartCoroutine(DelayCreateMaze()); } else { for (int y = 0; y < BlockSize.y - 1; y++) { RandomMergeRowBlocks(y); DropDownGroups(y); } OrganizeLastLine(); MakeHoleInPath(); if (!isDrawGizmo) { BuildWalls(); } } } /// <summary> /// 블럭을 초기화 하는 함수. /// A function that initializes blocks. /// </summary> private void InitBlocks() { for (int x = 0; x < BlockSize.x; x++) { for (int y = 0; y < BlockSize.y; y++) { _blocks[x, y] = new Block(); } } } /// <summary> /// 행의 블럭을 순차적으로 접근하면서 선택한 블럭과 오른쪽 블럭을 랜덤하게 합치는 함수. /// A function of randomly merge the selected block and the right block while sequentially approaching the blocks of the row. /// </summary> /// <param name="row">현재 행 (current row)</param> private void RandomMergeRowBlocks(int row) { for (int x = 0; x < BlockSize.x - 1; x++) { var canMerge = Random.Range(0, 2) == 1; var currentBlockNumber = _blocks[x, row].BlockNumber; var nextBlockNumber = _blocks[x + 1, row].BlockNumber; if (canMerge && !_disjointSet.IsUnion(currentBlockNumber, nextBlockNumber)) { _disjointSet.Merge(currentBlockNumber, nextBlockNumber); _blocks[x, row].OpenWay[(int)Direction.Right] = true; } } } /// <summary> /// 현재 행에서 가지를 내리는 함수 /// A function of branching off the current row. /// </summary> /// <param name="row">현재 행 (current row)</param> private void DropDownGroups(int row) { _lastRowBlocks.Clear(); for (int x = 0; x < BlockSize.x; x++) { var blockNumber = _blocks[x, row].BlockNumber; var parentNumber = _disjointSet.Find(_blocks[x, row].BlockNumber); if (!_lastRowBlocks.ContainsKey(parentNumber)) { _lastRowBlocks.Add(parentNumber, new List<int>()); } _lastRowBlocks[parentNumber].Add(blockNumber); } foreach (var group in _lastRowBlocks) { if (group.Value.Count == 0) continue; var randomDownCount = Random.Range(1, group.Value.Count); for (int i = 0; i < randomDownCount; i++) { var randomBlockIndex = Random.Range(0, group.Value.Count); var currentBlockNumber = group.Value[randomBlockIndex]; var currentBlockPosition = Block.GetPosition(currentBlockNumber, BlockSize); var currentBlock = _blocks[currentBlockPosition.x, currentBlockPosition.y]; var underBlock = _blocks[currentBlockPosition.x, currentBlockPosition.y + 1]; _disjointSet.Merge(currentBlock.BlockNumber, underBlock.BlockNumber); currentBlock.OpenWay[(int)Direction.Down] = true; group.Value.RemoveAt(randomBlockIndex); } } } /// <summary> /// 마지막 줄을 정리하는 함수 /// A function that organizes the last line. /// </summary> private void OrganizeLastLine() { var lastRow = BlockSize.y - 1; for (int x = 0; x < BlockSize.x - 1; x++) { var currentBlock = _blocks[x, lastRow]; var nextBlock = _blocks[x + 1, lastRow]; if (!_disjointSet.IsUnion(currentBlock.BlockNumber, nextBlock.BlockNumber)) { currentBlock.OpenWay[(int)Direction.Right] = true; } } } private IEnumerator DelayCreateMaze() { for (int y = 0; y < BlockSize.y - 1; y++) { yield return StartCoroutine(DelayRandomMergeBlocks(y)); yield return StartCoroutine(DelayDropDownGroups(y)); MakeHoleInPath(); yield return new WaitForSeconds(delayCreateTime); } yield return new WaitForSeconds(delayCreateTime); yield return StartCoroutine(DelayCleanUpLastLine()); MakeHoleInPath(); } private IEnumerator DelayRandomMergeBlocks(int row) { for (int x = 0; x < BlockSize.x - 1; x++) { var canMerge = Random.Range(0, 2) == 1; var currentBlockNumber = _blocks[x, row].BlockNumber; var nextBlockNumber = _blocks[x + 1, row].BlockNumber; if (canMerge && !_disjointSet.IsUnion(currentBlockNumber, nextBlockNumber)) { _disjointSet.Merge(currentBlockNumber, nextBlockNumber); _blocks[x, row].OpenWay[(int)Direction.Right] = true; } MakeHoleInPath(); yield return new WaitForSeconds(delayCreateTime); } } private IEnumerator DelayDropDownGroups(int row) { _lastRowBlocks.Clear(); for (int x = 0; x < BlockSize.x; x++) { var blockNumber = _blocks[x, row].BlockNumber; var parentNumber = _disjointSet.Find(_blocks[x, row].BlockNumber); if (!_lastRowBlocks.ContainsKey(parentNumber)) { _lastRowBlocks.Add(parentNumber, new List<int>()); } _lastRowBlocks[parentNumber].Add(blockNumber); } foreach (var group in _lastRowBlocks) { if (group.Value.Count == 0) continue; var randomDownCount = Random.Range(1, group.Value.Count); for (int i = 0; i < randomDownCount; i++) { var randomBlockIndex = Random.Range(0, group.Value.Count); var currentBlockNumber = group.Value[randomBlockIndex]; var currentBlockPosition = Block.GetPosition(currentBlockNumber, BlockSize); var currentBlock = _blocks[currentBlockPosition.x, currentBlockPosition.y]; var underBlock = _blocks[currentBlockPosition.x, currentBlockPosition.y + 1]; _disjointSet.Merge(currentBlock.BlockNumber, underBlock.BlockNumber); currentBlock.OpenWay[(int)Direction.Down] = true; group.Value.RemoveAt(randomBlockIndex); MakeHoleInPath(); yield return new WaitForSeconds(delayCreateTime); } } } private IEnumerator DelayCleanUpLastLine() { var lastRow = BlockSize.y - 1; for (int x = 0; x < BlockSize.x - 1; x++) { var currentBlock = _blocks[x, lastRow]; var nextBlock = _blocks[x + 1, lastRow]; if (!_disjointSet.IsUnion(currentBlock.BlockNumber, nextBlock.BlockNumber)) { currentBlock.OpenWay[(int)Direction.Right] = true; } MakeHoleInPath(); yield return new WaitForSeconds(delayCreateTime); } } private void MakeHoleInPath() { for (int x = 0; x < BlockSize.x; x++) { for (int y = 0; y < BlockSize.y; y++) { var adjustPosition = new Vector2Int(x * 2 + 1, y * 2 + 1); _existWalls[adjustPosition.x, adjustPosition.y] = true; if (_blocks[x, y].OpenWay[(int)Direction.Down]) _existWalls[adjustPosition.x, adjustPosition.y + 1] = true; if (_blocks[x, y].OpenWay[(int)Direction.Right]) _existWalls[adjustPosition.x + 1, adjustPosition.y] = true; } } } private void BuildWalls() { for (int x = 0; x < mazeSize.x; x++) { for (int y = 0; y < mazeSize.y; y++) { if (_existWalls[x, y]) continue; var myTransform = transform; var mazeHalfSize = new Vector3(mazeSize.x, 0, mazeSize.y) / 2; var wallPosition = new Vector3(x, 0.5f, y) - mazeHalfSize + myTransform.position; Instantiate(wallPrefab, wallPosition, Quaternion.identity, myTransform); } } } private void OnDrawGizmos() { if (Application.isPlaying && isDrawGizmo) { Gizmos.color = Color.red; for (int x = 0; x < mazeSize.x; x++) { for (int y = 0; y < mazeSize.y; y++) { if (!_existWalls[x, y]) { var mazeHalfSize = new Vector3(mazeSize.x, 0, mazeSize.y) / 2; var wallPosition = new Vector3(x, 0.5f, y) - mazeHalfSize + transform.position; Gizmos.DrawCube(wallPosition, Vector3.one); } } } } } } }<file_sep>namespace Maze { public enum Direction : sbyte { Down = 0, Right, } }<file_sep>using UnityEngine; namespace Maze { public class Block { public int BlockNumber { get; private set; } public readonly bool[] OpenWay = new bool[4]; private static int s_increaseGroupNumber; public Block() { BlockNumber = s_increaseGroupNumber++; } public static Vector2Int GetPosition(int blockNumber, Vector2Int size) { return new Vector2Int(blockNumber / size.x, blockNumber % size.y); } public Vector2Int GetPosition(Vector2Int size) => GetPosition(BlockNumber, size); public int GetParentIndex(Vector2Int size) => BlockNumber * size.x + BlockNumber % size.y; } }<file_sep>namespace Maze { public class DisjointSet { public int ParentsSize { get; private set; } public readonly int[] Parents; public DisjointSet(int parentSize) { ParentsSize = parentSize; Parents = new int[parentSize]; for (int i = 0; i < ParentsSize; i++) Parents[i] = i; } public int Find(int x) { if (x == Parents[x]) return x; return Parents[x] = Find(Parents[x]); } public void Merge(int a, int b) { a = Find(a); b = Find(b); if (a == b) return; if (a > b) Parents[a] = b; else Parents[b] = a; } public bool IsUnion(int a, int b) { a = Find(a); b = Find(b); if (a == b) return true; else return false; } } }<file_sep># 미로 자동 생성기 Maze Auto Generator 참고 사이트 : http://weblog.jamisbuck.org/2010/12/29/maze-generation-eller-s-algorithm 다음은 생성하는 과정을 나타낸 이미지입니다. ![ProcedualCreate](ProcedualCreate.gif) ## 방법 미로 자동 생성기는 `엘러` 알고리즘을 기반으로 제작되었습니다. 엘러 알고리즘은 미로를 제작하는 알고리즘으로 시간복잡도 O(N) 의 속도를 가지고 있습니다. 방법은 다음과 같습니다. 1. 전체 블럭을 각 번호로 초기화 시킵니다. 그리고 블럭 갯수만큼 집합을 만듭니다. 2. 인접한 블럭을 무작위로 병합합니다. 단 같은 집합일 경우 합치지 않습니다. 3. 해당 행의 집합중 최소 1개 이상 무작위로 아래 블럭과 병합시킵니다. 4. 마지막 행에 도달할 때까지 반복합니다. 5. 마지막 행일 경우 같은 집합에 속하지 않는 집합과의 벽을 허뭅니다. ## 팁 저는 이 알고리즘을 유니티로 제작하였으며 추가적으로 그룹핑을 하기 위해서 유니온 파인드(Disjoint Set) 알고리즘을 사용하여 그룹핑 작업하는 시간을 줄였습니다. 유니온 파인드 알고리즘을 사용할때 다음과 같은 로직을 썻습니다. 블럭의 집합 번호는 2차원 배열의 열과 행을 이용하여 도출하였습니다. ``` 집합 번호 : i * 미로 크기 + j % 미로 크기 ``` 블럭의 위치는 미로의 크기를 이용해 도출했습니다. ``` i = 집합번호 / 미로 크기 j = 집합번호 % 미로 크기 ``` --- ## Method The maze automatic generator is built on the basis of the Eller algorithm. The Eller algorithm is an algorithm that produces labyrinths and has a speed of time complexity O(N). The method is as follows. 1. Initialize the entire block to each number. And make a set by the number of blocks. 2. Randomly merge adjacent blocks. However, if it is the same set, it does not merge. 3. Randomly merge at least one set of rows with the block below. 4. Repeat until the last row is reached. 5. In the last row, break the wall with the set that does not belong to the same set. ## Tip I made this algorithm as Unity and reduced the time to group using the UnionFind algorithm to further group. When using the UnionFind algorithm, the following logic is written. The set number of blocks was derived using columns and rows in a two-dimensional array. ``` Set number: i * Maze size + j % Maze size ``` The location of the block was derived using the size of the maze. ``` i = Set number / Maze size j = Set number % Maze Size ```
b5a9852412ce8a0b0d46e38c9244a764b95b049c
[ "Markdown", "C#" ]
5
C#
cocodding0723/MazeAutoGenerator
ae4efaca6739eb3bcdc7ddd1399ca263f791c7c7
c7c6e64fb17466cdc69086f7947a3ba23b4ee6ed
refs/heads/master
<repo_name>Renatojr2/dropbox-clone<file_sep>/README.md This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Dropbox-clone ![Drobbox](https://github.com/Renatojr2/dropbox-clone/blob/master/assets/cloneDropbox.PNG) <file_sep>/src/components/MenuForm/styles.ts import styled from 'styled-components'; import { FaDropbox } from "react-icons/fa"; export const Container = styled.div` display: flex; flex-direction: column; height: 100%; @media (min-width: 1024px) { max-width: 480px; } `; export const NavigationForm = styled.nav` display: flex; align-items: center; justify-content: space-between; padding: 16px 32px; min-height: 61px; h1 { display: flex; align-items: center; span { font-size: 26px; margin-left: 8px; } } button { border: none; background: none; outline: none; font-size: 24px; cursor: pointer; } @media (min-width: 1024px) { h1 { display: none; } } ` export const Form = styled.form` display: flex; flex-direction: column; justify-content: center; padding: 0 32px; max-width: 480px; margin: 0 auto; width: 100%; > .title { font-size: 25px; font-weight: bold; } > .subTitle { font-size: 12; margin-top: 3px; } ` export const DropboxLogo = styled(FaDropbox)` width: 36px; height: 32px; fill: var(--color-blue); `;
880d9254e157cbfa682af9c8797ecf0f44010bdf
[ "Markdown", "TypeScript" ]
2
Markdown
Renatojr2/dropbox-clone
b80a040389adcc97497cc97bd1fba5d7cd5f527a
4c9a5b518193c85359a42b9566702c6935409fa7
refs/heads/master
<repo_name>makki08/Registration<file_sep>/src/java/org/feu/eac/ServiceLogic.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 org.feu.eac; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.codec.digest.DigestUtils; import org.feu.eac.dto.User; /** * * @author makki */ public class ServiceLogic { private static final String DB_URL = "jdbc:mysql://localhost:3306/test"; private static final String USER = "root"; private static final String PASS = "<PASSWORD>"; // private int account_id; // private String first_name; // private String last_name; // private String email; // private String username; // private String password; public User authenticate(String username, String password) { User user = new User(); // Open a connection Connection conn = null; //Create PreparedStatement object PreparedStatement preparedStatement = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL, USER, PASS); String sql = "SELECT * FROM test.accounts WHERE username = ? AND password = ?"; preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1, username); preparedStatement.setString(2, DigestUtils.md5Hex(password)); // Execute SQL query ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { //valid = true; user.setAccount_id(rs.getInt("account_id")); user.setFirst_name(rs.getString("first_name")); user.setLast_name(rs.getString("last_name")); user.setEmail(rs.getString("email")); user.setPhone(rs.getString("phone")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); } } catch (SQLException se) { System.out.println(se.getMessage()); } catch (Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException ex) { Logger.getLogger(ServiceLogic.class.getName()).log(Level.SEVERE, null, ex); } } if (conn != null) { try { conn.close(); } catch (SQLException ex) { Logger.getLogger(ServiceLogic.class.getName()).log(Level.SEVERE, null, ex); } } } return user; } public boolean checkUsername (String username) { boolean valid = true; Connection conn = null; //Create PreparedStatement object PreparedStatement preparedStatement = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL, USER, PASS); String sql = "SELECT * FROM test.accounts WHERE username = ?"; preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1, username); // Execute SQL query ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { valid = false; System.out.println("Username exists."); } } catch (SQLException se) { System.out.println(se.getMessage()); } catch (Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException ex) { Logger.getLogger(ServiceLogic.class.getName()).log(Level.SEVERE, null, ex); } } if (conn != null) { try { conn.close(); } catch (SQLException ex) { Logger.getLogger(ServiceLogic.class.getName()).log(Level.SEVERE, null, ex); } } } return valid; } public void insertInfo (String first_name, String last_name, String email, String phone, String username, String password) { Connection conn = null; //Create PreparedStatement object PreparedStatement preparedStatement = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL, USER, PASS); String sql = "INSERT INTO test.accounts(first_name, last_name, email, phone, username, password) VALUES (?, ?, ?, ?, ?, ?);"; preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1, first_name); preparedStatement.setString(2, last_name); preparedStatement.setString(3, email); preparedStatement.setString(4, phone); preparedStatement.setString(5, username); preparedStatement.setString(6, DigestUtils.md5Hex(password)); // Execute SQL insert preparedStatement.executeUpdate(); } catch (SQLException se) { System.out.println(se.getMessage()); } catch (Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException ex) { Logger.getLogger(ServiceLogic.class.getName()).log(Level.SEVERE, null, ex); } } if (conn != null) { try { conn.close(); } catch (SQLException ex) { Logger.getLogger(ServiceLogic.class.getName()).log(Level.SEVERE, null, ex); } } } } } <file_sep>/src/java/org/feu/eac/ControllerServlet.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 org.feu.eac; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.feu.eac.dto.User; /** * * @author makki */ public class ControllerServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet ControllerServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet ControllerServlet at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //processRequest(request, response); response.setContentType("text/html"); PrintWriter out = response.getWriter(); if (request.getParameter("login") != null && request.getParameter("login").equals("Login")) { String username = request.getParameter("username"); String password = request.getParameter("password"); ServiceLogic login = new ServiceLogic(); User user = login.authenticate(username, password); //boolean valid = login.authenticate(username, password); // User user = new User(); // user.setAccount_id(1); // user.setFirst_name("makki"); // user.setLast_name("menzon"); // user.setEmail("<EMAIL>"); // user.setUsername("makki"); // user.setPassword("<PASSWORD>"); //if (!user.getUsername().equals("")) { if (!user.getUsername().equals("")) { //request.getSession().setAttribute("makki", "makkivalue"); request.getSession().setAttribute("user", user); response.sendRedirect("welcome.jsp"); //request.getRequestDispatcher("success.jsp").forward(request, response); } else { request.getSession().setAttribute("errorMessage", "Invalid Username/Password"); response.sendRedirect("index.jsp"); //request.getRequestDispatcher("index.jsp").forward(request, response); } } else if (request.getParameter("login") != null && request.getParameter("login").equals("Register")){ //out.println("Register was pressed"); response.sendRedirect("register.jsp"); } else if (request.getParameter("register") != null && request.getParameter("register").equals("Submit")) { String first_name = request.getParameter("first_name"); String last_name = request.getParameter("last_name"); String email = request.getParameter("email"); String phone = request.getParameter("phone"); String username = request.getParameter("username"); String password = request.getParameter("password"); String password2 = request.getParameter("password2"); ServiceLogic check = new ServiceLogic(); boolean checkUsername = check.checkUsername(username); if (checkUsername) { check.insertInfo(first_name, last_name, email, phone, username, password); response.sendRedirect("success.jsp"); } else { request.getSession().setAttribute("errorMessage2", "Username already exists. Please choose another one."); response.sendRedirect("register.jsp"); } } else if (request.getParameter("logout") != null && request.getParameter("logout").equals("Logout")) { request.getSession().invalidate(); response.sendRedirect("index.jsp"); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
119d38e5f69915a1be502797fbffed710e776f37
[ "Java" ]
2
Java
makki08/Registration
5f4356270f417a14a8696c5f18932114f3f26a30
d5f541e2be49dc22867044b496770c3fab3bfae2
refs/heads/master
<repo_name>edjacks/scheduled-script<file_sep>/install-license.py import os import pexpect import sys lapass = os.environ['SSHPASS'] lauser = 'userid' host = sys.argv[1] license = sys.argv[2] child = pexpect.spawn("/usr/bin/ssh " + lauser + "@" + host) child.logfile_read = sys.stdout child.expect("assword:") child.sendline(lapass) child.expect('#') child.sendline('term len 0') child.expect('#') child.sendline('show clock') child.expect('#') child.sendline('show license detail') child.expect('#') child.sendline('show license udi') child.expect('#') child.sendline('license install flash:' + license) child.expect('#') child.sendline('show license detail') child.expect('#') child.sendline('show clock') child.expect('#') child.sendline('exit') child.close() <file_sep>/README.md # scheduled-script bash trick to run cron like job when there's no AT or CRONJOB available I used this trick to have a long running script in a tmux session that would run a set of commands at a given time. In this case it was to call a python (pexpect) script to log into a number of CSR routers and install the license files from flash. The system I used did not have ATD or allow me access to cron. <file_sep>/license.sh #!/bin/env bash while :; do # EST if [[ "$(date '+%Y%m%d%H%M')" == "201811082230" ]]; then break else echo -n . sleep 30 fi done echo date echo cat ./est.list | while read line; do dev=$(echo "${line}" | cut -d, -f1) lic=$(echo "${line}" | cut -d, -f2) python2 ./install-license.py ${dev} ${lic} done while :; do # CST if [[ "$(date '+%Y%m%d%H%M')" == "201811082330" ]]; then break else echo -n . sleep 30 fi done echo date echo cat ./cst.list | while read line; do dev=$(echo "${line}" | cut -d, -f1) lic=$(echo "${line}" | cut -d, -f2) python2 ./install-license.py ${dev} ${lic} done while :; do # PST if [[ "$(date '+%Y%m%d%H%M')" == "201811090130" ]]; then break else echo -n . sleep 30 fi done echo date echo cat ./pst.list | while read line; do dev=$(echo "${line}" | cut -d, -f1) lic=$(echo "${line}" | cut -d, -f2) python2 ./install-license.py ${dev} ${lic} done while :; do # HST if [[ "$(date '+%Y%m%d%H%M')" == "201811090330" ]]; then break else echo -n . sleep 30 fi done echo date echo cat ./hst.list | while read line; do dev=$(echo "${line}" | cut -d, -f1) lic=$(echo "${line}" | cut -d, -f2) python2 ./install-license.py ${dev} ${lic} done
2342ea66b9ae76fc584a9283778f5e5d87e64ad3
[ "Markdown", "Python", "Shell" ]
3
Python
edjacks/scheduled-script
f192cc4ad1d6b177272e66073cd32ea7aed5e6e5
1d30d2b88251b7eaf64b85733c551653b9aaac2c