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>use std::convert::TryFrom; use std::fs; use std::net::{Ipv4Addr, SocketAddr}; use std::path::PathBuf; use std::task::{Context, Poll}; use std::thread; use std::time::Duration; use crate::env; use crate::error::StdResult; use crate::shuffle::*; use crossbeam::channel as cb_channel; use futures::future; use hyper::{ client::Client, server::conn::AddrIncoming, service::Service, Body, Request, Response, Server, StatusCode, Uri, }; use tokio::time::delay_for; use uuid::Uuid; pub(crate) type Result<T> = StdResult<T, ShuffleError>; /// Creates directories and files required for storing shuffle data. /// It also creates the file server required for serving files via HTTP request. #[derive(Debug)] pub(crate) struct ShuffleManager { local_dir: PathBuf, shuffle_dir: PathBuf, server_uri: String, ask_status: cb_channel::Sender<()>, rcv_status: cb_channel::Receiver<Result<StatusCode>>, } impl ShuffleManager { pub fn new() -> Result<Self> { let local_dir = ShuffleManager::get_local_work_dir()?; let shuffle_dir = local_dir.join("shuffle"); fs::create_dir_all(&shuffle_dir).map_err(|_| ShuffleError::CouldNotCreateShuffleDir)?; let shuffle_port = env::Configuration::get().shuffle_svc_port; let server_uri = ShuffleManager::start_server(shuffle_port)?; let (send_main, rcv_main) = ShuffleManager::init_status_checker(&server_uri)?; let manager = ShuffleManager { local_dir, shuffle_dir, server_uri, ask_status: send_main, rcv_status: rcv_main, }; if let Ok(StatusCode::OK) = manager.check_status() { Ok(manager) } else { Err(ShuffleError::FailedToStart) } } pub fn get_server_uri(&self) -> String { self.server_uri.clone() } pub fn get_output_file( &self, shuffle_id: usize, input_id: usize, output_id: usize, ) -> StdResult<String, Box<dyn std::error::Error>> { let path = self .shuffle_dir .join(format!("{}/{}", shuffle_id, input_id)); fs::create_dir_all(&path)?; let file_path = path.join(format!("{}", output_id)); fs::File::create(&file_path)?; Ok(file_path .to_str() .ok_or_else(|| ShuffleError::CouldNotCreateShuffleDir)? .to_owned()) } pub fn check_status(&self) -> Result<StatusCode> { self.ask_status.send(()).unwrap(); self.rcv_status .recv() .map_err(|_| ShuffleError::AsyncRuntimeError)? } /// Returns the shuffle server URI as a string. pub(super) fn start_server(port: Option<u16>) -> Result<String> { let bind_ip = env::Configuration::get().local_ip; let port = if let Some(bind_port) = port { ShuffleManager::launch_async_server(bind_ip, bind_port)?; bind_port } else { let bind_port = crate::utils::get_free_port()?; ShuffleManager::launch_async_server(bind_ip, bind_port)?; bind_port }; let server_uri = format!("http://{}:{}", env::Configuration::get().local_ip, port,); log::debug!("server_uri {:?}", server_uri); Ok(server_uri) } fn launch_async_server(bind_ip: Ipv4Addr, bind_port: u16) -> Result<()> { let (s, r) = cb_channel::bounded::<Result<()>>(1); thread::spawn(move || { // TODO: use the main async global runtime match tokio::runtime::Builder::new() .enable_all() .threaded_scheduler() .build() .map_err(|_| ShuffleError::AsyncRuntimeError) { Err(err) => { s.send(Err(err)).unwrap(); } Ok(mut rt) => { if let Err(err) = rt.block_on(async move { let bind_addr = SocketAddr::from((bind_ip, bind_port)); Server::try_bind(&bind_addr.clone()) .map_err(|_| crate::NetworkError::FreePortNotFound(bind_port, 0))? .serve(ShuffleSvcMaker) .await .map_err(|_| ShuffleError::FailedToStart) }) { s.send(Err(err)).unwrap(); }; } } }); cb_channel::select! { recv(r) -> msg => { msg.map_err(|_| ShuffleError::FailedToStart)??; } // wait a prudential time to check that initialization is ok and the move on default(Duration::from_millis(100)) => log::debug!("started shuffle server @ {}", bind_port), }; Ok(()) } fn init_status_checker( server_uri: &str, ) -> Result<( cb_channel::Sender<()>, cb_channel::Receiver<Result<StatusCode>>, )> { // Build a two way com lane between the main thread and the background running executor let (send_child, rcv_main) = cb_channel::unbounded::<Result<StatusCode>>(); let (send_main, rcv_child) = cb_channel::unbounded::<()>(); let uri_str = format!("{}/status", server_uri); let status_uri = Uri::try_from(&uri_str)?; thread::Builder::new() .name(format!("{}_shuffle_server_hc", env::THREAD_PREFIX)) .spawn(|| -> Result<()> { // TODO: use the main async global runtime let mut rt = tokio::runtime::Builder::new() .enable_all() .basic_scheduler() .core_threads(1) .thread_stack_size(1024) .build() .map_err(|_| ShuffleError::AsyncRuntimeError)?; rt.block_on( #[allow(unreachable_code)] async move { let client = Client::builder().http2_only(true).build_http::<Body>(); // loop forever waiting for requests to send loop { let res = client.get(status_uri.clone()).await?; // dispatch all queued requests responses while let Ok(()) = rcv_child.try_recv() { send_child.send(Ok(res.status())).unwrap(); } // sleep for a while before checking again if there are status requests delay_for(Duration::from_millis(25)).await } Ok::<(), ShuffleError>(()) }, )?; Err(ShuffleError::AsyncRuntimeError) }) .map_err(|_| ShuffleError::FailedToStart)?; Ok((send_main, rcv_main)) } fn get_local_work_dir() -> Result<PathBuf> { let local_dir_root = &env::Configuration::get().local_dir; for _ in 0..10 { let local_dir = local_dir_root.join(format!("ns-local-{}", Uuid::new_v4().to_string())); if !local_dir.exists() { log::debug!("creating directory at path: {:?}", &local_dir); fs::create_dir_all(&local_dir) .map_err(|_| ShuffleError::CouldNotCreateShuffleDir)?; return Ok(local_dir); } } Err(ShuffleError::CouldNotCreateShuffleDir) } } //TODO implement drop for deleting files created when the shuffle manager stops type ShuffleServer = Server<AddrIncoming, ShuffleSvcMaker>; struct ShuffleService; enum ShuffleResponse { Status(StatusCode), CachedData(Vec<u8>), } impl ShuffleService { fn response_type(&self, uri: &Uri) -> Result<ShuffleResponse> { let parts: Vec<_> = uri.path().split('/').collect(); match parts.as_slice() { [_, endpoint] if *endpoint == "status" => Ok(ShuffleResponse::Status(StatusCode::OK)), [_, endpoint, shuffle_id, input_id, reduce_id] if *endpoint == "shuffle" => Ok( ShuffleResponse::CachedData( self.get_cached_data(uri, &[*shuffle_id, *input_id, *reduce_id])?, ), ), _ => Err(ShuffleError::UnexpectedUri(uri.path().to_string())), } } fn get_cached_data(&self, uri: &Uri, parts: &[&str]) -> Result<Vec<u8>> { // the path is: .../{shuffleid}/{inputid}/{reduceid} let parts: Vec<_> = match parts .iter() .map(|part| ShuffleService::parse_path_part(part)) .collect::<Result<_>>() { Err(_err) => { return Err(ShuffleError::UnexpectedUri(format!("{}", uri))); } Ok(parts) => parts, }; let params = &(parts[0], parts[1], parts[2]); if let Some(cached_data) = env::SHUFFLE_CACHE.get(params) { log::debug!( "got a request @ `{}`, params: {:?}, returning data", uri, params ); Ok(Vec::from(&cached_data[..])) } else { Err(ShuffleError::RequestedCacheNotFound) } } #[inline] fn parse_path_part(part: &str) -> Result<usize> { Ok(u64::from_str_radix(part, 10).map_err(|_| ShuffleError::NotValidRequest)? as usize) } } impl Service<Request<Body>> for ShuffleService { type Response = Response<Body>; type Error = ShuffleError; type Future = future::Ready<StdResult<Self::Response, Self::Error>>; fn poll_ready(&mut self, _cx: &mut Context) -> Poll<StdResult<(), Self::Error>> { Ok(()).into() } fn call(&mut self, req: Request<Body>) -> Self::Future { match self.response_type(req.uri()) { Ok(response) => match response { ShuffleResponse::Status(code) => { let body = Body::from(&[] as &[u8]); match Response::builder().status(code).body(body) { Ok(rsp) => future::ok(rsp), Err(_) => future::err(ShuffleError::InternalError), } } ShuffleResponse::CachedData(cached_data) => { let body = Body::from(Vec::from(&cached_data[..])); match Response::builder().status(200).body(body) { Ok(rsp) => future::ok(rsp), Err(_) => future::err(ShuffleError::InternalError), } } }, Err(err) => future::ok(err.into()), } } } struct ShuffleSvcMaker; impl<T> Service<T> for ShuffleSvcMaker { type Response = ShuffleService; type Error = ShuffleError; type Future = future::Ready<StdResult<Self::Response, Self::Error>>; fn poll_ready(&mut self, _cx: &mut Context) -> Poll<StdResult<(), Self::Error>> { Ok(()).into() } fn call(&mut self, _: T) -> Self::Future { future::ok(ShuffleService) } } #[cfg(test)] mod tests { use super::*; use std::net::TcpListener; use std::sync::Arc; fn client() -> Client<hyper::client::HttpConnector, Body> { Client::builder().http2_only(true).build_http::<Body>() } #[tokio::test] async fn start_ok() -> StdResult<(), Box<dyn std::error::Error + 'static>> { let port = get_free_port(); ShuffleManager::start_server(Some(port))?; let url = format!( "http://{}:{}/status", env::Configuration::get().local_ip, port ); let res = client().get(Uri::try_from(&url)?).await?; assert_eq!(res.status(), StatusCode::OK); Ok(()) } #[test] fn start_failure() -> StdResult<(), Box<dyn std::error::Error + 'static>> { let port = get_free_port(); // bind first so it fails while trying to start let _bind = TcpListener::bind(format!("127.0.0.1:{}", port))?; assert!(ShuffleManager::start_server(Some(port)) .unwrap_err() .no_port()); Ok(()) } #[test] fn status_checking_ok() -> StdResult<(), Box<dyn std::error::Error + 'static>> { let parallelism = num_cpus::get(); let manager = Arc::new(ShuffleManager::new()?); let mut threads = Vec::with_capacity(parallelism); for _ in 0..parallelism { let manager = manager.clone(); threads.push(thread::spawn(move || -> Result<()> { for _ in 0..10 { match manager.check_status() { Ok(StatusCode::OK) => {} _ => return Err(ShuffleError::AsyncRuntimeError), } } Ok(()) })); } let results = threads .into_iter() .filter_map(|res| res.join().ok()) .collect::<Result<Vec<_>>>()?; assert_eq!(results.len(), parallelism); Ok(()) } #[tokio::test] async fn cached_data_found() -> StdResult<(), Box<dyn std::error::Error + 'static>> { let port = get_free_port(); ShuffleManager::start_server(Some(port))?; let data = b"some random bytes".iter().copied().collect::<Vec<u8>>(); { env::SHUFFLE_CACHE.insert((2, 1, 0), data.clone()); } let url = format!( "http://{}:{}/shuffle/2/1/0", env::Configuration::get().local_ip, port ); let res = client().get(Uri::try_from(&url)?).await?; assert_eq!(res.status(), StatusCode::OK); let body = hyper::body::to_bytes(res.into_body()).await?; assert_eq!(body.to_vec(), data); Ok(()) } #[tokio::test] async fn cached_data_not_found() -> StdResult<(), Box<dyn std::error::Error + 'static>> { let port = get_free_port(); ShuffleManager::start_server(Some(port))?; let url = format!( "http://{}:{}/shuffle/0/1/2", env::Configuration::get().local_ip, port ); let res = client().get(Uri::try_from(&url)?).await?; assert_eq!(res.status(), StatusCode::NOT_FOUND); Ok(()) } #[tokio::test] async fn not_valid_endpoint() -> StdResult<(), Box<dyn std::error::Error + 'static>> { use std::iter::FromIterator; let port = get_free_port(); ShuffleManager::start_server(Some(port))?; let url = format!( "http://{}:{}/not_valid", env::Configuration::get().local_ip, port ); let res = client().get(Uri::try_from(&url)?).await?; assert_eq!(res.status(), StatusCode::BAD_REQUEST); let body = hyper::body::to_bytes(res.into_body()).await?; assert_eq!( String::from_iter(body.into_iter().map(|b| b as char)), "Failed to parse: /not_valid".to_string() ); Ok(()) } } <file_sep>pub(crate) mod random; #[cfg(test)] pub(crate) mod test_utils; use crate::error; use rand::Rng; use std::net::TcpListener; /// Shuffle the elements of a vec into a random order in place, modifying it. pub(crate) fn randomize_in_place<T, R>(iter: &mut Vec<T>, rand: &mut R) where R: Rng, { for i in (1..(iter.len() - 1)).rev() { let idx = rand.gen_range(0, i + 1); iter.swap(idx, i); } } /// Use this trick to block on the main `run_job` call to schedule the different /// tasks in parallel under the Tokio context. pub(crate) fn yield_tokio_futures() { futures::executor::block_on(async { tokio::task::yield_now().await; }); } pub(crate) fn get_free_port() -> Result<u16, error::NetworkError> { let mut port = 0; for _ in 0..100 { port = get_dynamic_port(); if TcpListener::bind(format!("127.0.0.1:{}", port)).is_ok() { return Ok(port); } } Err(error::NetworkError::FreePortNotFound(port, 100)) } fn get_dynamic_port() -> u16 { const FIRST_DYNAMIC_PORT: u16 = 49152; const LAST_DYNAMIC_PORT: u16 = 65535; FIRST_DYNAMIC_PORT + rand::thread_rng().gen_range(0, LAST_DYNAMIC_PORT - FIRST_DYNAMIC_PORT) } #[test] #[cfg(test)] fn test_randomize_in_place() { use rand::SeedableRng; let sample = vec![1_i64, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let mut randomized_samples = vec![]; for seed in 0..10 { let mut rng = rand_pcg::Pcg64::seed_from_u64(seed); let mut copied_sample = sample.clone(); randomize_in_place(&mut copied_sample, &mut rng); randomized_samples.push(copied_sample); } randomized_samples.push(sample); let equal: u8 = randomized_samples .iter() .enumerate() .map(|(i, v)| { let cmp1 = &randomized_samples[0..i]; let cmp2 = &randomized_samples[i + 1..]; if cmp1.iter().any(|x| x == v) || cmp2.iter().any(|x| x == v) { 1 } else { 0 } }) .sum(); assert!(equal == 0); } <file_sep>use std::any::Any; use std::clone::Clone; use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; use std::net::{Ipv4Addr, SocketAddrV4}; use std::option::Option; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use std::time::{Duration, Instant}; use crate::dag_scheduler::{CompletionEvent, TastEndReason}; use crate::dependency::ShuffleDependencyTrait; use crate::env; use crate::error::Result; use crate::job::{Job, JobTracker}; use crate::map_output_tracker::MapOutputTracker; use crate::rdd::{Rdd, RddBase}; use crate::result_task::ResultTask; use crate::scheduler::{EventQueue, NativeScheduler}; use crate::serializable_traits::{Data, SerFunc}; use crate::shuffle::ShuffleMapTask; use crate::stage::Stage; use crate::task::{TaskBase, TaskContext, TaskOption, TaskResult}; use crate::utils; use dashmap::DashMap; use parking_lot::Mutex; #[derive(Clone, Default)] pub struct LocalScheduler { max_failures: usize, attempt_id: Arc<AtomicUsize>, resubmit_timeout: u128, poll_timeout: u64, event_queues: EventQueue, pub(crate) next_job_id: Arc<AtomicUsize>, next_run_id: Arc<AtomicUsize>, next_task_id: Arc<AtomicUsize>, next_stage_id: Arc<AtomicUsize>, stage_cache: Arc<DashMap<usize, Stage>>, shuffle_to_map_stage: Arc<DashMap<usize, Stage>>, cache_locs: Arc<DashMap<usize, Vec<Vec<Ipv4Addr>>>>, master: bool, framework_name: String, is_registered: bool, //TODO check if it is necessary active_jobs: HashMap<usize, Job>, active_job_queue: Vec<Job>, taskid_to_jobid: HashMap<String, usize>, taskid_to_slaveid: HashMap<String, String>, job_tasks: HashMap<usize, HashSet<String>>, slaves_with_executors: HashSet<String>, map_output_tracker: MapOutputTracker, // TODO fix proper locking mechanism scheduler_lock: Arc<Mutex<bool>>, } impl LocalScheduler { pub fn new(max_failures: usize, master: bool) -> Self { LocalScheduler { max_failures, attempt_id: Arc::new(AtomicUsize::new(0)), resubmit_timeout: 2000, poll_timeout: 50, event_queues: Arc::new(DashMap::new()), next_job_id: Arc::new(AtomicUsize::new(0)), next_run_id: Arc::new(AtomicUsize::new(0)), next_task_id: Arc::new(AtomicUsize::new(0)), next_stage_id: Arc::new(AtomicUsize::new(0)), stage_cache: Arc::new(DashMap::new()), shuffle_to_map_stage: Arc::new(DashMap::new()), cache_locs: Arc::new(DashMap::new()), master, framework_name: "spark".to_string(), is_registered: true, //TODO check if it is necessary active_jobs: HashMap::new(), active_job_queue: Vec::new(), taskid_to_jobid: HashMap::new(), taskid_to_slaveid: HashMap::new(), job_tasks: HashMap::new(), slaves_with_executors: HashSet::new(), map_output_tracker: env::Env::get().map_output_tracker.clone(), scheduler_lock: Arc::new(Mutex::new(true)), } } pub fn run_job<T: Data, U: Data, F>( self: Arc<Self>, func: Arc<F>, final_rdd: Arc<dyn Rdd<Item = T>>, partitions: Vec<usize>, allow_local: bool, ) -> Result<Vec<U>> where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { // acquiring lock so that only one job can run at same time this lock is just // a temporary patch for preventing multiple jobs to update cache locks which affects // construction of dag task graph. dag task graph construction needs to be altered let _lock = self.scheduler_lock.lock(); let jt = JobTracker::from_scheduler(&*self, func, final_rdd.clone(), partitions); //TODO update cache if allow_local { if let Some(result) = LocalScheduler::local_execution(jt.clone())? { return Ok(result); } } self.event_queues.insert(jt.run_id, VecDeque::new()); let self_clone = Arc::clone(&self); let jt_clone = jt.clone(); // run in async executor let executor = env::Env::get_async_handle(); let results = executor.enter(move || { let self_borrow = &*self_clone; let jt = jt_clone; let mut results: Vec<Option<U>> = (0..jt.num_output_parts).map(|_| None).collect(); let mut fetch_failure_duration = Duration::new(0, 0); self_borrow.submit_stage(jt.final_stage.clone(), jt.clone()); utils::yield_tokio_futures(); log::debug!( "pending stages and tasks: {:?}", jt.pending_tasks .lock() .iter() .map(|(k, v)| (k.id, v.iter().map(|x| x.get_task_id()).collect::<Vec<_>>())) .collect::<Vec<_>>() ); let mut num_finished = 0; while num_finished != jt.num_output_parts { let event_option = self_borrow.wait_for_event(jt.run_id, self_borrow.poll_timeout); let start = Instant::now(); if let Some(evt) = event_option { log::debug!("event starting"); let stage = self_borrow .stage_cache .get(&evt.task.get_stage_id()) .unwrap() .clone(); log::debug!( "removing stage #{} task from pending task #{}", stage.id, evt.task.get_task_id() ); jt.pending_tasks .lock() .get_mut(&stage) .unwrap() .remove(&evt.task); use super::dag_scheduler::TastEndReason::*; match evt.reason { Success => self_borrow.on_event_success( evt, &mut results, &mut num_finished, jt.clone(), ), FetchFailed(failed_vals) => { self_borrow.on_event_failure( jt.clone(), failed_vals, evt.task.get_stage_id(), ); fetch_failure_duration = start.elapsed(); } Error(error) => panic!("{}", error), OtherFailure(msg) => panic!("{}", msg), } } } if !jt.failed.lock().is_empty() && fetch_failure_duration.as_millis() > self_borrow.resubmit_timeout { self_borrow.update_cache_locs(); for stage in jt.failed.lock().iter() { self_borrow.submit_stage(stage.clone(), jt.clone()); } utils::yield_tokio_futures(); jt.failed.lock().clear(); } results }); self.event_queues.remove(&jt.run_id); Ok(results .into_iter() .map(|s| match s { Some(v) => v, None => panic!("some results still missing"), }) .collect()) } fn run_task<T: Data, U: Data, F>( event_queues: Arc<DashMap<usize, VecDeque<CompletionEvent>>>, task: Vec<u8>, _id_in_job: usize, attempt_id: usize, ) where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { let des_task: TaskOption = bincode::deserialize(&task).unwrap(); let result = des_task.run(attempt_id); match des_task { TaskOption::ResultTask(tsk) => { let result = match result { TaskResult::ResultTask(r) => r, _ => panic!("wrong result type"), }; if let Ok(task_final) = tsk.downcast::<ResultTask<T, U, F>>() { let task_final = task_final as Box<dyn TaskBase>; LocalScheduler::task_ended( event_queues, task_final, TastEndReason::Success, result.into_any_send_sync(), ); } } TaskOption::ShuffleMapTask(tsk) => { let result = match result { TaskResult::ShuffleTask(r) => r, _ => panic!("wrong result type"), }; if let Ok(task_final) = tsk.downcast::<ShuffleMapTask>() { let task_final = task_final as Box<dyn TaskBase>; LocalScheduler::task_ended( event_queues, task_final, TastEndReason::Success, result.into_any_send_sync(), ); } } }; } fn task_ended( event_queues: Arc<DashMap<usize, VecDeque<CompletionEvent>>>, task: Box<dyn TaskBase>, reason: TastEndReason, result: Box<dyn Any + Send + Sync>, //TODO accumvalues needs to be done ) { let result = Some(result); if let Some(mut queue) = event_queues.get_mut(&(task.get_run_id())) { queue.push_back(CompletionEvent { task, reason, result, accum_updates: HashMap::new(), }); } else { log::debug!("ignoring completion event for DAG Job"); } } } impl NativeScheduler for LocalScheduler { /// Every single task is run in the local thread pool fn submit_task<T: Data, U: Data, F>( &self, task: TaskOption, id_in_job: usize, _server_address: SocketAddrV4, ) where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { log::debug!("inside submit task"); let my_attempt_id = self.attempt_id.fetch_add(1, Ordering::SeqCst); let event_queues = self.event_queues.clone(); let task = bincode::serialize(&task).unwrap(); tokio::task::spawn_blocking(move || { LocalScheduler::run_task::<T, U, F>(event_queues, task, id_in_job, my_attempt_id) }); } fn next_executor_server(&self, _rdd: &dyn TaskBase) -> SocketAddrV4 { // Just point to the localhost SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0) } impl_common_scheduler_funcs!(); } <file_sep>use crate::dependency::ShuffleDependencyTrait; use crate::rdd::RddBase; use std::cmp::Ordering; use std::fmt::Display; use std::sync::Arc; // this is strange. see into this in more detail //#[derive(Derivative)] //#[derivative(PartialEq)] //#[derive(Clone, Ord, PartialOrd, Eq)] #[derive(Clone)] pub struct Stage { pub id: usize, pub num_partitions: usize, pub shuffle_dependency: Option<Arc<dyn ShuffleDependencyTrait>>, pub is_shuffle_map: bool, pub rdd: Arc<dyn RddBase>, pub parents: Vec<Stage>, pub output_locs: Vec<Vec<String>>, pub num_available_outputs: usize, } impl PartialOrd for Stage { fn partial_cmp(&self, other: &Stage) -> Option<Ordering> { Some(self.id.cmp(&other.id)) } } impl PartialEq for Stage { fn eq(&self, other: &Stage) -> bool { self.id == other.id } } impl Eq for Stage {} impl Ord for Stage { fn cmp(&self, other: &Stage) -> Ordering { self.id.cmp(&other.id) } } impl Display for Stage { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Stage {}", self.id) } } impl Stage { pub fn get_rdd(&self) -> Arc<dyn RddBase> { self.rdd.clone() } pub fn new( id: usize, rdd: Arc<dyn RddBase>, shuffle_dependency: Option<Arc<dyn ShuffleDependencyTrait>>, parents: Vec<Stage>, ) -> Self { Stage { id, num_partitions: rdd.number_of_splits(), is_shuffle_map: shuffle_dependency.clone().is_some(), shuffle_dependency, parents, rdd: rdd.clone(), output_locs: { let mut v = Vec::new(); for _ in 0..rdd.number_of_splits() { v.push(Vec::new()); } v }, num_available_outputs: 0, } } pub fn is_available(&self) -> bool { if self.parents.is_empty() && !self.is_shuffle_map { true } else { log::debug!( "num available outputs {}, and num partitions {}, in is available method in stage", self.num_available_outputs, self.num_partitions ); self.num_available_outputs == self.num_partitions } } pub fn add_output_loc(&mut self, partition: usize, host: String) { log::debug!( "adding loc for partition inside stage {} @{}", partition, host ); if !self.output_locs[partition].is_empty() { self.num_available_outputs += 1; } self.output_locs[partition].push(host); } pub fn remove_output_loc(&mut self, partition: usize, host: &str) { let prev_vec = self.output_locs[partition].clone(); let new_vec = prev_vec .clone() .into_iter() .filter(|x| x != host) .collect::<Vec<_>>(); if (!prev_vec.is_empty()) && (new_vec.is_empty()) { self.num_available_outputs -= 1; } self.output_locs[partition] = new_vec; } } <file_sep>## SPDX-License-Identifier: Apache-2.0 # Stage 0 ## Set up and compilation stage FROM ubuntu:18.04 AS building ENV tempPkgs='\ build-essential \ pkg-config \ libssl-dev \ ca-certificates \ curl \ file \ capnproto \ ' ENV PATH="/root/.cargo/bin:$PATH" ARG RUST_VERSION RUN set -e; \ apt-get update -yq; \ apt-get install -yq --no-install-recommends $tempPkgs; # Install and set up rustup RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain $RUST_VERSION --no-modify-path; WORKDIR /home COPY . native_spark RUN set -e; cd native_spark; \ echo "PATH: ${PATH}"; \ # Build executables cargo build --release --examples; \ cp config_files/hosts.conf /root/; \ mkdir /home/release; \ # Copy all examples binaries find ./target/release/examples -exec file {} \; \ | grep "shared object" \ | cut -d: -f1 \ | grep -v .*- \ | xargs -I{} cp "{}" /home/release # Stage 1 ## Self-contained build with only necessary utils and binaries FROM ubuntu:18.04 WORKDIR /home/release RUN set -e; \ # Install requirements apt-get update -yq; \ apt-get install --no-install-recommends -yq \ locales iputils-ping capnproto openssh-server libssl-dev; \ # Locales locale-gen en_US.UTF-8; \ # Set SSH user groupadd ns && useradd -ms /bin/bash -g ns ns_user; \ # Cleanup #apt-get purge -y --auto-remove $tempPkgs; \ apt-get autoremove -q -y; \ apt-get clean -yq; \ rm -rf /var/lib/apt/lists/* COPY --from=building /home/release . COPY --chown=ns_user:ns ./docker/id_rsa.pub /home/ns_user/.ssh/authorized_keys COPY ./docker/id_rsa /root/.ssh/ RUN chmod 600 /root/.ssh/id_rsa /home/ns_user/.ssh/authorized_keys ENV LANG=en_US.UTF-8 \ LANGUAGE=en_US:en \ LC_ALL=en_US.UTF-8 <file_sep>use std::sync::Arc; use crate::result_task::ResultTask; use crate::serializable_traits::SerFunc; use crate::task::TaskContext; use crate::*; pub(crate) fn create_test_task<F>(func: F) -> ResultTask<u8, u8, F> where F: SerFunc((TaskContext, Box<dyn Iterator<Item = u8>>)) -> u8, { let ctxt = Context::with_mode(DeploymentMode::Local).unwrap(); let rdd_f = Fn!(move |data: u8| -> u8 { data }); let rdd = ctxt.parallelize(vec![0, 1, 2], 1).map(rdd_f); ResultTask::new(2, 0, 0, rdd.into(), Arc::new(func), 0, vec![], 0) } <file_sep>use std::net::SocketAddr; use std::path::Path; use crate::error::{Error, Result}; use once_cell::sync::OnceCell; use serde_derive::Deserialize; static HOSTS: OnceCell<Hosts> = OnceCell::new(); /// Handles loading of the hosts configuration. #[derive(Debug, Deserialize)] pub struct Hosts { pub master: SocketAddr, /// The slaves have the format "user@address", e.g. "worker@192.168.0.2" pub slaves: Vec<String>, } impl Hosts { pub fn get() -> Result<&'static Hosts> { HOSTS.get_or_try_init(Self::load) } fn load() -> Result<Self> { let home = std::env::home_dir().ok_or(Error::NoHome)?; Hosts::load_from(home.join("hosts.conf")) } fn load_from<P: AsRef<Path>>(path: P) -> Result<Self> { let s = std::fs::read_to_string(&path).map_err(|e| Error::LoadHosts { source: e, path: path.as_ref().into(), })?; toml::from_str(&s).map_err(|e| Error::ParseHosts { source: e, path: path.as_ref().into(), }) } } #[cfg(test)] mod tests { use super::*; use std::io::Write; #[test] fn test_missing_hosts_file() { match Hosts::load_from("/does_not_exist").unwrap_err() { Error::LoadHosts { .. } => {} _ => panic!("Expected Error::LoadHosts"), } } #[test] fn test_invalid_hosts_file() { let (mut file, path) = tempfile::NamedTempFile::new().unwrap().keep().unwrap(); file.write_all("invalid data".as_ref()).unwrap(); match Hosts::load_from(&path).unwrap_err() { Error::ParseHosts { .. } => {} _ => panic!("Expected Error::ParseHosts"), } } } <file_sep>use std::fs; use std::io::{BufReader, Read}; use std::marker::PhantomData; use std::net::{Ipv4Addr, SocketAddrV4}; use std::path::{Path, PathBuf}; use std::sync::Arc; use crate::context::Context; use crate::dependency::Dependency; use crate::error::{Error, Result}; use crate::io::ReaderConfiguration; use crate::rdd::{MapPartitionsRdd, MapperRdd, Rdd, RddBase}; use crate::serializable_traits::{AnyData, Data, SerFunc}; use crate::split::Split; use log::debug; use rand::prelude::*; use serde_derive::{Deserialize, Serialize}; use serde_traitobject::Arc as SerArc; pub struct LocalFsReaderConfig { filter_ext: Option<std::ffi::OsString>, expect_dir: bool, dir_path: PathBuf, executor_partitions: Option<u64>, } impl LocalFsReaderConfig { /// Read all the files from a directory or a path. pub fn new<T: Into<PathBuf>>(path: T) -> LocalFsReaderConfig { LocalFsReaderConfig { filter_ext: None, expect_dir: true, dir_path: path.into(), executor_partitions: None, } } /// Only will read files with a given extension. pub fn filter_extension<T: Into<String>>(&mut self, extension: T) { self.filter_ext = Some(extension.into().into()); } /// Default behaviour is to expect the directory to exist in every node, /// if it doesn't the executor will panic. pub fn expect_directory(mut self, should_exist: bool) -> Self { self.expect_dir = should_exist; self } /// Number of partitions to use per executor to perform the load tasks. /// One executor must be used per host with as many partitions as CPUs available (ideally). pub fn num_partitions_per_executor(mut self, num: u64) -> Self { self.executor_partitions = Some(num); self } } impl ReaderConfiguration<Vec<u8>> for LocalFsReaderConfig { fn make_reader<F, U>(self, context: Arc<Context>, decoder: F) -> SerArc<dyn Rdd<Item = U>> where F: SerFunc(Vec<u8>) -> U, U: Data, { let reader = LocalFsReader::<BytesReader>::new(self, context); let read_files = Fn!( |part: usize, readers: Box<dyn Iterator<Item = BytesReader>>| { Box::new(readers.into_iter().map(|file| file.into_iter()).flatten()) as Box<dyn Iterator<Item = _>> } ); let files_per_executor = Arc::new( MapPartitionsRdd::new(Arc::new(reader) as Arc<dyn Rdd<Item = _>>, read_files).pin(), ); SerArc::new(MapperRdd::new(files_per_executor, decoder).pin()) } } impl ReaderConfiguration<PathBuf> for LocalFsReaderConfig { fn make_reader<F, U>(self, context: Arc<Context>, decoder: F) -> SerArc<dyn Rdd<Item = U>> where F: SerFunc(PathBuf) -> U, U: Data, { let reader = LocalFsReader::<FileReader>::new(self, context); let read_files = Fn!( |part: usize, readers: Box<dyn Iterator<Item = FileReader>>| { Box::new(readers.map(|reader| reader.into_iter()).flatten()) as Box<dyn Iterator<Item = _>> } ); let files_per_executor = Arc::new( MapPartitionsRdd::new(Arc::new(reader) as Arc<dyn Rdd<Item = _>>, read_files).pin(), ); SerArc::new(MapperRdd::new(files_per_executor, decoder).pin()) } } /// Reads all files specified in a given directory from the local directory /// on all executors on every worker node. #[derive(Clone, Serialize, Deserialize)] pub struct LocalFsReader<T> { id: usize, path: PathBuf, is_single_file: bool, filter_ext: Option<std::ffi::OsString>, expect_dir: bool, executor_partitions: Option<u64>, #[serde(skip_serializing, skip_deserializing)] context: Arc<Context>, // explicitly copy the address map as the map under context is not // deserialized in tasks and this is required: splits: Vec<SocketAddrV4>, _marker_reader_data: PhantomData<T>, } impl<T: Data> LocalFsReader<T> { fn new(config: LocalFsReaderConfig, context: Arc<Context>) -> Self { let LocalFsReaderConfig { dir_path, expect_dir, filter_ext, executor_partitions, } = config; let is_single_file = { let path: &Path = dir_path.as_ref(); path.is_file() }; LocalFsReader { id: context.new_rdd_id(), path: dir_path, is_single_file, filter_ext, expect_dir, executor_partitions, splits: context.address_map.clone(), context, _marker_reader_data: PhantomData, } } /// This function should be called once per host to come with the paralel workload. /// Is safe to recompute on failure though. fn load_local_files(&self) -> Result<Vec<Vec<PathBuf>>> { let mut total_size = 0_u64; if self.is_single_file { let files = vec![vec![self.path.clone()]]; return Ok(files); } let mut num_partitions = self.get_executor_partitions(); let mut files: Vec<(u64, PathBuf)> = vec![]; // We compute std deviation incrementally to estimate a good breakpoint // of size per partition. let mut total_files = 0_u64; let mut k = 0; let mut ex = 0.0; let mut ex2 = 0.0; for (i, entry) in fs::read_dir(&self.path) .map_err(Error::InputRead)? .enumerate() { let path = entry.map_err(Error::InputRead)?.path(); if path.is_file() { let is_proper_file = { self.filter_ext.is_none() || path.extension() == self.filter_ext.as_ref().map(|s| s.as_ref()) }; if !is_proper_file { continue; } let size = fs::metadata(&path).map_err(Error::InputRead)?.len(); if i == 0 { // assign first file size as reference sample k = size; } // compute the necessary statistics ex += (size - k) as f32; ex2 += (size - k) as f32 * (size - k) as f32; total_size += size; total_files += 1; files.push((size, path)); } } let file_size_mean = (total_size / total_files) as u64; let std_dev = ((ex2 - (ex * ex) / total_files as f32) / total_files as f32).sqrt(); if total_files < num_partitions { // Coerce the number of partitions to the number of files num_partitions = total_files; } let avg_partition_size = (total_size / num_partitions) as u64; let partitions = self.assign_files_to_partitions( num_partitions, files, file_size_mean, avg_partition_size, std_dev, ); Ok(partitions) } /// Assign files according to total avg partition size and file size. /// This should return a fairly balanced total partition size. fn assign_files_to_partitions( &self, num_partitions: u64, files: Vec<(u64, PathBuf)>, file_size_mean: u64, avg_partition_size: u64, std_dev: f32, ) -> Vec<Vec<PathBuf>> { // Accept ~ 0.25 std deviations top from the average partition size // when assigning a file to a partition. let high_part_size_bound = (avg_partition_size + (std_dev * 0.25) as u64) as u64; debug!( "the average part size is {} with a high bound of {}", avg_partition_size, high_part_size_bound ); debug!( "assigning files from local fs to partitions, file size mean: {}; std_dev: {}", file_size_mean, std_dev ); let mut partitions = Vec::with_capacity(num_partitions as usize); let mut partition = Vec::with_capacity(0); let mut curr_part_size = 0_u64; let mut rng = rand::thread_rng(); for (size, file) in files.into_iter() { if partitions.len() as u64 == num_partitions - 1 { partition.push(file); continue; } let new_part_size = curr_part_size + size; let larger_than_mean = rng.gen::<bool>(); if (larger_than_mean && new_part_size < high_part_size_bound) || (!larger_than_mean && new_part_size <= avg_partition_size) { partition.push(file); curr_part_size = new_part_size; } else if size > avg_partition_size as u64 { if !partition.is_empty() { partitions.push(partition); } partitions.push(vec![file]); partition = vec![]; curr_part_size = 0; } else { if !partition.is_empty() { partitions.push(partition); } partition = vec![file]; curr_part_size = size; } } if !partition.is_empty() { partitions.push(partition); } let mut current_pos = partitions.len() - 1; while (partitions.len() as u64) < num_partitions { // If the number of specified partitions is relativelly equal to the number of files // or the file size of the last files is low skew can happen and there can be fewer // partitions than specified. This the number of partitions is actually the specified. if partitions.get(current_pos).unwrap().len() > 1 { // Only get elements from part as long as it has more than one element let last_part = partitions.get_mut(current_pos).unwrap().pop().unwrap(); partitions.push(vec![last_part]) } else if current_pos > 0 { current_pos -= 1; } else { break; } } partitions } fn get_executor_partitions(&self) -> u64 { if let Some(num) = self.executor_partitions { num } else { num_cpus::get() as u64 } } } macro_rules! impl_common_lfs_rddb_funcs { () => { fn get_rdd_id(&self) -> usize { self.id } fn get_context(&self) -> Arc<Context> { self.context.clone() } fn get_dependencies(&self) -> Vec<Dependency> { vec![] } fn is_pinned(&self) -> bool { true } default fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { Ok(Box::new( self.iterator(split)? .map(|x| Box::new(x) as Box<dyn AnyData>), )) } }; } impl RddBase for LocalFsReader<BytesReader> { impl_common_lfs_rddb_funcs!(); fn preferred_locations(&self, split: Box<dyn Split>) -> Vec<Ipv4Addr> { // for a given split there is only one preferred location because this is pinned, // the preferred location is the host at which this split will be executed; let split = split.downcast_ref::<BytesReader>().unwrap(); vec![split.host] } fn splits(&self) -> Vec<Box<dyn Split>> { let mut splits = Vec::with_capacity(self.splits.len()); for (idx, host) in self.splits.iter().enumerate() { splits.push(Box::new(BytesReader { idx, host: *host.ip(), files: Vec::new(), }) as Box<dyn Split>) } splits } } impl RddBase for LocalFsReader<FileReader> { impl_common_lfs_rddb_funcs!(); fn preferred_locations(&self, split: Box<dyn Split>) -> Vec<Ipv4Addr> { let split = split.downcast_ref::<FileReader>().unwrap(); vec![split.host] } fn splits(&self) -> Vec<Box<dyn Split>> { let mut splits = Vec::with_capacity(self.splits.len()); for (idx, host) in self.splits.iter().enumerate() { splits.push(Box::new(FileReader { idx, host: *host.ip(), files: Vec::new(), }) as Box<dyn Split>) } splits } } macro_rules! impl_common_lfs_rdd_funcs { () => { fn get_rdd(&self) -> Arc<dyn Rdd<Item = Self::Item>> where Self: Sized, { Arc::new(self.clone()) as Arc<dyn Rdd<Item = Self::Item>> } fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(self.clone()) as Arc<dyn RddBase> } }; } impl Rdd for LocalFsReader<BytesReader> { type Item = BytesReader; impl_common_lfs_rdd_funcs!(); fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { let split = split.downcast_ref::<BytesReader>().unwrap(); let files_by_part = self.load_local_files()?; let idx = split.idx; let host = split.host; Ok(Box::new( files_by_part .into_iter() .map(move |files| BytesReader { files, host, idx }), ) as Box<dyn Iterator<Item = Self::Item>>) } } impl Rdd for LocalFsReader<FileReader> { type Item = FileReader; impl_common_lfs_rdd_funcs!(); fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { let split = split.downcast_ref::<FileReader>().unwrap(); let files_by_part = self.load_local_files()?; let idx = split.idx; let host = split.host; Ok(Box::new( files_by_part .into_iter() .map(move |files| FileReader { files, host, idx }), ) as Box<dyn Iterator<Item = Self::Item>>) } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct BytesReader { files: Vec<PathBuf>, idx: usize, host: Ipv4Addr, } impl Split for BytesReader { fn get_index(&self) -> usize { self.idx } } impl Iterator for BytesReader { type Item = Vec<u8>; fn next(&mut self) -> Option<Self::Item> { if let Some(path) = self.files.pop() { let file = fs::File::open(path).unwrap(); let mut content = vec![]; let mut reader = BufReader::new(file); reader.read_to_end(&mut content).unwrap(); Some(content) } else { None } } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FileReader { files: Vec<PathBuf>, idx: usize, host: Ipv4Addr, } impl Split for FileReader { fn get_index(&self) -> usize { self.idx } } impl Iterator for FileReader { type Item = PathBuf; fn next(&mut self) -> Option<Self::Item> { self.files.pop() } } #[cfg(test)] mod tests { use super::*; #[test] fn load_files() { let context = Context::new().unwrap(); let mut loader: LocalFsReader<Vec<u8>> = LocalFsReader { id: 0, path: "A".into(), is_single_file: false, filter_ext: None, expect_dir: true, executor_partitions: Some(4), context, splits: Vec::new(), _marker_reader_data: PhantomData, }; // Skewed file sizes let files = vec![ (500u64, "A".into()), (2000, "B".into()), (3900, "C".into()), (2000, "D".into()), (1000, "E".into()), (1500, "F".into()), (500, "G".into()), ]; let file_size_mean = 1628; let avg_partition_size = 2850; let std_dev = 1182f32; let files = loader.assign_files_to_partitions( 4, files, file_size_mean, avg_partition_size, std_dev, ); assert_eq!(files.len(), 4); // Even size and less files than parts loader.executor_partitions = Some(8); let files = vec![ (500u64, "A".into()), (500, "B".into()), (500, "C".into()), (500, "D".into()), ]; let file_size_mean = 500; let avg_partition_size = 250; let files = loader.assign_files_to_partitions(8, files, file_size_mean, avg_partition_size, 0.0); assert_eq!(files.len(), 4); // Even size and more files than parts loader.executor_partitions = Some(2); let files = vec![ (500u64, "A".into()), (500, "B".into()), (500, "C".into()), (500, "D".into()), (500, "E".into()), (500, "F".into()), (500, "G".into()), (500, "H".into()), ]; let file_size_mean = 500; let avg_partition_size = 2000; let files = loader.assign_files_to_partitions(2, files, file_size_mean, avg_partition_size, 0.0); assert_eq!(files.len(), 2); assert!(files[0].len() >= 3 && files[0].len() <= 5); } } <file_sep># Summary - [Introduction](./chapter_1.md) <file_sep>use std::fs; use std::net::Ipv4Addr; use std::path::PathBuf; use std::sync::Arc; use crate::cache::BoundedMemoryCache; use crate::cache_tracker::CacheTracker; use crate::error::Error; use crate::hosts::Hosts; use crate::map_output_tracker::MapOutputTracker; use crate::shuffle::{ShuffleFetcher, ShuffleManager}; use dashmap::DashMap; use log::LevelFilter; use once_cell::sync::{Lazy, OnceCell}; use serde::{Deserialize, Serialize}; use tokio::runtime::{Handle, Runtime}; type ShuffleCache = Arc<DashMap<(usize, usize, usize), Vec<u8>>>; const ENV_VAR_PREFIX: &str = "NS_"; pub(crate) const THREAD_PREFIX: &str = "_NS"; static CONF: OnceCell<Configuration> = OnceCell::new(); static ENV: OnceCell<Env> = OnceCell::new(); static ASYNC_HANDLE: Lazy<Handle> = Lazy::new(Handle::current); pub(crate) static SHUFFLE_CACHE: Lazy<ShuffleCache> = Lazy::new(|| Arc::new(DashMap::new())); pub(crate) static BOUNDED_MEM_CACHE: Lazy<BoundedMemoryCache> = Lazy::new(BoundedMemoryCache::new); pub(crate) struct Env { pub map_output_tracker: MapOutputTracker, pub shuffle_manager: ShuffleManager, pub shuffle_fetcher: ShuffleFetcher, pub cache_tracker: CacheTracker, async_rt: Option<Runtime>, } impl Env { pub fn get() -> &'static Env { ENV.get_or_init(Self::new) } /// Get a handle to the current running async executor to spawn tasks. pub fn get_async_handle() -> &'static Handle { if let Some(executor) = &ENV.get_or_init(Self::new).async_rt { executor.handle() } else { &ASYNC_HANDLE } } /// Builds an async executor for executing DAG tasks according to env, /// machine properties and schedulling mode. fn build_async_executor() -> Option<Runtime> { if Handle::try_current().is_ok() { None } else { Some( tokio::runtime::Builder::new() .enable_all() .threaded_scheduler() .build() .unwrap(), ) } } fn new() -> Self { let conf = Configuration::get(); let master_addr = Hosts::get().unwrap().master; Env { map_output_tracker: MapOutputTracker::new(conf.is_driver, master_addr), shuffle_manager: ShuffleManager::new().unwrap(), shuffle_fetcher: ShuffleFetcher, cache_tracker: CacheTracker::new( conf.is_driver, master_addr, conf.local_ip, &BOUNDED_MEM_CACHE, ), async_rt: Env::build_async_executor(), } } } #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] #[serde(rename_all = "lowercase")] pub(crate) enum LogLevel { Error, Warn, Debug, Trace, Info, } impl LogLevel { pub fn is_debug_or_lower(self) -> bool { use LogLevel::*; match self { Debug | Trace => true, _ => false, } } } impl Into<LevelFilter> for LogLevel { fn into(self) -> LevelFilter { match self { LogLevel::Error => LevelFilter::Error, LogLevel::Warn => LevelFilter::Warn, LogLevel::Debug => LevelFilter::Debug, LogLevel::Trace => LevelFilter::Trace, _ => LevelFilter::Info, } } } /// Struct used for parsing environment vars #[derive(Deserialize, Debug)] struct EnvConfig { deployment_mode: Option<DeploymentMode>, local_ip: Option<String>, local_dir: Option<String>, log_level: Option<LogLevel>, log_cleanup: Option<bool>, shuffle_service_port: Option<u16>, slave_deployment: Option<bool>, slave_port: Option<u16>, } #[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum DeploymentMode { Distributed, Local, } impl DeploymentMode { pub fn is_local(self) -> bool { if let DeploymentMode::Local = self { true } else { false } } } #[derive(Serialize, Deserialize, Clone)] pub(crate) struct Configuration { pub is_driver: bool, pub local_ip: Ipv4Addr, pub local_dir: PathBuf, pub deployment_mode: DeploymentMode, pub shuffle_svc_port: Option<u16>, pub slave: Option<SlaveConfig>, pub loggin: LogConfig, } #[derive(Serialize, Deserialize, Clone)] pub(crate) struct SlaveConfig { pub deployment: bool, pub port: u16, } #[derive(Serialize, Deserialize, Clone)] pub(crate) struct LogConfig { pub log_level: LogLevel, pub log_cleanup: bool, } impl From<(bool, u16)> for SlaveConfig { fn from(config: (bool, u16)) -> Self { let (deployment, port) = config; SlaveConfig { deployment, port } } } impl Default for Configuration { fn default() -> Self { use DeploymentMode::*; // this may be a worker, try to get conf dynamically from file: if let Some(config) = Configuration::get_from_file() { return config; } // get config from env vars: let config = envy::prefixed(ENV_VAR_PREFIX) .from_env::<EnvConfig>() .unwrap(); let deployment_mode = match config.deployment_mode { Some(Distributed) => Distributed, _ => Local, }; let local_dir = if let Some(dir) = config.local_dir { PathBuf::from(dir) } else { std::env::temp_dir() }; // loggin config: let log_level = match config.log_level { Some(val) => val, _ => LogLevel::Info, }; let log_cleanup = match config.log_cleanup { Some(cond) => cond, _ => !cfg!(debug_assertions), }; log::debug!("Setting max log level to: {:?}", log_level); log::set_max_level(log_level.into()); let local_ip: Ipv4Addr = { if let Some(ip) = config.local_ip { ip.parse().unwrap() } else if deployment_mode == Distributed { panic!("Local IP required while deploying in distributed mode.") } else { Ipv4Addr::LOCALHOST } }; // master/slave config: let is_master; let slave: Option<SlaveConfig>; match config.slave_deployment { Some(true) => { if let Some(port) = config.slave_port { is_master = false; slave = Some(SlaveConfig { deployment: true, port, }); } else { panic!("Port required while deploying a worker.") } } _ => { is_master = true; slave = None; } } Configuration { is_driver: is_master, local_ip, local_dir, deployment_mode, loggin: LogConfig { log_level, log_cleanup, }, shuffle_svc_port: config.shuffle_service_port, slave, } } } impl Configuration { pub fn get() -> &'static Configuration { CONF.get_or_init(Self::default) } fn get_from_file() -> Option<Configuration> { let binary_path = std::env::current_exe() .map_err(|_| Error::CurrentBinaryPath) .unwrap(); if let Some(dir) = binary_path.parent() { let conf_file = dir.join("config.toml"); if conf_file.exists() { return fs::read_to_string(conf_file) .map(|content| toml::from_str::<Configuration>(&content).ok()) .ok() .flatten(); } } None } } <file_sep>use std::collections::HashMap; use std::convert::TryFrom; use std::sync::{atomic, atomic::AtomicBool, Arc}; use crate::env; use crate::serializable_traits::Data; use crate::shuffle::*; use futures::future; use hyper::{client::Client, Uri}; use tokio::sync::Mutex; /// Parallel shuffle fetcher. pub(crate) struct ShuffleFetcher; impl ShuffleFetcher { pub async fn fetch<K: Data, V: Data>( shuffle_id: usize, reduce_id: usize, mut func: impl FnMut((K, V)) -> (), ) -> Result<()> { log::debug!("inside fetch function"); let mut inputs_by_uri = HashMap::new(); let server_uris = env::Env::get() .map_output_tracker .get_server_uris(shuffle_id); log::debug!( "server uris for shuffle id {:?} - {:?}", shuffle_id, server_uris ); for (index, server_uri) in server_uris.into_iter().enumerate() { inputs_by_uri .entry(server_uri) .or_insert_with(Vec::new) .push(index); } let mut server_queue = Vec::new(); let mut total_results = 0; for (key, value) in inputs_by_uri { total_results += value.len(); server_queue.push((key, value)); } log::debug!( "servers for shuffle id {:?}, reduce id {:?} - {:?}", shuffle_id, reduce_id, server_queue ); let num_tasks = server_queue.len(); let server_queue = Arc::new(Mutex::new(server_queue)); let failure = Arc::new(AtomicBool::new(false)); let mut tasks = Vec::with_capacity(num_tasks); for _ in 0..num_tasks { let server_queue = server_queue.clone(); let failure = failure.clone(); // spawn a future for each expected result set let task = async move { let client = Client::builder().http2_only(true).build_http::<Body>(); let mut lock = server_queue.lock().await; if let Some((server_uri, input_ids)) = lock.pop() { let server_uri = format!("{}/shuffle/{}", server_uri, shuffle_id); let mut chunk_uri_str = String::with_capacity(server_uri.len() + 12); chunk_uri_str.push_str(&server_uri); let mut shuffle_chunks = Vec::with_capacity(input_ids.len()); for input_id in input_ids { if failure.load(atomic::Ordering::Acquire) { // Abort early since the work failed in an other future return Err(ShuffleError::AsyncRuntimeError); } log::debug!("inside parallel fetch {}", input_id); let chunk_uri = ShuffleFetcher::make_chunk_uri( &server_uri, &mut chunk_uri_str, input_id, reduce_id, )?; let data = { let res = client.get(chunk_uri).await?; hyper::body::to_bytes(res.into_body()).await }; if let Ok(data) = data { shuffle_chunks.push(data.to_vec()); } else { failure.store(true, atomic::Ordering::Release); return Err(ShuffleError::FailedFetchOp); } } Ok(shuffle_chunks) } else { Ok(Vec::new()) } }; // spawning is required so tasks are run in parallel in the tokio tp tasks.push(tokio::spawn(task)); } let task_results = future::join_all(tasks.into_iter()).await; log::debug!("total_results {}", total_results); // TODO: make this pure; instead of modifying the compute results inside the passing closure // return the deserialized values iterator to the caller task_results .into_iter() .map(|join_res| { if let Ok(results) = join_res { for res_set in &results { res_set .iter() .map(|bytes| { let set = bincode::deserialize::<Vec<(K, V)>>(&bytes)?; set.into_iter().for_each(|kv| func(kv)); Ok(()) }) .fold( Ok(()), |curr: Result<()>, res| if res.is_err() { res } else { curr }, )? } Ok(()) } else { Err(ShuffleError::AsyncRuntimeError) } }) .fold(Ok(()), |curr, res| if res.is_err() { res } else { curr }) } fn make_chunk_uri( base: &str, chunk: &mut String, input_id: usize, reduce_id: usize, ) -> Result<Uri> { let input_id = input_id.to_string(); let reduce_id = reduce_id.to_string(); let path_tail = ["/".to_string(), input_id, "/".to_string(), reduce_id].concat(); if chunk.len() == base.len() { chunk.push_str(&path_tail); } else { chunk.replace_range(base.len().., &path_tail); } Ok(Uri::try_from(chunk.as_str())?) } } #[cfg(test)] mod tests { use super::*; use crate::shuffle::get_free_port; #[tokio::test] async fn fetch_ok() -> StdResult<(), Box<dyn std::error::Error + 'static>> { let port = get_free_port(); ShuffleManager::start_server(Some(port))?; { let addr = format!("http://127.0.0.1:{}", port); let servers = &env::Env::get().map_output_tracker.server_uris; servers.insert(0, vec![Some(addr)]); let data = vec![(0i32, "example data".to_string())]; let serialized_data = bincode::serialize(&data).unwrap(); env::SHUFFLE_CACHE.insert((0, 0, 0), serialized_data); } let test_func = |(k, v): (i32, String)| { assert_eq!(k, 0); assert_eq!(v, "example data"); }; ShuffleFetcher::fetch(0, 0, test_func).await?; Ok(()) } #[tokio::test] async fn fetch_failure() -> StdResult<(), Box<dyn std::error::Error + 'static>> { let port = get_free_port(); ShuffleManager::start_server(Some(port))?; { let addr = format!("http://127.0.0.1:{}", port); let servers = &env::Env::get().map_output_tracker.server_uris; servers.insert(1, vec![Some(addr)]); let data = "corrupted data"; let serialized_data = bincode::serialize(&data).unwrap(); env::SHUFFLE_CACHE.insert((1, 0, 0), serialized_data); } let test_func = |(_k, _v): (i32, String)| {}; assert!(ShuffleFetcher::fetch(1, 0, test_func) .await .unwrap_err() .deserialization_err()); Ok(()) } #[test] fn build_shuffle_id_uri() -> StdResult<(), Box<dyn std::error::Error + 'static>> { let base = "http://127.0.0.1/shuffle"; let mut chunk = base.to_owned(); let uri0 = ShuffleFetcher::make_chunk_uri(base, &mut chunk, 0, 1)?; let expected = format!("{}/0/1", base); assert_eq!(expected.as_str(), uri0); let uri1 = ShuffleFetcher::make_chunk_uri(base, &mut chunk, 123, 123)?; let expected = format!("{}/123/123", base); assert_eq!(expected.as_str(), uri1); Ok(()) } } <file_sep>use std::collections::{BTreeSet, VecDeque}; use std::net::{Ipv4Addr, SocketAddrV4}; use std::sync::Arc; use std::thread; use std::time::{Duration, Instant}; use crate::dag_scheduler::{CompletionEvent, FetchFailedVals}; use crate::dependency::{Dependency, ShuffleDependencyTrait}; use crate::env; use crate::error::Result; use crate::job::JobTracker; use crate::rdd::{Rdd, RddBase}; use crate::result_task::ResultTask; use crate::serializable_traits::{Data, SerFunc}; use crate::shuffle::ShuffleMapTask; use crate::stage::Stage; use crate::task::{TaskBase, TaskContext, TaskOption}; use dashmap::DashMap; pub trait Scheduler { fn start(&self); fn wait_for_register(&self); fn run_job<T: Data, U: Data, F>( &self, rdd: &dyn Rdd<Item = T>, func: F, partitions: Vec<i64>, allow_local: bool, ) -> Vec<U> where Self: Sized, F: Fn(Box<dyn Iterator<Item = T>>) -> U; fn stop(&self); fn default_parallelism(&self) -> i64; } pub(crate) type EventQueue = Arc<DashMap<usize, VecDeque<CompletionEvent>>>; /// Functionality by the library built-in schedulers pub(crate) trait NativeScheduler { /// Fast path for execution. Runs the DD in the driver main thread if possible. fn local_execution<T: Data, U: Data, F>(jt: JobTracker<F, U, T>) -> Result<Option<Vec<U>>> where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { if jt.final_stage.parents.is_empty() && (jt.num_output_parts == 1) { futures::executor::block_on(tokio::task::block_in_place(|| async { let split = (jt.final_rdd.splits()[jt.output_parts[0]]).clone(); let task_context = TaskContext::new(jt.final_stage.id, jt.output_parts[0], 0); Ok(Some(vec![(&jt.func)(( task_context, jt.final_rdd.iterator(split)?, ))])) })) } else { Ok(None) } } fn new_stage( &self, rdd_base: Arc<dyn RddBase>, shuffle_dependency: Option<Arc<dyn ShuffleDependencyTrait>>, ) -> Stage { log::debug!("creating new stage"); env::Env::get() .cache_tracker .register_rdd(rdd_base.get_rdd_id(), rdd_base.number_of_splits()); if shuffle_dependency.is_some() { log::debug!("shuffle dependency exists, registering to map output tracker"); self.register_shuffle( shuffle_dependency.clone().unwrap().get_shuffle_id(), rdd_base.number_of_splits(), ); log::debug!("new stage tracker after"); } let id = self.get_next_stage_id(); log::debug!("new stage id #{}", id); let stage = Stage::new( id, rdd_base.clone(), shuffle_dependency, self.get_parent_stages(rdd_base), ); self.insert_into_stage_cache(id, stage.clone()); log::debug!("returning new stage #{}", id); stage } fn visit_for_missing_parent_stages( &self, missing: &mut BTreeSet<Stage>, visited: &mut BTreeSet<Arc<dyn RddBase>>, rdd: Arc<dyn RddBase>, ) { log::debug!( "missing stages: {:?}", missing.iter().map(|x| x.id).collect::<Vec<_>>() ); log::debug!( "visited stages: {:?}", visited.iter().map(|x| x.get_rdd_id()).collect::<Vec<_>>() ); if !visited.contains(&rdd) { visited.insert(rdd.clone()); // TODO CacheTracker register for _ in 0..rdd.number_of_splits() { let locs = self.get_cache_locs(rdd.clone()); log::debug!("cache locs: {:?}", locs); if locs == None { for dep in rdd.get_dependencies() { log::debug!("for dep in missing stages "); match dep { Dependency::ShuffleDependency(shuf_dep) => { let stage = self.get_shuffle_map_stage(shuf_dep.clone()); log::debug!("shuffle stage #{} in missing stages", stage.id); if !stage.is_available() { log::debug!( "inserting shuffle stage #{} in missing stages", stage.id ); missing.insert(stage); } } Dependency::NarrowDependency(nar_dep) => { log::debug!("narrow stage in missing stages"); self.visit_for_missing_parent_stages( missing, visited, nar_dep.get_rdd_base(), ) } } } } } } } fn visit_for_parent_stages( &self, parents: &mut BTreeSet<Stage>, visited: &mut BTreeSet<Arc<dyn RddBase>>, rdd: Arc<dyn RddBase>, ) { log::debug!( "parent stages: {:?}", parents.iter().map(|x| x.id).collect::<Vec<_>>() ); log::debug!( "visited stages: {:?}", visited.iter().map(|x| x.get_rdd_id()).collect::<Vec<_>>() ); if !visited.contains(&rdd) { visited.insert(rdd.clone()); env::Env::get() .cache_tracker .register_rdd(rdd.get_rdd_id(), rdd.number_of_splits()); for dep in rdd.get_dependencies() { match dep { Dependency::ShuffleDependency(shuf_dep) => { parents.insert(self.get_shuffle_map_stage(shuf_dep.clone())); } Dependency::NarrowDependency(nar_dep) => { self.visit_for_parent_stages(parents, visited, nar_dep.get_rdd_base()) } } } } } fn get_parent_stages(&self, rdd: Arc<dyn RddBase>) -> Vec<Stage> { log::debug!("inside get parent stages"); let mut parents: BTreeSet<Stage> = BTreeSet::new(); let mut visited: BTreeSet<Arc<dyn RddBase>> = BTreeSet::new(); self.visit_for_parent_stages(&mut parents, &mut visited, rdd.clone()); log::debug!( "parent stages: {:?}", parents.iter().map(|x| x.id).collect::<Vec<_>>() ); parents.into_iter().collect() } fn on_event_failure<T: Data, U: Data, F>( &self, jt: JobTracker<F, U, T>, failed_vals: FetchFailedVals, stage_id: usize, ) where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { let FetchFailedVals { server_uri, shuffle_id, map_id, .. } = failed_vals; //TODO mapoutput tracker needs to be finished for this // let failed_stage = self.id_to_stage.lock().get(&stage_id).unwrap().clone(); let failed_stage = self.fetch_from_stage_cache(stage_id); jt.running.lock().remove(&failed_stage); jt.failed.lock().insert(failed_stage); //TODO logging self.remove_output_loc_from_stage(shuffle_id, map_id, &server_uri); self.unregister_map_output(shuffle_id, map_id, server_uri); //logging jt.failed .lock() .insert(self.fetch_from_shuffle_to_cache(shuffle_id)); } fn on_event_success<T: Data, U: Data, F>( &self, mut completed_event: CompletionEvent, results: &mut Vec<Option<U>>, num_finished: &mut usize, jt: JobTracker<F, U, T>, ) where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { //TODO logging //TODO add to Accumulator let result_type = completed_event .task .downcast_ref::<ResultTask<T, U, F>>() .is_some(); if result_type { if let Ok(rt) = completed_event.task.downcast::<ResultTask<T, U, F>>() { let result = completed_event .result .take() .unwrap() .downcast_ref::<U>() .unwrap() .clone(); results[rt.output_id] = Some(result); jt.finished.lock()[rt.output_id] = true; *num_finished += 1; } } else if let Ok(smt) = completed_event.task.downcast::<ShuffleMapTask>() { let shuffle_server_uri = completed_event .result .take() .unwrap() .downcast_ref::<String>() .unwrap() .clone(); log::debug!( "completed shuffle task server uri: {:?}", shuffle_server_uri ); self.add_output_loc_to_stage(smt.stage_id, smt.partition, shuffle_server_uri); let stage = self.fetch_from_stage_cache(smt.stage_id); log::debug!( "pending stages: {:?}", jt.pending_tasks .lock() .iter() .map(|(x, y)| (x.id, y.iter().map(|k| k.get_task_id()).collect::<Vec<_>>())) .collect::<Vec<_>>() ); log::debug!( "pending tasks: {:?}", jt.pending_tasks .lock() .get(&stage) .unwrap() .iter() .map(|x| x.get_task_id()) .collect::<Vec<_>>() ); log::debug!( "running stages: {:?}", jt.running.lock().iter().map(|x| x.id).collect::<Vec<_>>() ); log::debug!( "waiting stages: {:?}", jt.waiting.lock().iter().map(|x| x.id).collect::<Vec<_>>() ); if jt.running.lock().contains(&stage) && jt.pending_tasks.lock().get(&stage).unwrap().is_empty() { log::debug!("started registering map outputs"); //TODO logging jt.running.lock().remove(&stage); if stage.shuffle_dependency.is_some() { log::debug!( "stage output locs before register mapoutput tracker: {:?}", stage.output_locs ); let locs = stage .output_locs .iter() .map(|x| x.get(0).map(|s| s.to_owned())) .collect(); log::debug!( "locs for shuffle id #{}: {:?}", stage.clone().shuffle_dependency.unwrap().get_shuffle_id(), locs ); self.register_map_outputs( stage.shuffle_dependency.unwrap().get_shuffle_id(), locs, ); log::debug!("finished registering map outputs"); } //TODO Cache self.update_cache_locs(); let mut newly_runnable = Vec::new(); for stage in jt.waiting.lock().iter() { log::debug!( "waiting stage parent stages for stage #{} are: {:?}", stage.id, self.get_missing_parent_stages(stage.clone()) .iter() .map(|x| x.id) .collect::<Vec<_>>() ); if self.get_missing_parent_stages(stage.clone()).is_empty() { newly_runnable.push(stage.clone()) } } for stage in &newly_runnable { jt.waiting.lock().remove(stage); } for stage in &newly_runnable { jt.running.lock().insert(stage.clone()); } for stage in newly_runnable { self.submit_missing_tasks(stage, jt.clone()); } } } } fn submit_stage<T: Data, U: Data, F>(&self, stage: Stage, jt: JobTracker<F, U, T>) where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { log::debug!("submitting stage #{}", stage.id); if !jt.waiting.lock().contains(&stage) && !jt.running.lock().contains(&stage) { let missing = self.get_missing_parent_stages(stage.clone()); log::debug!( "while submitting stage #{}, missing stages: {:?}", stage.id, missing.iter().map(|x| x.id).collect::<Vec<_>>() ); if missing.is_empty() { self.submit_missing_tasks(stage.clone(), jt.clone()); jt.running.lock().insert(stage); } else { for parent in missing { self.submit_stage(parent, jt.clone()); } jt.waiting.lock().insert(stage); } } } fn submit_missing_tasks<T: Data, U: Data, F>(&self, stage: Stage, jt: JobTracker<F, U, T>) where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { let mut pending_tasks = jt.pending_tasks.lock(); let my_pending = pending_tasks .entry(stage.clone()) .or_insert_with(BTreeSet::new); if stage == jt.final_stage { log::debug!("final stage #{}", stage.id); for (id_in_job, (id, part)) in jt .output_parts .iter() .enumerate() .take(jt.num_output_parts) .enumerate() { let locs = self.get_preferred_locs(jt.final_rdd.get_rdd_base(), *part); let result_task = ResultTask::new( self.get_next_task_id(), jt.run_id, jt.final_stage.id, jt.final_rdd.clone(), jt.func.clone(), *part, locs, id, ); let task = Box::new(result_task.clone()) as Box<dyn TaskBase>; let executor = self.next_executor_server(&*task); my_pending.insert(task); self.submit_task::<T, U, F>( TaskOption::ResultTask(Box::new(result_task)), id_in_job, executor, ) } } else { for p in 0..stage.num_partitions { log::debug!("shuffle stage #{}", stage.id); if stage.output_locs[p].is_empty() { let locs = self.get_preferred_locs(stage.get_rdd(), p); log::debug!("creating task for stage #{} partition #{}", stage.id, p); let shuffle_map_task = ShuffleMapTask::new( self.get_next_task_id(), jt.run_id, stage.id, stage.rdd.clone(), stage.shuffle_dependency.clone().unwrap(), p, locs, ); log::debug!( "creating task for stage #{}, partition #{} and shuffle id #{}", stage.id, p, shuffle_map_task.dep.get_shuffle_id() ); let task = Box::new(shuffle_map_task.clone()) as Box<dyn TaskBase>; let executor = self.next_executor_server(&*task); my_pending.insert(task); self.submit_task::<T, U, F>( TaskOption::ShuffleMapTask(Box::new(shuffle_map_task)), p, executor, ); } } } } fn wait_for_event(&self, run_id: usize, timeout: u64) -> Option<CompletionEvent> { // TODO: make use of async to wait for events let end = Instant::now() + Duration::from_millis(timeout); while self.get_event_queue().get(&run_id).unwrap().is_empty() { if Instant::now() > end { return None; } else { thread::sleep(end - Instant::now()); } } self.get_event_queue().get_mut(&run_id).unwrap().pop_front() } fn submit_task<T: Data, U: Data, F>( &self, task: TaskOption, id_in_job: usize, target_executor: SocketAddrV4, ) where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U; // mutators: fn add_output_loc_to_stage(&self, stage_id: usize, partition: usize, host: String); fn insert_into_stage_cache(&self, id: usize, stage: Stage); /// refreshes cache locations fn register_shuffle(&self, shuffle_id: usize, num_maps: usize); fn register_map_outputs(&self, shuffle_id: usize, locs: Vec<Option<String>>); fn remove_output_loc_from_stage(&self, shuffle_id: usize, map_id: usize, server_uri: &str); fn update_cache_locs(&self); fn unregister_map_output(&self, shuffle_id: usize, map_id: usize, server_uri: String); // getters: fn fetch_from_stage_cache(&self, id: usize) -> Stage; fn fetch_from_shuffle_to_cache(&self, id: usize) -> Stage; fn get_cache_locs(&self, rdd: Arc<dyn RddBase>) -> Option<Vec<Vec<Ipv4Addr>>>; fn get_event_queue(&self) -> &Arc<DashMap<usize, VecDeque<CompletionEvent>>>; fn get_missing_parent_stages(&self, stage: Stage) -> Vec<Stage>; fn get_next_job_id(&self) -> usize; fn get_next_stage_id(&self) -> usize; fn get_next_task_id(&self) -> usize; fn next_executor_server(&self, rdd: &dyn TaskBase) -> SocketAddrV4; fn get_preferred_locs(&self, rdd: Arc<dyn RddBase>, partition: usize) -> Vec<Ipv4Addr> { //TODO have to implement this completely if let Some(cached) = self.get_cache_locs(rdd.clone()) { if let Some(cached) = cached.get(partition) { return cached.clone(); } } let rdd_prefs = rdd.preferred_locations(rdd.splits()[partition].clone()); if !rdd.is_pinned() { if !rdd_prefs.is_empty() { return rdd_prefs; } for dep in rdd.get_dependencies().iter() { if let Dependency::NarrowDependency(nar_dep) = dep { for in_part in nar_dep.get_parents(partition) { let locs = self.get_preferred_locs(nar_dep.get_rdd_base(), in_part); if !locs.is_empty() { return locs; } } } } Vec::new() } else { // when pinned, is required that there is exactly one preferred location // for a given partition assert!(rdd_prefs.len() == 1); rdd_prefs } } fn get_shuffle_map_stage(&self, shuf: Arc<dyn ShuffleDependencyTrait>) -> Stage; } macro_rules! impl_common_scheduler_funcs { () => { fn add_output_loc_to_stage(&self, stage_id: usize, partition: usize, host: String) { self.stage_cache .get_mut(&stage_id) .unwrap() .add_output_loc(partition, host); } #[inline] fn insert_into_stage_cache(&self, id: usize, stage: Stage) { self.stage_cache.insert(id, stage.clone()); } #[inline] fn fetch_from_stage_cache(&self, id: usize) -> Stage { self.stage_cache.get(&id).unwrap().clone() } #[inline] fn fetch_from_shuffle_to_cache(&self, id: usize) -> Stage { self.shuffle_to_map_stage.get(&id).unwrap().clone() } fn update_cache_locs(&self) { self.cache_locs.clear(); env::Env::get() .cache_tracker .get_location_snapshot() .into_iter() .for_each(|(k, v)| { self.cache_locs.insert(k, v); }); } fn unregister_map_output(&self, shuffle_id: usize, map_id: usize, server_uri: String) { self.map_output_tracker.unregister_map_output( shuffle_id, map_id, server_uri ) } fn register_shuffle(&self, shuffle_id: usize, num_maps: usize) { self.map_output_tracker.register_shuffle( shuffle_id, num_maps ) } fn register_map_outputs(&self, shuffle_id: usize, locs: Vec<Option<String>>) { self.map_output_tracker.register_map_outputs( shuffle_id, locs ) } fn remove_output_loc_from_stage(&self, shuffle_id: usize, map_id: usize, server_uri: &str) { self.shuffle_to_map_stage .get_mut(&shuffle_id) .unwrap() .remove_output_loc(map_id, server_uri); } #[inline] fn get_cache_locs(&self, rdd: Arc<dyn RddBase>) -> Option<Vec<Vec<Ipv4Addr>>> { let locs_opt = self.cache_locs.get(&rdd.get_rdd_id()); locs_opt.map(|l| l.clone()) } #[inline] fn get_event_queue(&self) -> &Arc<DashMap<usize, VecDeque<CompletionEvent>>> { &self.event_queues } #[inline] fn get_next_job_id(&self) -> usize { self.next_job_id.fetch_add(1, Ordering::SeqCst) } #[inline] fn get_next_stage_id(&self) -> usize { self.next_stage_id.fetch_add(1, Ordering::SeqCst) } #[inline] fn get_next_task_id(&self) -> usize { self.next_task_id.fetch_add(1, Ordering::SeqCst) } fn get_missing_parent_stages(&self, stage: Stage) -> Vec<Stage> { log::debug!("getting missing parent stages"); let mut missing: BTreeSet<Stage> = BTreeSet::new(); let mut visited: BTreeSet<Arc<dyn RddBase>> = BTreeSet::new(); self.visit_for_missing_parent_stages(&mut missing, &mut visited, stage.get_rdd()); missing.into_iter().collect() } fn get_shuffle_map_stage(&self, shuf: Arc<dyn ShuffleDependencyTrait>) -> Stage { log::debug!("getting shuffle map stage"); let stage = self .shuffle_to_map_stage .get(&shuf.get_shuffle_id()) .map(|s| s.clone()); match stage { Some(stage) => stage, None => { log::debug!("started creating shuffle map stage before"); let stage = self.new_stage(shuf.get_rdd_base(), Some(shuf.clone())); self.shuffle_to_map_stage .insert(shuf.get_shuffle_id(), stage.clone()); log::debug!("finished inserting newly created shuffle stage"); stage } } } }; } <file_sep>use itertools::{iproduct, Itertools}; use crate::context::Context; use crate::dependency::Dependency; use crate::error::{Error, Result}; use crate::rdd::{Rdd, RddBase, RddVals}; use crate::serializable_traits::{AnyData, Data}; use crate::split::Split; use serde_derive::{Deserialize, Serialize}; use std::marker::PhantomData; use std::sync::Arc; #[derive(Clone, Serialize, Deserialize)] struct CartesianSplit { idx: usize, s1_idx: usize, s2_idx: usize, #[serde(with = "serde_traitobject")] s1: Box<dyn Split>, #[serde(with = "serde_traitobject")] s2: Box<dyn Split>, } impl Split for CartesianSplit { fn get_index(&self) -> usize { self.idx } } #[derive(Serialize, Deserialize)] pub struct CartesianRdd<T: Data, U: Data> { vals: Arc<RddVals>, #[serde(with = "serde_traitobject")] rdd1: Arc<dyn Rdd<Item = T>>, #[serde(with = "serde_traitobject")] rdd2: Arc<dyn Rdd<Item = U>>, num_partitions_in_rdd2: usize, _marker_t: PhantomData<T>, _market_u: PhantomData<U>, } impl<T: Data, U: Data> CartesianRdd<T, U> { pub(crate) fn new( rdd1: Arc<dyn Rdd<Item = T>>, rdd2: Arc<dyn Rdd<Item = U>>, ) -> CartesianRdd<T, U> { let vals = Arc::new(RddVals::new(rdd1.get_context())); let num_partitions_in_rdd2 = rdd2.number_of_splits(); CartesianRdd { vals, rdd1, rdd2, num_partitions_in_rdd2, _marker_t: PhantomData, _market_u: PhantomData, } } } impl<T: Data, U: Data> Clone for CartesianRdd<T, U> { fn clone(&self) -> Self { CartesianRdd { vals: self.vals.clone(), rdd1: self.rdd1.clone(), rdd2: self.rdd2.clone(), num_partitions_in_rdd2: self.num_partitions_in_rdd2, _marker_t: PhantomData, _market_u: PhantomData, } } } impl<T: Data, U: Data> RddBase for CartesianRdd<T, U> { fn get_rdd_id(&self) -> usize { self.vals.id } fn get_context(&self) -> Arc<Context> { self.vals.context.upgrade().unwrap() } fn get_dependencies(&self) -> Vec<Dependency> { self.vals.dependencies.clone() } fn splits(&self) -> Vec<Box<dyn Split>> { // create the cross product split let mut array = Vec::with_capacity(self.rdd1.number_of_splits() + self.rdd2.number_of_splits()); for (s1, s2) in iproduct!(self.rdd1.splits().iter(), self.rdd2.splits().iter()) { let s1_idx = s1.get_index(); let s2_idx = s2.get_index(); let idx = s1_idx * self.num_partitions_in_rdd2 + s2_idx; array.push(Box::new(CartesianSplit { idx, s1_idx, s2_idx, s1: s1.clone(), s2: s2.clone(), }) as Box<dyn Split>); } array } default fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { Ok(Box::new( self.iterator(split)? .map(|x| Box::new(x) as Box<dyn AnyData>), )) } } impl<T: Data, U: Data> Rdd for CartesianRdd<T, U> { type Item = (T, U); fn get_rdd(&self) -> Arc<dyn Rdd<Item = Self::Item>> where Self: Sized, { Arc::new(self.clone()) } fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(self.clone()) as Arc<dyn RddBase> } fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { let current_split = split .downcast::<CartesianSplit>() .or(Err(Error::DowncastFailure("CartesianSplit")))?; let iter1 = self.rdd1.iterator(current_split.s1)?; // required because iter2 must be clonable: let iter2: Vec<_> = self.rdd2.iterator(current_split.s2)?.collect(); Ok(Box::new(iter1.cartesian_product(iter2.into_iter()))) } } <file_sep>use crate::aggregator::Aggregator; use crate::env; use crate::partitioner::Partitioner; use crate::rdd::RddBase; use crate::serializable_traits::Data; use serde_derive::{Deserialize, Serialize}; use serde_traitobject::{Deserialize, Serialize}; use std::cmp::Ordering; use std::collections::HashMap; use std::hash::Hash; use std::sync::Arc; // Revise if enum is good choice. Considering enum since down casting one trait object to another trait object is difficult. #[derive(Clone, Serialize, Deserialize)] pub enum Dependency { #[serde(with = "serde_traitobject")] NarrowDependency(Arc<dyn NarrowDependencyTrait>), #[serde(with = "serde_traitobject")] ShuffleDependency(Arc<dyn ShuffleDependencyTrait>), } pub trait NarrowDependencyTrait: Serialize + Deserialize + Send + Sync { fn get_parents(&self, partition_id: usize) -> Vec<usize>; fn get_rdd_base(&self) -> Arc<dyn RddBase>; } #[derive(Serialize, Deserialize, Clone)] pub(crate) struct OneToOneDependency { #[serde(with = "serde_traitobject")] rdd_base: Arc<dyn RddBase>, } impl OneToOneDependency { pub fn new(rdd_base: Arc<dyn RddBase>) -> Self { OneToOneDependency { rdd_base } } } impl NarrowDependencyTrait for OneToOneDependency { fn get_parents(&self, partition_id: usize) -> Vec<usize> { vec![partition_id] } fn get_rdd_base(&self) -> Arc<dyn RddBase> { self.rdd_base.clone() } } /// Represents a one-to-one dependency between ranges of partitions in the parent and child RDDs. #[derive(Serialize, Deserialize, Clone)] pub(crate) struct RangeDependency { #[serde(with = "serde_traitobject")] rdd_base: Arc<dyn RddBase>, /// the start of the range in the child RDD out_start: usize, /// the start of the range in the parent RDD in_start: usize, /// the length of the range length: usize, } impl RangeDependency { pub fn new( rdd_base: Arc<dyn RddBase>, in_start: usize, out_start: usize, length: usize, ) -> Self { RangeDependency { rdd_base, in_start, out_start, length, } } } impl NarrowDependencyTrait for RangeDependency { fn get_parents(&self, partition_id: usize) -> Vec<usize> { if partition_id >= self.out_start && partition_id < self.out_start + self.length { vec![partition_id - self.out_start + self.in_start] } else { Vec::new() } } fn get_rdd_base(&self) -> Arc<dyn RddBase> { self.rdd_base.clone() } } pub trait ShuffleDependencyTrait: Serialize + Deserialize + Send + Sync { fn get_shuffle_id(&self) -> usize; fn get_rdd_base(&self) -> Arc<dyn RddBase>; fn is_shuffle(&self) -> bool; fn do_shuffle_task(&self, rdd_base: Arc<dyn RddBase>, partition: usize) -> String; } impl PartialOrd for dyn ShuffleDependencyTrait { fn partial_cmp(&self, other: &dyn ShuffleDependencyTrait) -> Option<Ordering> { Some(self.get_shuffle_id().cmp(&other.get_shuffle_id())) } } impl PartialEq for dyn ShuffleDependencyTrait { fn eq(&self, other: &dyn ShuffleDependencyTrait) -> bool { self.get_shuffle_id() == other.get_shuffle_id() } } impl Eq for dyn ShuffleDependencyTrait {} impl Ord for dyn ShuffleDependencyTrait { fn cmp(&self, other: &dyn ShuffleDependencyTrait) -> Ordering { self.get_shuffle_id().cmp(&other.get_shuffle_id()) } } #[derive(Serialize, Deserialize)] pub(crate) struct ShuffleDependency<K: Data, V: Data, C: Data> { pub shuffle_id: usize, pub is_cogroup: bool, #[serde(with = "serde_traitobject")] pub rdd_base: Arc<dyn RddBase>, #[serde(with = "serde_traitobject")] pub aggregator: Arc<Aggregator<K, V, C>>, #[serde(with = "serde_traitobject")] pub partitioner: Box<dyn Partitioner>, is_shuffle: bool, } impl<K: Data, V: Data, C: Data> ShuffleDependency<K, V, C> { pub fn new( shuffle_id: usize, is_cogroup: bool, rdd_base: Arc<dyn RddBase>, aggregator: Arc<Aggregator<K, V, C>>, partitioner: Box<dyn Partitioner>, ) -> Self { ShuffleDependency { shuffle_id, is_cogroup, rdd_base, aggregator, partitioner, is_shuffle: true, } } } impl<K: Data + Eq + Hash, V: Data, C: Data> ShuffleDependencyTrait for ShuffleDependency<K, V, C> { fn get_shuffle_id(&self) -> usize { self.shuffle_id } fn is_shuffle(&self) -> bool { self.is_shuffle } fn get_rdd_base(&self) -> Arc<dyn RddBase> { self.rdd_base.clone() } fn do_shuffle_task(&self, rdd_base: Arc<dyn RddBase>, partition: usize) -> String { log::debug!("executing shuffle task for partition #{}", partition); let split = rdd_base.splits()[partition].clone(); let aggregator = self.aggregator.clone(); let num_output_splits = self.partitioner.get_num_of_partitions(); log::debug!("is cogroup rdd: {}", self.is_cogroup); log::debug!("number of output splits: {}", num_output_splits); let partitioner = self.partitioner.clone(); let mut buckets: Vec<HashMap<K, C>> = (0..num_output_splits) .map(|_| HashMap::new()) .collect::<Vec<_>>(); log::debug!( "before iterating while executing shuffle map task for partition #{}", partition ); log::debug!("split index: {}", split.get_index()); let iter = if self.is_cogroup { rdd_base.cogroup_iterator_any(split) } else { rdd_base.iterator_any(split.clone()) }; for (count, i) in iter.unwrap().enumerate() { let b = i.into_any().downcast::<(K, V)>().unwrap(); let (k, v) = *b; if count == 0 { log::debug!( "iterating inside dependency map task after downcasting: key: {:?}, value: {:?}", k, v ); } let bucket_id = partitioner.get_partition(&k); let bucket = &mut buckets[bucket_id]; if let Some(old_v) = bucket.get_mut(&k) { let input = ((old_v.clone(), v),); let output = aggregator.merge_value.call(input); *old_v = output; } else { bucket.insert(k, aggregator.create_combiner.call((v,))); } } for (i, bucket) in buckets.into_iter().enumerate() { let set: Vec<(K, C)> = bucket.into_iter().collect(); let ser_bytes = bincode::serialize(&set).unwrap(); log::debug!( "shuffle dependency map task set from bucket #{} in shuffle id #{}, partition #{}: {:?}", i, self.shuffle_id, partition, set.get(0) ); env::SHUFFLE_CACHE.insert((self.shuffle_id, partition, i), ser_bytes); } env::Env::get().shuffle_manager.get_server_uri() } } <file_sep>#![allow(where_clauses_object_safety)] use native_spark::*; fn main() -> Result<()> { let sc = Context::new()?; let vec = vec![ ("x".to_string(), 1), ("x".to_string(), 2), ("x".to_string(), 3), ("x".to_string(), 4), ("x".to_string(), 5), ("x".to_string(), 6), ("x".to_string(), 7), ("y".to_string(), 1), ("y".to_string(), 2), ("y".to_string(), 3), ("y".to_string(), 4), ("y".to_string(), 5), ("y".to_string(), 6), ("y".to_string(), 7), ("y".to_string(), 8), ]; let r = sc.make_rdd(vec, 4); let g = r.group_by_key(4); let res = g.collect().unwrap(); println!("res {:?}", res); Ok(()) } <file_sep>pub mod common_config_keys; pub mod file_system; pub mod path; <file_sep>#![allow(where_clauses_object_safety)] use native_spark::*; #[macro_use] extern crate serde_closure; fn main() -> Result<()> { let sc = Context::new()?; let col = sc.make_rdd((0..10).collect::<Vec<_>>(), 32); //Fn! will make the closures serializable. It is necessary. use serde_closure version 0.1.3. let vec_iter = col.map(Fn!(|i| (0..i).collect::<Vec<_>>())); let res = vec_iter.collect().unwrap(); println!("result: {:?}", res); Ok(()) } <file_sep>use crate::serializable_traits::Data; use rand::{Rng, SeedableRng}; use rand_distr::{Distribution, Poisson}; use rand_pcg::Pcg64; use serde_derive::{Deserialize, Serialize}; use serde_traitobject::{Deserialize, Serialize}; /// Default maximum gap-sampling fraction. /// For sampling fractions <= this value, the gap sampling optimization will be applied. /// Above this value, it is assumed that "traditional" Bernoulli sampling is faster. The /// optimal value for this will depend on the RNG. More expensive RNGs will tend to make /// the optimal value higher. The most reliable way to determine this value for a new RNG /// is to experiment. When tuning for a new RNG, expect a value of 0.5 to be close in /// most cases, as an initial guess. // TODO: tune for PCG64, performance is similar and around same order of magnitude // of XORShift so shouldn't be too far off const DEFAULT_MAX_GAP_SAMPLING_FRACTION: f64 = 0.4; /// Default epsilon for floating point numbers sampled from the RNG. /// The gap-sampling compute logic requires taking log(x), where x is sampled from an RNG. /// To guard against errors from taking log(0), a positive epsilon lower bound is applied. /// A good value for this parameter is at or near the minimum positive floating /// point value returned by for the RNG being used. // TODO: this is a straight port, it may not apply exactly to pcg64 rng but should be mostly fine; // double check; Apache Spark(tm) uses XORShift by default const RNG_EPSILON: f64 = 5e-11; /// Sampling fraction arguments may be results of computation, and subject to floating /// point jitter. I check the arguments with this epsilon slop factor to prevent spurious /// warnings for cases such as summing some numbers to get a sampling fraction of 1.000000001 const ROUNDING_EPSILON: f64 = 1e-6; type RSamplerFunc<'a, T> = Box<dyn Fn(Box<dyn Iterator<Item = T>>) -> Vec<T> + 'a>; pub(crate) trait RandomSampler<T: Data>: Send + Sync + Serialize + Deserialize { /// Returns a function which returns random samples, /// the sampler is thread-safe as the RNG is seeded with random seeds per thread. fn get_sampler(&self) -> RSamplerFunc<T>; } pub(crate) fn get_default_rng() -> Pcg64 { Pcg64::new( 0xcafe_f00d_d15e_a5e5, 0x0a02_bdbf_7bb3_c0a7_ac28_fa16_a64a_bf96, ) } pub(crate) fn get_default_rng_from_seed(seed: u64) -> Pcg64 { Pcg64::seed_from_u64(seed) } /// Get a new rng with random thread local random seed fn get_rng_with_random_seed() -> Pcg64 { Pcg64::seed_from_u64(rand::random::<u64>()) } #[derive(Clone, Serialize, Deserialize)] pub(crate) struct PoissonSampler { fraction: f64, use_gap_sampling_if_possible: bool, prob: f64, } impl PoissonSampler { pub fn new(fraction: f64, use_gap_sampling_if_possible: bool) -> PoissonSampler { let prob = if fraction > 0.0 { fraction } else { 1.0 }; PoissonSampler { fraction, use_gap_sampling_if_possible, prob, } } } impl<T: Data> RandomSampler<T> for PoissonSampler { fn get_sampler(&self) -> RSamplerFunc<T> { Box::new(move |items: Box<dyn Iterator<Item = T>>| -> Vec<T> { if self.fraction <= 0.0 { vec![] } else { let use_gap_sampling = self.use_gap_sampling_if_possible && self.fraction <= DEFAULT_MAX_GAP_SAMPLING_FRACTION; let mut gap_sampling = if use_gap_sampling { // Initialize here and move to avoid constructing a new one each iteration Some(GapSamplingReplacement::new(self.fraction, RNG_EPSILON)) } else { None }; let dist = Poisson::new(self.prob).unwrap(); let mut rng = get_rng_with_random_seed(); items .flat_map(move |item| { let count = if use_gap_sampling { gap_sampling.as_mut().unwrap().sample() } else { dist.sample(&mut rng) }; if count != 0 { vec![item; count as usize] } else { vec![] } }) .collect() } }) } } #[derive(Clone, Serialize, Deserialize)] pub(crate) struct BernoulliSampler { fraction: f64, } impl BernoulliSampler { pub fn new(fraction: f64) -> BernoulliSampler { assert!(fraction >= (0.0 - ROUNDING_EPSILON) && fraction <= (1.0 + ROUNDING_EPSILON)); BernoulliSampler { fraction } } fn sample(&self, gap_sampling: Option<&mut GapSamplingReplacement>, rng: &mut Pcg64) -> u64 { match self.fraction { v if v <= 0.0 => 0, v if v >= 1.0 => 1, v if v <= DEFAULT_MAX_GAP_SAMPLING_FRACTION => gap_sampling.unwrap().sample(), v if rng.gen::<f64>() <= v => 1, _ => 0, } } } impl<T: Data> RandomSampler<T> for BernoulliSampler { fn get_sampler(&self) -> RSamplerFunc<T> { Box::new(move |items: Box<dyn Iterator<Item = T>>| -> Vec<T> { let mut gap_sampling = if self.fraction > 0.0 && self.fraction < 1.0 { Some(GapSamplingReplacement::new(self.fraction, RNG_EPSILON)) } else { None }; let mut rng = get_rng_with_random_seed(); items .filter(move |_| self.sample(gap_sampling.as_mut(), &mut rng) > 0) .collect() }) } } struct GapSamplingReplacement { fraction: f64, epsilon: f64, q: f64, rng: rand_pcg::Pcg64, count_for_dropping: u64, } impl GapSamplingReplacement { fn new(fraction: f64, epsilon: f64) -> GapSamplingReplacement { assert!(fraction > 0.0 && fraction < 1.0); assert!(epsilon > 0.0); let mut sampler = GapSamplingReplacement { q: (-fraction).exp(), fraction, epsilon, rng: get_rng_with_random_seed(), count_for_dropping: 0, }; // Advance to first sample as part of object construction. sampler.advance(); sampler } fn sample(&mut self) -> u64 { if self.count_for_dropping > 0 { self.count_for_dropping -= 1; 0 } else { let r = self.poisson_ge1(); self.advance(); r } } /// Sample from Poisson distribution, conditioned such that the sampled value is >= 1. /// This is an adaptation from the algorithm for generating /// [Poisson distributed random variables](http://en.wikipedia.org/wiki/Poisson_distribution) fn poisson_ge1(&mut self) -> u64 { // simulate that the standard poisson sampling // gave us at least one iteration, for a sample of >= 1 let mut pp: f64 = self.q + ((1.0 - self.q) * self.rng.gen::<f64>()); let mut r = 1; // now continue with standard poisson sampling algorithm pp *= self.rng.gen::<f64>(); while pp > self.q { r += 1; pp *= self.rng.gen::<f64>() } r } /// Skip elements with replication factor zero (i.e. elements that won't be sampled). /// Samples 'k' from geometric distribution P(k) = (1-q)(q)^k, where q = e^(-f), that is /// q is the probability of Poisson(0; f) fn advance(&mut self) { let u = self.epsilon.max(self.rng.gen::<f64>()); self.count_for_dropping = (u.log(std::f64::consts::E) / (-self.fraction)) as u64; } } /// Returns a sampling rate that guarantees a sample of size greater than or equal to /// `sample_size_lower_bound` 99.99% of the time. /// /// How the sampling rate is determined: /// /// Let p = num / total, where num is the sample size and total is the total number of /// datapoints in the RDD. We're trying to compute q > p such that /// - when sampling with replacement, we're drawing each datapoint with prob_i ~ Pois(q), /// where we want to guarantee /// Pr[s < num] < 0.0001 for s = sum(prob_i for i from 0 to total), /// i.e. the failure rate of not having a sufficiently large sample < 0.0001. /// Setting q = p + 5 /// sqrt(p/total) is sufficient to guarantee 0.9999 success rate for /// num > 12, but we need a slightly larger q (9 empirically determined). /// - when sampling without replacement, we're drawing each datapoint with prob_i /// ~ Binomial(total, fraction) and our choice of q guarantees 1-delta, or 0.9999 success /// rate, where success rate is defined the same as in sampling with replacement. /// /// The smallest sampling rate supported is 1e-10 (in order to avoid running into the limit of the /// RNG's resolution). pub(crate) fn compute_fraction_for_sample_size( sample_size_lower_bound: u64, total: u64, with_replacement: bool, ) -> f64 { if with_replacement { poisson_bounds::get_upper_bound(sample_size_lower_bound as f64) / total as f64 } else { let fraction = sample_size_lower_bound as f64 / total as f64; binomial_bounds::get_upper_bound(1e-4, total, fraction) } } mod poisson_bounds { /// Returns a lambda such that P[X < s] is very small, where X ~ Pois(lambda). pub(super) fn get_upper_bound(s: f64) -> f64 { (s + num_std(s) * s.sqrt()).max(1e-10) } #[inline(always)] fn num_std(s: f64) -> f64 { match s { v if v < 6.0 => 12.0, v if v < 16.0 => 9.0, _ => 6.0, } } } mod binomial_bounds { const MIN_SAMPLING_RATE: f64 = 1e-10; // Returns a threshold `p` such that if we conduct n Bernoulli trials with success rate = `p`, // it is very unlikely to have less than `fraction * n` successes. pub(super) fn get_upper_bound(delta: f64, n: u64, fraction: f64) -> f64 { let gamma = -delta.log(std::f64::consts::E) / n as f64; let max = MIN_SAMPLING_RATE .max(fraction + gamma + (gamma * gamma + 2.0 * gamma * fraction).sqrt()); max.min(1.0) } } <file_sep>// not necessary I guess use downcast_rs::DowncastSync; use serde_traitobject::{Deserialize, Serialize}; pub struct SplitStruct { index: usize, } pub trait Split: DowncastSync + dyn_clone::DynClone + Serialize + Deserialize { fn get_index(&self) -> usize; } impl_downcast!(Split); dyn_clone::clone_trait_object!(Split); <file_sep>use std::net::SocketAddr; use std::sync::Arc; use std::time::Instant; use crate::env; use crate::error::{Error, NetworkError, Result}; use crate::serialized_data_capnp::serialized_data; use crate::task::TaskOption; use capnp::{ message::{Builder as MsgBuilder, HeapAllocator, Reader as CpnpReader, ReaderOptions}, serialize::OwnedSegments, }; use capnp_futures::serialize as capnp_serialize; use serde::{Deserialize, Serialize}; use tokio::{ net::TcpListener, stream::StreamExt, sync::oneshot::{channel, Receiver, Sender}, task::{spawn, spawn_blocking}, }; use tokio_util::compat::{Tokio02AsyncReadCompatExt, Tokio02AsyncWriteCompatExt}; const CAPNP_BUF_READ_OPTS: ReaderOptions = ReaderOptions { traversal_limit_in_words: std::u64::MAX, nesting_limit: 64, }; pub(crate) struct Executor { port: u16, } impl Executor { pub fn new(port: u16) -> Self { Executor { port } } /// Worker which spawns threads for received tasks, deserializes them, /// executes the task and sends the result back to the master. /// /// This will spawn it's own Tokio runtime to run the tasks on. #[allow(clippy::drop_copy)] pub fn worker(self: Arc<Self>) -> Result<Signal> { let executor = env::Env::get_async_handle(); executor.enter(move || -> Result<Signal> { futures::executor::block_on(async move { let (send_child, rcv_main) = channel::<Signal>(); let process_err = Arc::clone(&self).process_stream(rcv_main); let handler_err = spawn(Arc::clone(&self).signal_handler(send_child)); tokio::select! { err = process_err => err, err = handler_err => err?, } }) }) } #[allow(clippy::drop_copy)] async fn process_stream(self: Arc<Self>, mut rcv_main: Receiver<Signal>) -> Result<Signal> { let addr = SocketAddr::from(([0, 0, 0, 0], self.port)); let mut listener = TcpListener::bind(addr) .await .map_err(NetworkError::TcpListener)?; while let Some(Ok(mut stream)) = listener.incoming().next().await { let (reader, writer) = stream.split(); let reader = reader.compat(); let mut writer = writer.compat_write(); match rcv_main.try_recv() { Ok(Signal::ShutDownError) => { log::info!("shutting down executor @{} due to error", self.port); return Err(Error::ExecutorShutdown); } Ok(Signal::ShutDownGracefully) => { log::info!("shutting down executor @{} gracefully", self.port); return Ok(Signal::ShutDownGracefully); } _ => {} } log::debug!("received new task @{} executor", self.port); let message = { let message_reader = { if let Some(data) = capnp_serialize::read_message(reader, CAPNP_BUF_READ_OPTS).await? { data } else { return Err(Error::AsyncRuntimeError); } }; let self_clone = Arc::clone(&self); spawn_blocking(move || -> Result<_> { let des_task = self_clone.deserialize_task(message_reader)?; self_clone.run_task(des_task) }) .await?? }; capnp_serialize::write_message(&mut writer, &message) .await .map_err(Error::CapnpDeserialization)?; log::debug!("sent result data to driver"); } Err(Error::ExecutorShutdown) } #[allow(clippy::drop_copy)] fn deserialize_task( self: &Arc<Self>, message_reader: CpnpReader<OwnedSegments>, ) -> Result<TaskOption> { let start = Instant::now(); let task_data = message_reader .get_root::<serialized_data::Reader>() .unwrap(); log::debug!( "deserialized data task @{} executor with {} bytes, took {}ms", self.port, task_data.get_msg().unwrap().len(), start.elapsed().as_millis() ); // let local_dir_root = "/tmp"; // let uuid = Uuid::new_v4(); // let local_dir_uuid = uuid.to_string(); // let local_dir_path = // format!("{}/spark-task-{}", local_dir_root, local_dir_uuid); // let local_dir = fs::create_dir_all(local_dir_path.clone()).unwrap(); // let task_dir_path = // format!("{}/spark-task-{}/task", local_dir_root, local_dir_uuid); // let mut f = fs::File::create(task_dir_path.clone()).unwrap(); let msg = match task_data.get_msg() { Ok(s) => { log::debug!("got the task message in executor {}", self.port); s } Err(e) => { log::debug!("problem while getting the task in executor: {:?}", e); std::process::exit(0); } }; std::mem::drop(task_data); // f.write(msg); // let f = fs::File::open(task_dir_path.clone()).unwrap(); // let mut f = fs::File::open(task_dir_path).unwrap(); // let mut buffer = vec![0; msg.len()]; // f.read(&mut buffer).unwrap(); let start = Instant::now(); let des_task: TaskOption = bincode::deserialize(&msg)?; log::debug!( "deserialized task at executor @{} with id #{}, deserialization, took {}ms", self.port, des_task.get_task_id(), start.elapsed().as_millis(), ); Ok(des_task) } fn run_task(self: &Arc<Self>, des_task: TaskOption) -> Result<MsgBuilder<HeapAllocator>> { // Run execution + serialization in parallel in the executor threadpool let result: Result<Vec<u8>> = { let start = Instant::now(); log::debug!("executing the task from server port {}", self.port); //TODO change attempt id from 0 to proper value let result = des_task.run(0); log::debug!( "time taken @{} executor running task #{}: {}ms", self.port, des_task.get_task_id(), start.elapsed().as_millis(), ); let start = Instant::now(); let result = bincode::serialize(&result)?; log::debug!( "time taken @{} executor serializing task #{} result of size {} bytes: {}ms", self.port, des_task.get_task_id(), result.len(), start.elapsed().as_millis(), ); Ok(result) }; let mut message = capnp::message::Builder::new_default(); let mut task_data = message.init_root::<serialized_data::Builder>(); task_data.set_msg(&(result?)); Ok(message) } /// A listener for exit signal from master to end the whole slave process. async fn signal_handler(self: Arc<Self>, send_child: Sender<Signal>) -> Result<Signal> { let addr = SocketAddr::from(([0, 0, 0, 0], self.port + 10)); log::debug!("signal handler port open @ {}", addr.port()); let mut listener = TcpListener::bind(addr) .await .map_err(NetworkError::TcpListener)?; let mut signal: Result<Signal> = Err(Error::ExecutorShutdown); while let Some(Ok(stream)) = listener.incoming().next().await { let stream = stream.compat(); let signal_data = if let Some(data) = capnp_serialize::read_message(stream, CAPNP_BUF_READ_OPTS).await? { data } else { continue; }; let data = bincode::deserialize::<Signal>( signal_data .get_root::<serialized_data::Reader>()? .get_msg()?, )?; match data { Signal::ShutDownError => { log::info!("received error shutdown signal @ {}", self.port); send_child .send(Signal::ShutDownError) .map_err(|_| Error::AsyncRuntimeError)?; signal = Err(Error::ExecutorShutdown); break; } Signal::ShutDownGracefully => { log::info!("received graceful shutdown signal @ {}", self.port); send_child .send(Signal::ShutDownGracefully) .map_err(|_| Error::AsyncRuntimeError)?; signal = Ok(Signal::ShutDownGracefully); break; } _ => {} } } signal } } #[derive(Serialize, Deserialize, Debug)] pub(crate) enum Signal { ShutDownError, ShutDownGracefully, Continue, } #[cfg(test)] mod tests { #![allow(unused_must_use)] use super::*; use crate::task::{TaskContext, TaskResult}; use crate::utils::{get_free_port, test_utils::create_test_task}; use crossbeam::channel::{unbounded, Receiver, Sender}; use std::io::Write; use std::thread; use std::time::Duration; type Port = u16; type ComputeResult = std::result::Result<(), ()>; fn initialize_exec() -> Arc<Executor> { let port = get_free_port().unwrap(); Arc::new(Executor::new(port)) } fn connect_to_executor(mut port: u16, signal_handler: bool) -> Result<std::net::TcpStream> { use std::net::TcpStream; let mut i: usize = 0; if signal_handler { // connect to signal handling port port += 10; } loop { let addr: SocketAddr = format!("{}:{}", "0.0.0.0", port).parse().unwrap(); if let Ok(stream) = TcpStream::connect(addr) { return Ok(stream); } thread::sleep_ms(10); i += 1; if i > 10 { break; } } Err(Error::AsyncRuntimeError) } fn send_shutdown_signal_msg(stream: &mut std::net::TcpStream) -> Result<()> { let signal = bincode::serialize(&Signal::ShutDownGracefully)?; let mut message = capnp::message::Builder::new_default(); let mut msg_data = message.init_root::<serialized_data::Builder>(); msg_data.set_msg(&signal); capnp::serialize::write_message(stream, &message).map_err(Error::OutputWrite)?; Ok(()) } async fn _start_test<TF, CF>(test_func: TF, checker_func: CF) -> Result<()> where TF: FnOnce(Receiver<ComputeResult>, Port) -> Result<()> + Send + 'static, CF: FnOnce(Sender<ComputeResult>, Result<Signal>) -> Result<()>, { let executor = initialize_exec(); let port = executor.port; let (send_exec, client_rcv) = unbounded::<ComputeResult>(); let test_fut = spawn_blocking(move || test_func(client_rcv, port)); let worker_fut = spawn_blocking(move || executor.worker()); let (test_res, worker_res) = tokio::join!(test_fut, worker_fut); checker_func(send_exec, worker_res?)?; test_res? } #[tokio::test] async fn send_shutdown_signal() -> Result<()> { fn test(client_rcv: Receiver<ComputeResult>, port: Port) -> Result<()> { let end = Instant::now() + Duration::from_millis(150); while Instant::now() < end { match client_rcv.try_recv() { Ok(Ok(_)) => return Ok(()), Ok(Err(_)) => return Err(Error::AsyncRuntimeError), _ => {} } if let Ok(mut stream) = connect_to_executor(port, true) { send_shutdown_signal_msg(&mut stream)?; return Ok(()); } thread::sleep_ms(5); } Err(Error::AsyncRuntimeError) } fn result_checker(sender: Sender<ComputeResult>, result: Result<Signal>) -> Result<()> { match result { Ok(Signal::ShutDownGracefully) => { sender.send(Ok(())); Ok(()) } Ok(_) | Err(_) => { sender.send(Err(())); Err(Error::AsyncRuntimeError) } } } _start_test(test, result_checker).await } #[tokio::test] async fn send_task() -> Result<()> { fn test(client_rcv: Receiver<ComputeResult>, port: Port) -> Result<()> { // Mock data: let func = Fn!( move |(task_context, iter): (TaskContext, Box<dyn Iterator<Item = u8>>)| -> u8 { // let iter = iter.collect::<Vec<u8>>(); // eprintln!("{:?}", iter); iter.into_iter().next().unwrap() } ); let mock_task: TaskOption = create_test_task(func).into(); let ser_task = bincode::serialize(&mock_task)?; let mut message = capnp::message::Builder::new_default(); let mut msg_data = message.init_root::<serialized_data::Builder>(); msg_data.set_msg(&ser_task); let mut buf = Vec::new(); capnp::serialize::write_message(&mut buf, &message).map_err(Error::OutputWrite)?; let end = Instant::now() + Duration::from_millis(150); while Instant::now() < end { match client_rcv.try_recv() { Ok(Ok(_)) => return Ok(()), Ok(Err(_)) => return Err(Error::AsyncRuntimeError), _ => {} } if let Ok(mut stream) = connect_to_executor(port, false) { // Send task to executor: stream.write_all(&*buf).map_err(Error::OutputWrite)?; if let Ok(Err(_)) = client_rcv.try_recv() { return Err(Error::AsyncRuntimeError); } // Get the results back: if let Ok(res) = capnp::serialize::read_message(&mut stream, CAPNP_BUF_READ_OPTS) { let task_data = res.get_root::<serialized_data::Reader>().unwrap(); match bincode::deserialize::<TaskResult>(&*task_data.get_msg().unwrap())? { TaskResult::ResultTask(_) => {} _ => return Err(Error::DowncastFailure("incorrect task result")), } let mut signal_handler = connect_to_executor(port, true)?; send_shutdown_signal_msg(&mut signal_handler)?; return Ok(()); } else { return Err(Error::AsyncRuntimeError); } } thread::sleep_ms(5); } Err(Error::AsyncRuntimeError) }; fn result_checker(sender: Sender<ComputeResult>, result: Result<Signal>) -> Result<()> { match result { Ok(Signal::ShutDownGracefully) => Ok(()), Ok(_) => { sender.send(Ok(())); Err(Error::AsyncRuntimeError) } Err(err) => { sender.send(Err(())); Err(err) } } } _start_test(test, result_checker).await } } <file_sep>#![allow(where_clauses_object_safety, clippy::single_component_path_imports)] #[macro_use] extern crate serde_closure; #[macro_use] extern crate itertools; use chrono::prelude::*; use native_spark::*; use parquet::column::reader::get_typed_column_reader; use parquet::data_type::{ByteArrayType, Int32Type, Int64Type}; use parquet::file::reader::{FileReader, SerializedFileReader}; use std::fs::File; use std::path::PathBuf; fn main() -> Result<()> { let context = Context::new()?; let deserializer = Fn!(|file: PathBuf| read(file)); let files = context .read_source(LocalFsReaderConfig::new("./parquet_file_dir"), deserializer) .flat_map(Fn!( |iter: Vec<((i32, String, i64), (i64, f64))>| Box::new(iter.into_iter()) as Box<dyn Iterator<Item = _>> )); let sum = files.reduce_by_key(Fn!(|((vl, cl), (vr, cr))| (vl + vr, cl + cr)), 1); let avg = sum.map(Fn!(|(k, (v, c))| (k, v as f64 / c))); let res = avg.collect().unwrap(); println!("{:?}", &res[0]); Ok(()) } fn read(file: PathBuf) -> Vec<((i32, String, i64), (i64, f64))> { let file = File::open(file).unwrap(); let reader = SerializedFileReader::new(file).unwrap(); let metadata = reader.metadata(); let batch_size = 500_000 as usize; let iter = (0..metadata.num_row_groups()).flat_map(move |i| { let row_group_reader = reader.get_row_group(i).unwrap(); let mut first_reader = get_typed_column_reader::<Int32Type>(row_group_reader.get_column_reader(0).unwrap()); let mut second_reader = get_typed_column_reader::<ByteArrayType>( row_group_reader.get_column_reader(1).unwrap(), ); let mut bytes_reader = get_typed_column_reader::<Int64Type>(row_group_reader.get_column_reader(7).unwrap()); let mut time_reader = get_typed_column_reader::<Int64Type>(row_group_reader.get_column_reader(8).unwrap()); let num_rows = metadata.row_group(i).num_rows() as usize; println!("row group rows {}", num_rows); let mut chunks = vec![]; let mut batch_count = 0 as usize; while batch_count < num_rows { let begin = batch_count; let mut end = batch_count + batch_size; if end > num_rows { end = num_rows as usize; } chunks.push((begin, end)); batch_count = end; } println!("total rows-{} chunks-{:?}", num_rows, chunks); chunks.into_iter().flat_map(move |(begin, end)| { let end = end as usize; let begin = begin as usize; let mut first = vec![Default::default(); end - begin]; let mut second = vec![Default::default(); end - begin]; let mut time = vec![Default::default(); end - begin]; let mut bytes = vec![Default::default(); end - begin]; first_reader .read_batch(batch_size, None, None, &mut first) .unwrap(); second_reader .read_batch(batch_size, None, None, &mut second) .unwrap(); time_reader .read_batch(batch_size, None, None, &mut time) .unwrap(); bytes_reader .read_batch(batch_size, None, None, &mut bytes) .unwrap(); let first = first.into_iter(); let second = second .into_iter() .map(|x| unsafe { String::from_utf8_unchecked(x.data().to_vec()) }); let time = time.into_iter().map(|t| { let t = t / 1000; i64::from(Utc.timestamp(t, 0).hour()) }); let bytes = bytes.into_iter().map(|b| (b, 1.0)); let key = izip!(first, second, time); let value = bytes; key.zip(value) }) }); iter.collect() } <file_sep>[package] name = "native_spark" version = "0.1.0" authors = ["raja <<EMAIL>>"] edition = "2018" build = "build.rs" [lib] name = "native_spark" [features] aws_connectors = ["rusoto_core", "rusoto_s3"] [dependencies] crossbeam = "0.7.3" dashmap = "^3.5.1" envy = "^0.4.1" fasthash = "0.4.0" futures = "0.3" hyper = "0.13.4" http = "0.2.1" itertools = "0.9.0" num_cpus = "1.12.0" log = "0.4.8" once_cell = "1.3.1" parking_lot = { version = "0.10.0", features = ["serde"] } simplelog = "0.7.4" thiserror = "1.0.13" threadpool = "1.7.1" toml = "0.5.6" tokio = { version = "^0.2", features = ["rt-threaded", "stream", "sync", "time", "macros"] } tokio-util = { version = "0.3.1", features = ["compat"] } uuid = { version = "0.8", features = ["v4"] } regex = "1.3.6" # randomness rand = "0.7.3" rand_distr = "0.2" rand_pcg = "0.2" # serialization bincode = "1.2.1" capnp = "0.12.1" capnp-futures = "0.12.0" serde = { version = "1.0.105", features = ["rc"] } serde_closure = "^0.2.9" serde_derive = "1.0.105" uriparse = "0.6.1" # dynamic typing downcast-rs = "1.1.1" dyn-clone = "1.0.1" serde_traitobject = "0.2.4" # optional features ## aws rusoto_core = { version = "0.43", optional = true } rusoto_s3 = { version = "0.43", optional = true } [build-dependencies] capnpc = "0.12.1" [dev-dependencies] async-std = { version = "1.5.0", features = ["attributes"] } chrono = "0.4.11" parquet = "0.15.1" tempfile = "3" tokio = { version = "^0.2", features = ["macros"] } <file_sep>use std::cmp::Ordering; use std::net::Ipv4Addr; use crate::result_task::ResultTask; use crate::serializable_traits::{Data, SerFunc}; use crate::shuffle::ShuffleMapTask; use downcast_rs::Downcast; use serde_derive::{Deserialize, Serialize}; use serde_traitobject::{Deserialize, Serialize}; pub struct TaskContext { pub stage_id: usize, pub split_id: usize, pub attempt_id: usize, } impl TaskContext { pub fn new(stage_id: usize, split_id: usize, attempt_id: usize) -> Self { TaskContext { stage_id, split_id, attempt_id, } } } pub trait TaskBase: Downcast + Send + Sync { fn get_run_id(&self) -> usize; fn get_stage_id(&self) -> usize; fn get_task_id(&self) -> usize; fn is_pinned(&self) -> bool { false } fn preferred_locations(&self) -> Vec<Ipv4Addr> { Vec::new() } fn generation(&self) -> Option<i64> { None } } impl_downcast!(TaskBase); impl PartialOrd for dyn TaskBase { fn partial_cmp(&self, other: &dyn TaskBase) -> Option<Ordering> { Some(self.get_task_id().cmp(&other.get_task_id())) } } impl PartialEq for dyn TaskBase { fn eq(&self, other: &dyn TaskBase) -> bool { self.get_task_id() == other.get_task_id() } } impl Eq for dyn TaskBase {} impl Ord for dyn TaskBase { fn cmp(&self, other: &dyn TaskBase) -> Ordering { self.get_task_id().cmp(&other.get_task_id()) } } pub trait Task: TaskBase + Send + Sync + Downcast { fn run(&self, id: usize) -> serde_traitobject::Box<dyn serde_traitobject::Any + Send + Sync>; } impl_downcast!(Task); pub trait TaskBox: Task + Serialize + Deserialize + 'static + Downcast {} impl<K> TaskBox for K where K: Task + Serialize + Deserialize + 'static {} impl_downcast!(TaskBox); #[derive(Serialize, Deserialize)] pub enum TaskOption { #[serde(with = "serde_traitobject")] ResultTask(Box<dyn TaskBox>), #[serde(with = "serde_traitobject")] ShuffleMapTask(Box<dyn TaskBox>), } impl<T: Data, U: Data, F> From<ResultTask<T, U, F>> for TaskOption where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { fn from(t: ResultTask<T, U, F>) -> Self { TaskOption::ResultTask(Box::new(t) as Box<dyn TaskBox>) } } impl From<ShuffleMapTask> for TaskOption { fn from(t: ShuffleMapTask) -> Self { TaskOption::ResultTask(Box::new(t)) } } #[derive(Serialize, Deserialize)] pub enum TaskResult { ResultTask(serde_traitobject::Box<dyn serde_traitobject::Any + Send + Sync>), ShuffleTask(serde_traitobject::Box<dyn serde_traitobject::Any + Send + Sync>), } impl TaskOption { pub fn run(&self, id: usize) -> TaskResult { match self { TaskOption::ResultTask(tsk) => TaskResult::ResultTask(tsk.run(id)), TaskOption::ShuffleMapTask(tsk) => TaskResult::ShuffleTask(tsk.run(id)), } } pub fn get_task_id(&self) -> usize { match self { TaskOption::ResultTask(tsk) => tsk.get_task_id(), TaskOption::ShuffleMapTask(tsk) => tsk.get_task_id(), } } pub fn get_run_id(&self) -> usize { match self { TaskOption::ResultTask(tsk) => tsk.get_run_id(), TaskOption::ShuffleMapTask(tsk) => tsk.get_run_id(), } } pub fn get_stage_id(&self) -> usize { match self { TaskOption::ResultTask(tsk) => tsk.get_stage_id(), TaskOption::ShuffleMapTask(tsk) => tsk.get_stage_id(), } } } <file_sep>use crate::dependency::ShuffleDependencyTrait; use crate::env; use crate::rdd::RddBase; use crate::task::{Task, TaskBase}; use serde_derive::{Deserialize, Serialize}; use std::fmt::Display; use std::net::Ipv4Addr; use std::sync::Arc; #[derive(Serialize, Deserialize, Clone)] pub(crate) struct ShuffleMapTask { pub task_id: usize, pub run_id: usize, pub stage_id: usize, #[serde(with = "serde_traitobject")] pub rdd: Arc<dyn RddBase>, pinned: bool, #[serde(with = "serde_traitobject")] pub dep: Arc<dyn ShuffleDependencyTrait>, pub partition: usize, pub locs: Vec<Ipv4Addr>, } impl ShuffleMapTask { pub fn new( task_id: usize, run_id: usize, stage_id: usize, rdd: Arc<dyn RddBase>, dep: Arc<dyn ShuffleDependencyTrait>, partition: usize, locs: Vec<Ipv4Addr>, ) -> Self { ShuffleMapTask { task_id, run_id, stage_id, pinned: rdd.is_pinned(), rdd, dep, partition, locs, } } } impl Display for ShuffleMapTask { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "ShuffleMapTask({:?}, {:?})", self.stage_id, self.partition ) } } impl TaskBase for ShuffleMapTask { fn get_run_id(&self) -> usize { self.run_id } fn get_stage_id(&self) -> usize { self.stage_id } fn get_task_id(&self) -> usize { self.task_id } fn is_pinned(&self) -> bool { self.pinned } fn preferred_locations(&self) -> Vec<Ipv4Addr> { self.locs.clone() } fn generation(&self) -> Option<i64> { Some(env::Env::get().map_output_tracker.get_generation()) } } impl Task for ShuffleMapTask { fn run(&self, _id: usize) -> serde_traitobject::Box<dyn serde_traitobject::Any + Send + Sync> { serde_traitobject::Box::new(self.dep.do_shuffle_task(self.rdd.clone(), self.partition)) as serde_traitobject::Box<dyn serde_traitobject::Any + Send + Sync> } } <file_sep>use crate::serializable_traits::Data; use downcast_rs::Downcast; use fasthash::MetroHasher; use serde_derive::{Deserialize, Serialize}; use serde_traitobject::{Deserialize, Serialize}; use std::any::Any; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; /// Partitioner trait for creating Rdd partitions pub trait Partitioner: Downcast + Send + Sync + dyn_clone::DynClone + Serialize + Deserialize { fn equals(&self, other: &dyn Any) -> bool; fn get_num_of_partitions(&self) -> usize; fn get_partition(&self, key: &dyn Any) -> usize; } dyn_clone::clone_trait_object!(Partitioner); fn hash<T: Hash>(t: &T) -> u64 { let mut s: MetroHasher = Default::default(); t.hash(&mut s); s.finish() } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HashPartitioner<K: Data + Hash + Eq> { partitions: usize, _marker: PhantomData<K>, } // Hash partitioner implementing naive hash function. impl<K: Data + Hash + Eq> HashPartitioner<K> { pub fn new(partitions: usize) -> Self { HashPartitioner { partitions, _marker: PhantomData, } } } impl<K: Data + Hash + Eq> Partitioner for HashPartitioner<K> { fn equals(&self, other: &dyn Any) -> bool { if let Some(hp) = other.downcast_ref::<HashPartitioner<K>>() { self.partitions == hp.partitions } else { false } } fn get_num_of_partitions(&self) -> usize { self.partitions } fn get_partition(&self, key: &dyn Any) -> usize { let key = key.downcast_ref::<K>().unwrap(); hash(key) as usize % self.partitions } } #[cfg(test)] mod tests { use super::*; #[test] fn hash_partition() { let data = vec![1, 2]; let num_partition = 3; let hash_partitioner = HashPartitioner::<i32>::new(num_partition); for i in &data { println!("value: {:?}-hash: {:?}", i, hash(i)); println!( "value: {:?}-index: {:?}", i, hash_partitioner.get_partition(i) ); } let mut partition = vec![Vec::new(); num_partition]; for i in &data { let index = hash_partitioner.get_partition(i); partition[index].push(i) } assert_eq!(partition.len(), 3) } #[test] fn hash_partitioner_eq() { let p1 = HashPartitioner::<i32>::new(1); let p2_1 = HashPartitioner::<i32>::new(2); let p2_2 = HashPartitioner::<i32>::new(2); assert!(p1.equals(&p1)); assert!(p1.clone().equals(&p1)); assert!(p2_1.equals(&p2_1)); assert!(p2_1.equals(&p2_2)); assert!(p2_2.equals(&p2_1)); assert!(!p1.equals(&p2_1)); assert!(!p1.equals(&p2_2)); let mut p1 = Some(p1); assert!(p1.clone().map(|p| (&p).equals(&p1.clone().unwrap())) == Some(true)); assert!(p1.clone().map(|p| p.equals(&p2_1.clone())) == Some(false)); assert!(p1.clone().map(|p| p.equals(&p2_2.clone())) == Some(false)); assert!(p1.clone().map(|p| p.equals(&p1.clone().unwrap())) != None); assert!(p1 .clone() .map_or(false, |p| (&p).equals(&p1.clone().unwrap()))); assert!(!p1.clone().map_or(false, |p| p.equals(&p2_1.clone()))); assert!(!p1.clone().map_or(false, |p| p.equals(&p2_2.clone()))); p1 = None; assert!(p1.clone().map(|p| p.equals(&p1.clone().unwrap())) == None); assert!(p1.clone().map(|p| p.equals(&p2_1.clone())) == None); assert!(p1.clone().map(|p| p.equals(&p2_2.clone())) == None); assert!(!p1 .clone() .map_or(false, |p| (&p).equals(&p1.clone().unwrap()))); assert!(!p1.clone().map_or(false, |p| p.equals(&p2_1.clone()))); assert!(!p1.map_or(false, |p| p.equals(&p2_2.clone()))); let p2_1 = Box::new(p2_1) as Box<dyn Partitioner>; let p2_2 = Box::new(p2_2) as Box<dyn Partitioner>; assert!(p2_1.equals((&*p2_2).as_any())) } } <file_sep>use native_spark::*; use std::sync::Arc; extern crate serde_closure; use once_cell::sync::Lazy; static CONTEXT: Lazy<Arc<Context>> = Lazy::new(|| Context::new().unwrap()); #[test] fn test_group_by() { let sc = CONTEXT.clone(); let vec = vec![ ("x".to_string(), 1), ("x".to_string(), 2), ("x".to_string(), 3), ("x".to_string(), 4), ("x".to_string(), 5), ("x".to_string(), 6), ("x".to_string(), 7), ("y".to_string(), 1), ("y".to_string(), 2), ("y".to_string(), 3), ("y".to_string(), 4), ("y".to_string(), 5), ("y".to_string(), 6), ("y".to_string(), 7), ("y".to_string(), 8), ]; let r = sc.make_rdd(vec, 4); let g = r.group_by_key(4); let mut res = g.collect().unwrap(); res.sort(); let expected = vec![ ("x".to_string(), vec![1, 2, 3, 4, 5, 6, 7]), ("y".to_string(), vec![1, 2, 3, 4, 5, 6, 7, 8]), ]; assert_eq!(expected, res); } #[test] fn test_join() { let sc = CONTEXT.clone(); let col1 = vec![ (1, ("A".to_string(), "B".to_string())), (2, ("C".to_string(), "D".to_string())), (3, ("E".to_string(), "F".to_string())), (4, ("G".to_string(), "H".to_string())), ]; let col1 = sc.clone().parallelize(col1, 4); let col2 = vec![ (1, "A1".to_string()), (1, "A2".to_string()), (2, "B1".to_string()), (2, "B2".to_string()), (3, "C1".to_string()), (3, "C2".to_string()), ]; let col2 = sc.parallelize(col2, 4); let inner_joined_rdd = col2.join(col1.clone(), 4); let mut res = inner_joined_rdd.collect().unwrap(); println!("res {:?}", res); res.sort(); let expected = vec![ (1, "A1", "A", "B"), (1, "A2", "A", "B"), (2, "B1", "C", "D"), (2, "B2", "C", "D"), (3, "C1", "E", "F"), (3, "C2", "E", "F"), ] .iter() .map(|tuple| { ( tuple.0, ( tuple.1.to_string(), (tuple.2.to_string(), tuple.3.to_string()), ), ) }) .collect::<Vec<_>>(); assert_eq!(expected, res); } <file_sep>version: '3.7' networks: native-spark: services: ns_master: image: native_spark:latest ports: - "3000" tty: true networks: native-spark: volumes: - type: "bind" source: "../target" target: "/home/dev" environment: NS_DEPLOYMENT_MODE: distributed depends_on: - ns_worker ns_worker: image: native_spark:latest ports: - "10500" - "22" tty: true networks: native-spark: <file_sep>use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; use std::net::Ipv4Addr; use std::sync::atomic::{AtomicUsize, Ordering as SyncOrd}; use std::sync::Arc; use parking_lot::Mutex; use rand::Rng; use serde_derive::{Deserialize, Serialize}; use serde_traitobject::{Arc as SerArc, Box as SerBox, Deserialize, Serialize}; use crate::context::Context; use crate::dependency::{Dependency, NarrowDependencyTrait}; use crate::error::{Error, Result}; use crate::rdd::{Rdd, RddBase, RddVals}; use crate::serializable_traits::{AnyData, Data}; use crate::split::Split; use crate::utils; /// Class that captures a coalesced RDD by essentially keeping track of parent partitions. #[derive(Serialize, Deserialize, Clone)] struct CoalescedRddSplit { index: usize, #[serde(with = "serde_traitobject")] rdd: Arc<dyn RddBase>, parent_indices: Vec<usize>, preferred_location: Option<PrefLoc>, } impl CoalescedRddSplit { fn new( index: usize, preferred_location: Option<PrefLoc>, rdd: Arc<dyn RddBase>, parent_indices: Vec<usize>, ) -> Self { CoalescedRddSplit { index, preferred_location, rdd, parent_indices, } } /// Computes the fraction of the parents partitions containing preferred_location within /// their preferred_locs. /// /// Returns locality of this coalesced partition between 0 and 1. fn local_fraction(&self) -> f64 { if self.parent_indices.is_empty() { 0.0 } else { let mut loc = 0u32; let pl: Ipv4Addr = self.preferred_location.unwrap().into(); for p in self.rdd.splits() { let parent_pref_locs = self.rdd.preferred_locations(p); if parent_pref_locs.contains(&pl) { loc += 1; } } loc as f64 / self.parent_indices.len() as f64 } } fn downcasting(split: Box<dyn Split>) -> Box<CoalescedRddSplit> { split .downcast::<CoalescedRddSplit>() .or(Err(Error::DowncastFailure("CoalescedRddSplit"))) .unwrap() } } impl Split for CoalescedRddSplit { fn get_index(&self) -> usize { self.index } } #[derive(Serialize, Deserialize)] struct CoalescedSplitDep { #[serde(with = "serde_traitobject")] rdd: Arc<dyn RddBase>, #[serde(with = "serde_traitobject")] prev: Arc<dyn RddBase>, } impl CoalescedSplitDep { fn new(rdd: Arc<dyn RddBase>, prev: Arc<dyn RddBase>) -> CoalescedSplitDep { CoalescedSplitDep { rdd, prev } } } impl NarrowDependencyTrait for CoalescedSplitDep { fn get_parents(&self, partition_id: usize) -> Vec<usize> { self.rdd .splits() .into_iter() .enumerate() .find(|(i, _)| i == &partition_id) .map(|(_, p)| CoalescedRddSplit::downcasting(p)) .unwrap() .parent_indices } fn get_rdd_base(&self) -> Arc<dyn RddBase> { // this method is called on the scheduler on get_preferred_locs // and is expected to return the previous dependency self.prev.clone() } } /// Represents a coalesced RDD that has fewer partitions than its parent RDD /// /// This type uses the PartitionCoalescer type to find a good partitioning of the parent RDD /// so that each new partition has roughly the same number of parent partitions and that /// the preferred location of each new partition overlaps with as many preferred locations of its /// parent partitions #[derive(Serialize, Deserialize, Clone)] pub struct CoalescedRdd<T> where T: Data, { vals: Arc<RddVals>, #[serde(with = "serde_traitobject")] parent: Arc<dyn Rdd<Item = T>>, max_partitions: usize, } impl<T: Data> CoalescedRdd<T> { /// ## Arguments /// /// max_partitions: number of desired partitions in the coalesced RDD pub(crate) fn new(prev: Arc<dyn Rdd<Item = T>>, max_partitions: usize) -> Self { let vals = RddVals::new(prev.get_context()); CoalescedRdd { vals: Arc::new(vals), parent: prev, max_partitions, } } } impl<T: Data> RddBase for CoalescedRdd<T> { fn splits(&self) -> Vec<Box<dyn Split>> { let partition_coalescer = DefaultPartitionCoalescer::default(); partition_coalescer .coalesce(self.max_partitions, self.parent.get_rdd_base()) .into_iter() .enumerate() .map(|(i, pg)| { let ids: Vec<_> = pg.partitions.iter().map(|p| p.get_index()).collect(); Box::new(CoalescedRddSplit::new( i, pg.preferred_location, self.parent.get_rdd_base(), ids, )) as Box<dyn Split> }) .collect() } fn get_rdd_id(&self) -> usize { self.vals.id } fn get_context(&self) -> Arc<Context> { self.vals.context.upgrade().unwrap() } fn get_dependencies(&self) -> Vec<Dependency> { vec![Dependency::NarrowDependency( Arc::new(CoalescedSplitDep::new( self.get_rdd_base(), self.parent.get_rdd_base(), )) as Arc<dyn NarrowDependencyTrait>, )] } /// Returns the preferred machine for the partition. If split is of type CoalescedRddSplit, /// then the preferred machine will be one which most parent splits prefer too. fn preferred_locations(&self, split: Box<dyn Split>) -> Vec<Ipv4Addr> { let split = CoalescedRddSplit::downcasting(split); if let Some(loc) = split.preferred_location { vec![loc.into()] } else { Vec::new() } } default fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { Ok(Box::new( self.iterator(split)? .map(|x| Box::new(x) as Box<dyn AnyData>), )) } } impl<T: Data> Rdd for CoalescedRdd<T> { type Item = T; fn get_rdd(&self) -> Arc<dyn Rdd<Item = Self::Item>> where Self: Sized, { Arc::new(self.clone()) } fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(self.clone()) as Arc<dyn RddBase> } fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { let split = CoalescedRddSplit::downcasting(split); let mut iter = Vec::new(); for (_, p) in self .parent .splits() .into_iter() .enumerate() .filter(|(i, _)| split.parent_indices.contains(i)) { let it = self.parent.iterator(p)?; iter.push(it); } Ok(Box::new(iter.into_iter().flatten()) as Box<dyn Iterator<Item = Self::Item>>) } } type SplitIdx = usize; /// A PartitionCoalescer defines how to coalesce the partitions of a given RDD. pub trait PartitionCoalescer: Serialize + Deserialize + Send + Sync { // FIXME: Decide upon this really requiring any of those trait bounds. // The implementation in Scala embeeds the coalescer into the rdd itself, so on initial // transliteration this was added. But in reality the only moment this being called // is upon task computation in the driver at the main thread in a completely synchronous and // single-threaded environment under the splits subroutine. // With the current implementation all those required traits could be dropped entirely. /// Coalesce the partitions of the given RDD. /// /// ## Arguments /// /// * max_partitions: the maximum number of partitions to have after coalescing /// * parent: the parent RDD whose partitions to coalesce /// /// ## Return /// /// A vec of `PartitionGroup`s, where each element is itself a vector of /// `Partition`s and represents a partition after coalescing is performed. fn coalesce(self, max_partitions: usize, parent: Arc<dyn RddBase>) -> Vec<PartitionGroup>; } #[derive(Debug, Clone, Serialize, Deserialize, Copy)] struct PrefLoc(u32); impl Into<Ipv4Addr> for PrefLoc { fn into(self) -> Ipv4Addr { Ipv4Addr::from(self.0) } } impl From<Ipv4Addr> for PrefLoc { fn from(other: Ipv4Addr) -> PrefLoc { PrefLoc(other.into()) } } #[derive(Serialize, Deserialize)] pub struct PartitionGroup { id: usize, /// preferred location for the partition group preferred_location: Option<PrefLoc>, partitions: Vec<SerBox<dyn Split>>, } impl PartitionGroup { fn new(preferred_location: Option<Ipv4Addr>, id: usize) -> Self { PartitionGroup { id, preferred_location: preferred_location.map(|pl| pl.into()), partitions: vec![], } } fn num_partitions(&self) -> usize { self.partitions.len() } } impl PartialEq for PartitionGroup { fn eq(&self, other: &Self) -> bool { self.id == other.id } } impl Eq for PartitionGroup {} impl PartialOrd for PartitionGroup { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for PartitionGroup { fn cmp(&self, other: &Self) -> Ordering { self.num_partitions().cmp(&other.num_partitions()) } } // Coalesce the partitions of a parent RDD (`prev`) into fewer partitions, so that each partition of // this RDD computes one or more of the parent ones. It will produce exactly `max_partitions` if the // parent had more than max_partitions, or fewer if the parent had fewer. // // This transformation is useful when an RDD with many partitions gets filtered into a smaller one, // or to avoid having a large number of small tasks when processing a directory with many files. // // If there is no locality information (no preferred_locations) in the parent, then the coalescing // is very simple: chunk parents that are close in the array in chunks. // If there is locality information, it proceeds to pack them with the following four goals: // // (1) Balance the groups so they roughly have the same number of parent partitions // (2) Achieve locality per partition, i.e. find one machine which most parent partitions prefer // (3) Be efficient, i.e. O(n) algorithm for n parent partitions (problem is likely NP-hard) // (4) Balance preferred machines, i.e. avoid as much as possible picking the same preferred machine // // Furthermore, it is assumed that the parent RDD may have many partitions, e.g. 100 000. // We assume the final number of desired partitions is small, e.g. less than 1000. // // The algorithm tries to assign unique preferred machines to each partition. If the number of // desired partitions is greater than the number of preferred machines (can happen), it needs to // start picking duplicate preferred machines. This is determined using coupon collector estimation // (2n log(n)). The load balancing is done using power-of-two randomized bins-balls with one twist: // it tries to also achieve locality. This is done by allowing a slack (balanceSlack, where // 1.0 is all locality, 0 is all balance) between two bins. If two bins are within the slack // in terms of balance, the algorithm will assign partitions according to locality. #[derive(Clone)] struct PartitionLocations { /// contains all the partitions from the previous RDD that don't have preferred locations parts_without_locs: Vec<Box<dyn Split>>, /// contains all the partitions from the previous RDD that have preferred locations parts_with_locs: Vec<(Ipv4Addr, Box<dyn Split>)>, } impl PartitionLocations { fn new(prev: Arc<dyn RddBase>) -> Self { // Gets all the preferred locations of the previous RDD and splits them into partitions // with preferred locations and ones without let mut tmp_parts_with_loc: Vec<(Box<dyn Split>, Vec<Ipv4Addr>)> = Vec::new(); let mut parts_without_locs = vec![]; let mut parts_with_locs = vec![]; // first get the locations for each partition, only do this once since it can be expensive prev.splits().into_iter().for_each(|p| { let locs = Self::current_pref_locs(p.clone(), &*prev); if !locs.is_empty() { tmp_parts_with_loc.push((p, locs)); } else { parts_without_locs.push(p); } }); // convert it into an array of host to partition for x in 0..=2 { for (part, locs) in tmp_parts_with_loc.iter() { if locs.len() > x { parts_with_locs.push((locs[x], part.clone())) } } } PartitionLocations { parts_without_locs, parts_with_locs, } } /// Gets the *current* preferred locations from the DAGScheduler (as opposed to the static ones). fn current_pref_locs(part: Box<dyn Split>, prev: &dyn RddBase) -> Vec<Ipv4Addr> { //TODO: this is inefficient and likely to happen in more places, //we should add a preferred_locs method that takes split by ref (&dyn Split) not by value prev.preferred_locations(part) } } /// A group of `Partition`s #[derive(Serialize, Deserialize)] struct PSyncGroup(Mutex<PartitionGroup>); impl std::convert::From<PartitionGroup> for PSyncGroup { fn from(origin: PartitionGroup) -> Self { PSyncGroup(Mutex::new(origin)) } } impl std::ops::Deref for PSyncGroup { type Target = Mutex<PartitionGroup>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Clone, Serialize, Deserialize)] struct DefaultPartitionCoalescer { balance_slack: f64, /// each element of group arr represents one coalesced partition group_arr: Vec<SerArc<PSyncGroup>>, /// hash used to check whether some machine is already in group_arr group_hash: HashMap<Ipv4Addr, Vec<SerArc<PSyncGroup>>>, /// hash used for the first max_partitions (to avoid duplicates) initial_hash: HashSet<SplitIdx>, /// true if no preferred_locations exists for parent RDD no_locality: bool, } impl Default for DefaultPartitionCoalescer { fn default() -> Self { DefaultPartitionCoalescer { balance_slack: 0.10, group_arr: Vec::new(), group_hash: HashMap::new(), initial_hash: HashSet::new(), no_locality: true, } } } impl DefaultPartitionCoalescer { fn new(balance_slack: Option<f64>) -> Self { if let Some(slack) = balance_slack { DefaultPartitionCoalescer { balance_slack: slack, group_arr: Vec::new(), group_hash: HashMap::new(), initial_hash: HashSet::new(), no_locality: true, } } else { Self::default() } } fn add_part_to_pgroup(&mut self, part: SerBox<dyn Split>, pgroup: &mut PartitionGroup) -> bool { if !self.initial_hash.contains(&part.get_index()) { self.initial_hash.insert(part.get_index()); // needed to avoid assigning partitions to multiple buckets pgroup.partitions.push(part); // already assign this element true } else { false } } /// Gets the least element of the list associated with key in group_hash /// The returned PartitionGroup is the least loaded of all groups that represent the machine "key" fn get_least_group_hash(&self, key: Ipv4Addr) -> Option<SerArc<PSyncGroup>> { let mut current_min: Option<SerArc<PSyncGroup>> = None; if let Some(group) = self.group_hash.get(&key) { for g in group.as_slice() { if let Some(ref cmin) = current_min { if *cmin.lock() > *g.lock() { current_min = Some((*g).clone()); } } } } current_min } /// Initializes target_len partition groups. If there are preferred locations, each group /// is assigned a preferred location. This uses coupon collector to estimate how many /// preferred locations it must rotate through until it has seen most of the preferred /// locations (2 * n log(n)) /// /// ## Arguments /// /// * target_len - the number of desired partition groups #[allow(clippy::map_entry)] fn setup_groups(&mut self, target_len: usize, partition_locs: &mut PartitionLocations) { let mut rng = utils::random::get_default_rng(); let part_cnt = AtomicUsize::new(0); // deal with empty case, just create target_len partition groups with no preferred location if partition_locs.parts_with_locs.is_empty() { for _ in 1..=target_len { self.group_arr .push(SerArc::new(PSyncGroup(Mutex::new(PartitionGroup::new( None, part_cnt.fetch_add(1, SyncOrd::SeqCst), ))))) } return; } self.no_locality = false; // number of iterations needed to be certain that we've seen most preferred locations let expected_coupons_2 = { let target_len = target_len as f64; 2 * (target_len.ln() * target_len + target_len + 0.5f64) as u64 }; let mut num_created = 0; let mut tries = 0; // rotate through until either target_len unique/distinct preferred locations have been created // OR (we have went through either all partitions OR we've rotated expected_coupons_2 - in // which case we have likely seen all preferred locations) let num_parts_to_look_at = expected_coupons_2.min(partition_locs.parts_with_locs.len() as u64); while num_created < target_len as u64 && tries < num_parts_to_look_at { let (nxt_replica, nxt_part) = &partition_locs.parts_with_locs[tries as usize]; tries += 1; if !self.group_hash.contains_key(&nxt_replica) { let mut pgroup = PartitionGroup::new(Some(*nxt_replica), part_cnt.fetch_add(1, SyncOrd::SeqCst)); self.add_part_to_pgroup(dyn_clone::clone_box(&**nxt_part).into(), &mut pgroup); self.group_hash.insert( *nxt_replica, vec![SerArc::new(PSyncGroup(Mutex::new(pgroup)))], ); // list in case we have multiple num_created += 1; } } // if we don't have enough partition groups, create duplicates while num_created < target_len as u64 { // Copy the preferred location from a random input partition. // This helps in avoiding skew when the input partitions are clustered by preferred location. let (nxt_replica, nxt_part) = &partition_locs.parts_with_locs [rng.gen_range(0, partition_locs.parts_with_locs.len()) as usize]; let pgroup = SerArc::new(PSyncGroup(Mutex::new(PartitionGroup::new( Some(*nxt_replica), part_cnt.fetch_add(1, SyncOrd::SeqCst), )))); self.add_part_to_pgroup( dyn_clone::clone_box(&**nxt_part).into(), &mut *pgroup.lock(), ); self.group_hash .entry(*nxt_replica) .or_insert_with(Vec::new) .push(pgroup.clone()); self.group_arr.push(pgroup); num_created += 1; } } /// Takes a parent RDD partition and decides which of the partition groups to put it in /// Takes locality into account, but also uses power of 2 choices to load balance /// It strikes a balance between the two using the balance_slack variable /// /// ## Arguments /// /// * p: partition (ball to be thrown) /// * balance_slack: determines the trade-off between load-balancing the partitions sizes and /// their locality. e.g., balance_slack=0.10 means that it allows up to 10% /// imbalance in favor of locality fn pick_bin( &mut self, p: Box<dyn Split>, prev: &dyn RddBase, balance_slack: f64, ) -> SerArc<PSyncGroup> { let mut rnd = utils::random::get_default_rng(); let slack = balance_slack * prev.number_of_splits() as f64; // least loaded pref_locs let pref: Vec<_> = PartitionLocations::current_pref_locs(p, prev) .into_iter() .map(|i| self.get_least_group_hash(i)) .collect(); let pref_part = if pref.is_empty() { None } else { let mut min: Option<SerArc<PSyncGroup>> = None; for pl in pref.into_iter().flatten() { if let Some(ref pl_min) = min { if *pl.lock() < *pl_min.lock() { min = Some(pl) } } else { min = Some(pl); } } min // pref.iter().enumerate().map(|i| &*(***i).lock()).min() }; let r1 = rnd.gen_range(0, self.group_arr.len()); let r2 = rnd.gen_range(0, self.group_arr.len()); let min_power_of_two = { if self.group_arr[r1].lock().num_partitions() < self.group_arr[r2].lock().num_partitions() { self.group_arr[r1].clone() } else { self.group_arr[r2].clone() } }; if let Some(pref_part_actual) = pref_part { // more imbalance than the slack allows if min_power_of_two.lock().num_partitions() + slack as usize <= pref_part_actual.lock().num_partitions() { min_power_of_two // prefer balance over locality } else { pref_part_actual // prefer locality over balance } } else { // if no preferred locations, just use basic power of two min_power_of_two } } fn throw_balls( &mut self, max_partitions: usize, prev: Arc<dyn RddBase>, balance_slack: f64, mut partition_locs: PartitionLocations, ) { if self.no_locality { // no preferred_locations in parent RDD, no randomization needed if max_partitions > self.group_arr.len() { // just return prev.partitions for (i, p) in prev.splits().into_iter().enumerate() { self.group_arr[i].lock().partitions.push(p.into()); } } else { // no locality available, then simply split partitions based on positions in array let prev_splits = prev.splits(); let chunk_size = (prev_splits.len() as f64 / max_partitions as f64).floor() as usize; let mut chunk = 0; for (i, e) in prev_splits.into_iter().enumerate() { if i % chunk_size == 0 && chunk + 1 < max_partitions && i != 0 { chunk += 1; } self.group_arr[chunk].lock().partitions.push(e.into()); } } } else { // It is possible to have unionRDD where one rdd has preferred locations and another rdd // that doesn't. To make sure we end up with the requested number of partitions, // make sure to put a partition in every group. // if we don't have a partition assigned to every group first try to fill them // with the partitions with preferred locations let mut part_iter = partition_locs.parts_with_locs.drain(..).peekable(); for pg in self .group_arr .iter() .filter(|pg| pg.lock().num_partitions() == 0) { while part_iter.peek().is_some() && pg.lock().num_partitions() == 0 { let (_, nxt_part) = part_iter.next().unwrap(); if !self.initial_hash.contains(&nxt_part.get_index()) { self.initial_hash.insert(nxt_part.get_index()); pg.lock().partitions.push(nxt_part.into()); } } } // if we didn't get one partitions per group from partitions with preferred locations // use partitions without preferred locations let mut part_no_loc_iter = partition_locs.parts_without_locs.drain(..).peekable(); for pg in self .group_arr .iter() .filter(|pg| pg.lock().num_partitions() == 0) { while part_no_loc_iter.peek().is_some() && pg.lock().num_partitions() == 0 { let nxt_part = part_no_loc_iter.next().unwrap(); if !self.initial_hash.contains(&nxt_part.get_index()) { self.initial_hash.insert(nxt_part.get_index()); pg.lock().partitions.push(nxt_part.into()); } } } // finally pick bin for the rest for p in prev.splits().into_iter() { if !self.initial_hash.contains(&p.get_index()) { // throw every partition into group self.pick_bin(p.clone(), &*prev, balance_slack) .lock() .partitions .push(SerBox::from(p)); } } } } fn get_partitions(self) -> Vec<PartitionGroup> { self.group_arr .into_iter() .filter(|pg| pg.lock().num_partitions() > 0) .map(|pg: SerArc<PSyncGroup>| { let pg: PSyncGroup = Arc::try_unwrap(pg.into()) .map_err(|_| "Not unique reference.") .unwrap(); pg.0.into_inner() }) .collect() } } impl PartitionCoalescer for DefaultPartitionCoalescer { /// Runs the packing algorithm and returns an array of InnerPGroups that if possible are /// load balanced and grouped by locality fn coalesce(mut self, max_partitions: usize, prev: Arc<dyn RddBase>) -> Vec<PartitionGroup> { let mut partition_locs = PartitionLocations::new(prev.clone()); // setup the groups (bins) let target_len = prev.number_of_splits().min(max_partitions); self.setup_groups(target_len, &mut partition_locs); // assign partitions (balls) to each group (bins) self.throw_balls( max_partitions, prev.clone(), self.balance_slack, partition_locs, ); self.get_partitions() } } <file_sep>use std::any::Any; use std::hash::Hash; use std::hash::Hasher; use std::marker::PhantomData; use std::sync::Arc; use crate::aggregator::Aggregator; use crate::context::Context; use crate::dependency::{ Dependency, NarrowDependencyTrait, OneToOneDependency, ShuffleDependency, ShuffleDependencyTrait, }; use crate::env; use crate::error::Result; use crate::partitioner::Partitioner; use crate::rdd::{Rdd, RddBase, RddVals}; use crate::serializable_traits::{AnyData, Data}; use crate::shuffle::ShuffleFetcher; use crate::split::Split; use dashmap::DashMap; use serde_derive::{Deserialize, Serialize}; #[derive(Clone, Serialize, Deserialize)] enum CoGroupSplitDep { NarrowCoGroupSplitDep { #[serde(with = "serde_traitobject")] rdd: Arc<dyn RddBase>, #[serde(with = "serde_traitobject")] split: Box<dyn Split>, }, ShuffleCoGroupSplitDep { shuffle_id: usize, }, } #[derive(Clone, Serialize, Deserialize)] struct CoGroupSplit { index: usize, deps: Vec<CoGroupSplitDep>, } impl CoGroupSplit { fn new(index: usize, deps: Vec<CoGroupSplitDep>) -> Self { CoGroupSplit { index, deps } } } impl Hasher for CoGroupSplit { fn finish(&self) -> u64 { self.index as u64 } fn write(&mut self, bytes: &[u8]) { for i in bytes { self.write_u8(*i); } } } impl Split for CoGroupSplit { fn get_index(&self) -> usize { self.index } } #[derive(Clone, Serialize, Deserialize)] pub struct CoGroupedRdd<K: Data> { pub(crate) vals: Arc<RddVals>, pub(crate) rdds: Vec<serde_traitobject::Arc<dyn RddBase>>, #[serde(with = "serde_traitobject")] pub(crate) part: Box<dyn Partitioner>, _marker: PhantomData<K>, } impl<K: Data + Eq + Hash> CoGroupedRdd<K> { pub fn new(rdds: Vec<serde_traitobject::Arc<dyn RddBase>>, part: Box<dyn Partitioner>) -> Self { let context = rdds[0].get_context(); let mut vals = RddVals::new(context.clone()); let create_combiner = Box::new(Fn!(|v: Box<dyn AnyData>| vec![v])); fn merge_value( mut buf: Vec<Box<dyn AnyData>>, v: Box<dyn AnyData>, ) -> Vec<Box<dyn AnyData>> { buf.push(v); buf } let merge_value = Box::new(Fn!(|(buf, v)| merge_value(buf, v))); fn merge_combiners( mut b1: Vec<Box<dyn AnyData>>, mut b2: Vec<Box<dyn AnyData>>, ) -> Vec<Box<dyn AnyData>> { b1.append(&mut b2); b1 } let merge_combiners = Box::new(Fn!(|(b1, b2)| merge_combiners(b1, b2))); trait AnyDataWithEq: AnyData + PartialEq {} impl<T: AnyData + PartialEq> AnyDataWithEq for T {} let aggr = Arc::new( Aggregator::<K, Box<dyn AnyData>, Vec<Box<dyn AnyData>>>::new( create_combiner, merge_value, merge_combiners, ), ); let mut deps = Vec::new(); for (_index, rdd) in rdds.iter().enumerate() { let part = part.clone(); if rdd .partitioner() .map_or(false, |p| p.equals(&part as &dyn Any)) { let rdd_base = rdd.clone().into(); deps.push(Dependency::NarrowDependency( Arc::new(OneToOneDependency::new(rdd_base)) as Arc<dyn NarrowDependencyTrait>, )) } else { let rdd_base = rdd.clone().into(); log::debug!("creating aggregator inside cogrouprdd"); deps.push(Dependency::ShuffleDependency( Arc::new(ShuffleDependency::new( context.new_shuffle_id(), true, rdd_base, aggr.clone(), part, )) as Arc<dyn ShuffleDependencyTrait>, )) } } vals.dependencies = deps; let vals = Arc::new(vals); CoGroupedRdd { vals, rdds, part, _marker: PhantomData, } } } impl<K: Data + Eq + Hash> RddBase for CoGroupedRdd<K> { fn get_rdd_id(&self) -> usize { self.vals.id } fn get_context(&self) -> Arc<Context> { self.vals.context.upgrade().unwrap() } fn get_dependencies(&self) -> Vec<Dependency> { self.vals.dependencies.clone() } fn splits(&self) -> Vec<Box<dyn Split>> { let mut splits = Vec::new(); for i in 0..self.part.get_num_of_partitions() { splits.push(Box::new(CoGroupSplit::new( i, self.rdds .iter() .enumerate() .map(|(i, r)| match &self.get_dependencies()[i] { Dependency::ShuffleDependency(s) => { CoGroupSplitDep::ShuffleCoGroupSplitDep { shuffle_id: s.get_shuffle_id(), } } _ => CoGroupSplitDep::NarrowCoGroupSplitDep { rdd: r.clone().into(), split: r.splits()[i].clone(), }, }) .collect(), )) as Box<dyn Split>) } splits } fn number_of_splits(&self) -> usize { self.part.get_num_of_partitions() } fn partitioner(&self) -> Option<Box<dyn Partitioner>> { let part = self.part.clone() as Box<dyn Partitioner>; Some(part) } fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { Ok(Box::new(self.iterator(split)?.map(|(k, v)| { Box::new((k, Box::new(v) as Box<dyn AnyData>)) as Box<dyn AnyData> }))) } } impl<K: Data + Eq + Hash> Rdd for CoGroupedRdd<K> { type Item = (K, Vec<Vec<Box<dyn AnyData>>>); fn get_rdd(&self) -> Arc<dyn Rdd<Item = Self::Item>> { Arc::new(self.clone()) } fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(self.clone()) as Arc<dyn RddBase> } #[allow(clippy::type_complexity)] fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { if let Ok(split) = split.downcast::<CoGroupSplit>() { let agg: Arc<DashMap<K, Vec<Vec<Box<dyn AnyData>>>>> = Arc::new(DashMap::new()); let executor = env::Env::get_async_handle(); for (dep_num, dep) in split.clone().deps.into_iter().enumerate() { match dep { CoGroupSplitDep::NarrowCoGroupSplitDep { rdd, split } => { log::debug!("inside iterator CoGroupedRdd narrow dep"); for i in rdd.iterator_any(split)? { log::debug!( "inside iterator CoGroupedRdd narrow dep iterator any: {:?}", i ); let b = i .into_any() .downcast::<(Box<dyn AnyData>, Box<dyn AnyData>)>() .unwrap(); let (k, v) = *b; let k = *(k.into_any().downcast::<K>().unwrap()); agg.entry(k) .or_insert_with(|| vec![Vec::new(); self.rdds.len()])[dep_num] .push(v) } } CoGroupSplitDep::ShuffleCoGroupSplitDep { shuffle_id } => { log::debug!("inside iterator CoGroupedRdd shuffle dep, agg: {:?}", agg); let num_rdds = self.rdds.len(); let agg_clone = agg.clone(); let merge_pair = move |(k, c): (K, Vec<Box<dyn AnyData>>)| { let mut temp = agg_clone .entry(k) .or_insert_with(|| vec![Vec::new(); num_rdds]); for v in c { temp[dep_num].push(v); } }; let split_idx = split.get_index(); executor.enter(|| -> Result<()> { let fut = ShuffleFetcher::fetch(shuffle_id, split_idx, merge_pair); Ok(futures::executor::block_on(fut)?) })?; } } } let agg = Arc::try_unwrap(agg).unwrap(); Ok(Box::new(agg.into_iter().map(|(k, v)| (k, v)))) } else { panic!("Got split object from different concrete type other than CoGroupSplit") } } } <file_sep>use std::any::Any; use std::collections::{btree_set::BTreeSet, vec_deque::VecDeque, HashMap, HashSet}; use std::iter::FromIterator; use std::net::{Ipv4Addr, SocketAddrV4}; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use std::time::{Duration, Instant}; use crate::dag_scheduler::{CompletionEvent, TastEndReason}; use crate::dependency::ShuffleDependencyTrait; use crate::env; use crate::error::{Error, Result}; use crate::job::{Job, JobTracker}; use crate::local_scheduler::LocalScheduler; use crate::map_output_tracker::MapOutputTracker; use crate::rdd::{Rdd, RddBase}; use crate::result_task::ResultTask; use crate::scheduler::{EventQueue, NativeScheduler}; use crate::serializable_traits::{Data, SerFunc}; use crate::serialized_data_capnp::serialized_data; use crate::shuffle::ShuffleMapTask; use crate::stage::Stage; use crate::task::{TaskBase, TaskContext, TaskOption, TaskResult}; use crate::utils; use capnp::message::ReaderOptions; use capnp_futures::serialize as capnp_serialize; use dashmap::DashMap; use parking_lot::Mutex; use tokio::net::TcpStream; use tokio_util::compat::{Tokio02AsyncReadCompatExt, Tokio02AsyncWriteCompatExt}; const CAPNP_BUF_READ_OPTS: ReaderOptions = ReaderOptions { traversal_limit_in_words: std::u64::MAX, nesting_limit: 64, }; //just for now, creating an entire scheduler functions without dag scheduler trait. Later change it to extend from dag scheduler #[derive(Clone, Default)] pub struct DistributedScheduler { max_failures: usize, attempt_id: Arc<AtomicUsize>, resubmit_timeout: u128, poll_timeout: u64, event_queues: EventQueue, next_job_id: Arc<AtomicUsize>, next_run_id: Arc<AtomicUsize>, next_task_id: Arc<AtomicUsize>, next_stage_id: Arc<AtomicUsize>, stage_cache: Arc<DashMap<usize, Stage>>, shuffle_to_map_stage: Arc<DashMap<usize, Stage>>, cache_locs: Arc<DashMap<usize, Vec<Vec<Ipv4Addr>>>>, master: bool, framework_name: String, is_registered: bool, //TODO check if it is necessary active_jobs: HashMap<usize, Job>, active_job_queue: Vec<Job>, taskid_to_jobid: HashMap<String, usize>, taskid_to_slaveid: HashMap<String, String>, job_tasks: HashMap<usize, HashSet<String>>, slaves_with_executors: HashSet<String>, server_uris: Arc<Mutex<VecDeque<SocketAddrV4>>>, port: u16, map_output_tracker: MapOutputTracker, // TODO fix proper locking mechanism scheduler_lock: Arc<Mutex<bool>>, } impl DistributedScheduler { pub fn new( max_failures: usize, master: bool, servers: Option<Vec<SocketAddrV4>>, port: u16, ) -> Self { log::debug!( "starting distributed scheduler @ port {} (in master mode: {})", port, master, ); DistributedScheduler { max_failures, attempt_id: Arc::new(AtomicUsize::new(0)), resubmit_timeout: 2000, poll_timeout: 50, event_queues: Arc::new(DashMap::new()), next_job_id: Arc::new(AtomicUsize::new(0)), next_run_id: Arc::new(AtomicUsize::new(0)), next_task_id: Arc::new(AtomicUsize::new(0)), next_stage_id: Arc::new(AtomicUsize::new(0)), stage_cache: Arc::new(DashMap::new()), shuffle_to_map_stage: Arc::new(DashMap::new()), cache_locs: Arc::new(DashMap::new()), master, framework_name: "native_spark".to_string(), is_registered: true, //TODO check if it is necessary active_jobs: HashMap::new(), active_job_queue: Vec::new(), taskid_to_jobid: HashMap::new(), taskid_to_slaveid: HashMap::new(), job_tasks: HashMap::new(), slaves_with_executors: HashSet::new(), server_uris: if let Some(servers) = servers { Arc::new(Mutex::new(VecDeque::from_iter(servers))) } else { Arc::new(Mutex::new(VecDeque::new())) }, port, map_output_tracker: env::Env::get().map_output_tracker.clone(), scheduler_lock: Arc::new(Mutex::new(true)), } } fn task_ended( event_queues: Arc<DashMap<usize, VecDeque<CompletionEvent>>>, task: Box<dyn TaskBase>, reason: TastEndReason, result: Box<dyn Any + Send + Sync>, //TODO accumvalues needs to be done ) { let result = Some(result); if let Some(mut queue) = event_queues.get_mut(&(task.get_run_id())) { queue.push_back(CompletionEvent { task, reason, result, accum_updates: HashMap::new(), }); } else { log::debug!("ignoring completion event for DAG Job"); } } pub fn run_job<T: Data, U: Data, F>( self: Arc<Self>, func: Arc<F>, final_rdd: Arc<dyn Rdd<Item = T>>, partitions: Vec<usize>, allow_local: bool, ) -> Result<Vec<U>> where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { // acquiring lock so that only one job can run a same time this lock is just // a temporary patch for preventing multiple jobs to update cache locks which affects // construction of dag task graph. dag task graph construction need to be altered let _lock = self.scheduler_lock.lock(); let jt = JobTracker::from_scheduler(&*self, func, final_rdd.clone(), partitions); //TODO update cache if allow_local { if let Some(result) = LocalScheduler::local_execution(jt.clone())? { return Ok(result); } } self.event_queues.insert(jt.run_id, VecDeque::new()); let self_clone = Arc::clone(&self); let jt_clone = jt.clone(); // run in async executor let executor = env::Env::get_async_handle(); let results = executor.enter(move || { let self_borrow = &*self_clone; let jt = jt_clone; let mut results: Vec<Option<U>> = (0..jt.num_output_parts).map(|_| None).collect(); let mut fetch_failure_duration = Duration::new(0, 0); self_borrow.submit_stage(jt.final_stage.clone(), jt.clone()); utils::yield_tokio_futures(); log::debug!( "pending stages and tasks: {:?}", jt.pending_tasks .lock() .iter() .map(|(k, v)| (k.id, v.iter().map(|x| x.get_task_id()).collect::<Vec<_>>())) .collect::<Vec<_>>() ); let mut num_finished = 0; while num_finished != jt.num_output_parts { let event_option = self_borrow.wait_for_event(jt.run_id, self_borrow.poll_timeout); let start_time = Instant::now(); if let Some(evt) = event_option { log::debug!("event starting"); let stage = self_borrow .stage_cache .get(&evt.task.get_stage_id()) .unwrap() .clone(); log::debug!( "removing stage #{} task from pending task #{}", stage.id, evt.task.get_task_id() ); jt.pending_tasks .lock() .get_mut(&stage) .unwrap() .remove(&evt.task); use super::dag_scheduler::TastEndReason::*; match evt.reason { Success => self_borrow.on_event_success( evt, &mut results, &mut num_finished, jt.clone(), ), FetchFailed(failed_vals) => { self_borrow.on_event_failure( jt.clone(), failed_vals, evt.task.get_stage_id(), ); fetch_failure_duration = start_time.elapsed(); } _ => { //TODO error handling } } } if !jt.failed.lock().is_empty() && fetch_failure_duration.as_millis() > self_borrow.resubmit_timeout { self_borrow.update_cache_locs(); for stage in jt.failed.lock().iter() { self_borrow.submit_stage(stage.clone(), jt.clone()); } utils::yield_tokio_futures(); jt.failed.lock().clear(); } } results }); self.event_queues.remove(&jt.run_id); Ok(results .into_iter() .map(|s| match s { Some(v) => v, None => panic!("some results still missing"), }) .collect()) } async fn receive_results<T: Data, U: Data, F, R>( event_queues: Arc<DashMap<usize, VecDeque<CompletionEvent>>>, receiver: R, task: TaskOption, target_port: u16, ) where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, R: futures::AsyncRead + std::marker::Unpin, { let result: TaskResult = { let message = capnp_futures::serialize::read_message(receiver, CAPNP_BUF_READ_OPTS) .await .unwrap() .unwrap(); let task_data = message.get_root::<serialized_data::Reader>().unwrap(); log::debug!( "received task #{} result of {} bytes from executor @{}", task.get_task_id(), task_data.get_msg().unwrap().len(), target_port ); bincode::deserialize(&task_data.get_msg().unwrap()).unwrap() }; match task { TaskOption::ResultTask(tsk) => { let result = match result { TaskResult::ResultTask(r) => r, _ => panic!("wrong result type"), }; if let Ok(task_final) = tsk.downcast::<ResultTask<T, U, F>>() { let task_final = task_final as Box<dyn TaskBase>; DistributedScheduler::task_ended( event_queues, task_final, TastEndReason::Success, // Can break in future. But actually not needed for distributed scheduler since task runs on different processes. // Currently using this because local scheduler needs it. It can be solved by refactoring tasks differently for local and distributed scheduler result.into_any_send_sync(), ); } } TaskOption::ShuffleMapTask(tsk) => { let result = match result { TaskResult::ShuffleTask(r) => r, _ => panic!("wrong result type"), }; if let Ok(task_final) = tsk.downcast::<ShuffleMapTask>() { let task_final = task_final as Box<dyn TaskBase>; DistributedScheduler::task_ended( event_queues, task_final, TastEndReason::Success, result.into_any_send_sync(), ); } } }; } } impl NativeScheduler for DistributedScheduler { fn submit_task<T: Data, U: Data, F>( &self, task: TaskOption, _id_in_job: usize, target_executor: SocketAddrV4, ) where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { if !env::Configuration::get().is_driver { return; } log::debug!("inside submit task"); let event_queues_clone = self.event_queues.clone(); futures::executor::block_on(async move { let mut num_retries = 0; loop { match TcpStream::connect(&target_executor).await { Ok(mut stream) => { let (reader, writer) = stream.split(); let reader = reader.compat(); let mut writer = writer.compat_write(); let task_bytes = bincode::serialize(&task).unwrap(); log::debug!( "sending task #{} of {} bytes to exec @{},", task.get_task_id(), task_bytes.len(), target_executor.port(), ); let mut message = capnp::message::Builder::new_default(); let mut task_data = message.init_root::<serialized_data::Builder>(); task_data.set_msg(&task_bytes); capnp_serialize::write_message(&mut writer, &message) .await .map_err(Error::CapnpDeserialization) .unwrap(); log::debug!("sent data to exec @{}", target_executor.port()); // receive results back DistributedScheduler::receive_results::<T, U, F, _>( event_queues_clone, reader, task, target_executor.port(), ) .await; break; } Err(_) => { if num_retries > 5 { panic!("executor @{} not initialized", target_executor.port()); } tokio::time::delay_for(Duration::from_millis(20)).await; num_retries += 1; continue; } } } }); } fn next_executor_server(&self, task: &dyn TaskBase) -> SocketAddrV4 { if !task.is_pinned() { // pick the first available server let socket_addrs = self.server_uris.lock().pop_back().unwrap(); self.server_uris.lock().push_front(socket_addrs); socket_addrs } else { // seek and pick the selected host let servers = &mut *self.server_uris.lock(); let location: Ipv4Addr = task.preferred_locations()[0]; if let Some((pos, _)) = servers .iter() .enumerate() .find(|(_, e)| *e.ip() == location) { let target_host = servers.remove(pos).unwrap(); servers.push_front(target_host.clone()); target_host } else { unreachable!() } } } impl_common_scheduler_funcs!(); } <file_sep>use serde_traitobject::{deserialize, serialize, Deserialize, Serialize}; use std::{ any, borrow::{Borrow, BorrowMut}, boxed, error, fmt, marker, ops::{self, Deref, DerefMut}, }; // Data passing through RDD needs to satisfy the following traits. // Debug is only added here for debugging convenience during development stage but is not necessary. // Sync is also not necessary I think. Have to look into it. pub trait Data: Clone + any::Any + Send + Sync + fmt::Debug + serde::ser::Serialize + serde::de::DeserializeOwned + 'static { } impl< T: Clone + any::Any + Send + Sync + fmt::Debug + serde::ser::Serialize + serde::de::DeserializeOwned + 'static, > Data for T { } pub trait AnyData: dyn_clone::DynClone + any::Any + Send + Sync + fmt::Debug + Serialize + Deserialize + 'static { fn as_any(&self) -> &dyn any::Any; /// Convert to a `&mut std::any::Any`. fn as_any_mut(&mut self) -> &mut dyn any::Any; /// Convert to a `std::boxed::Box<dyn std::any::Any>`. fn into_any(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any>; /// Convert to a `std::boxed::Box<dyn std::any::Any + Send>`. fn into_any_send(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any + Send>; /// Convert to a `std::boxed::Box<dyn std::any::Any + Sync>`. fn into_any_sync(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any + Sync>; /// Convert to a `std::boxed::Box<dyn std::any::Any + Send + Sync>`. fn into_any_send_sync(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any + Send + Sync>; } dyn_clone::clone_trait_object!(AnyData); // Automatically implementing the Data trait for all types which implements the required traits impl< T: dyn_clone::DynClone + any::Any + Send + Sync + fmt::Debug + Serialize + Deserialize + 'static, > AnyData for T { fn as_any(&self) -> &dyn any::Any { self } fn as_any_mut(&mut self) -> &mut dyn any::Any { self } fn into_any(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any> { self } fn into_any_send(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any + Send> { self } fn into_any_sync(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any + Sync> { self } fn into_any_send_sync(self: boxed::Box<Self>) -> boxed::Box<dyn any::Any + Send + Sync> { self } } impl serde::ser::Serialize for boxed::Box<dyn AnyData + 'static> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serialize(&self, serializer) } } impl<'de> serde::de::Deserialize<'de> for boxed::Box<dyn AnyData + 'static> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { <Box<dyn AnyData + 'static>>::deserialize(deserializer).map(|x| x.0) } } impl serde::ser::Serialize for boxed::Box<dyn AnyData + Send + 'static> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serialize(&self, serializer) } } impl<'de> serde::de::Deserialize<'de> for boxed::Box<dyn AnyData + Send + 'static> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { <Box<dyn AnyData + Send + 'static>>::deserialize(deserializer).map(|x| x.0) } } #[derive(Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Box<T: ?Sized>(boxed::Box<T>); impl<T> Box<T> { // Create a new Box wrapper pub fn new(t: T) -> Self { Self(boxed::Box::new(t)) } } impl<T: ?Sized> Box<T> { // Convert to a regular `std::Boxed::Box<T>`. Coherence rules prevent currently prevent `impl Into<std::boxed::Box<T>> for Box<T>`. pub fn into_box(self) -> boxed::Box<T> { self.0 } } impl Box<dyn AnyData> { // Convert into a `std::boxed::Box<dyn std::any::Any>`. pub fn into_any(self) -> boxed::Box<dyn any::Any> { self.0.into_any() } } impl<T: ?Sized + marker::Unsize<U>, U: ?Sized> ops::CoerceUnsized<Box<U>> for Box<T> {} impl<T: ?Sized> Deref for Box<T> { type Target = boxed::Box<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T: ?Sized> DerefMut for Box<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<T: ?Sized> AsRef<boxed::Box<T>> for Box<T> { fn as_ref(&self) -> &boxed::Box<T> { &self.0 } } impl<T: ?Sized> AsMut<boxed::Box<T>> for Box<T> { fn as_mut(&mut self) -> &mut boxed::Box<T> { &mut self.0 } } impl<T: ?Sized> AsRef<T> for Box<T> { fn as_ref(&self) -> &T { &*self.0 } } impl<T: ?Sized> AsMut<T> for Box<T> { fn as_mut(&mut self) -> &mut T { &mut *self.0 } } impl<T: ?Sized> Borrow<T> for Box<T> { fn borrow(&self) -> &T { &*self.0 } } impl<T: ?Sized> BorrowMut<T> for Box<T> { fn borrow_mut(&mut self) -> &mut T { &mut *self.0 } } impl<T: ?Sized> From<boxed::Box<T>> for Box<T> { fn from(t: boxed::Box<T>) -> Self { Self(t) } } // impl<T: ?Sized> Into<boxed::Box<T>> for Box<T> { // fn into(self) -> boxed::Box<T> { // self.0 // } // } impl<T> From<T> for Box<T> { fn from(t: T) -> Self { Self(boxed::Box::new(t)) } } impl<T: error::Error> error::Error for Box<T> { fn description(&self) -> &str { error::Error::description(&**self) } #[allow(deprecated)] fn cause(&self) -> Option<&dyn error::Error> { error::Error::cause(&**self) } fn source(&self) -> Option<&(dyn error::Error + 'static)> { error::Error::source(&**self) } } impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { self.0.fmt(f) } } impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { self.0.fmt(f) } } impl<A, F: ?Sized> ops::FnOnce<A> for Box<F> where F: FnOnce<A>, { type Output = F::Output; extern "rust-call" fn call_once(self, args: A) -> Self::Output { self.0.call_once(args) } } impl<A, F: ?Sized> ops::FnMut<A> for Box<F> where F: FnMut<A>, { extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output { self.0.call_mut(args) } } impl<A, F: ?Sized> ops::Fn<A> for Box<F> where F: Func<A>, { extern "rust-call" fn call(&self, args: A) -> Self::Output { self.0.call(args) } } impl<T: Serialize + ?Sized + 'static> serde::ser::Serialize for Box<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serialize(&self.0, serializer) } } impl<'de, T: Deserialize + ?Sized + 'static> serde::de::Deserialize<'de> for Box<T> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { deserialize(deserializer).map(Self) } } pub trait SerFunc<Args>: Fn<Args> + Send + Sync + Clone + serde::ser::Serialize + serde::de::DeserializeOwned + 'static + Serialize + Deserialize { } impl<Args, T> SerFunc<Args> for T where T: Fn<Args> + Send + Sync + Clone + serde::ser::Serialize + serde::de::DeserializeOwned + 'static + Serialize + Deserialize { } pub trait Func<Args>: ops::Fn<Args> + Serialize + Deserialize + Send + Sync + 'static + dyn_clone::DynClone { } impl<T: ?Sized, Args> Func<Args> for T where T: ops::Fn<Args> + Serialize + Deserialize + Send + Sync + 'static + dyn_clone::DynClone { } impl<Args: 'static, Output: 'static> std::clone::Clone for boxed::Box<dyn Func<Args, Output = Output>> { fn clone(&self) -> Self { dyn_clone::clone_box(&**self) } } impl<'a, Args, Output> AsRef<Self> for dyn Func<Args, Output = Output> + 'a { fn as_ref(&self) -> &Self { self } } impl<Args: 'static, Output: 'static> serde::ser::Serialize for dyn Func<Args, Output = Output> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serialize(self, serializer) } } impl<'de, Args: 'static, Output: 'static> serde::de::Deserialize<'de> for boxed::Box<dyn Func<Args, Output = Output> + 'static> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { <Box<dyn Func<Args, Output = Output> + 'static>>::deserialize(deserializer).map(|x| x.0) } } <file_sep># Introduction `native_spark` is a distributed computing framework inspired by Apache Spark. ## Getting started ### Installation Right now the framework lacks any sort of cluster manager of submit program/script. In order to use the framework you have to clone the repository and add the local dependency or add the upstream GitHub repository to your Rust project (the crate is not yet published on [crates.io](https://crates.io/)). E.g. add to your application Cargo.toml or: ```doc [dependencies] native_spark = { path = "/path/to/local/git/repo" } # or native_spark = { git = "https://github.com/rajasekarv/native_spark", branch = "master } ``` Is not recommended to use the application for any sort of production code yet as it's under heavy development. Check [examples](https://github.com/rajasekarv/native_spark/tree/master/examples) and [tests](https://github.com/rajasekarv/native_spark/tree/master/tests) in the source code to get a basic idea of how the framework works. ## Executing an application In order to execute application code some preliminary setup is required. (So far only tested on Linux.) * Install [Cap'n Proto](https://capnproto.org/install.html). Required for serialization/deserialziation and IPC between executors. * If you want to execute examples, tests or contribute to development, clone the repository `git clone https://github.com/rajasekarv/native_spark/`, if you want to use the library in your own application you can just add the depency as indicated in the installation paragraph. * You need to have [hosts.conf](https://github.com/rajasekarv/native_spark/blob/master/config_files/hosts.conf) in the format present inside config folder in the home directory of the user deploying executors in any of the machines. * In `local` mode this means in your current user home, e.g.: > $ cp native_spark/config_files/hosts.conf $HOME * In `distributed` mode the same file is required in each host that may be deploying executors (the ones indicated in the `hosts.conf` file) and the master. E.g.: ```doc $ ssh remote_user@192.168.3.11 # this machine IP is in hosts.conf # create the same hosts.conf file in every machine: $ cd ~ && vim hosts.conf ... ``` * The environment variable `NS_LOCAL_IP` must be set for the user executing application code. * In `local` it suffices to set up for the current user: > $ export NS_LOCAL_IP=0.0.0.0 * In `distributed` the variable is required, aditionally, to be set up for the users remotely connecting. Depending on the O.S. and ssh defaults this may require some additional configuration. E.g.: ```doc $ ssh remote_user@192.168.3.11 $ sudo echo "NS_LOCAL_IP=192.168.3.11" >> .ssh/environment $ sudo echo "PermitUserEnvironment yes" >> /etc/ssh/sshd_config $ service ssh restart ``` Now you are ready to execute your application code; if you want to try the provided examples just run them. In `local`: > cargo run --example make_rdd In `distributed`: > export NS_DEPLOYMENT_MODE=distributed > > cargo run --example make_rdd ## Deploying with Docker There is a docker image and docker-compose script in order to ease up trying testing and deploying distributed mode on your local host. In order to use them: 1. Build the examples image under the repository `docker` directory: > bash docker/build_image.sh 2. When done, you can deploy a testing cluster: > bash testing_cluster.sh This will execute all the necessary steeps to to deploy a working network of containers where you can execute the tests. When finished you can attach a shell to the master and run the examples: ```doc $ docker exec -it docker_ns_master_1 bash $ ./make_rdd ``` ## Setting execution mode In your application you can set the execution mode (`local` or `distributed`) in one of the following ways: 1. Set it explicitly while creating the context, e.g.: ```doc use native_spark::DeploymentMode; let context = Context::with_mode(DeploymentMode::Local)?; ``` 2. Set the DEPLOYMENT_MODE environment variable (e.g.: `DEPLOYMENT_MODE=local`). ### Additional notes * Depending on the source you intend to use you may have to write your own source reading rdd (like manually reading from S3) if it's not yet available. * Ctrl-C and panic handling are not compeltely done yet, so if there is a problem during runtime, executors won't shut down automatically and you will have to manually kill the processes. * One of the limitations of current implementation is that the input and return types of all closures and all input to make_rdd should be owned data. <file_sep>use crate::context::Context; use crate::dependency::{Dependency, OneToOneDependency}; use crate::error::Result; use crate::rdd::{Rdd, RddBase, RddVals}; use crate::serializable_traits::{AnyData, Data, Func, SerFunc}; use crate::split::Split; use serde_derive::{Deserialize, Serialize}; use std::marker::PhantomData; use std::net::Ipv4Addr; use std::sync::{atomic::AtomicBool, atomic::Ordering::SeqCst, Arc}; /// An RDD that applies the provided function to every partition of the parent RDD. #[derive(Serialize, Deserialize)] pub struct MapPartitionsRdd<T: Data, U: Data, F> where F: Func(usize, Box<dyn Iterator<Item = T>>) -> Box<dyn Iterator<Item = U>> + Clone, { #[serde(with = "serde_traitobject")] prev: Arc<dyn Rdd<Item = T>>, vals: Arc<RddVals>, f: F, pinned: AtomicBool, _marker_t: PhantomData<T>, } impl<T: Data, U: Data, F> Clone for MapPartitionsRdd<T, U, F> where F: Func(usize, Box<dyn Iterator<Item = T>>) -> Box<dyn Iterator<Item = U>> + Clone, { fn clone(&self) -> Self { MapPartitionsRdd { prev: self.prev.clone(), vals: self.vals.clone(), f: self.f.clone(), pinned: AtomicBool::new(self.pinned.load(SeqCst)), _marker_t: PhantomData, } } } impl<T: Data, U: Data, F> MapPartitionsRdd<T, U, F> where F: SerFunc(usize, Box<dyn Iterator<Item = T>>) -> Box<dyn Iterator<Item = U>>, { pub(crate) fn new(prev: Arc<dyn Rdd<Item = T>>, f: F) -> Self { let mut vals = RddVals::new(prev.get_context()); vals.dependencies .push(Dependency::NarrowDependency(Arc::new( OneToOneDependency::new(prev.get_rdd_base()), ))); let vals = Arc::new(vals); MapPartitionsRdd { prev, vals, f, pinned: AtomicBool::new(false), _marker_t: PhantomData, } } pub(crate) fn pin(self) -> Self { self.pinned.store(true, SeqCst); self } } impl<T: Data, U: Data, F> RddBase for MapPartitionsRdd<T, U, F> where F: SerFunc(usize, Box<dyn Iterator<Item = T>>) -> Box<dyn Iterator<Item = U>>, { fn get_rdd_id(&self) -> usize { self.vals.id } fn get_context(&self) -> Arc<Context> { self.vals.context.upgrade().unwrap() } fn get_dependencies(&self) -> Vec<Dependency> { self.vals.dependencies.clone() } fn preferred_locations(&self, split: Box<dyn Split>) -> Vec<Ipv4Addr> { self.prev.preferred_locations(split) } fn splits(&self) -> Vec<Box<dyn Split>> { self.prev.splits() } fn number_of_splits(&self) -> usize { self.prev.number_of_splits() } default fn cogroup_iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { self.iterator_any(split) } default fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { log::debug!("inside iterator_any map_partitions_rdd",); Ok(Box::new( self.iterator(split)? .map(|x| Box::new(x) as Box<dyn AnyData>), )) } fn is_pinned(&self) -> bool { self.pinned.load(SeqCst) } } impl<T: Data, V: Data, U: Data, F> RddBase for MapPartitionsRdd<T, (V, U), F> where F: SerFunc(usize, Box<dyn Iterator<Item = T>>) -> Box<dyn Iterator<Item = (V, U)>>, { fn cogroup_iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { log::debug!("inside iterator_any map_partitions_rdd",); Ok(Box::new(self.iterator(split)?.map(|(k, v)| { Box::new((k, Box::new(v) as Box<dyn AnyData>)) as Box<dyn AnyData> }))) } } impl<T: Data, U: Data, F: 'static> Rdd for MapPartitionsRdd<T, U, F> where F: SerFunc(usize, Box<dyn Iterator<Item = T>>) -> Box<dyn Iterator<Item = U>>, { type Item = U; fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(self.clone()) as Arc<dyn RddBase> } fn get_rdd(&self) -> Arc<dyn Rdd<Item = Self::Item>> { Arc::new(self.clone()) } fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { let f_result = self.f.clone()(split.get_index(), self.prev.iterator(split)?); Ok(Box::new(f_result)) } } <file_sep>//! This module implements parallel collection RDD for dividing the input collection for parallel processing. use std::sync::{Arc, Weak}; use crate::context::Context; use crate::dependency::Dependency; use crate::error::Result; use crate::rdd::{Rdd, RddBase, RddVals}; use crate::serializable_traits::{AnyData, Data}; use crate::split::Split; use serde_derive::{Deserialize, Serialize}; /// A collection of objects which can be sliced into partitions with a partitioning function. pub trait Chunkable<D> where D: Data, { fn slice_with_set_parts(self, parts: usize) -> Vec<Arc<Vec<D>>>; fn slice(self) -> Vec<Arc<Vec<D>>> where Self: Sized, { let as_many_parts_as_cpus = num_cpus::get(); self.slice_with_set_parts(as_many_parts_as_cpus) } } #[derive(Serialize, Deserialize, Clone)] pub struct ParallelCollectionSplit<T> { rdd_id: i64, index: usize, values: Arc<Vec<T>>, } impl<T: Data> Split for ParallelCollectionSplit<T> { fn get_index(&self) -> usize { self.index } } impl<T: Data> ParallelCollectionSplit<T> { fn new(rdd_id: i64, index: usize, values: Arc<Vec<T>>) -> Self { ParallelCollectionSplit { rdd_id, index, values, } } // Lot of unnecessary cloning is there. Have to refactor for better performance fn iterator(&self) -> Box<dyn Iterator<Item = T>> { let data = self.values.clone(); let len = data.len(); Box::new((0..len).map(move |i| data[i].clone())) // let res = res.collect::<Vec<_>>(); // let log_output = format!("inside iterator maprdd {:?}", res.get(0)); // env::log_file.lock().write(&log_output.as_bytes()); // Box::new(res.into_iter()) as Box<Iterator<Item = T>> // Box::new(self.values.clone().into_iter()) } } #[derive(Serialize, Deserialize)] pub struct ParallelCollectionVals<T> { vals: Arc<RddVals>, #[serde(skip_serializing, skip_deserializing)] context: Weak<Context>, splits_: Vec<Arc<Vec<T>>>, num_slices: usize, } #[derive(Serialize, Deserialize)] pub struct ParallelCollection<T> { rdd_vals: Arc<ParallelCollectionVals<T>>, } impl<T: Data> Clone for ParallelCollection<T> { fn clone(&self) -> Self { ParallelCollection { rdd_vals: self.rdd_vals.clone(), } } } impl<T: Data> ParallelCollection<T> { pub fn new<I>(context: Arc<Context>, data: I, num_slices: usize) -> Self where I: IntoIterator<Item = T>, { ParallelCollection { rdd_vals: Arc::new(ParallelCollectionVals { context: Arc::downgrade(&context), vals: Arc::new(RddVals::new(context.clone())), splits_: ParallelCollection::slice(data, num_slices), num_slices, }), } } pub fn from_chunkable<C>(context: Arc<Context>, data: C) -> Self where C: Chunkable<T>, { let splits_ = data.slice(); let rdd_vals = ParallelCollectionVals { context: Arc::downgrade(&context), vals: Arc::new(RddVals::new(context.clone())), num_slices: splits_.len(), splits_, }; ParallelCollection { rdd_vals: Arc::new(rdd_vals), } } fn slice<I>(data: I, num_slices: usize) -> Vec<Arc<Vec<T>>> where I: IntoIterator<Item = T>, { if num_slices < 1 { panic!("Number of slices should be greater than or equal to 1"); } else { let mut slice_count = 0; let data: Vec<_> = data.into_iter().collect(); let data_len = data.len(); //let mut start = (count * data.len()) / num_slices; let mut end = ((slice_count + 1) * data_len) / num_slices; let mut output = Vec::new(); let mut tmp = Vec::new(); let mut iter_count = 0; for i in data { if iter_count < end { tmp.push(i); iter_count += 1; } else { slice_count += 1; end = ((slice_count + 1) * data_len) / num_slices; output.push(Arc::new(tmp.drain(..).collect::<Vec<_>>())); tmp.push(i); iter_count += 1; } } output.push(Arc::new(tmp.drain(..).collect::<Vec<_>>())); output // data.chunks(num_slices) // .map(|x| Arc::new(x.to_vec())) // .collect() } } } impl<K: Data, V: Data> RddBase for ParallelCollection<(K, V)> { fn cogroup_iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { log::debug!("inside iterator_any parallel collection",); Ok(Box::new(self.iterator(split)?.map(|(k, v)| { Box::new((k, Box::new(v) as Box<dyn AnyData>)) as Box<dyn AnyData> }))) } } impl<T: Data> RddBase for ParallelCollection<T> { fn get_rdd_id(&self) -> usize { self.rdd_vals.vals.id } fn get_context(&self) -> Arc<Context> { self.rdd_vals.vals.context.upgrade().unwrap() } fn get_dependencies(&self) -> Vec<Dependency> { self.rdd_vals.vals.dependencies.clone() } fn splits(&self) -> Vec<Box<dyn Split>> { // let slices = self.slice(); (0..self.rdd_vals.splits_.len()) .map(|i| { Box::new(ParallelCollectionSplit::new( self.rdd_vals.vals.id as i64, i, self.rdd_vals.splits_[i as usize].clone(), )) as Box<dyn Split> }) .collect::<Vec<Box<dyn Split>>>() } fn number_of_splits(&self) -> usize { self.rdd_vals.splits_.len() } default fn cogroup_iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { self.iterator_any(split) } default fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { log::debug!("inside iterator_any parallel collection",); Ok(Box::new( self.iterator(split)? .map(|x| Box::new(x) as Box<dyn AnyData>), )) } } impl<T: Data> Rdd for ParallelCollection<T> { type Item = T; fn get_rdd(&self) -> Arc<dyn Rdd<Item = Self::Item>> { Arc::new(ParallelCollection { rdd_vals: self.rdd_vals.clone(), }) } fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(self.clone()) as Arc<dyn RddBase> } fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { if let Some(s) = split.downcast_ref::<ParallelCollectionSplit<T>>() { Ok(s.iterator()) } else { panic!( "Got split object from different concrete type other than ParallelCollectionSplit" ) } } } //impl<K: Data + Eq + Hash, V: Data + Eq + Hash> PairRdd<K, V> for ParallelCollection<(K, V)> {} <file_sep>use std::collections::LinkedList; use std::collections::{HashMap, HashSet}; use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream}; use std::sync::Arc; use std::thread; use std::time; use crate::cache::{BoundedMemoryCache, CachePutResponse, KeySpace}; use crate::env; use crate::rdd::Rdd; use crate::serializable_traits::Data; use crate::serialized_data_capnp::serialized_data; use crate::split::Split; use capnp::serialize_packed; use dashmap::DashMap; use parking_lot::RwLock; use serde_derive::{Deserialize, Serialize}; // Cache tracker works by creating a server in master node and slave nodes acting as clients #[derive(Serialize, Deserialize)] pub enum CacheTrackerMessage { AddedToCache { rdd_id: usize, partition: usize, host: Ipv4Addr, size: usize, }, DroppedFromCache { rdd_id: usize, partition: usize, host: Ipv4Addr, size: usize, }, MemoryCacheLost { host: Ipv4Addr, }, RegisterRdd { rdd_id: usize, num_partitions: usize, }, SlaveCacheStarted { host: Ipv4Addr, size: usize, }, GetCacheStatus, GetCacheLocations, StopCacheTracker, } #[derive(Serialize, Deserialize)] pub enum CacheTrackerMessageReply { CacheLocations(HashMap<usize, Vec<LinkedList<Ipv4Addr>>>), CacheStatus(Vec<(Ipv4Addr, usize, usize)>), Ok, } #[derive(Clone, Debug)] pub(crate) struct CacheTracker { is_master: bool, locs: Arc<DashMap<usize, Vec<LinkedList<Ipv4Addr>>>>, slave_capacity: Arc<DashMap<Ipv4Addr, usize>>, slave_usage: Arc<DashMap<Ipv4Addr, usize>>, registered_rdd_ids: Arc<RwLock<HashSet<usize>>>, loading: Arc<RwLock<HashSet<(usize, usize)>>>, cache: KeySpace<'static>, master_addr: SocketAddr, } impl CacheTracker { pub fn new( is_master: bool, master_addr: SocketAddr, local_ip: Ipv4Addr, the_cache: &'static BoundedMemoryCache, ) -> Self { let m = CacheTracker { is_master, locs: Arc::new(DashMap::new()), slave_capacity: Arc::new(DashMap::new()), slave_usage: Arc::new(DashMap::new()), registered_rdd_ids: Arc::new(RwLock::new(HashSet::new())), loading: Arc::new(RwLock::new(HashSet::new())), cache: the_cache.new_key_space(), master_addr: SocketAddr::new(master_addr.ip(), master_addr.port() + 1), }; m.server(); m.client(CacheTrackerMessage::SlaveCacheStarted { host: local_ip, size: m.cache.get_capacity(), }); m } // Slave node will ask master node for cache locs fn client(&self, message: CacheTrackerMessage) -> CacheTrackerMessageReply { while let Err(_) = TcpStream::connect(self.master_addr) { continue; } let mut stream = TcpStream::connect(self.master_addr).unwrap(); // println!( // "connected to mapoutput tracker {}:{}", // self.master_ip, self.master_port // ); let shuffle_id_bytes = bincode::serialize(&message).unwrap(); let mut message = capnp::message::Builder::new_default(); let mut shuffle_data = message.init_root::<serialized_data::Builder>(); shuffle_data.set_msg(&shuffle_id_bytes); serialize_packed::write_message(&mut stream, &message).unwrap(); let r = capnp::message::ReaderOptions { traversal_limit_in_words: std::u64::MAX, nesting_limit: 64, }; let mut stream_r = std::io::BufReader::new(&mut stream); let message_reader = serialize_packed::read_message(&mut stream_r, r).unwrap(); let shuffle_data = message_reader .get_root::<serialized_data::Reader>() .unwrap(); let reply: CacheTrackerMessageReply = bincode::deserialize(&shuffle_data.get_msg().unwrap()).unwrap(); reply } // This will start only in master node and will server all the slave nodes fn server(&self) { if self.is_master { let locs = self.locs.clone(); let slave_capacity = self.slave_capacity.clone(); let slave_usage = self.slave_usage.clone(); let master_addr = self.master_addr; thread::spawn(move || { // TODO: make this use async rt let listener = TcpListener::bind(master_addr).unwrap(); // println!("started mapoutput tracker at {}", port); for stream in listener.incoming() { match stream { Err(_) => continue, Ok(mut stream) => { let locs = locs.clone(); let slave_capacity = slave_capacity.clone(); let slave_usage = slave_usage.clone(); thread::spawn(move || { //reading let r = capnp::message::ReaderOptions { traversal_limit_in_words: std::u64::MAX, nesting_limit: 64, }; let mut stream_r = std::io::BufReader::new(&mut stream); let message_reader = match serialize_packed::read_message(&mut stream_r, r) { Ok(s) => s, Err(_) => return, }; let data = message_reader .get_root::<serialized_data::Reader>() .unwrap(); let message: CacheTrackerMessage = bincode::deserialize(data.get_msg().unwrap()).unwrap(); //TODO logging let reply = match message { CacheTrackerMessage::SlaveCacheStarted { host, size } => { slave_capacity.insert(host.clone(), size); slave_usage.insert(host, 0); CacheTrackerMessageReply::Ok } CacheTrackerMessage::RegisterRdd { rdd_id, num_partitions, } => { locs.insert( rdd_id, (0..num_partitions) .map(|_| LinkedList::new()) .collect(), ); CacheTrackerMessageReply::Ok } CacheTrackerMessage::AddedToCache { rdd_id, partition, host, size, } => { if size > 0 { slave_usage.insert( host.clone(), CacheTracker::get_cache_usage( slave_usage.clone(), host, ) + size, ); } else { //TODO logging } if let Some(mut locs_rdd) = locs.get_mut(&rdd_id) { if let Some(locs_rdd_p) = locs_rdd.get_mut(partition) { locs_rdd_p.push_front(host); } } CacheTrackerMessageReply::Ok } CacheTrackerMessage::DroppedFromCache { rdd_id, partition, host, size, } => { if size > 0 { let remaining = CacheTracker::get_cache_usage( slave_usage.clone(), host, ) - size; slave_usage.insert(host.clone(), remaining); } let remaining_locs = locs .get(&rdd_id) .unwrap() .get(partition) .unwrap() .iter() .filter(|x| *x == &host) .copied() .collect(); if let Some(mut locs_r) = locs.get_mut(&rdd_id) { if let Some(locs_p) = locs_r.get_mut(partition) { *locs_p = remaining_locs; } } CacheTrackerMessageReply::Ok } //TODO memory cache lost needs to be implemented CacheTrackerMessage::GetCacheLocations => { let locs_clone = locs .iter() .map(|kv| { let (k, v) = (kv.key(), kv.value()); (*k, v.clone()) }) .collect(); CacheTrackerMessageReply::CacheLocations(locs_clone) } CacheTrackerMessage::GetCacheStatus => { let status = slave_capacity .iter() .map(|kv| { let (host, capacity) = (kv.key(), kv.value()); ( *host, *capacity, CacheTracker::get_cache_usage( slave_usage.clone(), *host, ), ) }) .collect(); CacheTrackerMessageReply::CacheStatus(status) } _ => CacheTrackerMessageReply::Ok, }; let result = bincode::serialize(&reply).unwrap(); let mut message = capnp::message::Builder::new_default(); let mut locs_data = message.init_root::<serialized_data::Builder>(); locs_data.set_msg(&result); serialize_packed::write_message(&mut stream, &message).unwrap(); }); } } } }); } } pub fn get_cache_usage(slave_usage: Arc<DashMap<Ipv4Addr, usize>>, host: Ipv4Addr) -> usize { match slave_usage.get(&host) { Some(s) => *s, None => 0, } } pub fn get_cache_capacity( slave_capacity: Arc<DashMap<Ipv4Addr, usize>>, host: Ipv4Addr, ) -> usize { match slave_capacity.get(&host) { Some(s) => *s, None => 0, } } pub fn register_rdd(&self, rdd_id: usize, num_partitions: usize) { if !self.registered_rdd_ids.read().contains(&rdd_id) { //TODO logging self.registered_rdd_ids.write().insert(rdd_id); self.client(CacheTrackerMessage::RegisterRdd { rdd_id, num_partitions, }); } } pub fn get_location_snapshot(&self) -> HashMap<usize, Vec<Vec<Ipv4Addr>>> { match self.client(CacheTrackerMessage::GetCacheLocations) { CacheTrackerMessageReply::CacheLocations(s) => s .into_iter() .map(|(k, v)| { let v = v .into_iter() .map(|x| x.into_iter().map(|x| x).collect()) .collect(); (k, v) }) .collect(), _ => panic!("wrong type from cache tracker"), } } pub fn get_cache_status(&self) -> Vec<(Ipv4Addr, usize, usize)> { match self.client(CacheTrackerMessage::GetCacheStatus) { CacheTrackerMessageReply::CacheStatus(s) => s, _ => panic!("wrong type from cache tracker"), } } pub fn get_or_compute<T: Data>( &self, rdd: Arc<dyn Rdd<Item = T>>, split: Box<dyn Split>, ) -> Box<dyn Iterator<Item = T>> { if let Some(cached_val) = self.cache.get(rdd.get_rdd_id(), split.get_index()) { let res: Vec<T> = bincode::deserialize(&cached_val).unwrap(); Box::new(res.into_iter()) } else { let key = (rdd.get_rdd_id(), split.get_index()); while self.loading.read().contains(&key) { let dur = time::Duration::from_millis(1); thread::sleep(dur); } if let Some(cached_val) = self.cache.get(rdd.get_rdd_id(), split.get_index()) { let res: Vec<T> = bincode::deserialize(&cached_val).unwrap(); return Box::new(res.into_iter()); } self.loading.write().insert(key); let mut lock = self.loading.write(); let res: Vec<_> = rdd.compute(split.clone()).unwrap().collect(); let res_bytes = bincode::serialize(&res).unwrap(); let put_response = self .cache .put(rdd.get_rdd_id(), split.get_index(), res_bytes); lock.remove(&key); if let CachePutResponse::CachePutSuccess(size) = put_response { self.client(CacheTrackerMessage::AddedToCache { rdd_id: rdd.get_rdd_id(), partition: split.get_index(), host: env::Configuration::get().local_ip, size, }); } Box::new(res.into_iter()) } } //TODO drop_entry needs to be implemented } <file_sep>use std::sync::Arc; use crate::context::Context; use crate::rdd::Rdd; use crate::serializable_traits::{Data, SerFunc}; use serde_traitobject::Arc as SerArc; mod local_file_reader; pub use local_file_reader::{LocalFsReader, LocalFsReaderConfig}; pub trait ReaderConfiguration<I: Data> { fn make_reader<F, O>(self, context: Arc<Context>, decoder: F) -> SerArc<dyn Rdd<Item = O>> where O: Data, F: SerFunc(I) -> O; } <file_sep>use std::result::Result as StdResult; use hyper::{Body, Response, StatusCode}; use rand::Rng; use thiserror::Error; pub(self) mod shuffle_fetcher; pub(self) mod shuffle_manager; pub(self) mod shuffle_map_task; // re-exports: pub(crate) use shuffle_fetcher::ShuffleFetcher; pub(crate) use shuffle_manager::ShuffleManager; pub(crate) use shuffle_map_task::ShuffleMapTask; pub(crate) type Result<T> = StdResult<T, ShuffleError>; #[derive(Debug, Error)] pub enum ShuffleError { #[error("failure while initializing/running the async runtime")] AsyncRuntimeError, #[error("failed to create local shuffle dir after 10 attempts")] CouldNotCreateShuffleDir, #[error("deserialization error")] DeserializationError(#[from] bincode::Error), #[error("incorrect URI sent in the request")] IncorrectUri(#[from] http::uri::InvalidUri), #[error("internal server error")] InternalError, #[error("shuffle fetcher failed while fetching chunk")] FailedFetchOp, #[error("failed to start shuffle server")] FailedToStart, #[error(transparent)] NetworkError(#[from] crate::NetworkError), #[error("not valid request")] NotValidRequest, #[error("cached data not found")] RequestedCacheNotFound, #[error("unexpected shuffle server problem")] UnexpectedServerError(#[from] hyper::error::Error), #[error("unexpected URI sent in the request: {0}")] UnexpectedUri(String), } impl Into<Response<Body>> for ShuffleError { fn into(self) -> Response<Body> { match self { ShuffleError::UnexpectedUri(uri) => Response::builder() .status(StatusCode::BAD_REQUEST) .body(Body::from(format!("Failed to parse: {}", uri))) .unwrap(), ShuffleError::RequestedCacheNotFound => Response::builder() .status(StatusCode::NOT_FOUND) .body(Body::from(&[] as &[u8])) .unwrap(), _ => Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) .body(Body::from(&[] as &[u8])) .unwrap(), } } } impl ShuffleError { fn no_port(&self) -> bool { match self { ShuffleError::NetworkError(crate::NetworkError::FreePortNotFound(_, _)) => true, _ => false, } } fn deserialization_err(&self) -> bool { match self { ShuffleError::DeserializationError(_) => true, _ => false, } } } fn get_dynamic_port() -> u16 { const FIRST_DYNAMIC_PORT: u16 = 49152; const LAST_DYNAMIC_PORT: u16 = 65535; FIRST_DYNAMIC_PORT + rand::thread_rng().gen_range(0, LAST_DYNAMIC_PORT - FIRST_DYNAMIC_PORT) } #[cfg(test)] fn get_free_port() -> u16 { use std::net::TcpListener; let mut port; for _ in 0..100 { port = get_dynamic_port(); if TcpListener::bind(format!("127.0.0.1:{}", port)).is_ok() { return port; } } panic!("failed to find free port while testing"); } <file_sep>use std::cmp::min; use std::marker::PhantomData; use std::sync::Arc; use crate::serializable_traits::{AnyData, Data}; use serde_derive::{Deserialize, Serialize}; use crate::context::Context; use crate::dependency::{Dependency, OneToOneDependency}; use crate::error::{Error, Result}; use crate::rdd::{Rdd, RddBase, RddVals}; use crate::split::Split; #[derive(Clone, Serialize, Deserialize)] pub struct ZippedPartitionsSplit { fst_idx: usize, sec_idx: usize, idx: usize, #[serde(with = "serde_traitobject")] fst_split: Box<dyn Split>, #[serde(with = "serde_traitobject")] sec_split: Box<dyn Split>, } impl Split for ZippedPartitionsSplit { fn get_index(&self) -> usize { self.idx } } #[derive(Serialize, Deserialize)] pub struct ZippedPartitionsRdd<F: Data, S: Data> { #[serde(with = "serde_traitobject")] first: Arc<dyn Rdd<Item = F>>, #[serde(with = "serde_traitobject")] second: Arc<dyn Rdd<Item = S>>, vals: Arc<RddVals>, _marker_t: PhantomData<(F, S)>, } impl<F: Data, S: Data> Clone for ZippedPartitionsRdd<F, S> { fn clone(&self) -> Self { ZippedPartitionsRdd { first: self.first.clone(), second: self.second.clone(), vals: self.vals.clone(), _marker_t: PhantomData, } } } impl<F: Data, S: Data> RddBase for ZippedPartitionsRdd<F, S> { fn get_rdd_id(&self) -> usize { self.vals.id } fn get_context(&self) -> Arc<Context> { self.vals.context.upgrade().unwrap() } fn get_dependencies(&self) -> Vec<Dependency> { self.vals.dependencies.clone() } fn splits(&self) -> Vec<Box<dyn Split>> { let mut arr = Vec::with_capacity(min( self.first.number_of_splits(), self.second.number_of_splits(), )); for (fst, sec) in self.first.splits().iter().zip(self.second.splits().iter()) { let fst_idx = fst.get_index(); let sec_idx = sec.get_index(); arr.push(Box::new(ZippedPartitionsSplit { fst_idx, sec_idx, idx: fst_idx, fst_split: fst.clone(), sec_split: sec.clone(), }) as Box<dyn Split>) } arr } fn number_of_splits(&self) -> usize { self.splits().len() } fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { Ok(Box::new( self.iterator(split)? .map(|x| Box::new(x) as Box<dyn AnyData>), )) } fn cogroup_iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { self.iterator_any(split) } } impl<F: Data, S: Data> Rdd for ZippedPartitionsRdd<F, S> { type Item = (F, S); fn get_rdd(&self) -> Arc<dyn Rdd<Item = Self::Item>> { Arc::new(self.clone()) } fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(self.clone()) as Arc<dyn RddBase> } fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { let current_split = split .downcast::<ZippedPartitionsSplit>() .or(Err(Error::DowncastFailure("ZippedPartitionsSplit")))?; let fst_iter = self.first.iterator(current_split.fst_split.clone())?; let sec_iter = self.second.iterator(current_split.sec_split.clone())?; Ok(Box::new(fst_iter.zip(sec_iter))) } fn iterator(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { self.compute(split.clone()) } } impl<F: Data, S: Data> ZippedPartitionsRdd<F, S> { pub fn new(first: Arc<dyn Rdd<Item = F>>, second: Arc<dyn Rdd<Item = S>>) -> Self { let mut vals = RddVals::new(first.get_context()); vals.dependencies .push(Dependency::NarrowDependency(Arc::new( OneToOneDependency::new(first.get_rdd_base()), ))); let vals = Arc::new(vals); ZippedPartitionsRdd { first, second, vals, _marker_t: PhantomData, } } } <file_sep>use crate::serializable_traits::Data; use serde_derive::{Deserialize, Serialize}; use std::marker::PhantomData; // Aggregator for shuffle tasks. #[derive(Serialize, Deserialize)] pub struct Aggregator<K: Data, V: Data, C: Data> { #[serde(with = "serde_traitobject")] pub create_combiner: Box<dyn serde_traitobject::Fn(V) -> C + Send + Sync>, #[serde(with = "serde_traitobject")] pub merge_value: Box<dyn serde_traitobject::Fn((C, V)) -> C + Send + Sync>, #[serde(with = "serde_traitobject")] pub merge_combiners: Box<dyn serde_traitobject::Fn((C, C)) -> C + Send + Sync>, _marker: PhantomData<K>, } impl<K: Data, V: Data, C: Data> Aggregator<K, V, C> { pub fn new( create_combiner: Box<dyn serde_traitobject::Fn(V) -> C + Send + Sync>, merge_value: Box<dyn serde_traitobject::Fn((C, V)) -> C + Send + Sync>, merge_combiners: Box<dyn serde_traitobject::Fn((C, C)) -> C + Send + Sync>, ) -> Self { Aggregator { create_combiner, merge_value, merge_combiners, _marker: PhantomData, } } } impl<K: Data, V: Data> Default for Aggregator<K, V, Vec<V>> { fn default() -> Self { let merge_value = Box::new(Fn!(|mv: (Vec<V>, V)| { let (mut buf, v) = mv; buf.push(v); buf })); let create_combiner = Box::new(Fn!(|v: V| vec![v])); let merge_combiners = Box::new(Fn!(|mc: (Vec<V>, Vec<V>)| { let (mut b1, mut b2) = mc; b1.append(&mut b2); b1 })); Aggregator { create_combiner, merge_value, merge_combiners, _marker: PhantomData, } } } <file_sep>#![allow(where_clauses_object_safety, clippy::single_component_path_imports)] use native_spark::io::*; use native_spark::*; #[macro_use] extern crate serde_closure; use chrono::prelude::*; fn main() -> Result<()> { let context = Context::new()?; let deserializer = Fn!(|file: Vec<u8>| { String::from_utf8(file) .unwrap() .lines() .map(|s| s.to_string()) .collect::<Vec<_>>() }); let lines = context.read_source(LocalFsReaderConfig::new("./csv_folder"), deserializer); let line = lines.flat_map(Fn!(|lines: Vec<String>| { Box::new(lines.into_iter().map(|line| { let line = line.split(' ').collect::<Vec<_>>(); let mut time: i64 = line[8].parse::<i64>().unwrap(); time /= 1000; let time = Utc.timestamp(time, 0).hour(); ( (line[0].to_string(), line[1].to_string(), time), (line[7].parse::<i64>().unwrap(), 1.0), ) })) as Box<dyn Iterator<Item = _>> })); let sum = line.reduce_by_key(Fn!(|((vl, cl), (vr, cr))| (vl + vr, cl + cr)), 1); let avg = sum.map(Fn!(|(k, (v, c))| (k, v as f64 / c))); let res = avg.collect().unwrap(); println!("{:?}", &res[0]); Ok(()) } <file_sep>#![feature( arbitrary_self_types, coerce_unsized, core_intrinsics, fn_traits, never_type, specialization, unboxed_closures, unsize )] #![allow(dead_code, where_clauses_object_safety, deprecated)] #![allow(clippy::single_component_path_imports)] #[macro_use] extern crate downcast_rs; #[macro_use] extern crate serde_closure; pub mod serialized_data_capnp { include!(concat!(env!("OUT_DIR"), "/capnp/serialized_data_capnp.rs")); } pub mod context; pub use context::Context; mod executor; pub mod partitioner; mod shuffle; pub use partitioner::*; #[path = "rdd/rdd.rs"] pub mod rdd; pub use rdd::*; pub mod io; pub use io::*; mod dependency; pub use dependency::*; pub mod split; pub use split::*; mod cache; mod cache_tracker; #[macro_use] mod scheduler; pub mod aggregator; mod dag_scheduler; mod distributed_scheduler; mod local_scheduler; mod stage; mod task; pub use aggregator::*; mod env; mod job; mod map_output_tracker; mod result_task; pub mod serializable_traits; pub use env::DeploymentMode; pub mod error; pub use error::*; pub mod fs; mod hosts; pub mod utils; <file_sep>use std::clone::Clone; use std::cmp::Ordering; use std::collections::{BTreeMap, BTreeSet}; use std::marker::PhantomData; use std::option::Option; use std::sync::Arc; use crate::scheduler::NativeScheduler; use crate::serializable_traits::{Data, SerFunc}; use crate::stage::Stage; use crate::task::{TaskBase, TaskContext}; use crate::Rdd; use parking_lot::Mutex; #[derive(Clone, Debug)] pub struct Job { run_id: usize, job_id: usize, } impl Job { pub fn new(run_id: usize, job_id: usize) -> Self { Job { run_id, job_id } } } // manual ordering implemented because we want the jobs to sorted in reverse order impl PartialOrd for Job { fn partial_cmp(&self, other: &Job) -> Option<Ordering> { Some(other.job_id.cmp(&self.job_id)) } } impl PartialEq for Job { fn eq(&self, other: &Job) -> bool { self.job_id == other.job_id } } impl Eq for Job {} impl Ord for Job { fn cmp(&self, other: &Job) -> Ordering { other.job_id.cmp(&self.job_id) } } type PendingTasks = BTreeMap<Stage, BTreeSet<Box<dyn TaskBase>>>; /// Contains all the necessary types to run and track a job progress pub(crate) struct JobTracker<F, U: Data, T: Data> where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { pub output_parts: Vec<usize>, pub num_output_parts: usize, pub final_stage: Stage, pub func: Arc<F>, pub final_rdd: Arc<dyn Rdd<Item = T>>, pub run_id: usize, pub waiting: Arc<Mutex<BTreeSet<Stage>>>, pub running: Arc<Mutex<BTreeSet<Stage>>>, pub failed: Arc<Mutex<BTreeSet<Stage>>>, pub finished: Arc<Mutex<Vec<bool>>>, pub pending_tasks: Arc<Mutex<PendingTasks>>, _marker_t: PhantomData<T>, _marker_u: PhantomData<U>, } impl<F, U: Data, T: Data> JobTracker<F, U, T> where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { pub fn from_scheduler<S>( scheduler: &S, func: Arc<F>, final_rdd: Arc<dyn Rdd<Item = T>>, output_parts: Vec<usize>, ) -> JobTracker<F, U, T> where S: NativeScheduler, { let run_id = scheduler.get_next_job_id(); let final_stage = scheduler.new_stage(final_rdd.clone().get_rdd_base(), None); JobTracker::new(run_id, final_stage, func, final_rdd, output_parts) } fn new( run_id: usize, final_stage: Stage, func: Arc<F>, final_rdd: Arc<dyn Rdd<Item = T>>, output_parts: Vec<usize>, ) -> JobTracker<F, U, T> { let finished: Vec<bool> = (0..output_parts.len()).map(|_| false).collect(); let pending_tasks: BTreeMap<Stage, BTreeSet<Box<dyn TaskBase>>> = BTreeMap::new(); JobTracker { num_output_parts: output_parts.len(), output_parts, final_stage, func, final_rdd, run_id, waiting: Arc::new(Mutex::new(BTreeSet::new())), running: Arc::new(Mutex::new(BTreeSet::new())), failed: Arc::new(Mutex::new(BTreeSet::new())), finished: Arc::new(Mutex::new(finished)), pending_tasks: Arc::new(Mutex::new(pending_tasks)), _marker_t: PhantomData, _marker_u: PhantomData, } } } impl<F, U: Data, T: Data> Clone for JobTracker<F, U, T> where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { fn clone(&self) -> Self { JobTracker { output_parts: self.output_parts.clone(), num_output_parts: self.num_output_parts, final_stage: self.final_stage.clone(), func: self.func.clone(), final_rdd: self.final_rdd.clone(), run_id: self.run_id, waiting: self.waiting.clone(), running: self.running.clone(), failed: self.running.clone(), finished: self.finished.clone(), pending_tasks: self.pending_tasks.clone(), _marker_t: PhantomData, _marker_u: PhantomData, } } } #[cfg(test)] mod tests { use super::*; #[test] fn sort_job() { let mut jobs = vec![Job::new(1, 2), Job::new(1, 1), Job::new(1, 3)]; println!("{:?}", jobs); jobs.sort(); println!("{:?}", jobs); assert_eq!(jobs, vec![Job::new(1, 3), Job::new(1, 2), Job::new(1, 1),]) } } <file_sep>use std::ffi::OsString; use std::path::PathBuf; use thiserror::Error; pub type Result<T> = std::result::Result<T, Error>; pub type StdResult<T, E> = std::result::Result<T, E>; #[derive(Debug, Error)] pub enum Error { #[error("async runtime configuration error")] AsyncRuntimeError, #[error(transparent)] AsyncJoinError(#[from] tokio::task::JoinError), #[error("failed to run {command}")] CommandOutput { source: std::io::Error, command: String, }, #[error("failed to create the log file")] CreateLogFile(#[source] std::io::Error), #[error("failed to create the terminal logger")] CreateTerminalLogger, #[error("couldn't determine the current binary's name")] CurrentBinaryName, #[error("couldn't determine the path to the current binary")] CurrentBinaryPath, #[error("failed trying converting to type {0}")] ConversionError(&'static str), #[error(transparent)] BincodeDeserialization(#[from] bincode::Error), #[error(transparent)] CapnpDeserialization(#[from] capnp::Error), #[error("failure while downcasting an object to a concrete type: {0}")] DowncastFailure(&'static str), #[error("executor shutdown signal")] ExecutorShutdown, #[error("configuration failure: {0}")] GetOrCreateConfig(&'static str), #[error("partitioner not set")] LackingPartitioner, #[error("failed to load hosts file from {}", path.display())] LoadHosts { source: std::io::Error, path: PathBuf, }, #[error("network error")] NetworkError(#[from] NetworkError), #[error("failed to determine the home directory")] NoHome, #[error("failed to convert {:?} to a String", .0)] OsStringToString(OsString), #[error("failed writing to output source")] OutputWrite(#[source] std::io::Error), #[error("failed to parse hosts file at {}", path.display())] ParseHosts { source: toml::de::Error, path: PathBuf, }, #[error("failed to convert {} to a String", .0.display())] PathToString(PathBuf), #[error("failed to parse slave address {0}")] ParseHostAddress(String), #[error("failed reading from input source")] InputRead(#[source] std::io::Error), #[error(transparent)] ShuffleError(#[from] crate::shuffle::ShuffleError), #[error("operation not supported: {0}")] UnsupportedOperation(&'static str), } impl Error { pub(crate) fn executor_shutdown(&self) -> bool { match self { Error::ExecutorShutdown => true, _ => false, } } } #[derive(Debug, Error)] pub enum NetworkError { #[error(transparent)] TcpListener(#[from] tokio::io::Error), #[error("disconnected from address")] ConnectionFailure, #[error("failed to find free port {0}, tried {1} times")] FreePortNotFound(u16, usize), } <file_sep>use std::fs; use std::io::Write; use std::net::{Ipv4Addr, SocketAddrV4, TcpStream}; use std::ops::Range; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use crate::distributed_scheduler::DistributedScheduler; use crate::error::{Error, Result}; use crate::executor::{Executor, Signal}; use crate::io::ReaderConfiguration; use crate::local_scheduler::LocalScheduler; use crate::parallel_collection_rdd::ParallelCollection; use crate::rdd::union_rdd::UnionRdd; use crate::rdd::{Rdd, RddBase}; use crate::scheduler::NativeScheduler; use crate::serializable_traits::{Data, SerFunc}; use crate::serialized_data_capnp::serialized_data; use crate::task::TaskContext; use crate::{env, hosts}; use log::error; use once_cell::sync::OnceCell; use simplelog::*; use uuid::Uuid; // There is a problem with this approach since T needs to satisfy PartialEq, Eq for Range. // No such restrictions are needed for Vec. pub enum Sequence<T> { Range(Range<T>), Vec(Vec<T>), } #[derive(Clone)] enum Schedulers { Local(Arc<LocalScheduler>), Distributed(Arc<DistributedScheduler>), } impl Default for Schedulers { fn default() -> Schedulers { Schedulers::Local(Arc::new(LocalScheduler::new(20, true))) } } impl Schedulers { pub fn run_job<T: Data, U: Data, F>( &self, func: Arc<F>, final_rdd: Arc<dyn Rdd<Item = T>>, partitions: Vec<usize>, allow_local: bool, ) -> Result<Vec<U>> where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { use Schedulers::*; match self { Distributed(distributed) => { distributed .clone() .run_job(func, final_rdd, partitions, allow_local) } Local(local) => local .clone() .run_job(func, final_rdd, partitions, allow_local), } } } #[derive(Default)] pub struct Context { next_rdd_id: Arc<AtomicUsize>, next_shuffle_id: Arc<AtomicUsize>, scheduler: Schedulers, pub(crate) address_map: Vec<SocketAddrV4>, distributed_driver: bool, /// the executing job tmp work_dir work_dir: PathBuf, } impl Drop for Context { fn drop(&mut self) { //TODO clean up temp files #[cfg(debug_assertions)] { let deployment_mode = env::Configuration::get().deployment_mode; if self.distributed_driver && deployment_mode == env::DeploymentMode::Distributed { log::info!("inside context drop in master"); } else if deployment_mode == env::DeploymentMode::Distributed { log::info!("inside context drop in executor"); } } self.drop_executors(); Context::clean_up_work_dir(&self.work_dir); } } impl Context { pub fn new() -> Result<Arc<Self>> { Context::with_mode(env::Configuration::get().deployment_mode) } pub fn with_mode(mode: env::DeploymentMode) -> Result<Arc<Self>> { match mode { env::DeploymentMode::Distributed => { if env::Configuration::get().is_driver { Context::init_distributed_driver() } else { Context::init_distributed_worker()? } } env::DeploymentMode::Local => Context::init_local_scheduler(), } } fn init_local_scheduler() -> Result<Arc<Self>> { let job_id = Uuid::new_v4().to_string(); let job_work_dir = env::Configuration::get() .local_dir .join(format!("ns-job-{}", job_id)); fs::create_dir_all(&job_work_dir).unwrap(); initialize_loggers(job_work_dir.join("ns-driver.log")); let scheduler = Schedulers::Local(Arc::new(LocalScheduler::new(20, true))); Ok(Arc::new(Context { next_rdd_id: Arc::new(AtomicUsize::new(0)), next_shuffle_id: Arc::new(AtomicUsize::new(0)), scheduler, address_map: vec![SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0)], distributed_driver: false, work_dir: job_work_dir, })) } /// Initialization function for the application driver. /// * Distributes the configuration setup to the workers. /// * Distributes a copy of the application binary to all the active worker host nodes. /// * Launches the workers in the remote machine using the same binary (required). /// * Creates and returns a working Context. fn init_distributed_driver() -> Result<Arc<Self>> { let mut port: u16 = 10000; let mut address_map = Vec::new(); let job_id = Uuid::new_v4().to_string(); let job_work_dir = env::Configuration::get() .local_dir .join(format!("ns-job-{}", job_id)); let job_work_dir_str = job_work_dir .to_str() .ok_or_else(|| Error::PathToString(job_work_dir.clone()))?; let binary_path = std::env::current_exe().map_err(|_| Error::CurrentBinaryPath)?; let binary_path_str = binary_path .to_str() .ok_or_else(|| Error::PathToString(binary_path.clone()))? .into(); let binary_name = binary_path .file_name() .ok_or(Error::CurrentBinaryName)? .to_os_string() .into_string() .map_err(Error::OsStringToString)?; fs::create_dir_all(&job_work_dir).unwrap(); let conf_path = job_work_dir.join("config.toml"); let conf_path = conf_path.to_str().unwrap(); initialize_loggers(job_work_dir.join("ns-driver.log")); for address in &hosts::Hosts::get()?.slaves { log::debug!("deploying executor at address {:?}", address); let address_ip: Ipv4Addr = address .split('@') .nth(1) .ok_or_else(|| Error::ParseHostAddress(address.into()))? .parse() .map_err(|x| Error::ParseHostAddress(format!("{}", x)))?; address_map.push(SocketAddrV4::new(address_ip, port)); // Create work dir: Command::new("ssh") .args(&[address, "mkdir", &job_work_dir_str]) .output() .map_err(|e| Error::CommandOutput { source: e, command: "ssh mkdir".into(), })?; // Copy conf file to remote: Context::create_workers_config_file(address_ip, port, conf_path)?; let remote_path = format!("{}:{}/config.toml", address, job_work_dir_str); Command::new("scp") .args(&[conf_path, &remote_path]) .output() .map_err(|e| Error::CommandOutput { source: e, command: "scp config".into(), })?; // Copy binary: let remote_path = format!("{}:{}/{}", address, job_work_dir_str, binary_name); Command::new("scp") .args(&[&binary_path_str, &remote_path]) .output() .map_err(|e| Error::CommandOutput { source: e, command: "scp executor".into(), })?; // Deploy a remote slave: let path = format!("{}/{}", job_work_dir_str, binary_name); log::debug!("remote path {}", path); Command::new("ssh") .args(&[address, &path]) .spawn() .map_err(|e| Error::CommandOutput { source: e, command: "ssh run".into(), })?; port += 5000; } Ok(Arc::new(Context { next_rdd_id: Arc::new(AtomicUsize::new(0)), next_shuffle_id: Arc::new(AtomicUsize::new(0)), scheduler: Schedulers::Distributed(Arc::new(DistributedScheduler::new( 20, true, Some(address_map.clone()), 10000, ))), address_map, distributed_driver: true, work_dir: job_work_dir, })) } fn init_distributed_worker() -> Result<!> { let mut work_dir = PathBuf::from(""); match std::env::current_exe().map_err(|_| Error::CurrentBinaryPath) { Ok(binary_path) => { match binary_path.parent().ok_or_else(|| Error::CurrentBinaryPath) { Ok(dir) => work_dir = dir.into(), Err(err) => Context::worker_clean_up(Err(err), work_dir)?, }; initialize_loggers(work_dir.join("ns-executor.log")); } Err(err) => Context::worker_clean_up(Err(err), work_dir)?, } log::debug!("starting worker"); let port = match env::Configuration::get() .slave .as_ref() .map(|c| c.port) .ok_or(Error::GetOrCreateConfig("executor port not set")) { Ok(port) => port, Err(err) => Context::worker_clean_up(Err(err), work_dir)?, }; let executor = Arc::new(Executor::new(port)); Context::worker_clean_up(executor.worker(), work_dir) } fn worker_clean_up(run_result: Result<Signal>, work_dir: PathBuf) -> Result<!> { match run_result { Err(err) => { log::error!("executor failed with error: {}", err); Context::clean_up_work_dir(&work_dir); std::process::exit(1); } Ok(value) => { log::info!("executor closed gracefully with signal: {:?}", value); Context::clean_up_work_dir(&work_dir); std::process::exit(0); } } } #[allow(unused_must_use)] fn clean_up_work_dir(work_dir: &Path) { if env::Configuration::get().loggin.log_cleanup { // Remove created files. if fs::remove_dir_all(&work_dir).is_err() { log::error!("failed removing tmp work dir: {}", work_dir.display()); } } else if let Ok(dir) = fs::read_dir(work_dir) { for e in dir { if let Ok(p) = e { if let Ok(m) = p.metadata() { if m.is_dir() { fs::remove_dir_all(p.path()); } else { let file = p.path(); if let Some(ext) = file.extension() { if ext.to_str() != "log".into() { fs::remove_file(file); } } else { fs::remove_file(file); } } } } } } } fn create_workers_config_file(local_ip: Ipv4Addr, port: u16, config_path: &str) -> Result<()> { let mut current_config = env::Configuration::get().clone(); current_config.local_ip = local_ip; current_config.slave = Some(std::convert::From::<(bool, u16)>::from((true, port))); current_config.is_driver = false; let config_string = toml::to_string_pretty(&current_config).unwrap(); let mut config_file = fs::File::create(config_path).unwrap(); config_file.write_all(config_string.as_bytes()).unwrap(); Ok(()) } fn drop_executors(&self) { if env::Configuration::get().deployment_mode.is_local() { return; } for socket_addr in self.address_map.clone() { log::debug!( "dropping executor in {:?}:{:?}", socket_addr.ip(), socket_addr.port() ); if let Ok(mut stream) = TcpStream::connect(format!("{}:{}", socket_addr.ip(), socket_addr.port() + 10)) { let signal = bincode::serialize(&Signal::ShutDownGracefully).unwrap(); let mut message = capnp::message::Builder::new_default(); let mut task_data = message.init_root::<serialized_data::Builder>(); task_data.set_msg(&signal); capnp::serialize::write_message(&mut stream, &message) .map_err(Error::InputRead) .unwrap(); } else { error!( "Failed to connect to {}:{} in order to stop its executor", socket_addr.ip(), socket_addr.port() ); } } } pub fn new_rdd_id(self: &Arc<Self>) -> usize { self.next_rdd_id.fetch_add(1, Ordering::SeqCst) } pub fn new_shuffle_id(self: &Arc<Self>) -> usize { self.next_shuffle_id.fetch_add(1, Ordering::SeqCst) } pub fn make_rdd<T: Data, I>( self: &Arc<Self>, seq: I, num_slices: usize, ) -> serde_traitobject::Arc<dyn Rdd<Item = T>> where I: IntoIterator<Item = T>, { self.parallelize(seq, num_slices) } pub fn parallelize<T: Data, I>( self: &Arc<Self>, seq: I, num_slices: usize, ) -> serde_traitobject::Arc<dyn Rdd<Item = T>> where I: IntoIterator<Item = T>, { serde_traitobject::Arc::new(ParallelCollection::new(self.clone(), seq, num_slices)) } /// Load from a distributed source and turns it into a parallel collection. pub fn read_source<F, C, I: Data, O: Data>( self: &Arc<Self>, config: C, func: F, ) -> impl Rdd<Item = O> where F: SerFunc(I) -> O, C: ReaderConfiguration<I>, { config.make_reader(self.clone(), func) } pub fn run_job<T: Data, U: Data, F>( self: &Arc<Self>, rdd: Arc<dyn Rdd<Item = T>>, func: F, ) -> Result<Vec<U>> where F: SerFunc(Box<dyn Iterator<Item = T>>) -> U, { let cl = Fn!(move |(task_context, iter)| (func)(iter)); let func = Arc::new(cl); self.scheduler.run_job( func, rdd.clone(), (0..rdd.number_of_splits()).collect(), false, ) } pub fn run_job_with_partitions<T: Data, U: Data, F, P>( self: &Arc<Self>, rdd: Arc<dyn Rdd<Item = T>>, func: F, partitions: P, ) -> Result<Vec<U>> where F: SerFunc(Box<dyn Iterator<Item = T>>) -> U, P: IntoIterator<Item = usize>, { let cl = Fn!(move |(task_context, iter)| (func)(iter)); self.scheduler .run_job(Arc::new(cl), rdd, partitions.into_iter().collect(), false) } pub fn run_job_with_context<T: Data, U: Data, F>( self: &Arc<Self>, rdd: Arc<dyn Rdd<Item = T>>, func: F, ) -> Result<Vec<U>> where F: SerFunc((TaskContext, Box<dyn Iterator<Item = T>>)) -> U, { log::debug!("inside run job in context"); let func = Arc::new(func); self.scheduler.run_job( func, rdd.clone(), (0..rdd.number_of_splits()).collect(), false, ) } pub(crate) fn get_preferred_locs( &self, rdd: Arc<dyn RddBase>, partition: usize, ) -> Vec<std::net::Ipv4Addr> { match &self.scheduler { Schedulers::Distributed(scheduler) => scheduler.get_preferred_locs(rdd, partition), Schedulers::Local(scheduler) => scheduler.get_preferred_locs(rdd, partition), } } pub fn union<T: Data>(rdds: &[Arc<dyn Rdd<Item = T>>]) -> Result<UnionRdd<T>> { UnionRdd::new(rdds) } } static LOGGER: OnceCell<()> = OnceCell::new(); fn initialize_loggers<P: Into<PathBuf>>(file_path: P) { fn _initializer(file_path: PathBuf) { let log_level = env::Configuration::get().loggin.log_level.into(); log::info!("path for file logger: {}", file_path.display()); let file_logger: Box<dyn SharedLogger> = WriteLogger::new( log_level, Config::default(), fs::File::create(file_path).expect("not able to create log file"), ); let mut combined = vec![file_logger]; if let Some(term_logger) = TermLogger::new(log_level, Config::default(), TerminalMode::Mixed) { let logger: Box<dyn SharedLogger> = term_logger; combined.push(logger); } CombinedLogger::init(combined).unwrap(); } LOGGER.get_or_init(move || _initializer(file_path.into())); } <file_sep>use std::net::Ipv4Addr; use std::sync::Arc; use itertools::{Itertools, MinMaxResult}; use serde_derive::{Deserialize, Serialize}; use serde_traitobject::Arc as SerArc; use crate::context::Context; use crate::dependency::{Dependency, NarrowDependencyTrait, OneToOneDependency, RangeDependency}; use crate::error::{Error, Result}; use crate::partitioner::Partitioner; use crate::rdd::union_rdd::UnionVariants::{NonUniquePartitioner, PartitionerAware}; use crate::rdd::{Rdd, RddBase, RddVals}; use crate::serializable_traits::{AnyData, Data}; use crate::split::Split; #[derive(Clone, Serialize, Deserialize)] struct UnionSplit<T: 'static> { /// index of the partition idx: usize, /// the parent RDD this partition refers to rdd: SerArc<dyn Rdd<Item = T>>, /// index of the parent RDD this partition refers to parent_rdd_index: usize, /// index of the partition within the parent RDD this partition refers to parent_rdd_split_index: usize, } impl<T: Data> UnionSplit<T> { fn parent_partition(&self) -> Box<dyn Split> { self.rdd.splits()[self.parent_rdd_split_index].clone() } } impl<T: Data> Split for UnionSplit<T> { fn get_index(&self) -> usize { self.idx } } #[derive(Clone, Serialize, Deserialize)] struct PartitionerAwareUnionSplit { idx: usize, } impl PartitionerAwareUnionSplit { fn parents<'a, T: Data>( &'a self, rdds: &'a [SerArc<dyn Rdd<Item = T>>], ) -> impl Iterator<Item = Box<dyn Split>> + 'a { rdds.iter().map(move |rdd| rdd.splits()[self.idx].clone()) } } impl Split for PartitionerAwareUnionSplit { fn get_index(&self) -> usize { self.idx } } #[derive(Serialize, Deserialize)] pub struct UnionRdd<T: 'static>(UnionVariants<T>); impl<T> UnionRdd<T> where T: Data, { pub(crate) fn new(rdds: &[Arc<dyn Rdd<Item = T>>]) -> Result<Self> { Ok(UnionRdd(UnionVariants::new(rdds)?)) } } #[derive(Serialize, Deserialize)] enum UnionVariants<T: 'static> { NonUniquePartitioner { rdds: Vec<SerArc<dyn Rdd<Item = T>>>, vals: Arc<RddVals>, }, /// An RDD that can take multiple RDDs partitioned by the same partitioner and /// unify them into a single RDD while preserving the partitioner. So m RDDs with p partitions each /// will be unified to a single RDD with p partitions and the same partitioner. PartitionerAware { rdds: Vec<SerArc<dyn Rdd<Item = T>>>, vals: Arc<RddVals>, #[serde(with = "serde_traitobject")] part: Box<dyn Partitioner>, }, } impl<T: Data> Clone for UnionVariants<T> { fn clone(&self) -> Self { match self { NonUniquePartitioner { rdds, vals, .. } => NonUniquePartitioner { rdds: rdds.clone(), vals: vals.clone(), }, PartitionerAware { rdds, vals, part, .. } => PartitionerAware { rdds: rdds.clone(), vals: vals.clone(), part: part.clone(), }, } } } impl<T: Data> UnionVariants<T> { fn new(rdds: &[Arc<dyn Rdd<Item = T>>]) -> Result<Self> { let context = rdds[0].get_context(); let mut vals = RddVals::new(context); let mut pos = 0; let final_rdds: Vec<_> = rdds.iter().map(|rdd| rdd.clone().into()).collect(); if !UnionVariants::has_unique_partitioner(rdds) { let deps = rdds .iter() .map(|rdd| { let rdd_base = rdd.get_rdd_base(); let num_parts = rdd_base.number_of_splits(); let dep = Dependency::NarrowDependency(Arc::new(RangeDependency::new( rdd_base, 0, pos, num_parts, ))); pos += num_parts; dep }) .collect(); vals.dependencies = deps; let vals = Arc::new(vals); log::debug!("inside unique partitioner constructor"); Ok(NonUniquePartitioner { rdds: final_rdds, vals, }) } else { let part = rdds[0].partitioner().ok_or(Error::LackingPartitioner)?; log::debug!("inside partition aware constructor"); let deps = rdds .iter() .map(|x| { Dependency::NarrowDependency( Arc::new(OneToOneDependency::new(x.get_rdd_base())) as Arc<dyn NarrowDependencyTrait>, ) }) .collect(); vals.dependencies = deps; let vals = Arc::new(vals); Ok(PartitionerAware { rdds: final_rdds, vals, part, }) } } fn has_unique_partitioner(rdds: &[Arc<dyn Rdd<Item = T>>]) -> bool { rdds.iter() .map(|p| p.partitioner()) .try_fold(None, |prev: Option<Box<dyn Partitioner>>, p| { if let Some(partitioner) = p { if let Some(prev_partitioner) = prev { if prev_partitioner.equals((&*partitioner).as_any()) { // only continue in case both partitioners are the same Ok(Some(partitioner)) } else { Err(()) } } else { // first element Ok(Some(partitioner)) } } else { Err(()) } }) .is_ok() } fn current_pref_locs<'a>( &'a self, rdd: Arc<dyn RddBase>, split: &dyn Split, context: Arc<Context>, ) -> impl Iterator<Item = std::net::Ipv4Addr> + 'a { context .get_preferred_locs(rdd, split.get_index()) .into_iter() } } impl<T: Data> RddBase for UnionRdd<T> { fn get_rdd_id(&self) -> usize { match &self.0 { NonUniquePartitioner { vals, .. } => vals.id, PartitionerAware { vals, .. } => vals.id, } } fn get_context(&self) -> Arc<Context> { match &self.0 { NonUniquePartitioner { vals, .. } => vals.context.upgrade().unwrap(), PartitionerAware { vals, .. } => vals.context.upgrade().unwrap(), } } fn get_dependencies(&self) -> Vec<Dependency> { match &self.0 { NonUniquePartitioner { vals, .. } => vals.dependencies.clone(), PartitionerAware { vals, .. } => vals.dependencies.clone(), } } fn preferred_locations(&self, split: Box<dyn Split>) -> Vec<Ipv4Addr> { match &self.0 { NonUniquePartitioner { .. } => Vec::new(), PartitionerAware { rdds, .. } => { log::debug!( "finding preferred location for PartitionerAwareUnionRdd, partition {}", split.get_index() ); let split = &*split .downcast::<PartitionerAwareUnionSplit>() .or(Err(Error::DowncastFailure("UnionSplit"))) .unwrap(); let locations = rdds.iter() .zip(split.parents(rdds.as_slice())) .map(|(rdd, part)| { let parent_locations = self.0.current_pref_locs( rdd.get_rdd_base(), &*part, self.get_context(), ); log::debug!("location of {} partition {} = {}", 1, 2, 3); parent_locations }); // Find the location that maximum number of parent partitions prefer let location = match locations.flatten().minmax_by_key(|loc| *loc) { MinMaxResult::MinMax(_, max) => Some(max), MinMaxResult::OneElement(e) => Some(e), MinMaxResult::NoElements => None, }; log::debug!( "selected location for PartitionerAwareRdd, partition {} = {:?}", split.get_index(), location ); location.into_iter().collect() } } } fn splits(&self) -> Vec<Box<dyn Split>> { match &self.0 { NonUniquePartitioner { rdds, .. } => rdds .iter() .enumerate() .flat_map(|(rdd_idx, rdd)| { rdd.splits() .into_iter() .enumerate() .map(move |(split_idx, _split)| (rdd_idx, rdd, split_idx)) }) .enumerate() .map(|(idx, (rdd_idx, rdd, s_idx))| { Box::new(UnionSplit { idx, rdd: rdd.clone(), parent_rdd_index: rdd_idx, parent_rdd_split_index: s_idx, }) as Box<dyn Split> }) .collect(), PartitionerAware { part, .. } => { let num_partitions = part.get_num_of_partitions(); (0..num_partitions) .map(|idx| Box::new(PartitionerAwareUnionSplit { idx }) as Box<dyn Split>) .collect() } } } fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { log::debug!("inside iterator_any union_rdd",); Ok(Box::new( self.iterator(split)? .map(|x| Box::new(x) as Box<dyn AnyData>), )) } fn partitioner(&self) -> Option<Box<dyn Partitioner>> { match &self.0 { NonUniquePartitioner { .. } => None, PartitionerAware { part, .. } => Some(part.clone()), } } } impl<T: Data> Rdd for UnionRdd<T> { type Item = T; fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(UnionRdd(self.0.clone())) as Arc<dyn RddBase> } fn get_rdd(&self) -> Arc<dyn Rdd<Item = T>> { Arc::new(UnionRdd(self.0.clone())) as Arc<dyn Rdd<Item = T>> } fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = T>>> { match &self.0 { NonUniquePartitioner { rdds, .. } => { let part = &*split .downcast::<UnionSplit<T>>() .or(Err(Error::DowncastFailure("UnionSplit")))?; let parent = &rdds[part.parent_rdd_index]; parent.iterator(part.parent_partition()) } PartitionerAware { rdds, .. } => { let split = split .downcast::<PartitionerAwareUnionSplit>() .or(Err(Error::DowncastFailure("PartitionerAwareUnionSplit")))?; let iter: Result<Vec<_>> = rdds .iter() .zip(split.parents(&rdds)) .map(|(rdd, p)| rdd.iterator(p.clone())) .collect(); Ok(Box::new(iter?.into_iter().flatten())) } } } } <file_sep>use std::fmt::Display; use std::marker::PhantomData; use std::net::Ipv4Addr; use std::sync::Arc; use crate::env; use crate::rdd::Rdd; use crate::serializable_traits::Data; use crate::task::{Task, TaskBase, TaskContext}; use serde_derive::{Deserialize, Serialize}; use serde_traitobject::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] pub struct ResultTask<T: Data, U: Data, F> where F: Fn((TaskContext, Box<dyn Iterator<Item = T>>)) -> U + 'static + Send + Sync + Serialize + Deserialize + Clone, { pub task_id: usize, pub run_id: usize, pub stage_id: usize, pinned: bool, #[serde(with = "serde_traitobject")] pub rdd: Arc<dyn Rdd<Item = T>>, pub func: Arc<F>, pub partition: usize, pub locs: Vec<Ipv4Addr>, pub output_id: usize, _marker: PhantomData<T>, } impl<T: Data, U: Data, F> Display for ResultTask<T, U, F> where F: Fn((TaskContext, Box<dyn Iterator<Item = T>>)) -> U + 'static + Send + Sync + Serialize + Deserialize + Clone, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ResultTask({}, {})", self.stage_id, self.partition) } } impl<T: Data, U: Data, F> ResultTask<T, U, F> where F: Fn((TaskContext, Box<dyn Iterator<Item = T>>)) -> U + 'static + Send + Sync + Serialize + Deserialize + Clone, { pub fn clone(&self) -> Self { ResultTask { task_id: self.task_id, run_id: self.run_id, stage_id: self.stage_id, pinned: self.rdd.is_pinned(), rdd: self.rdd.clone(), func: self.func.clone(), partition: self.partition, locs: self.locs.clone(), output_id: self.output_id, _marker: PhantomData, } } } impl<T: Data, U: Data, F> ResultTask<T, U, F> where F: Fn((TaskContext, Box<dyn Iterator<Item = T>>)) -> U + 'static + Send + Sync + Serialize + Deserialize + Clone, { pub fn new( task_id: usize, run_id: usize, stage_id: usize, rdd: Arc<dyn Rdd<Item = T>>, func: Arc<F>, partition: usize, locs: Vec<Ipv4Addr>, output_id: usize, ) -> Self { ResultTask { task_id, run_id, stage_id, pinned: rdd.is_pinned(), rdd, func, partition, locs, output_id, _marker: PhantomData, } } } impl<T: Data, U: Data, F> TaskBase for ResultTask<T, U, F> where F: Fn((TaskContext, Box<dyn Iterator<Item = T>>)) -> U + 'static + Send + Sync + Serialize + Deserialize + Clone, { fn get_run_id(&self) -> usize { self.run_id } fn get_stage_id(&self) -> usize { self.stage_id } fn get_task_id(&self) -> usize { self.task_id } fn is_pinned(&self) -> bool { self.pinned } fn preferred_locations(&self) -> Vec<Ipv4Addr> { self.locs.clone() } fn generation(&self) -> Option<i64> { Some(env::Env::get().map_output_tracker.get_generation()) } } impl<T: Data, U: Data, F> Task for ResultTask<T, U, F> where F: Fn((TaskContext, Box<dyn Iterator<Item = T>>)) -> U + 'static + Send + Sync + Serialize + Deserialize + Clone, { fn run(&self, id: usize) -> serde_traitobject::Box<dyn serde_traitobject::Any + Send + Sync> { let split = self.rdd.splits()[self.partition].clone(); let context = TaskContext::new(self.stage_id, self.partition, id); serde_traitobject::Box::new((self.func)((context, self.rdd.iterator(split).unwrap()))) as serde_traitobject::Box<dyn serde_traitobject::Any + Send + Sync> } } <file_sep>use crate::scheduler::Scheduler; use crate::task::TaskBase; use std::any::Any; use std::collections::HashMap; use std::error::Error; #[derive(Debug, Clone)] pub struct FetchFailedVals { pub server_uri: String, pub shuffle_id: usize, pub map_id: usize, pub reduce_id: usize, } // Send, Sync are required only because of local scheduler where threads are used. // Since distributed scheduler runs tasks on different processes, such restriction is not required. // Have to redesign this because serializing the Send, Sync traits is not such a good idea. pub struct CompletionEvent { pub task: Box<dyn TaskBase>, pub reason: TastEndReason, pub result: Option<Box<dyn Any + Send + Sync>>, pub accum_updates: HashMap<i64, Box<dyn Any + Send + Sync>>, } //impl CompletionEvent { // pub fn get_result<T: 'static + Send + Sync + serde_traitobject::Any + Debug>(&mut self) -> T { // if let Some(data) = self.result.take() { // // let data = data as Box<Any>; // let res: Box<T> = Box::<Any>::downcast(data.into_any()).unwrap(); // *res // // if let Ok(res) = data.downcast::<T>() { // // *res // // } else { // // panic!("unable to downcast to appropriate type"); // // } // } else { // panic!("result seems to empty"); // } // } //} pub enum TastEndReason { Success, FetchFailed(FetchFailedVals), Error(Box<dyn Error + Send + Sync>), OtherFailure(String), } pub trait DAGTask: TaskBase { fn get_run_id(&self) -> usize; fn get_stage_id(&self) -> usize; fn get_gen(&self) -> i64; fn generation(&self) -> Option<i64> { Some(self.get_gen()) } } pub trait DAGScheduler: Scheduler { fn submit_tasks(&self, tasks: Vec<Box<dyn TaskBase>>, run_id: i64) -> (); fn task_ended( task: Box<dyn TaskBase>, reason: TastEndReason, result: Box<dyn Any>, accum_updates: HashMap<i64, Box<dyn Any>>, ); } <file_sep>use native_spark::io::*; use native_spark::partitioner::HashPartitioner; use native_spark::rdd::CoGroupedRdd; use native_spark::*; use serde_traitobject::Arc as SerArc; use std::fs::{create_dir_all, File}; use std::io::prelude::*; use std::sync::Arc; #[macro_use] extern crate serde_closure; use once_cell::sync::Lazy; static CONTEXT: Lazy<Arc<Context>> = Lazy::new(|| Context::new().unwrap()); static WORK_DIR: Lazy<std::path::PathBuf> = Lazy::new(std::env::temp_dir); const TEST_DIR: &str = "ns_test_dir"; #[allow(unused_must_use)] fn set_up(file_name: &str) { let temp_dir = WORK_DIR.join(TEST_DIR); println!("Creating tests in dir: {}", (&temp_dir).to_str().unwrap()); create_dir_all(&temp_dir); let fixture = b"This is some textual test data.\nCan be converted to strings and there are two lines."; if !std::path::Path::new(file_name).exists() { let mut f = File::create(temp_dir.join(file_name)).unwrap(); f.write_all(fixture).unwrap(); } } #[test] fn test_make_rdd() -> Result<()> { let sc = CONTEXT.clone(); let col = sc.make_rdd((0..10).collect::<Vec<_>>(), 32); let vec_iter = col.map(Fn!(|i| (0..i).collect::<Vec<_>>())); let res = vec_iter.collect()?; let expected = (0..10) .map(|i| (0..i).collect::<Vec<_>>()) .collect::<Vec<_>>(); assert_eq!(expected, res); Ok(()) } #[test] fn test_map_partitions() -> Result<()> { let sc = CONTEXT.clone(); let rdd = sc.make_rdd(vec![1, 2, 3, 4], 2); let partition_sums = rdd .map_partitions(Fn!( |iter: Box<dyn Iterator<Item = i64>>| Box::new(std::iter::once(iter.sum::<i64>())) as Box<dyn Iterator<Item = i64>> )) .collect()?; assert_eq!(partition_sums, vec![3, 7]); assert_eq!(rdd.glom().collect()?, vec![vec![1, 2], vec![3, 4]]); Ok(()) } #[test] fn test_fold() { let sc = CONTEXT.clone(); let rdd = sc.make_rdd((-1000..1000).collect::<Vec<_>>(), 10); let f = Fn!(|c, x| c + x); // def op: (Int, Int) => Int = (c: Int, x: Int) => c + x let sum = rdd.fold(0, f).unwrap(); assert_eq!(sum, -1000) } #[test] fn test_fold_with_modifying_initial_value() { let sc = CONTEXT.clone(); let rdd = sc .make_rdd((-1000..1000).collect::<Vec<i32>>(), 10) .map(Fn!(|x| vec![x])); let f = Fn!(|mut c: Vec<i32>, x: Vec<i32>| { c[0] += x[0]; c }); let sum = rdd.fold(vec![0], f).unwrap(); assert_eq!(sum[0], -1000) } #[test] fn test_aggregate() { let sc = CONTEXT.clone(); let pairs = sc.make_rdd( vec![ ("a".to_owned(), 1_i32), ("b".to_owned(), 2), ("a".to_owned(), 2), ("c".to_owned(), 5), ("a".to_owned(), 3), ], 2, ); use std::collections::{HashMap, HashSet}; type StringMap = HashMap<String, i32>; let empty_map = StringMap::new(); let merge_element = Fn!(|mut map: StringMap, pair: (String, i32)| { *map.entry(pair.0).or_insert(0) += pair.1; map }); let merge_maps = Fn!(|mut map1: StringMap, map2: StringMap| { for (key, value) in map2 { *map1.entry(key).or_insert(0) += value; } map1 }); let result = pairs .aggregate(empty_map, merge_element, merge_maps) .unwrap(); assert_eq!( result.into_iter().collect::<HashSet<_>>(), vec![ ("a".to_owned(), 6), ("b".to_owned(), 2), ("c".to_owned(), 5) ] .into_iter() .collect() ) } #[test] fn test_take() -> Result<()> { let sc = CONTEXT.clone(); let col1 = vec![1, 2, 3, 4, 5, 6]; let col1_rdd = sc.clone().parallelize(col1, 4); let taken_1 = col1_rdd.take(1)?; assert_eq!(taken_1.len(), 1); let taken_3 = col1_rdd.take(3)?; assert_eq!(taken_3.len(), 3); let taken_7 = col1_rdd.take(7)?; assert_eq!(taken_7.len(), 6); let col2: Vec<i32> = vec![]; let col2_rdd = sc.parallelize(col2, 4); let taken_0 = col2_rdd.take(1)?; assert!(taken_0.is_empty()); Ok(()) } #[test] fn test_first() { let sc = CONTEXT.clone(); let col1 = vec![1, 2, 3, 4]; let col1_rdd = sc.clone().parallelize(col1, 4); let taken_1 = col1_rdd.first(); assert!(taken_1.is_ok()); let col2: Vec<i32> = vec![]; let col2_rdd = sc.parallelize(col2, 4); let taken_0 = col2_rdd.first(); assert!(taken_0.is_err()); } #[test] fn test_read_files_bytes() -> Result<()> { let deserializer = Fn!(|file: Vec<u8>| -> Vec<String> { // do stuff with the read files ... let parsed: Vec<_> = String::from_utf8(file) .unwrap() .lines() .map(|s| s.to_string()) .collect(); assert_eq!(parsed.len(), 2); assert_eq!(parsed[0], "This is some textual test data."); // return lines parsed }); // Single file test let file_name = "test_file_1"; let file_path = WORK_DIR.join(TEST_DIR).join(file_name); set_up(file_name); let context = CONTEXT.clone(); let result = context .read_source(LocalFsReaderConfig::new(file_path), deserializer) .collect() .unwrap(); assert_eq!(result[0].len(), 2); // Multiple files test (0..10).for_each(|idx| { let f_name = format!("test_file_{}", idx); let path = WORK_DIR.join(TEST_DIR).join(f_name.as_str()); set_up(path.as_path().to_str().unwrap()); }); let sc = CONTEXT.clone(); let files = sc.read_source( LocalFsReaderConfig::new(WORK_DIR.join(TEST_DIR)), deserializer, ); let result: Vec<_> = files.collect().unwrap().into_iter().flatten().collect(); assert_eq!(result.len(), 20); Ok(()) } #[test] fn test_read_files() -> Result<()> { let deserializer = Fn!(|file: std::path::PathBuf| { let mut file = File::open(file).unwrap(); let mut content = String::new(); file.read_to_string(&mut content).unwrap(); let parsed: Vec<_> = content.lines().map(|s| s.to_string()).collect(); assert_eq!(parsed.len(), 2); assert_eq!(parsed[0], "This is some textual test data."); parsed }); let file_name = "test_file_1"; let file_path = WORK_DIR.join(TEST_DIR).join(file_name); set_up(file_name); let context = CONTEXT.clone(); let result = context .read_source(LocalFsReaderConfig::new(file_path), deserializer) .collect() .unwrap(); assert_eq!(result[0].len(), 2); Ok(()) } #[test] fn test_distinct() -> Result<()> { use std::collections::HashSet; let sc = CONTEXT.clone(); let rdd = sc.parallelize(vec![1, 2, 2, 2, 3, 3, 3, 4, 4, 5], 3); assert_eq!(rdd.distinct().collect()?.len(), 5); assert_eq!( rdd.distinct() .collect()? .into_iter() .collect::<HashSet<_>>(), rdd.distinct() .collect()? .into_iter() .collect::<HashSet<_>>() ); assert_eq!( rdd.distinct_with_num_partitions(2) .collect()? .into_iter() .collect::<HashSet<_>>(), rdd.distinct() .collect()? .into_iter() .collect::<HashSet<_>>() ); assert_eq!( rdd.distinct_with_num_partitions(10) .collect()? .into_iter() .collect::<HashSet<_>>(), rdd.distinct() .collect()? .into_iter() .collect::<HashSet<_>>() ); Ok(()) } #[test] fn test_partition_wise_sampling() -> Result<()> { let sc = CONTEXT.clone(); // w/o replace & num < sample { let rdd = sc.clone().parallelize(vec![1, 2, 3, 4, 5], 6); let result = rdd.take_sample(false, 6, Some(123))?; assert!(result.len() == 5); // guaranteed with this seed: assert!(result[0] > result[1]); } // replace & Poisson & no-GapSampling { // high enough samples param to guarantee drawing >1 times w/ replacement let rdd = sc.clone().parallelize((0_i32..100).collect::<Vec<_>>(), 5); let result = rdd.take_sample(true, 80, None)?; assert!(result.len() == 80); } // no replace & Bernoulli + GapSampling { let rdd = sc.parallelize((0_i32..100).collect::<Vec<_>>(), 5); let result = rdd.take_sample(false, 10, None)?; assert!(result.len() == 10); } Ok(()) } #[test] fn test_cartesian() -> Result<()> { let sc = CONTEXT.clone(); let rdd1 = sc.parallelize((0..2).collect::<Vec<_>>(), 2); let rdd2 = sc.parallelize("αβ".chars().collect::<Vec<_>>(), 2); let res = rdd1.cartesian(rdd2).collect()?; itertools::assert_equal(res, vec![(0, 'α'), (0, 'β'), (1, 'α'), (1, 'β')]); Ok(()) } #[test] fn test_coalesced() -> Result<()> { let sc = CONTEXT.clone(); // do not shuffle { let rdd = sc.parallelize(vec![1; 101], 101); let res = rdd.coalesce(5, false).glom().collect()?; assert_eq!(res.len(), 5); assert_eq!(res[0].iter().sum::<u8>(), 20); assert_eq!(res[4].iter().sum::<u8>(), 21); } // shuffle and increase num partitions { let rdd = sc.parallelize(vec![1; 100], 20); let res = rdd.repartition(100).glom().collect()?; assert_eq!(res.len(), 100); } Ok(()) } #[test] fn test_union() -> Result<()> { let sc = CONTEXT.clone(); let rdd0 = sc.parallelize(vec![1i32, 2, 3, 4], 2); let rdd1 = sc.parallelize(vec![5i32, 6, 7, 8], 2); let res = rdd0.union(rdd1.get_rdd())?; assert_eq!(res.collect()?.len(), 8); let sc = CONTEXT.clone(); let join = || { let col1 = vec![ (1, ("A".to_string(), "B".to_string())), (2, ("C".to_string(), "D".to_string())), (3, ("E".to_string(), "F".to_string())), (4, ("G".to_string(), "H".to_string())), ]; let col1 = sc.parallelize(col1, 4); let col2 = vec![ (1, "A1".to_string()), (1, "A2".to_string()), (2, "B1".to_string()), (2, "B2".to_string()), (3, "C1".to_string()), (3, "C2".to_string()), ]; let col2 = sc.parallelize(col2, 4); col2.join(col1.clone(), 4) }; let join1 = join(); let join2 = join(); let res = join1.union(join2.get_rdd()).unwrap().collect().unwrap(); assert_eq!(res.len(), 12); Ok(()) } #[test] fn test_union_with_unique_partitioner() { let sc = CONTEXT.clone(); let partitioner = HashPartitioner::<i32>::new(2); let co_grouped = || { let rdd = vec![ (1i32, "A".to_string()), (2, "B".to_string()), (3, "C".to_string()), (4, "D".to_string()), ]; let rdd0 = SerArc::new(sc.parallelize(rdd.clone(), 2)) as SerArc<dyn Rdd<Item = (i32, String)>>; let rdd1 = SerArc::new(sc.parallelize(rdd, 2)) as SerArc<dyn Rdd<Item = (i32, String)>>; CoGroupedRdd::<i32>::new( vec![rdd0.get_rdd_base().into(), rdd1.get_rdd_base().into()], Box::new(partitioner.clone()), ) }; let rdd0 = co_grouped(); let rdd1 = co_grouped(); let res = rdd0.union(rdd1.get_rdd()).unwrap().collect().unwrap(); assert_eq!(res.len(), 8); } #[test] fn test_zip() { let sc = CONTEXT.clone(); let col1 = vec![1, 2, 3, 4, 5]; let col2 = vec![ "5a".to_string(), "4b".to_string(), "3c".to_string(), "2d".to_string(), "1a".to_string(), ]; let first = sc.parallelize(col1, 3); let second = sc.parallelize(col2, 3); let res = first.zip(Arc::new(second)).collect().unwrap(); let expected = vec![ (1, "5a".to_string()), (2, "4b".to_string()), (3, "3c".to_string()), (4, "2d".to_string()), (5, "1a".to_string()), ]; assert_eq!(res, expected); } #[test] fn test_intersection_with_num_partitions() { let sc = CONTEXT.clone(); let col1 = vec![1, 2, 3, 4, 5, 10, 12, 13, 19, 0]; let col2 = vec![3, 4, 5, 6, 7, 8, 11, 13]; let first = sc.parallelize(col1, 2); let second = sc.parallelize(col2, 4); let mut res = first .intersection_with_num_partitions(Arc::new(second), 3) .collect() .unwrap(); res.sort(); let expected = vec![3, 4, 5, 13]; assert_eq!(res, expected); } #[test] fn test_intersection() { let sc = CONTEXT.clone(); let col1 = vec![1, 2, 3, 4, 5, 10, 12, 13, 19, 0]; let col2 = vec![3, 4, 5, 6, 7, 8, 11, 13]; let first = sc.parallelize(col1, 2); let second = sc.parallelize(col2, 4); let mut res = first.intersection(Arc::new(second)).collect().unwrap(); res.sort(); let expected = vec![3, 4, 5, 13]; assert_eq!(res, expected); } #[test] fn test_count_by_value() -> Result<()> { let sc = CONTEXT.clone(); let rdd = sc.parallelize(vec![1i32, 2, 1, 2, 2], 2); let rdd = rdd.count_by_value(); let res = rdd.collect().unwrap(); assert_eq!(res.len(), 2); itertools::assert_equal(res, vec![(1, 2), (2, 3)]); Ok(()) }<file_sep>extern crate capnpc; fn main() { capnpc::CompilerCommand::new() .src_prefix("src") .file("src/capnp/serialized_data.capnp") .run() .expect("capnpc compiling issue"); } <file_sep>#![allow(where_clauses_object_safety)] use native_spark::*; fn main() -> Result<()> { let sc = Context::new()?; let col1 = vec![ (1, ("A".to_string(), "B".to_string())), (2, ("C".to_string(), "D".to_string())), (3, ("E".to_string(), "F".to_string())), (4, ("G".to_string(), "H".to_string())), ]; let col1 = sc.parallelize(col1, 4); let col2 = vec![ (1, "A1".to_string()), (1, "A2".to_string()), (2, "B1".to_string()), (2, "B2".to_string()), (3, "C1".to_string()), (3, "C2".to_string()), ]; let col2 = sc.parallelize(col2, 4); let inner_joined_rdd = col2.join(col1.clone(), 4); let res = inner_joined_rdd.collect().unwrap(); println!("res {:?}", res); Ok(()) } <file_sep>// WIP pub trait FileSystem { fn get_default_port(&self) -> u16 { 0 } // fn canonicalize_url(&self, mut url: Url) -> Url { // if url.port().is_none() && self.get_default_port() > 0 { // url.set_port(Some(self.get_default_port())); // } // return url; // } // // fn get_canonical_uri(&self) -> Url { // self.canonicalize_url(self.get_uri().clone()) // } //fn get_uri(&self) -> &Url; //fn get_fs_of_path(Path abs_or_fq_path); } <file_sep>use std::hash::Hash; use std::sync::Arc; use std::time::Instant; use crate::aggregator::Aggregator; use crate::context::Context; use crate::dependency::{Dependency, ShuffleDependency}; use crate::env; use crate::error::Result; use crate::partitioner::Partitioner; use crate::rdd::{Rdd, RddBase, RddVals}; use crate::serializable_traits::{AnyData, Data}; use crate::shuffle::ShuffleFetcher; use crate::split::Split; use dashmap::DashMap; use serde_derive::{Deserialize, Serialize}; #[derive(Clone, Serialize, Deserialize)] struct ShuffledRddSplit { index: usize, } impl ShuffledRddSplit { fn new(index: usize) -> Self { ShuffledRddSplit { index } } } impl Split for ShuffledRddSplit { fn get_index(&self) -> usize { self.index } } #[derive(Serialize, Deserialize)] pub struct ShuffledRdd<K: Data + Eq + Hash, V: Data, C: Data> { #[serde(with = "serde_traitobject")] parent: Arc<dyn Rdd<Item = (K, V)>>, #[serde(with = "serde_traitobject")] aggregator: Arc<Aggregator<K, V, C>>, vals: Arc<RddVals>, #[serde(with = "serde_traitobject")] part: Box<dyn Partitioner>, shuffle_id: usize, } impl<K: Data + Eq + Hash, V: Data, C: Data> Clone for ShuffledRdd<K, V, C> { fn clone(&self) -> Self { ShuffledRdd { parent: self.parent.clone(), aggregator: self.aggregator.clone(), vals: self.vals.clone(), part: self.part.clone(), shuffle_id: self.shuffle_id, } } } impl<K: Data + Eq + Hash, V: Data, C: Data> ShuffledRdd<K, V, C> { pub(crate) fn new( parent: Arc<dyn Rdd<Item = (K, V)>>, aggregator: Arc<Aggregator<K, V, C>>, part: Box<dyn Partitioner>, ) -> Self { let ctx = parent.get_context(); let shuffle_id = ctx.new_shuffle_id(); let mut vals = RddVals::new(ctx); vals.dependencies .push(Dependency::ShuffleDependency(Arc::new( ShuffleDependency::new( shuffle_id, false, parent.get_rdd_base(), aggregator.clone(), part.clone(), ), ))); let vals = Arc::new(vals); ShuffledRdd { parent, aggregator, vals, part, shuffle_id, } } } impl<K: Data + Eq + Hash, V: Data, C: Data> RddBase for ShuffledRdd<K, V, C> { fn get_rdd_id(&self) -> usize { self.vals.id } fn get_context(&self) -> Arc<Context> { self.vals.context.upgrade().unwrap() } fn get_dependencies(&self) -> Vec<Dependency> { self.vals.dependencies.clone() } fn splits(&self) -> Vec<Box<dyn Split>> { (0..self.part.get_num_of_partitions()) .map(|x| Box::new(ShuffledRddSplit::new(x)) as Box<dyn Split>) .collect() } fn number_of_splits(&self) -> usize { self.part.get_num_of_partitions() } fn partitioner(&self) -> Option<Box<dyn Partitioner>> { Some(self.part.clone()) } fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { log::debug!("inside iterator_any shuffledrdd",); Ok(Box::new( self.iterator(split)? .map(|(k, v)| Box::new((k, v)) as Box<dyn AnyData>), )) } fn cogroup_iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { log::debug!("inside cogroup iterator_any shuffledrdd",); Ok(Box::new(self.iterator(split)?.map(|(k, v)| { Box::new((k, Box::new(v) as Box<dyn AnyData>)) as Box<dyn AnyData> }))) } } impl<K: Data + Eq + Hash, V: Data, C: Data> Rdd for ShuffledRdd<K, V, C> { type Item = (K, C); fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(self.clone()) as Arc<dyn RddBase> } fn get_rdd(&self) -> Arc<dyn Rdd<Item = Self::Item>> { Arc::new(self.clone()) } fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { log::debug!("compute inside shuffled rdd"); let combiners: Arc<DashMap<K, Option<C>>> = Arc::new(DashMap::new()); let comb_clone = combiners.clone(); let agg = self.aggregator.clone(); let merge_pair = move |(k, c): (K, C)| { if let Some(mut old_c) = comb_clone.get_mut(&k) { let old = old_c.take().unwrap(); let input = ((old, c),); let output = agg.merge_combiners.call(input); *old_c = Some(output); } else { comb_clone.insert(k, Some(c)); } }; let start = Instant::now(); let shuffle_id = self.shuffle_id; let split_idx = split.get_index(); let executor = env::Env::get_async_handle(); executor.enter(|| -> Result<()> { let fut = ShuffleFetcher::fetch(shuffle_id, split_idx, merge_pair); Ok(futures::executor::block_on(fut)?) })?; log::debug!("time taken for fetching {}", start.elapsed().as_millis()); let combiners = Arc::try_unwrap(combiners).unwrap(); Ok(Box::new( combiners.into_iter().map(|(k, v)| (k, v.unwrap())), )) } } <file_sep>use std::cmp::Ordering; use std::fs; use std::hash::Hash; use std::io::{BufWriter, Write}; use std::net::Ipv4Addr; use std::path::Path; use std::sync::{Arc, Weak}; use crate::context::Context; use crate::dependency::Dependency; use crate::error::{Error, Result}; use crate::partitioner::{HashPartitioner, Partitioner}; use crate::serializable_traits::{AnyData, Data, Func, SerFunc}; use crate::split::Split; use crate::task::TaskContext; use crate::utils; use crate::utils::random::{BernoulliSampler, PoissonSampler, RandomSampler}; use fasthash::MetroHasher; use rand::{Rng, SeedableRng}; use serde_derive::{Deserialize, Serialize}; use serde_traitobject::{Arc as SerArc, Deserialize, Serialize}; pub mod parallel_collection_rdd; pub use parallel_collection_rdd::*; pub mod cartesian_rdd; pub use cartesian_rdd::*; pub mod co_grouped_rdd; pub use co_grouped_rdd::*; pub mod coalesced_rdd; pub use coalesced_rdd::*; pub mod mapper_rdd; pub use mapper_rdd::*; pub mod flatmap_rdd; pub use flatmap_rdd::*; pub mod pair_rdd; pub use pair_rdd::*; pub mod partitionwise_sampled_rdd; pub use partitionwise_sampled_rdd::*; pub mod shuffled_rdd; pub use shuffled_rdd::*; pub mod map_partitions_rdd; pub use map_partitions_rdd::*; pub mod zip_rdd; pub use zip_rdd::*; pub mod union_rdd; pub use union_rdd::*; // Values which are needed for all RDDs #[derive(Serialize, Deserialize)] pub(crate) struct RddVals { pub id: usize, pub dependencies: Vec<Dependency>, should_cache: bool, #[serde(skip_serializing, skip_deserializing)] pub context: Weak<Context>, } impl RddVals { pub fn new(sc: Arc<Context>) -> Self { RddVals { id: sc.new_rdd_id(), dependencies: Vec::new(), should_cache: false, context: Arc::downgrade(&sc), } } fn cache(mut self) -> Self { self.should_cache = true; self } } // Due to the lack of HKTs in Rust, it is difficult to have collection of generic data with different types. // Required for storing multiple RDDs inside dependencies and other places like Tasks, etc., // Refactored RDD trait into two traits one having RddBase trait which contains only non generic methods which provide information for dependency lists // Another separate Rdd containing generic methods like map, etc., pub trait RddBase: Send + Sync + Serialize + Deserialize { fn get_rdd_id(&self) -> usize; fn get_context(&self) -> Arc<Context>; fn get_dependencies(&self) -> Vec<Dependency>; fn preferred_locations(&self, _split: Box<dyn Split>) -> Vec<Ipv4Addr> { Vec::new() } fn partitioner(&self) -> Option<Box<dyn Partitioner>> { None } fn splits(&self) -> Vec<Box<dyn Split>>; fn number_of_splits(&self) -> usize { self.splits().len() } // Analyse whether this is required or not. It requires downcasting while executing tasks which could hurt performance. fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>>; fn cogroup_iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { self.iterator_any(split) } fn is_pinned(&self) -> bool { false } } impl PartialOrd for dyn RddBase { fn partial_cmp(&self, other: &dyn RddBase) -> Option<Ordering> { Some(self.get_rdd_id().cmp(&other.get_rdd_id())) } } impl PartialEq for dyn RddBase { fn eq(&self, other: &dyn RddBase) -> bool { self.get_rdd_id() == other.get_rdd_id() } } impl Eq for dyn RddBase {} impl Ord for dyn RddBase { fn cmp(&self, other: &dyn RddBase) -> Ordering { self.get_rdd_id().cmp(&other.get_rdd_id()) } } impl<I: Rdd + ?Sized> RddBase for serde_traitobject::Arc<I> { fn get_rdd_id(&self) -> usize { (**self).get_rdd_base().get_rdd_id() } fn get_context(&self) -> Arc<Context> { (**self).get_rdd_base().get_context() } fn get_dependencies(&self) -> Vec<Dependency> { (**self).get_rdd_base().get_dependencies() } fn splits(&self) -> Vec<Box<dyn Split>> { (**self).get_rdd_base().splits() } fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { (**self).get_rdd_base().iterator_any(split) } } impl<I: Rdd + ?Sized> Rdd for serde_traitobject::Arc<I> { type Item = I::Item; fn get_rdd(&self) -> Arc<dyn Rdd<Item = Self::Item>> { (**self).get_rdd() } fn get_rdd_base(&self) -> Arc<dyn RddBase> { (**self).get_rdd_base() } fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { (**self).compute(split) } } // Rdd containing methods associated with processing pub trait Rdd: RddBase + 'static { type Item: Data; fn get_rdd(&self) -> Arc<dyn Rdd<Item = Self::Item>>; fn get_rdd_base(&self) -> Arc<dyn RddBase>; fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>>; fn iterator(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { self.compute(split) } fn map<U: Data, F>(&self, f: F) -> SerArc<dyn Rdd<Item = U>> where F: SerFunc(Self::Item) -> U, Self: Sized, { SerArc::new(MapperRdd::new(self.get_rdd(), f)) } fn flat_map<U: Data, F>(&self, f: F) -> SerArc<dyn Rdd<Item = U>> where F: SerFunc(Self::Item) -> Box<dyn Iterator<Item = U>>, Self: Sized, { SerArc::new(FlatMapperRdd::new(self.get_rdd(), f)) } /// Return a new RDD by applying a function to each partition of this RDD. fn map_partitions<U: Data, F>(&self, func: F) -> SerArc<dyn Rdd<Item = U>> where F: SerFunc(Box<dyn Iterator<Item = Self::Item>>) -> Box<dyn Iterator<Item = U>>, Self: Sized, { let ignore_idx = Fn!(move |_index: usize, items: Box<dyn Iterator<Item = Self::Item>>| -> Box<dyn Iterator<Item = _>> { (func)(items) }); SerArc::new(MapPartitionsRdd::new(self.get_rdd(), ignore_idx)) } /// Return a new RDD by applying a function to each partition of this RDD, /// while tracking the index of the original partition. fn map_partitions_with_index<U: Data, F>(&self, f: F) -> SerArc<dyn Rdd<Item = U>> where F: SerFunc(usize, Box<dyn Iterator<Item = Self::Item>>) -> Box<dyn Iterator<Item = U>>, Self: Sized, { SerArc::new(MapPartitionsRdd::new(self.get_rdd(), f)) } /// Return an RDD created by coalescing all elements within each partition into an array. #[allow(clippy::type_complexity)] fn glom(&self) -> SerArc<dyn Rdd<Item = Vec<Self::Item>>> where Self: Sized, { let func = Fn!( |_index: usize, iter: Box<dyn Iterator<Item = Self::Item>>| Box::new(std::iter::once( iter.collect::<Vec<_>>() )) as Box<Iterator<Item = Vec<Self::Item>>> ); SerArc::new(MapPartitionsRdd::new(self.get_rdd(), Box::new(func))) } fn save_as_text_file(&self, path: String) -> Result<Vec<()>> where Self: Sized, { fn save<R: Data>(ctx: TaskContext, iter: Box<dyn Iterator<Item = R>>, path: String) { fs::create_dir_all(&path).unwrap(); let id = ctx.split_id; let file_path = Path::new(&path).join(format!("part-{}", id)); let f = fs::File::create(file_path).expect("unable to create file"); let mut f = BufWriter::new(f); for item in iter { let line = format!("{:?}", item); f.write_all(line.as_bytes()) .expect("error while writing to file"); } } let cl = Fn!(move |(ctx, iter)| save::<Self::Item>(ctx, iter, path.to_string())); self.get_context().run_job_with_context(self.get_rdd(), cl) } fn reduce<F>(&self, f: F) -> Result<Option<Self::Item>> where Self: Sized, F: SerFunc(Self::Item, Self::Item) -> Self::Item, { // cloned cause we will use `f` later. let cf = f.clone(); let reduce_partition = Fn!(move |iter: Box<dyn Iterator<Item = Self::Item>>| { let acc = iter.reduce(&cf); match acc { None => vec![], Some(e) => vec![e], } }); let results = self.get_context().run_job(self.get_rdd(), reduce_partition); Ok(results?.into_iter().flatten().reduce(f)) } /// Aggregate the elements of each partition, and then the results for all the partitions, using a /// given associative function and a neutral "initial value". The function /// Fn(t1, t2) is allowed to modify t1 and return it as its result value to avoid object /// allocation; however, it should not modify t2. /// /// This behaves somewhat differently from fold operations implemented for non-distributed /// collections. This fold operation may be applied to partitions individually, and then fold /// those results into the final result, rather than apply the fold to each element sequentially /// in some defined ordering. For functions that are not commutative, the result may differ from /// that of a fold applied to a non-distributed collection. /// /// # Arguments /// /// * `init` - an initial value for the accumulated result of each partition for the `op` /// operator, and also the initial value for the combine results from different /// partitions for the `f` function - this will typically be the neutral /// element (e.g. `0` for summation) /// * `f` - a function used to both accumulate results within a partition and combine results /// from different partitions fn fold<F>(&self, init: Self::Item, f: F) -> Result<Self::Item> where Self: Sized, F: SerFunc(Self::Item, Self::Item) -> Self::Item, { let cf = f.clone(); let zero = init.clone(); let reduce_partition = Fn!(move |iter: Box<dyn Iterator<Item = Self::Item>>| iter.fold(zero.clone(), &cf)); let results = self.get_context().run_job(self.get_rdd(), reduce_partition); Ok(results?.into_iter().fold(init, f)) } /// Aggregate the elements of each partition, and then the results for all the partitions, using /// given combine functions and a neutral "initial value". This function can return a different result /// type, U, than the type of this RDD, T. Thus, we need one operation for merging a T into an U /// and one operation for merging two U's, as in Rust Iterator fold method. Both of these functions are /// allowed to modify and return their first argument instead of creating a new U to avoid memory /// allocation. /// /// # Arguments /// /// * `init` - an initial value for the accumulated result of each partition for the `seq_fn` function, /// and also the initial value for the combine results from /// different partitions for the `comb_fn` function - this will typically be the /// neutral element (e.g. `vec![]` for vector aggregation or `0` for summation) /// * `seq_fn` - a function used to accumulate results within a partition /// * `comb_fn` - an associative function used to combine results from different partitions fn aggregate<U: Data, SF, CF>(&self, init: U, seq_fn: SF, comb_fn: CF) -> Result<U> where Self: Sized, SF: SerFunc(U, Self::Item) -> U, CF: SerFunc(U, U) -> U, { let zero = init.clone(); let reduce_partition = Fn!(move |iter: Box<dyn Iterator<Item = Self::Item>>| iter.fold(zero.clone(), &seq_fn)); let results = self.get_context().run_job(self.get_rdd(), reduce_partition); Ok(results?.into_iter().fold(init, comb_fn)) } /// Return the Cartesian product of this RDD and another one, that is, the RDD of all pairs of /// elements (a, b) where a is in `this` and b is in `other`. fn cartesian<U: Data>( &self, other: serde_traitobject::Arc<dyn Rdd<Item = U>>, ) -> SerArc<dyn Rdd<Item = (Self::Item, U)>> where Self: Sized, { SerArc::new(CartesianRdd::new(self.get_rdd(), other.into())) } /// Return a new RDD that is reduced into `num_partitions` partitions. /// /// This results in a narrow dependency, e.g. if you go from 1000 partitions /// to 100 partitions, there will not be a shuffle, instead each of the 100 /// new partitions will claim 10 of the current partitions. If a larger number /// of partitions is requested, it will stay at the current number of partitions. /// /// However, if you're doing a drastic coalesce, e.g. to num_partitions = 1, /// this may result in your computation taking place on fewer nodes than /// you like (e.g. one node in the case of num_partitions = 1). To avoid this, /// you can pass shuffle = true. This will add a shuffle step, but means the /// current upstream partitions will be executed in parallel (per whatever /// the current partitioning is). /// /// ## Notes /// /// With shuffle = true, you can actually coalesce to a larger number /// of partitions. This is useful if you have a small number of partitions, /// say 100, potentially with a few partitions being abnormally large. Calling /// coalesce(1000, shuffle = true) will result in 1000 partitions with the /// data distributed using a hash partitioner. The optional partition coalescer /// passed in must be serializable. fn coalesce(&self, num_partitions: usize, shuffle: bool) -> SerArc<dyn Rdd<Item = Self::Item>> where Self: Sized, { if shuffle { // Distributes elements evenly across output partitions, starting from a random partition. use std::hash::Hasher; let distributed_partition = Fn!( move |index: usize, items: Box<dyn Iterator<Item = Self::Item>>| { let mut hasher = MetroHasher::default(); index.hash(&mut hasher); let mut rand = utils::random::get_default_rng_from_seed(hasher.finish()); let mut position = rand.gen_range(0, num_partitions); Box::new(items.map(move |t| { // Note that the hash code of the key will just be the key itself. // The HashPartitioner will mod it with the number of total partitions. position += 1; (position, t) })) as Box<dyn Iterator<Item = (usize, Self::Item)>> } ); let map_steep: SerArc<dyn Rdd<Item = (usize, Self::Item)>> = SerArc::new(MapPartitionsRdd::new(self.get_rdd(), distributed_partition)); let partitioner = Box::new(HashPartitioner::<usize>::new(num_partitions)); SerArc::new(CoalescedRdd::new( Arc::new(map_steep.partition_by_key(partitioner)), num_partitions, )) } else { SerArc::new(CoalescedRdd::new(self.get_rdd(), num_partitions)) } } fn collect(&self) -> Result<Vec<Self::Item>> where Self: Sized, { let cl = Fn!(|iter: Box<dyn Iterator<Item = Self::Item>>| iter.collect::<Vec<Self::Item>>()); let results = self.get_context().run_job(self.get_rdd(), cl)?; let size = results.iter().fold(0, |a, b: &Vec<Self::Item>| a + b.len()); Ok(results .into_iter() .fold(Vec::with_capacity(size), |mut acc, v| { acc.extend(v); acc })) } fn count(&self) -> Result<u64> where Self: Sized, { let context = self.get_context(); let counting_func = Fn!(|iter: Box<dyn Iterator<Item = Self::Item>>| { iter.count() as u64 }); Ok(context .run_job(self.get_rdd(), counting_func)? .into_iter() .sum()) } /// Return the count of each unique value in this RDD as a dictionary of (value, count) pairs. fn count_by_value(&self) -> SerArc<dyn Rdd<Item = (Self::Item, u64)>> where Self: Sized, Self::Item: Data + Eq + Hash, { self.map(Fn!(|x| (x, 1u64))) .reduce_by_key(Box::new(Fn!(|(x, y)| x + y)) as Box< dyn Func((u64, u64)) -> u64, >, self.number_of_splits()) } /// Return a new RDD containing the distinct elements in this RDD. fn distinct_with_num_partitions( &self, num_partitions: usize, ) -> SerArc<dyn Rdd<Item = Self::Item>> where Self: Sized, Self::Item: Data + Eq + Hash, { self.map(Box::new(Fn!(|x| (Some(x), None))) as Box< dyn Func(Self::Item) -> (Option<Self::Item>, Option<Self::Item>), >) .reduce_by_key(Box::new(Fn!(|(x, y)| y)), num_partitions) .map(Box::new(Fn!(|x: ( Option<Self::Item>, Option<Self::Item> )| { let (x, y) = x; x.unwrap() }))) } /// Return a new RDD containing the distinct elements in this RDD. fn distinct(&self) -> SerArc<dyn Rdd<Item = Self::Item>> where Self: Sized, Self::Item: Data + Eq + Hash, { self.distinct_with_num_partitions(self.number_of_splits()) } /// Return the first element in this RDD. fn first(&self) -> Result<Self::Item> where Self: Sized, { if let Some(result) = self.take(1)?.into_iter().next() { Ok(result) } else { Err(Error::UnsupportedOperation("empty collection")) } } /// Return a new RDD that has exactly num_partitions partitions. /// /// Can increase or decrease the level of parallelism in this RDD. Internally, this uses /// a shuffle to redistribute data. /// /// If you are decreasing the number of partitions in this RDD, consider using `coalesce`, /// which can avoid performing a shuffle. fn repartition(&self, num_partitions: usize) -> SerArc<dyn Rdd<Item = Self::Item>> where Self: Sized, { self.coalesce(num_partitions, true) } /// Take the first num elements of the RDD. It works by first scanning one partition, and use the /// results from that partition to estimate the number of additional partitions needed to satisfy /// the limit. /// /// This method should only be used if the resulting array is expected to be small, as /// all the data is loaded into the driver's memory. fn take(&self, num: usize) -> Result<Vec<Self::Item>> where Self: Sized, { //TODO: in original spark this is configurable; see rdd/RDD.scala:1397 // Math.max(conf.get(RDD_LIMIT_SCALE_UP_FACTOR), 2) const SCALE_UP_FACTOR: f64 = 2.0; if num == 0 { return Ok(vec![]); } let mut buf = vec![]; let total_parts = self.number_of_splits() as u32; let mut parts_scanned = 0_u32; while buf.len() < num && parts_scanned < total_parts { // The number of partitions to try in this iteration. It is ok for this number to be // greater than total_parts because we actually cap it at total_parts in run_job. let mut num_parts_to_try = 1u32; let left = num - buf.len(); if parts_scanned > 0 { // If we didn't find any rows after the previous iteration, quadruple and retry. // Otherwise, interpolate the number of partitions we need to try, but overestimate // it by 50%. We also cap the estimation in the end. let parts_scanned = f64::from(parts_scanned); num_parts_to_try = if buf.is_empty() { (parts_scanned * SCALE_UP_FACTOR).ceil() as u32 } else { let num_parts_to_try = (1.5 * left as f64 * parts_scanned / (buf.len() as f64)).ceil(); num_parts_to_try.min(parts_scanned * SCALE_UP_FACTOR) as u32 }; } let partitions: Vec<_> = (parts_scanned as usize ..total_parts.min(parts_scanned + num_parts_to_try) as usize) .collect(); let num_partitions = partitions.len() as u32; let take_from_partion = Fn!(move |iter: Box<dyn Iterator<Item = Self::Item>>| { iter.take(left).collect::<Vec<Self::Item>>() }); let res = self.get_context().run_job_with_partitions( self.get_rdd(), take_from_partion, partitions, )?; res.into_iter().for_each(|r| { let take = num - buf.len(); buf.extend(r.into_iter().take(take)); }); parts_scanned += num_partitions; } Ok(buf) } /// Return a sampled subset of this RDD. /// /// # Arguments /// /// * `with_replacement` - can elements be sampled multiple times (replaced when sampled out) /// * `fraction` - expected size of the sample as a fraction of this RDD's size /// ** if without replacement: probability that each element is chosen; fraction must be [0, 1] /// ** if with replacement: expected number of times each element is chosen; fraction must be greater than or equal to 0 /// * seed for the random number generator /// /// # Notes /// /// This is NOT guaranteed to provide exactly the fraction of the count of the given RDD. /// /// Replacement requires extra allocations due to the nature of the used sampler (Poisson distribution). /// This implies a performance penalty but should be negligible unless fraction and the dataset are rather large. fn sample(&self, with_replacement: bool, fraction: f64) -> SerArc<dyn Rdd<Item = Self::Item>> where Self: Sized, { assert!(fraction >= 0.0); let sampler = if with_replacement { Arc::new(PoissonSampler::new(fraction, true)) as Arc<dyn RandomSampler<Self::Item>> } else { Arc::new(BernoulliSampler::new(fraction)) as Arc<dyn RandomSampler<Self::Item>> }; SerArc::new(PartitionwiseSampledRdd::new(self.get_rdd(), sampler, true)) } /// Return a fixed-size sampled subset of this RDD in an array. /// /// # Arguments /// /// `with_replacement` - can elements be sampled multiple times (replaced when sampled out) /// /// # Notes /// /// This method should only be used if the resulting array is expected to be small, /// as all the data is loaded into the driver's memory. /// /// Replacement requires extra allocations due to the nature of the used sampler (Poisson distribution). /// This implies a performance penalty but should be negligible unless fraction and the dataset are rather large. fn take_sample( &self, with_replacement: bool, num: u64, seed: Option<u64>, ) -> Result<Vec<Self::Item>> where Self: Sized, { const NUM_STD_DEV: f64 = 10.0f64; const REPETITION_GUARD: u8 = 100; //TODO: this could be const eval when the support is there for the necessary functions let max_sample_size = std::u64::MAX - (NUM_STD_DEV * (std::u64::MAX as f64).sqrt()) as u64; assert!(num <= max_sample_size); if num == 0 { return Ok(vec![]); } let initial_count = self.count()?; if initial_count == 0 { return Ok(vec![]); } // The original implementation uses java.util.Random which is a LCG pseudorng, // not cryptographically secure and some problems; // Here we choose Pcg64, which is a proven good performant pseudorng although without // strong cryptographic guarantees, which ain't necessary here. let mut rng = if let Some(seed) = seed { rand_pcg::Pcg64::seed_from_u64(seed) } else { // PCG with default specification state and stream params utils::random::get_default_rng() }; if !with_replacement && num >= initial_count { let mut sample = self.collect()?; utils::randomize_in_place(&mut sample, &mut rng); Ok(sample) } else { let fraction = utils::random::compute_fraction_for_sample_size( num, initial_count, with_replacement, ); let mut samples = self.sample(with_replacement, fraction).collect()?; // If the first sample didn't turn out large enough, keep trying to take samples; // this shouldn't happen often because we use a big multiplier for the initial size. let mut num_iters = 0; while samples.len() < num as usize && num_iters < REPETITION_GUARD { log::warn!( "Needed to re-sample due to insufficient sample size. Repeat #{}", num_iters ); samples = self.sample(with_replacement, fraction).collect()?; num_iters += 1; } if num_iters >= REPETITION_GUARD { panic!("Repeated sampling {} times; aborting", REPETITION_GUARD) } utils::randomize_in_place(&mut samples, &mut rng); Ok(samples.into_iter().take(num as usize).collect::<Vec<_>>()) } } /// Applies a function f to all elements of this RDD. fn for_each<F>(&self, func: F) -> Result<Vec<()>> where F: SerFunc(Self::Item), Self: Sized, { let func = Fn!(move |iter: Box<dyn Iterator<Item = Self::Item>>| iter.for_each(&func)); self.get_context().run_job(self.get_rdd(), func) } /// Applies a function f to each partition of this RDD. fn for_each_partition<F>(&self, func: F) -> Result<Vec<()>> where F: SerFunc(Box<dyn Iterator<Item = Self::Item>>), Self: Sized + 'static, { let func = Fn!(move |iter: Box<dyn Iterator<Item = Self::Item>>| (&func)(iter)); self.get_context().run_job(self.get_rdd(), func) } fn union( &self, other: Arc<dyn Rdd<Item = Self::Item>>, ) -> Result<SerArc<dyn Rdd<Item = Self::Item>>> where Self: Clone, { Ok(SerArc::new(Context::union(&[ Arc::new(self.clone()) as Arc<dyn Rdd<Item = Self::Item>>, other, ])?)) } fn zip<S: Data>( &self, second: Arc<dyn Rdd<Item = S>>, ) -> SerArc<dyn Rdd<Item = (Self::Item, S)>> where Self: Clone, { SerArc::new(ZippedPartitionsRdd::<Self::Item, S>::new( Arc::new(self.clone()) as Arc<dyn Rdd<Item = Self::Item>>, second, )) } fn intersection<T>(&self, other: Arc<T>) -> SerArc<dyn Rdd<Item = Self::Item>> where Self: Clone, Self::Item: Data + Eq + Hash, T: Rdd<Item = Self::Item> + Sized, { self.intersection_with_num_partitions(other, self.number_of_splits()) } fn intersection_with_num_partitions<T>( &self, other: Arc<T>, num_splits: usize, ) -> SerArc<dyn Rdd<Item = Self::Item>> where Self: Clone, Self::Item: Data + Eq + Hash, T: Rdd<Item = Self::Item> + Sized, { let other = other .map(Box::new(Fn!( |x: Self::Item| -> (Self::Item, Option<Self::Item>) { (x, None) } ))) .clone(); self.map( Box::new(Fn!( |x| -> (Self::Item, Option<Self::Item>){ (x, None) } ) ) ).cogroup( other, Box::new(HashPartitioner::<Self::Item>::new(num_splits)) as Box<dyn Partitioner> ).map( Box::new( Fn!( |(x, (v1, v2)): (Self::Item, (Vec::<Option<Self::Item>>, Vec::<Option<Self::Item>>))| -> Option<Self::Item> { if v1.len() >= 1 && v2.len() >= 1 { Some(x) } else { None } } ) ) ).map_partitions( Box::new( Fn!( |iter: Box<dyn Iterator<Item=Option<Self::Item>>>| -> Box<dyn Iterator<Item=Self::Item>> { Box::new( iter.filter(|x| x.is_some()).map(|x| x.unwrap()) ) as Box<dyn Iterator<Item=Self::Item>> } ) ) ) } } pub trait Reduce<T> { fn reduce<F>(self, f: F) -> Option<T> where Self: Sized, F: FnMut(T, T) -> T; } impl<T, I> Reduce<T> for I where I: Iterator<Item = T>, { #[inline] fn reduce<F>(mut self, f: F) -> Option<T> where Self: Sized, F: FnMut(T, T) -> T, { self.next().map(|first| self.fold(first, f)) } } <file_sep>use once_cell::sync::Lazy; use regex::Regex; use uriparse::{Authority, Fragment, Query, URI}; pub const SEPARATOR: char = '/'; pub const SEPARATOR_CHAR: char = '/'; pub const CUR_DIR: &str = "."; pub static WINDOWS: Lazy<bool> = Lazy::new(|| cfg!(windows)); static HAS_URI_SCHEME: Lazy<Regex> = Lazy::new(|| Regex::new("[a-zA-Z][a-zA-Z0-9+-.]+:").unwrap()); static HAS_DRIVE_LETTER_SPECIFIER: Lazy<Regex> = Lazy::new(|| Regex::new("^/?[a-zA-Z]:").unwrap()); #[derive(Eq, PartialEq, Debug)] pub struct Path { url: URI<'static>, } impl Path { pub fn from_url(url: URI<'static>) -> Self { Path { url } } pub fn from_path_string(path_string: &str) -> Self { // TODO can't directly parse as string might not be escaped let mut path_string: String = path_string.to_string(); if path_string.is_empty() { panic!("can not create a Path from an empty string"); } if Self::has_windows_drive(&path_string) && !path_string.starts_with('/') { path_string = format!("/{:?}", path_string); } let mut scheme = None; let mut authority = None; let mut index = 0; // parse uri scheme if any present let colon = path_string.find(':'); let slash = path_string.find('/'); if colon.is_some() && (slash.is_none() || colon.unwrap() < slash.unwrap()) { scheme = Some(path_string.get(0..colon.unwrap()).unwrap()); index = colon.unwrap() + 1; } if path_string.get(index..).unwrap().starts_with("//") && path_string.len() - index > 2 { let next_slash = path_string[index + 2..] .find('/') .map(|fi| index + 2 + fi) .unwrap(); let auth_end = if next_slash > 0 { next_slash } else { path_string.len() }; authority = Some(path_string.get(index + 2..auth_end).unwrap()); index = auth_end; } let path = path_string.get(index..path_string.len()); if scheme.is_none() { scheme = Some("file"); } let path = Self::normalize_path(scheme.unwrap().to_string(), path.unwrap().to_string()); let mut url = URI::from_parts( scheme.unwrap(), None::<Authority>, path.as_str(), None::<Query>, None::<Fragment>, ) .unwrap(); url.normalize(); Path { url: url.into_owned(), } } pub fn from_scheme_auth_path(scheme: &str, auth: Option<&str>, path: &str) -> Self { let mut path = path.to_string(); if path.is_empty() { panic!("cannot creeate path from empty string"); } if Self::has_windows_drive(&path) && !path.starts_with('/') { path = format!("/{}", path); } if !*WINDOWS && !path.starts_with('/') { path = format!("./{}", path); } path = Self::normalize_path(scheme.to_string(), path); let url = URI::from_parts(scheme, auth, path.as_str(), None::<Query>, None::<Fragment>).unwrap(); Path::from_url(url.into_owned()) } pub fn to_url(&self) -> &URI { &self.url } pub fn merge_paths(path1: Path, path2: Path) -> Path { let mut path2 = path2.to_url().path().to_string(); path2 = path2 .get(Self::start_position_without_windows_drive(&path2)..) .unwrap() .into(); let scheme = path1.to_url().scheme().to_string(); let auth = path1.to_url().authority().map(|x| x.to_string()); let path = path1.to_url().path().to_string(); Path::from_scheme_auth_path(scheme.as_str(), auth.as_deref(), path.as_str()) } pub fn is_url_path_absolute(&self) -> bool { let start = Self::start_position_without_windows_drive(&self.url.path().to_string()); self.url .path() .to_string() .get(start..) .unwrap() .starts_with(SEPARATOR) } pub fn is_absolute(&self) -> bool { self.is_url_path_absolute() } fn start_position_without_windows_drive(path: &str) -> usize { if Self::has_windows_drive(path) { if path.chars().next().unwrap() == SEPARATOR { 3 } else { 2 } } else { 0 } } fn has_windows_drive(path: &str) -> bool { *WINDOWS && HAS_DRIVE_LETTER_SPECIFIER.find(path).is_some() } pub fn get_name(&self) -> Option<String> { let path = self.url.path(); let slash = path.to_string().rfind(SEPARATOR).map_or(0, |i| i + 1); path.to_string().get(slash..).map(|x| x.to_owned()) } pub fn get_parent(&self) -> Option<Path> { let path = self.url.path(); let last_slash = path.to_string().rfind(SEPARATOR); let start = Self::start_position_without_windows_drive(&path.to_string()); if (path.to_string().len() == start) || (last_slash? == start && path.to_string().len() == start + 1) { return None; } let parent_path = if last_slash.is_none() { CUR_DIR.to_string() } else { path.to_string() .get( 0..if last_slash? == start { start + 1 } else { last_slash? }, ) .map(|x| x.to_string())? }; let mut parent = self.url.clone(); parent.set_path(parent_path.as_str()).unwrap(); Some(Path::from_url(parent.into_owned())) } pub fn is_root(&self) -> bool { self.get_parent().is_none() } fn normalize_path(scheme: String, mut path: String) -> String { path = path.replace("//", "/"); if *WINDOWS && (Self::has_windows_drive(&path) || scheme.eq("file")) { path = path.replace("\\", "/"); } let min_len = Self::start_position_without_windows_drive(&path) + 1; if (path.len() > min_len) && path.ends_with(SEPARATOR) { path = path.get(0..path.len() - 1).unwrap().to_string(); } path } } #[cfg(test)] mod tests { use super::*; #[test] fn get_name() { assert_eq!("", Path::from_path_string("/").get_name().unwrap()); assert_eq!("foo", Path::from_path_string("foo").get_name().unwrap()); assert_eq!("foo", Path::from_path_string("/foo").get_name().unwrap()); assert_eq!("foo", Path::from_path_string("/foo/").get_name().unwrap()); assert_eq!( "bar", Path::from_path_string("/foo/bar").get_name().unwrap() ); assert_eq!( "bar", Path::from_path_string("hdfs://host/foo/bar") .get_name() .unwrap() ); } #[test] fn is_absolute() { assert!(Path::from_path_string("/").is_absolute()); assert!(Path::from_path_string("/foo").is_absolute()); assert!(!Path::from_path_string("foo").is_absolute()); assert!(!Path::from_path_string("foo/bar").is_absolute()); assert!(!Path::from_path_string(".").is_absolute()); assert!(Path::from_path_string("scheme:///foo/bar").is_absolute()); if *WINDOWS { assert!(Path::from_path_string("C:/a/b").is_absolute()); assert!(Path::from_path_string("C:a/b").is_absolute()); } } #[test] fn parent() { assert_eq!( Path::from_path_string("/foo"), Path::from_path_string("file:///foo/bar") .get_parent() .unwrap() ); assert_eq!( Path::from_path_string("foo"), Path::from_path_string("foo/bar").get_parent().unwrap() ); assert_eq!( Path::from_path_string("/"), Path::from_path_string("/foo").get_parent().unwrap() ); assert!(Path::from_path_string("/").get_parent().is_none()); if *WINDOWS { assert_eq!( Path::from_path_string("c:/"), Path::from_path_string("c:/foo").get_parent().unwrap() ); } } } <file_sep>use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use dashmap::DashMap; use serde_derive::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub enum CachePutResponse { CachePutSuccess(usize), CachePutFailure, } // Despite the name, it is currently unbounded cache. Once done with LRU iterator, have to make this bounded. // Since we are storing everything as serialized objects, size estimation is as simple as getting the length of byte vector #[derive(Debug, Clone)] pub struct BoundedMemoryCache { max_bytes: usize, next_key_space_id: Arc<AtomicUsize>, current_bytes: usize, map: Arc<DashMap<((usize, usize), usize), (Vec<u8>, usize)>>, } //TODO remove all hardcoded values impl BoundedMemoryCache { pub fn new() -> Self { BoundedMemoryCache { max_bytes: 2000, // in MB next_key_space_id: Arc::new(AtomicUsize::new(0)), current_bytes: 0, map: Arc::new(DashMap::new()), } } fn new_key_space_id(&self) -> usize { self.next_key_space_id.fetch_add(1, Ordering::SeqCst) } pub fn new_key_space(&self) -> KeySpace { KeySpace::new(self, self.new_key_space_id()) } fn get(&self, dataset_id: (usize, usize), partition: usize) -> Option<Vec<u8>> { self.map .get(&(dataset_id, partition)) .map(|entry| entry.0.clone()) } fn put( &self, dataset_id: (usize, usize), partition: usize, value: Vec<u8>, ) -> CachePutResponse { let key = (dataset_id, partition); //TODO logging let size = value.len() * 8 + 2 * 8; //this number of MB if size as f64 / (1000.0 * 1000.0) > self.max_bytes as f64 { CachePutResponse::CachePutFailure } else { //TODO ensure free space needs to be done and this needs to be modified self.map.insert(key, (value, size)); CachePutResponse::CachePutSuccess(size) } } fn ensure_free_space(&self, _dataset_id: u64, _space: u64) -> bool { //TODO logging unimplemented!() } fn report_entry_dropped(_data_set_id: usize, _partition: usize, _entry: (Vec<u8>, usize)) { //TODO loggging unimplemented!() } } #[derive(Debug, Clone)] pub struct KeySpace<'a> { pub cache: &'a BoundedMemoryCache, pub key_space_id: usize, } impl<'a> KeySpace<'a> { fn new(cache: &'a BoundedMemoryCache, key_space_id: usize) -> Self { KeySpace { cache, key_space_id, } } pub fn get(&self, dataset_id: usize, partition: usize) -> Option<Vec<u8>> { self.cache.get((self.key_space_id, dataset_id), partition) } pub fn put(&self, dataset_id: usize, partition: usize, value: Vec<u8>) -> CachePutResponse { self.cache .put((self.key_space_id, dataset_id), partition, value) } pub fn get_capacity(&self) -> usize { self.cache.max_bytes } } <file_sep>[book] authors = ["raja"] language = "en" multilingual = false src = "src" <file_sep>use std::collections::HashSet; use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream}; use std::sync::Arc; use std::thread; use std::time; use crate::serialized_data_capnp::serialized_data; use capnp::{message::ReaderOptions, serialize_packed}; use dashmap::DashMap; use parking_lot::{Mutex, RwLock}; const CAPNP_BUF_READ_OPTS: ReaderOptions = ReaderOptions { traversal_limit_in_words: std::u64::MAX, nesting_limit: 64, }; pub enum MapOutputTrackerMessage { //contains shuffle_id GetMapOutputLocations(i64), StopMapOutputTracker, } // Starts the server in master node and client in slave nodes. Similar to cache tracker. #[derive(Clone, Debug)] pub(crate) struct MapOutputTracker { is_master: bool, pub server_uris: Arc<DashMap<usize, Vec<Option<String>>>>, fetching: Arc<RwLock<HashSet<usize>>>, generation: Arc<Mutex<i64>>, master_addr: SocketAddr, } // Only master_addr doesn't have a default. impl Default for MapOutputTracker { fn default() -> Self { MapOutputTracker { is_master: Default::default(), server_uris: Default::default(), fetching: Default::default(), generation: Default::default(), master_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0), } } } impl MapOutputTracker { pub fn new(is_master: bool, master_addr: SocketAddr) -> Self { let m = MapOutputTracker { is_master, server_uris: Arc::new(DashMap::new()), fetching: Arc::new(RwLock::new(HashSet::new())), generation: Arc::new(Mutex::new(0)), master_addr, }; m.server(); m } fn client(&self, shuffle_id: usize) -> Vec<String> { let mut stream = loop { match TcpStream::connect(self.master_addr) { Ok(stream) => break stream, Err(_) => continue, } }; let shuffle_id_bytes = bincode::serialize(&shuffle_id).unwrap(); let mut message = capnp::message::Builder::new_default(); let mut shuffle_data = message.init_root::<serialized_data::Builder>(); shuffle_data.set_msg(&shuffle_id_bytes); serialize_packed::write_message(&mut stream, &message).unwrap(); let mut stream_r = std::io::BufReader::new(&mut stream); let message_reader = serialize_packed::read_message(&mut stream_r, CAPNP_BUF_READ_OPTS).unwrap(); let shuffle_data = message_reader .get_root::<serialized_data::Reader>() .unwrap(); let locs: Vec<String> = bincode::deserialize(&shuffle_data.get_msg().unwrap()).unwrap(); locs } fn server(&self) { if self.is_master { log::debug!("mapoutput tracker server starting"); let master_addr = self.master_addr; let server_uris = self.server_uris.clone(); thread::spawn(move || { // TODO: make this use async rt let listener = TcpListener::bind(master_addr).unwrap(); log::debug!("mapoutput tracker server started"); for stream in listener.incoming() { match stream { Err(_) => continue, Ok(mut stream) => { let server_uris_clone = server_uris.clone(); thread::spawn(move || { //reading let r = capnp::message::ReaderOptions { traversal_limit_in_words: std::u64::MAX, nesting_limit: 64, }; let mut stream_r = std::io::BufReader::new(&mut stream); let message_reader = match serialize_packed::read_message(&mut stream_r, r) { Ok(s) => s, Err(_) => return, }; let data = message_reader .get_root::<serialized_data::Reader>() .unwrap(); let shuffle_id: usize = bincode::deserialize(data.get_msg().unwrap()).unwrap(); while server_uris_clone .get(&shuffle_id) .unwrap() .iter() .filter(|x| !x.is_none()) .count() == 0 { //check whether this will hurt the performance or not let wait = time::Duration::from_millis(1); thread::sleep(wait); } let locs = server_uris_clone .get(&shuffle_id) .map(|kv| kv.value().clone()) .unwrap_or_default(); log::debug!("locs inside mapoutput tracker server before unwrapping for shuffle id {:?} {:?}",shuffle_id,locs); let locs = locs.into_iter().map(|x| x.unwrap()).collect::<Vec<_>>(); log::debug!("locs inside mapoutput tracker server after unwrapping for shuffle id {:?} {:?} ", shuffle_id, locs); //writing let result = bincode::serialize(&locs).unwrap(); let mut message = capnp::message::Builder::new_default(); let mut locs_data = message.init_root::<serialized_data::Builder>(); locs_data.set_msg(&result); serialize_packed::write_message(&mut stream, &message).unwrap(); }); } } } }); } } pub fn register_shuffle(&self, shuffle_id: usize, num_maps: usize) { log::debug!("inside register shuffle"); if self.server_uris.get(&shuffle_id).is_some() { //TODO error handling log::debug!("map tracker register shuffle none"); return; } self.server_uris.insert(shuffle_id, vec![None; num_maps]); log::debug!("server_uris after register_shuffle {:?}", self.server_uris); } pub fn register_map_output(&self, shuffle_id: usize, map_id: usize, server_uri: String) { log::debug!( "registering map output from shuffle task #{} with map id #{} at server: {}", shuffle_id, map_id, server_uri ); self.server_uris.get_mut(&shuffle_id).unwrap()[map_id] = Some(server_uri); } pub fn register_map_outputs(&self, shuffle_id: usize, locs: Vec<Option<String>>) { log::debug!( "registering map outputs inside map output tracker for shuffle id #{}: {:?}", shuffle_id, locs ); self.server_uris.insert(shuffle_id, locs); } pub fn unregister_map_output(&self, shuffle_id: usize, map_id: usize, server_uri: String) { let array = self.server_uris.get(&shuffle_id); if let Some(arr) = array { if arr.get(map_id).unwrap() == &Some(server_uri) { self.server_uris .get_mut(&shuffle_id) .unwrap() .insert(map_id, None) } self.increment_generation(); } else { //TODO error logging } } pub fn get_server_uris(&self, shuffle_id: usize) -> Vec<String> { log::debug!( "trying to get uri for shuffle task #{}, current server uris: {:?}", shuffle_id, self.server_uris ); if self .server_uris .get(&shuffle_id) .map(|some| some.iter().filter_map(|x| x.clone()).next()) .flatten() .is_none() { if self.fetching.read().contains(&shuffle_id) { while self.fetching.read().contains(&shuffle_id) { //check whether this will hurt the performance or not let wait = time::Duration::from_millis(1); thread::sleep(wait); } let servers = self .server_uris .get(&shuffle_id) .unwrap() .iter() .filter(|x| !x.is_none()) .map(|x| x.clone().unwrap()) .collect::<Vec<_>>(); log::debug!("returning after fetching done, return: {:?}", servers); return servers; } else { log::debug!("adding to fetching queue"); self.fetching.write().insert(shuffle_id); } let fetched = self.client(shuffle_id); log::debug!("fetched locs from client: {:?}", fetched); self.server_uris.insert( shuffle_id, fetched.iter().map(|x| Some(x.clone())).collect(), ); log::debug!("added locs to server uris after fetching"); self.fetching.write().remove(&shuffle_id); fetched } else { self.server_uris .get(&shuffle_id) .unwrap() .iter() .filter(|x| !x.is_none()) .map(|x| x.clone().unwrap()) .collect() } } pub fn increment_generation(&self) { *self.generation.lock() += 1; } pub fn get_generation(&self) -> i64 { *self.generation.lock() } pub fn update_generation(&mut self, new_gen: i64) { if new_gen > *self.generation.lock() { self.server_uris = Arc::new(DashMap::new()); *self.generation.lock() = new_gen; } } } <file_sep>#!/bin/bash SCRIPT_PATH=`dirname $(readlink -f $0)` VERSION=$1 if [ -z $VERSION ] then VERSION='latest' fi PACKAGE="native_spark:${VERSION}" cd $SCRIPT_PATH && cd .. echo "work dir: $(pwd)" RUST_VERSION="$(cat ./rust-toolchain | tr -d '[:space:]')" echo "rust version: $RUST_VERSION" echo "building $PACKAGE..." docker build --build-arg RUST_VERSION=$RUST_VERSION -t $PACKAGE -f docker/Dockerfile --force-rm . <file_sep># native_spark [![Join the chat at https://gitter.im/fast_spark/community](https://badges.gitter.im/fast_spark/community.svg)](https://gitter.im/fast_spark/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://travis-ci.org/rajasekarv/native_spark.svg?branch=master)](https://travis-ci.org/rajasekarv/native_spark) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) **[Documentation](https://rajasekarv.github.io/native_spark/)** A new, arguably faster, implementation of Apache Spark from scratch in Rust. WIP Framework tested only on Linux, requires nightly Rust. Read how to get started in the [documentation](https://rajasekarv.github.io/native_spark/chapter_1.html). ## Contributing If you are interested in contributing please jump on Gitter and check out and head to the issue tracker where you can find open issues (anything labelled `good first issue` and `help wanted` is up for grabs). <file_sep>//! Test whether the library can be used with different running async executors. use native_spark::*; #[macro_use] extern crate serde_closure; use once_cell::sync::Lazy; use std::sync::Arc; static CONTEXT: Lazy<Arc<Context>> = Lazy::new(|| Context::new().unwrap()); #[tokio::test] async fn existing_tokio_rt() -> Result<()> { let initially = async { "initially" }.await; assert_eq!(initially, "initially"); let sc = CONTEXT.clone(); let col = sc.make_rdd((0..10).collect::<Vec<_>>(), 32); let vec_iter = col.map(Fn!(|i| (0..i).collect::<Vec<_>>())); let res = vec_iter.collect()?; let expected = (0..10) .map(|i| (0..i).collect::<Vec<_>>()) .collect::<Vec<_>>(); assert_eq!(expected, res); let finally = async { "finally" }.await; assert_eq!(finally, "finally"); Ok(()) } #[async_std::test] async fn existing_async_std_rt() -> Result<()> { let initially = async { "initially" }.await; assert_eq!(initially, "initially"); let sc = CONTEXT.clone(); let col = sc.make_rdd((0..10).collect::<Vec<_>>(), 32); let vec_iter = col.map(Fn!(|i| (0..i).collect::<Vec<_>>())); let res = vec_iter.collect()?; let expected = (0..10) .map(|i| (0..i).collect::<Vec<_>>()) .collect::<Vec<_>>(); assert_eq!(expected, res); let finally = async { "finally" }.await; assert_eq!(finally, "finally"); Ok(()) } <file_sep>#!/bin/bash SCRIPT_PATH=`dirname $(readlink -f $0)` cd $SCRIPT_PATH # Deploy a testing cluster with one master and 2 workers docker-compose up --scale ns_worker=2 -d # Since we can't resolved domains yet, we have to get each container IP to create the config file WORKER_IPS=$(docker-compose ps | grep -oE "docker_ns_worker_[0-9]+" \ | xargs -I{} docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' {}) read -a WORKER_IPS <<< $(echo $WORKER_IPS) slaves=$(printf ",\"ns_user@%s\"" "${WORKER_IPS[@]}") slaves="slaves = [${slaves:1}]" MASTER_IP=$(docker-compose ps | grep -oE "docker_ns_master_[0-9]+" \ | xargs -I{} docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' {}) CONF_FILE=`cat <<EOF master = "$MASTER_IP:3000" ${slaves} EOF ` count=0 for WORKER in $(docker-compose ps | grep -oE "docker_ns_worker_[0-9]+") do echo "Setting $WORKER"; docker exec -e CONF_FILE="$CONF_FILE" -e NS_LOCAL_IP="${WORKER_IPS[count]}" -w /home/ns_user/ $WORKER \ bash -c 'echo "$CONF_FILE" >> hosts.conf && \ echo "NS_LOCAL_IP=$NS_LOCAL_IP" >> .ssh/environment && \ echo "PermitUserEnvironment yes" >> /etc/ssh/sshd_config && \ echo "AcceptEnv RUST_BACKTRACE" >> /etc/ssh/sshd_config && \ service ssh start'; (( count++ )); done docker exec -e CONF_FILE="$CONF_FILE" -e NS_LOCAL_IP="${MASTER_IP}" -w /root/ docker_ns_master_1 \ bash -c 'echo "$CONF_FILE" >> hosts.conf && \ echo "export NS_LOCAL_IP=$NS_LOCAL_IP" >> .bashrc && echo "SendEnv RUST_BACKTRACE" >> ~/.ssh/config '; for WORKER_IP in ${WORKER_IPS[@]} do docker exec docker_ns_master_1 bash -c "ssh-keyscan ${WORKER_IP} >> ~/.ssh/known_hosts" done # When done is posible to open a shell into the master and run any of the examples in distributed mode <file_sep>use std::hash::Hash; use std::marker::PhantomData; use std::sync::Arc; use crate::aggregator::Aggregator; use crate::context::Context; use crate::dependency::{Dependency, OneToOneDependency}; use crate::error::Result; use crate::partitioner::{HashPartitioner, Partitioner}; use crate::rdd::co_grouped_rdd::CoGroupedRdd; use crate::rdd::shuffled_rdd::ShuffledRdd; use crate::rdd::{Rdd, RddBase, RddVals}; use crate::serializable_traits::{AnyData, Data, Func, SerFunc}; use crate::split::Split; use serde_derive::{Deserialize, Serialize}; use serde_traitobject::{Arc as SerArc, Deserialize, Serialize}; // Trait containing pair rdd methods. No need of implicit conversion like in Spark version pub trait PairRdd<K: Data + Eq + Hash, V: Data>: Rdd<Item = (K, V)> + Send + Sync { fn combine_by_key<C: Data>( &self, aggregator: Aggregator<K, V, C>, partitioner: Box<dyn Partitioner>, ) -> SerArc<dyn Rdd<Item = (K, C)>> where Self: Sized + Serialize + Deserialize + 'static, { SerArc::new(ShuffledRdd::new( self.get_rdd(), Arc::new(aggregator), partitioner, )) } fn group_by_key(&self, num_splits: usize) -> SerArc<dyn Rdd<Item = (K, Vec<V>)>> where Self: Sized + Serialize + Deserialize + 'static, { self.group_by_key_using_partitioner( Box::new(HashPartitioner::<K>::new(num_splits)) as Box<dyn Partitioner> ) } fn group_by_key_using_partitioner( &self, partitioner: Box<dyn Partitioner>, ) -> SerArc<dyn Rdd<Item = (K, Vec<V>)>> where Self: Sized + Serialize + Deserialize + 'static, { self.combine_by_key(Aggregator::<K, V, _>::default(), partitioner) } fn reduce_by_key<F>(&self, func: F, num_splits: usize) -> SerArc<dyn Rdd<Item = (K, V)>> where F: SerFunc((V, V)) -> V, Self: Sized + Serialize + Deserialize + 'static, { self.reduce_by_key_using_partitioner( func, Box::new(HashPartitioner::<K>::new(num_splits)) as Box<dyn Partitioner>, ) } fn reduce_by_key_using_partitioner<F>( &self, func: F, partitioner: Box<dyn Partitioner>, ) -> SerArc<dyn Rdd<Item = (K, V)>> where F: SerFunc((V, V)) -> V, Self: Sized + Serialize + Deserialize + 'static, { let create_combiner = Box::new(Fn!(|v: V| v)); let f_clone = func.clone(); let merge_value = Box::new(Fn!(move |(buf, v)| { (f_clone)((buf, v)) })); let merge_combiners = Box::new(Fn!(move |(b1, b2)| { (func)((b1, b2)) })); let aggregator = Aggregator::new(create_combiner, merge_value, merge_combiners); self.combine_by_key(aggregator, partitioner) } fn map_values<U: Data, F: SerFunc(V) -> U + Clone>( &self, f: F, ) -> SerArc<dyn Rdd<Item = (K, U)>> where F: SerFunc(V) -> U + Clone, Self: Sized, { SerArc::new(MappedValuesRdd::new(self.get_rdd(), f)) } fn flat_map_values<U: Data, F: SerFunc(V) -> Box<dyn Iterator<Item = U>> + Clone>( &self, f: F, ) -> SerArc<dyn Rdd<Item = (K, U)>> where F: SerFunc(V) -> Box<dyn Iterator<Item = U>> + Clone, Self: Sized, { SerArc::new(FlatMappedValuesRdd::new(self.get_rdd(), f)) } fn join<W: Data>( &self, other: serde_traitobject::Arc<dyn Rdd<Item = (K, W)>>, num_splits: usize, ) -> SerArc<dyn Rdd<Item = (K, (V, W))>> { let f = Fn!(|v: (Vec<V>, Vec<W>)| { let (vs, ws) = v; let combine = vs .into_iter() .flat_map(move |v| ws.clone().into_iter().map(move |w| (v.clone(), w))); Box::new(combine) as Box<dyn Iterator<Item = (V, W)>> }); self.cogroup( other, Box::new(HashPartitioner::<K>::new(num_splits)) as Box<dyn Partitioner>, ) .flat_map_values(Box::new(f)) } fn cogroup<W: Data>( &self, other: serde_traitobject::Arc<dyn Rdd<Item = (K, W)>>, partitioner: Box<dyn Partitioner>, ) -> SerArc<dyn Rdd<Item = (K, (Vec<V>, Vec<W>))>> { let rdds: Vec<serde_traitobject::Arc<dyn RddBase>> = vec![ serde_traitobject::Arc::from(self.get_rdd_base()), serde_traitobject::Arc::from(other.get_rdd_base()), ]; let cg_rdd = CoGroupedRdd::<K>::new(rdds, partitioner); let f = Fn!(|v: Vec<Vec<Box<dyn AnyData>>>| -> (Vec<V>, Vec<W>) { let mut count = 0; let mut vs: Vec<V> = Vec::new(); let mut ws: Vec<W> = Vec::new(); for v in v.into_iter() { if count >= 2 { break; } if count == 0 { for i in v { vs.push(*(i.into_any().downcast::<V>().unwrap())) } } else if count == 1 { for i in v { ws.push(*(i.into_any().downcast::<W>().unwrap())) } } count += 1; } (vs, ws) }); cg_rdd.map_values(Box::new(f)) } fn partition_by_key(&self, partitioner: Box<dyn Partitioner>) -> SerArc<dyn Rdd<Item = V>> { // Guarantee the number of partitions by introducing a shuffle phase let shuffle_steep = ShuffledRdd::new( self.get_rdd(), Arc::new(Aggregator::<K, V, _>::default()), partitioner, ); // Flatten the results of the combined partitions let flattener = Fn!(|grouped: (K, Vec<V>)| { let (key, values) = grouped; let iter: Box<dyn Iterator<Item = _>> = Box::new(values.into_iter()); iter }); shuffle_steep.flat_map(flattener) } } // Implementing the PairRdd trait for all types which implements Rdd impl<K: Data + Eq + Hash, V: Data, T> PairRdd<K, V> for T where T: Rdd<Item = (K, V)> {} impl<K: Data + Eq + Hash, V: Data, T> PairRdd<K, V> for SerArc<T> where T: Rdd<Item = (K, V)> {} #[derive(Serialize, Deserialize)] pub struct MappedValuesRdd<K: Data, V: Data, U: Data, F> where F: Func(V) -> U + Clone, { #[serde(with = "serde_traitobject")] prev: Arc<dyn Rdd<Item = (K, V)>>, vals: Arc<RddVals>, f: F, _marker_t: PhantomData<K>, // phantom data is necessary because of type parameter T _marker_v: PhantomData<V>, _marker_u: PhantomData<U>, } impl<K: Data, V: Data, U: Data, F> Clone for MappedValuesRdd<K, V, U, F> where F: Func(V) -> U + Clone, { fn clone(&self) -> Self { MappedValuesRdd { prev: self.prev.clone(), vals: self.vals.clone(), f: self.f.clone(), _marker_t: PhantomData, _marker_v: PhantomData, _marker_u: PhantomData, } } } impl<K: Data, V: Data, U: Data, F> MappedValuesRdd<K, V, U, F> where F: Func(V) -> U + Clone, { fn new(prev: Arc<dyn Rdd<Item = (K, V)>>, f: F) -> Self { let mut vals = RddVals::new(prev.get_context()); vals.dependencies .push(Dependency::NarrowDependency(Arc::new( OneToOneDependency::new(prev.get_rdd_base()), ))); let vals = Arc::new(vals); MappedValuesRdd { prev, vals, f, _marker_t: PhantomData, _marker_v: PhantomData, _marker_u: PhantomData, } } } impl<K: Data, V: Data, U: Data, F> RddBase for MappedValuesRdd<K, V, U, F> where F: SerFunc(V) -> U, { fn get_rdd_id(&self) -> usize { self.vals.id } fn get_context(&self) -> Arc<Context> { self.vals.context.upgrade().unwrap() } fn get_dependencies(&self) -> Vec<Dependency> { self.vals.dependencies.clone() } fn splits(&self) -> Vec<Box<dyn Split>> { self.prev.splits() } fn number_of_splits(&self) -> usize { self.prev.number_of_splits() } // TODO Analyze the possible error in invariance here fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { log::debug!("inside iterator_any mapvaluesrdd"); Ok(Box::new( self.iterator(split)? .map(|(k, v)| Box::new((k, v)) as Box<dyn AnyData>), )) } fn cogroup_iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { log::debug!("inside cogroup_iterator_any mapvaluesrdd"); Ok(Box::new(self.iterator(split)?.map(|(k, v)| { Box::new((k, Box::new(v) as Box<dyn AnyData>)) as Box<dyn AnyData> }))) } } impl<K: Data, V: Data, U: Data, F> Rdd for MappedValuesRdd<K, V, U, F> where F: SerFunc(V) -> U, { type Item = (K, U); fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(self.clone()) as Arc<dyn RddBase> } fn get_rdd(&self) -> Arc<dyn Rdd<Item = Self::Item>> { Arc::new(self.clone()) } fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { let f = self.f.clone(); Ok(Box::new( self.prev.iterator(split)?.map(move |(k, v)| (k, f(v))), )) } } #[derive(Serialize, Deserialize)] pub struct FlatMappedValuesRdd<K: Data, V: Data, U: Data, F> where F: Func(V) -> Box<dyn Iterator<Item = U>> + Clone, { #[serde(with = "serde_traitobject")] prev: Arc<dyn Rdd<Item = (K, V)>>, vals: Arc<RddVals>, f: F, _marker_t: PhantomData<K>, // phantom data is necessary because of type parameter T _marker_v: PhantomData<V>, _marker_u: PhantomData<U>, } impl<K: Data, V: Data, U: Data, F> Clone for FlatMappedValuesRdd<K, V, U, F> where F: Func(V) -> Box<dyn Iterator<Item = U>> + Clone, { fn clone(&self) -> Self { FlatMappedValuesRdd { prev: self.prev.clone(), vals: self.vals.clone(), f: self.f.clone(), _marker_t: PhantomData, _marker_v: PhantomData, _marker_u: PhantomData, } } } impl<K: Data, V: Data, U: Data, F> FlatMappedValuesRdd<K, V, U, F> where F: Func(V) -> Box<dyn Iterator<Item = U>> + Clone, { fn new(prev: Arc<dyn Rdd<Item = (K, V)>>, f: F) -> Self { let mut vals = RddVals::new(prev.get_context()); vals.dependencies .push(Dependency::NarrowDependency(Arc::new( OneToOneDependency::new(prev.get_rdd_base()), ))); let vals = Arc::new(vals); FlatMappedValuesRdd { prev, vals, f, _marker_t: PhantomData, _marker_v: PhantomData, _marker_u: PhantomData, } } } impl<K: Data, V: Data, U: Data, F> RddBase for FlatMappedValuesRdd<K, V, U, F> where F: SerFunc(V) -> Box<dyn Iterator<Item = U>>, { fn get_rdd_id(&self) -> usize { self.vals.id } fn get_context(&self) -> Arc<Context> { self.vals.context.upgrade().unwrap() } fn get_dependencies(&self) -> Vec<Dependency> { self.vals.dependencies.clone() } fn splits(&self) -> Vec<Box<dyn Split>> { self.prev.splits() } fn number_of_splits(&self) -> usize { self.prev.number_of_splits() } // TODO Analyze the possible error in invariance here fn iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { log::debug!("inside iterator_any flatmapvaluesrdd",); Ok(Box::new( self.iterator(split)? .map(|(k, v)| Box::new((k, v)) as Box<dyn AnyData>), )) } fn cogroup_iterator_any( &self, split: Box<dyn Split>, ) -> Result<Box<dyn Iterator<Item = Box<dyn AnyData>>>> { log::debug!("inside iterator_any flatmapvaluesrdd",); Ok(Box::new(self.iterator(split)?.map(|(k, v)| { Box::new((k, Box::new(v) as Box<dyn AnyData>)) as Box<dyn AnyData> }))) } } impl<K: Data, V: Data, U: Data, F> Rdd for FlatMappedValuesRdd<K, V, U, F> where F: SerFunc(V) -> Box<dyn Iterator<Item = U>>, { type Item = (K, U); fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(self.clone()) as Arc<dyn RddBase> } fn get_rdd(&self) -> Arc<dyn Rdd<Item = Self::Item>> { Arc::new(self.clone()) } fn compute(&self, split: Box<dyn Split>) -> Result<Box<dyn Iterator<Item = Self::Item>>> { let f = self.f.clone(); Ok(Box::new( self.prev .iterator(split)? .flat_map(move |(k, v)| f(v).map(move |x| (k.clone(), x))), )) } }
71d0896391bfb55f4d68e7fc89dd9de82adbd0c2
[ "YAML", "Markdown", "TOML", "Rust", "Dockerfile", "Shell" ]
62
Rust
lumost/native_spark
05a99029c7381b54f27dfe9fb4bd697a51f2a2ea
4d253d58139dba12f8fee0ac9a7411b883574065
refs/heads/master
<file_sep>export const environment = { production: false, firebase: { apiKey: '<KEY>', authDomain: 'morsetrash.firebaseapp.com', databaseURL: 'https://morsetrash.firebaseio.com', projectId: 'morsetrash', storageBucket: 'morsetrash.appspot.com', messagingSenderId: '307678454355' } };
f72a2c896453ca91148ddc6ceb6e7e59a791a4e5
[ "TypeScript" ]
1
TypeScript
dankphetamine/awa-a1-2019
0c0292cad068e81352238bf26f68c941686be956
f9d1c2260f99ea894ff8a2e9886468822a0ab5db
refs/heads/master
<repo_name>pchico83/overlay<file_sep>/Dockerfile FROM ubuntu COPY start.sh / ENTRYPOINT ["/start.sh"]<file_sep>/start.sh 34f34 case efe f34f34 ewfew erver ewfew adsfds<file_sep>/hooks/build #!/bin/bash docker version docker build -t $IMAGE_NAME . if [ "$?" -eq "1" ]; then echo "FAILED!"; sleep 1100; exit 1; fi
c99607eb4110a3c9568240076d5f5a11626bcb02
[ "Dockerfile", "Shell" ]
3
Dockerfile
pchico83/overlay
24d0095b9adcf8ac8193f205b4aac693c20fe745
0d05c43d96adbe209ebafba00551624b67492d1c
refs/heads/master
<repo_name>Be-libra/Team-Roster<file_sep>/src/reducers/teamSearchField.js const initialstate={ searchValue:'' } export const setTeamsSearchField = (state=initialstate, action={}) => { switch (action.type) { case 'TEAMS_SEARCH_CHANGE': return Object.assign({}, state, {searchValue:action.payload}) default: return state } } <file_sep>/src/pages/players/AddPlayer.js import React from 'react'; import {connect} from 'react-redux' import TextField from '@material-ui/core/TextField' import MenuItem from '@material-ui/core/MenuItem'; import FormControl from '@material-ui/core/FormControl'; import Select from '@material-ui/core/Select'; import Button from '@material-ui/core/Button' import './styles/addPlayer.scss' const mapStateToProps=(state)=>{ return{ allTeams:state.setTeams.teams } } const AddPlayer = (props) => { const [name,setName] =React.useState('') const [teamId,setTeamID] =React.useState('') const handleSubmit=()=>{ fetch(`http://54.201.87.31/api/vaco-api/team/${teamId}/player`,{ method:'POST', headers:{ "content-type":'application/json' }, body:JSON.stringify({ name }) }) .then(res=>res.json()) .then(data=>{ if(data._id){ location.reload() } else{ window.alert('try again by refreshing') } }) } return ( <div className='add-player-modal' > <div className='container'> <TextField variant='outlined' size='small' placeholder='Name of the player' onChange={(e)=>setName(e.target.value)} /> <FormControl variant="outlined" > <Select labelId="teams" id="team" > <MenuItem value=""> <em>None</em> </MenuItem> {props.allTeams.map(team=> <MenuItem value={team._id} onClick={(e)=>setTeamID(team._id)}>{team.name}</MenuItem> )} </Select> </FormControl> <Button variant="contained" color="primary" disableElevation onClick={handleSubmit}> Add Player </Button> <Button variant="contained" disableElevation onClick={()=>props.onClick(false)}> Cancel </Button> </div> </div> ); } export default connect(mapStateToProps,null)(AddPlayer); <file_sep>/src/pages/home/TeamCard.js import React from 'react'; import {RiDeleteBin6Line} from 'react-icons/ri' import { SetPlayers } from '../../Action'; import './styles/teamCard.scss' const TeamCard = (props) => { const [players,setPlayers] = React.useState([]) React.useEffect(()=>{ fetch('http://54.201.87.31/api/vaco-api/allTeamPlayers',{ method:'POST', headers:{ "content-type":"application/json" }, body:JSON.stringify({teamId:props.data._id}) }) .then(res=>res.json()) .then(data=>setPlayers(data)) },[players]) const removeTeam =()=>{ fetch('http://54.201.87.31/api/vaco-api/removeTeam',{ method:'DELETE', headers:{ "content-type":"application/json" }, body:JSON.stringify({team:props.data.name}) }) .then(res=>res.json()) .then(data=>{ if(data.deletedCount===1){ location.reload() } else{ window.alert('something wrong') } } ) } return ( <div className='team-card'> <div className='card-head'> <h2>{props.data.name} </h2> <RiDeleteBin6Line style={{position:'relative',top:'3px',color:'#053ED1',fontSize:'1.3rem',marginRight:'10px'}} onClick={removeTeam} /> </div> <div className='Card-body'> { players.map((player,i)=><p key={i}>{player.name}</p>) } </div> </div> ); } export default TeamCard; <file_sep>/src/pages/players/Players.js import React,{useState,useEffect} from 'react' import {RiDeleteBin6Line} from 'react-icons/ri' import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import TextField from '@material-ui/core/TextField' import {GrAddCircle} from 'react-icons/gr' import {connect} from 'react-redux' import {PlayersSearchField, SetPlayers,setTeams} from '../../Action' import AddPlayer from './AddPlayer'; import './styles/players.scss' const mapStateToProps=(state)=>{ return { searchValue:state.setPlayersSearchField.searchValue, players:state.setPlayers.players, allTeams:state.setTeams.teams } } const mapDispatchToProps=(dispatch)=>{ return{ setSearchField:(value)=>dispatch(PlayersSearchField(value)), setAllPlayers:(value)=>dispatch(SetPlayers(value)), setAllTeams:(value)=>dispatch(setTeams(value)) } } const Players =(props)=>{ const [teams,setTeams] =useState({}) const [fileteredPlayers,setFilteredPlayers] = useState([]) const [modalState,setModalState]=useState(false) useEffect(()=>{ fetch('http://54.201.87.31/api/vaco-api/allplayers') .then(res=>res.json()) .then(playerdata=>{ fetch('http://192.168.3.11/api/vaco-api/allTeams') .then(res=>res.json()) .then(data=>{ props.setAllTeams(data) const teamObj={} data.map(team=>{ teamObj[team._id]=team.name }) setTeams(teamObj) props.setAllPlayers(playerdata) setFilteredPlayers(playerdata) }) }) },[]) const removePlayer =(id)=>{ fetch(`http://192.168.3.11/api/vaco-api/removePlayer`,{ method:'DELETE', headers:{ "content-type":"application/json" }, body:JSON.stringify({playerId:id}) }) .then(res=>res.json()) .then(data=>{ if(data.deletedCount===1){ location.reload() } else{ window.alert('something wrong') } }) } const handleSearchFieldChange=(e)=>{ const search=e.target.value const filter = props.players.filter(player=> player.name.toLowerCase().includes(search.toLowerCase())) setFilteredPlayers(filter) props.setSearchField(e.target.value) } return( <div className='contact-container'> <div className='head'> <h2>All pLayers({props.players.length})<span> <GrAddCircle onClick={(e)=>setModalState(!modalState)} style={{position:'relative',top:'3px',color:'#053ED1'}} /> </span></h2> <TextField variant='outlined' placeholder='Search' size="small" value={props.searchValue} onChange={handleSearchFieldChange} /> </div> <TableContainer className='table-container'> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell>Player</TableCell> <TableCell align="left">Team</TableCell> <TableCell align="left">PlayerId</TableCell> <TableCell></TableCell> </TableRow> </TableHead> <TableBody> {fileteredPlayers.map((player,i)=> <> <TableRow key={player._id} > <TableCell scope="row"> {player.name} </TableCell> <TableCell ><p>{teams[player.team]}</p></TableCell> <TableCell ><p>{player._id}</p></TableCell> <TableCell className='delete-icon'> <RiDeleteBin6Line onClick={()=>removePlayer(player._id)}/> </TableCell> </TableRow> </> )} </TableBody> </Table> </TableContainer> {modalState?<AddPlayer onClick={setModalState}/>:null } </div> ); } export default connect(mapStateToProps,mapDispatchToProps)(Players);<file_sep>/src/Action.js export const PlayersSearchField = (param)=>({type:'PLAYERS_SEARCH_CHANGE',payload:param}) export const TeamssSearchField = (param)=>({type:'TEAMS_SEARCH_CHANGE',payload:param}) export const SetPlayers = (param) => ({type:'SET_PLAYERS',payload:param}) export const setTeams = (param) =>({type:'SET_TEAMS',payload:param})<file_sep>/src/reducers/setPlayers.js const initialstate={ players:'' } export const setPlayers= (state=initialstate, action={}) => { switch (action.type) { case 'SET_PLAYERS': return Object.assign({}, state, {players:action.payload}) default: return state } }<file_sep>/src/pages/home/Team.js import React,{useState,useEffect} from 'react'; import TeamCard from './TeamCard'; import {GrAddCircle } from 'react-icons/gr' import './styles/team.scss' import { NavLink } from 'react-router-dom'; import { connect } from 'react-redux'; import { setTeams } from '../../Action'; import AddTeam from './AddTeam'; const mapStateToProps=(state)=>{ return { allTeams:state.setTeams.teams } } const mapDispatchToProps=(dispatch)=>{ return{ setAllTeams:(value)=>dispatch(setTeams(value)) } } const Team =(props) =>{ const [loading,setLoading] =useState(true) const [modalState,setModalState] = useState(false) useEffect(() => { fetch('http://localhost:3000/vaco-api/allTeams') .then(res=>res.json()) .then(data=>{ props.setAllTeams(data) setLoading(false) }) }, []); return( <div className='team'> <div className='team-comp'> <h2>All Teams({47}) <span> <GrAddCircle style={{position:'relative',top:'3px',color:'#053ED1'}} onClick={()=>setModalState(!modalState)} /> </span></h2> <NavLink to='/players'>View All players</NavLink> {loading?'loading': <div className='card-container'> {props.allTeams.map(team=> <TeamCard key={team._id} data={team}/> )} </div> } </div> { modalState?<AddTeam onClick={setModalState} />:null } </div> ); } export default connect(mapStateToProps,mapDispatchToProps)(Team);<file_sep>/src/reducers/PlayersSearch.js const initialstate={ searchValue:'' } export const setPlayersSearchField = (state=initialstate, action={}) => { switch (action.type) { case 'PLAYERS_SEARCH_CHANGE': return Object.assign({}, state, {searchValue:action.payload}) default: return state } }
c7a7b486cefecd70be47d666173e0f285d950bb0
[ "JavaScript" ]
8
JavaScript
Be-libra/Team-Roster
48e8c488e373937b39e1e4d99a8e1689b931f92a
e02118e4a1aae8a02e2c4ebc20a18bc31e46319f
refs/heads/master
<repo_name>allengonger/distrack<file_sep>/main.js // const contents = document.getElementById('contents'); // contents.parentNode.removeChild(contents); // import swal from 'sweetalert'; // when you open browser (goes to website), start the timer // const docIDArr = document.querySelectorAll('*[id]'); const divArr = [...document.getElementsByTagName('div')]; // console.log(divArr); // console.log("divArr type: ", Array.isArray(divArr)); // console.log(docIDArr[0]); function changeDom() { let start = divArr.length - 1; function inner() { // divArr[start].parentNode.removeChild(divArr[start]); const sp1 = document.createElement("h1"); sp1.id = "newDiv"; // sp1_content = document.createTextNode("Work on algos!!!"); // sp1.appendChild(sp1_content); sp1.innerText = "Work on Algos!!!" divArr[start].parentNode.replaceChild(sp1, divArr[start]) start -= 1; console.log("start: ", start) if (start === 1) { console.log("interval cleared!!!!") // alert("done!!!!!") // break; clearInterval(interval); } } // for (let i = start; i >= 0; i +=1) { // divArr[i].parentNode.removeChild(divArr[i]); return inner; } const removeEl = changeDom(); const interval = setInterval(removeEl, 50); // function changeDom() { // const contents = document.getElementById('img'); // console.log("contents parent: ", contents.parentNode) // contents.parentNode.removeChild(contents); // } // every interval, increment index by 1 // call the changeDom function with the index // function changeDom() { // // const contents = document.getElementById('img'); // for (let i = divArr.length - 1; i >= 0; i +=1) { // divArr[i].parentNode.removeChild(divArr[i]); // } // } // when timer reaches 30 seconds, pop up?? with selection?? // emoji's for selection (happy, depress, unmotivated etc..) // when clicked, pop up with random motivation quotes etc... // document.body.src = 'https://images.app.goo.gl/cvydRS6kLYBQsfES6';
8e49783bfd7d8d15e7ea400b21b13c469b5809b6
[ "JavaScript" ]
1
JavaScript
allengonger/distrack
57a8c55fc23ae2f10b1d998b19a078c202c71cdd
673c4afa0c579eadc26f941eb6d282be560d08e3
refs/heads/master
<file_sep>import { expect } from 'chai' import * as Actions from '../Actions/index' // testing incomplete - need to mock async actions const current = { time: 1453402675, summary: "Rain" } const alerts = [ {title:"flood",uri:"http://google.com"}, {title:"earthquake",uri:"http://yelp.com"} ] const forecast = { current: current, days: [{current},{current}], alerts: alerts } describe('actions - forecast - getCoordinates:', function() { it('should return the correct action object', function() { const actual = Actions.getCoordinates('Seattle') const expected = { type: Actions.GET_COORDINATES, payload: { first: false, isFetching: true, requested: 'Seattle' } } expect(actual).to.deep.equal(expected) }) }) describe('actions - forecast - parseCoordinates', function() { it('should return the correct action object', function() { const coordinates = { lat: 1234, lng: 5678, fa: 'Seattle' } const actual = Actions.parseCoordinates(coordinates) const expected = { type: Actions.PARSE_COORDINATES, payload: { lat: 1234, lng: 5678, fa: 'Seattle' } } expect(actual).to.deep.equal(expected) }) }) describe('actions - forecast - parseForecast', function() { it('should return the correct action object', function() { const actual = Actions.parseForecast(forecast) const expected = { type: Actions.PARSE_FORECAST, payload: { isFetching: false, current: current, days: [{current},{current}], alerts: alerts } } expect(actual).to.deep.equal(expected) }) }) describe('actions - forecast - fetchError', function() { it('should return the correct action object', function() { const error = { message: "error found" } const actual = Actions.fetchError(error) const expected = { type: Actions.FETCH_ERROR, payload: { isFetching: false, error: { message: "error found" } } } expect(actual).to.deep.equal(expected) }) }) <file_sep>import React, { Component } from 'react' import { Field, reduxForm } from 'redux-form' import { coordinatesRequest } from '../Actions/index' // Customize Field and Error Display const renderInput = (field) => { const isError = field.meta.touched && field.meta.error return ( <div> <div className="formError"> {(isError) ? field.meta.error : null} </div> <h1>{"What's the weather in"}&nbsp; <input {...field.input} type={field.type} placeholder={field.placeholder} className={(isError)?"inputError":null} />&nbsp;{"?"} </h1> </div> ) } // Form Validation const validate = (values) => { let errors = {} if (!values.location) { errors.location = 'Location is missing' } if (!(/^[a-z0-9, -]+$/i.test(values.location))) { errors.location = 'Location is invalid' } return errors } // Location Form class Location extends Component { constructor (props) { super(props) this.handleDispatch = this.handleDispatch.bind(this) } handleDispatch (formValues) { this.props.dispatch(coordinatesRequest(formValues)) this.context.router.push(`/fivedays/${formValues.location}`) document.activeElement.blur() } render () { const {handleSubmit} = this.props return ( <form className="formLocation" onSubmit={handleSubmit(this.handleDispatch)}> <Field name="location" label="Location" component={renderInput} type="text" placeholder="Reykjavik, Iceland" /> <button className="btn btn-info" type="submit">{"Let's Find Out"}</button> </form> ) } } Location.contextTypes = { router: React.PropTypes.object } export default reduxForm({ form: 'Location', validate })(Location) <file_sep>import React, { Component } from 'react' import { render } from 'react-dom' import { Link } from 'react-router' import { calendarDate, forecastConverter } from '../Utilities' import Icon from './Icons' import { Processing, Unknown } from './Processing' import AddressLink from './AddressLink' class Day extends Component { constructor (props) { super(props) this.dataDisplay = this.dataDisplay.bind(this) } dataDisplay (data) { let list = [], i = 0 list.push(<h2 key={i}>{calendarDate(data.time)}</h2>) i++ if (data.icon) { list.push(<div key={i}><Icon icon={data.icon} isDay={(this.props.params.dayID !== undefined)?true:false} /></div>) i++ } for (let item in data) { if (item === "summary") { list.push(<div key={i} className="summary">{forecastConverter[item].format(data[item])}</div>) } else if (item !== "icon" && item !== "time") { try { list.push(<div key={i}>{forecastConverter[item].name}: {forecastConverter[item].format(data[item])}</div>) } catch(e) { console.log(`${item} is unknown`) } } i++ } return list } render () { const { isFetching, days, formatted_address, params } = this.props const data = days[params.dayID] // fetching data if (isFetching) { return <Processing /> } // unknown location if (days.length === 0) { return <Unknown /> } return ( <div className="forecastBlock fadeIn dayBlock"> <Link to={`/fivedays/${params.requested}`}>Five Day Forecast</Link> <h1 className="address"><AddressLink formatted_address={formatted_address} /></h1> <div className="dayBlock">{this.dataDisplay(data)}</div> </div> ) } } export default Day<file_sep>import React from 'react' import { Route, IndexRoute } from 'react-router' import Home from './Forecast/index' import FiveDays from './Forecast/Components/FiveDays' import Day from './Forecast/Components/Day' import store from './store' import { coordinatesRequest } from './Forecast/Actions/index' const forecastDirect = (props) => { // `this` === Route store.dispatch(coordinatesRequest(props.params.requested)) } module.exports = ( <Route path="/" component={Home}> {/* Handled as Children inside of the Home Container */} <Route path="fivedays/:requested" component={FiveDays} onEnter={forecastDirect} /> <Route path="day/:requested/:dayID" component={Day} onEnter={forecastDirect} /> </Route> ) <file_sep>import React, { Component } from 'react' import { render } from 'react-dom' import { connect } from 'react-redux' import Header from '../Components/Header' import Footer from '../Components/Footer' class Home extends Component { constructor (props) { super(props) } render () { return ( <div className="container-fluid"> <Header dispatch={this.props.dispatch} /> {/*pass props to children components*/} {this.props.children && React.cloneElement(this.props.children, {...this.props.forecast}) } <Footer /> </div> ) } } const mapStateToProps = (state) => { return { ...state } } // connect redux state and dispatch() to react export default connect(mapStateToProps)(Home)<file_sep>import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { Router, browserHistory } from 'react-router' import Routes from './routes' import store from './store' // app styles transformed by webpack import './Forecast/Styles/Main.scss' import './Forecast/Styles/Location.scss' import './Forecast/Styles/FiveDays.scss' import './Forecast/Styles/Responsive.scss' import './Forecast/Styles/Icons.scss' import './Forecast/Styles/Day.scss' render( <Provider store={store}> <Router routes={Routes} history={browserHistory} /> </Provider>, document.getElementById('app') ) <file_sep>import React, { Component } from 'react' import { render } from 'react-dom' const AddressLink = (props) => { const mapParameters = props.formatted_address.replace(/\s/g,'+') const mapLink = `https://www.google.com/maps/place/${mapParameters}` return ( <a href={mapLink} target="_blank">{props.formatted_address}</a> ) } export default AddressLink<file_sep>import { expect } from 'chai' import * as forecast from '../Reducers/index' // imported so that test coverage is more accurate<file_sep> **Forecaster displays the weather conditions for the next five days and any alerts which appear. Location Coordinates are retrieved using Google Maps Geocode API. Weather data is pulled from the Dark Sky API.** ## [Live Forecaster](https://forecaster-darksky.herokuapp.com/) ## Build Instructions 1. Download or clone repo: `git clone https://github.com/slmoore/forecaster.git` 2. Sign up for [Dark Sky](https://developer.forecast.io/) and [Google Maps Geocode](https://developers.google.com/maps/documentation/geocoding/start) in order to get your personal API keys. 3. Change to forecaster directory and install dependencies: - `cd path/to/forecaster` - `npm install` 4. Create a `.env` file in the root directory and paste in the following environment variables. Replace the values with your own: - `PORT=8080` - `GEOCODE=1234` - `DARK_SKY=5678` - ***Unless port 8080 is already in use, it can be left as 8080.*** 5. You're done! So now you can run any of the following commands: - `npm run dev # run in development environment` (visit http://localhost:8080) - `npm test # run unit tests` - `npm run cover # run unit test coverage report` (html version generated inside /coverage/index.html) - `npm start # run from node server` (visit http://localhost:8080) - `npm run build:all # build server and client bundles` **This application accesses the environment variables using node, so it does not run statically.** ## Technology used with reasoning: - react - view framework to maintain display as state changes - redux - simplifies maintaining state as new features are added - react-router - maintaining routing within a single page application - sass - simplifies style over time - bootstrap - initial style - mocha/chai/istanbul - unit testing (only partial testing as of 10/16/16) - webpack/babel - bundles project with babel allowing for ES6/JSX features, hot reloading in development, uglify tasks, sass css preprocessor tasks, and server-side rendering - heroku - quick deployment and the reason that the bundle is included in the repo (saves heroku the time) ## User Story: Using the Dark Sky API - For the next five days display the: - conditions - status: complete - min and max temperature - status: complete Extra - additional features beyond task - location generated based on user input: complete - added Alerts feature: complete - started unit tests - started server-side rendering ## To be continued: - write tests for async actions, reducers, components - improve server-side rendering <file_sep>import { createStore, applyMiddleware, compose } from 'redux' import thunkMiddleware from 'redux-thunk' import createLogger from 'redux-logger' import rootReducer from './combinedReducers' // used only for server-side bundling if (typeof window === 'undefined') { global.window = {} } // get the state from the server first const preloadedState = window.__PRELOADED_STATE__ /* Store Config */ export const configureStore = function (preloadedState = {}) { if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test') { return createStore( rootReducer, preloadedState, compose( applyMiddleware(thunkMiddleware) ) ) } else { let logger = createLogger() return createStore( rootReducer, preloadedState, compose( applyMiddleware(thunkMiddleware, logger), window.devToolsExtension() ) ) } } const store = configureStore(preloadedState) export default store <file_sep>import * as Actions from '../Actions/index' export const initForecast = { first: true, isFetching: false, requested: "", formatted_address: "", current: {}, days: [], alerts: [], error: {} } export const forecast = (state = initForecast, action) => { let newState = {} switch (action.type) { case Actions.GET_COORDINATES: newState = Object.assign({},state,initForecast) return Object.assign({},newState,action.payload) case Actions.PARSE_COORDINATES: return Object.assign({},state,{ formatted_address: action.payload.fa }) case Actions.PARSE_FORECAST: return Object.assign({},state,action.payload) case Actions.FETCH_ERROR: newState = Object.assign({},state,initForecast) return Object.assign({},newState,action.payload) default: return state } } export default forecast<file_sep>import React, { Component } from 'react' import { render } from 'react-dom' import Location from './Location' const Header = (props) => { return ( <div> <Location dispatch={props.dispatch} /> </div> ) } export default Header<file_sep>import React from 'react' export default () => <div className="footer"> <div>Forecaster by <NAME></div> <div>Powered by</div> <ul className="list-inline"> <li> <a href="https://darksky.net" target="_blank"> <img src="https://darksky.net/images/darkskylogo.png" alt="Dark Sky API" /> </a> </li> <li>&</li> <li> <a href="https://developers.google.com/maps/documentation/geocoding/start" target="_blank"> <i className="fa fa-google fa-2x"></i> </a> </li> </ul> </div>
60df6160044c4e66fdb2a9fef17ddfc83e3551c9
[ "JavaScript", "Markdown" ]
13
JavaScript
slmoore/forecaster
6bfc23f9a99e65f422bc21b3361751da4bda2fce
8eeafea5c6f99574c889137fdb96c857c108ed15
refs/heads/master
<repo_name>jakelacey2012/Micro-Services<file_sep>/notifications/server/main.js import { Meteor } from 'meteor/meteor'; import { Notifications } from 'meteor/notification-microservice'; Meteor.startup(() => { console.log(Notifications.example()); });
c86e8230f8f4b2162830fbe11d9ad1b9b29f3c3a
[ "JavaScript" ]
1
JavaScript
jakelacey2012/Micro-Services
56a4e9067b8984f171c3e6655dc1e07ffd969ad9
acfe25eaa15041fdb51c2b194bc25fa12e88dff4
refs/heads/master
<repo_name>juhyun10/sp4-chap12<file_sep>/README.md # Spring4 # MVC 2 : 메시지, 커맨트 객체, 검증, 세션, 인터셉터, 쿠키 contents - - 메시지 처리 - 커맨드 객체 검증과 에러 메시지 - HttpSession 사용 - HandlerInterceptor - 쿠키 접근 <file_sep>/sp4-chap12/src/main/java/spring/AlreadyExistingMemberException.java package spring; /** * 회원 가입 처리 관련 클래스 * * @author assu * @date 2016.05.22 */ public class AlreadyExistingMemberException extends RuntimeException { /** */ private static final long serialVersionUID = 8541713429299719920L; public AlreadyExistingMemberException(String message) { super(message); } } <file_sep>/sp4-chap12/src/main/java/interceptor/AuthCheckInterceptor.java package interceptor; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; /** * 로그인 여부 인터셉터 * * request.getSession(), request.getSession(true) - HttpSession이 존재하면 현재의 HttpSession 반환, * 존재하지 않으면 새로운 HttpSession 생성. * request.getSession(false) - 존재하지 않으면 null 반환. * * @author assu * @date 2016. 7. 30. */ public class AuthCheckInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { HttpSession session = request.getSession(false); if (session != null) { Object authInfo = session.getAttribute("authInfo"); if (authInfo != null) { return true; } } response.sendRedirect(request.getContextPath() + "/login"); return false; } }
8d11b3094399ac65a8e1a1920f3632b1b0babbae
[ "Markdown", "Java" ]
3
Markdown
juhyun10/sp4-chap12
9c30f75134b0d34ee9fea6fa010cc9e85d2321fc
a36380a2d70d7335df349499e31eb7b8e1bc4e70
refs/heads/master
<repo_name>michellbrito/interviewQuestions<file_sep>/Coding Bootcamp/maxNum.js // Write code to return the largest number in the given array function maxNum(arr){ let maxNumber; for (let i = 0; i < arr.length; i++){ if (arr[i] > arr[i+1]){ maxNumber = arr[i] } } return maxNumber; }<file_sep>/Coding Bootcamp/logNums.js /* Print all numbers from 1 up to the given nums argument inclusive. e.g. given the number 5 as the num argument, the following should be printed to the console, one log at a time: */ module.exports = { logNums: function(num){ for (var i = 1; i <= num; i++){ console.log(i); } } }<file_sep>/Coding Bootcamp/productOfLargestTwo.js // Write code to create a function that accepts an array of numbers, finds the largest two numbers, and returns the product of the two function productOfLargestTwo(arr) { let highest = 0; let secondHighest = 0; for (let i = 0; i < arr.length; i++){ if (arr[i] > highest || highest == 0){ secondHighest = highest; highest = arr[i]; } else if (arr[i] > secondHighest || secondHighest == 0) { secondHighest = arr[i]; }; }; return highest * secondHighest; }; <file_sep>/Coding Bootcamp/doubleTripleMap.js // Write code to create a function that accepts an array of numbers and returns a new array that corresponds to the original array // If a element in the original array is even, the element at the same index in the new array should be double the original element // If an element in the original array is odd, the element at the same index of the new array should be triple the original element function doubleTripleMap(arr) { let doubleTripleArray = []; for (let i = 0; i < arr.length; i++){ if (arr[i] % 2 == 0){ let result = arr[i] * 2; doubleTripleArray.push(result); } else { let result = arr[i] * 3; doubleTripleArray.push(result); } } return doubleTripleArray; }; <file_sep>/Coding Bootcamp/test/minIncrementForUniqueTest.js var expect = chai.expect; describe("minIncrement", function() { it(`should return 1 if given the array [1, 2, 2]`, function() { var arr = [1, 2, 2]; var result = minIncrement(arr); expect(result).to.eql(1); }); it(`should return 6 if given the array [3, 2, 1, 2, 1, 7]`, function() { var arr = [3, 2, 1, 2, 1, 7]; var result = minIncrement(arr); expect(result).to.eql(6); }); it(`should return 3 if given the array [8, 6, 8, 9, 10]`, function() { var arr = [8, 6, 8, 9, 10]; var result = minIncrement(arr); expect(result).to.eql(3); }); it(`should return 13 if given the array [0, 0, 1, 2, 2, 3, 0]`, function() { var arr = [0, 0, 1, 2, 2, 3, 0]; var result = minIncrement(arr); expect(result).to.eql(13); }); it(`should return 0 if given the array [1, 0, 2, -4, 9, 4]`, function() { var arr = [1, 0, 2, -4, 9, 4]; var result = minIncrement(arr); expect(result).to.eql(0); }); it(`should return 0 if given the array []`, function() { var arr = []; var result = minIncrement(arr); expect(result).to.eql(0); }); });<file_sep>/Coding Bootcamp/stringMap.js // Write code to create a function that accepts a string and returns an object // The object should contain keys for each character in the string // Each key should point to an array containing the indexes the character is found in the string function stringMap(str) { let stringMap = {}; for (let i = 0; i < str.length; i++){ if (stringMap[str[i]]){ stringMap[str[i]].push(i) } else { stringMap[str[i]] = [i]; } } return stringMap; };<file_sep>/Coding Bootcamp/test/oddevenTest.js var chai = require('chai'); var assert = chai.assert; var expect = chai.expect; var should = chai.should() var oddOrEven = require('../oddeven').oddOrEven; describe("oddOrEven", function() { it('should return the string "odd" if a number IS NOT evenly divisible by 2', function() { var num = 777; var result = oddOrEven(num); expect(result).to.eql("odd"); }); it('should return the string "even" if a number IS evenly divisible by 2', function() { var num = 1002; var result = oddOrEven(num); expect(result).to.eql("even"); }); });<file_sep>/Coding Bootcamp/swapCase.js function swapCase(str) { var swappedStr = ""; for (var i = 0; i < str.length; i++) { if (str[i] == str[i].toLowerCase()) { swappedStr = swappedStr + str[i].toUpperCase(); } else { swappedStr = swappedStr + str[i].toLowerCase(); } } return swappedStr; };<file_sep>/Cracking The Coding Interview/isUnique.py ''' THE PROBLEM - Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? ''' def isUnique(userString): for i in range(0,len(userString)): for j in range(i+1,len(userString)): if userString[i] == userString[j]: return False return True isUnique("testing") ''' MY LOGIC - take in a string - turn that string into a array - loop through that array - loop through that array again in order to compare the first and second letter - return true if all letters don't repeate, - return false if more than one letter is the same ''' <file_sep>/Coding Bootcamp/mergeSorted.js // Write code to merge two sorted arrays into a new sorted array function mergeSorted(arr1, arr2) { let mergeSortedArray = []; mergeSortedArray.push(...arr1,...arr2); for (let i = mergeSortedArray.length - 1; i >= 0; i--){ for (let j = 1; j <= i; j++){ if (mergeSortedArray[j-1] > mergeSortedArray[j]){ let temp = mergeSortedArray[j-1]; mergeSortedArray[j-1] = mergeSortedArray[j]; mergeSortedArray[j] = temp; } } } return mergeSortedArray; };<file_sep>/Coding Bootcamp/arithmetic.js /* In this file you will be writing code in the body of each function defined to accomplish the following: add: returns the result of num1 plus num2. subtract: returns the result of num1 minus num2. multiply: returns the result of num1 times num2. divide: returns the result of num1 divided by num2. */ module.exports = { add: function(num1, num2){ return num1 + num2; }, subtract: function(num1,num2){ return num1 - num2; }, multiply: function(num1,num2){ return num1 * num2; }, divide: function(num1,num2){ return num1 / num2; } } <file_sep>/Coding Bootcamp/leftRotation.js // Write a function that takes an array and a positive integer and "rotates" the array to the left by the integer // Modify the original array rather than returning a new one // There is no need to return from this function function leftRotation(arr, positions) { while (positions > 0){ let firstElem = arr.shift(); arr.push(firstElem); positions--; } };<file_sep>/Coding Bootcamp/missingNumber.js // Write a function that takes an unsorted array of positive and unique integers and returns the number missing from the array function missingNumber(nums) { let numsPresent = {}; for (let i = 0; i < nums.length; i++) { numsPresent[nums[i]] = true; } for (let i = 0; i < nums.length + 1; i++) { if (!numsPresent[i]) { return i; } } }; <file_sep>/Coding Bootcamp/characterCount.js // Write code to create a function that accepts a string and returns an object containing the number of times each character appears in the string function characterCount(str) { let characterMap = {}; for (let i = 0; i < str.length; i++){ if (str[i] in characterMap){ characterMap[str[i]]++; } else { characterMap[str[i]] = 1; } } return characterMap; }; characterCount("Hello World!");<file_sep>/Coding Bootcamp/test/arrayIntersectionTest.js var expect = chai.expect; function containSameElements(arr1, arr2) { var arr1Copy = JSON.parse(JSON.stringify(arr1)); for (var i = 0; i < arr2.length; i++) { var num = arr2[i]; var arr1Index = arr1Copy.indexOf(num); if (arr1Index === -1 || arr1Copy.length === 0) { return false; } arr1Copy.splice(arr1Index, 1); } return true; } describe("arrayIntersection", function() { it(`should return [1, 3, 5] when given [1, 2, 3, 4, 5] and [5, 0, 3, 10, -2, 1]`, function() { var arr1 = [1, 2, 3, 4, 5]; var arr2 = [5, 0, 3, 10, -2, 1]; var result = arrayIntersection(arr1, arr2); var expected = [1, 3, 5]; var areEqual = containSameElements(result, expected); expect(areEqual).to.eql(true); }); it(`should return [7, 13, 13, 13] when given [13, 12, 13, 14, 13, -9, 7] and [11, 7, 13, -19, 13, 111, 13]`, function() { var arr1 = [13, 12, 13, 14, 13, -9, 7]; var arr2 = [11, 7, 13, -19, 13, 111, 13]; var result = arrayIntersection(arr1, arr2); var expected = [7, 13, 13, 13]; var areEqual = containSameElements(result, expected); expect(areEqual).to.eql(true); }); it(`should return [] when given [99, 88, 77, 66] and [55, 44, 33, 22, 11]`, function() { var arr1 = [99, 88, 77, 66]; var arr2 = [55, 44, 33, 22, 11]; var result = arrayIntersection(arr1, arr2); var expected = []; expect(result).to.eql(expected); }); });<file_sep>/Coding Bootcamp/camelCase.js function camelCase(str) { let camelCaseSentence = str.toLowerCase().split(" "); for (var i = 1; i < camelCaseSentence.length; i++){ camelCaseSentence[i] = camelCaseSentence[i][0].toUpperCase() + camelCaseSentence[i].substring(1); } return camelCaseSentence.join(""); }; camelCase("Hello World");<file_sep>/Coding Bootcamp/zerosAndOnes.js // Write code to create a function that accepts a string containing only 0s and 1s // Return true if there are an equal number of 0s and 1s // Else return false function zerosAndOnes(str) { let zeroCounter = 0; let oneCounter = 0; let isZeroEqualToOne = false; for (let i = 0; i < str.length; i++){ if (str[i] == "0"){ zeroCounter++ } else if (str[i] == "1"){ oneCounter++ } } if (zeroCounter == oneCounter){ isZeroEqualToOne = true; } return isZeroEqualToOne; }; <file_sep>/Coding Bootcamp/maxProfit.js // Write a function that takes an array of integers representing the price of a stock on different days. Return the maximum profit that can be made from buying and selling a single stock function maxProfit(prices) { let minPrice = prices[0]; let maxProfit = prices[1] - prices[0]; for (let i = 0; i < prices.length; i++) { maxProfit = Math.max(maxProfit, prices[i] - minPrice ); minPrice = Math.min(minPrice, prices[i]); } return maxProfit; };<file_sep>/Coding Bootcamp/arraySearch2D.js // Write code to create a function that accepts a two-dimensional array // Each 2D element contains either the string "X" or "O" (both capitalized) // Return the number of times "X" appears in the 2D array function arraySearch2D(arr) { let counter = 0; for (let i = 0; i < arr.length; i++){ for (j = 0; j < arr[i].length; j++){ if (arr[i][j] == "X"){ counter++ } } } return counter; };<file_sep>/Coding Bootcamp/oddeven.js /* In this file you will be writing code in the body of the oddOrEven function to achieve the following: If num is evenly divisible by 2, return the string "even". If num is NOT evenly divisible by 2, return the string "odd". */ module.exports = { oddOrEven: function(num){ if (num % 2 == 0){ return "even" } else { return "odd" } } }<file_sep>/Coding Bootcamp/peakFinder.js // Write a function that takes an array of integers containing exactly one peak. A peak is defined as a location in the array where the value is greater than every number to the left and every number to the right. Return the value found at the array's peak function peakFinder(nums) { let sortedArray = nums; for (let i = sortedArray.length - 1; i >= 0; i--){ for (let j = 1; j <= i; j++){ if (sortedArray[j-1] > sortedArray[j]){ let temp = sortedArray[j-1]; sortedArray[j-1] = sortedArray[j]; sortedArray[j] = temp; } } } return sortedArray[sortedArray.length -1] };<file_sep>/Coding Bootcamp/logEvenNums.js /* Print all even numbers from 0 up to the given nums argument inclusive. e.g. given the number 6 as the num argument, the following should be printed to the console, one log at a time: 0 2 4 6 */ module.exports = { logEvenNums: function(nums){ for (let i = 0; i < nums; i++){ if (i % 2 == 0){ console.log(i) } } } }<file_sep>/Coding Bootcamp/multiplyInto20.js // Write code to create a function that accepts an array of unique numbers // If any two numbers in the array add up to 20, return true, else return false function multiplyInto20(arr) { let isArrEqualTo20 = false; for (let i = 0; i < arr.length; i++){ for (let j = i + 1; j < arr.length; j++){ if (arr[i] * arr[j] == 20){ isArrEqualTo20 = true; break; } } } return isArrEqualTo20; }; <file_sep>/Coding Bootcamp/sumArray.js /* Add all of the numbers in the given arr array argument and return the total. e.g. given the following array: var arr = [3, 1, 5, 6]; The following number should be returned: 15; */ module.exports = { sumArray: function(arr){ let total = 0; for (let i = 0; i < arr.length; i++){ total += arr[i]; } return total; } }<file_sep>/Coding Bootcamp/isArmstrong.js // Write a function that takes a positive integer and returns true if the integer is an armstrong number, else return false. To find out if a number is an armstrong number, take each individual digit and raise it to the power of the length of the entire number and add the digits. If the sum equals the original number, the number is an armstrong number function isArmstrong(num) { let sum = 0; let numSplit = num.toString().split('') for (let i = 0; i < numSplit.length; i++){ sum = sum + Math.pow(numSplit[i], numSplit.length) } return sum == num; };
2616142b93a8fd03cbba7477670718f388ab07ab
[ "JavaScript", "Python" ]
25
JavaScript
michellbrito/interviewQuestions
24ae7e322cdad48a5d68933bf98e5cb0c8abb9d8
1628d0f5d0f116708600d6db529120a559673007
refs/heads/main
<repo_name>abyanphukan434/Class-115<file_sep>/logisticRegression.py import plotly.express as px import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression df = pd.read_csv('tempData.csv') temperature_list = df['Temperature'].tolist() melted_list = df['Melted'].tolist() fig = px.scatter(x = temperature_list, y = melted_list) fig.show() temperature_array = np.array(temperature_list) melted_array = np.array(melted_list) m, c = np.polyfit(temperature_array, melted_array, 1) y = [] for x in temperature_array: y_value = m * x + c y.append(y_value) fig = px.scatter(x = temperature_array, y = melted_array) fig.update_layout(shapes = [ dict( type = 'line', y0 = min(y), y1 = max(y), x0 = min(temperature_array), x1 = max(temperature_array) ) ]) fig.show() X = np.reshape(temperature_list, (len(temperature_list), 1)) Y = np.reshape(melted_list, (len(melted_list), 1)) lr = LogisticRegression() lr.fit(X, Y) plt.figure() plt.scatter(X.ravel(), Y, color = 'black', zorder = 20) def model(x): return 1/(1 + np.exp(-x)) X_test = np.linspace(0, 5000, 10000) chances = model(X_test * lr.coef_ + lr.intercept_).ravel() plt.plot(X_test, chances, color = 'red', linewidth = 3) plt.axhline(y = 0, color = 'k', linestyle = '-') plt.axhline(y = 1, color = 'k', linestyle = '-') plt.axhline(y = 0.5, color = 'b', linestyle = '--') plt.axvline(x = X_test[6843], color = 'b', linestyle = '--') plt.ylabel('y') plt.xlabel('X') plt.xlim(3400, 3450) plt.show() temp = float(input('Enter the temperature:')) chances = model(temp * lr.coef_ + lr.intercept_).ravel()[0] if chances <= 0.01: print('Tungsten will not be melted.') elif chances >= 1: print('Tungsten will be melted.') elif chances < 0.5: print('Tungsten might not get melted.') else: print('Tungsten may get melted.')
6c820e98b2ebb7d219afb8cb6a01283680efc58f
[ "Python" ]
1
Python
abyanphukan434/Class-115
74725552737b47784c1d31911210f5b0bbbaaecd
021bb4abc4295f8502a0b0624926202e8e1f16f2
refs/heads/master
<file_sep>import os url_path_start = "/prepended-start-" my_str = input("Enter string: ") print(url_path_start + my_str.replace(' ', '-').lower()) os.system("pause")
ca5910e35a0a5e6cc69b6ca3c88ea3e97efcbe65
[ "Python" ]
1
Python
mario4l/url-cleanup
cc35c806855efbc234418972dcbf605052f80acf
93af1dec31d4d919d507aa63b03fdcf842236718
refs/heads/master
<repo_name>jjxxs/Pathfinder<file_sep>/problem/problem.go package problem import ( "encoding/json" "errors" "io/ioutil" "math" "math/rand" "os" "path/filepath" "strings" ) const ( Geographic = "geographic" Euclidean = "euclidean" ) // contains the distances between each point on a route type Adjacency [][]float64 // a cycle is a set of integers that are to be mapped to points type Cycle []int // a route is a set of points in a specific order, it is a high-level representation of a cycle type Route []Point func (r Route) String() string { routeStr := "" for i, p := range r { if i == len(r)-1 { routeStr += p.Name } else { routeStr += p.Name + " <-> " } } return routeStr } // represents a 'tsp-problem' that is to be solved by the solver type Problem struct { // info about the problem Info Info `json:"info"` // path to the image of the problem, if any Image Image `json:"image"` // route of the problem, e.g. a set of points that the solver has to bring into the right order // for it to be the shortest route possible Points []Point `json:"points"` ShortestRoute Route `json:"route"` ShortestDistance float64 `json:"shortestDistance"` // adjacency matrix, e.g. distances between the points Adjacency Adjacency `json:"adjacency"` } // contains information about a problem type Info struct { Name string `json:"name"` Description string `json:"description"` // either 'geographic' or 'euclidean' // determines how distance between two points is calculated Type string `json:"type"` } type Image struct { Path string `json:"path"` X1 float64 `json:"x1"` Y1 float64 `json:"y1"` X2 float64 `json:"x2"` Y2 float64 `json:"y2"` Width int `json:"width"` Height int `json:"height"` } // a point in two-dimensional space type Point struct { X float64 `json:"x"` Y float64 `json:"y"` Name string `json:"name"` } type Status struct { Algorithm string `json:"algorithm"` Problem string `json:"problem"` Description string `json:"description"` Elapsed string `json:"elapsed"` Shortest float64 `json:"shortest"` Running bool `json:"running"` } func NewProblem(points []Point) *Problem { p := Problem{ Points: points, } p.calculateAdjacency() return &p } // loads a set of problems from a directory func FromDir(dir string) ([]Problem, error) { // stat directory to test if it's accessible if file, err := os.Stat(dir); err != nil { return []Problem{}, err } else if !file.IsDir() { // if it's not a directory try to load it as a file problem, err := FromFile(dir) if err != nil { return []Problem{}, err } return []Problem{problem}, nil } // try to read directory files, err := ioutil.ReadDir(dir) if err != nil { return []Problem{}, err } // try to load every file in directory as problem problems := make([]Problem, 0) for _, file := range files { // is subdirectory, ignore if file.IsDir() { continue } // skip files that don't end with "json" absFilePath := filepath.Join(dir, file.Name()) if filepath.Ext(absFilePath) != ".json" { continue } // load problem problem, err := FromFile(absFilePath) if err != nil { continue } problems = append(problems, problem) } return problems, nil } // loads a problem from a file func FromFile(file string) (Problem, error) { // stat file to test if it's accessible if file, err := os.Stat(file); err != nil { return Problem{}, err } else if file.IsDir() { return Problem{}, errors.New("expected file but provided directory") } // read file bytes, err := ioutil.ReadFile(file) if err != nil { return Problem{}, err } // parse json to problem var problem = Problem{} err = json.Unmarshal(bytes, &problem) if err != nil { return Problem{}, err } // calculate adjacency and return problem.calculateAdjacency() return problem, nil } func (p *Problem) UpdateRoute(cycle Cycle) { // set new route route := make(Route, len(cycle)) for i, j := range cycle { route[i] = p.Points[j] } p.ShortestRoute = route // calculate new distance var distance float64 for i := range cycle { if i == len(cycle)-1 { distance += p.Adjacency[cycle[i]][cycle[0]] } else { distance += p.Adjacency[cycle[i]][cycle[i+1]] } } p.ShortestDistance = distance } // calculates the adjacency matrix of the problem with given points // - uses the haversine-formula to calculate distances for "geographic" problems // - uses euclidean distance for "euclidean" problems func (p *Problem) calculateAdjacency() { var calcDistance func(p1, p2 Point) float64 switch pType := strings.ToLower(p.Info.Type); pType { case Geographic: calcDistance = haversine case Euclidean: calcDistance = euclidean default: calcDistance = euclidean } // shuffle before calculating adjacency rand.Shuffle(len(p.Points), func(i, j int) { p.Points[i], p.Points[j] = p.Points[j], p.Points[i] }) // allocate adjacency and calculate distances p.Adjacency = make(Adjacency, len(p.Points)) for i, rowPoint := range p.Points { adjRow := make([]float64, len(p.Points)) for j, colPoint := range p.Points { adjRow[j] = calcDistance(rowPoint, colPoint) } p.Adjacency[i] = adjRow } } // the earths radius in kilometer, used to calculate distances on spheres using the haversine formula const EarthRadius = 6371 // calculates the shortest point between two points located on a sphere (the earth) func haversine(p1, p2 Point) float64 { deg2rad := func(deg float64) float64 { return (math.Pi * deg) / 180 } lat1 := deg2rad(p1.X) lat2 := deg2rad(p2.X) long1 := deg2rad(p1.Y) long2 := deg2rad(p2.Y) deltaLong := long1 - long2 deltaLat := lat1 - lat2 a := math.Pow(math.Sin(deltaLat/2), 2) + math.Cos(lat1)*math.Cos(lat2)*math.Pow(math.Sin(deltaLong/2), 2) c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) return EarthRadius * c } // calculates the shortest distance between two points in an euclidean system func euclidean(p1, p2 Point) float64 { deltaX := math.Abs(p1.X - p2.X) deltaY := math.Abs(p1.Y - p2.Y) return math.Sqrt(math.Pow(deltaX, 2) + math.Pow(deltaY, 2)) } func (p *Problem) MapRouteToImageCoordinates() []int { coordinates := make([]int, 2*len(p.ShortestRoute)) if p.Info.Type == Geographic { xDiff := math.Abs(p.Image.X1 - p.Image.X2) yDiff := math.Abs(p.Image.Y1 - p.Image.Y2) xPixel := float64(p.Image.Width) / xDiff yPixel := float64(p.Image.Height) / yDiff for i, point := range p.ShortestRoute { x := (point.X - p.Image.X1) * xPixel y := (p.Image.Y1 - point.Y) * yPixel coordinates[i*2] = int(x) coordinates[i*2+1] = int(y) } } else { for i, point := range p.ShortestRoute { coordinates[i*2] = int(point.X) coordinates[i*2+1] = int(point.Y) } } return coordinates } <file_sep>/algorithm/algorithm.go package algorithm import ( "fmt" "strings" "leistungsnachweis-graphiker/problem" ) type Algorithm interface { Solve(adjacency problem.Adjacency, updates chan problem.Cycle) Stop() String() string } func FromString(algorithmName string) (Algorithm, error) { switch alg := strings.ToLower(algorithmName); alg { //case "mst": // return NewMst(), nil case "bruteforce": return NewBruteForce(), nil case "heldkarp": return NewHeldKarp(), nil default: return nil, fmt.Errorf("algorithm not found: %s", algorithmName) } } <file_sep>/algorithm/misc_test.go package algorithm import ( "reflect" "testing" ) func TestGetPrimesTo(t *testing.T) { // generate primes in [2, 1000] isPrimes := GetPrimesTo(1000) // primes in [2, 1000] shouldPrimes := []int{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997} for i := range isPrimes { if isPrimes[i] != shouldPrimes[i] { t.Fatalf("non-matching primes: %d != %d", isPrimes[i], shouldPrimes[i]) } } } func BenchmarkGetPrimesTo(b *testing.B) { GetPrimesTo(b.N) } func TestPowerSet(t *testing.T) { set := Set{1, 2, 3, 4} isSet := PowerSet(set) shouldSet := []Set{ {}, {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}, } if len(isSet) != len(shouldSet) { t.Fatalf("sets have different lengths") } for i := range isSet { eq := reflect.DeepEqual(isSet[i], shouldSet[i]) if !eq { t.Fatalf("sets are not equal") } } } <file_sep>/webui/src/redux/AppState.ts import {Reducer} from "redux"; //********************************************************** // Actions //********************************************************** export enum ActionTypes { ON_INIT = "ON_INIT", ON_MESSAGE_RECEIVED = "ON_MESSAGE_RECEIVED", ON_CONNECT = "ON_CONNECT", ON_DISCONNECT = "ON_DISCONNECT", ON_POST_IMAGE = "ON_POST_IMAGE", ON_POST_COORDINATES = "ON_POST_COORDINATES", ON_POST_STATUS = "ON_POST_STATUS", } export interface OnInit { type: string } export const onInit = () => { return {type: ActionTypes.ON_INIT} }; export interface OnConnect { type: string } export const onConnect = () => { return {type: ActionTypes.ON_CONNECT} }; export interface OnDisconnect { type: string } export const onDisconnect = () => { return {type: ActionTypes.ON_DISCONNECT} }; export interface OnPostImage { type: string, image: string } export const onPostImage = (image: string) => { return {type: ActionTypes.ON_POST_IMAGE, image} }; export interface OnPostCoordinates { type: string, coordinates: number[] } export const onPostCoordinates = (coordinates: number[]) => { return {type: ActionTypes.ON_POST_COORDINATES, coordinates} }; export interface OnPostStatus { type: string, status: Status } export const onPostStatus = (status: Status) => { return {type: ActionTypes.ON_POST_STATUS, status} }; //********************************************************** // Messages //********************************************************** export enum MessageTypes { POST_IMAGE = "PostImage", COORDINATES = "Coordinates", STATUS = "Status", } export interface ImageMessageData { image: string; } export interface CoordinatesMessageData { coordinates: number[]; } export interface StatusMessageData { status: Status; } //********************************************************** // Types //********************************************************** export interface AppState { connected: boolean; image: string; points: number[]; settings: Settings; status: Status; } export interface Settings { server: string; } export interface Message { type: string; data: object; } export interface Status { algorithm: string; problem: string; description: string; elapsed: string; shortest: number; running: boolean; } //********************************************************** // Reducer //********************************************************** const initialState: AppState = { connected: false, image: "", points: [], settings: {server: "ws://localhost:8091/websocket/"}, status: {algorithm: "", problem: "", description: "", elapsed: "", running: false, shortest: 0}, }; const reducer: Reducer<AppState> = (state = initialState, action) => { switch (action.type) { case ActionTypes.ON_CONNECT: return Object.assign({}, state, {connected: true}); case ActionTypes.ON_DISCONNECT: return initialState; case ActionTypes.ON_POST_IMAGE: return Object.assign({}, state, {image: (action as OnPostImage).image}); case ActionTypes.ON_POST_COORDINATES: return Object.assign({}, state, {points: (action as OnPostCoordinates).coordinates}); case ActionTypes.ON_POST_STATUS: return Object.assign({}, state, {status: (action as OnPostStatus).status }); default: break; } return state; }; export {reducer as appReducer}<file_sep>/algorithm/mst.go package algorithm import ( "leistungsnachweis-graphiker/problem" "sort" ) type Mst struct { running bool shortestDistance float64 shortestCycle problem.Cycle } type edge struct { i int j int dist float64 } func NewMst() *Mst { return &Mst{} } func (a *Mst) Stop() { a.running = false } func (a *Mst) Solve(adjacency problem.Adjacency, updates chan problem.Cycle) { a.running = true // generate all edges edges := make([]edge, 0) for i := 0; i < len(adjacency); i++ { for j := i + 1; j < len(adjacency); j++ { edges = append(edges, edge{i: i, j: j, dist: adjacency[i][j]}) } } // sort by weight sort.Slice(edges, func(i, j int) bool { return edges[i].dist < edges[j].dist }) // kruskal's algorithm mst := make([]edge, 0) for len(edges) > 0 { candidate := edges[0] // test for shortestCycle i, j := false, false for _, edge := range mst { if edge.i == candidate.i { i = true } else if edge.j == candidate.j { j = true } } // shortestCycle detected, discard and continue if i && j { edges = edges[1:] continue } // otherwise add to mst mst = append(mst, candidate) edges = edges[1:] } // generate shortestCycle current := 0 a.shortestCycle = problem.Cycle{current} visited := make([]bool, len(adjacency)) visited[0] = true v := 1 for v < len(adjacency) { for _, e := range mst { if e.i != current && e.j != current { continue } if e.i == current { if visited[e.j] { current = e.j } else { visited[e.j] = true a.shortestCycle = append(a.shortestCycle, e.j) v++ } } else if e.j == current { if visited[e.i] { current = e.i } else { visited[e.i] = true a.shortestCycle = append(a.shortestCycle, e.i) v++ } } } } for i := range a.shortestCycle { if i == len(a.shortestCycle)-1 { a.shortestDistance += adjacency[a.shortestCycle[i]][a.shortestCycle[0]] } else { a.shortestDistance += adjacency[a.shortestCycle[i]][a.shortestCycle[i+1]] } } updates <- a.shortestCycle close(updates) a.running = false } <file_sep>/go.mod module leistungsnachweis-graphiker go 1.12 require ( github.com/gorilla/websocket v1.4.0 github.com/urfave/cli v1.20.0 ) <file_sep>/algorithm/bruteforce_test.go package algorithm import ( "leistungsnachweis-graphiker/problem" "math" "testing" ) func TestBruteForce(t *testing.T) { points := []problem.Point{ {X: 0, Y: 0}, {X: 50, Y: 0}, {X: 50, Y: 50}, {X: 0, Y: 50}, {X: 25, Y: 75}, } p := problem.NewProblem(points) b := NewBruteForce() u := make(chan problem.Cycle, 10) go b.Solve(p.Adjacency, u) for { cycle, hasMore := <-u if !hasMore { break } p.UpdateRoute(cycle) } if math.Round(p.ShortestDistance*100)/100 != 220.71 { t.Fatalf("wrong distance: %f", p.ShortestDistance) } } <file_sep>/solver/cli.go package solver import ( "leistungsnachweis-graphiker/algorithm" "leistungsnachweis-graphiker/problem" "leistungsnachweis-graphiker/web" "log" "math" "time" ) type CliController struct { running bool algorithm algorithm.Algorithm problem problem.Problem startTime time.Time webHandler *web.Handler } func NewCli(algorithmName, problemPath, bind string) CliController { log.Printf("running as cli") // try to instantiate algorithm from string alg, err := algorithm.FromString(algorithmName) if err != nil { log.Fatal(err) } // try to load problem from provided filepath prob, err := problem.FromFile(problemPath) if err != nil { log.Fatal(err) } // start webhandler? if len(bind) != 0 { wh, err := web.NewHandler(prob.Image.Path, bind) if err != nil { log.Fatal(err) } return CliController{algorithm: alg, problem: prob, webHandler: wh} } return CliController{algorithm: alg, problem: prob} } func (c *CliController) Start() { c.running = true c.startTime = time.Now() updates := make(chan problem.Cycle, 10) go c.algorithm.Solve(c.problem.Adjacency, updates) // ticker to update stats every second ticker := time.NewTicker(1 * time.Second) // immediately send status status := problem.Status{ Algorithm: c.algorithm.String(), Problem: c.problem.Info.Name, Description: c.problem.Info.Description, Elapsed: time.Since(c.startTime).String(), Shortest: math.Round(c.problem.ShortestDistance*100) / 100, Running: true, } if c.webHandler != nil { c.webHandler.Status <- status } for c.running { select { case update, more := <-updates: if !more { c.running = false log.Printf("Finished execution of problemset \"%s\":\n\tRoute: %v\n\tDistance: %f\n\tTime: %fs\n", c.problem.Info.Name, c.problem.ShortestRoute, c.problem.ShortestDistance, time.Since(c.startTime).Seconds(), ) break } c.problem.UpdateRoute(update) log.Printf("New Route:\n\tRoute: %v\n\tDistance: %f\n", c.problem.ShortestRoute, c.problem.ShortestDistance) if c.webHandler != nil { coordinates := c.problem.MapRouteToImageCoordinates() c.webHandler.Updates <- coordinates } case <-ticker.C: if c.webHandler == nil { continue } status := problem.Status{ Algorithm: c.algorithm.String(), Problem: c.problem.Info.Name, Description: c.problem.Info.Description, Elapsed: time.Since(c.startTime).String(), Shortest: math.Round(c.problem.ShortestDistance*100) / 100, Running: true, } c.webHandler.Status <- status case <-time.After(100 * time.Millisecond): break } } ticker.Stop() } <file_sep>/main.go package main import ( "log" "os" "time" "leistungsnachweis-graphiker/solver" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Name = "Pathfinder" app.Usage = "A solver for the travelling salesman problem" app.HideVersion = true app.Flags = []cli.Flag{ cli.StringFlag{ Name: "algorithm", Usage: "name of the algorithm to use", }, cli.StringFlag{ Name: "problem", Usage: "path to the problem-file to be solved", }, cli.StringFlag{ Name: "bind", Usage: "address to listen for websocket-connections", }, } app.Action = startCli err := app.Run(os.Args) if err != nil { log.Fatal(err) } } func startCli(c *cli.Context) { algorithm := c.String("algorithm") problem := c.String("problem") bind := c.String("bind") cliController := solver.NewCli(algorithm, problem, bind) time.Sleep(time.Second * 3) cliController.Start() } <file_sep>/algorithm/heldkarp.go package algorithm import ( "leistungsnachweis-graphiker/problem" "math" ) type HeldKarp struct { running bool primes []int shortestDistance float64 shortestCycle problem.Cycle } func NewHeldKarp() *HeldKarp { return &HeldKarp{ shortestDistance: math.MaxFloat64, } } func (a *HeldKarp) Stop() { a.running = false } func (a *HeldKarp) Solve(adjacency problem.Adjacency, updates chan problem.Cycle) { a.running = true set := make([]int, len(adjacency)) for i := range set { set[i] = i } // prime table for hashing the sets a.primes = GetPrimesTo(len(set) * 100) // create table table := make([]map[int]float64, len(set)) // route from i through the empty set to 0 for i := range set { table[i] = make(map[int]float64) table[i][a.getHash(Set{})] = adjacency[i][0] } backtracking := make([]map[int]int, len(set)) for i := range set { backtracking[i] = make(map[int]int) } // for every subset of S\{0} for _, subset := range PowerSet(set[1:]) { // stopped by user if !a.running { break } if len(subset) == 0 { continue } // for every i, find the shortest shortestDistance that goes from i through subset to 0 // e.g. choose a j from subset that connects to i so that shortestDistance is minimal NextElement: for _, i := range set { // if i is element of subset, cancel for _, j := range subset { if i == j { continue NextElement } } hash := a.getHash(subset) // try for every j in subset the route from i to j through subset so that the shortestDistance is minimal minDistance := float64(math.MaxFloat64) minJ := 0 for _, j := range subset { // subset\{j} subsetNoJ := make([]int, len(subset)-1) index := 0 for _, p := range subset { if p == j { continue } subsetNoJ[index] = p index++ } h := a.getHash(subsetNoJ) dist := adjacency[i][j] + table[j][h] if dist < minDistance { minDistance = dist minJ = j } } table[i][hash] = minDistance backtracking[i][hash] = minJ } } if !a.running { return } // backtracking backtrackingSet := make(Set, len(set)-1) for i := range backtrackingSet { backtrackingSet[i] = i + 1 } a.shortestCycle = make(problem.Cycle, len(set)) last := 0 for i := range set { h := a.getHash(backtrackingSet) a.shortestCycle[i] = backtracking[last][h] last = a.shortestCycle[i] tmpSet := make(Set, len(backtrackingSet)-1) if len(tmpSet) == 0 { break } index := 0 for j := range backtrackingSet { if backtrackingSet[j] == a.shortestCycle[i] { continue } tmpSet[index] = backtrackingSet[j] index++ } backtrackingSet = tmpSet } // get shortest shortestDistance from table hShortestCycle := a.getHash(set[1:]) a.shortestDistance = table[0][hShortestCycle] // done, write solution to channel updates <- a.shortestCycle close(updates) a.running = false } func (a *HeldKarp) getHash(s Set) int { hash := 1 for _, k := range s { hash *= a.primes[k] } return hash } func (a HeldKarp) String() string { return "Held-Karp" } <file_sep>/webui/src/redux/Middleware.ts import {JWebSocket} from "../JWebsocket"; import {Dispatch, Middleware, MiddlewareAPI} from "redux"; import { ActionTypes, AppState, CoordinatesMessageData, ImageMessageData, Message, MessageTypes, onConnect, onDisconnect, onPostCoordinates, onPostImage, onPostStatus, StatusMessageData } from "./AppState"; let _websocket: JWebSocket; function onMessageReceived(messageEvent: MessageEvent) { return {type: ActionTypes.ON_MESSAGE_RECEIVED, messageEvent} } export function serverMiddleware() { const webSocketMiddleware: Middleware = ({ getState, dispatch }: MiddlewareAPI) => (next: Dispatch) => action => { switch (action.type) { case ActionTypes.ON_INIT: const url = (getState() as AppState).settings.server; console.log("[webSocketMiddleware] ON_INIT, trying to connect to " + url); const msgRcvCb = (me: MessageEvent) => { dispatch(onMessageReceived(me)) }; _websocket = new JWebSocket(url, 1, msgRcvCb, () => dispatch(onConnect()), () => dispatch(onDisconnect()), null); _websocket.connect(); break; case ActionTypes.ON_MESSAGE_RECEIVED: const msg = JSON.parse(action.messageEvent.data) as Message; switch (msg.type) { case MessageTypes.POST_IMAGE: const imageMessageData = msg.data as ImageMessageData; dispatch(onPostImage(imageMessageData.image)); break; case MessageTypes.COORDINATES: const coordinatesMessageData = msg.data as CoordinatesMessageData; dispatch(onPostCoordinates(coordinatesMessageData.coordinates)); break; case MessageTypes.STATUS: const statusMessageData = msg.data as StatusMessageData; dispatch(onPostStatus(statusMessageData.status)); break; default: break; } break; } return next(action); }; return webSocketMiddleware }<file_sep>/web/web.go package web import ( "encoding/base64" "io/ioutil" "leistungsnachweis-graphiker/problem" "log" "net/http" "os" "sync" "time" "github.com/gorilla/websocket" ) type Handler struct { bind string image string upgrader websocket.Upgrader connections []*websocket.Conn sync sync.Mutex Updates chan []int Status chan problem.Status } func NewHandler(image, bind string) (*Handler, error) { f, err := os.Open(image) if err != nil { return nil, err } b, err := ioutil.ReadAll(f) if err != nil { return nil, err } imgStr := base64.StdEncoding.EncodeToString(b) wh := Handler{ bind: bind, image: imgStr, upgrader: websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: checkOriginTrue}, connections: make([]*websocket.Conn, 0), sync: sync.Mutex{}, Updates: make(chan []int, 100), Status: make(chan problem.Status, 10), } go wh.startListen() go wh.processUpdates() return &wh, nil } func (wh *Handler) startListen() { log.Printf("starting webhandler on %s", wh.bind) http.HandleFunc("/websocket/", wh.handleWebsocket) //http.Handle("/", http.FileServer(http.Dir("website/"))) err := http.ListenAndServe(wh.bind, nil) if err != nil { log.Fatal(err) } } func (wh *Handler) handleWebsocket(w http.ResponseWriter, r *http.Request) { conn, err := wh.upgrader.Upgrade(w, r, nil) if err != nil { log.Println("error upgrading websocket") return } // send image imgMsg := Message{Type: PostImage, Data: ImageMessageData{Image: wh.image}} err = conn.WriteJSON(imgMsg) if err != nil { return } // new connection wh.addConnection(conn) } func (wh *Handler) addConnection(conn *websocket.Conn) { wh.sync.Lock() defer wh.sync.Unlock() wh.connections = append(wh.connections, conn) log.Printf("webclient connected, %s", conn.RemoteAddr()) } func (wh *Handler) removeConnection(conn *websocket.Conn) { wh.sync.Lock() defer wh.sync.Unlock() newConnections := make([]*websocket.Conn, 0) for _, c := range wh.connections { if c == conn { log.Printf("webclient disconnected, %s", conn.RemoteAddr()) continue } newConnections = append(newConnections, c) } wh.connections = newConnections } func (wh *Handler) processUpdates() { for { select { case update := <-wh.Updates: wh.sendUpdate(update) time.Sleep(100 * time.Millisecond) // hack, to prevent frontend to draw too fast case status := <-wh.Status: wh.sendStatus(status) case <-time.After(100 * time.Millisecond): break } } } func (wh *Handler) sendUpdate(coordinates []int) { for _, conn := range wh.connections { msg := Message{Type: Coordinates, Data: CoordinatesMessageData{Coordinates: coordinates}} err := conn.WriteJSON(msg) if err != nil { wh.removeConnection(conn) } } } func (wh *Handler) sendStatus(status problem.Status) { for _, conn := range wh.connections { msg := Message{Type: Status, Data: StatusMessageData{Status: status}} err := conn.WriteJSON(msg) if err != nil { wh.removeConnection(conn) } } } func checkOriginTrue(_ *http.Request) bool { return true } <file_sep>/webapp.dockerfile FROM node:8 as builder COPY webui/public /webui/public COPY webui/src /webui/src COPY webui/package.json /webui/package.json COPY webui/tsconfig.json /webui/tsconfig.json WORKDIR /webui RUN npm install && npm run build FROM nginx:stable COPY --from=builder /webui/build /usr/share/nginx/html <file_sep>/algorithm/bruteforce.go package algorithm import ( "log" "math" "time" "leistungsnachweis-graphiker/problem" ) type BruteForce struct { running bool calculations uint64 shortestDistance float64 shortestCycle []int } func NewBruteForce() *BruteForce { return &BruteForce{ shortestDistance: math.MaxFloat64, } } func (a *BruteForce) Stop() { a.running = false } // 64.099.164 // 132.215.492 func (a *BruteForce) Solve(adjacency problem.Adjacency, updates chan problem.Cycle) { // set state to running a.running = true log.Printf("solving problemset with %d entries using bruteforce", len(adjacency)) // start worker for statistics go a.worker() // slice to permute points := make([]int, len(adjacency)) for i := range points { points[i] = i } // calculate shortestDistance for the first permutation var distance float64 for i := range points { if i == len(points)-1 { distance += adjacency[points[i]][points[0]] } else { distance += adjacency[points[i]][points[i+1]] } } // found new shortest shortestCycle, set properties shortestCycle := make([]int, len(points)) copy(shortestCycle, points) a.shortestDistance = distance a.shortestCycle = shortestCycle // forward result to session updates <- problem.Cycle(shortestCycle) // heap's algorithm c := make([]int, len(adjacency)) for i := range c { c[i] = 0 } pointLength := len(points) cLength := len(c) i := 0 for i < cLength && a.running { if c[i] < i { // which point to swap with j := 0 if i%2 != 0 { j = c[i] } // indices jLeft := j - 1 if jLeft < 0 { jLeft = pointLength - 1 } jRight := j + 1 if jRight == pointLength { jRight = 0 } iLeft := i - 1 if iLeft < 0 { iLeft = pointLength - 1 } iRight := i + 1 if iRight == pointLength { iRight = 0 } // by only re-calculating the distances of the swapped points instead of the whole route, // we increase performance by a factor of two. performance increase on a intel core i7-8700k is // up from 64.000.000 to 132.000.000 iterations per second // subtract distances distance -= adjacency[points[j]][points[jLeft]] + adjacency[points[j]][points[jRight]] + adjacency[points[i]][points[iLeft]] + adjacency[points[i]][points[iRight]] // swap i with j points[j], points[i] = points[i], points[j] // add distances distance += adjacency[points[j]][points[jLeft]] + adjacency[points[j]][points[jRight]] + adjacency[points[i]][points[iLeft]] + adjacency[points[i]][points[iRight]] if distance < a.shortestDistance { // found new shortest shortestCycle, set properties and forward the result shortestCycle := make([]int, len(points)) copy(shortestCycle, points) a.shortestDistance = distance a.shortestCycle = shortestCycle updates <- problem.Cycle(shortestCycle) } a.calculations++ c[i]++ i = 0 } else { c[i] = 0 i++ } } // finished, close the channel and set state close(updates) a.running = false } func (a *BruteForce) worker() { startTime := time.Now() ticker := time.NewTicker(time.Second) defer ticker.Stop() for a.running { <-ticker.C cps := float64(a.calculations) / time.Since(startTime).Seconds() log.Printf("calculations per second: %d", int64(cps)) } } func (a BruteForce) String() string { return "Bruteforce" } <file_sep>/webui/src/JWebsocket.ts export class JWebSocket { isConnected: boolean = false; shutdownRequested: boolean = false; private webSocket: WebSocket | null = null; constructor(public readonly url: string, public readonly timeout: number = 1, private onMessage: ((this: JWebSocket, messageEvent: MessageEvent) => any | void) | null, private onOpen: ((this: JWebSocket, openEvent: Event) => any | void) | null, private onClose: ((this: JWebSocket, closeEvent: CloseEvent) => any | void) | null, private onError: ((this: JWebSocket, errorEvent: Event) => any | void) | null) { } connect() { this.shutdownRequested = false; this.webSocket = new WebSocket(this.url); this.webSocket.onopen = this._onopen.bind(this); this.webSocket.onclose = this._onclose.bind(this); this.webSocket.onerror = this._onerror.bind(this); this.webSocket.onmessage = this._onmessage.bind(this); } shutdown() { this.shutdownRequested = true; if (this.webSocket !== null) { this.webSocket.close(); } } send(data: any) { if (this.webSocket !== null && this.isConnected) { this.webSocket.send(data); } else { console.log("[Warning] WebSocket not connected, dropped message."); } } _onopen(openEvent: Event) { this.isConnected = true; if (this.onOpen !== null) { this.onOpen(openEvent); } } _onmessage(messageEvent: MessageEvent) { if (this.onMessage !== null) { this.onMessage(messageEvent); } } _onclose(closeEvent: CloseEvent) { this.isConnected = false; if (this.onClose !== null) { this.onClose(closeEvent); } if (!this.shutdownRequested) { setTimeout(this.connect.bind(this), this.timeout); } } _onerror(errorEvent: Event) { if (this.onError !== null) { this.onError(errorEvent); } } }<file_sep>/solver.dockerfile FROM obraun/vss-protoactor-jenkins as solverbuilder COPY . /solver WORKDIR /solver RUN go build -o main main.go FROM iron/go RUN mkdir /app COPY --from=solverbuilder /solver /solver EXPOSE 8191 ENTRYPOINT ["/solver/main"] <file_sep>/problem/problem_test.go package problem import ( "math" "testing" ) const ( TestProblemDir = "../samples/" TestProblemFileGermany = "../samples/germany13.json" TestProblemFileWorkpiece = "../samples/workpiece.json" ) func TestProblemLoadDir(t *testing.T) { // try to load directory problems, err := FromDir(TestProblemDir) if err != nil { t.Fatalf("failed to load problems from dir=%s, err=%s", TestProblemDir, err) } if len(problems) != 2 { t.Fatalf("failed to load problems from dir, invalid length") } } func TestProblemFileLoadGermany(t *testing.T) { // try to load problem problem, err := FromFile(TestProblemFileGermany) if err != nil { t.Fatalf("failed to load problem from file=%s, err=%s", TestProblemFileGermany, err) } // test Info if problem.Info.Name != "Germany 13" || problem.Info.Description != "The thirteen biggest german cities by population" || problem.Info.Type != Geographic { t.Fatalf("failed to load problem Info") } // test points length if len(problem.Points) != 13 { t.Fatalf("failed to load problem-points, invalid length") } // verify points expectedPoints := []Point{ {X: 13.40514, Y: 52.5246, Name: "Berlin"}, {X: 9.994583, Y: 53.5544, Name: "Hamburg"}, {X: 11.5755, Y: 48.1374, Name: "München"}, {X: 6.95000, Y: 50.9333, Name: "Köln"}, {X: 8.68333, Y: 50.1167, Name: "Frankfurt"}, {X: 9.1770, Y: 48.7823, Name: "Stuttgart"}, {X: 6.8121, Y: 51.2205, Name: "Düsseldorf"}, {X: 7.4660, Y: 51.5149, Name: "Dortmund"}, {X: 7.0086, Y: 51.4624, Name: "Essen"}, {X: 12.3713, Y: 51.3396, Name: "Leipzig"}, {X: 8.8077, Y: 53.07516, Name: "Bremen"}, {X: 13.7500, Y: 51.0500, Name: "Dresden"}, {X: 9.7332, Y: 52.3705, Name: "Hannover"}, } for _, actualPoint := range problem.Points { contains := false for _, expectedPoint := range expectedPoints { if expectedPoint.X == actualPoint.X || expectedPoint.Y == actualPoint.Y || expectedPoint.Name == actualPoint.Name { contains = true } } if !contains { t.Fatalf("failed to load problem-points, invalid Point-details") } } } func TestProblemFileLoadWerkstueck(t *testing.T) { // try to load problem problem, err := FromFile(TestProblemFileWorkpiece) if err != nil { t.Fatalf("failed to load problem from file=%s, err=%s", TestProblemFileWorkpiece, err) } // test Info if problem.Info.Name != "Workpiece" || problem.Info.Description != "Technical drawing of a flat workpiece with prisms" || problem.Info.Type != Euclidean { t.Fatalf("failed to load problem Info") } // test points length if len(problem.Points) != 30 { t.Fatalf("failed to load problem-points, invalid length") } // verify points expectedPoints := []Point{ {X: 230, Y: 138}, {X: 195, Y: 197}, {X: 157, Y: 198}, {X: 157, Y: 298}, {X: 187, Y: 328}, {X: 157, Y: 357}, {X: 157, Y: 550}, {X: 218, Y: 611}, {X: 309, Y: 611}, {X: 357, Y: 611}, {X: 514, Y: 611}, {X: 278, Y: 555}, {X: 389, Y: 555}, {X: 513, Y: 537}, {X: 559, Y: 537}, {X: 559, Y: 138}, {X: 309, Y: 207}, {X: 350, Y: 274}, {X: 270, Y: 274}, {X: 328, Y: 432}, {X: 328, Y: 450}, {X: 308, Y: 450}, {X: 275, Y: 475}, {X: 239, Y: 441}, {X: 276, Y: 406}, {X: 309, Y: 433}, {X: 456, Y: 312}, {X: 456, Y: 235}, {X: 417, Y: 273}, {X: 494, Y: 273}, } for _, actualPoint := range problem.Points { contains := false for _, expectedPoint := range expectedPoints { if expectedPoint.X == actualPoint.X || expectedPoint.Y == actualPoint.Y || expectedPoint.Name == actualPoint.Name { contains = true } } if !contains { t.Fatalf("failed to load problem-points, invalid Point-details") } } } func TestProblemFromPointsEuclidean(t *testing.T) { points := []Point{ {X: 13.23, Y: 52.31, Name: "Berlin"}, {X: 10.0, Y: 53.33, Name: "Hamburg"}, {X: 11.34, Y: 48.8, Name: "Munich"}, {X: 6.57, Y: 50.56, Name: "Cologne"}, } info := Info{ Type: Euclidean, } cartesianProblem := Problem{Points: points, Info: info} cartesianProblem.calculateAdjacency() expectedAdj := [][]float64{ {0, 3.387226003679116, 6.886080162182256, 3.9865022262630228}, {3.387226003679116, 0, 4.408832044884447, 4.7240342928475885}, {6.886080162182256, 4.408832044884447, 0, 5.0843386983953005}, {3.9865022262630228, 4.7240342928475885, 5.0843386983953005, 0}, } for i, row := range expectedAdj { for j := range row { if math.Round(cartesianProblem.Adjacency[i][j]*100)/100 != math.Round(expectedAdj[i][j]*100)/100 { t.Fatalf("failed to load euclidean problem") } } } } func TestProblemFromPointsGeographic(t *testing.T) { points := []Point{ {X: 13.23, Y: 52.31, Name: "Berlin"}, {X: 10.0, Y: 53.33, Name: "Hamburg"}, {X: 11.34, Y: 48.8, Name: "Munich"}, {X: 6.57, Y: 50.56, Name: "Cologne"}, } info := Info{ Type: Geographic, } geographicProblem := Problem{Points: points, Info: info} geographicProblem.calculateAdjacency() expectedAdj := [][]float64{ {0, 375.94456892271836, 764.9363495938279, 435.41080570770396}, {375.94456892271836, 0, 488.19591094433196, 516.9268227447614}, {764.9363495938279, 488.19591094433196, 0, 564.5107479834015}, {435.41080570770396, 516.9268227447614, 564.5107479834015, 0}, } for i, row := range expectedAdj { for j := range row { if math.Round(geographicProblem.Adjacency[i][j]*100)/100 != math.Round(expectedAdj[i][j]*100)/100 { t.Fatalf("failed to load geographic problem: %f == %f", geographicProblem.Adjacency[i][j], expectedAdj[i][j]) } } } } <file_sep>/README.md ![Icon](icon.png "Icon") # Pathfinder Yet another solver for the [Traveling Salesman Problem](https://en.wikipedia.org/wiki/Travelling_salesman_problem). Provides simple abstractions to be easily extendable with user-defined algorithms and problem-sets. Comes with a nice webui that enables the user to watch the state of the solver. ``` NAME: Pathfinder - A solver for the travelling salesman problem USAGE: main [global options] command [command options] [arguments...] COMMANDS: help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --algorithm value name of the algorithm to use --problem value path to the problem-file to be solved --bind value address to listen for websocket-connections --help, -h show help ``` ## Features Pathfinder is written in go and makes use of languages features such as go-routines, channels and field-tags. Problems are defined as JSON-Objects and can be imported from Files: ``` { "info": { "name": "Germany 13", "description": "The thirteen biggest german cities by population", "type": "geographic" }, "image": { "path": "/home/pathfinder/samples/germany.png", "x1": 5.5, "y1": 55.1, "x2": 15.5, "y2": 47.2, "width": 1000, "height": 1186 }, "points": [ {"x": 13.40514, "y": 52.5246, "name": "Berlin"}, {"x": 9.994583, "y": 53.5544, "name": "Hamburg"}, {"x": 11.5755, "y": 48.1374, "name": "München"}, {"x": 6.95000, "y": 50.9333, "name": "Köln"}, {"x": 8.68333, "y": 50.1167, "name": "Frankfurt"}, {"x": 9.1770, "y": 48.7823, "name": "Stuttgart"}, {"x": 6.8121, "y": 51.2205, "name": "Düsseldorf"}, {"x": 7.4660, "y": 51.5149, "name": "Dortmund"}, {"x": 7.0086, "y": 51.4624, "name": "Essen"}, {"x": 12.3713, "y": 51.3396, "name": "Leipzig"}, {"x": 8.8077, "y": 53.07516, "name": "Bremen"}, {"x": 13.7500, "y": 51.0500, "name": "Dresden"}, {"x": 9.7332, "y": 52.3705, "name": "Hannover"} ] } ``` Problems can include an image for visualization of the solving-process. Check out the ```/samples```-folder. There are two types of problems: - Geographic: Distances between the points are calculated using the haversine-function - Euclidean: Distances between the points are calculated using pythagoras To add a new problem that you want to solve, simply create a file containing a JSON-Object as seen above. To run the solver, invoke it with the ```--problem```-switch which points to the newly created file. Algorithms included: - Bruteforce - Held-Karp - Minimum-Spanning-Tree Heuristic ## WebApp Pathfinder comes with a simple web-interface. To use it, specify the address to listen on for incoming connections with the```--bind```-flag. Communication between the solver and the webapp is done using a websocket, enabling for bi-directional real-time communication. The webapp is done using [TypeScript](https://www.typescriptlang.org/) and [ReactJs](https://reactjs.org/). ![WebUI](webapp_small.gif "WebUI") ## CLI The solver can be run without the webapp by omitting the ```-bind```-flag. Progress will be shown by outputting information to the console. Example usage: ``` [traveller@mchn bin]$ ./pathfinder --algorithm="bruteforce" --problem="samples/germany13.json" ``` Example output: ``` 2019/05/20 01:57:07 running as cli 2019/05/20 01:57:07 solving problemset with 13 entries using bruteforce 2019/05/20 01:58:18 Finished execution of problemset "Germany 13": Route: Berlin <-> Leipzig <-> Hannover <-> Hamburg <-> Bremen <-> Dortmund <-> Essen <-> Düsseldorf <-> Köln <-> Frankfurt <-> Stuttgart <-> München <-> Dresden Distance: 2316.814589 Time: 71.207625s ``` ## Docker You can run the application within docker: 1. Build the webapp: ```docker build -f webapp.dockerfile -t pathfinder .``` 2. Run the webapp: ```docker run -d -p 8080:80 pathfinder``` 3. Open the browser: http://localhost:8080 4. Build the solver: ```docker build -f solver.dockerfile -t solver .``` 5. Run the solver: ``` docker run -p 8091:8091 --rm --name solver solver --algorithm="bruteforce" --problem="/solver/samples/germany13.json" --bind=":8091" ``` <file_sep>/algorithm/misc.go package algorithm import ( "math" "math/bits" "sort" ) // uses the sieve of atkins to generate // a list of all primes in [2, upperBound] // returns the primes in ascending order func GetPrimesTo(upperBound int) []int { sieve := make([]bool, upperBound) for x := 1; x*x < upperBound; x++ { for y := 1; y*y < upperBound; y++ { n := (4 * x * x) + (y * y) if n <= upperBound && (n%12 == 1 || n%12 == 5) { sieve[n] = !sieve[n] } n = (3 * x * x) + (y * y) if n <= upperBound && n%12 == 7 { sieve[n] = !sieve[n] } n = (3 * x * x) - (y * y) if x > y && n <= upperBound && n%12 == 11 { sieve[n] = !sieve[n] } } } for i := 5; i*i < upperBound; i++ { if sieve[i] { for j := i * i; j < upperBound; j += i * i { sieve[j] = false } } } primes := []int{2, 3} for i := range sieve { if sieve[i] { primes = append(primes, i) } } return primes } // A set type Set []int // generates all 2^n possible subsets of the specified set // returns them in order, ascending by length and // and ascending by elements func PowerSet(s Set) []Set { cardinality := uint(math.Pow(2, float64(len(s)))) results := make([]Set, cardinality) for i := uint(0); i < cardinality; i++ { currentSet := Set{} bitMask := i for j := 0; j < bits.Len(i); j++ { if bitMask%2 == 1 { currentSet = append(currentSet, s[j]) } bitMask >>= 1 } sort.Ints(currentSet) results[i] = currentSet } compareByLengthOrElements := func(i, j int) bool { if len(results[i]) == len(results[j]) { for k := range results[i] { if results[i][k] == results[j][k] { continue } return results[i][k] < results[j][k] } } return len(results[i]) < len(results[j]) } sort.Slice(results, compareByLengthOrElements) return results } <file_sep>/web/messages.go package web import "leistungsnachweis-graphiker/problem" const ( PostImage = "PostImage" Coordinates = "Coordinates" Status = "Status" ) type Message struct { Type string `json:"type"` Data interface{} `json:"data"` } type ImageMessageData struct { Image string `json:"image"` } type CoordinatesMessageData struct { Coordinates []int `json:"coordinates"` } type StatusMessageData struct { Status problem.Status `json:"status"` }
cff92dd71d0e2f7ac4a0876aef5cfc3e07e979f3
[ "Markdown", "Go Module", "TypeScript", "Go", "Dockerfile" ]
20
Go
jjxxs/Pathfinder
ac27b610cebdf38471336ebab305bf2d781f58f7
1bd2dabb0a97c32b80e4b4b0f044e07d2b618700
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Text; using WebChatApp.Models.RelationShip; namespace WebChatApp.Models.Entities { public class ChatEntity : BaseEntity { public int? UserCreatorId { get; set; } public int Type { get; set; } public UserEntity UserCreator { get; set; } public List<UserChat> Users { get; set; } public List<MessageEntity> Messages { get; set; } } } <file_sep>using System; using Microsoft.EntityFrameworkCore.Migrations; namespace WebChatApp.Data.Migrations { public partial class Init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AccessRules", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AccessRules", x => x.Id); }); migrationBuilder.CreateTable( name: "Roles", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Roles", x => x.Id); }); migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), FirstName = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true), LastName = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true), BirthDate = table.Column<DateTime>(type: "datetime2", nullable: false), Login = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true), Password = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true), IsBlocked = table.Column<bool>(type: "bit", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); }); migrationBuilder.CreateTable( name: "RoleAccessRules", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), RoleId = table.Column<int>(type: "int", nullable: false), AccessRuleId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_RoleAccessRules", x => x.Id); table.ForeignKey( name: "FK_RoleAccessRules_AccessRules_AccessRuleId", column: x => x.AccessRuleId, principalTable: "AccessRules", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_RoleAccessRules_Roles_RoleId", column: x => x.RoleId, principalTable: "Roles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Chats", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), UserCreatorId = table.Column<int>(type: "int", nullable: true), Type = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Chats", x => x.Id); table.ForeignKey( name: "FK_Chats_Users_UserCreatorId", column: x => x.UserCreatorId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.SetNull); }); migrationBuilder.CreateTable( name: "UserRoles", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), UserId = table.Column<int>(type: "int", nullable: false), RoleId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_UserRoles", x => x.Id); table.ForeignKey( name: "FK_UserRoles_Roles_RoleId", column: x => x.RoleId, principalTable: "Roles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_UserRoles_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Messages", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Text = table.Column<string>(type: "nvarchar(max)", nullable: true), ChatId = table.Column<int>(type: "int", nullable: false), UserCreatorId = table.Column<int>(type: "int", nullable: false), IsDeleted = table.Column<bool>(type: "bit", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Messages", x => x.Id); table.ForeignKey( name: "FK_Messages_Chats_ChatId", column: x => x.ChatId, principalTable: "Chats", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Messages_Users_UserCreatorId", column: x => x.UserCreatorId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "UserChats", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), ChatId = table.Column<int>(type: "int", nullable: false), UserId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_UserChats", x => x.Id); table.ForeignKey( name: "FK_UserChats_Chats_ChatId", column: x => x.ChatId, principalTable: "Chats", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_UserChats_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Chats_UserCreatorId", table: "Chats", column: "UserCreatorId"); migrationBuilder.CreateIndex( name: "IX_Messages_ChatId", table: "Messages", column: "ChatId"); migrationBuilder.CreateIndex( name: "IX_Messages_UserCreatorId", table: "Messages", column: "UserCreatorId"); migrationBuilder.CreateIndex( name: "IX_RoleAccessRules_AccessRuleId", table: "RoleAccessRules", column: "AccessRuleId"); migrationBuilder.CreateIndex( name: "IX_RoleAccessRules_RoleId", table: "RoleAccessRules", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_UserChats_ChatId", table: "UserChats", column: "ChatId"); migrationBuilder.CreateIndex( name: "IX_UserChats_UserId", table: "UserChats", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_UserRoles_RoleId", table: "UserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_UserRoles_UserId", table: "UserRoles", column: "UserId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Messages"); migrationBuilder.DropTable( name: "RoleAccessRules"); migrationBuilder.DropTable( name: "UserChats"); migrationBuilder.DropTable( name: "UserRoles"); migrationBuilder.DropTable( name: "AccessRules"); migrationBuilder.DropTable( name: "Chats"); migrationBuilder.DropTable( name: "Roles"); migrationBuilder.DropTable( name: "Users"); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace WebChatApp1._0.Models.InputModels { public class UpdateUserInputDto { [Required] [StringLength(50)] public string FirstName { get; set; } [Required] [StringLength(50)] public string LastName { get; set; } [Required] [StringLength(50, MinimumLength = 6)] public string Login { get; set; } } } <file_sep>using System; using WebChatApp.Models.Entities; using WebChatApp1._0.Models.InputModels; namespace WebChatApp.ServicesApp { public interface IChatService { public ChatEntity GetChatById(int id); public int AddChat(ChatInputDto chatDto); public int UpdateChat(ChatEntity chatDto); public int DeleteChat(int id); } } <file_sep>using Microsoft.EntityFrameworkCore; using WebChatApp.Models.Entities; using WebChatApp.Models.RelationShip; namespace WebChatApp.Data { public class ApplicationContext : DbContext { public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options) { } public DbSet<UserEntity> Users { get; set; } public DbSet<RoleEntity> Roles { get; set; } public DbSet<AccessRuleEntity> AccessRules { get; set; } public DbSet<ChatEntity> Chats { get; set; } public DbSet<MessageEntity> Messages { get; set; } public DbSet<RoleAccessRule> RoleAccessRules { get; set; } public DbSet<UserChat> UserChats { get; set; } public DbSet<UserRole> UserRoles { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<RoleAccessRule>().ToTable("RoleAccessRules"); modelBuilder.Entity<UserRole>().ToTable("UserRoles"); modelBuilder.Entity<UserChat>().ToTable("UserChats"); modelBuilder.Entity<MessageEntity>().HasOne(x => x.UserCreator) .WithMany(x => x.Messages) .HasForeignKey(x => x.UserCreatorId) .HasPrincipalKey(x => x.Id) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<ChatEntity>().HasOne(x => x.UserCreator) .WithMany() .HasForeignKey(x => x.UserCreatorId) .HasPrincipalKey(x => x.Id) .OnDelete(DeleteBehavior.SetNull); modelBuilder.Entity<UserChat>().HasOne(x => x.Chat) .WithMany(x=> x.Users) .HasForeignKey(x => x.ChatId) .HasPrincipalKey(x => x.Id) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<UserChat>().HasOne(x => x.User) .WithMany(x => x.Chats) .HasForeignKey(x => x.UserId) .HasPrincipalKey(x => x.Id) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<RoleAccessRule>().HasOne(x => x.AccessRule) .WithMany(x => x.Roles) .HasForeignKey(x => x.AccessRuleId) .HasPrincipalKey(x => x.Id) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<RoleAccessRule>().HasOne(x => x.Role) .WithMany(x => x.AccessRules) .HasForeignKey(x => x.RoleId) .HasPrincipalKey(x => x.Id) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<UserRole>().HasOne(x => x.User) .WithMany(x => x.Roles) .HasForeignKey(x => x.UserId) .HasPrincipalKey(x => x.Id) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<UserRole>().HasOne(x => x.Role) .WithMany(x=> x.Users) .HasForeignKey(x => x.RoleId) .HasPrincipalKey(x => x.Id) .OnDelete(DeleteBehavior.Cascade); } } } <file_sep>using WebChatApp.Models.Entities; namespace WebChatApp.ServicesApp { public interface IUserService { public UserEntity GetUserById(int id); public int UpdateUser(int id, UserEntity userDto); public int AddUser(UserEntity userDto); public int DeleteUser(int id); public UserEntity UpdateUserLogin(string login, int userId); } } <file_sep>using System.Collections.Generic; using WebChatApp.Models.Entities; using WebChatApp1._0.Models.InputModels; using WebChatApp1._0.Models.OutputModels; namespace WebChatApp.ServicesApp { public interface IMessageService { public int AddMessage(MessageInputDto messageDto); public int DeleteMessage(int id); public List<MessageOutputDto> GetMaterialsByGroupId(int id); } } <file_sep>using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebChatApp.Data; using WebChatApp.ServicesApp; namespace WebChatApp1._0.Config { public static class ServicesConfig { public static void RegistrateServicesConfig(this IServiceCollection services) { //services.AddScoped<IUserService, UserService>(); //services.AddScoped<IMessageService, MessageService>(); //services.AddScoped<IChatService, ChatService>(); ////services.AddScoped<IAuthenticationService, AuthenticationService>(); //services.AddScoped<IUserRepository, UserRepository>(); //services.AddScoped<IMessageRepository, MessageRepository>(); //services.AddScoped<IChatRepository, ChatRepository>(); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace WebChatApp.Models.Models.InputModels { public class AuthenticationInputDto { public string Login { get; set; } public string Password { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using WebChatApp.Models.Entities; namespace WebChatApp.Models.RelationShip { public class UserChat : BaseEntity { public int ChatId { get; set; } public int UserId { get; set; } public ChatEntity Chat { get; set; } public UserEntity User { get; set; } } } <file_sep>using System.Collections.Generic; using WebChatApp.Models.RelationShip; namespace WebChatApp.Models.Entities { public class RoleEntity : BaseEntity { public string Name { get; set; } public List<UserRole> Users { get; set; } public List<RoleAccessRule> AccessRules { get; set; } } } <file_sep>using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using WebChatApp.Models.Entities; using WebChatApp.ServicesApp; using WebChatApp1._0.Models.InputModels; using WebChatApp1._0.Models.OutputModels; namespace WebChatApp1._0.Controllers { // https://localhost:44365/api/chat/ [ApiController] [Route("api/[controller]")] //[Authorize] public class ChatController : ControllerBase { private IChatService _service; private IMapper _mapper; public ChatController(IChatService chatService, IMapper mapper) { _service = chatService; _mapper = mapper; } /// <summary> /// Creates Chat /// </summary> /// <param name="chat"> is used to get all the information about new chat that is necessary to create it</param> /// <returns>Returns the ChatOutputModel</returns> // https://localhost:/api/chat/ [ProducesResponseType(typeof(ChatOutputDto), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status409Conflict)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [HttpPost] //[Authorize] public ActionResult<int> AddNewChat([FromBody] ChatInputDto chat) { var addedChatId = _service.AddChat(chat); //var result = _mapper.Map<ChatOutputDto>(_service.GetChatById(addedChatId)); //в сервисы убрать //return Ok(result); return Ok(addedChatId); } // можно сделать 3 контроллера на создание комнат. 3 вида комнат, актоматически заполнять поле Тип Чата. // убрать id из ассациативнаых таблиц. Добавить таблицу блок позователей. С датой начала блока и временем блока. Chek is bloked user // можно выгнать пользователя по DateTime(MAX) /// <summary> /// Rename Chat /// </summary> /// <param name="chat"> is used to rename chat </param> /// <returns>Returns the ChatOutputModel</returns> /// https://localhost:/api/chat/ [ProducesResponseType(typeof(ChatOutputDto), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status409Conflict)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [HttpPut("id")] //[Authorize] public ActionResult<ChatOutputDto> UpdateChatName(int id, [FromBody] ChatInputDto chat) { if (_service.GetChatById(id) == null) { return NotFound("Error. Chat not Found"); } //var chatDto = _mapper.Map<Chat>(chat); //_service.UpdateChat(chatDto); //var result = _mapper.Map<ChatOutputDto>(_service.GetChatById(id)); return Ok(); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using WebChatApp.Models.Entities; namespace WebChatApp.Models.RelationShip { public class RoleAccessRule : BaseEntity { public int RoleId { get; set; } public int AccessRuleId { get; set; } public RoleEntity Role { get; set; } public AccessRuleEntity AccessRule { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using WebChatApp.Models; using WebChatApp.Models.Entities; using WebChatApp.Models.Models; namespace WebChatApp.Services { public class AuthenticationService : IAuthenticationService { public AuthResponse GenerateToken(User user) { return new AuthResponse(); } public User GetAuthentificatedUser(string login) { return new User(); } } } <file_sep>using AutoMapper; using System; using System.Collections.Generic; using System.Text; using WebChatApp.Data; using WebChatApp.Models.Entities; using WebChatApp1._0.Models.InputModels; using WebChatApp1._0.Models.OutputModels; namespace WebChatApp.ServicesApp { public class MessageService //: IMessageService { //private IMessageRepository _messageRepository; //private IMapper _mapper; //public MessageService(IMessageRepository messageRepository, IMapper mapper) //{ // _messageRepository = messageRepository; // _mapper = mapper; //} //public int AddMessage(MessageInputDto messageInputDto) //{ // var messageDto = _mapper.Map<MessageEntity>(messageInputDto); // return _messageRepository.AddMessage(messageDto); //} //public int DeleteMessage(int id) //{ // return _messageRepository.DeleteMessage(id); //} //public List<MessageOutputDto> GetMaterialsByGroupId(int id) //{ // var messages = _messageRepository.GetMaterialsByGroupId(id); // return null; //_mapper.Map<List<MaterialOutputModel>>(messages); //} } } <file_sep>using System; using System.Collections.Generic; using System.Text; using WebChatApp.Data; using WebChatApp.Models; namespace WebChatApp.Services { public class ChatService : IChatService { private IChatRepository _chatRepository; public ChatService(IChatRepository chatRepository) { _chatRepository = chatRepository; } public Chat GetChatById(int id) { var dto = _chatRepository.GetChatById(id); return dto; } public int AddChat(Chat chatDto) { return _chatRepository.AddChat(chatDto); } public int UpdateChat(Chat chatDto) { return _chatRepository.UpdateChat(chatDto); } public int DeleteChat(int id) { return _chatRepository.DeleteChat(id); } } } <file_sep>using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebChatApp.Models.Entities; using WebChatApp1._0.Models.InputModels; using WebChatApp1._0.Models.OutputModels; namespace WebChatApp1._0 { public class AutomapperConfig : Profile { private const string _dateFormat = "dd.MM.yyyy"; private const string _dateFormatWithTime = "dd.MM.yyyy H:mm:ss"; public AutomapperConfig() { CreateMap<UserEntity, UserOutputDto>(); CreateMap<ChatEntity, ChatOutputDto>(); CreateMap<MessageEntity, MessageOutputDto>(); CreateMap<UserInputDto, UserEntity>(); CreateMap<ChatInputDto, ChatEntity>(); CreateMap<MessageInputDto, MessageEntity>(); } } } <file_sep>using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using WebChatApp.Data; using WebChatApp.Models.Entities; using WebChatApp.ServicesApp; using WebChatApp1._0.Models.InputModels; using WebChatApp1._0.Models.OutputModels; namespace WebChatApp1._0.Controllers { [ApiController] [Route("api/[controller]")] //[Authorize] public class MessageController : ControllerBase { private IMessageService _service; private IMapper _mapper; public MessageController(IMessageService messageService, IMapper mapper) { _service = messageService; _mapper = mapper; } /// <summary> /// Create new message /// </summary> /// <param name="messageInputModel">Model object of message to be created</param> /// <returns>Return OutputModel of created attachment</returns> // https://localhost:/api/chat/message [ProducesResponseType(typeof(MessageOutputDto), StatusCodes.Status200OK)] [HttpPost] //[Authorize] public ActionResult<int> AddMessage([FromBody] MessageInputDto messageInputDto) { var newEntityId = _service.AddMessage(messageInputDto); //var newMessageDto = _service.GetMessageById(newEntityId); //var result = _mapper.Map<MessageOutputDto>(newMessageDto); return Ok(newEntityId); } /// <summary> /// Delete Message(by Id) /// </summary> /// <param name="id">Id of the message to be deleted</param> /// <returns>Return deleted MessageOutputModel</returns> // https://localhost:/api/chat/../message/ [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status204NoContent)] [HttpDelete("{id}")] //[Authorize(Roles = "Администратор, Модератор")] public ActionResult DeleteMessage(int id) { //if (_service.GetMessageById(id) is null) // return NotFound($"Message {id} not found"); //_service.DeleteMessageById(id); return NoContent(); } // https://localhost:/api/message/by-chat/2 /// <summary>Get all message related to chat</summary> /// <param name="id">Id of chat, which chat is needed</param> /// <returns>List of message to chat</returns> [ProducesResponseType(typeof(List<MessageOutputDto>), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [HttpGet("by-chat/{id}")] //[Authorize] public ActionResult<List<MessageOutputDto>> GetMessagesByChatId(int id) { //if (_serviceGroup.GetChatById(id) is null) // return NotFound($"Chat {id} not found"); var listMessage = _service.GetMaterialsByGroupId(id); return Ok(listMessage); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using WebChatApp.Models; using WebChatApp.Models.Entities; namespace WebChatApp.Services { public interface IChatService { public Chat GetChatById(int id); public int AddChat(Chat chatDto); public int UpdateChat(Chat chatDto); public int DeleteChat(int id); } } <file_sep>using System; using WebChatApp.Data; using WebChatApp.Models; using WebChatApp.Models.Entities; namespace WebChatApp.Services { public class UserService : IUserService { private IUserRepository _userRepository; public UserService(IUserRepository userRepository) { _userRepository = userRepository; } public User GetUserById(int id) { return _userRepository.GetUserById(id); } public int UpdateUser(int id, User userDto) { userDto.Id = id; return _userRepository.UpdateUser(userDto); } public int AddUser(User userDto) { //userDto.Password = new SecurityService().GetHash(userDto.Password); var result = _userRepository.AddUser(userDto); // if (userDto.Roles != null && userDto.Roles.Count > 0) // { // foreach (var role in userDto.Roles) // { // _userRepository.AddRoleToUser(result, (int)role); // } // } return result; } public int DeleteUser(int id) { //bool isDeleted = true; return _userRepository.DeleteUser(id); } public User UpdateUserLogin(string login, int userId) { var userDto = GetUserById(userId); userDto.Login = login; int updateUserId=_userRepository.UpdateUser(userDto); return GetUserById(updateUserId); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using WebChatApp.Models; using WebChatApp.Models.Entities; namespace WebChatApp.Services { public interface IUserService { public User GetUserById(int id); public int UpdateUser(int id, User userDto); public int AddUser(User userDto); public int DeleteUser(int id); public User UpdateUserLogin(string login, int userId); } } <file_sep> using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using WebChatApp.Data; using WebChatApp.Models.Models; using WebChatApp.Models.Models.InputModels; namespace WebChatApp1._0.Controllers { [Route("api/[controller]")] [ApiController] public class AuthenticationController : ControllerBase { public AuthenticationController() { } [HttpPost] [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(string), StatusCodes.Status404NotFound)] public ActionResult<AuthResponse> Authentificate([FromBody] AuthenticationInputDto login) { //var user = _service.GetAuthentificatedUser(login.Login); //if (user != null && _securityService.VerifyHashAndPassword(user.Password, login.Password)) //{ // var token = _service.GenerateToken(user); // return Ok(token); //} return NotFound("Wrong credentials"); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using WebChatApp.Models.RelationShip; namespace WebChatApp.Models.Entities { public class UserEntity : BaseEntity { [StringLength(50)] public string FirstName { get; set; } [StringLength(50)] public string LastName { get; set; } public DateTime BirthDate { get; set; } [StringLength(50)] public string Login { get; set; } [StringLength(50)] public string Password { get; set; } public bool IsBlocked { get; set; } public List<UserRole> Roles { get; set; } public List<UserChat> Chats { get; set; } public List<MessageEntity> Messages { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using WebChatApp.Models.Entities; namespace WebChatApp.Models.Models { public class AuthResponse { public string Token { get; set; } public string UserName { get; set; } public List<RoleEntity> Roles { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using WebChatApp.Data; using WebChatApp.Models.Entities; namespace WebChatApp.ServicesApp { public class UserService //: IUserService { //private IUserRepository _userRepository; //public UserService(IUserRepository userRepository) //{ // _userRepository = userRepository; //} //public UserEntity GetUserById(int id) //{ // return _userRepository.GetUserById(id); //} //public int UpdateUser(int id, UserEntity userDto) //{ // userDto.Id = id; // return _userRepository.UpdateUser(userDto); //} //public int AddUser(UserEntity userDto) //{ // var result = _userRepository.AddUser(userDto); // return result; //} //public int DeleteUser(int id) //{ // //bool isDeleted = true; // return _userRepository.DeleteUser(id); //} //public UserEntity UpdateUserLogin(string login, int userId) //{ // var userDto = GetUserById(userId); // userDto.Login = login; // int updateUserId = _userRepository.UpdateUser(userDto); // return GetUserById(updateUserId); //} } } <file_sep>using System; using System.Collections.Generic; using System.Text; using WebChatApp.Models; using WebChatApp.Models.Entities; using WebChatApp.Models.Models; namespace WebChatApp.Services { public interface IAuthenticationService { AuthResponse GenerateToken(User user); User GetAuthentificatedUser(string login); } } <file_sep>using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using WebChatApp.Data; using WebChatApp.Models; using WebChatApp.Models.Entities; using WebChatApp.ServicesApp; using WebChatApp1._0.Models.InputModels; using WebChatApp1._0.Models.OutputModels; namespace WebChatApp1._0.Controllers { [ApiController] [Route("api/[controller]")] //[Authorize] public class UserController : ControllerBase { private IUserService _service; public UserController(IUserService userService) { _service = userService; } // https://localhost:44365/api/user/42 /// <summary>Get info of user</summary> /// <param name="userId">Id of user</param> /// <returns>Info of user</returns> [ProducesResponseType(typeof(UserOutputDto), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [HttpGet("{userId}")] //[Authorize] public ActionResult<UserOutputDto> GetUser(int userId) { var user = _service.GetUserById(userId); if (user == null) { return NotFound($"User with id {userId} is not found"); } //var outputModel = _mapper.Map<UserOutputModel>(user); // //return Ok(outputModel); return Ok(); } [HttpGet("current")] //[Authorize] public ActionResult<UserOutputDto> GetCurrentUser() { var userId = Convert.ToInt32(User.FindFirst("id").Value); //var user = _service.GetUserById(userId); return Ok(); } // https://localhost:/api/user/register /// <summary>user registration</summary> /// <param name="inputModel">information about registered user</param> /// <returns>rReturn information about added user</returns> [ProducesResponseType(typeof(UserOutputDto), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status409Conflict)] [HttpPost("register")] //[Authorize(Roles = "Администратор, Менеджер")] public ActionResult<UserOutputDto> Register([FromBody] UserEntity inputModel) { //var userDto = _mapper.Map<User>(inputModel); var id = _service.AddUser(inputModel); // var user = _service.GetUserById(id); //var outputModel = _mapper.Map<UserOutputDto>(); return Ok(); } // [HttpPost("login")] // public ActionResult Login([FromBody] UserInputDto inputModel) // { // // } // // [HttpPost("logout")] // public ActionResult Logout() // { // // } // https://localhost:/api/user/42 /// <summary>Update information about user</summary> /// <param name="userId">Id of user</param> /// /// <param name="inputModel">Nonupdated info about user </param> /// <returns>Updated info about user</returns> [ProducesResponseType(typeof(UserOutputDto), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status409Conflict)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [HttpPut("{userId}")] [Authorize(Roles = "Администратор, Пользователь")] public ActionResult<UserOutputDto> UpdateUserInfo(int userId, [FromBody] UpdateUserInputDto inputModel) { // var user = _service.GetUserById(userId); // if (user == null) // { // return NotFound($"User with id {userId} is not found"); // } // if (User.IsInRole("Администратор") // || (User.IsInRole("Пользователь") && user.Roles.Contains(Core.Enums.Role.User))) // { // var userDto = _mapper.Map<User>(inputModel); // _service.UpdateUser(userId, userDto); // var outputModel = _mapper.Map<UserOutputDto>(_service.GetUserById(userId)); // return Ok(outputModel); // } /// return Forbid("Updated user is not ChatUser"); // } } } <file_sep>using AutoMapper; using System; using System.Collections.Generic; using System.Text; using WebChatApp.Data; using WebChatApp.Models.Entities; using WebChatApp1._0.Models.InputModels; namespace WebChatApp.ServicesApp { public class ChatService // : IChatService { private IMapper _mapper; public ChatService(IMapper mapper) { _mapper = mapper; } //public ChatEntity GetChatById(int id) //{ // var dto = _chatRepository.GetChatById(id); // return dto; //} //public int AddChat(ChatInputDto chatDto) //{ // var chatModel = _mapper.Map<ChatEntity>(chatDto); // return _chatRepository.AddChat(chatModel); //} //public int UpdateChat(ChatEntity chatDto) //{ // return _chatRepository.UpdateChat(chatDto); //} //public int DeleteChat(int id) //{ // return _chatRepository.DeleteChat(id); //} } } <file_sep>using System; using System.Collections.Generic; using System.Text; using WebChatApp.Data; using WebChatApp.Models; using WebChatApp.Models.Entities; namespace WebChatApp.Services { public class MessageService : IMessageService { private IMessageRepository _messageRepository; public MessageService(IMessageRepository messageRepository) { _messageRepository = messageRepository; } public int AddMessage(Message messageDto) { return _messageRepository.AddMessage(messageDto); } public int DeleteMessage(int id) { return _messageRepository.DeleteMessage(id); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace WebChatApp.Models.Entities { public class MessageEntity : BaseEntity { public string Text { get; set; } public int ChatId { get; set; } public int UserCreatorId { get; set; } public bool IsDeleted { get; set; } public UserEntity UserCreator { get; set; } public ChatEntity Chat { get; set; } } } <file_sep>using System.Collections.Generic; using WebChatApp.Models.RelationShip; namespace WebChatApp.Models.Entities { public class AccessRuleEntity : BaseEntity { public string Name { get; set; } public List<RoleAccessRule> Roles { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace WebChatApp1._0.Models.InputModels { public class MessageInputDto { [Required] [StringLength(1000)] public string Text { get; set; } [Required] [Range(1, int.MaxValue)] public int ChatId { get; set; } [Required] [Range(1, int.MaxValue)] public int UserCreatorId { get; set; } [Required] public bool isDeleted { get; set; } } }
1c1913775b47cbba8cd76d71b37570dbf02fda16
[ "C#" ]
32
C#
frendorDM/ChatProject
d69ee9c8354e054bd30a0f72be10c1ec587dc51d
687c45cd3d3e34ce35489b3e1d29293c87672be8
refs/heads/master
<file_sep>class CreateBeneficiaries < ActiveRecord::Migration def change create_table :beneficiaries do |t| t.string :name t.string :address t.integer :company_category_id t.string :details t.strign :contacts t.timestamps end end end <file_sep>class Payment < ActiveRecord::Base attr_accessible :beneficiary_id, :comment, :currency, :date, :delay, :item, :payer_id, :state, :summ belongs_to :Beneficiary belongs_to :Payer end <file_sep>class CreatePayments < ActiveRecord::Migration def change create_table :payments do |t| t.integer :payer_id t.integer :beneficiary_id t.date :date t.date :delay t.float :summ t.string :currency t.text :comment t.string :item t.boolean :state t.timestamps end end end <file_sep>class CompanyCategory < ActiveRecord::Base attr_accessible :name has_many :Beneficiary end <file_sep>class Beneficiary < ActiveRecord::Base attr_accessible :address, :company_category_id, :contacts, :details, :name belongs_to :company_category has_many :Payments end <file_sep>class User < ActiveRecord::Base attr_accessible :email, :login, :name, :password, :role_id belongs_to :role end
8dea18c9779214ecf9c22c9c26ee10b548829802
[ "Ruby" ]
6
Ruby
threem/payments
b15f8d7c37138fe330883b966d55a71576613ec7
81d0e2cc0698cc9a0d9807cf7972c84ff0624712
refs/heads/master
<repo_name>garydivine/oregon-trail<file_sep>/oregon-trail.ts (function(){ /* * Interfaces */ //interface describing what attributes and methods a traveler should have interface ITraveler { food: number; name: string; isHealthy: boolean; hunt(): number; eat(): boolean; } //interface describing attributes and methods a wagon should have interface IWagon{ capacity: number; passengerArray: Traveler[]; addPassenger(traveler: Traveler): string; isQuarantined(): boolean; getFood(): number; } /* * Classes */ //The traveler class that implements the ITraveler interface //This is currently in violation of its contract with the interface. //Create the code required to satisfy the contract with the interface class Traveler implements ITraveler { food: number; name: string; isHealthy: boolean; constructor(food: number, name: string, isHealthy: boolean ) { this.food = food; this.name = name; this.isHealthy = isHealthy; } //when implemented, There should be 50% chance to increase the traveler's food by 100. //return the travelers new food value hunt(): number { if (Math.random() > 0.5) { this.food = this.food + 100 } return this.food; } //when implemented, we should check to see if the traveler has a food supply of 20 //If they do then we should consume 20 of the available food supply //If they don't have 20 food then we should change isHealthy to false //return the travelers health after attempting to eat eat(): boolean { if (this.food >= 20) { this.food = this.food - 20; } else { this.isHealthy = false; } return this.isHealthy; } } //The wagon class that implements the IWagon interface //This is currently in violation of its contract with the interface. //Create the code required to satisfy the contract with the interface class Wagon implements IWagon { capacity: number; passengerArray: Traveler[]; constructor (capacity: number, passengerArray: Traveler[]) { this.capacity = capacity; this.passengerArray = passengerArray; } //when implemented, we should add the traveler to the wagon if the capacity permits //this function should return the string "added" on success and "sorry" on failure addPassenger(traveler: Traveler): string { if (this.capacity != 0) { this.passengerArray.push(traveler); this.capacity = this.capacity - 1; return "added"; } else { return "sorry"; } } //this should return true if there is at least one unhealthy person in the wagon //if everyone is healthy false should be returned isQuarantined(): boolean { let quarantined: boolean = false; for (let passenger of this.passengerArray) { if (passenger.isHealthy == false) { quarantined = true; } } return quarantined; } //Return the total amount of food among all passengers of the wagon. getFood(): number { let totalFoodAmount: number = 0; for (let passenger of this.passengerArray) { totalFoodAmount = totalFoodAmount + passenger.food; } return totalFoodAmount; } } /* * Play the game * * X Create 5 healthy travelers object with a random amount of food between 0 and 100 (inclusive) * * X Create wagon with an empty passenger list and a capacity of 4. * * X Make 3 of 5 the travelers eat by calling their eat methods * * X Make the remaining 2 travelers hunt * * X Create an array of your travelers, loop over the array of travelers and give each traveler a 50% chance * of attempting to be being added to the wagon using the wagons addPassenger method. * * X Run the isQuarantined method for the wagon * * X Run the getFood method for the wagon * * X the return values of all the methods should be displayed in the console using console.log() * the console.log statements should not live inside any methods on the objects * */ let traveler1 = new Traveler(10, "Gary", true); let traveler2 = new Traveler(50, "Katie", true); let traveler3 = new Traveler(40, "John", true); let traveler4 = new Traveler(100, "Greg", true); let traveler5 = new Traveler(30, "Megan", true); let wagon = new Wagon(4, []); console.log("Result of first three travelers eating:"); console.log(traveler1.eat()); console.log(traveler2.eat()); console.log(traveler3.eat()); console.log(" "); console.log("Result of last two travelers hunting:"); console.log(traveler4.hunt()); console.log(traveler5.hunt()); console.log(" "); let travelers = new Array<Traveler>(); travelers.push(traveler1); travelers.push(traveler2); travelers.push(traveler3); travelers.push(traveler4); travelers.push(traveler5); console.log("50% chance of being added to wagon:"); for (let travler of travelers) { console.log(`${travler.name} tries to board the wagon`); if (Math.random() > 0.5) { console.log("Verdict:") console.log(wagon.addPassenger(travler)); } else { console.log(`${travler.name} not permitted to board`); } } console.log(" "); console.log("Is the wagon quarantined?") console.log(wagon.isQuarantined()); console.log(" "); console.log("Total amount of food among all passengers of the wagon:") console.log(wagon.getFood()); })(); <file_sep>/oregon-trail.js (function () { /* * Interfaces */ /* * Classes */ //The traveler class that implements the ITraveler interface //This is currently in violation of its contract with the interface. //Create the code required to satisfy the contract with the interface var Traveler = /** @class */ (function () { function Traveler(food, name, isHealthy) { this.food = food; this.name = name; this.isHealthy = isHealthy; } //when implemented, There should be 50% chance to increase the traveler's food by 100. //return the travelers new food value Traveler.prototype.hunt = function () { if (Math.random() > 0.5) { this.food = this.food + 100; } return this.food; }; //when implemented, we should check to see if the traveler has a food supply of 20 //If they do then we should consume 20 of the available food supply //If they don't have 20 food then we should change isHealthy to false //return the travelers health after attempting to eat Traveler.prototype.eat = function () { if (this.food >= 20) { this.food = this.food - 20; } else { this.isHealthy = false; } return this.isHealthy; }; return Traveler; }()); //The wagon class that implements the IWagon interface //This is currently in violation of its contract with the interface. //Create the code required to satisfy the contract with the interface var Wagon = /** @class */ (function () { function Wagon(capacity, passengerArray) { this.capacity = capacity; this.passengerArray = passengerArray; } //when implemented, we should add the traveler to the wagon if the capacity permits //this function should return the string "added" on success and "sorry" on failure Wagon.prototype.addPassenger = function (traveler) { if (this.capacity != 0) { this.passengerArray.push(traveler); this.capacity = this.capacity - 1; return "added"; } else { return "sorry"; } }; //this should return true if there is at least one unhealthy person in the wagon //if everyone is healthy false should be returned Wagon.prototype.isQuarantined = function () { var quarantined = false; for (var _i = 0, _a = this.passengerArray; _i < _a.length; _i++) { var passenger = _a[_i]; if (passenger.isHealthy == false) { quarantined = true; } } return quarantined; }; //Return the total amount of food among all passengers of the wagon. Wagon.prototype.getFood = function () { var totalFoodAmount = 0; for (var _i = 0, _a = this.passengerArray; _i < _a.length; _i++) { var passenger = _a[_i]; totalFoodAmount = totalFoodAmount + passenger.food; } return totalFoodAmount; }; return Wagon; }()); /* * Play the game * * X Create 5 healthy travelers object with a random amount of food between 0 and 100 (inclusive) * * X Create wagon with an empty passenger list and a capacity of 4. * * X Make 3 of 5 the travelers eat by calling their eat methods * * X Make the remaining 2 travelers hunt * * X Create an array of your travelers, loop over the array of travelers and give each traveler a 50% chance * of attempting to be being added to the wagon using the wagons addPassenger method. * * X Run the isQuarantined method for the wagon * * X Run the getFood method for the wagon * * X the return values of all the methods should be displayed in the console using console.log() * the console.log statements should not live inside any methods on the objects * */ var traveler1 = new Traveler(10, "Gary", true); var traveler2 = new Traveler(50, "Katie", true); var traveler3 = new Traveler(40, "John", true); var traveler4 = new Traveler(100, "Greg", true); var traveler5 = new Traveler(30, "Megan", true); var wagon = new Wagon(4, []); console.log("Result of first three travelers eating:"); console.log(traveler1.eat()); console.log(traveler2.eat()); console.log(traveler3.eat()); console.log(" "); console.log("Result of last two travelers hunting:"); console.log(traveler4.hunt()); console.log(traveler5.hunt()); console.log(" "); var travelers = new Array(); travelers.push(traveler1); travelers.push(traveler2); travelers.push(traveler3); travelers.push(traveler4); travelers.push(traveler5); console.log("50% chance of being added to wagon:"); for (var _i = 0, travelers_1 = travelers; _i < travelers_1.length; _i++) { var travler = travelers_1[_i]; console.log(travler.name + " tries to board the wagon"); if (Math.random() > 0.5) { console.log("Verdict:"); console.log(wagon.addPassenger(travler)); } else { console.log(travler.name + " not permitted to board"); } } console.log(" "); console.log("Is the wagon quarantined?"); console.log(wagon.isQuarantined()); console.log(" "); console.log("Total amount of food among all passengers of the wagon:"); console.log(wagon.getFood()); })();
752cf5e9517aabb2995daf8abc69c818f93ecb5a
[ "JavaScript", "TypeScript" ]
2
TypeScript
garydivine/oregon-trail
e108de794ce4bfe9fc133e08e8a0c88d4fe22ffd
0d40b2f2f89ce9fa752383cdc769ee6cc0477f04
refs/heads/master
<repo_name>Garritosk8CR/101A<file_sep>/project/101A/src/store/modules/Models/Player.js export default function newPlayer (params) { return { id: 'sdsdsd', name: params.name, email: params.email, gamertag: params.gamertag, //games: params.games, platform: params.platform, rank: params.rank, division: params.division, timezone: params.timezone } } <file_sep>/project/101A/src/store/modules/Players.js import db from '@/db' import Player from './Models/Player' const state = { players: [] } const getters = { players(state) { return state.players } } const mutations = { storePlayer(state, player) { state.player = player }, storePlayers(state, players) { state.players = players } } const actions = { storePlayer({ dispatch }, playerData ) { const newPlayer = Player(playerData) db.collection('Players').add(newPlayer) .then(res => { newPlayer.id = res.id dispatch('setId', newPlayer) }) .catch(error => console.log(error)) }, fetchPlayers({ commit }) { var enlistedPlayers = [] db.collection('Players').get() .then( querySnapshot => { querySnapshot.forEach(element => { const data = { ...element.data() } data.id = element.id enlistedPlayers.push(data) }) commit('storePlayers', enlistedPlayers) }) .catch(error => console.log(error)) }, deletePlayer({commit, dispatch}, player) { db.collection('Players').where('id', '==', player.id).get() .then( querySnapshot => { querySnapshot.forEach(doc => { doc.ref.delete() dispatch('fetchPlayers') }) }) .catch(error => console.log(error)) }, updatePlayer({dispatch}, player) { db.collection('Players').where('id', '==', player.id).get() .then( querySnapshot => { querySnapshot.forEach(doc => { doc.ref.update({...player}) dispatch('fetchPlayers') }) }) }, setId({dispatch}, player) { db.collection('Players').where('gamertag', '==', player.gamertag).get() .then( querySnapshot => { querySnapshot.forEach(doc => { doc.ref.update(player) dispatch('fetchPlayers') }) }) .catch(error => console.log(error)) } } export default { state, mutations, actions, getters } <file_sep>/project/101A/src/router.js import Vue from 'vue' import Router from 'vue-router' import Store from './store/store' import MainNavbar from '../src/layout/MainNavbar' import MainFooter from '../src/layout/MainFooter' import TrainingManagement from './views/TrainingManagement.vue' import TrainingLogin from './views/Training/Login.vue' import TrainingSignup from './views/Training/Signup.vue' import TrainingDashboard from './views/Training/Dashboard.vue' import Enlisted from './views/Training/Users/Enlisted.vue' import Bct from './views/Training/BCT/BCT.vue' Vue.use(Router) export default new Router({ routes: [ { path: '/trainingmanagement', name: 'trainingmanagement', components: { default: TrainingManagement, header: MainNavbar }, props: { header: { colorOnScroll: 400, title: '101st Airborne Division Training Management', items: [ { icon: '', text: 'Sign Up', path: '/signup' }, { icon: '', text: 'Login', path: '/login' } ], toolbarColor: 'md-dark' } }, children: [ { path: '/login' , components: {default: TrainingLogin}, name: 'traininglogin' }, { path: '/signup' , component: TrainingSignup } ] }, { path: '/', component: TrainingDashboard, name: 'trainingdashboard', beforeEnter(to, from, next) { if(Store.getters.isAuthenticated) { next() } else { next('/login') } }, children: [ { path: 'enlisted' , component: Enlisted, name: 'enlisted' }, { path: 'bct' , component: Bct, name: 'bct' } ] } ], mode: 'history', scrollBehavior: to => { if (to.hash) { return { selector: to.hash } } else { return { x: 0, y: 0 } } } })
ce685a3fa154dbf5051a397d6ca6aa270c878d4d
[ "JavaScript" ]
3
JavaScript
Garritosk8CR/101A
3523f8f4af64ebd654708e4e146b347bba572063
b643e6e08c1ed70521deb39bab26453df5fd003c
refs/heads/master
<file_sep>--- home: true heroImage: /home.svg heroText: Full Stack Library tagline: 绘 Web 全栈架构师图谱,打造个人核心竞争力, 🙏🙏🙏 项目正在努力建设中,请持续关注 🙏🙏🙏 actionText: 开始修炼 → actionLink: /Js/ features: - title: 愿景 details: 主要帮助前端开发人员进阶Web全栈架构师,做到先精后广,一专多长!内容涵盖深入Vue、React、Node、小程序、微信公众号开发、React-native、Flutter、Hybrid、区块链、工程化、自动化测试、数据结构与算法等等,助你职场路上披荆斩棘。 - title: 如何成为Web全栈架构师 details: 如果你和我一样是个凡人,那么想成长为全栈架构师,只能从少到多、慢慢积累知识和经验。这里我推荐采用“先精后广,一专多长”的流程来学习。采用这种方式来学习,不光可以触类旁通、举一反三,还让我们学习得更快,而且循序渐进更符合一般人的职业生涯发展。 - title: 开源 details: 本数字图书馆旨在搜集整理互联网优质内容,系统梳理全栈开发进阶知识脉络,本着开源的原则,帮助coder掌握Web全栈主流干货技术,掌握互联网核心技术硬技能,掌握架构师成长的核心软技能。 footer: MIT Licensed | Copyright © 2019-2021 ViktorHub --- <file_sep># React框架简介 react<file_sep>const sidebarMap = [ { title: "面试专栏", dirname: "Interviews" }, { title: "JS 进阶", dirname: "Js" }, { title: "CSS 进阶", dirname: "CSS" }, { title: "Vue 专栏", dirname: "Vue" }, { title: "React 专栏", dirname: "React" }, { title: "小程序专栏", dirname: "Applets" }, { title: "微信公众号开发", dirname: "Wechat" }, { title: "Hybrid 开发专栏", dirname: "Hybrid" }, { title: "数据结构与算法", dirname: "Algorithms" }, { title: "HTTP 详解", dirname: "HTTP" }, { title: "深入学习 Node.js", dirname: "Node" }, { title: "Flutter 探索", dirname: "Flutter" }, { title: "自动化测试", dirname: "AutoText" }, { title: "Web安全", dirname: "WebSafety" }, { title: "区块链揭秘", dirname: "Blockchain" }, { title: "藏金阁", dirname: "Repository" }, ] module.exports = sidebarMap <file_sep> # 图书资料 ## JavaScript [《ECMAScript 6 入门》](http://es6.ruanyifeng.com/) [《how-javascript-works》](https://github.com/Troland/how-javascript-works) [《前端工程师手册》](https://leohxj.gitbooks.io/front-end-database/content/html-and-css-basic/index.html) ## TypeScript [《TypeScript 入门教程》](https://ts.xcatliu.com/) [《深入理解 TypeScript》](https://jkchao.github.io/typescript-book-chinese/) ## Node [《深入理解Node.js:核心思想与源码分析》](https://yjhjstz.gitbooks.io/deep-into-node/) ## CSS [《You-need-to-know-css》](https://lhammer.cn/You-need-to-know-css/#/) ## Vue [《Vue.js Cookbook》](https://cn.vuejs.org/v2/cookbook/) [《Vue.js 服务器端渲染指南》](https://ssr.vuejs.org/zh/) ## Docker [《Docker —— 从入门到实践》](https://philipzheng.gitbooks.io/docker_practice/) ## Mongodb [《mongoose中文文档》](https://mongoose.shujuwajue.com/) ## 思考类阅读 [《未来世界的幸存者》](http://survivor.ruanyifeng.com/) <file_sep># 该目录中的 Vue 组件将会被自动注册为全局组件。 <file_sep># 文章收集 ::: tip 说明 主要是用来收集汇总平时看过得一些不错的文章,方便日后查找 ::: ## 前端 [Press Enter to Submit 背后的那些事](http://david-chen-blog.logdown.com/posts/177766-how-forms-submit-when-pressing-enter) [Webnovel 国际化实践](https://juejin.im/post/5c24a09d5188252a9412fabf) [Things I Don’t Know as of 2018](https://overreacted.io/things-i-dont-know-as-of-2018/) [用webpack搭建多页面项目](https://juejin.im/post/5a0c13b3518825329314154d) [Vue 折腾记 - (14) Nuxt.js 2 正式版升级采坑以及部署姿势改动](https://juejin.im/post/5badce536fb9a05d26596a5a) [开源库架构实战——从0到1搭建属于你自己的开源库](https://juejin.im/post/5b729909e51d45662434aef0) [前端常用插件、工具类库汇总,不要重复造轮子啦!!!](https://juejin.im/post/5ba7d5dd5188255c6140cc9d) [2万5千字大厂面经 | 掘金技术征文](https://juejin.im/post/5ba34e54e51d450e5162789b) [八段代码彻底掌握 Promise](https://juejin.im/post/597724c26fb9a06bb75260e8) [让老板虎躯一震的前端技术,KPI杀手](https://juejin.im/post/5c3ff18b6fb9a04a0a5f76aa?utm_source=gold_browser_extension) [一次弄懂Event Loop(彻底解决此类面试问题)](https://juejin.im/post/5c3d8956e51d4511dc72c200?utm_source=gold_browser_extension) ## GraphQL [GraphQL 核心概念](https://segmentfault.com/a/1190000014131950) [RPC vs REST vs GraphQL](https://segmentfault.com/a/1190000013961872) [Why use GraphQL, good and bad reasons](https://honest.engineering/posts/why-use-graphql-good-and-bad-reasons) [GraphQL-前端进阶的利剑与桥梁](https://mp.weixin.qq.com/s/Gw3iOyuRr8HvOqY1GNxqqA) ## 职业发展 [一个程序员的成长之路](https://github.com/fouber/blog/issues/41) 张云龙大佬的文章,强推!!值得反复阅读。 [开发者如何在「技术+管理」的路上越走越宽?](https://zhuanlan.zhihu.com/p/36018203) [蔡志忠:努力是没有用的](https://www.yuque.com/book-academy/share/shp7tu) ## 视频 [计算机科学速成课](https://www.bilibili.com/video/av21376839) 计算机科学基础的系列视频,很不错,浅显易懂,看完这四十节课能多计算机世界有一个大概的整体认知。 ## 其它 [前端人工智能?TensorFlow.js 学会游戏通关](https://zhuanlan.zhihu.com/p/35451395) [谈谈 WebSocket ](https://halfrost.com/websocket/) [https://zhuanlan.zhihu.com/p/37171897](https://zhuanlan.zhihu.com/p/37171897) ## 小程序 [只需两步获取任何微信小程序源码](https://juejin.im/post/5b0e431f51882515497d979f?utm_source=花裤衩) 挺有意思的一篇文章 ## node [基于 node.js 的脚手架工具开发经历](https://juejin.im/post/5a31d210f265da431a43330e) ## 网络 [什么是 RPC 框架?](https://www.zhihu.com/question/25536695) [前端技术清单](https://github.com/alienzhou/frontend-tech-list) [关于 JavaScript 单线程的一些事](https://github.com/JChehe/blog/blob/master/posts/%E5%85%B3%E4%BA%8EJavaScript%E5%8D%95%E7%BA%BF%E7%A8%8B%E7%9A%84%E4%B8%80%E4%BA%9B%E4%BA%8B.md) [从零开始开发一款属于你的 Visual Studio Code 插件](https://www.microsoft.com/china/events/video_316) ## AST [平庸前端码农之蜕变 — AST](https://github.com/CodeLittlePrince/blog/issues/19) <file_sep># 静态资源目录。 <file_sep># 敬请期待。。。<file_sep># 存储 HTML 模板文件。 ## `dev.html`: 用于开发环境的 HTML 模板文件。 ## `ssr.html`: 构建时基于 Vue SSR 的 HTML 模板文件。 <file_sep><!-- Author: Viktor (<EMAIL>) config.md (c) 2021 Desc: description Created: 2021/2/1 下午8:55:36 Modified: 2021/2/1 下午8:55:37 --> <file_sep># 00.数据库篇 ## test ## MySQL 篇 ### Q1:主键 超键 候选键 外键是什么 #### 定义 **超键(super key)**: 在关系中能唯一标识元组的属性集称为关系模式的超键 **候选键(candidate key)**: 不含有多余属性的超键称为候选键。也就是在候选键中,若再删除属性,就不是键了! **主键(primary key)**: 用户选作元组标识的一个候选键程序主键 **外键(foreign key)**:如果关系模式R中属性K是其它模式的主键,那么k在模式R中称为外键。 #### 举例 比如有如下数据: | 学号 | 姓名 | 性别 | 年龄 | 系别 | 专业 |:---:|:---:|:---:|:---:|:---:|:---: |20020612 |李辉 |男 |20 |计算机 |软件开发 |20060613| 张明| 男 |18 |计算机 |软件开发 |20060614| 王小玉| 女 |19 |物理 |力学 |20060615| 李淑华| 女 |17 |生物 |动物学 |20060616| 赵静| 男 |21 |化学 |食品化学 |20060617| 赵静| 女 |20 |生物 |植物学 1. 超键 在关系中能唯一标识元组的属性集称为关系模式的超键。 于是我们从例子中可以发现 学号是标识学生实体的唯一标识。那么该元组的超键就为学号。 除此之外我们还可以把它跟其他属性组合起来,比如: (`学号`,`性别`) (`学号`,`年龄`) 这样也是超键. 2. 候选键 不含多余属性的超键为候选键。 根据例子可知,学号是一个可以唯一标识元组的唯一标识,因此学号是一个候选键,实际上,候选键是超键的子集,比如 (学号,年龄)是超键,但是它不是候选键。因为它还有了额外的属性。 3. 主键 用户选择的候选键作为该元组的唯一标识,那么它就为主键。 简单的说,例子中的元组的候选键为学号,但是我们选定他作为该元组的唯一标识,那么学号就为主键。 4. 外键 外键是相对于主键的,比如在学生记录里,主键为学号,在成绩单表中也有学号字段,因此学号为成绩单表的外键,为学生表的主键。 #### 总结 **主键为候选键的子集,候选键为超键的子集,而外键的确定是相对于主键的。** ### Q2:数据库事务的四个特性及含义 #### **参考答案**: 数据库事务transanction正确执行的四个基本要素。ACID,原子性(Atomicity)、一致性(Correspondence)、隔离性(Isolation)、持久性(Durability)。 * 原子性:整个事务中的所有操作,要么全部完成,要么全部不完成,不可能停滞在中间某个环节。事务在执行过程中发生错误,会被回滚(Rollback)到事务开始前的状态,就像这个事务从来没有执行过一样。 * 一致性:在事务开始之前和事务结束以后,数据库的完整性约束没有被破坏。 * 隔离性:隔离状态执行事务,使它们好像是系统在给定时间内执行的唯一操作。如果有两个事务,运行在相同的时间内,执行 相同的功能,事务的隔离性将确保每一事务在系统中认为只有该事务在使用系统。这种属性有时称为串行化,为了防止事务操作间的混淆,必须串行化或序列化请 求,使得在同一时间仅有一个请求用于同一数据。 * 持久性:在事务完成以后,该事务所对数据库所作的更改便持久的保存在数据库之中,并不会被回滚。 ### Q3:视图的作用,视图可以更改么? #### **参考答案**: 视图是虚拟的表,与包含数据的表不一样,视图只包含使用时动态检索数据的查询;不包含任何列或数据。使用视图可以简化复杂的sql操作,隐藏具体的细节,保护数据;视图创建后,可以使用与表相同的方式利用它们。 视图不能被索引,也不能有关联的触发器或默认值,如果视图本身内有order by 则对视图再次order by将被覆盖。 创建视图:create view XXX as XXXXXXXXXXXXXX; 对于某些视图比如未使用联结子查询分组聚集函数Distinct Union等,是可以对其更新的,对视图的更新将对基表进行更新;但是视图主要用于简化检索,保护数据,并不用于更新,而且大部分视图都不可以更新。 ### Q4:drop,delete与truncate的区别 #### **参考答案**: drop直接删掉表 truncate删除表中数据,再插入时自增长id又从1开始 delete删除表中数据,可以加where字句。 (1) DELETE语句执行删除的过程是每次从表中删除一行,并且同时将该行的删除操作作为事务记录在日志中保存以便进行进行回滚操作。TRUNCATE TABLE 则一次性地从表中删除所有的数据并不把单独的删除操作记录记入日志保存,删除行是不能恢复的。并且在删除的过程中不会激活与表有关的删除触发器。执行速度快。 (2) 表和索引所占空间。当表被TRUNCATE 后,这个表和索引所占用的空间会恢复到初始大小,而DELETE操作不会减少表或索引所占用的空间。drop语句将表所占用的空间全释放掉。 (3) 一般而言,drop > truncate > delete (4) 应用范围。TRUNCATE 只能对TABLE;DELETE可以是table和view (5) TRUNCATE 和DELETE只删除数据,而DROP则删除整个表(结构和数据)。 (6) truncate与不带where的delete :只删除数据,而不删除表的结构(定义)drop语句将删除表的结构被依赖的约束(constrain),触发器(trigger)索引(index);依赖于该表的存储过程/函数将被保留,但其状态会变为:invalid。 (7) delete语句为DML(Data Manipulation Language),这个操作会被放到 rollback segment中,事务提交后才生效。如果有相应的 tigger,执行的时候将被触发。 (8) truncate、drop是DDL(Data Define Language),操作立即生效,原数据不放到 rollback segment中,不能回滚 (9) 在没有备份情况下,谨慎使用 drop 与 truncate。要删除部分数据行采用delete且注意结合where来约束影响范围。回滚段要足够大。要删除表用drop;若想保留表而将表中数据删除,如果于事务无关,用truncate即可实现。如果和事务有关,或老师想触发trigger,还是用delete。 (10) Truncate table 表名 速度快,而且效率高,因为: truncate table 在功能上与不带 WHERE 子句的 DELETE 语句相同:二者均删除表中的全部行。但 TRUNCATE TABLE 比 DELETE 速度快,且使用的系统和事务日志资源少。DELETE 语句每次删除一行,并在事务日志中为所删除的每行记录一项。TRUNCATE TABLE 通过释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放。 (11) TRUNCATE TABLE 删除表中的所有行,但表结构及其列、约束、索引等保持不变。新行标识所用的计数值重置为该列的种子。如果想保留标识计数值,请改用 DELETE。如果要删除表定义及其数据,请使用 DROP TABLE 语句。 (12) 对于由 FOREIGN KEY 约束引用的表,不能使用 TRUNCATE TABLE,而应使用不带 WHERE 子句的 DELETE 语句。由于 TRUNCATE TABLE 不记录在日志中,所以它不能激活触发器。 ### Q5:索引的工作原理及其种类 #### **参考答案**: **数据库索引**,是数据库管理系统中一个排序的数据结构,以协助快速查询、更新数据库表中数据。索引的实现通常使用B树及其变种B+树。 在数据之外,数据库系统还维护着满足特定查找算法的数据结构,这些数据结构以某种方式引用(指向)数据,这样就可以在这些数据结构上实现高级查找算法。这种数据结构,就是索引。 为表设置索引要付出代价的:一是增加了数据库的存储空间,二是在插入和修改数据时要花费较多的时间(因为索引也要随之变动)。 <img src=http://www.2cto.com/uploadfile/Collfiles/20150416/2015041610033731.png> </img> 图展示了一种可能的索引方式。左边是数据表,一共有两列七条记录,最左边的是数据记录的物理地址(注意逻辑上相邻的记录在磁盘上也并不是一定物理相邻的)。为了加快Col2的查找,可以维护一个右边所示的二叉查找树,每个节点分别包含索引键值和一个指向对应数据记录物理地址的指针,这样就可以运用二叉查找在O(log2n)的复杂度内获取到相应数据。 创建索引可以大大提高系统的性能。 第一,通过创建唯一性索引,可以保证数据库表中每一行数据的唯一性。 第二,可以大大加快数据的检索速度,这也是创建索引的最主要的原因。 第三,可以加速表和表之间的连接,特别是在实现数据的参考完整性方面特别有意义。 第四,在使用分组和排序子句进行数据检索时,同样可以显著减少查询中分组和排序的时间。 第五,通过使用索引,可以在查询的过程中,使用优化隐藏器,提高系统的性能。 也许会有人要问:增加索引有如此多的优点,为什么不对表中的每一个列创建一个索引呢?因为,增加索引也有许多不利的方面。 第一,创建索引和维护索引要耗费时间,这种时间随着数据量的增加而增加。 第二,索引需要占物理空间,除了数据表占数据空间之外,每一个索引还要占一定的物理空间,如果要建立聚簇索引,那么需要的空间就会更大。 第三,当对表中的数据进行增加、删除和修改的时候,索引也要动态的维护,这样就降低了数据的维护速度。 索引是建立在数据库表中的某些列的上面。在创建索引的时候,应该考虑在哪些列上可以创建索引,在哪些列上不能创建索引。一般来说,应该在这些列上创建索引:在经常需要搜索的列上,可以加快搜索的速度;在作为主键的列上,强制该列的唯一性和组织表中数据的排列结构;在经常用在连接的列上,这些列主要是一些外键,可以加快连接的速度;在经常需要根据范围进行搜索的列上创建索引,因为索引已经排序,其指定的范围是连续的;在经常需要排序的列上创建索引,因为索引已经排序,这样查询可以利用索引的排序,加快排序查询时间;在经常使用在WHERE子句中的列上面创建索引,加快条件的判断速度。 同样,对于有些列不应该创建索引。一般来说,不应该创建索引的的这些列具有下列特点: 第一,对于那些在查询中很少使用或者参考的列不应该创建索引。这是因为,既然这些列很少使用到,因此有索引或者无索引,并不能提高查询速度。相反,由于增加了索引,反而降低了系统的维护速度和增大了空间需求。 第二,对于那些只有很少数据值的列也不应该增加索引。这是因为,由于这些列的取值很少,例如人事表的性别列,在查询的结果中,结果集的数据行占了表中数据行的很大比例,即需要在表中搜索的数据行的比例很大。增加索引,并不能明显加快检索速度。 第三,对于那些定义为text, image和bit数据类型的列不应该增加索引。这是因为,这些列的数据量要么相当大,要么取值很少。 第四,当修改性能远远大于检索性能时,不应该创建索引。这是因为,修改性能和检索性能是互相矛盾的。当增加索引时,会提高检索性能,但是会降低修改性能。当减少索引时,会提高修改性能,降低检索性能。因此,当修改性能远远大于检索性能时,不应该创建索引。 根据数据库的功能,可以在数据库设计器中创建三种索引:唯一索引、主键索引和聚集索引。 唯一索引 唯一索引是不允许其中任何两行具有相同索引值的索引。 当现有数据中存在重复的键值时,大多数数据库不允许将新创建的唯一索引与表一起保存。数据库还可能防止添加将在表中创建重复键值的新数据。例如,如果在employee表中职员的姓(lname)上创建了唯一索引,则任何两个员工都不能同姓。 主键索引 数据库表经常有一列或列组合,其值唯一标识表中的每一行。该列称为表的主键。 在数据库关系图中为表定义主键将自动创建主键索引,主键索引是唯一索引的特定类型。该索引要求主键中的每个值都唯一。当在查询中使用主键索引时,它还允许对数据的快速访问。 聚集索引 在聚集索引中,表中行的物理顺序与键值的逻辑(索引)顺序相同。一个表只能包含一个聚集索引。 如果某索引不是聚集索引,则表中行的物理顺序与键值的逻辑顺序不匹配。与非聚集索引相比,聚集索引通常提供更快的数据访问速度。 局部性原理与磁盘预读 由于存储介质的特性,磁盘本身存取就比主存慢很多,再加上机械运动耗费,磁盘的存取速度往往是主存的几百分分之一,因此为了提高效率,要尽量减少磁盘I/O。为了达到这个目的,磁盘往往不是严格按需读取,而是每次都会预读,即使只需要一个字节,磁盘也会从这个位置开始,顺序向后读取一定长度的数据放入内存。这样做的理论依据是计算机科学中著名的局部性原理:当一个数据被用到时,其附近的数据也通常会马上被使用。程序运行期间所需要的数据通常比较集中。 由于磁盘顺序读取的效率很高(不需要寻道时间,只需很少的旋转时间),因此对于具有局部性的程序来说,预读可以提高I/O效率。 预读的长度一般为页(page)的整倍数。页是计算机管理存储器的逻辑块,硬件及操作系统往往将主存和磁盘存储区分割为连续的大小相等的块,每个存储块称为一页(在许多操作系统中,页得大小通常为4k),主存和磁盘以页为单位交换数据。当程序要读取的数据不在主存中时,会触发一个缺页异常,此时系统会向磁盘发出读盘信号,磁盘会找到数据的起始位置并向后连续读取一页或几页载入内存中,然后异常返回,程序继续运行。 B-/+Tree索引的性能分析 到这里终于可以分析B-/+Tree索引的性能了。 上文说过一般使用磁盘I/O次数评价索引结构的优劣。先从B-Tree分析,根据B-Tree的定义,可知检索一次最多需要访问h个节点。数据库系统的设计者巧妙利用了磁盘预读原理,将一个节点的大小设为等于一个页,这样每个节点只需要一次I/O就可以完全载入。为了达到这个目的,在实际实现B-Tree还需要使用如下技巧: 每次新建节点时,直接申请一个页的空间,这样就保证一个节点物理上也存储在一个页里,加之计算机存储分配都是按页对齐的,就实现了一个node只需一次I/O。 B-Tree中一次检索最多需要h-1次I/O(根节点常驻内存),渐进复杂度为O(h)=O(logdN)。一般实际应用中,出度d是非常大的数字,通常超过100,因此h非常小(通常不超过3)。 而红黑树这种结构,h明显要深的多。由于逻辑上很近的节点(父子)物理上可能很远,无法利用局部性,所以红黑树的I/O渐进复杂度也为O(h),效率明显比B-Tree差很多。 综上所述,用B-Tree作为索引结构效率是非常高的。 ### Q6:连接的种类 #### **参考答案**: 查询分析器中执行: ``` --建表table1,table2: create table table1(id int,name varchar(10)) create table table2(id int,score int) insert into table1 select 1,'lee' insert into table1 select 2,'zhang' insert into table1 select 4,'wang' insert into table2 select 1,90 insert into table2 select 2,100 insert into table2 select 3,70 ``` 如表: ``` ------------------------------------------------- table1 | table2 | ------------------------------------------------- id name |id score | 1 lee |1 90| 2 zhang| 2 100| 4 wang| 3 70| ------------------------------------------------- ``` 以下均在查询分析器中执行 一、外连接 1.概念:包括左向外联接、右向外联接或完整外部联接 2.左连接:left join 或 left outer join (1)左向外联接的结果集包括 LEFT OUTER 子句中指定的左表的所有行,而不仅仅是联接列所匹配的行。如果左表的某行在右表中没有匹配行,则在相关联的结果集行中右表的所有选择列表列均为空值(null)。 (2)sql 语句 ``` select * from table1 left join table2 on table1.id=table2.id -------------结果------------- idnameidscore ------------------------------ 1lee190 2zhang2100 4wangNULLNULL ------------------------------ ``` 注释:包含table1的所有子句,根据指定条件返回table2相应的字段,不符合的以null显示 3.右连接:right join 或 right outer join (1)右向外联接是左向外联接的反向联接。将返回右表的所有行。如果右表的某行在左表中没有匹配行,则将为左表返回空值。 (2)sql 语句 ``` select * from table1 right join table2 on table1.id=table2.id -------------结果------------- idnameidscore ------------------------------ 1lee190 2zhang2100 NULLNULL370 ------------------------------ ``` 注释:包含table2的所有子句,根据指定条件返回table1相应的字段,不符合的以null显示 4.完整外部联接:full join 或 full outer join (1)完整外部联接返回左表和右表中的所有行。当某行在另一个表中没有匹配行时,则另一个表的选择列表列包含空值。如果表之间有匹配行,则整个结果集行包含基表的数据值。 (2)sql 语句 ``` select * from table1 full join table2 on table1.id=table2.id -------------结果------------- idnameidscore ------------------------------ 1lee190 2zhang2100 4wangNULLNULL NULLNULL370 ------------------------------ ``` 注释:返回左右连接的和(见上左、右连接) 二、内连接 1.概念:内联接是用比较运算符比较要联接列的值的联接 2.内连接:join 或 inner join 3.sql 语句 ``` select * from table1 join table2 on table1.id=table2.id -------------结果------------- idnameidscore ------------------------------ 1lee190 2zhang2100 ------------------------------ ``` 注释:只返回符合条件的table1和table2的列 4.等价(与下列执行效果相同) ``` A:select a.*,b.* from table1 a,table2 b where a.id=b.id B:select * from table1 cross join table2 where table1.id=table2.id (注:cross join后加条件只能用where,不能用on) ``` 三、交叉连接(完全) 1.概念:没有 WHERE 子句的交叉联接将产生联接所涉及的表的笛卡尔积。第一个表的行数乘以第二个表的行数等于笛卡尔积结果集的大小。(table1和table2交叉连接产生3*3=9条记录) 2.交叉连接:cross join (不带条件where...) 3.sql语句 ``` select * from table1 cross join table2 -------------结果------------- idnameidscore ------------------------------ 1lee190 2zhang190 4wang190 1lee2100 2zhang2100 4wang2100 1lee370 2zhang370 4wang370 ------------------------------ ``` 注释:返回3*3=9条记录,即笛卡尔积 4.等价(与下列执行效果相同) ``` A:select * from table1,table2 ``` ### Q7:数据库范式 #### **参考答案**: 1 第一范式(1NF) 在任何一个关系数据库中,第一范式(1NF)是对关系模式的基本要求,不满足第一范式(1NF)的数据库就不是关系数据库。 所谓第一范式(1NF)是指数据库表的每一列都是不可分割的基本数据项,同一列中不能有多个值,即实体中的某个属性不能有多个值或者不能有重复的属性。如果出现重复的属性,就可能需要定义一个新的实体,新的实体由重复的属性构成,新实体与原实体之间为一对多关系。在第一范式(1NF)中表的每一行只包含一个实例的信息。简而言之,第一范式就是无重复的列。 2 第二范式(2NF) 第二范式(2NF)是在第一范式(1NF)的基础上建立起来的,即满足第二范式(2NF)必须先满足第一范式(1NF)。第二范式(2NF)要求数据库表中的每个实例或行必须可以被惟一地区分。为实现区分通常需要为表加上一个列,以存储各个实例的惟一标识。这个惟一属性列被称为主关键字或主键、主码。 第二范式(2NF)要求实体的属性完全依赖于主关键字。所谓完全依赖是指不能存在仅依赖主关键字一部分的属性,如果存在,那么这个属性和主关键字的这一部分应该分离出来形成一个新的实体,新实体与原实体之间是一对多的关系。为实现区分通常需要为表加上一个列,以存储各个实例的惟一标识。简而言之,第二范式就是非主属性非部分依赖于主关键字。 3 第三范式(3NF) 满足第三范式(3NF)必须先满足第二范式(2NF)。简而言之,第三范式(3NF)要求一个数据库表中不包含已在其它表中已包含的非主关键字信息。例如,存在一个部门信息表,其中每个部门有部门编号(dept_id)、部门名称、部门简介等信息。那么在员工信息表中列出部门编号后就不能再将部门名称、部门简介等与部门有关的信息再加入员工信息表中。如果不存在部门信息表,则根据第三范式(3NF)也应该构建它,否则就会有大量的数据冗余。简而言之,第三范式就是属性不依赖于其它非主属性。(我的理解是消除冗余) ### Q8:数据库优化的思路 #### **参考答案**: 这个我借鉴了慕课上关于数据库优化的课程。 1.SQL语句优化 - 应尽量避免在 where 子句中使用!=或<>操作符,否则将引擎放弃使用索引而进行全表扫描。 - 应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如: ```sql select id from t where num is null ``` 可以在num上设置默认值0,确保表中num列没有null值,然后这样查询: ```sql select id from t where num=0 ``` *liueleven* 的评论: ``` 不是非我杠精,关于null,isNull,isNotNull其实是要看成本的,是否回表等因素总和考虑,才会决定是要走索引还是走全表扫描。 ``` 也给大家找了一个作者的博文([MySQL中IS NULL、IS NOT NULL、!=不能用索引?胡扯!](https://mp.weixin.qq.com/s/CEJFsDBizdl0SvugGX7UmQ)),仅供参考!!! [zhiyong0804d的意见] 之所以未把第二条删除还是考虑可能很多人都被误导了。那这样的组织能让大家兼听则明。 - 很多时候用 exists 代替 in 是一个好的选择。 - 用Where子句替换HAVING 子句 因为HAVING 只会在检索出所有记录之后才对结果集进行过滤。 2.索引优化 看上文索引 3.数据库结构优化 - 范式优化: 比如消除冗余(节省空间。。) - 反范式优化:比如适当加冗余等(减少join) - 拆分表:分区将数据在物理上分隔开,不同分区的数据可以制定保存在处于不同磁盘上的数据文件里。这样,当对这个表进行查询时,只需要在表分区中进行扫描,而不必进行全表扫描,明显缩短了查询时间,另外处于不同磁盘的分区也将对这个表的数据传输分散在不同的磁盘I/O,一个精心设置的分区可以将数据传输对磁盘I/O竞争均匀地分散开。对数据量大的时时表可采取此方法。可按月自动建表分区。 - 拆分其实又分垂直拆分和水平拆分: 案例: 简单购物系统暂设涉及如下表: 1.产品表(数据量10w,稳定) 2.订单表(数据量200w,且有增长趋势) 3.用户表 (数据量100w,且有增长趋势) 以mysql为例讲述下水平拆分和垂直拆分,mysql能容忍的数量级在百万静态数据可以到千万 **垂直拆分:** 解决问题:表与表之间的io竞争 不解决问题:单表中数据量增长出现的压力 方案: 把产品表和用户表放到一个server上 订单表单独放到一个server上 **水平拆分:** 解决问题:单表中数据量增长出现的压力 不解决问题:表与表之间的io争夺 方案:**用户表** 通过性别拆分为男用户表和女用户表,**订单表** 通过已完成和完成中拆分为已完成订单和未完成订单,**产品表** 未完成订单放一个server上,已完成订单表盒男用户表放一个server上,女用户表放一个server上(女的爱购物 哈哈)。 4.服务器硬件优化 这个么多花钱咯! ### Q9:存储过程与触发器的区别 #### **参考答案**: 触发器与存储过程非常相似,触发器也是SQL语句集,两者唯一的区别是触发器不能用EXECUTE语句调用,而是在用户执行Transact-SQL语句时自动触发(激活)执行。 触发器是在一个修改了指定表中的数据时执行的存储过程。 通常通过创建触发器来强制实现不同表中的逻辑相关数据的引用完整性和一致性。由于用户不能绕过触发器,所以可以用它来强制实施复杂的业务规则,以确保数据的完整性。 触发器不同于存储过程,触发器主要是通过事件执行触发而被执行的,而存储过程可以通过存储过程名称名字而直接调用。当对某一表进行诸如UPDATE、INSERT、DELETE这些操作时,SQLSERVER就会自动执行触发器所定义的SQL语句,从而确保对数据的处理必须符合这些SQL语句所定义的规则。 ## Redis 篇 ### Q1:使用 Redis 有哪些好处? #### **参考答案**: (1) 速度快,因为数据存在内存中,类似于HashMap,HashMap的优势就是查找和操作的时间复杂度都是O(1) (2) 支持丰富数据类型,支持string,list,set,sorted set,hash (3) 支持事务,操作都是原子性,所谓的原子性就是对数据的更改要么全部执行,要么全部不执行 (4) 丰富的特性:可用于缓存,消息,按key设置过期时间,过期后将会自动删除 ### Q2:redis相比memcached有哪些优势? #### **参考答案**: (1) memcached所有的值均是简单的字符串,redis作为其替代者,支持更为丰富的数据类型 (2) redis的速度比memcached快很多 (3) redis可以持久化其数据 ### Q3:redis常见性能问题和解决方案 #### **参考答案**: (1) Master最好不要做任何持久化工作,如RDB内存快照和AOF日志文件 (2) 如果数据比较重要,某个Slave开启AOF备份数据,策略设置为每秒同步一次 (3) 为了主从复制的速度和连接的稳定性,Master和Slave最好在同一个局域网内 (4) 尽量避免在压力很大的主库上增加从库 (5) 主从复制不要用图状结构,用单向链表结构更为稳定,即:Master <- Slave1 <- Slave2 <- Slave3... 这样的结构方便解决单点故障问题,实现Slave对Master的替换。如果Master挂了,可以立刻启用Slave1做Master,其他不变。 ### Q4:MySQL里有2000w数据,redis中只存20w的数据,如何保证redis中的数据都是热点数据 #### **参考答案**: 相关知识:redis 内存数据集大小上升到一定大小的时候,就会施行数据淘汰策略。redis 提供 6种数据淘汰策略: voltile-lru:从已设置过期时间的数据集(server.db[i].expires)中挑选最近最少使用的数据淘汰 volatile-ttl:从已设置过期时间的数据集(server.db[i].expires)中挑选将要过期的数据淘汰 volatile-random:从已设置过期时间的数据集(server.db[i].expires)中任意选择数据淘汰 allkeys-lru:从数据集(server.db[i].dict)中挑选最近最少使用的数据淘汰 allkeys-random:从数据集(server.db[i].dict)中任意选择数据淘汰 no-enviction(驱逐):禁止驱逐数据 ### Q5:Memcache与Redis的区别都有哪些? #### **参考答案**: 1)、存储方式 Memecache把数据全部存在内存之中,断电后会挂掉,数据不能超过内存大小。 Redis有部份存在硬盘上,这样能保证数据的持久性。 2)、数据支持类型 Memcache对数据类型支持相对简单。 Redis有复杂的数据类型。 3)、使用底层模型不同 它们之间底层实现方式 以及与客户端之间通信的应用协议不一样。 Redis直接自己构建了VM 机制 ,因为一般的系统调用系统函数的话,会浪费一定的时间去移动和请求。 4),value大小 redis最大可以达到1GB,而memcache只有1MB ### Q6:Redis 常见的性能问题都有哪些?如何解决? #### **参考答案**: 1) Master写内存快照,save命令调度rdbSave函数,会阻塞主线程的工作,当快照比较大时对性能影响是非常大的,会间断性暂停服务,所以Master最好不要写内存快照。 2) Master AOF持久化,如果不重写AOF文件,这个持久化方式对性能的影响是最小的,但是AOF文件会不断增大,AOF文件过大会影响Master重启的恢复速度。Master最好不要做任何持久化工作,包括内存快照和AOF日志文件,特别是不要启用内存快照做持久化,如果数据比较关键,某个Slave开启AOF备份数据,策略为每秒同步一次。 3) Master调用BGREWRITEAOF重写AOF文件,AOF在重写的时候会占大量的CPU和内存资源,导致服务load过高,出现短暂服务暂停现象。 4) Redis主从复制的性能问题,为了主从复制的速度和连接的稳定性,Slave和Master最好在同一个局域网内 ### Q7:redis 最适合的场景 #### **参考答案**: Redis最适合所有数据in-momory的场景,虽然Redis也提供持久化功能,但实际更多的是一个disk-backed的功能,跟传统意义上的持久化有比较大的差别,那么可能大家就会有疑问,似乎Redis更像一个加强版的Memcached,那么何时使用Memcached,何时使用Redis呢? 如果简单地比较Redis与Memcached的区别,大多数都会得到以下观点: 1) Redis不仅仅支持简单的k/v类型的数据,同时还提供list,set,zset,hash等数据结构的存储。 2) Redis支持数据的备份,即master-slave模式的数据备份。 3) Redis支持数据的持久化,可以将内存中的数据保持在磁盘中,重启的时候可以再次加载进行使用 ### Q8:Redis的同步机制了解么? #### **参考答案**: 从从同步。第一次同步时,主节点做一次bgsave,并同时将后续修改操作记录到内存buffer,待完成后将rdb文件全量同步到复制节点,复制节点接受完成后将rdb镜像加载到内存。加载完成后,再通知主节点将期间修改的操作记录同步到复制节点进行重放就完成了同步过程。 ### Q9:是否使用过Redis集群,集群的原理是什么? #### **参考答案**: Redis Sentinel着眼于高可用,在master宕机时会自动将slave提升为master,继续提供服务。 Redis Cluster着眼于扩展性,在单个redis内存不足时,使用Cluster进行分片存储。 ## MongoDB 篇 ### Q1:什么是MongoDB #### **参考答案**: MongoDB是一个文档数据库,提供好的性能,领先的非关系型数据库。采用BSON存储文档数据。2007年10月,MongoDB由10gen团队所发展。2009年2月首度推出。获得安装包和查看详细的API可以访问官网网址www.mongodb.com ### Q2:MongoDB是由哪种语言写的 #### **参考答案**: MongoDB用c++编写的,流行的开源数据库MySQL也是用C++开发的。C++1983年发行是一种使用广泛的计算机程序设计语言。它是一种通用程序设计语言,支持多重编程模式。 ### Q3:MongoDB的优势有哪些 #### **参考答案**: 面向文档的存储:以 JSON 格式的文档保存数据。 * 任何属性都可以建立索引。 * 复制以及高可扩展性。 * 自动分片。 * 丰富的查询功能。 * 快速的即时更新。 * 来自 MongoDB 的专业支持。 ### Q4:什么是数据库 #### **参考答案**: 数据库可以看成是一个电子化的文件柜,用户可以对文件中的数据运行新增、检索、更新、删除等操作。数据库是一个所有集合的容器,在文件系统中每一个数据库都有一个相关的物理文件。 ### Q5:什么是集合 #### **参考答案**: 集合就是一组 MongoDB 文档。它相当于关系型数据库(RDBMS)中的表这种概念。集合位于单独的一个数据库中。一个集合内的多个文档可以有多个不同的字段。一般来说,集合中的文档都有着相同或相关的目的。 ### Q6:什么是文档 #### **参考答案**: 文档由一组key value组成。文档是动态模式,这意味着同一集合里的文档不需要有相同的字段和结构。在关系型数据库中table中的每一条记录相当于MongoDB中的一个文档。 ### Q7:什么是”mongod“ #### **参考答案**: mongod是处理MongoDB系统的主要进程。它处理数据请求,管理数据存储,和执行后台管理操作。当我们运行mongod命令意味着正在启动MongoDB进程,并且在后台运行。 ### Q8:"mongod"参数有什么 #### **参考答案**: 传递数据库存储路径,默认是"/data/db" 端口号 默认是 "27017" ### Q9:什么是"mongo" #### **参考答案**: 它是一个命令行工具用于连接一个特定的mongod实例。当我们没有带参数运行mongo命令它将使用默认的端口号和localhost连接。 ### Q10:MongoDB哪个命令可以切换数据库 #### **参考答案**: MongoDB 用use+数据库名称的方式来创建数据库。use会创建一个新的数据库,如果该数据库存在,则返回这个数据库。 >use database_name ### Q11:什么是非关系型数据库 #### **参考答案**: 非关系型数据库是对不同于传统关系型数据库的统称。非关系型数据库的显著特点是不使用SQL作为查询语言,数据存储不需要特定的表格模式。由于简单的设计和非常好的性能所以被用于大数据和Web Apps等 ### Q12:非关系型数据库有哪些类型 #### **参考答案**: * Key-Value 存储 Eg:Amazon S3 * 图表 Eg:Neo4J * 文档存储 Eg:MongoDB * 基于列存储 Eg:Cassandra ### Q13:为什么用MOngoDB? #### **参考答案**: * 架构简单 * 没有复杂的连接 * 深度查询能力,MongoDB支持动态查询。 * 容易调试 * 容易扩展 * 不需要转化/映射应用对象到数据库对象 * 使用内部内存作为存储工作区,以便更快的存取数据。 ### Q14:在哪些场景使用MongoDB #### **参考答案**: * 大数据 * 内容管理系统 * 移动端Apps * 数据管理 ### Q15:MongoDB中的命名空间是什么意思? #### **参考答案**: MongoDB内部有预分配空间的机制,每个预分配的文件都用0进行填充。 数据文件每新分配一次,它的大小都是上一个数据文件大小的2倍,每个数据文件最大2G。 MongoDB每个集合和每个索引都对应一个命名空间,这些命名空间的元数据集中在16M的*.ns文件中,平均每个命名占用约 628 字节,也即整个数据库的命名空间的上限约为24000。 如果每个集合有一个索引(比如默认的_id索引),那么最多可以创建12000个集合。如果索引数更多,则可创建的集合数就更少了。同时,如果集合数太多,一些操作也会变慢。 要建立更多的集合的话,MongoDB 也是支持的,只需要在启动时加上“--nssize”参数,这样对应数据库的命名空间文件就可以变得更大以便保存更多的命名。这个命名空间文件(.ns文件)最大可以为 2G。 每个命名空间对应的盘区不一定是连续的。与数据文件增长相同,每个命名空间对应的盘区大小都是随分配次数不断增长的。目的是为了平衡命名空间浪费的空间与保持一个命名空间数据的连续性。 需要注意的一个命名空间$freelist,这个命名空间用于记录不再使用的盘区(被删除的Collection或索引)。每当命名空间需要分配新盘区时,会先查看$freelist是否有大小合适的盘区可以使用,如果有就回收空闲的磁盘空间。 ### Q16: 哪些语言支持MongoDB? #### **参考答案**: * C * C++ * C# * Java * Node.js * Perl * Php 等 ### Q17:在MongoDB中如何创建一个新的数据库 #### **参考答案**: MongoDB 用 use + 数据库名称 的方式来创建数据库。use 会创建一个新的数据库,如果该数据库存在,则返回这个数据库。 >use mydb switched to db mydb ### Q18:在MongoDB中如何查看数据库列表 #### **参考答案**: 使用命令"show dbs" >show dbs ### Q19:MongoDB中的分片是什么意思 #### **参考答案**: 分片是将数据水平切分到不同的物理节点。当应用数据越来越大的时候,数据量也会越来越大。当数据量增长时,单台机器有可能无法存储数据或可接受的读取写入吞吐量。利用分片技术可以添加更多的机器来应对数据量增加以及读写操作的要求。 参考:[https://docs.mongodb.com/manual/sharding/](https://docs.mongodb.com/manual/sharding/) ### Q20:如何查看使用MongoDB的连接 使用命令"db.adminCommand(“connPoolStats”)" >db.adminCommand(“connPoolStats”) ### Q21 <file_sep>/** * --- 配置文件的入口文件 --- */ const utils = require('./utils') module.exports = { title: 'Full-Stack Library', description: '前端图书馆', base: '/', head: [ [ 'link', { rel: 'icon', href: '/favicon.ico' } ] ], themeConfig: { nav: [ { text: '首页', link: '/' }, { text: '面试专栏', link: '/Interviews/' }, { text: '基础进阶', items: [ { text: '深入 JavaScript', link: '/Js/' }, { text: '深入 CSS', link: '/CSS/' }, ] }, { text: '主流框架', items: [ { text: 'Vue专栏', link: '/Vue/' }, { text: 'React专栏', link: '/React/' }, { text: '小程序专栏', link: '/Applets/' }, { text: '微信公众号', link: '/Wechat/' }, { text: 'Hybrid开发专栏', link: '/Hybrid/' } ] }, // { // text: '移动端', // items: [ // { // text: 'Flutter', // link: '/Flutter/' // }, // { // text: 'iOS原生开发', // link: '/iOS/' // } // ] // }, // { // text: '服务端', // items: [ // { text: '数据结构与算法', link: '/Algorithms/' }, // { text: 'HTTP详解', link: '/HTTP/' }, // { text: 'Node.js', link: '/Node/' } // ] // }, // { // text: '全栈思维', // items: [ // { // text: 'Web安全', // link: '/WebSafety/' // }, // { // text: '自动化测试', // link: '/AutoText/' // }, // { // text: '区块链', // link: '/Blockchain/' // }, // { // text: '推荐库', // link: '/Repository/' // } // ] // } // { // text: 'Blog', // link: 'https://viktorwong.github.io/' // } ], sidebar: utils.inferSiderbars(), lastUpdated: '上次更新', repo: 'ViktorWong/Full-Stack-Library', editLinks: true, docsDir: 'docs', editLinkText: '在 GitHub 上编辑此页', sidebarDepth: 4 }, configureWebpack: { resolve: { alias: { '@public': './public' } } }, ga: 'UA-132773827-1', markdown: { config: md => { // use more markdown-it plugins! md.use(require('markdown-it-include')) } } }
4c4d3baffee0b6aab7e9349be73f870f0638187c
[ "Markdown", "JavaScript" ]
12
Markdown
ViktorWong/Full-Stack-Library
57d7e0c78b5c131074a60268b68b62fb3f78ce3a
fb2586f45046a2dfdd492f9a3e6bed8133ad943f
refs/heads/master
<repo_name>th0br0/rocks-to-graph<file_sep>/build.gradle plugins { id 'java' } group 'org.iota.utils' version '1.0-SNAPSHOT' sourceCompatibility = 1.8 repositories { maven { url 'https://jitpack.io' } mavenCentral() } def jgVersion = '0.3.1' def tkVersion = '3.3.4' dependencies { compile 'com.github.iotaledger:iota-java:1.0.0-beta2' compile group: 'org.rocksdb', name: 'rocksdbjni', version: '5.15.10' compile group: 'com.beust', name: 'jcommander', version: '1.72' compile group: 'org.apache.tinkerpop', name: 'gremlin-server', version: tkVersion compile group: 'org.janusgraph', name: 'janusgraph-core', version: jgVersion compile group: 'org.janusgraph', name: 'janusgraph-cassandra', version: jgVersion compile group: 'org.janusgraph', name: 'janusgraph-cql', version: jgVersion compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.13' testCompile group: 'junit', name: 'junit', version: '4.12' } <file_sep>/conf/cql.properties gremlin.graph=org.janusgraph.core.JanusGraphFactory storage.backend=cql storage.cql.keyspace=runtest storage.hostname=172.17.0.2 query.batch=true storage.batch-loading=true schema.default = none <file_sep>/src/main/java/org/iota/rockstograph/RocksDBImporter.java package org.iota.rockstograph; import com.google.common.base.Strings; import jota.model.Transaction; import jota.utils.Converter; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.janusgraph.core.*; import org.janusgraph.core.schema.JanusGraphManagement; import org.rocksdb.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jota.model.Transaction; /** * @author <NAME> */ public class RocksDBImporter implements Runnable { private final static Logger LOG = LoggerFactory.getLogger(RocksDBImporter.class); private final Config config; private Map<String, ColumnFamilyHandle> rdbCFHandles = new HashMap<>(); private JanusGraph graphInst; private RocksDB rdbInst; private GraphTraversalSource graph; public RocksDBImporter(Config config) { this.config = config; } void openRocksDB() throws RocksDBException { LOG.info("Opening RocksDB from: " + config.rocksDbPath); List<ColumnFamilyDescriptor> cfs = new ArrayList<>(); List<ColumnFamilyHandle> handles = new ArrayList<>(); DBOptions dbOptions = new DBOptions(); OptionsUtil.loadLatestOptions(config.rocksDbPath, Env.getDefault(), dbOptions, cfs); rdbInst = RocksDB.open(dbOptions, config.rocksDbPath, cfs, handles); for (ColumnFamilyHandle handle : handles) { rdbCFHandles.put(new String(handle.getName()), handle); } } void closeRocksDB() { rdbInst.close(); rdbInst = null; } void openGraphDB() { graphInst = JanusGraphFactory.open(config.janusConfig); setupGraphSchema(); graph = graphInst.traversal(); } void closeGraphDB() { try { graph.close(); } catch (Exception e) { LOG.error("graph.close() failed", e); } graphInst.close(); graph = null; graphInst = null; } void setupGraphSchema() { final JanusGraphManagement management = graphInst.openManagement(); if (management.getRelationTypes(RelationType.class).iterator().hasNext()) { LOG.info("Graph schema already setup"); management.rollback(); return; } LOG.info("Creating graph schema"); management.makeVertexLabel("transaction").make(); management.makePropertyKey("hash").dataType(String.class).make(); management.makePropertyKey("address").dataType(String.class).make(); management.makePropertyKey("bundle").dataType(String.class).make(); management.makePropertyKey("tag").dataType(String.class).make(); management.makePropertyKey("value").dataType(Long.class).make(); management.makePropertyKey("timestamp").dataType(Long.class).make(); management.makePropertyKey("attachmentTimestamp").dataType(Long.class).make(); management.makePropertyKey("attachmentTag").dataType(String.class).make(); management.makeEdgeLabel("ref").directed().multiplicity(Multiplicity.MULTI).make(); management.makePropertyKey("refKind").dataType(Integer.class).cardinality(Cardinality.SINGLE).make(); management.commit(); } void performImport() throws RocksDBException { long count = 0; int[] txTrits = new int[8019]; try (RocksIterator iter = rdbInst.newIterator(rdbCFHandles.get("transaction"))) { long txCount = rdbInst.getLongProperty(rdbCFHandles.get("transaction"), "rocksdb.estimate-num-keys"); LOG.info("Estimated transaction count: " + txCount); Map<String, Object> hashToID = new HashMap<>(); // Genesis { String all9 = Strings.repeat("9", 81); Vertex vx = graph.addV("transaction") .property("hash", all9) .property("address", all9) .property("bundle", all9) .property("tag", all9.substring(0, 27)) .property("attachmentTag", all9.substring(0, 27)) .property("value", 0) .property("timestamp", 0) .property("attachmentTimestamp", 0).next(); hashToID.put(all9, vx.id()); } // Vertices for (iter.seekToFirst(); iter.isValid(); iter.next()) { count++; byte[] transactionData = iter.value(); Converter.getTrits(transactionData, txTrits); Transaction iotaTx = Transaction.asTransactionObject(Converter.trytes(txTrits)); Vertex vx = graph.addV("transaction") .property("hash", iotaTx.getHash()) .property("address", iotaTx.getAddress()) .property("bundle", iotaTx.getBundle()) .property("tag", iotaTx.getObsoleteTag()) .property("attachmentTag", iotaTx.getTag()) .property("value", iotaTx.getValue()) .property("timestamp", iotaTx.getTimestamp()) .property("attachmentTimestamp", iotaTx.getAttachmentTimestamp()).next(); hashToID.put(iotaTx.getHash(), vx.id()); if (count % 10000L == 0) { graph.tx().commit(); LOG.info("Persisted " + count + " vertices."); } } graph.tx().commit(); LOG.info("Persisted " + count + " vertices."); // Edges count = 0; for (iter.seekToFirst(); iter.isValid(); iter.next()) { count++; byte[] transactionData = iter.value(); Converter.getTrits(transactionData, txTrits); Transaction iotaTx = Transaction.asTransactionObject(Converter.trytes(txTrits)); graph .V(hashToID.get(iotaTx.getHash())) .as("a") .V(hashToID.get(iotaTx.getTrunkTransaction())) .addE("ref") .property("refKind", 0) .from("a").next(); graph .V(hashToID.get(iotaTx.getHash())) .as("a") .V(hashToID.get(iotaTx.getBranchTransaction())) .addE("ref") .property("refKind", 1) .from("a").next(); if (count % 10000L == 0) { graph.tx().commit(); LOG.info("Persisted " + 2 * count + " edges."); } } graph.tx().commit(); LOG.info("Persisted " + 2 * count + " edges."); } } @Override public void run() { try { openRocksDB(); } catch (Exception e) { LOG.error("Opening RocksDB failed.", e); return; } openGraphDB(); LOG.info("Databases opened."); try { if (graph.V().count().next() != 0) { throw new RuntimeException("Graph already populated! Aborting."); } performImport(); } catch (Exception e) { LOG.error("Import failed.", e); } closeGraphDB(); closeRocksDB(); LOG.info("Databases closed."); } } <file_sep>/settings.gradle rootProject.name = 'rocks-to-graph'
ce2f47a5e3b02973cfd330e6381c230a270546f4
[ "Java", "INI", "Gradle" ]
4
Gradle
th0br0/rocks-to-graph
87d3af5367d3286cfbb8ee02c18dfdb4d306e133
ba624a46ffada81272b736ec4de29616b67d5ee5
refs/heads/master
<repo_name>MakerCollider/SmartNode_Build_Tool<file_sep>/edison_tools/extboardcheck.sh #!/bin/sh BOARDNAME="/etc/mc_extboard_name" EDIBOT="mc_newbreakout" check_edibot() { check6050 local mpu=$? check5883 local cmp=$? check5611 local baro=$? if [ $mpu -eq '1' -a $cmp -eq '1' -a $baro -eq '1' ] ; then echo "Edibot extension board confirmed." echo $EDIBOT > $BOARDNAME fi arr=( 3 7 6 5 4 2 1 0 8 9 10 11 12 13 14 15 ) echo "test IO are (${arr[@]})" echo "turn on all leds." for i in ${arr[@]} do echo "IO led on:" $i mraaio $i 0 done } rm -rf $BOARDNAME check_edibot <file_sep>/sn_dev.sh #!/bin/bash cat << "EOF" __ __ _ ____ _ _ _ _ | \/ | __ _| | _____ _ __ / ___|___ | | (_) __| | ___ _ __ | |\/| |/ _` | |/ / _ \ '__| | | / _ \| | | |/ _` |/ _ \ '__| | | | | (_| | < __/ | | |__| (_) | | | | (_| | __/ | |_| |_|\__,_|_|\_\___|_| \____\___/|_|_|_|\__,_|\___|_| EOF CMD=`pwd` NODE_PATH="node-red/node_modules" SMART_GIT="https://github.com/MakerCollider/node-red-contrib-smartnode.git" HOOK_GIT="https://github.com/MakerCollider/node-red-contrib-smartnode-hook.git" SEEED_GIT="https://github.com/MakerCollider/node-red-contrib-smartnode-seeed.git" DFROBOT_GIT="https://github.com/MakerCollider/node-red-contrib-smartnode-dfrobot.git" echo "## 1 ## Stop node-red service" systemctl stop nodered echo "## 2 ## Clone latest repository from Github" rm -rf node-red/node_modules/node-red-contrib-smartnode* git clone ${SMART_GIT} ${CMD}/${NODE_PATH}/node-red-contrib-smartnode git clone ${HOOK_GIT} ${CMD}/${NODE_PATH}/node-red-contrib-smartnode-hook git clone ${SEEED_GIT} ${CMD}/${NODE_PATH}/node-red-contrib-smartnode-seeed git clone ${DFROBOT_GIT} ${CMD}/${NODE_PATH}/node-red-contrib-smartnode-dfrobot echo "## 3 ## Add soft link" rm -rf link && mkdir link ln -s ../${NODE_PATH}/node-red-contrib-smartnode ${CMD}/link/smartnode ln -s ../${NODE_PATH}/node-red-contrib-smartnode-hook ${CMD}/link/smartnode-hook ln -s ../${NODE_PATH}/node-red-contrib-smartnode-dfrobot ${CMD}/link/smartnode-dfrobot ln -s ../${NODE_PATH}/node-red-contrib-smartnode-seeed ${CMD}/link/smartnode-seeed echo "## 4 ## Restart node-red service" systemctl start nodered echo "## 5 ## All finish"<file_sep>/pub/install_head.sh #!/bin/sh cat << "EOF" ____ _ _ _ _ / ___| _ __ ___ __ _ _ __| |_ | \ | | ___ __| | ___ \___ \| '_ ` _ \ / _` | '__| __| | \| |/ _ \ / _` |/ _ \ ___) | | | | | | (_| | | | |_ | |\ | (_) | (_| | __/ |____/|_| |_| |_|\__,_|_| \__| |_| \_|\___/ \__,_|\___| Copyright (C) 2015-2016, <NAME>, All Rights Reserved. EOF CURR=`pwd` LOG=$CURR/install.log echo "## 0 ## Extract package" line=`wc -l $0|awk '{print $1}'` line=`expr $line - 27` rm -rf node-red/ lib/ edison_tools/ README.md install.sh sn_dev.sh #configure/ tail -n $line $0 |tar xzv >> $LOG ./install.sh ret=$? # # # exit $ret <file_sep>/install.sh #!/bin/sh CURR=`pwd` LOG=$CURR/install.log echo "## 1 ## Import configure" ASOUND=/etc/asound.conf echo "defaults.pcm.card 2" > $ASOUND #cp $CURR/configure/asound.conf /etc/ #cp $CURR/configure/asound.state /var/lib/alsa/ #cp $CURR/configure/timesyncd.conf /etc/systemd/ #cp $CURR/configure/mosquitto.conf /etc/mosquitto/ echo "## 1.1 ## Apply configure(disabled)" #amixer -c 2 set Speaker 100% #alsactl store #timedatectl set-timezone Asia/Hong_Kong #systemctl restart mosquitto echo "## 2 ## Update mraa(disabled)" #opkg install $CURR/lib/mraa_0.9.0_i586.ipk echo "## 3 ## Update upm(disabled)" #opkg install $CURR/lib/upm_0.4.1_i586.ipk echo "## 4 ## Install git(disabled)" #opkg install $CURR/lib/git_2.5.0-r0_core2-32.ipk echo "## 5 ## Install opencv" #opkg install $CURR/lib/opencv/libpng16-16_1.6.13-r0_core2-32.ipk opkg install $CURR/lib/opencv/libpng16-dev_1.6.13-r0_core2-32.ipk opkg install $CURR/lib/opencv/libgif4_4.1.6-r3_core2-32.ipk opkg install $CURR/lib/opencv/libgif-dev_4.1.6-r3_core2-32.ipk opkg install $CURR/lib/opencv/libtiff5_4.0.3-r0_core2-32.ipk opkg install $CURR/lib/opencv/libtiff-dev_4.0.3-r0_core2-32.ipk opkg install $CURR/lib/opencv/libv4l_1.0.1-r0_core2-32.ipk opkg install $CURR/lib/opencv/libv4l-dev_1.0.1-r0_core2-32.ipk opkg install $CURR/lib/opencv/libwebp_0.4.0-r0_core2-32.ipk opkg install $CURR/lib/opencv/libwebp-dev_0.4.0-r0_core2-32.ipk opkg install $CURR/lib/opencv/v4l-utils_1.0.1-r0_core2-32.ipk opkg install $CURR/lib/opencv/v4l-utils-dev_1.0.1-r0_core2-32.ipk sh $CURR/lib/opencv/OpenCV-3.1.0-1017-g52444bf-i686.sh --prefix=/usr --exclude-subdir echo "## 6 ## Install sox" #tar -xzvf $CURR/lib/sox.tar.gz -C /usr >> $LOG opkg install $CURR/lib/sox/libx264-133_r2265+git0+ffc3ad4945-r0_core2-32.ipk opkg install $CURR/lib/sox/libtheora_1.1.1-r1_core2-32.ipk opkg install $CURR/lib/sox/libavutil51_0.8.15-r0_core2-32.ipk opkg install $CURR/lib/sox/libavcodec53_0.8.15-r0_core2-32.ipk opkg install $CURR/lib/sox/libavformat53_0.8.15-r0_core2-32.ipk #opkg install $CURR/lib/sox/libpng16-16_1.6.13-r0_core2-32.ipk opkg install $CURR/lib/sox/sox_14.4.0-r1_core2-32.ipk echo "## 7 ## Install mpg123" #tar -xzvf $CURR/lib/mpg123.tar.gz -C /usr >> $LOG opkg install $CURR/lib/mpg123/mpg123_1.22.4-r0_core2-32.ipk echo "## 8 ## Install festival" #tar -xzvf $CURR/lib/festival_prebuild.tar.gz -C /opt >> $LOG #cp /opt/festival/festival/bin/festival /usr/bin opkg install $CURR/lib/festival/festival_2.3-r0_core2-32.ipk echo "## 9 ## Hacking mraa-diy library" opkg remove mraa mraa-dev --force-depends tar -xzvf $CURR/lib/mraa-diy.tgz -C /usr >> $LOG #cp -r /usr/lib/node_modules/mraa/mraa.node $CURR/node-red/node_modules/mraa/build/Release/ echo "## 10 ## Hacking upm-diy library" tar -xzvf $CURR/lib/upm-diy.tgz -C /usr >> $LOG echo "## 11 ## Run board auto detect tools" cd $CURR/edison_tools ./install_edisontools.sh cd $CURR echo "## 12 ## Install mqtt package(disabled)" #opkg install $CURR/lib/mqtt_1.4/*.ipk echo "## 12.1 ## Config mqtt(disabled, move to stage 1.1)" #cp $CURR/lib/mqtt_1.4/mosquitto.conf /etc/mosquitto/ echo "## 13 ## Add showip service" mkdir -p /etc/init.d cp $CURR/lib/showip/showip /etc/init.d chmod 755 /etc/init.d/showip update-rc.d -f showip remove update-rc.d showip defaults 91 echo "## 14 ## Set smartnode service" SERVICE=/etc/systemd/system/nodered.service rm -rf $SERVICE echo "[Unit]" > $SERVICE echo "Description=Node-RED" >> $SERVICE echo "" >> $SERVICE echo "[Service]" >> $SERVICE echo "Type=simple" >> $SERVICE echo "Environment=\"NODE_PATH=/usr/lib/node_modules\"" >> $SERVICE echo "ExecStart=/usr/bin/node $CURR/node-red/red.js --userDir $CURR/node-red -v" >> $SERVICE echo "Restart=always" >> $SERVICE echo "RestartSec=1" >> $SERVICE echo "[Install]" >> $SERVICE echo "WantedBy=multi-user.target" >> $SERVICE echo "## 14.1 ## Start smartnode service" sleep 1 systemctl disable nodered sleep 1 systemctl enable nodered sleep 1 systemctl restart nodered > /dev/null 2>&1 echo "## 15 ## All finish, log saved to $LOG"<file_sep>/pub/make_rel_pack_for_bb.sh #!/bin/sh TAR_NAME=smartnode_1.0.tar.gz echo $TAR_NAME echo "make release package for edison image bitbake project ..." rm -rf $TAR_NAME TARDIR=smartnode_1.0 mkdir $TARDIR SERVICE=./$TARDIR/nodered.service rm -rf $SERVICE echo "[Unit]" > $SERVICE echo "Description=Node-RED" >> $SERVICE echo "" >> $SERVICE echo "[Service]" >> $SERVICE echo "Type=simple" >> $SERVICE echo "Environment=\"NODE_PATH=/usr/lib/node_modules\"" >> $SERVICE echo "ExecStart=/usr/bin/node /home/root/$TARDIR/node-red/red.js --userDir /home/root/TARDIR/node-red -v" >> $SERVICE echo "Restart=always" >> $SERVICE echo "RestartSec=1" >> $SERVICE echo "[Install]" >> $SERVICE echo "WantedBy=multi-user.target" >> $SERVICE cp ../nodered.service ./$TARDIR cp -r ../node-red/ ./$TARDIR cp ../install.sh ./$TARDIR cp ../install_for_dev.sh ./$TARDIR cp ../install_for_edibot.sh ./$TARDIR cp ../README.md ./$TARDIR tar -czvf $TAR_NAME ./$TARDIR chmod 755 ./$TAR_NAME rm -rf ./$TARDIR <file_sep>/pub/make_rel_pack.sh #!/bin/sh VERSION=$1 echo $VERSION if [ ! -n "$VERSION" ] ;then echo "USAGE: ./make_rel_pack.sh Version_number! etc. ./make_rel_pack.sh 0.9.5" exit fi TAR_NAME=smart_node.tgz echo $TAR_NAME echo "make release package..." rm -rf $TAR_NAME tar -czvf $TAR_NAME -X ./package_exclude ../node-red/ ../lib ../install.sh ../sn_dev.sh ../edison_tools ../README.md ../version #../configure cat install_head.sh smart_node.tgz > SmartNode-$VERSION.install chmod 755 SmartNode-${VERSION}.install rm ./smart_node.tgz <file_sep>/edison_tools/install_edisontools.sh #!/bin/sh echo "Installing Edison extension board check tool." cp extboardcheck.sh /etc/ cp all_built/check5611 /usr/bin cp all_built/check6050 /usr/bin cp all_built/check5883 /usr/bin cp all_built/mraaio /usr/bin systemctl disable extboard_detect cp extboard_detect.service /etc/systemd/system/ echo "Enabling Edison extension board check tool start up." systemctl enable extboard_detect systemctl start extboard_detect echo "All done."
6889f5a81895eed5fb5d274142aefd93e3a3c409
[ "Shell" ]
7
Shell
MakerCollider/SmartNode_Build_Tool
06eec55e39eec0476d74104636f2922455396721
9603040f449b83e34364d7a50b8f969e6f5a573f
refs/heads/master
<repo_name>bubbapizza/alsacap<file_sep>/man/Makefile.am # Include the pod file in the distribution. If we don't do this, then # the make files bark when building from a distribution tarball. EXTRA_DIST = alsacap.pod # Here is where we build the man file from pod. dist_man_MANS = alsacap.1 alsacap.1: alsacap.pod pod2man --release='$(PACKAGE_VERSION)' --center='$(PACKAGE_NAME)' \ --section=1 $< > $@ CLEANFILES = alsacap.1 <file_sep>/src/alsacap.c /* * ALSA parameter test program * * Copyright (c) 2007 <NAME> (alsacap at the domain volkerschatz.com) * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * * This program was originally written by <NAME>. <NAME> * bundled it into an autotools package and cut and pasted some code * from the alsa speaker-test command to display min/max buffer and * period sizes. * */ /*============================================================================ Includes ============================================================================*/ #include <stdlib.h> #include <stdio.h> #include <alsa/asoundlib.h> #include <errno.h> #include <string.h> /*============================================================================ Constant and type definitions ============================================================================*/ #define RATE_KHZ_LIMIT 200 #define HWP_END 0 #define HWP_RATE 1 #define HWP_NCH 2 #define HWP_FORMAT 3 #define SIZE_HWP 7 typedef struct { int recdevices, verbose, card, dev; char *device; int hwparams[SIZE_HWP]; } aiopts; /*============================================================================ Global variables ============================================================================*/ static snd_ctl_t *handle= NULL; static snd_pcm_t *pcm= NULL; static snd_ctl_card_info_t *info; static snd_pcm_info_t *pcminfo; static snd_pcm_hw_params_t *pars; static snd_pcm_format_mask_t *fmask; /*============================================================================ Prototypes ============================================================================*/ void usagemsg(int code); void errnumarg(char optchar); void errarg(char optchar); void errtoomany(); void scancards(snd_pcm_stream_t stream, int thecard, int thedev); int sc_errcheck(int retval, const char *doingwhat, int cardnr, int devnr); void testconfig(snd_pcm_stream_t stream, const char *device, const int *hwpars); void tc_errcheck(int retval, const char *doingwhat); const char *alsaerrstr(const int errcode); const char *dirstr(int dir); int parse_alsaformats(const char *fmtstr); const char *alsafmtstr(int fmtnum); void printfmtmask(const snd_pcm_format_mask_t *fmask); /*============================================================================ Main program ============================================================================*/ int main(int argc, char **argv) { aiopts options= { 0, 1, -1, -1, NULL }; snd_pcm_stream_t stream; char *argpar; int argind, hwpind; snd_ctl_card_info_alloca(&info); snd_pcm_info_alloca(&pcminfo); snd_pcm_hw_params_alloca(&pars); snd_pcm_format_mask_alloca(&fmask); hwpind= 0; for( argind= 1; argind< argc; ++argind ) { if( argv[argind][0]!='-' ) { fprintf(stderr, "Unrecognised command-line argument `%s'.\n", argv[argind]); usagemsg(1); } if( argv[argind][2] ) argpar= argv[argind]+2; else { if( argind+1 >= argc ) argpar= NULL; else argpar= argv[argind+1]; } if( argv[argind][1]=='h' || !strcmp(argv[argind]+1, "-help") ) usagemsg(0); else if( argv[argind][1]=='R' ) { options.recdevices= 1; argpar= NULL; // set to NULL if unused to keep track of next arg index } else if( argv[argind][1]=='C' ) { if( !argpar || !isdigit(*argpar) ) errnumarg('C'); options.card= strtol(argpar, NULL, 0); } else if( argv[argind][1]=='D' ) { if( !argpar || !isdigit(*argpar) ) errnumarg('D'); options.dev= strtol(argpar, NULL, 0); } else if( argv[argind][1]=='d' ) { if( !argpar ) errarg('d'); options.device= argpar; } else if( argv[argind][1]=='r' ) { if( !argpar || !isdigit(*argpar) ) errnumarg('r'); if( hwpind+3 > SIZE_HWP ) errtoomany(); options.hwparams[hwpind++]= HWP_RATE; options.hwparams[hwpind]= strtol(argpar, NULL, 0); if( options.hwparams[hwpind] <= RATE_KHZ_LIMIT ) options.hwparams[hwpind] *= 1000; // sanity check: Hz or kHz ? ++hwpind; } else if( argv[argind][1]=='c' ) { if( !argpar || !isdigit(*argpar) ) errnumarg('c'); if( hwpind+3 > SIZE_HWP ) errtoomany(); options.hwparams[hwpind++]= HWP_NCH; options.hwparams[hwpind++]= strtol(argpar, NULL, 0); } else if( argv[argind][1]=='f' ) { if( !argpar ) errarg('f'); if( hwpind+3 > SIZE_HWP ) errtoomany(); options.hwparams[hwpind++]= HWP_FORMAT; options.hwparams[hwpind++]= parse_alsaformat(argpar); } else { fprintf(stderr, "Unrecognised command-line option `%s'.\n", argv[argind]); usagemsg(1); } if( argpar && !argv[argind][2] ) ++argind; // additional increment if separate parameter argument was used } options.hwparams[hwpind]= HWP_END; if( options.dev >= 0 && options.card < 0 ) { fprintf(stderr, "The card has to be specified with -C if a device number is given (-D).\n"); exit(1); } if( options.device && (options.card>=0 || options.dev>=0) ) { fprintf(stderr, "Specifying a device name (-d) and a card and possibly device number (-C, -D) is mutually exclusive.\n"); exit(1); } stream= options.recdevices? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK; if( !options.device ) scancards(stream, options.card, options.dev); else testconfig(stream, options.device, options.hwparams); } /*============================================================================ Usage message and command-line argument error functions ============================================================================*/ void usagemsg(int code) { fprintf(stderr, "Usage: alsacap [-R] [-C <card #> [-D <device #>]]\n" " alsacap [-R] -d <device name> [-r <rate>|-c <# of channels>|-f <sample format>]...\n" "ALSA capability lister.\n" "First form: Scans one or all soundcards known to ALSA for devices, \n" "subdevices and parameter ranges. -R causes a scan for recording\n" "rather than playback devices. The other options specify the sound\n" "card and possibly the device by number.\n" "Second form: Displays ranges of configuration parameters for the given\n" "ALSA device. Unlike with the first form, a non-hardware device may be\n" "given. Up to three optional command-line arguments fix the rate,\n" "number of channels and sample format in the order in which they are\n" "given. The remaining parameter ranges are output. If unique, the\n" "number of significant bits of the sample values is output. (Some\n" "sound cards ignore some of the bits.)\n"); exit(code); } void errnumarg(char optchar) { fprintf(stderr, "The -%c option requires a numerical argument! Aborting.\n", optchar); exit(1); } void errarg(char optchar) { fprintf(stderr, "The -%c option requires an argument! Aborting.\n", optchar); exit(1); } void errtoomany() { fprintf(stderr, "Too many -r/-c/-f options given! (Maximum is %d.) Aborting.\n", (SIZE_HWP-1)/2); exit(1); } /*============================================================================ Function for scanning all cards ============================================================================*/ #define HWCARDTEMPL "hw:%d" #define HWDEVTEMPL "hw:%d,%d" #define HWDEVLEN 32 void scancards(snd_pcm_stream_t stream, int thecard, int thedev) { char hwdev[HWDEVLEN+1]; unsigned min, max; int card, err, dev, subd, nsubd; snd_pcm_uframes_t period_size_min; snd_pcm_uframes_t period_size_max; snd_pcm_uframes_t buffer_size_min; snd_pcm_uframes_t buffer_size_max; printf("*** Scanning for %s devices", stream == SND_PCM_STREAM_CAPTURE? "recording" : "playback"); if( thecard >= 0 ) printf(" on card %d", thecard); if( thedev >= 0 ) printf(", device %d", thedev); printf(" ***\n"); hwdev[HWDEVLEN]= 0; if( thecard >= 0 ) card= thecard; else { card= -1; if( snd_card_next(&card) < 0 ) return; } while( card >= 0 ) { snprintf(hwdev, HWDEVLEN, HWCARDTEMPL, card); err= snd_ctl_open(&handle, hwdev, 0); if( sc_errcheck(err, "opening control interface", card, -1) ) goto nextcard; err= snd_ctl_card_info(handle, info); if( sc_errcheck(err, "obtaining card info", card, -1) ) { snd_ctl_close(handle); goto nextcard; } printf("Card %d, ID `%s', name `%s'\n", card, snd_ctl_card_info_get_id(info), snd_ctl_card_info_get_name(info)); if( thedev >= 0 ) dev= thedev; else { dev= -1; if( snd_ctl_pcm_next_device(handle, &dev) < 0 ) { snd_ctl_close(handle); goto nextcard; } } while( dev >= 0 ) { snd_pcm_info_set_device(pcminfo, dev); snd_pcm_info_set_subdevice(pcminfo, 0); snd_pcm_info_set_stream(pcminfo, stream); err= snd_ctl_pcm_info(handle, pcminfo); if( thedev<0 && err == -ENOENT ) goto nextdev; if( sc_errcheck(err, "obtaining device info", card, dev) ) goto nextdev; nsubd= snd_pcm_info_get_subdevices_count(pcminfo); if( sc_errcheck(nsubd, "obtaining device info", card, dev) ) goto nextdev; printf( " Device %d, ID `%s', name `%s', %d subdevices (%d available)\n", dev, snd_pcm_info_get_id(pcminfo), snd_pcm_info_get_name(pcminfo), nsubd, snd_pcm_info_get_subdevices_avail(pcminfo)); snprintf(hwdev, HWDEVLEN, HWDEVTEMPL, card, dev); err= snd_pcm_open(&pcm, hwdev, stream, SND_PCM_NONBLOCK); if( sc_errcheck(err, "opening sound device", card, dev) ) goto nextdev; err= snd_pcm_hw_params_any(pcm, pars); if( sc_errcheck(err, "obtaining hardware parameters", card, dev) ) { snd_pcm_close(pcm); goto nextdev; } snd_pcm_hw_params_get_channels_min(pars, &min); snd_pcm_hw_params_get_channels_max(pars, &max); if( min == max ) if( min == 1 ) printf(" 1 channel, "); else printf(" %d channels, ", min); else printf(" %u..%u channels, ", min, max); /* Find and print out min/max sampling rates. */ snd_pcm_hw_params_get_rate_min(pars, &min, NULL); snd_pcm_hw_params_get_rate_max(pars, &max, NULL); printf("sampling rate %u..%u Hz\n", min, max); /* Find and print out possible PCM formats. */ snd_pcm_hw_params_get_format_mask(pars, fmask); printf(" Sample formats: "); printfmtmask(fmask); printf("\n"); /* Find and print out min/max buffer and period sizes. */ err = snd_pcm_hw_params_get_buffer_size_min( pars, &buffer_size_min); err = snd_pcm_hw_params_get_buffer_size_max( pars, &buffer_size_max); err = snd_pcm_hw_params_get_period_size_min( pars, &period_size_min, NULL); err = snd_pcm_hw_params_get_period_size_max( pars, &period_size_max, NULL); printf(" Buffer size range from %lu to %lu\n", buffer_size_min, buffer_size_max); printf(" Period size range from %lu to %lu\n", period_size_min, period_size_max); snd_pcm_close(pcm); printf("\n"); pcm= NULL; for( subd= 0; subd< nsubd; ++subd ) { snd_pcm_info_set_subdevice(pcminfo, subd); err= snd_ctl_pcm_info(handle, pcminfo); if( sc_errcheck(err, "obtaining subdevice info", card, dev) ) goto nextdev; printf(" Subdevice %d, name `%s'\n", subd, snd_pcm_info_get_subdevice_name(pcminfo)); } nextdev: if( thedev >= 0 || snd_ctl_pcm_next_device(handle, &dev) < 0 ) break; } snd_ctl_close(handle); nextcard: if( thecard >= 0 || snd_card_next(&card) < 0 ) break; } } int sc_errcheck(int retval, const char *doingwhat, int cardnr, int devnr) { if( retval<0 ) { if( devnr>= 0 ) fprintf(stderr, "Error %s for card %d, device %d: %s. Skipping.\n", doingwhat, cardnr, devnr, alsaerrstr(retval)); else fprintf(stderr, "Error %s for card %d: %s. Skipping.\n", doingwhat, cardnr, alsaerrstr(retval)); return 1; } return 0; } /*============================================================================ Function for investigating device configurations ============================================================================*/ void testconfig(snd_pcm_stream_t stream, const char *device, const int *hwpars) { unsigned min, max, param; int err, count, dir, result; snd_pcm_uframes_t period_size_min; snd_pcm_uframes_t period_size_max; snd_pcm_uframes_t buffer_size_min; snd_pcm_uframes_t buffer_size_max; printf("*** Exploring configuration space of device `%s' for %s ***\n", device, stream==SND_PCM_STREAM_CAPTURE? "recording" : "playback"); err= snd_pcm_open(&pcm, device, stream, SND_PCM_NONBLOCK); tc_errcheck(err, "opening sound device"); err= snd_pcm_hw_params_any(pcm, pars); tc_errcheck(err, "initialising hardware parameters"); for( count= 0; hwpars[count]!=HWP_END; count += 2 ) switch(hwpars[count]) { case HWP_RATE:param= hwpars[count+1]; err= snd_pcm_hw_params_set_rate_near(pcm, pars, &param, &result); if( err<0 ) fprintf(stderr, "Could not set sampling rate to %d Hz: %s. " "Continuing regardless.\n", hwpars[count+1], alsaerrstr(err)); else printf("Set sampling rate %d Hz --> got %u Hz, %s requested.\n", hwpars[count+1], param, dirstr(dir)); break; case HWP_NCH:err= snd_pcm_hw_params_set_channels(pcm, pars, hwpars[count+1]); if( err<0 ) fprintf(stderr, "Could not set # of channels to %d: %s. " "Continuing regardless.\n", hwpars[count+1], alsaerrstr(err)); else printf("Set number of channels to %d.\n", hwpars[count+1]); break; case HWP_FORMAT:err= snd_pcm_hw_params_set_format(pcm, pars, hwpars[count+1]); if( err<0 ) fprintf(stderr, "Could not set sample format to %s: %s." " Continuing regardless.\n", alsafmtstr(hwpars[count+1]), alsaerrstr(err)); else printf("Set sample format to %s.\n", alsafmtstr(hwpars[count+1])); break; default: break; } if( count>0 ) printf("Parameter ranges remaining after these settings:\n"); snd_pcm_hw_params_get_channels_min(pars, &min); snd_pcm_hw_params_get_channels_max(pars, &max); if( min==max ) if( min==1 ) printf("1 channel\n"); else printf("%u channels\n", min); else printf("%u..%u channels\n", min, max); snd_pcm_hw_params_get_rate_min(pars, &min, NULL); snd_pcm_hw_params_get_rate_max(pars, &max, NULL); if( min==max ) printf("Sampling rate %u Hz\n", min); else printf("Sampling rate %u..%u Hz\n", min, max); /* Find and print out possible PCM formats. */ snd_pcm_hw_params_get_format_mask(pars, fmask); printf(" Sample formats: "); printfmtmask(fmask); printf("\n"); /* Find and print out min/max buffer and period sizes. */ err = snd_pcm_hw_params_get_buffer_size_min( pars, &buffer_size_min); err = snd_pcm_hw_params_get_buffer_size_max( pars, &buffer_size_max); err = snd_pcm_hw_params_get_period_size_min( pars, &period_size_min, NULL); err = snd_pcm_hw_params_get_period_size_max( pars, &period_size_max, NULL); printf(" Buffer size range from %lu to %lu\n", buffer_size_min, buffer_size_max); printf(" Period size range from %lu to %lu\n", period_size_min, period_size_max); result= snd_pcm_hw_params_get_sbits(pars); if( result >= 0 ) // only available if bit width of all formats is the same printf("Significant bits: %d\n", result); snd_pcm_close(pcm); } void tc_errcheck(int retval, const char *doingwhat) { if( retval<0 ) { fprintf(stderr, "Error %s: %s. Aborting.\n", doingwhat, alsaerrstr(retval)); if( pcm ) snd_pcm_close(pcm); exit(1); } } /*============================================================================ String-building functions ============================================================================*/ struct alsaerr { int err; char *msg; }; struct alsaerr aelist[]= { -EBADFD, "PCM device is in a bad state", -EPIPE, "An underrun occurred", -ESTRPIPE, "A suspend event occurred", -ENOTTY, "Hotplug device has been removed", -ENODEV, "Hotplug device has been removed", -ENOENT, "Device does not exist", 0, NULL }; const char *alsaerrstr(const int errcode) { struct alsaerr *search; if( errcode >= 0 ) return "No error"; for( search= aelist; search->msg && search->err!=errcode; ++search); if( search->msg ) return search->msg; else return strerror(-errcode); } const char *dirstr(int dir) { if( !dir ) return "="; else if( dir<0 ) return "<"; else return ">"; } /*============================================================================ Functions for parsing and string output of ALSA sample formats ============================================================================*/ struct fmtdef { char *fmtname; int format; }; static struct fmtdef fmtlist[]= { "S8", SND_PCM_FORMAT_S8, "U8", SND_PCM_FORMAT_U8, "S16_LE", SND_PCM_FORMAT_S16_LE, "S16_BE", SND_PCM_FORMAT_S16_BE, "U16_LE", SND_PCM_FORMAT_U16_LE, "U16_BE", SND_PCM_FORMAT_U16_BE, "S24_LE", SND_PCM_FORMAT_S24_LE, "S24_BE", SND_PCM_FORMAT_S24_BE, "U24_LE", SND_PCM_FORMAT_U24_LE, "U24_BE", SND_PCM_FORMAT_U24_BE, "S32_LE", SND_PCM_FORMAT_S32_LE, "S32_BE", SND_PCM_FORMAT_S32_BE, "U32_LE", SND_PCM_FORMAT_U32_LE, "U32_BE", SND_PCM_FORMAT_U32_BE, "FLOAT_LE", SND_PCM_FORMAT_FLOAT_LE, "FLOAT_BE", SND_PCM_FORMAT_FLOAT_BE, "FLOAT64_LE", SND_PCM_FORMAT_FLOAT64_LE, "FLOAT64_BE", SND_PCM_FORMAT_FLOAT64_BE, "IEC958_SUBFRAME_LE", SND_PCM_FORMAT_IEC958_SUBFRAME_LE, "IEC958_SUBFRAME_BE", SND_PCM_FORMAT_IEC958_SUBFRAME_BE, "MU_LAW", SND_PCM_FORMAT_MU_LAW, "A_LAW", SND_PCM_FORMAT_A_LAW, "IMA_ADPCM", SND_PCM_FORMAT_IMA_ADPCM, "MPEG", SND_PCM_FORMAT_MPEG, "GSM", SND_PCM_FORMAT_GSM, "SPECIAL", SND_PCM_FORMAT_SPECIAL, "S24_3LE", SND_PCM_FORMAT_S24_3LE, "S24_3BE", SND_PCM_FORMAT_S24_3BE, "U24_3LE", SND_PCM_FORMAT_U24_3LE, "U24_3BE", SND_PCM_FORMAT_U24_3BE, "S20_3LE", SND_PCM_FORMAT_S20_3LE, "S20_3BE", SND_PCM_FORMAT_S20_3BE, "U20_3LE", SND_PCM_FORMAT_U20_3LE, "U20_3BE", SND_PCM_FORMAT_U20_3BE, "S18_3LE", SND_PCM_FORMAT_S18_3LE, "S18_3BE", SND_PCM_FORMAT_S18_3BE, "U18_3LE", SND_PCM_FORMAT_U18_3LE, "U18_3BE", SND_PCM_FORMAT_U18_3BE, "S16", SND_PCM_FORMAT_S16, "U16", SND_PCM_FORMAT_U16, "S24", SND_PCM_FORMAT_S24, "U24", SND_PCM_FORMAT_U24, "S32", SND_PCM_FORMAT_S32, "U32", SND_PCM_FORMAT_U32, "FLOAT", SND_PCM_FORMAT_FLOAT, "FLOAT64", SND_PCM_FORMAT_FLOAT64, "IEC958_SUBFRAME", SND_PCM_FORMAT_IEC958_SUBFRAME, NULL, 0 }; int parse_alsaformat(const char *fmtstr) { struct fmtdef *search; for( search= fmtlist; search->fmtname && strcmp(search->fmtname, fmtstr); ++search ); if( !search->fmtname ) { fprintf(stderr, "Unknown sample format `%s'. Aborting.\n", fmtstr); exit(1); } return search->format; } const char *alsafmtstr(int fmtnum) { struct fmtdef *search; for( search= fmtlist; search->fmtname && search->format!=fmtnum; ++search ); if( !search->fmtname ) return "(unknown)"; else return search->fmtname; } /*============================================================================ Printout functions ============================================================================*/ void printfmtmask(const snd_pcm_format_mask_t *fmask) { int fmt, prevformat= 0; for( fmt= 0; fmt <= SND_PCM_FORMAT_LAST; ++fmt ) if( snd_pcm_format_mask_test(fmask, (snd_pcm_format_t)fmt) ) { if( prevformat ) printf(", "); printf("%s", snd_pcm_format_name((snd_pcm_format_t)fmt)); prevformat= 1; } if( !prevformat ) printf("(none)"); } <file_sep>/configure.ac AC_INIT(alsacap, 1.0) AM_INIT_AUTOMAKE # Set the CC command. AC_PROG_CC # Check for the alsa sound library. AC_CHECK_LIB(asound, asound) AC_CONFIG_FILES([ Makefile src/Makefile man/Makefile ]) AC_OUTPUT <file_sep>/src/Makefile.am bin_PROGRAMS = alsacap AM_LDFLAGS = -lasound
0849df8d1d68af2a48f0cf2b99bfd4c872eae9b0
[ "C", "Makefile", "M4Sugar" ]
4
Makefile
bubbapizza/alsacap
05968d33bd42b9550ac0892c0214edc956d09d8d
a0618aa549d1e47fc9f60cde61702e0a737470d1
refs/heads/master
<file_sep>package com.example.nutesh.twitter_search_demo; /** * Created by nutesh on 14/2/18. */ public class Authenticated { String token_type; String access_token; }
0e93a5d88ce8378f3772c9be4b2258df93e4bd95
[ "Java" ]
1
Java
Nutesh/Twitter_Search_Demo
e415e9c42b492e5d02726e0936cef464d9d1e8b6
76a55fecd6265710e95c9f7e72489da876dbdfde
refs/heads/master
<repo_name>Apezkin/ApeBook<file_sep>/README.md # ApeBook Web Applications course project 1 APEBOOK ApeBook is a microblogging service done by me for the course Web Applications. It allows users to post 500-character long microblogs and read other users’ microblogs. ApeBook doesn’t require logging in or any registration whatsoever, meaning anyone can post anything anonymously, but every user also has the right to remove other people’s posts, meaning the service is completely community moderated. The whole service is hosted by Rahti-service. A link to ApeBook as well as to the source code is in the Links section. 2 DESIGN & ARCHITECTURE The project uses Node.js as foundation. ApeBook’s frontend was done with React, which turned out to be quite easy to implement, and backend with Express, which at first was quite hard, but after finding a great tutorial video, was quite easy. The service also utilizes a Mongoose database, which is what the Express backend handles. The frontend and backend run on different containers in Rahti 3 INSTRUCTIONS FOR ENVIRONMENT SETUP FOR LOCALHOST The localhost branch on GitHub should be ready for localhosting, but if it doesn’t work, the following instructions should work. First go to expressproject folder and db.js file. Uncomment the “for local development” and comment out all the other URL handling. Also change the port to 3001 in app.js. Then start the Express and Mongoose backend and database with npm start. After the backend has connected to the database, go to reactproject folder and go to the files NewPost, Post and Posts and change the Rahti link to http://localhost:3001/posts. Then start it with npm start. Make sure that the backend and frontend work on two different URLs, meaning for localhosting, make sure that the URL //localhost:3000 doesn’t connect to both the frontend and backend, otherwise problems will arise. For example, if the backend used the port 3000, and you started the frontend before backend, no errors will come while starting, but when you go look at the main page, errors will arise quickly there, as react is trying to fetch data from the URL //localhost:3000, which react is using itself, meaning react is trying to fetch data from the webpage and not the database, resulting in an error. But if you start the backend before frontend, while starting the frontend, it will ask the user to change the port, resulting in a different URL and the program working fine. <file_sep>/reactproject/src/NewPost.js import React, { useState } from 'react'; import './App.css'; import { Link } from "react-router-dom"; function NewPost() { const [length, setLength] = useState(0); //For a visual representation of how long the post text is const charCounter = (event => { //Updating the char counter for post text event.preventDefault(); setLength(event.target.value.length); }); const submitPost = (async event => { //Post to database event.preventDefault(); const bodyData = { user: event.target.user.value, title: event.target.title.value, text: event.target.text.value } await fetch( "http://apebookb-apebook.rahtiapp.fi/posts", { method: "post", headers: {"Content-Type":"application/json"}, body: JSON.stringify(bodyData) } ); window.location.href="/posts" //Go back to mainpage after posting }); return( <div className="app"> <h1 className="title">ApeBook</h1> <h2 className="title2">New Post</h2> <Link to="/posts"> <button className="button">Back</button> </Link> <form onSubmit={submitPost} className="title2"> User:<br></br> <input className="inputUser" type="text" maxLength="20" name="user"></input><br></br> Title:<br></br> <input className="input" type="text" maxLength="50" name="title"></input><br></br> Text:<br></br> <textarea onChange={charCounter} className="input2" maxLength="500" name="text" rows="4" cols="100"></textarea> <p className="margin">Characters: {length}/500</p> <button type="submit" className="button2">Save</button> </form> </div> ); } export default NewPost;<file_sep>/expressproject/routes/posts.js const express = require("express"); const router = express.Router(); const Post = require("../models/Post"); router.get("/", async (req, res) => { //Get posts from the database try{ const posts = await Post.find(); res.json(posts); }catch(err){ res.json({message: err}); } }); router.post("/", async (req, res) => { //Post new posts to the database const post = new Post({ user: req.body.user, title: req.body.title, text: req.body.text }) try{ const savedPost = await post.save(); res.json(savedPost); }catch(err){ res.json({message: err}); } }); router.delete("/:postid", async (req, res) => { //Delete a post from the database by post id try{ const removedPost = await Post.remove({_id: req.params.postid}); res.json(removedPost); }catch(err){ res.json({message: err}); } }); router.patch("/:user", async (req, res) => { //Update a post in the database (not used) try{ const updatedPost = await Post.updateOne( {user: req.params.user}, {$set: {text: req.body.text}} ); }catch(err){ res.json({message: err}); } }); module.exports = router;<file_sep>/reactproject/src/Posts.js import React, { useState, useEffect } from 'react'; import './App.css'; import Post from "./Post"; import { Link } from "react-router-dom"; function Posts() { useEffect(() => { fetchItems(); }, []); const [posts, setPosts] = useState([]); const fetchItems = async () => { //Get all posts from the database and create new Post components with post.map let data, jsonData; data = await fetch( "http://apebookb-apebook.rahtiapp.fi/posts" ); jsonData = await data.json(); setPosts(jsonData); } return ( <div className="app"> <h1 className="title">ApeBook</h1> <h2 className="title2">Posts:</h2> <Link to="/newPost"> <button className ="button">New Post</button> </Link> {posts.map(post => ( <Post key={post._id} id={post._id} user={post.user} title={post.title} text={post.text} /> ))} </div> ); } export default Posts;<file_sep>/reactproject/src/Post.js import React from "react"; function Post (props) { const removePost = async () => { //Remove a post from database by post id (unique key created automatically by mongoose) console.log(props.id); await fetch ( "http://apebookb-apebook.rahtiapp.fi/posts/" + props.id, { method: "DELETE", headers: { "Accept":"application/json", "Content-Type":"application/json"} } ) window.location.href="/posts" }; return ( <div className="post"> <button onClick={removePost} className="removePostButton">Remove</button> <h5>{props.user}</h5> <h3>{props.title}</h3> <p className="content">{props.text}</p> </div> ); } export default Post;
7aa8265a167f6f42836ebeeac7a4f6a308fe72e6
[ "Markdown", "JavaScript" ]
5
Markdown
Apezkin/ApeBook
3693124b45eaa05ec18df9d16d256f5733deedcc
4cc9c4152d6b6926e777847e8cc46c5577dd7ff6
refs/heads/master
<repo_name>zhaol2012/IFOVST<file_sep>/webapp/Component.js sap.ui.define(["sap/ui/core/UIComponent", "sap/ui/core/ComponentSupport"], function (UIComponent, Support, ODataModel) { "use strict"; return UIComponent.extend("anders.aif.if.overview.Component", { metadata: { manifest: "json" } }); }); <file_sep>/webapp/i18n/i18n_en.properties appTitle=AIF Interface Overview appDescription=Get AIF Interface Static Overview for User TITLE=Fetch Interface Static datetime_from=Start Date Time datetime_to=End Date Time ns=Namespace ifname=Interface Name ifver=Interface Version nsrecip=Recipient Namespace recipient=Recipient count_all=All Messages count_w=Warnings count_e=Errors count_a=Technical Errors count_i=In Process count_s=Success count_c=Canceled <file_sep>/webapp/controller/App.controller.js $.sap.require("anders.aif.if.overview.model.formatter2"); sap.ui.define([ "sap/ui/core/mvc/Controller", "sap/ui/model/json/JSONModel", "../model/formatter" ], function (Controller, JSONModel, formatter) { 'use strict'; return Controller.extend("anders.aif.if.overview.controller.App", { formatter: formatter, onInit: function () { /* this.uname = this.getView().byId("UNAME"); this.dtfrom = this.getView().byId("DTFROM"); this.dtto = this.getView().byId("DTTO"); */ this.ifstatab = this.getTable(); this.oBusyIndicator = this.getTable().getNoData(); this.oModelIFSTA = this.getOwnerComponent().getModel('ifsta'); this.getView().setModel(this.oModelIFSTA); }, initBindingEventHandler: function () { let oBusyIndicator = this.oBusyIndicator; let oTable = this.getTable(); let oBinding = oTable.getBinding("rows"); oBinding.attachDataRequested(function () { oTable.setNoData(oBusyIndicator); }); oBinding.attachDataReceived(function () { oTable.setNoData(null); //Use default again ("No Data" in case no data is available) //Set title let sTitle = "Interace Statics"; let iCount = oBinding.getLength(); sTitle += "(" + iCount + ")"; oTable.setAggregation("title", sTitle); }); oBinding.attachChange(function () { let sTitle = "Interace Statics"; let iCount = oBinding.getLength(); sTitle += "(" + iCount + ")"; oTable.setAggregation("title", sTitle); }); }, onModelRefresh: function () { this.getTable().getBinding().refresh(true); }, onExit: function () { this.oBusyIndicator.destroy(); this.oBusyIndicator = null; }, /* onGetSta: function () { let pathTmp = "(p_uname='%uname%',p_datetime_from=datetimeoffset'%dtfrom%',p_datetime_to=datetimeoffset'%dtto%')"; let uname = this.uname.getValue(); let dtform = this.dtfrom.getDateValue().toISOString(); let dtto = this.dtto.getDateValue().toISOString(); let dtfromtmp = "datetimeoffset'%dtfrom%'"; let dttotmp = "datetimeoffset'%dtto%'"; pathTmp = pathTmp.replace("%uname%", uname); pathTmp = pathTmp.replace("%dtfrom%", dtform); pathTmp = pathTmp.replace("%dtto%", dtto); dtfromtmp = dtfromtmp.replace("%dtfrom%", dtform); dttotmp = dttotmp.replace("%dtto%", dtto); pathTmp = encodeURIComponent(pathTmp); //let pathReq = "/ZAND_IF_OVERVIEW" + pathTmp + "/Set?$format=json"; //let bindPath = "/ZAND_IF_OVERVIEW" + pathTmp + "/Set"; let pathReq = "/IFStats" + pathTmp + "/Set?$format=json"; let bindPath = "/IFStats" + pathTmp + "/Set"; let outthis = this; this.oModelIFSTA.read(pathReq, { method: "GET", success: function (data) { outthis.ifstatab.setTableBindingPath(bindPath); outthis.ifstatab.rebindTable(true); }, error: function (err) { console.log(err); } }); }, */ getTable: function () { return this.byId("IFSTA"); }, initBindingEventHandler: function () { var oBusyIndicator = this.oBusyIndicator; var oTable = this.getTable(); var oBinding = oTable.getBinding("rows"); oBinding.attachDataRequested(function () { oTable.setNoData(oBusyIndicator); }); oBinding.attachDataReceived(function () { oTable.setNoData(null); //Use default again ("No Data" in case no data is available) }); /* oBinding.attachChange(function (oEvent){ let sTitle = "Interace Statics"; let iCount = oBinding.getLength(); sTitle += "(" + iCount + ")"; oTable.setAggregation("title", sTitle); }); */ }, onBeforeRebindTable: function (oEvent) { let oBindingParams = oEvent.getParameter("bindingParams"); // let oFilter = new sap.ui.model.Filter("STATUS", sap.ui.model.FilterOperator.NE, "D"); //oBindingParams.preventTableBind = 'true'; }, onInitialise: function (oEvent) { //let oBindingParams = oEvent.getParameter( "bindingParams" ); }, onSearch: function (oEvent) { // let oFilter = this.byId("smartFilterBar"); // let sBindPath = oFilter.getParameterBindingPath(); let sBindPath = oEvent.getSource().getParameterBindingPath(); this.ifstatab.setTableBindingPath(sBindPath); } } ) });<file_sep>/webapp/model/formatter.js sap.ui.define([], function () { "use strict"; return { staticColorError: function (iStatic) { if (iStatic > 0) { // this.addStyleClass("staticRed"); return "Error"; } else { // this.removeStyleClass("staticRed"); } //return iStatic; }, staticColorSuccess: function (iStatic) { if (iStatic > 0) { //this.addStyleClass("staticGreen"); return "Success"; } else { //this.removeStyleClass("staticGreen"); } //return iStatic; }, staticColorInProcess: function (iStatic) { if (iStatic > 0) { //this.addStyleClass("staticYellow"); return "InProcess"; } else { //this.removeStyleClass("staticYellow"); } // return iStatic; } }; });
e331769757492f6e3b8d5bc13e1dedbe43002d2e
[ "JavaScript", "INI" ]
4
JavaScript
zhaol2012/IFOVST
7f872445b6e09dd97c6ab0ce8fe6aea82db95cee
ee444c6fbd71efc3bac4563cee93c989ae0f30fd
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ScintillaNET; using Newtonsoft.Json; namespace MatlabEditor { /// <summary> /// Editor UI clss for matlab. /// </summary> public class MEditor : UserControl { #region Contstruction public MEditor() : this(Configuration.Matlab) { } public MEditor(Configuration cnfg = Configuration.Matlab, bool AutoConfigure=true) { InitializeComponent(); m_editor = new Scintilla(); pannelEditor.Controls.Add(m_editor); m_editor.Dock = DockStyle.Fill; m_editor.TextChanged += M_editor_TextChanged; if (AutoConfigure) ConfigureEditor(cnfg); } #region Text editing private void M_editor_TextChanged(object sender, EventArgs e) { LastChanged = DateTime.Now; if (TextChanged != null) TextChanged(this, e); } /// <summary> /// Called when the text is changed. /// </summary> public event EventHandler TextChanged; #endregion #endregion #region Control members private Panel pannelEditor; Scintilla m_editor; /// <summary> /// The date when the control last changed. /// </summary> public DateTime LastChanged { get; private set; } /// <summary> /// Returns the text value for the control. /// </summary> public string Value { get { return m_editor.Text; } set { m_editor.Text = value; } } /// <summary> /// The editor; /// </summary> public Scintilla Editor { get => m_editor; } #endregion #region Editor Initialization; public void ConfigureEditor(Configuration cnfg) { switch(cnfg) { case Configuration.Matlab: ConfigGenerators.MatlabConfigGenerator.Configure(m_editor); break; } } #endregion #region Load configuration public enum Configuration { Matlab, } #endregion #region Components private void InitializeComponent() { this.pannelEditor = new System.Windows.Forms.Panel(); this.SuspendLayout(); // // pannelEditor // this.pannelEditor.Dock = System.Windows.Forms.DockStyle.Fill; this.pannelEditor.Location = new System.Drawing.Point(0, 0); this.pannelEditor.Name = "pannelEditor"; this.pannelEditor.Size = new System.Drawing.Size(423, 305); this.pannelEditor.TabIndex = 0; // // MEditor // this.Controls.Add(this.pannelEditor); this.Name = "MEditor"; this.Size = new System.Drawing.Size(423, 305); this.ResumeLayout(false); } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace MatlabEditor { /// <summary> /// Configuration file for MEditor /// </summary> public class MeditorConfig { public MeditorConfig() { } #region enums public enum AutoIndentType { /// <summary> /// No auto indent. /// </summary> None, /// <summary> /// Keep previous line indent. /// </summary> Simple, } #endregion #region configuration emembers. /// <summary> /// The lexer language in values. /// </summary> public int LexerLang { get; set; } = 1; /// <summary> /// The au /// </summary> public AutoIndentType AutoIndent { get; private set; } = AutoIndentType.Simple; /// <summary> /// A connection between colors and names. Replaces the connection between color styles and names. /// </summary> public Dictionary<string, ScintillaNET.Style> StyleByName { get; protected set; } = new Dictionary<string, ScintillaNET.Style>(); /// <summary> /// Style by number. (Use only when unnamed.); /// </summary> public Dictionary<int, ScintillaNET.Style> Styles { get; protected set; } = new Dictionary<int, ScintillaNET.Style>(); /// <summary> /// The map between names and styles for the config. /// </summary> public Dictionary<int, string> NamedStyles { get; protected set; } = new Dictionary<int, string>(); #endregion #region GetterAndSetters #endregion #region conversion public static MeditorConfig FromFile(string fname) { return FromString(System.IO.File.ReadAllText(fname)); } public static MeditorConfig FromString(string val) { return (MeditorConfig)JsonConvert.DeserializeObject(val, typeof(MeditorConfig)); } public string ToJson(bool isPretty=true) { return JsonConvert.SerializeObject(this, isPretty? Formatting.Indented : Formatting.None); } public override string ToString() { return ToJson(false); } #endregion } } <file_sep>using ScintillaNET; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MatlabEditor.ConfigGenerators { public static class MatlabConfigGenerator { public static void Configure(Scintilla editor) { // Default configuration values. editor.Lexer = (Lexer)Matlab_LexerLang; InitSyntaxColoring(editor); InitNumberMargin(editor); InitCodeFolding(editor); InitAutoComplete(editor); InitHotkeys(editor); } #region Syntax coloring static void SetTextStyle(Scintilla editor, MatlabLexerConfig t, Color c, bool isbold = false, bool isItalic = false) { SetTextStyle(editor,(int)t, c, isbold, isItalic); } static void SetTextStyle(Scintilla editor, int t, Color c, bool isbold = false, bool isItalic = false) { editor.Styles[t].ForeColor = c; editor.Styles[t].Italic = isItalic; editor.Styles[t].Bold = isbold; } static private void InitSyntaxColoring(Scintilla editor) { editor.StyleResetDefault(); SetTextStyle(editor,MatlabLexerConfig.DEFAULT, Color.DarkGray); SetTextStyle(editor,MatlabLexerConfig.COMMENT, Color.Green); SetTextStyle(editor,MatlabLexerConfig.NUMBER, Color.Red); SetTextStyle(editor,MatlabLexerConfig.STRING, Color.Purple); SetTextStyle(editor,MatlabLexerConfig.DOUBLEQUOTESTRING, Color.Purple); SetTextStyle(editor,MatlabLexerConfig.KEYWORD, Color.Blue); SetTextStyle(editor,MatlabLexerConfig.OPERATOR, Color.DarkCyan); SetTextStyle(editor,MatlabLexerConfig.COMMAND, Color.Gold); editor.SetKeywords(0, string.Join(" ", MatlabKeyWords)); } #endregion #region Numbers, Bookmarks, Code Folding /// <summary> /// the background color of the text area /// </summary> private const int BACK_COLOR = 0x2A211C; /// <summary> /// default text color of the text area /// </summary> private const int FORE_COLOR = 0xB7B7B7; /// <summary> /// change this to whatever margin you want the line numbers to show in /// </summary> private const int NUMBER_MARGIN = 1; /// <summary> /// change this to whatever margin you want the bookmarks/breakpoints to show in /// </summary> private const int BOOKMARK_MARGIN = 2; private const int BOOKMARK_MARKER = 2; /// <summary> /// change this to whatever margin you want the code folding tree (+/-) to show in /// </summary> private const int FOLDING_MARGIN = 3; /// <summary> /// set this true to show circular buttons for code folding (the [+] and [-] buttons on the margin) /// </summary> private const bool CODEFOLDING_CIRCULAR = false; static private void InitNumberMargin(Scintilla editor) { editor.Styles[Style.LineNumber].BackColor = IntToColor(BACK_COLOR); editor.Styles[Style.LineNumber].ForeColor = IntToColor(FORE_COLOR); editor.Styles[Style.IndentGuide].ForeColor = IntToColor(FORE_COLOR); editor.Styles[Style.IndentGuide].BackColor = IntToColor(BACK_COLOR); var nums = editor.Margins[NUMBER_MARGIN]; nums.Width = 30; nums.Type = MarginType.Number; nums.Sensitive = true; nums.Mask = 0; editor.MarginClick += editor_MarginClick; } static private void InitBookmarkMargin(Scintilla editor) { var margin = editor.Margins[BOOKMARK_MARGIN]; margin.Width = 20; margin.Sensitive = true; margin.Type = MarginType.Symbol; margin.Mask = (1 << BOOKMARK_MARKER); var marker = editor.Markers[BOOKMARK_MARKER]; marker.Symbol = MarkerSymbol.Circle; marker.SetBackColor(IntToColor(0xFF003B)); marker.SetForeColor(IntToColor(0x000000)); marker.SetAlpha(100); } static private void InitCodeFolding(Scintilla editor) { // Enable code folding editor.SetProperty("fold", "1"); editor.SetProperty("fold.compact", "1"); // Configure a margin to display folding symbols editor.IndentWidth = 5; editor.WrapIndentMode = WrapIndentMode.Indent; editor.IndentationGuides = IndentView.LookBoth; editor.WrapStartIndent = 5; editor.Margins[FOLDING_MARGIN].Type = MarginType.Symbol; editor.Margins[FOLDING_MARGIN].Mask = Marker.MaskAll; editor.Margins[FOLDING_MARGIN].Sensitive = true; editor.Margins[FOLDING_MARGIN].Width = 20; editor.InsertCheck += editor_InsertCheck; // Configure folding markers with respective symbols editor.Markers[Marker.Folder].Symbol = CODEFOLDING_CIRCULAR ? MarkerSymbol.CirclePlus : MarkerSymbol.BoxPlus; editor.Markers[Marker.FolderOpen].Symbol = CODEFOLDING_CIRCULAR ? MarkerSymbol.CircleMinus : MarkerSymbol.BoxMinus; editor.Markers[Marker.FolderEnd].Symbol = CODEFOLDING_CIRCULAR ? MarkerSymbol.CirclePlusConnected : MarkerSymbol.BoxPlusConnected; editor.Markers[Marker.FolderMidTail].Symbol = MarkerSymbol.TCorner; editor.Markers[Marker.FolderOpenMid].Symbol = CODEFOLDING_CIRCULAR ? MarkerSymbol.CircleMinusConnected : MarkerSymbol.BoxMinusConnected; editor.Markers[Marker.FolderSub].Symbol = MarkerSymbol.VLine; editor.Markers[Marker.FolderTail].Symbol = MarkerSymbol.LCorner; // Enable automatic folding editor.AutomaticFold = (AutomaticFold.Show | AutomaticFold.Click | AutomaticFold.Change); } static private void editor_InsertCheck(object sender, InsertCheckEventArgs e) { Scintilla editor = (Scintilla)sender; if ((e.Text.EndsWith("\r") || e.Text.EndsWith("\n"))) { var curLine = editor.LineFromPosition(e.Position); var curLineText = editor.Lines[curLine].Text; var indent = System.Text.RegularExpressions.Regex.Match(curLineText, @"^\s*"); e.Text += indent.Value; // Add indent following "\r\n" // Current line end with bracket? if (System.Text.RegularExpressions.Regex.IsMatch(curLineText, @"{\s*$")) e.Text += '\t'; // Add tab } } static private void editor_MarginClick(object sender, MarginClickEventArgs e) { Scintilla editor = (Scintilla)sender; if (e.Margin == BOOKMARK_MARGIN) { // Do we have a marker for this line? const uint mask = (1 << BOOKMARK_MARKER); var line = editor.Lines[editor.LineFromPosition(e.Position)]; if ((line.MarkerGet() & mask) > 0) { // Remove existing bookmark line.MarkerDelete(BOOKMARK_MARKER); } else { // Add bookmark line.MarkerAdd(BOOKMARK_MARKER); } } } #endregion #region AutoComplete static void InitAutoComplete(Scintilla editor) { editor.CharAdded += editor_CharAdded1; } static private void editor_CharAdded1(object sender, CharAddedEventArgs e) { Scintilla editor = (Scintilla)sender; // Find the word start var currentPos = editor.CurrentPosition; var wordStartPos = editor.WordStartPosition(currentPos, true); // Display the autocompletion list var lenEntered = currentPos - wordStartPos; if (lenEntered > 0) { if (!editor.AutoCActive) editor.AutoCShow(lenEntered, String.Join(" ",MatlabKeyWords)); // "abstract as base break case catch checked continue default delegate do else event explicit extern false finally fixed for foreach goto if implicit in interface internal is lock namespace new null object operator out override params private protected public readonly ref return sealed sizeof stackalloc switch this throw true try typeof unchecked unsafe using virtual while"); } } #endregion #region keys config private static void InitHotkeys(Scintilla editor) { // register the hotkeys with the form //HotKeyManager.AddHotKey(this, OpenSearch, Keys.F, true); //HotKeyManager.AddHotKey(this, OpenFindDialog, Keys.F, true, false, true); //HotKeyManager.AddHotKey(this, OpenReplaceDialog, Keys.R, true); //HotKeyManager.AddHotKey(this, OpenReplaceDialog, Keys.H, true); //HotKeyManager.AddHotKey(this, Uppercase, Keys.U, true); //HotKeyManager.AddHotKey(this, Lowercase, Keys.L, true); //HotKeyManager.AddHotKey(this, ZoomIn, Keys.Oemplus, true); //HotKeyManager.AddHotKey(this, ZoomOut, Keys.OemMinus, true); //HotKeyManager.AddHotKey(this, ZoomDefault, Keys.D0, true); //HotKeyManager.AddHotKey(this, CloseSearch, Keys.Escape); // remove conflicting hotkeys from scintilla editor.ClearCmdKey(Keys.Control | Keys.S); editor.ClearCmdKey(Keys.Control | Keys.F); editor.ClearCmdKey(Keys.Control | Keys.R); editor.ClearCmdKey(Keys.Control | Keys.H); editor.ClearCmdKey(Keys.Control | Keys.L); editor.ClearCmdKey(Keys.Control | Keys.U); } #endregion #region Helpers public static Color IntToColor(int rgb) { return Color.FromArgb(255, (byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb); } #endregion #region Definitions public const int Matlab_LexerLang = 32; public enum MatlabLexerConfig { DEFAULT = 0, COMMENT = 1, COMMAND = 2, NUMBER = 3, KEYWORD = 4, STRING = 5, OPERATOR = 6, IDENTIFIER = 7, DOUBLEQUOTESTRING = 8, } public static string[] MatlabKeyWords = { "break" , "case" , "catch" , "classdef" , "continue" , "else" , "elseif" , "end" , "for" , "function" , "global" , "if" , "otherwise" , "parfor" , "persistent" , "return" , "spmd" , "switch" , "try" , "methods", "properties", "while" }; #endregion } }
cad1f6c3c02b1cb9c1af8f9dd67fe700af72ca20
[ "C#" ]
3
C#
merilesLab223/CMCryoSys
25bd1cd5112a41cfdf03d8aa7b7133152e5c2820
54aeba5e43c9bd634d739a09eda4ca4c4f7c6751
refs/heads/master
<file_sep>source 'https://rubygems.org' ruby '2.1.0' # gems requiring credentials for 3rd party services gem 'config_env' gem 'aws-sdk' # SQS Message Queue gem 'httparty' <file_sep>require_relative 'bundle/bundler/setup' require 'aws-sdk' require 'config_env' array = ["apple", "apple", "banana", "apple", "happy", "QQ", "be happy", "cheer up!", "banana", "happy", "sunshine", "sunshine", "QQ", "apple", "happy"] ConfigEnv.path_to_config("#{__dir__}/config/config_env.rb") sqs = Aws::SQS::Client.new() q_url = sqs.get_queue_url(queue_name: 'searched_keyword').queue_url array.each do |word| msg = word resp = sqs.send_message({ queue_url: q_url, # required message_body: msg.to_json # required }) if resp.successful? puts "successful, #{word}" else puts "failed, #{word}" end end <file_sep>require_relative 'bundle/bundler/setup' require 'aws-sdk' require 'config_env' require 'httparty' require 'json' ConfigEnv.path_to_config("#{__dir__}/config/config_env.rb") sqs = Aws::SQS::Client.new() q_url = sqs.get_queue_url(queue_name: 'Kiwi_messenger').queue_url poller = Aws::SQS::QueuePoller.new(q_url) # set hash default function count = Hash.new{|h,k| h[k] = {'keyword'=>k,'count'=>0 }} # get msg and count begin poller.poll(wait_time_seconds:nil, idle_timeout:2) do |msg| word = msg.body.delete('"') #set default if count.has_key?(word) count[word] end count[word]['count'] += 1 end rescue AWS::SQS::Error::ServiceError end count = count.sort_by{|k,v| v['count']}.reverse.to_h countarray = count.values countarray.each_index do |i| countarray[i]['rank']=i+1 end # print countarray h = {'results' => countarray.to_json} print h # post to api server begin HTTParty.post( 'https://kiwi-api.herokuapp.com/api/v1/popularity', :header => {'Content-Type' => 'application/json'}, :body => {'results' => countarray.to_json}) rescue puts "post error" end
309c61cd58a8793a3e15ce64122da2d0ad07ab2d
[ "Ruby" ]
3
Ruby
Kiwi-Learn/kiwi-popularworker
f9c88972a49e9cebf9a5276370c1893bebc57209
ff5fef697e10f7287f41cc9c7e92c00f7879cf8a
refs/heads/master
<repo_name>taradownes/barbgoodman<file_sep>/app.js const express = require("express"), bodyParser = require("body-parser"), exphbs = require("express-handlebars"), nodemailer = require("nodemailer"), app = express() app.engine("handlebars", exphbs()); app.set("view engine", "handlebars"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(__dirname)); //ROUTES //HOME app.get("/", function(req, res){ res.render("index"); }); //MYTEAM app.get("/team", function(req, res){ res.render("team"); }); //SERVICES app.get("/services", function(req, res){ res.render("services"); }) app.get("/philanthropy", function(req, res){ res.render("phil"); }); //CONTACT app.get("/contact", function(req, res){ res.render("contact"); }); //TESTIMONIALS app.listen(process.env.PORT, process.env.IP, function(){ console.log("server started"); }); // app.listen(3000, function(){ // console.log("server started"); // });
53480264414896986a7d7378dbfdf3dde223c76f
[ "JavaScript" ]
1
JavaScript
taradownes/barbgoodman
6800d5d6e7e0f297f72e35570dcba5fd9056a13b
9889f1ff459b7286e1f80578ab24cd2d8bebe71f
refs/heads/master
<file_sep>import time import boto3 import funcs aws_region = "eu-west-2" availability_zone = "eu-west-2a" volume_size = 10 ec2 = boto3.client("ec2", region_name=aws_region) # Create new volume funcs.create_volume(ec2, availability_zone) <file_sep>import boto3 #create volume def create_volume(ec2_client, availability_zone, DryRunFlag=False): try: response= ec2_client.create_volume( AvailabilityZone=availability_zone, Encrypted=False, #Iops=100, #KmsKeyId='string', Size=10, #SnapshotId='string', VolumeType='gp2', #standard'|'io1'|'gp2'|'sc1'|'st1', DryRun=DryRunFlag ) #pprint(response) if response['ResponseMetadata']['HTTPStatusCode']== 200: volume_id= response['VolumeId'] print('***volume:', volume_id) ec2_client.get_waiter('volume_available').wait( VolumeIds=[volume_id], DryRun=DryRunFlag ) print('***Success!! volume:', volume_id, 'created...') except Exception as e: print('***Failed to create the volume...') print(type(e), ':', e) def attach_volume(volume_id, instance_id, DryRunFlag=False): try: print('***attaching volume:', volume_id, 'to:', instance_id) response= ec2_client.attach_volume( Device=device, InstanceId=instance_id, VolumeId=volume_id, DryRun=DryRunFlag ) #pprint(response) if response['ResponseMetadata']['HTTPStatusCode']== 200: ec2_client.get_waiter('volume_in_use').wait( VolumeIds=[volume_id], DryRun=False ) print('***Success!! volume:', volume_id, 'is attached to instance:', instance_id) except Exception as e: print('***Error - Failed to attach volume:', volume_id, 'to the instance:', instance_id) print(type(e), ':', e)
41b5ce5def01351f43c59aa456a7dd9eab5b9743
[ "Python" ]
2
Python
pabloli84/scylla_attach_volume
83ffd4ecbdea4af023f31039eebba9fef78a4345
195552948d26adf5f34359f8dc29c1f76e04ce40
refs/heads/main
<file_sep>videos that I used for code training --- downloaded from Youtube via [**youtube-dl**](https://www.youtube-dl.org/) [**animals.mp4**](https://www.youtube.com/watch?v=5adoTkOnBVw) [**v_cars.mp4**](https://www.youtube.com/watch?v=q5PPNZiu52w&t=39s) <file_sep>2021 Jun. 7 --- use [PyRetri](https://github.com/PyRetri/PyRetri) to search one frame from a video ## use opencv to extract frames [extract_frames_v2.py](https://github.com/fu-yanyuan/video_retrieval/blob/main/code_training/extract_frames_v2.py) this will save the frames(1 fps) into the *gallery* as required: and press 's' to save the key frames that i want to search in the future into *query* ```shell # dataset need to be splited v_cars ├── gallery │ └── honda │ ├──xxx.jpg │ └──··· └── query └── honda ├──xxx.jpg └──··· ``` ## use PyRetri to do the single frame index ```shell # make data json $ python3 main/make_data_json.py -d data/v_cars/gallery/ -sp data_jsons/v_cars_gallery.json -t general $ python3 main/make_data_json.py -d data/v_cars/query/ -sp data_jsons/v_cars_query.json -t general # extract features $ CUDA_VISIBLE_DEVICES=4 python3 main/extract_feature.py -dj data_jsons/v_cars_gallery.json -sp data/features/v_cars/gallery/ -cfg configs/v_cars.yaml $ CUDA_VISIBLE_DEVICES=4 python3 main/extract_feature.py -dj data_jsons/v_cars_query.json -sp data/features/v_cars/query/ -cfg configs/v_cars.yaml # single image index $ CUDA_VISIBLE_DEVICES=4 python3 main/test_video.py -cfg configs/v_cars.yaml ``` ## experiment results [v_cars.mp4](https://www.youtube.com/watch?v=q5PPNZiu52w) ### query <img src="image_3706_q.jpg" width="224"/> ### top 5 results <img src="55.png" width="224"/><img src="56.png" width="224"> <img src="70.png" width="224"/><img src="72.png" width="224"/><img src="73.png" width="224"/> ### query <img src="image_2812_q.jpg" width="224"/> ### top 5 results <img src="16.png" width="224"/><img src="17.png" width="224"/> <img src="61.png" width="224"/> <img src="144.png" width="224"/><img src="145.png" width="224"/> <file_sep>import cv2 as cv # videoName = "Honda_NSX" videoFile = "videos/Honda_NSX.mp4" imagesFolder_gallery = "v_cars/gallery/honda" imagesFolder_query = "v_cars/query/honda" cap = cv.VideoCapture(videoFile) frameRate = cap.get(5) # refer to cap.get() print("#frames =", cap.get(7)) # total number of frames in this video print("fps =", cap.get(5)) # framerate print("h, w = ", cap.get(4), cap.get(3)) while cap.isOpened(): frameID = cap.get(1) # current frame number isTrue, frame = cap.read() if not isTrue: print("can't receive any frame (stream end?)") break cv.imshow('frame', frame) # resize # to be done in the PyRetri # save frames if frameID % round(frameRate) == 0: fileName = imagesFolder_gallery + "/image_" + str(int(frameID/round(frameRate))) + ".jpg" cv.imwrite(fileName, frame) # quit or save for query k = cv.waitKey(20) if k == ord('q'): break elif k == ord('s'): fileName_2 = imagesFolder_query + "/image_" + str(int(frameID)) + "_q.jpg" cv.imwrite(fileName_2, frame) cap.release() print("done!")
7eaf7e04fee9798bb36baa0072d368afeb542a67
[ "Markdown", "Python" ]
3
Markdown
fu-yanyuan/video_retrieval
2bf8c02687d9271ff8ecd75cab9be90e0dda8096
200d4cab4187b37ae52d411d0873ae02f319e753
refs/heads/master
<file_sep>import com.modeliosoft.modelio.javadesigner.annotations.objid; @objid ("85027495-16e8-4b24-807d-686372abd03a") public class Grille { @objid ("b942a6bc-4b32-4f4f-9161-530ec1dc9632") private int tailleAbscisse; @objid ("66fb2834-274c-4657-a063-e0fb8b9508ca") private int tailleOrdonnee; @objid ("db56e7f3-7603-4b7b-b037-06fc240cb0ef") public void initGrille() { } @objid ("d00ae0aa-998a-4df2-a1a8-0d979d8721b4") public void affichage() { } @objid ("b613b8eb-fe95-4b3f-9f67-c8e642685004") public boolean caseVide(int abscisse, int ordonnee) { } @objid ("35fddacf-8c75-43ce-ac36-07c01c9ff2be") int getTailleAbscisse() { // Automatically generated method. Please delete this comment before entering specific code. return this.tailleAbscisse; } @objid ("395e860d-3c99-4fe9-a2c4-dbac2c95b747") void setTailleAbscisse(int value) { // Automatically generated method. Please delete this comment before entering specific code. this.tailleAbscisse = value; } @objid ("801fa341-55cf-4b8f-b22b-4a2774cd24bb") int getTailleOrdonnee() { // Automatically generated method. Please delete this comment before entering specific code. return this.tailleOrdonnee; } @objid ("e58eb97a-2cf4-473a-ab34-ec380a45d005") void setTailleOrdonnee(int value) { // Automatically generated method. Please delete this comment before entering specific code. this.tailleOrdonnee = value; } } <file_sep> public class Vetement{ private String nom; private int encombrement; private int[] solidite; //*******************CONSTRUCTEUR PAR DEFAUT************************ public Vetement (){ this.nom = "default"; this.encombrement = 0; this.solidite = new int[2]; } //***************CONSTRUCTEUR CHAMPS A CHAMPS********************** public Vetement(String nom,int encombrement,int[] solidite){ this.nom = nom; this.encombrement =encombrement; this.solidite=solidite; } //*********************EQUIPER************************************* public void equiper() { } //********************DESQUIPER************************************ public void desequiper () { } //*******************ACCESSEUR************************************ public String getNom(){ return this.nom; } public int getEncombrement() { return this.encombrement; } public int[] getSolidite() { return this.solidite; } //****************MUTATEUR************************************ public void setNom(String nom){ this.nom = nom; } public void setEncombrement(int value) { this.encombrement = value; } public void setSolidite(int[] value) { this.solidite = value; } //********************TO STRING****************************** public String toString(){ return "le nom"+this.nom+"encombrement"+this.encombrement+"solidite"+this.solidite; } } <file_sep> import java.util.Scanner; public class Menu { //**********************************DEMARRER************************************** public void demarrer(){ int a=0; while(a<1||a>3){ Scanner sc= new Scanner(System.in); System.out.println(" -----------------"); System.out.println(" |EHPTMMMORPGSVR |"); System.out.println(" -----------------"); System.out.println("\n-----------------------------------------"); System.out.println(" Que voulez-vous:"); System.out.println("-----------------------------------------"); System.out.println("\n1-Nouvelle Partie"); System.out.println("2-Continuer"); System.out.println("3-Quitter le Jeu"); System.out.println("-----------------------------------------"); a= sc.nextInt(); if(a==1){ nouvellePartie(); } else if(a==2){ //jouer(); } else if(a==3){ System.out.println("\nVous avez quitter le jeu"); } else{ System.out.println("\n--------------------------------------------"); System.out.println("Le numéro que vous avez saisie n'est pas bon"); System.out.println("--------------------------------------------"); } sc.close(); } } //**********************************NOUVELLE PARTIE************************************** public void nouvellePartie(){ Grille g= new Grille(); int a,i=0; Scanner sc= new Scanner(System.in); g.initGrille(); Personnage p = new Personnage(g.creerPersonnage()); while(i<15){ System.out.println("\nAttribuer les caractÈristiques : \nReste "+(15-i)+" points ‡ attribuer\n\n1- Force : "+p.getForce()+"\n2- Adresse : "+p.getAdresse()+"\n3- Resistance "+p.getResistance()); a = sc.nextInt(); if(a>0&&a<4){ if(a==1){ p.setForce(p.getForce()+1); } else if(a==2){ p.setAdresse(p.getAdresse()+1); } else{ p.setResistance(p.getResistance()+1); } i++; } } int b=0; System.out.println("\nChoisir un Èquipement de dÈpart : \n\n1- Epee en bois\n2- Vetements en cuir"); a=sc.nextInt(); while(b==1||b==2){ int q[] = new int[2]; q[0]=1; q[1]=2; if(b==1){ p.setArmeGauche(new Arme("Epee en bois",q,q)); } if(b==2){ p.setVetement(new Vetement("Vetements en cuir",1,q)); } } g.genererMurAleatoire(105); g.apparaitreMonstre(); g.apparaitreObjetAleatoire(10); g.affichageGrille(); jouer(g,p); } public void jouer(Grille g, Personnage p){ int a=0; while(a!=5){ a=0; while(a<1||a>6){ Scanner sc= new Scanner(System.in); System.out.println("\nAction :\n\n1- Se Deplacer\n2- Attaquer\n3- Objets\n4- Ramasser\n5- Finir Tour\n6-Quitter le jeu"); a=sc.nextInt(); if(a==1){ g.initDeplacer(p); } else if(a==2){ p.attaquer(g.apparaitreMonstre(), new Arme()); } else if(a==6){ System.out.println("Vous avez quittez le jeu"); } } } } }<file_sep>import com.modeliosoft.modelio.javadesigner.annotations.objid; @objid ("aa3f8606-3217-4360-9df0-ca27a90a04b2") public class Potion extends Equipements { @objid ("03596406-2330-432b-97fa-3b18eeaf6e82") private String caracteristique; @objid ("a127afe3-a877-44ed-96da-8f2d14054a03") private int bonus; @objid ("52de878c-5d58-4725-8806-d458d6ad59d1") public void utiliser() { } @objid ("39f9b37e-2163-4953-b97c-c7b0f0ed1f53") String getCaracteristique() { // Automatically generated method. Please delete this comment before entering specific code. return this.caracteristique; } @objid ("08d57e92-a670-417a-9750-6b0c52637538") void setCaracteristique(String value) { // Automatically generated method. Please delete this comment before entering specific code. this.caracteristique = value; } @objid ("23534579-5a58-46b9-888d-16bfbda99dd4") int getBonus() { // Automatically generated method. Please delete this comment before entering specific code. return this.bonus; } @objid ("6a0a97ee-14fa-47a0-9b50-fd64ba6b38d2") void setBonus(int value) { // Automatically generated method. Please delete this comment before entering specific code. this.bonus = value; } } <file_sep> import java.util.ArrayList; import java.util.Scanner; public class Equipements { private ArrayList<Object> equipement; public Equipements(){ this.equipement=new ArrayList<Object>(); } //********************CONSTRUCTEUR PAR DEFAUT************************* public Equipements( ArrayList<Object> equipement){ this.equipement=equipement; } //********************CHOISIR OBJET*********************************** public void choisirObjet() { int a=0; Scanner sc= new Scanner(System.in); do{ System.out.println("Veuillez saisir l'objet que vous voulez\n"); System.out.println("1-Armes"); System.out.println("2-Potions"); System.out.println("3-Vetements"); a=sc.nextInt(); }while(a<1 && a>3); if(a==1){// arme choisirArme(); } if(a==2){// potion choisirPotion(); } if(a==3){// vetements choisirVetement(); } sc.close(); } //**********************CHOISIR ARME****************************************** public void choisirArme(){ System.out.println("Veuillez saisir l'objet que vous voulez\n"); for(int i=0;i<this.equipement.size();i++){ Arme a= (Arme)this.equipement.get(i); System.out.println(a); } // afficher tout les elements du tableau qui on type de arme } //**********************CHOISIR POTION****************************************** public void choisirPotion(){ System.out.println("Veuillez saisir l'objet que vous voulez\n"); for(int i=0;i<this.equipement.size();i++){ Potion p= (Potion)this.equipement.get(i); System.out.println(p); } // afficher tout les elements du tableau qui on type de arme } //**********************CHOISIR VETEMENT****************************************** public void choisirVetement(){ System.out.println("Veuillez saisir l'objet que vous voulez\n"); for(int i=0;i<this.equipement.size();i++){ Vetement v= (Vetement)this.equipement.get(i); System.out.println(v); } // afficher tout les elements du tableau qui on type de arme } //**********************ACCESSEUR****************************************** public ArrayList<Object> getequipement() { return this.equipement; } //**********************MUTATEUR****************************************** public void setequipement(ArrayList<Object> equipement) { this.equipement = equipement; } } <file_sep>import com.modeliosoft.modelio.javadesigner.annotations.objid; @objid ("08194e3f-0dbe-4002-a9ed-897d56803826") public class Arme extends Equipements { @objid ("79ce5480-e2d2-4300-b4a5-d12f95a511a1") private int impact; @objid ("b3cd7ba5-841f-4a48-88a6-7b098bb64169") private int maniabilite; @objid ("79ca5409-f583-4bf8-97cc-8d9403a69d2e") public void equiper() { } @objid ("4fad37e0-479b-4283-8244-375d88b585da") public void desequiper() { } @objid ("af89d645-aa7c-4e1f-82c4-861b5d154f64") int getImpact() { // Automatically generated method. Please delete this comment before entering specific code. return this.impact; } @objid ("7ffab20d-0946-4ce3-994a-273861e07377") void setImpact(int value) { // Automatically generated method. Please delete this comment before entering specific code. this.impact = value; } @objid ("98c5ae69-2b75-437d-9124-d35e6ce8132e") int getManiabilite() { // Automatically generated method. Please delete this comment before entering specific code. return this.maniabilite; } @objid ("96b9d235-1c9f-4ca5-9183-f4b8b21450ad") void setManiabilite(int value) { // Automatically generated method. Please delete this comment before entering specific code. this.maniabilite = value; } }
9b9d36f70c8eb999e482ec991c564f4359df554c
[ "Java" ]
6
Java
alain1996/projet_tutore_S2
3c189d701bbe300878d0a9bf134bea3ea351f48f
9342810fad073553f6de633290206f51c9d77e4d
refs/heads/main
<file_sep># 시발 좀 되길 testing 1. 되나요? 1. 재접속<file_sep>package com.scmaster.ict; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Handles requests for the application home page. */ @Controller public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); // 지도를 띄우는 코드 작성 @RequestMapping(value = "/educate01") public String educate01() { return "educate01"; } // 지도를 띄우는 코드 작성 @RequestMapping(value = "/educate02") public String educate02() { return "educate02"; } // 지도를 띄우는 코드 작성 @RequestMapping(value = "/educate03") public String educate03() { return "educate03"; } // 지도를 띄우는 코드 작성 @RequestMapping(value = "/educate04") public String educate04() { return "educate04"; } // 지도를 띄우는 코드 작성 @RequestMapping(value = "/educate05") public String educate05() { return "educate05"; } // 지도를 띄우는 코드 작성 @RequestMapping(value = "/educate06") public String educate06() { return "educate06"; } }
3665fb8cefd4fe5da3886fd05f19f38821eb3812
[ "Markdown", "Java" ]
2
Markdown
Yangcamel/Covid19Chaser
a78021f6a9d4d6c066af94eacd4f47dd83894fda
244bba325f4d233907be97f900acc063290a213b
refs/heads/master
<file_sep>var request = require('request'); var key = ''; var endpoint = ''; var emailAddr = ''; var userPass = ''; request({ url: endpoint, //URL to hit qs: {from: 'User Post Test', time: +new Date()}, //Query string data method: 'POST', headers: { 'Authorization': key }, json: { user: { 'email': emailAddr, 'password': <PASSWORD>, } }, }, function(error, response, body){ if(error) { console.log(error); } else{ console.log('Status: ' + response.statusCode); console.log('BODY: \n'); console.log(body); console.log(response.statusCode); } }); <file_sep>// A little messy, just hits all the get routes on the API // Make sure to use your own authorization key, also you will need to make sure the url is correct var request = require('request'); //Authorization key var key = ''; //API url - Don't forget to include http or https var apiURL = ''; //Get Account //With auth request({ url: apiURL + '/account', method: 'GET', timeout: 2000, headers: { 'Authorization': key }, }, function (error, response, body) { //no error and 200 response if (!error && response.statusCode == 200) { console.log("\nGET - /account"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } //if there is an error then else if(error){ console.log("\nGET - /account"); console.log("With Authorization Header - ERROR"); console.log(error); } else { console.log("\nGET - /account"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } }); //Get Account //without auth request({ url: apiURL + '/account', method: 'GET', timeout: 2000, headers: { 'Authorization': '' }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /account"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /account"); console.log("Without Authorization Header - ERROR"); console.log(error); } else { console.log("\nGET - /account"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } }); //-------------------------------------------------------------------------- //Get Managers //With auth request({ url: apiURL + '/managers', method: 'GET', timeout: 2000, headers: { 'Authorization': key }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /managers"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /managers"); console.log("With Authorization Header - ERROR"); console.log(error); } else { console.log("\nGET - /managers"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } }); //Get Managers //without auth request({ url: apiURL + '/managers', method: 'GET', timeout: 2000, headers: { 'Authorization': '' }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /managers"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /managers"); console.log("Without Authorization Header - ERROR"); console.log(error); } else { console.log("\nGET - /managers"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } }); //-------------------------------------------------------------------------- //Get Manager Records //With auth request({ url: apiURL + '/manager/573f96a0436d05664056729b/records', method: 'GET', timeout: 2000, headers: { 'Authorization': key }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /managers/id/records"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /managers/id/records - ERROR"); console.log("With Authorization Header"); console.log(error); } else{ console.log("\nGET - /managers/id/records"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } }); //Get Managers Records //without auth request({ url: apiURL + '/manager/573f96a0436d05664056729b/records', method: 'GET', timeout: 2000, headers: { 'Authorization': '' }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /managers/id/records"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /managers/id/records - ERROR"); console.log("Without Authorization Header"); console.log(error); } else{ console.log("\nGET - /managers/id/records"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } }); //-------------------------------------------------------------------------- //Get tag //With auth request({ url: apiURL + '/tag', method: 'GET', timeout: 2000, headers: { 'Authorization': key }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /tag"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /tag"); console.log("With Authorization Header - ERROR"); console.log(error); } else{ console.log("\nGET - /tag"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } }); //Get tag //without auth request({ url: apiURL + '/tag', method: 'GET', timeout: 2000, headers: { 'Authorization': '' }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /tag"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /tag"); console.log("Without Authorization Header - ERROR"); console.log(error); } else{ console.log("\nGET - /tag"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } }); //-------------------------------------------------------------------------- //Get field //With auth request({ url: apiURL + '/field', method: 'GET', timeout: 2000, headers: { 'Authorization': key }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /field"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /field"); console.log("With Authorization Header - ERROR"); console.log(error); } else{ console.log("\nGET - /field"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } }); //Get field //without auth request({ url: apiURL + '/field', method: 'GET', timeout: 2000, headers: { 'Authorization': '' }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /field"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /field"); console.log("Without Authorization Header - ERROR"); console.log(error); } else{ console.log("\nGET - /field"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } }); //-------------------------------------------------------------------------- //Get reminder //With auth request({ url: apiURL + '/reminder', method: 'GET', timeout: 2000, headers: { 'Authorization': key }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /reminder"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /reminder"); console.log("With Authorization Header - ERROR"); console.log(error); } else{ console.log("\nGET - /reminder"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } }); //Get reminder //without auth request({ url: apiURL + '/reminder', method: 'GET', timeout: 2000, headers: { 'Authorization': '' }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /reminder"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /reminder"); console.log("Without Authorization Header - ERROR"); console.log(error); } else{ console.log("\nGET - /reminder"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } }); //-------------------------------------------------------------------------- //Get user //With auth request({ url: apiURL + '/user/5<PASSWORD>', method: 'GET', timeout: 2000, headers: { 'Authorization': key }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /user/id"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /user/id"); console.log("With Authorization Header - ERROR"); console.log(error); } else{ console.log("\nGET - /user/id"); console.log("With Authorization Header"); console.log(response.statusCode); console.log(body); } }); //Get reminder //without auth request({ url: apiURL + '/user/573e589432178b732c4b9a0d', method: 'GET', timeout: 2000, headers: { 'Authorization': '' }, }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("\nGET - /user/id"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } else if(error){ console.log("\nGET - /user/id"); console.log("Without Authorization Header - ERROR"); console.log(error); } else{ console.log("\nGET - /user/id"); console.log("Without Authorization Header"); console.log(response.statusCode); console.log(body); } }); <file_sep>## mbTester These are just a couple of the tests from the fuzzing on the API I did. These should give you somewhat of an idea on how posts/gets with the API will work. However on the client we will be using HttpProvider instead of the NPM request package. <file_sep>var request = require('request'); var key = ''; var endpoint = ''; var orgName = ''; var accountName = ''; request({ url: endpoint, //URL to hit qs: {from: 'Manager Post Test', time: +new Date()}, //Query string data method: 'POST', headers: { 'Authorization': key, }, json: { manager: { 'organization':orgName, 'account': accountName, }, }, }, function(error, response, body){ if(error) { console.log(error); } else{ console.log('Status: ' + response.statusCode); console.log('BODY: \n'); console.log(body); console.log(response.statusCode); } });
543d130b8aa873d22940c4cf8935ee3949e850c5
[ "JavaScript", "Markdown" ]
4
JavaScript
JCron245/mbTester
68f9e67091e7050e6c6e8c330a623be17cb1eaf9
e8a5892eed6211e1d75e24907405aa089d6f5729
refs/heads/master
<repo_name>ninjaparade/invoice-ninja<file_sep>/app/Http/Controllers/QuoteApiController.php <?php namespace App\Http\Controllers; use Utils; use Response; use App\Models\Invoice; use App\Ninja\Repositories\InvoiceRepository; class QuoteApiController extends Controller { protected $invoiceRepo; public function __construct(InvoiceRepository $invoiceRepo) { $this->invoiceRepo = $invoiceRepo; } public function index() { $invoices = Invoice::scope() ->with('client', 'user') ->where('invoices.is_quote', '=', true) ->orderBy('created_at', 'desc') ->get(); $invoices = Utils::remapPublicIds($invoices); $response = json_encode($invoices, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(count($invoices)); return Response::make($response, 200, $headers); } /* public function store() { $data = Input::all(); $invoice = $this->invoiceRepo->save(false, $data, false); $response = json_encode($invoice, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(); return Response::make($response, 200, $headers); } */ } <file_sep>/app/Http/Controllers/InvoiceController.php <?php namespace App\Http\Controllers; use Auth; use Session; use Utils; use View; use Input; use Cache; use Redirect; use DB; use Event; use URL; use Datatable; use finfo; use Request; use DropdownButton; use App\Models\Invoice; use App\Models\Invitation; use App\Models\Client; use App\Models\Account; use App\Models\Product; use App\Models\Country; use App\Models\TaxRate; use App\Models\Currency; use App\Models\Size; use App\Models\Industry; use App\Models\PaymentTerm; use App\Models\InvoiceDesign; use App\Models\AccountGateway; use App\Models\Activity; use App\Models\Gateway; use App\Ninja\Mailers\ContactMailer as Mailer; use App\Ninja\Repositories\InvoiceRepository; use App\Ninja\Repositories\ClientRepository; use App\Ninja\Repositories\TaxRateRepository; use App\Events\InvoiceViewed; class InvoiceController extends BaseController { protected $mailer; protected $invoiceRepo; protected $clientRepo; protected $taxRateRepo; public function __construct(Mailer $mailer, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, TaxRateRepository $taxRateRepo) { parent::__construct(); $this->mailer = $mailer; $this->invoiceRepo = $invoiceRepo; $this->clientRepo = $clientRepo; $this->taxRateRepo = $taxRateRepo; } public function index() { $data = [ 'title' => trans('texts.invoices'), 'entityType' => ENTITY_INVOICE, 'columns' => Utils::trans(['checkbox', 'invoice_number', 'client', 'invoice_date', 'invoice_total', 'balance_due', 'due_date', 'status', 'action']), ]; $recurringInvoices = Invoice::scope()->where('is_recurring', '=', true); if (Session::get('show_trash:invoice')) { $recurringInvoices->withTrashed(); } else { $recurringInvoices->join('clients', 'clients.id', '=', 'invoices.client_id') ->where('clients.deleted_at', '=', null); } if ($recurringInvoices->count() > 0) { $data['secEntityType'] = ENTITY_RECURRING_INVOICE; $data['secColumns'] = Utils::trans(['checkbox', 'frequency', 'client', 'start_date', 'end_date', 'invoice_total', 'action']); } return View::make('list', $data); } public function clientIndex() { $invitationKey = Session::get('invitation_key'); if (!$invitationKey) { return Redirect::to('/setup'); } $invitation = Invitation::with('account')->where('invitation_key', '=', $invitationKey)->first(); $account = $invitation->account; $color = $account->primary_color ? $account->primary_color : '#0b4d78'; $data = [ 'color' => $color, 'hideLogo' => $account->isWhiteLabel(), 'title' => trans('texts.invoices'), 'entityType' => ENTITY_INVOICE, 'columns' => Utils::trans(['invoice_number', 'invoice_date', 'invoice_total', 'balance_due', 'due_date']), ]; return View::make('public_list', $data); } public function getDatatable($clientPublicId = null) { $accountId = Auth::user()->account_id; $search = Input::get('sSearch'); return $this->invoiceRepo->getDatatable($accountId, $clientPublicId, ENTITY_INVOICE, $search); } public function getClientDatatable() { //$accountId = Auth::user()->account_id; $search = Input::get('sSearch'); $invitationKey = Session::get('invitation_key'); $invitation = Invitation::where('invitation_key', '=', $invitationKey)->first(); if (!$invitation || $invitation->is_deleted) { return []; } $invoice = $invitation->invoice; if (!$invoice || $invoice->is_deleted) { return []; } return $this->invoiceRepo->getClientDatatable($invitation->contact_id, ENTITY_INVOICE, $search); } public function getRecurringDatatable($clientPublicId = null) { $query = $this->invoiceRepo->getRecurringInvoices(Auth::user()->account_id, $clientPublicId, Input::get('sSearch')); $table = Datatable::query($query); if (!$clientPublicId) { $table->addColumn('checkbox', function ($model) { return '<input type="checkbox" name="ids[]" value="'.$model->public_id.'" '.Utils::getEntityRowClass($model).'>'; }); } $table->addColumn('frequency', function ($model) { return link_to('invoices/'.$model->public_id, $model->frequency); }); if (!$clientPublicId) { $table->addColumn('client_name', function ($model) { return link_to('clients/'.$model->client_public_id, Utils::getClientDisplayName($model)); }); } return $table->addColumn('start_date', function ($model) { return Utils::fromSqlDate($model->start_date); }) ->addColumn('end_date', function ($model) { return Utils::fromSqlDate($model->end_date); }) ->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id); }) ->addColumn('dropdown', function ($model) { if ($model->is_deleted) { return '<div style="height:38px"/>'; } $str = '<div class="btn-group tr-action" style="visibility:hidden;"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> '.trans('texts.select').' <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu">'; if (!$model->deleted_at || $model->deleted_at == '0000-00-00') { $str .= '<li><a href="'.URL::to('invoices/'.$model->public_id.'/edit').'">'.trans('texts.edit_invoice').'</a></li> <li class="divider"></li> <li><a href="javascript:archiveEntity('.$model->public_id.')">'.trans('texts.archive_invoice').'</a></li> <li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans('texts.delete_invoice').'</a></li>'; } else { $str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans('texts.restore_invoice').'</a></li>'; } return $str.'</ul> </div>'; }) ->make(); } public function view($invitationKey) { $invitation = Invitation::where('invitation_key', '=', $invitationKey)->firstOrFail(); $invoice = $invitation->invoice; if (!$invoice || $invoice->is_deleted) { return View::make('invoices.deleted'); } $invoice->load('user', 'invoice_items', 'invoice_design', 'account.country', 'client.contacts', 'client.country'); $client = $invoice->client; $account = $client->account; if (!$client || $client->is_deleted) { return View::make('invoices.deleted'); } if ($account->subdomain) { $server = explode('.', Request::server('HTTP_HOST')); $subdomain = $server[0]; if (!in_array($subdomain, ['app', 'www']) && $subdomain != $account->subdomain) { return View::make('invoices.deleted'); } } if (!Session::has($invitationKey) && (!Auth::check() || Auth::user()->account_id != $invoice->account_id)) { Activity::viewInvoice($invitation); Event::fire(new InvoiceViewed($invoice)); } Session::set($invitationKey, true); Session::set('invitation_key', $invitationKey); $account->loadLocalizationSettings(); $invoice->invoice_date = Utils::fromSqlDate($invoice->invoice_date); $invoice->due_date = Utils::fromSqlDate($invoice->due_date); $invoice->is_pro = $account->isPro(); if ($invoice->invoice_design_id == CUSTOM_DESIGN) { $invoice->invoice_design->javascript = $account->custom_design; } else { $invoice->invoice_design->javascript = $invoice->invoice_design->pdfmake; } $contact = $invitation->contact; $contact->setVisible([ 'first_name', 'last_name', 'email', 'phone', ]); // Determine payment options $paymentTypes = []; if ($client->getGatewayToken()) { $paymentTypes[] = [ 'url' => URL::to("payment/{$invitation->invitation_key}/token"), 'label' => trans('texts.use_card_on_file') ]; } foreach(Gateway::$paymentTypes as $type) { if ($account->getGatewayByType($type)) { $typeLink = strtolower(str_replace('PAYMENT_TYPE_', '', $type)); $paymentTypes[] = [ 'url' => URL::to("/payment/{$invitation->invitation_key}/{$typeLink}"), 'label' => trans('texts.'.strtolower($type)) ]; } } $paymentURL = ''; if (count($paymentTypes)) { $paymentURL = $paymentTypes[0]['url']; } $data = array( 'isConverted' => $invoice->quote_invoice_id ? true : false, 'showBreadcrumbs' => false, 'hideLogo' => $account->isWhiteLabel(), 'invoice' => $invoice->hidePrivateFields(), 'invitation' => $invitation, 'invoiceLabels' => $account->getInvoiceLabels(), 'contact' => $contact, 'paymentTypes' => $paymentTypes, 'paymentURL' => $paymentURL, ); return View::make('invoices.view', $data); } public function edit($publicId, $clone = false) { $invoice = Invoice::scope($publicId)->withTrashed()->with('invitations', 'account.country', 'client.contacts', 'client.country', 'invoice_items')->firstOrFail(); $entityType = $invoice->getEntityType(); $contactIds = DB::table('invitations') ->join('contacts', 'contacts.id', '=', 'invitations.contact_id') ->where('invitations.invoice_id', '=', $invoice->id) ->where('invitations.account_id', '=', Auth::user()->account_id) ->where('invitations.deleted_at', '=', null) ->select('contacts.public_id')->lists('public_id'); if ($clone) { $invoice->id = null; $invoice->invoice_number = Auth::user()->account->getNextInvoiceNumber($invoice->is_quote); $invoice->balance = $invoice->amount; $invoice->invoice_status_id = 0; $invoice->invoice_date = date_create()->format('Y-m-d'); $method = 'POST'; $url = "{$entityType}s"; } else { Utils::trackViewed($invoice->getDisplayName().' - '.$invoice->client->getDisplayName(), $invoice->getEntityType()); $method = 'PUT'; $url = "{$entityType}s/{$publicId}"; } $invoice->invoice_date = Utils::fromSqlDate($invoice->invoice_date); $invoice->due_date = Utils::fromSqlDate($invoice->due_date); $invoice->start_date = Utils::fromSqlDate($invoice->start_date); $invoice->end_date = Utils::fromSqlDate($invoice->end_date); $invoice->is_pro = Auth::user()->isPro(); $actions = [ ['url' => 'javascript:onCloneClick()', 'label' => trans("texts.clone_{$entityType}")], ['url' => URL::to("{$entityType}s/{$entityType}_history/{$invoice->public_id}"), 'label' => trans("texts.view_history")], DropdownButton::DIVIDER ]; if ($invoice->invoice_status_id < INVOICE_STATUS_SENT && !$invoice->is_recurring) { $actions[] = ['url' => 'javascript:onMarkClick()', 'label' => trans("texts.mark_sent")]; } if ($entityType == ENTITY_QUOTE) { if ($invoice->quote_invoice_id) { $actions[] = ['url' => URL::to("invoices/{$invoice->quote_invoice_id}/edit"), 'label' => trans("texts.view_invoice")]; } else { $actions[] = ['url' => 'javascript:onConvertClick()', 'label' => trans("texts.convert_to_invoice")]; } } elseif ($entityType == ENTITY_INVOICE) { if ($invoice->quote_id) { $actions[] = ['url' => URL::to("quotes/{$invoice->quote_id}/edit"), 'label' => trans("texts.view_quote")]; } if (!$invoice->is_recurring && $invoice->balance > 0) { $actions[] = ['url' => 'javascript:onPaymentClick()', 'label' => trans('texts.enter_payment')]; } } if (count($actions) > 3) { $actions[] = DropdownButton::DIVIDER; } $actions[] = ['url' => 'javascript:onArchiveClick()', 'label' => trans("texts.archive_{$entityType}")]; $actions[] = ['url' => 'javascript:onDeleteClick()', 'label' => trans("texts.delete_{$entityType}")]; $data = array( 'entityType' => $entityType, 'showBreadcrumbs' => $clone, 'invoice' => $invoice, 'data' => false, 'method' => $method, 'invitationContactIds' => $contactIds, 'url' => $url, 'title' => trans("texts.edit_{$entityType}"), 'client' => $invoice->client, 'isRecurring' => $invoice->is_recurring, 'actions' => $actions); $data = array_merge($data, self::getViewModel()); // Set the invitation link on the client's contacts if (!$clone) { $clients = $data['clients']; foreach ($clients as $client) { if ($client->id == $invoice->client->id) { foreach ($invoice->invitations as $invitation) { foreach ($client->contacts as $contact) { if ($invitation->contact_id == $contact->id) { $contact->invitation_link = $invitation->getLink(); } } } break; } } } return View::make('invoices.edit', $data); } public function create($clientPublicId = 0, $isRecurring = false) { $client = null; $invoiceNumber = $isRecurring ? microtime(true) : Auth::user()->account->getNextInvoiceNumber(); if ($clientPublicId) { $client = Client::scope($clientPublicId)->firstOrFail(); } $data = array( 'entityType' => ENTITY_INVOICE, 'invoice' => null, 'data' => Input::old('data'), 'invoiceNumber' => $invoiceNumber, 'method' => 'POST', 'url' => 'invoices', 'title' => trans('texts.new_invoice'), 'isRecurring' => $isRecurring, 'client' => $client); $data = array_merge($data, self::getViewModel()); return View::make('invoices.edit', $data); } public function createRecurring($clientPublicId = 0) { return self::create($clientPublicId, true); } private static function getViewModel() { $recurringHelp = ''; foreach (preg_split("/((\r?\n)|(\r\n?))/", trans('texts.recurring_help')) as $line) { $parts = explode("=>", $line); if (count($parts) > 1) { $line = $parts[0].' => '.Utils::processVariables($parts[0]); $recurringHelp .= '<li>'.strip_tags($line).'</li>'; } else { $recurringHelp .= $line; } } return [ 'account' => Auth::user()->account->load('country'), 'products' => Product::scope()->orderBy('id')->get(array('product_key', 'notes', 'cost', 'qty')), 'countries' => Cache::get('countries'), 'clients' => Client::scope()->with('contacts', 'country')->orderBy('name')->get(), 'taxRates' => TaxRate::scope()->orderBy('name')->get(), 'currencies' => Cache::get('currencies'), 'sizes' => Cache::get('sizes'), 'paymentTerms' => Cache::get('paymentTerms'), 'industries' => Cache::get('industries'), 'invoiceDesigns' => InvoiceDesign::getDesigns(), 'frequencies' => array( 1 => 'Weekly', 2 => 'Two weeks', 3 => 'Four weeks', 4 => 'Monthly', 5 => 'Three months', 6 => 'Six months', 7 => 'Annually', ), 'recurringHelp' => $recurringHelp, 'invoiceLabels' => Auth::user()->account->getInvoiceLabels(), 'tasks' => Session::get('tasks') ? json_encode(Session::get('tasks')) : null, ]; } /** * Store a newly created resource in storage. * * @return Response */ public function store() { return InvoiceController::save(); } private function save($publicId = null) { $action = Input::get('action'); $entityType = Input::get('entityType'); if (in_array($action, ['archive', 'delete', 'mark', 'restore'])) { return InvoiceController::bulk($entityType); } $input = json_decode(Input::get('data')); $invoice = $input->invoice; if ($errors = $this->invoiceRepo->getErrors($invoice)) { Session::flash('error', trans('texts.invoice_error')); return Redirect::to("{$entityType}s/create") ->withInput()->withErrors($errors); } else { $this->taxRateRepo->save($input->tax_rates); $clientData = (array) $invoice->client; $client = $this->clientRepo->save($invoice->client->public_id, $clientData); $invoiceData = (array) $invoice; $invoiceData['client_id'] = $client->id; $invoice = $this->invoiceRepo->save($publicId, $invoiceData, $entityType); $account = Auth::user()->account; if ($account->invoice_taxes != $input->invoice_taxes || $account->invoice_item_taxes != $input->invoice_item_taxes || $account->invoice_design_id != $input->invoice->invoice_design_id) { $account->invoice_taxes = $input->invoice_taxes; $account->invoice_item_taxes = $input->invoice_item_taxes; $account->invoice_design_id = $input->invoice->invoice_design_id; $account->save(); } $client->load('contacts'); $sendInvoiceIds = []; foreach ($client->contacts as $contact) { if ($contact->send_invoice || count($client->contacts) == 1) { $sendInvoiceIds[] = $contact->id; } } foreach ($client->contacts as $contact) { $invitation = Invitation::scope()->whereContactId($contact->id)->whereInvoiceId($invoice->id)->first(); if (in_array($contact->id, $sendInvoiceIds) && !$invitation) { $invitation = Invitation::createNew(); $invitation->invoice_id = $invoice->id; $invitation->contact_id = $contact->id; $invitation->invitation_key = str_random(RANDOM_KEY_LENGTH); $invitation->save(); } elseif (!in_array($contact->id, $sendInvoiceIds) && $invitation) { $invitation->delete(); } } $message = trans($publicId ? "texts.updated_{$entityType}" : "texts.created_{$entityType}"); if ($input->invoice->client->public_id == '-1') { $message = $message.' '.trans('texts.and_created_client'); $url = URL::to('clients/'.$client->public_id); Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT, $url); } $pdfUpload = Input::get('pdfupload'); if (!empty($pdfUpload) && strpos($pdfUpload, 'data:application/pdf;base64,') === 0) { $this->storePDF(Input::get('pdfupload'), $invoice); } if ($action == 'clone') { return $this->cloneInvoice($publicId); } elseif ($action == 'convert') { return $this->convertQuote($publicId); } elseif ($action == 'email') { if (Auth::user()->confirmed && !Auth::user()->isDemo()) { if ($invoice->is_recurring) { if ($invoice->shouldSendToday()) { $invoice = $this->invoiceRepo->createRecurringInvoice($invoice); $response = $this->mailer->sendInvoice($invoice); } else { $response = trans('texts.recurring_too_soon'); } } else { $response = $this->mailer->sendInvoice($invoice); } if ($response === true) { $message = trans("texts.emailed_{$entityType}"); Session::flash('message', $message); } else { Session::flash('error', $response); } } else { $errorMessage = trans(Auth::user()->registered ? 'texts.confirmation_required' : 'texts.registration_required'); Session::flash('error', $errorMessage); Session::flash('message', $message); } } else { Session::flash('message', $message); } $url = "{$entityType}s/".$invoice->public_id.'/edit'; return Redirect::to($url); } } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($publicId) { Session::reflash(); return Redirect::to('invoices/'.$publicId.'/edit'); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($publicId) { return InvoiceController::save($publicId); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function bulk($entityType = ENTITY_INVOICE) { $action = Input::get('action'); $statusId = Input::get('statusId', INVOICE_STATUS_SENT); $ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $count = $this->invoiceRepo->bulk($ids, $action, $statusId); if ($count > 0) { $key = $action == 'mark' ? "updated_{$entityType}" : "{$action}d_{$entityType}"; $message = Utils::pluralize($key, $count); Session::flash('message', $message); } if ($action == 'restore' && $count == 1) { return Redirect::to("{$entityType}s/".Utils::getFirst($ids)); } else { return Redirect::to("{$entityType}s"); } } public function convertQuote($publicId) { $invoice = Invoice::with('invoice_items')->scope($publicId)->firstOrFail(); $clone = $this->invoiceRepo->cloneInvoice($invoice, $invoice->id); Session::flash('message', trans('texts.converted_to_invoice')); return Redirect::to('invoices/'.$clone->public_id); } public function cloneInvoice($publicId) { /* $invoice = Invoice::with('invoice_items')->scope($publicId)->firstOrFail(); $clone = $this->invoiceRepo->cloneInvoice($invoice); $entityType = $invoice->getEntityType(); Session::flash('message', trans('texts.cloned_invoice')); return Redirect::to("{$entityType}s/" . $clone->public_id); */ return self::edit($publicId, true); } public function invoiceHistory($publicId) { $invoice = Invoice::withTrashed()->scope($publicId)->firstOrFail(); $invoice->load('user', 'invoice_items', 'account.country', 'client.contacts', 'client.country'); $invoice->invoice_date = Utils::fromSqlDate($invoice->invoice_date); $invoice->due_date = Utils::fromSqlDate($invoice->due_date); $invoice->is_pro = Auth::user()->isPro(); $invoice->is_quote = intval($invoice->is_quote); $activityTypeId = $invoice->is_quote ? ACTIVITY_TYPE_UPDATE_QUOTE : ACTIVITY_TYPE_UPDATE_INVOICE; $activities = Activity::scope(false, $invoice->account_id) ->where('activity_type_id', '=', $activityTypeId) ->where('invoice_id', '=', $invoice->id) ->orderBy('id', 'desc') ->get(['id', 'created_at', 'user_id', 'json_backup', 'message']); $versionsJson = []; $versionsSelect = []; $lastId = false; foreach ($activities as $activity) { $backup = json_decode($activity->json_backup); $backup->invoice_date = Utils::fromSqlDate($backup->invoice_date); $backup->due_date = Utils::fromSqlDate($backup->due_date); $backup->is_pro = Auth::user()->isPro(); $backup->is_quote = isset($backup->is_quote) && intval($backup->is_quote); $backup->account = $invoice->account->toArray(); $versionsJson[$activity->id] = $backup; $key = Utils::timestampToDateTimeString(strtotime($activity->created_at)) . ' - ' . Utils::decodeActivity($activity->message); $versionsSelect[$lastId ? $lastId : 0] = $key; $lastId = $activity->id; } $versionsSelect[$lastId] = Utils::timestampToDateTimeString(strtotime($invoice->created_at)) . ' - ' . $invoice->user->getDisplayName(); $data = [ 'invoice' => $invoice, 'versionsJson' => json_encode($versionsJson), 'versionsSelect' => $versionsSelect, 'invoiceDesigns' => InvoiceDesign::getDesigns(), ]; return View::make('invoices.history', $data); } private function storePDF($encodedString, $invoice) { $encodedString = str_replace('data:application/pdf;base64,', '', $encodedString); file_put_contents($invoice->getPDFPath(), base64_decode($encodedString)); } } <file_sep>/app/Http/Controllers/IntegrationController.php <?php namespace App\Http\Controllers; use Utils; use Response; use Auth; use Input; use App\Models\Subscription; class IntegrationController extends Controller { public function subscribe() { $eventId = Utils::lookupEventId(trim(Input::get('event'))); if (!$eventId) { return Response::json('', 500); } $subscription = Subscription::where('account_id', '=', Auth::user()->account_id)->where('event_id', '=', $eventId)->first(); if (!$subscription) { $subscription = new Subscription(); $subscription->account_id = Auth::user()->account_id; $subscription->event_id = $eventId; } $subscription->target_url = trim(Input::get('target_url')); $subscription->save(); return Response::json('{"id":'.$subscription->id.'}', 201); } } <file_sep>/app/Console/Commands/SendRecurringInvoices.php <?php namespace App\Console\Commands; use DateTime; use Carbon; use Utils; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use App\Ninja\Mailers\ContactMailer as Mailer; use App\Ninja\Repositories\InvoiceRepository; use App\Models\Invoice; use App\Models\InvoiceItem; use App\Models\Invitation; class SendRecurringInvoices extends Command { protected $name = 'ninja:send-invoices'; protected $description = 'Send recurring invoices'; protected $mailer; protected $invoiceRepo; public function __construct(Mailer $mailer, InvoiceRepository $invoiceRepo) { parent::__construct(); $this->mailer = $mailer; $this->invoiceRepo = $invoiceRepo; } public function fire() { $this->info(date('Y-m-d').' Running SendRecurringInvoices...'); $today = new DateTime(); $invoices = Invoice::with('account.timezone', 'invoice_items', 'client', 'user') ->whereRaw('is_deleted IS FALSE AND deleted_at IS NULL AND is_recurring IS TRUE AND start_date <= ? AND (end_date IS NULL OR end_date >= ?)', array($today, $today))->get(); $this->info(count($invoices).' recurring invoice(s) found'); foreach ($invoices as $recurInvoice) { $this->info('Processing Invoice '.$recurInvoice->id.' - Should send '.($recurInvoice->shouldSendToday() ? 'YES' : 'NO')); $invoice = $this->invoiceRepo->createRecurringInvoice($recurInvoice); if ($invoice) { $recurInvoice->account->loadLocalizationSettings(); $this->mailer->sendInvoice($invoice); } } $this->info('Done'); } protected function getArguments() { return array( //array('example', InputArgument::REQUIRED, 'An example argument.'), ); } protected function getOptions() { return array( //array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null), ); } } <file_sep>/app/Models/Contact.php <?php namespace App\Models; use HTML; use Illuminate\Database\Eloquent\SoftDeletes; class Contact extends EntityModel { use SoftDeletes; protected $dates = ['deleted_at']; public static $fieldFirstName = 'Contact - First Name'; public static $fieldLastName = 'Contact - Last Name'; public static $fieldEmail = 'Contact - Email'; public static $fieldPhone = 'Contact - Phone'; public function client() { return $this->belongsTo('App\Models\Client'); } public function getPersonType() { return PERSON_CONTACT; } /* public function getLastLogin() { if ($this->last_login == '0000-00-00 00:00:00') { return '---'; } else { return $this->last_login->format('m/d/y h:i a'); } } */ public function getName() { return $this->getDisplayName(); } public function getDisplayName() { if ($this->getFullName()) { return $this->getFullName(); } else { return $this->email; } } public function getFullName() { if ($this->first_name || $this->last_name) { return $this->first_name.' '.$this->last_name; } else { return ''; } } } <file_sep>/app/Http/Controllers/ActivityController.php <?php namespace App\Http\Controllers; use Auth; use DB; use Datatable; use Utils; use View; class ActivityController extends BaseController { public function getDatatable($clientPublicId) { $query = DB::table('activities') ->join('clients', 'clients.id', '=', 'activities.client_id') ->where('clients.public_id', '=', $clientPublicId) ->where('activities.account_id', '=', Auth::user()->account_id) ->select('activities.id', 'activities.message', 'activities.created_at', 'clients.currency_id', 'activities.balance', 'activities.adjustment'); return Datatable::query($query) ->addColumn('activities.id', function ($model) { return Utils::timestampToDateTimeString(strtotime($model->created_at)); }) ->addColumn('message', function ($model) { return Utils::decodeActivity($model->message); }) ->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id); }) ->addColumn('adjustment', function ($model) { return $model->adjustment != 0 ? self::wrapAdjustment($model->adjustment, $model->currency_id) : ''; }) ->make(); } private function wrapAdjustment($adjustment, $currencyId) { $class = $adjustment <= 0 ? 'success' : 'default'; $adjustment = Utils::formatMoney($adjustment, $currencyId); return "<h4><div class=\"label label-{$class}\">$adjustment</div></h4>"; } } <file_sep>/app/Http/Controllers/ClientController.php <?php namespace App\Http\Controllers; use Auth; use Datatable; use Utils; use View; use URL; use Validator; use Input; use Session; use Redirect; use Cache; use App\Models\Activity; use App\Models\Client; use App\Models\Contact; use App\Models\Invoice; use App\Models\Size; use App\Models\PaymentTerm; use App\Models\Industry; use App\Models\Currency; use App\Models\Country; use App\Models\Task; use App\Ninja\Repositories\ClientRepository; class ClientController extends BaseController { protected $clientRepo; public function __construct(ClientRepository $clientRepo) { parent::__construct(); $this->clientRepo = $clientRepo; } /** * Display a listing of the resource. * * @return Response */ public function index() { return View::make('list', array( 'entityType' => ENTITY_CLIENT, 'title' => trans('texts.clients'), 'sortCol' => '4', 'columns' => Utils::trans(['checkbox', 'client', 'contact', 'email', 'date_created', 'last_login', 'balance', 'action']), )); } public function getDatatable() { $clients = $this->clientRepo->find(Input::get('sSearch')); return Datatable::query($clients) ->addColumn('checkbox', function ($model) { return '<input type="checkbox" name="ids[]" value="'.$model->public_id.'" '.Utils::getEntityRowClass($model).'>'; }) ->addColumn('name', function ($model) { return link_to('clients/'.$model->public_id, $model->name); }) ->addColumn('first_name', function ($model) { return link_to('clients/'.$model->public_id, $model->first_name.' '.$model->last_name); }) ->addColumn('email', function ($model) { return link_to('clients/'.$model->public_id, $model->email); }) ->addColumn('clients.created_at', function ($model) { return Utils::timestampToDateString(strtotime($model->created_at)); }) ->addColumn('last_login', function ($model) { return Utils::timestampToDateString(strtotime($model->last_login)); }) ->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id); }) ->addColumn('dropdown', function ($model) { if ($model->is_deleted) { return '<div style="height:38px"/>'; } $str = '<div class="btn-group tr-action" style="visibility:hidden;"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> '.trans('texts.select').' <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu">'; if (!$model->deleted_at || $model->deleted_at == '0000-00-00') { $str .= '<li><a href="'.URL::to('clients/'.$model->public_id.'/edit').'">'.trans('texts.edit_client').'</a></li> <li class="divider"></li> <li><a href="'.URL::to('tasks/create/'.$model->public_id).'">'.trans('texts.new_task').'</a></li> <li><a href="'.URL::to('invoices/create/'.$model->public_id).'">'.trans('texts.new_invoice').'</a></li>'; if (Auth::user()->isPro()) { $str .= '<li><a href="'.URL::to('quotes/create/'.$model->public_id).'">'.trans('texts.new_quote').'</a></li>'; } $str .= '<li class="divider"></li> <li><a href="'.URL::to('payments/create/'.$model->public_id).'">'.trans('texts.enter_payment').'</a></li> <li><a href="'.URL::to('credits/create/'.$model->public_id).'">'.trans('texts.enter_credit').'</a></li> <li class="divider"></li> <li><a href="javascript:archiveEntity('.$model->public_id.')">'.trans('texts.archive_client').'</a></li>'; } else { $str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans('texts.restore_client').'</a></li>'; } return $str.'<li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans('texts.delete_client').'</a></li></ul> </div>'; }) ->make(); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { return $this->save(); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($publicId) { $client = Client::withTrashed()->scope($publicId)->with('contacts', 'size', 'industry')->firstOrFail(); Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT); $actionLinks = [ ['label' => trans('texts.new_task'), 'url' => '/tasks/create/'.$client->public_id] ]; if (Utils::isPro()) { array_push($actionLinks, ['label' => trans('texts.new_quote'), 'url' => '/quotes/create/'.$client->public_id]); } array_push($actionLinks, ['label' => trans('texts.enter_payment'), 'url' => '/payments/create/'.$client->public_id], ['label' => trans('texts.enter_credit'), 'url' => '/credits/create/'.$client->public_id] ); $data = array( 'actionLinks' => $actionLinks, 'showBreadcrumbs' => false, 'client' => $client, 'credit' => $client->getTotalCredit(), 'title' => trans('texts.view_client'), 'hasRecurringInvoices' => Invoice::scope()->where('is_recurring', '=', true)->whereClientId($client->id)->count() > 0, 'hasQuotes' => Invoice::scope()->where('is_quote', '=', true)->whereClientId($client->id)->count() > 0, 'hasTasks' => Task::scope()->whereClientId($client->id)->count() > 0, 'gatewayLink' => $client->getGatewayLink(), ); return View::make('clients.show', $data); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { if (Client::scope()->count() > Auth::user()->getMaxNumClients()) { return View::make('error', ['hideHeader' => true, 'error' => "Sorry, you've exceeded the limit of ".Auth::user()->getMaxNumClients()." clients"]); } $data = [ 'client' => null, 'method' => 'POST', 'url' => 'clients', 'title' => trans('texts.new_client'), ]; $data = array_merge($data, self::getViewModel()); return View::make('clients.edit', $data); } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($publicId) { $client = Client::scope($publicId)->with('contacts')->firstOrFail(); $data = [ 'client' => $client, 'method' => 'PUT', 'url' => 'clients/'.$publicId, 'title' => trans('texts.edit_client'), ]; $data = array_merge($data, self::getViewModel()); return View::make('clients.edit', $data); } private static function getViewModel() { return [ 'sizes' => Cache::get('sizes'), 'paymentTerms' => Cache::get('paymentTerms'), 'industries' => Cache::get('industries'), 'currencies' => Cache::get('currencies'), 'countries' => Cache::get('countries'), 'customLabel1' => Auth::user()->account->custom_client_label1, 'customLabel2' => Auth::user()->account->custom_client_label2, ]; } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($publicId) { return $this->save($publicId); } private function save($publicId = null) { $rules = array( 'email' => 'email|required_without:first_name', 'first_name' => 'required_without:email', ); $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { $url = $publicId ? 'clients/'.$publicId.'/edit' : 'clients/create'; return Redirect::to($url) ->withErrors($validator) ->withInput(Input::except('password')); } else { if ($publicId) { $client = Client::scope($publicId)->firstOrFail(); } else { $client = Client::createNew(); } $client->name = trim(Input::get('name')); $client->id_number = trim(Input::get('id_number')); $client->vat_number = trim(Input::get('vat_number')); $client->work_phone = trim(Input::get('work_phone')); $client->custom_value1 = trim(Input::get('custom_value1')); $client->custom_value2 = trim(Input::get('custom_value2')); $client->address1 = trim(Input::get('address1')); $client->address2 = trim(Input::get('address2')); $client->city = trim(Input::get('city')); $client->state = trim(Input::get('state')); $client->postal_code = trim(Input::get('postal_code')); $client->country_id = Input::get('country_id') ?: null; $client->private_notes = trim(Input::get('private_notes')); $client->size_id = Input::get('size_id') ?: null; $client->industry_id = Input::get('industry_id') ?: null; $client->currency_id = Input::get('currency_id') ?: null; $client->payment_terms = Input::get('payment_terms') ?: 0; $client->website = trim(Input::get('website')); $client->save(); $data = json_decode(Input::get('data')); $contactIds = []; $isPrimary = true; foreach ($data->contacts as $contact) { if (isset($contact->public_id) && $contact->public_id) { $record = Contact::scope($contact->public_id)->firstOrFail(); } else { $record = Contact::createNew(); } $record->email = trim($contact->email); $record->first_name = trim($contact->first_name); $record->last_name = trim($contact->last_name); $record->phone = trim($contact->phone); $record->is_primary = $isPrimary; $isPrimary = false; $client->contacts()->save($record); $contactIds[] = $record->public_id; } foreach ($client->contacts as $contact) { if (!in_array($contact->public_id, $contactIds)) { $contact->delete(); } } if ($publicId) { Session::flash('message', trans('texts.updated_client')); } else { Activity::createClient($client); Session::flash('message', trans('texts.created_client')); } return Redirect::to('clients/'.$client->public_id); } } public function bulk() { $action = Input::get('action'); $ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $count = $this->clientRepo->bulk($ids, $action); $message = Utils::pluralize($action.'d_client', $count); Session::flash('message', $message); if ($action == 'restore' && $count == 1) { return Redirect::to('clients/'.Utils::getFirst($ids)); } else { return Redirect::to('clients'); } } } <file_sep>/database/migrations/2015_07_19_081332_add_custom_design.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddCustomDesign extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('accounts', function($table) { $table->text('custom_design')->nullable(); }); DB::table('invoice_designs')->insert(['id' => CUSTOM_DESIGN, 'name' => 'Custom']); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('accounts', function($table) { $table->dropColumn('custom_design'); }); } } <file_sep>/app/Http/Controllers/PaymentController.php <?php namespace App\Http\Controllers; use Datatable; use Input; use Redirect; use Request; use Session; use Utils; use View; use Validator; use Omnipay; use CreditCard; use URL; use Cache; use Event; use DateTime; use App\Models\Account; use App\Models\Invoice; use App\Models\Invitation; use App\Models\Client; use App\Models\PaymentType; use App\Models\Country; use App\Models\License; use App\Models\Payment; use App\Models\Affiliate; use App\Models\AccountGatewayToken; use App\Ninja\Repositories\PaymentRepository; use App\Ninja\Repositories\InvoiceRepository; use App\Ninja\Repositories\AccountRepository; use App\Ninja\Mailers\ContactMailer; use App\Events\InvoicePaid; class PaymentController extends BaseController { protected $creditRepo; public function __construct(PaymentRepository $paymentRepo, InvoiceRepository $invoiceRepo, AccountRepository $accountRepo, ContactMailer $contactMailer) { parent::__construct(); $this->paymentRepo = $paymentRepo; $this->invoiceRepo = $invoiceRepo; $this->accountRepo = $accountRepo; $this->contactMailer = $contactMailer; } public function index() { return View::make('list', array( 'entityType' => ENTITY_PAYMENT, 'title' => trans('texts.payments'), 'columns' => Utils::trans(['checkbox', 'invoice', 'client', 'transaction_reference', 'method', 'payment_amount', 'payment_date', 'action']), )); } public function clientIndex() { $invitationKey = Session::get('invitation_key'); if (!$invitationKey) { return Redirect::to('/setup'); } $invitation = Invitation::with('account')->where('invitation_key', '=', $invitationKey)->first(); $account = $invitation->account; $color = $account->primary_color ? $account->primary_color : '#0b4d78'; $data = [ 'color' => $color, 'hideLogo' => $account->isWhiteLabel(), 'entityType' => ENTITY_PAYMENT, 'title' => trans('texts.payments'), 'columns' => Utils::trans(['invoice', 'transaction_reference', 'method', 'payment_amount', 'payment_date']) ]; return View::make('public_list', $data); } public function getDatatable($clientPublicId = null) { $payments = $this->paymentRepo->find($clientPublicId, Input::get('sSearch')); $table = Datatable::query($payments); if (!$clientPublicId) { $table->addColumn('checkbox', function ($model) { return '<input type="checkbox" name="ids[]" value="'.$model->public_id.'" '.Utils::getEntityRowClass($model).'>'; }); } $table->addColumn('invoice_number', function ($model) { return $model->invoice_public_id ? link_to('invoices/'.$model->invoice_public_id.'/edit', $model->invoice_number, ['class' => Utils::getEntityRowClass($model)]) : ''; }); if (!$clientPublicId) { $table->addColumn('client_name', function ($model) { return link_to('clients/'.$model->client_public_id, Utils::getClientDisplayName($model)); }); } $table->addColumn('transaction_reference', function ($model) { return $model->transaction_reference ? $model->transaction_reference : '<i>Manual entry</i>'; }) ->addColumn('payment_type', function ($model) { return $model->payment_type ? $model->payment_type : ($model->account_gateway_id ? $model->gateway_name : ''); }); return $table->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id); }) ->addColumn('payment_date', function ($model) { return Utils::dateToString($model->payment_date); }) ->addColumn('dropdown', function ($model) { if ($model->is_deleted || $model->invoice_is_deleted) { return '<div style="height:38px"/>'; } $str = '<div class="btn-group tr-action" style="visibility:hidden;"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> '.trans('texts.select').' <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu">'; if (!$model->deleted_at || $model->deleted_at == '0000-00-00') { $str .= '<li><a href="payments/'.$model->public_id.'/edit">'.trans('texts.edit_payment').'</a></li> <li class="divider"></li> <li><a href="javascript:archiveEntity('.$model->public_id.')">'.trans('texts.archive_payment').'</a></li>'; } else { $str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans('texts.restore_payment').'</a></li>'; } return $str.'<li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans('texts.delete_payment').'</a></li></ul> </div>'; }) ->make(); } public function getClientDatatable() { $search = Input::get('sSearch'); $invitationKey = Session::get('invitation_key'); $invitation = Invitation::where('invitation_key', '=', $invitationKey)->with('contact.client')->first(); if (!$invitation) { return []; } $invoice = $invitation->invoice; if (!$invoice || $invoice->is_deleted) { return []; } $payments = $this->paymentRepo->findForContact($invitation->contact->id, Input::get('sSearch')); return Datatable::query($payments) ->addColumn('invoice_number', function ($model) { return $model->invitation_key ? link_to('/view/'.$model->invitation_key, $model->invoice_number) : $model->invoice_number; }) ->addColumn('transaction_reference', function ($model) { return $model->transaction_reference ? $model->transaction_reference : '<i>Manual entry</i>'; }) ->addColumn('payment_type', function ($model) { return $model->payment_type ? $model->payment_type : ($model->account_gateway_id ? '<i>Online payment</i>' : ''); }) ->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id); }) ->addColumn('payment_date', function ($model) { return Utils::dateToString($model->payment_date); }) ->make(); } public function create($clientPublicId = 0, $invoicePublicId = 0) { $invoices = Invoice::scope() ->where('is_recurring', '=', false) ->where('is_quote', '=', false) ->where('invoices.balance', '>', 0) ->with('client', 'invoice_status') ->orderBy('invoice_number')->get(); $data = array( 'clientPublicId' => Input::old('client') ? Input::old('client') : $clientPublicId, 'invoicePublicId' => Input::old('invoice') ? Input::old('invoice') : $invoicePublicId, 'invoice' => null, 'invoices' => $invoices, 'payment' => null, 'method' => 'POST', 'url' => "payments", 'title' => trans('texts.new_payment'), 'paymentTypes' => Cache::get('paymentTypes'), 'clients' => Client::scope()->with('contacts')->orderBy('name')->get(), ); return View::make('payments.edit', $data); } public function edit($publicId) { $payment = Payment::scope($publicId)->firstOrFail(); $payment->payment_date = Utils::fromSqlDate($payment->payment_date); $data = array( 'client' => null, 'invoice' => null, 'invoices' => Invoice::scope()->where('is_recurring', '=', false)->where('is_quote', '=', false) ->with('client', 'invoice_status')->orderBy('invoice_number')->get(), 'payment' => $payment, 'method' => 'PUT', 'url' => 'payments/'.$publicId, 'title' => trans('texts.edit_payment'), 'paymentTypes' => Cache::get('paymentTypes'), 'clients' => Client::scope()->with('contacts')->orderBy('name')->get(), ); return View::make('payments.edit', $data); } private function createGateway($accountGateway) { $gateway = Omnipay::create($accountGateway->gateway->provider); $config = json_decode($accountGateway->config); foreach ($config as $key => $val) { if (!$val) { continue; } $function = "set".ucfirst($key); $gateway->$function($val); } if ($accountGateway->gateway->id == GATEWAY_DWOLLA) { if ($gateway->getSandbox() && isset($_ENV['DWOLLA_SANDBOX_KEY']) && isset($_ENV['DWOLLA_SANSBOX_SECRET'])) { $gateway->setKey($_ENV['DWOLLA_SANDBOX_KEY']); $gateway->setSecret($_ENV['DWOLLA_SANSBOX_SECRET']); } elseif (isset($_ENV['DWOLLA_KEY']) && isset($_ENV['DWOLLA_SECRET'])) { $gateway->setKey($_ENV['DWOLLA_KEY']); $gateway->setSecret($_ENV['DWOLLA_SECRET']); } } return $gateway; } private function getLicensePaymentDetails($input, $affiliate) { $data = self::convertInputForOmnipay($input); $card = new CreditCard($data); return [ 'amount' => $affiliate->price, 'card' => $card, 'currency' => 'USD', 'returnUrl' => URL::to('license_complete'), 'cancelUrl' => URL::to('/') ]; } private function convertInputForOmnipay($input) { $data = [ 'firstName' => $input['first_name'], 'lastName' => $input['last_name'], 'number' => $input['card_number'], 'expiryMonth' => $input['expiration_month'], 'expiryYear' => $input['expiration_year'], 'cvv' => $input['cvv'], ]; if (isset($input['country_id'])) { $country = Country::find($input['country_id']); $data = array_merge($data, [ 'billingAddress1' => $input['address1'], 'billingAddress2' => $input['address2'], 'billingCity' => $input['city'], 'billingState' => $input['state'], 'billingPostcode' => $input['postal_code'], 'billingCountry' => $country->iso_3166_2, 'shippingAddress1' => $input['address1'], 'shippingAddress2' => $input['address2'], 'shippingCity' => $input['city'], 'shippingState' => $input['state'], 'shippingPostcode' => $input['postal_code'], 'shippingCountry' => $country->iso_3166_2 ]); } return $data; } private function getPaymentDetails($invitation, $input = null) { $invoice = $invitation->invoice; $account = $invoice->account; $key = $invoice->account_id.'-'.$invoice->invoice_number; $currencyCode = $invoice->client->currency ? $invoice->client->currency->code : ($invoice->account->currency ? $invoice->account->currency->code : 'USD'); if ($input) { $data = self::convertInputForOmnipay($input); Session::put($key, $data); } elseif (Session::get($key)) { $data = Session::get($key); } else { $data = []; } $card = new CreditCard($data); return [ 'amount' => $invoice->getRequestedAmount(), 'card' => $card, 'currency' => $currencyCode, 'returnUrl' => URL::to('complete'), 'cancelUrl' => $invitation->getLink(), 'description' => trans('texts.' . $invoice->getEntityType()) . " {$invoice->invoice_number}", ]; } public function show_payment($invitationKey, $paymentType = false) { $invitation = Invitation::with('invoice.invoice_items', 'invoice.client.currency', 'invoice.client.account.account_gateways.gateway')->where('invitation_key', '=', $invitationKey)->firstOrFail(); $invoice = $invitation->invoice; $client = $invoice->client; $account = $client->account; $useToken = false; if ($paymentType) { $paymentType = 'PAYMENT_TYPE_' . strtoupper($paymentType); } else { $paymentType = Session::get('payment_type', $account->account_gateways[0]->getPaymentType()); } if ($paymentType == PAYMENT_TYPE_TOKEN) { $useToken = true; $paymentType = PAYMENT_TYPE_CREDIT_CARD; } Session::put('payment_type', $paymentType); // Handle offsite payments if ($useToken || $paymentType != PAYMENT_TYPE_CREDIT_CARD) { if (Session::has('error')) { Session::reflash(); return Redirect::to('view/'.$invitationKey); } else { return self::do_payment($invitationKey, false, $useToken); } } $accountGateway = $invoice->client->account->getGatewayByType($paymentType); $gateway = $accountGateway->gateway; $acceptedCreditCardTypes = $accountGateway->getCreditcardTypes(); $data = [ 'showBreadcrumbs' => false, 'url' => 'payment/'.$invitationKey, 'amount' => $invoice->getRequestedAmount(), 'invoiceNumber' => $invoice->invoice_number, 'client' => $client, 'contact' => $invitation->contact, 'gateway' => $gateway, 'acceptedCreditCardTypes' => $acceptedCreditCardTypes, 'countries' => Cache::get('countries'), 'currencyId' => $client->getCurrencyId(), 'currencyCode' => $client->currency ? $client->currency->code : ($account->currency ? $account->currency->code : 'USD'), 'account' => $client->account, 'hideLogo' => $account->isWhiteLabel(), 'showAddress' => $accountGateway->show_address, ]; return View::make('payments.payment', $data); } public function show_license_payment() { if (Input::has('return_url')) { Session::set('return_url', Input::get('return_url')); } if (Input::has('affiliate_key')) { if ($affiliate = Affiliate::where('affiliate_key', '=', Input::get('affiliate_key'))->first()) { Session::set('affiliate_id', $affiliate->id); } } Session::set('product_id', Input::get('product_id', PRODUCT_ONE_CLICK_INSTALL)); if (!Session::get('affiliate_id')) { return Utils::fatalError(); } if (Utils::isNinjaDev() && Input::has('test_mode')) { Session::set('test_mode', Input::get('test_mode')); } $account = $this->accountRepo->getNinjaAccount(); $account->load('account_gateways.gateway'); $accountGateway = $account->getGatewayByType(Session::get('payment_type')); $gateway = $accountGateway->gateway; $acceptedCreditCardTypes = $accountGateway->getCreditcardTypes(); $affiliate = Affiliate::find(Session::get('affiliate_id')); $data = [ 'showBreadcrumbs' => false, 'hideHeader' => true, 'url' => 'license', 'amount' => $affiliate->price, 'client' => false, 'contact' => false, 'gateway' => $gateway, 'acceptedCreditCardTypes' => $acceptedCreditCardTypes, 'countries' => Cache::get('countries'), 'currencyId' => 1, 'paymentTitle' => $affiliate->payment_title, 'paymentSubtitle' => $affiliate->payment_subtitle, 'showAddress' => true, ]; return View::make('payments.payment', $data); } public function do_license_payment() { $testMode = Session::get('test_mode') === 'true'; $rules = array( 'first_name' => 'required', 'last_name' => 'required', 'card_number' => 'required', 'expiration_month' => 'required', 'expiration_year' => 'required', 'cvv' => 'required', 'address1' => 'required', 'city' => 'required', 'state' => 'required', 'postal_code' => 'required', 'country_id' => 'required', ); $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return Redirect::to('license') ->withErrors($validator); } $account = $this->accountRepo->getNinjaAccount(); $account->load('account_gateways.gateway'); $accountGateway = $account->getGatewayByType(PAYMENT_TYPE_CREDIT_CARD); try { $affiliate = Affiliate::find(Session::get('affiliate_id')); if ($testMode) { $ref = 'TEST_MODE'; } else { $gateway = self::createGateway($accountGateway); $details = self::getLicensePaymentDetails(Input::all(), $affiliate); $response = $gateway->purchase($details)->send(); $ref = $response->getTransactionReference(); if (!$ref) { Session::flash('error', $response->getMessage()); return Redirect::to('license')->withInput(); } if (!$response->isSuccessful()) { Session::flash('error', $response->getMessage()); Utils::logError($response->getMessage()); return Redirect::to('license')->withInput(); } } $licenseKey = Utils::generateLicense(); $license = new License(); $license->first_name = Input::get('first_name'); $license->last_name = Input::get('last_name'); $license->email = Input::get('email'); $license->transaction_reference = $ref; $license->license_key = $licenseKey; $license->affiliate_id = Session::get('affiliate_id'); $license->product_id = Session::get('product_id'); $license->save(); $data = [ 'message' => $affiliate->payment_subtitle, 'license' => $licenseKey, 'hideHeader' => true, 'productId' => $license->product_id ]; $name = "{$license->first_name} {$license->last_name}"; $this->contactMailer->sendLicensePaymentConfirmation($name, $license->email, $affiliate->price, $license->license_key, $license->product_id); if (Session::has('return_url')) { $data['redirectTo'] = Session::get('return_url')."?license_key={$license->license_key}&product_id=".Session::get('product_id'); $data['message'] = "Redirecting to " . Session::get('return_url'); } return View::make('public.license', $data); } catch (\Exception $e) { $errorMessage = trans('texts.payment_error'); Session::flash('error', $errorMessage); Utils::logError(Utils::getErrorString($e)); return Redirect::to('license')->withInput(); } } public function claim_license() { $licenseKey = Input::get('license_key'); $productId = Input::get('product_id', PRODUCT_ONE_CLICK_INSTALL); $license = License::where('license_key', '=', $licenseKey) ->where('is_claimed', '<', 5) ->where('product_id', '=', $productId) ->first(); if ($license) { if ($license->transaction_reference != 'TEST_MODE') { $license->is_claimed = $license->is_claimed + 1; $license->save(); } return $productId == PRODUCT_INVOICE_DESIGNS ? file_get_contents(storage_path() . '/invoice_designs.txt') : 'valid'; } else { return 'invalid'; } } public function do_payment($invitationKey, $onSite = true, $useToken = false) { $invitation = Invitation::with('invoice.invoice_items', 'invoice.client.currency', 'invoice.client.account.currency', 'invoice.client.account.account_gateways.gateway')->where('invitation_key', '=', $invitationKey)->firstOrFail(); $invoice = $invitation->invoice; $client = $invoice->client; $account = $client->account; $accountGateway = $account->getGatewayByType(Session::get('payment_type')); $rules = [ 'first_name' => 'required', 'last_name' => 'required', 'card_number' => 'required', 'expiration_month' => 'required', 'expiration_year' => 'required', 'cvv' => 'required', ]; if ($accountGateway->show_address) { $rules = array_merge($rules, [ 'address1' => 'required', 'city' => 'required', 'state' => 'required', 'postal_code' => 'required', 'country_id' => 'required', ]); } if ($onSite) { $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { Utils::logError('Payment Error [invalid]'); return Redirect::to('payment/'.$invitationKey) ->withErrors($validator) ->withInput(); } if ($accountGateway->update_address) { $client->address1 = trim(Input::get('address1')); $client->address2 = trim(Input::get('address2')); $client->city = trim(Input::get('city')); $client->state = trim(Input::get('state')); $client->postal_code = trim(Input::get('postal_code')); $client->country_id = Input::get('country_id'); $client->save(); } } try { $gateway = self::createGateway($accountGateway); $details = self::getPaymentDetails($invitation, ($useToken || !$onSite) ? false : Input::all()); if ($accountGateway->gateway_id == GATEWAY_STRIPE) { if ($useToken) { $details['cardReference'] = $client->getGatewayToken(); } elseif ($account->token_billing_type_id == TOKEN_BILLING_ALWAYS || Input::get('token_billing')) { $tokenResponse = $gateway->createCard($details)->send(); $cardReference = $tokenResponse->getCardReference(); if ($cardReference) { $details['cardReference'] = $cardReference; $token = AccountGatewayToken::where('client_id', '=', $client->id) ->where('account_gateway_id', '=', $accountGateway->id)->first(); if (!$token) { $token = new AccountGatewayToken(); $token->account_id = $account->id; $token->contact_id = $invitation->contact_id; $token->account_gateway_id = $accountGateway->id; $token->client_id = $client->id; } $token->token = $cardReference; $token->save(); } else { Session::flash('error', $tokenResponse->getMessage()); Utils::logError('Payment Error [no-token-ref]: ' . $tokenResponse->getMessage()); return Redirect::to('payment/'.$invitationKey)->withInput(); } } } $response = $gateway->purchase($details)->send(); $ref = $response->getTransactionReference(); if (!$ref) { Session::flash('error', $response->getMessage()); Utils::logError('Payment Error [no-ref]: ' . $response->getMessage()); if ($onSite) { return Redirect::to('payment/'.$invitationKey)->withInput(); } else { return Redirect::to('view/'.$invitationKey); } } if ($response->isSuccessful()) { $payment = self::createPayment($invitation, $ref); Session::flash('message', trans('texts.applied_payment')); if ($account->account_key == NINJA_ACCOUNT_KEY) { Session::flash('trackEventCategory', '/account'); Session::flash('trackEventAction', '/buy_pro_plan'); } return Redirect::to('view/'.$payment->invitation->invitation_key); } elseif ($response->isRedirect()) { $invitation->transaction_reference = $ref; $invitation->save(); Session::put('transaction_reference', $ref); Session::save(); $response->redirect(); } else { Session::flash('error', $response->getMessage()); Utils::logError('Payment Error [fatal]: ' . $response->getMessage()); return Utils::fatalError('Sorry, there was an error processing your payment. Please try again later.<p>', $response->getMessage()); } } catch (\Exception $e) { $errorMessage = trans('texts.payment_error'); Session::flash('error', $errorMessage."<p>".$e->getMessage()); Utils::logError('Payment Error [uncaught]:' . Utils::getErrorString($e)); if ($onSite) { return Redirect::to('payment/'.$invitationKey)->withInput(); } else { return Redirect::to('view/'.$invitationKey); } } } private function createPayment($invitation, $ref, $payerId = null) { $invoice = $invitation->invoice; $accountGateway = $invoice->client->account->getGatewayByType(Session::get('payment_type')); if ($invoice->account->account_key == NINJA_ACCOUNT_KEY && $invoice->amount == PRO_PLAN_PRICE) { $account = Account::with('users')->find($invoice->client->public_id); if ($account->pro_plan_paid && $account->pro_plan_paid != '0000-00-00') { $date = DateTime::createFromFormat('Y-m-d', $account->pro_plan_paid); $account->pro_plan_paid = $date->modify('+1 year')->format('Y-m-d'); } else { $account->pro_plan_paid = date_create()->format('Y-m-d'); } $account->save(); $user = $account->users()->first(); $this->accountRepo->syncAccounts($user->id, $account->pro_plan_paid); } $payment = Payment::createNew($invitation); $payment->invitation_id = $invitation->id; $payment->account_gateway_id = $accountGateway->id; $payment->invoice_id = $invoice->id; $payment->amount = $invoice->getRequestedAmount(); $payment->client_id = $invoice->client_id; $payment->contact_id = $invitation->contact_id; $payment->transaction_reference = $ref; $payment->payment_date = date_create()->format('Y-m-d'); if ($payerId) { $payment->payer_id = $payerId; } $payment->save(); Event::fire(new InvoicePaid($payment)); return $payment; } public function offsite_payment() { $payerId = Request::query('PayerID'); $token = Request::query('token'); if (!$token) { $token = Session::pull('transaction_reference'); } if (!$token) { return redirect(NINJA_WEB_URL); } $invitation = Invitation::with('invoice.client.currency', 'invoice.client.account.account_gateways.gateway')->where('transaction_reference', '=', $token)->firstOrFail(); $invoice = $invitation->invoice; $accountGateway = $invoice->client->account->getGatewayByType(Session::get('payment_type')); $gateway = self::createGateway($accountGateway); // Check for Dwolla payment error if ($accountGateway->isGateway(GATEWAY_DWOLLA) && Input::get('error')) { $errorMessage = trans('texts.payment_error')."\n\n".Input::get('error_description'); Session::flash('error', $errorMessage); Utils::logError($errorMessage); return Redirect::to('view/'.$invitation->invitation_key); } try { if (method_exists($gateway, 'completePurchase')) { $details = self::getPaymentDetails($invitation); $response = $gateway->completePurchase($details)->send(); $ref = $response->getTransactionReference(); if ($response->isSuccessful()) { $payment = self::createPayment($invitation, $ref, $payerId); Session::flash('message', trans('texts.applied_payment')); return Redirect::to('view/'.$invitation->invitation_key); } else { $errorMessage = trans('texts.payment_error')."\n\n".$response->getMessage(); Session::flash('error', $errorMessage); Utils::logError($errorMessage); return Redirect::to('view/'.$invitation->invitation_key); } } else { $payment = self::createPayment($invitation, $token, $payerId); Session::flash('message', trans('texts.applied_payment')); return Redirect::to('view/'.$invitation->invitation_key); } } catch (\Exception $e) { $errorMessage = trans('texts.payment_error'); Session::flash('error', $errorMessage); Utils::logError($errorMessage."\n\n".$e->getMessage()); return Redirect::to('view/'.$invitation->invitation_key); } } public function store() { return $this->save(); } public function update($publicId) { return $this->save($publicId); } private function save($publicId = null) { if (!$publicId && $errors = $this->paymentRepo->getErrors(Input::all())) { $url = $publicId ? 'payments/'.$publicId.'/edit' : 'payments/create'; return Redirect::to($url) ->withErrors($errors) ->withInput(); } else { $payment = $this->paymentRepo->save($publicId, Input::all()); if ($publicId) { Session::flash('message', trans('texts.updated_payment')); return Redirect::to('payments/'); } else { if (Input::get('email_receipt')) { $this->contactMailer->sendPaymentConfirmation($payment); Session::flash('message', trans('texts.created_payment_emailed_client')); } else { Session::flash('message', trans('texts.created_payment')); } return Redirect::to('clients/'.Input::get('client')); } } } public function bulk() { $action = Input::get('action'); $ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $count = $this->paymentRepo->bulk($ids, $action); if ($count > 0) { $message = Utils::pluralize($action.'d_payment', $count); Session::flash('message', $message); } return Redirect::to('payments'); } } <file_sep>/app/Models/Gateway.php <?php namespace App\Models; use Eloquent; use Omnipay; class Gateway extends Eloquent { public $timestamps = true; public static $paymentTypes = [ PAYMENT_TYPE_CREDIT_CARD, PAYMENT_TYPE_PAYPAL, PAYMENT_TYPE_BITCOIN, PAYMENT_TYPE_DWOLLA ]; public static $hiddenFields = [ // PayPal 'headerImageUrl', 'solutionType', 'landingPage', 'brandName', 'logoImageUrl', 'borderColor', // Dwolla 'returnUrl', ]; public static $optionalFields = [ // PayPal 'testMode', 'developerMode', // Dwolla 'sandbox', ]; public function getLogoUrl() { return '/images/gateways/logo_'.$this->provider.'.png'; } public static function getPaymentTypeLinks() { $data = []; foreach (self::$paymentTypes as $type) { $data[] = strtolower(str_replace('PAYMENT_TYPE_', '', $type)); } return $data; } public function getHelp() { $link = ''; if ($this->id == GATEWAY_AUTHORIZE_NET || $this->id == GATEWAY_AUTHORIZE_NET_SIM) { $link = 'http://reseller.authorize.net/application/?id=5560364'; } elseif ($this->id == GATEWAY_PAYPAL_EXPRESS) { $link = 'https://www.paypal.com/us/cgi-bin/webscr?cmd=_login-api-run'; } elseif ($this->id == GATEWAY_TWO_CHECKOUT) { $link = 'https://www.2checkout.com/referral?r=2c37ac2298'; } elseif ($this->id == GATEWAY_BITPAY) { $link = 'https://bitpay.com/dashboard/signup'; } elseif ($this->id == GATEWAY_DWOLLA) { $link = 'https://www.dwolla.com/register'; } $key = 'texts.gateway_help_'.$this->id; $str = trans($key, ['link' => "<a href='$link' target='_blank'>Click here</a>"]); return $key != $str ? $str : ''; } public function getFields() { return Omnipay::create($this->provider)->getDefaultParameters(); } public static function getPaymentType($gatewayId) { if ($gatewayId == GATEWAY_PAYPAL_EXPRESS) { return PAYMENT_TYPE_PAYPAL; } else if ($gatewayId == GATEWAY_BITPAY) { return PAYMENT_TYPE_BITCOIN; } else if ($gatewayId == GATEWAY_DWOLLA) { return PAYMENT_TYPE_DWOLLA; } else { return PAYMENT_TYPE_CREDIT_CARD; } } public static function getPrettyPaymentType($gatewayId) { return trans('texts.' . strtolower(Gateway::getPaymentType($gatewayId))); } } <file_sep>/app/Models/Credit.php <?php namespace App\Models; use Illuminate\Database\Eloquent\SoftDeletes; class Credit extends EntityModel { use SoftDeletes; protected $dates = ['deleted_at']; public function invoice() { return $this->belongsTo('App\Models\Invoice')->withTrashed(); } public function client() { return $this->belongsTo('App\Models\Client')->withTrashed(); } public function getName() { return ''; } public function getEntityType() { return ENTITY_CREDIT; } public function apply($amount) { if ($amount > $this->balance) { $applied = $this->balance; $this->balance = 0; } else { $applied = $amount; $this->balance = $this->balance - $amount; } $this->save(); return $applied; } } Credit::created(function ($credit) { Activity::createCredit($credit); }); Credit::updating(function ($credit) { Activity::updateCredit($credit); }); Credit::deleting(function ($credit) { Activity::archiveCredit($credit); }); Credit::restoring(function ($credit) { Activity::restoreCredit($credit); }); <file_sep>/resources/lang/nb_NO/texts.php <?php return array( // client 'organization' => 'Organisasjon', 'name' => 'Navn', 'website' => 'Webside', 'work_phone' => 'Telefon', 'address' => 'Adresse', 'address1' => 'Gate', 'address2' => 'Nummer', 'city' => 'By', 'state' => 'Fylke', 'postal_code' => 'Postnummer', 'country_id' => 'Land', 'contacts' => 'Kontakter', 'first_name' => 'Fornavn', 'last_name' => 'Etternavn', 'phone' => 'Telefon', 'email' => 'Email', 'additional_info' => 'Tilleggsinfo', 'payment_terms' => 'Betalingsvilk&#229;r', 'currency_id' => 'Valuta', 'size_id' => 'St&#248;rrelse', 'industry_id' => 'Sektor', 'private_notes' => 'Private notater', // invoice 'invoice' => 'Faktura', 'client' => 'Klient', 'invoice_date' => 'Faktureringsdato', 'due_date' => 'Betalingsfrist', 'invoice_number' => 'Fakturanummer', 'invoice_number_short' => 'Faktura #', 'po_number' => 'Ordrenummer', 'po_number_short' => 'Ordre #', 'frequency_id' => 'Frekvens', 'discount' => 'Rabatt', 'taxes' => 'Skatter', 'tax' => 'Skatt', 'item' => 'Bel&#248;pstype', 'description' => 'Beskrivese', 'unit_cost' => 'Š pris', 'quantity' => 'STK', 'line_total' => 'Sum', 'subtotal' => 'Totalbel&#248;p', 'paid_to_date' => 'Betalt', 'balance_due' => 'Gjenst&#229;ende', 'invoice_design_id' => 'Design', 'terms' => 'Vilk&#229;r', 'your_invoice' => 'Din faktura', 'remove_contact' => 'Fjern kontakt', 'add_contact' => 'Legg til kontakt', 'create_new_client' => 'Opprett ny klient', 'edit_client_details' => 'Endre klientdetaljer', 'enable' => 'Aktiver', 'learn_more' => 'L&#230;r mer', 'manage_rates' => 'Administrer priser', 'note_to_client' => 'Merknad til klient', 'invoice_terms' => 'Vilk&#229;r for fakturaen', 'save_as_default_terms' => 'Lagre som standard vilk&#229;r', 'download_pdf' => 'Last ned PDF', 'pay_now' => 'Betal n&#229;', 'save_invoice' => 'Lagre faktura', 'clone_invoice' => 'Kopier faktura', 'archive_invoice' => 'Arkiver faktura', 'delete_invoice' => 'Slett faktura', 'email_invoice' => 'Send faktura p&#229; epost', 'enter_payment' => 'Oppgi betaling', 'tax_rates' => 'Skattesatser', 'rate' => 'Sats', 'settings' => 'Innstillinger', 'enable_invoice_tax' => 'Aktiver for &#229; spesifisere en <b>faktura skatt</b>', 'enable_line_item_tax' => 'Aktiver for &#229; spesifisere <b>artikkel skatt</b>', // navigation 'dashboard' => 'Dashboard', 'clients' => 'Klienter', 'invoices' => 'Fakturaer', 'payments' => 'Betalinger', 'credits' => 'Kreditter', 'history' => 'Historie', 'search' => 'S&#248;k', 'sign_up' => 'Registrer deg', 'guest' => 'Gjest', 'company_details' => 'Firmainformasjon', 'online_payments' => 'Online betaling', 'notifications' => 'Varsler', 'import_export' => 'Import/Export', 'done' => 'Ferdig', 'save' => 'Lagre', 'create' => 'Lag', 'upload' => 'Last opp', 'import' => 'Importer', 'download' => 'Last ned', 'cancel' => 'Avbryt', 'close' => 'Lukk', 'provide_email' => 'Vennligst oppgi en gyldig e-postadresse', 'powered_by' => 'Drevet av', 'no_items' => 'Ingen elementer', // recurring invoices 'recurring_invoices' => 'Gjentakende fakturaer', 'recurring_help' => '<p>Automatisk send klienter de samme fakturaene ukentlig, bi-m&#229;nedlig, m&#229;nedlig, kvartalsvis eller &#229;rlig.</p> <p>Bruk :MONTH, :QUARTER eller :YEAR for dynamiske datoer. Grunnleggende matematikk fungerer ogs&#229;, for eksempel :MONTH-1.</p> <p>Eksempler p&#229; dynamiske faktura variabler:</p> <ul> <li>"Treningsmedlemskap for m&#229;neden :MONTH" => "Treningsmedlemskap for m&#229;neden Juli"</li> <li>":YEAR+1 &#229;rlig abonnement" => "2015 &#229;rlig abonnement"</li> <li>"Forh&#229;ndsbetaling for :QUARTER+1" => "Forh&#229;ndsbetaling for Q2"</li> </ul>', // dashboard 'in_total_revenue' => 'totale inntekter', 'billed_client' => 'fakturert klient', 'billed_clients' => 'fakturerte klienter', 'active_client' => 'aktiv klient', 'active_clients' => 'aktive klienter', 'invoices_past_due' => 'Fakturaer forfalt', 'upcoming_invoices' => 'Forest&#229;ende fakturaer', 'average_invoice' => 'Gjennomsnittlige fakturaer', // list pages 'archive' => 'Arkiv', 'delete' => 'Slett', 'archive_client' => 'Arkiver klient', 'delete_client' => 'Slett klient', 'archive_payment' => 'Arkiver betaling', 'delete_payment' => 'Slett betaling', 'archive_credit' => 'Arkiver kreditt', 'delete_credit' => 'Slett kreditt', 'show_archived_deleted' => 'Vis slettet/arkivert', 'filter' => 'Filter', 'new_client' => 'Ny klient', 'new_invoice' => 'Ny faktura', 'new_payment' => 'Ny betaling', 'new_credit' => 'Ny kreditt', 'contact' => 'Kontakt', 'date_created' => 'Dato opprettet', 'last_login' => 'Siste p&#229;logging', 'balance' => 'Balanse', 'action' => 'Handling', 'status' => 'Status', 'invoice_total' => 'Faktura total', 'frequency' => 'Frekvens', 'start_date' => 'Startdato', 'end_date' => 'Sluttdato', 'transaction_reference' => 'Transaksjonsreferanse', 'method' => 'Betalingsm&#229;te', 'payment_amount' => 'Bel&#248;p', 'payment_date' => 'Betalingsdato', 'credit_amount' => 'Kredittbel&#248;p', 'credit_balance' => 'Kreditsaldo', 'credit_date' => 'Kredittdato', 'empty_table' => 'Ingen data er tilgjengelige i tabellen', 'select' => 'Velg', 'edit_client' => 'Rediger klient', 'edit_invoice' => 'Rediger faktura', // client view page 'create_invoice' => 'Lag faktura', 'enter_credit' => 'Oppgi kreditt', 'last_logged_in' => 'Sist p&#229;logget', 'details' => 'Detaljer', 'standing' => 'St&#229;ende', 'credit' => 'Kreditt', 'activity' => 'Aktivitet', 'date' => 'Dato', 'message' => 'Beskjed', 'adjustment' => 'Justering', 'are_you_sure' => 'Er du sikker?', // payment pages 'payment_type_id' => 'Betalingsmetode', 'amount' => 'Bel&#248;p', // account/company pages 'work_email' => 'Email', 'language_id' => 'Spr&#229;k', 'timezone_id' => 'Tidssone', 'date_format_id' => 'Dato format', 'datetime_format_id' => 'Dato/Tidsformat', 'users' => 'Brukere', 'localization' => 'Lokaliseing', 'remove_logo' => 'Fjern logo', 'logo_help' => 'St&#248;ttedefiltyper: JPEG, GIF og PNG. Anbefalt st&#248;rrelse: 200px bredde by 120px h&#248;yde', 'payment_gateway' => 'Betalingsl&#248;sning', 'gateway_id' => 'Tilbyder', 'email_notifications' => 'Varsel via email', 'email_sent' => 'Varsle n&#229;r en faktura er <b>sendt</b>', 'email_viewed' => 'Varsle n&#229;r en faktura er <b>sett</b>', 'email_paid' => 'Varsle n&#229;r en faktura er <b>betalt</b>', 'site_updates' => 'Nettsted oppdateringer', 'custom_messages' => 'Tilpassede meldinger', 'default_invoice_terms' => 'Sett standard fakturavilk&#229;r', 'default_email_footer' => 'Sett standard emailsignatur', 'import_clients' => 'Importer klientdata', 'csv_file' => 'Velg CSV-fil', 'export_clients' => 'Exporter klientdata', 'select_file' => 'Vennligst velg en fil', 'first_row_headers' => 'Bruk f&#248;rste rad som overskrifter', 'column' => 'Kolonne', 'sample' => 'Eksempel', 'import_to' => 'Importer til', 'client_will_create' => 'Klient vil bli opprettet', 'clients_will_create' => 'Klienter vil bli opprettet', 'email_settings' => 'Email Settings', 'pdf_email_attachment' => 'Attach PDF to Emails', // application messages 'created_client' => 'Klient opprettet suksessfullt', 'created_clients' => 'Klienter opprettet suksessfullt', 'updated_settings' => 'Innstillger oppdatert', 'removed_logo' => 'Logo fjernet', 'sent_message' => 'Melding sendt', 'invoice_error' => 'Vennligst s&#248;rg for &#229; velge en klient og rette eventuelle feil', 'limit_clients' => 'Dessverre, dette vil overstige grensen p&#229; :count klienter', 'payment_error' => 'Det oppstod en feil under din betaling. Vennligst pr&#248;v igjen senere.', 'registration_required' => 'Vennligst registrer deg for &#229; sende e-postfaktura', 'confirmation_required' => 'Vennligst bekreft din e-postadresse', 'updated_client' => 'Klient oppdatert', 'created_client' => 'Klient lagret', 'archived_client' => 'Klient arkivert', 'archived_clients' => 'Arkiverte :count klienter', 'deleted_client' => 'Klient slettet', 'deleted_clients' => 'Slettet :count kliener', 'updated_invoice' => 'Faktura oppdatert', 'created_invoice' => 'Faktura opprettet', 'cloned_invoice' => 'Faktura kopiert', 'emailed_invoice' => 'Emailfaktura sendt', 'and_created_client' => 'og klient opprettet', 'archived_invoice' => 'Faktura arkivert', 'archived_invoices' => 'Fakturaer arkivert', 'deleted_invoice' => 'Faktura slettet', 'deleted_invoices' => 'Slettet :count fakturaer', 'created_payment' => 'Betaling opprettet', 'archived_payment' => 'Betaling arkivert', 'archived_payments' => 'Arkiverte :count betalinger', 'deleted_payment' => 'Betaling slettet', 'deleted_payments' => 'Slettet :count betalinger', 'applied_payment' => 'Betaling lagret', 'created_credit' => 'Kreditt opprettet', 'archived_credit' => 'Kreditt arkivert', 'archived_credits' => 'Arkiverte :count kreditter', 'deleted_credit' => 'Kreditt slettet', 'deleted_credits' => 'Slettet :count kreditter', // Emails 'confirmation_subject' => 'Invoice Ninja kontobekreftelse', 'confirmation_header' => 'Kontobekreftelse', 'confirmation_message' => 'Vennligst &#229;pne koblingen nedenfor for &#229; bekrefte kontoen din.', 'invoice_subject' => 'Ny faktura :invoice fra :account', 'invoice_message' => 'Sor &#229; se din faktura p&#229; :amount, klikk linken nedenfor.', 'payment_subject' => 'Betaling mottatt', 'payment_message' => 'Fakk for din betaling p&#229;lydende :amount.', 'email_salutation' => 'Kj&#230;re :name,', 'email_signature' => 'Med vennlig hilsen,', 'email_from' => 'The Invoice Ninja Team', 'user_email_footer' => 'For &#229; justere varslingsinnstillingene vennligst bes&#248;k '.SITE_URL.'/company/notifications', 'invoice_link_message' => 'Hvis du vil se din klientfaktura klikk p&#229; linken under:', 'notification_invoice_paid_subject' => 'Faktura :invoice betalt av :client', 'notification_invoice_sent_subject' => 'Faktura :invoice sendt til :client', 'notification_invoice_viewed_subject' => 'Faktura :invoice sett av :client', 'notification_invoice_paid' => 'En betaling p&#229;lydende :amount ble gjort av :client for faktura :invoice.', 'notification_invoice_sent' => 'Email har blitt sendt til :client - Faktura :invoice p&#229;lydende :amount.', 'notification_invoice_viewed' => ':client har n&#229; sett faktura :invoice p&#229;lydende :amount.', 'reset_password' => 'Du kan nullstille ditt passord ved &#229; bes&#248;ke f&#248;lgende link:', 'reset_password_footer' => 'Hvis du ikke ba om &#229; f&#229; nullstillt ditt passord, vennligst kontakt kundeservice: ' . CONTACT_EMAIL, // Payment page 'secure_payment' => 'Sikker betaling', 'card_number' => 'Kortnummer', 'expiration_month' => 'Utl&#248;psdato', 'expiration_year' => 'Utl&#248;ps&#229;r', 'cvv' => 'CVV', // Security alerts 'security' => [ 'too_many_attempts' => 'For mange fors&#248;k. Pr&#248;v igjen om noen f&#229; minutter.', 'wrong_credentials' => 'Feil e-post eller passord.', 'confirmation' => 'Din konto har blitt bekreftet!', 'wrong_confirmation' => 'Feil bekreftelseskode.', 'password_forgot' => 'Informasjonen om tilbakestilling av passord ble sendt til e-postadressen.', 'password_reset' => '<PASSWORD>.', 'wrong_password_reset' => 'U<PASSWORD>ig passord. Pr&#248;v p&#229; nytt', ], // Pro Plan 'pro_plan' => [ 'remove_logo' => ':link for &#229; fjerne Invoice Ninja-logoen, oppgrader til en Pro Plan', 'remove_logo_link' => 'Klikk her', ], 'logout' => 'Logg ut', 'sign_up_to_save' => 'Registrer deg for &#229; lagre arbeidet ditt', 'agree_to_terms' =>'Jeg godtar Invoice Ninja :terms', 'terms_of_service' => 'vilk&#229;r for bruk', 'email_taken' => 'Epost-adressen er allerede registrert', 'working' => 'Jobber', 'success' => 'Suksess', 'success_message' => 'Du har n&#229; blitt registrert. Vennligst g&#229; inn p&#229; linken som du har mottatt i e-postbekreftelsen for &#229; bekrefte e-postadressen.', 'erase_data' => 'Dette vil permanent slette dine data.', 'password' => '<PASSWORD>', 'pro_plan_product' => 'Pro Plan', 'pro_plan_description' => 'Ett &#229;rs innmelding i Invoice Ninja Pro Plan.', 'pro_plan_success' => 'Takk for at du valgte Invoice Ninja\'s Pro plan!<p/>&nbsp;<br/> <b>Neste steg</b><p/>en betalbar faktura er send til e-postadressen som er tilknyttet knotoen din. For &#229; l&#229;se opp alle de utrolige Pro-funksjonene, kan du f&#248;lge instruksjonene p&#229; fakturaen til &#229; betale for et &#229;r med Pro-niv&#229; funksjonerer.<p/> Finner du ikke fakturaen? Trenger du mer hjelp? Vi hjelper deg gjerne om det skulle v&#230;re noe -- kontakt oss p&#229; <EMAIL>', 'unsaved_changes' => 'Du har ulagrede endringer', 'custom_fields' => 'Egendefinerte felt', 'company_fields' => 'Selskapets felt', 'client_fields' => 'Klientens felt', 'field_label' => 'Felt etikett', 'field_value' => 'Feltets verdi', 'edit' => 'Endre', 'set_name' => 'Sett ditt firmanavn', 'view_as_recipient' => 'Vis som mottaker', // product management 'product_library' => 'Produktbibliotek', 'product' => 'Produkt', 'products' => 'Produkter', 'fill_products' => 'Automatisk-fyll produkter', 'fill_products_help' => 'Valg av produkt vil automatisk fylle ut <b>beskrivelse og kostnaden</b>', 'update_products' => 'Automatisk oppdater produkter', 'update_products_help' => '&#197; endre en faktura vil automatisk <b>oppdatere produktbilioteket</b>', 'create_product' => 'Lag nytt produkt', 'edit_product' => 'Endre produkt', 'archive_product' => 'Arkiver produkt', 'updated_product' => 'Produkt oppdatert', 'created_product' => 'Produkt lagret', 'archived_product' => 'Produkt arkivert', 'pro_plan_custom_fields' => ':link for &#229; aktivere egendefinerte felt ved &#229; delta i Pro Plan', 'advanced_settings' => 'Avanserte innstillinger', 'pro_plan_advanced_settings' => ':link for &#229; aktivere avanserte innstillinger ved &#229; delta i en Pro Plan', 'invoice_design' => 'Fakturadesign', 'specify_colors' => 'Egendefinerte farger', 'specify_colors_label' => 'Velg farger som brukes i fakturaen', 'chart_builder' => 'Diagram bygger', 'ninja_email_footer' => 'Bruk :site til &#229; fakturere kundene dine og f&#229; betalt p&#229; nettet - gratis!', 'go_pro' => 'Velg Pro', // Quotes 'quote' => 'Pristilbud', 'quotes' => 'Pristilbud', 'quote_number' => 'Tilbuds nummer', 'quote_number_short' => 'Tilbuds #', 'quote_date' => 'Tilbudsdato', 'quote_total' => 'Tilbud total', 'your_quote' => 'Ditt tilbud', 'total' => 'Total', 'clone' => 'Kopier', 'new_quote' => 'Nytt tilbud', 'create_quote' => 'Lag tilbud', 'edit_quote' => 'Endre tilbud', 'archive_quote' => 'Arkiver tilbud', 'delete_quote' => 'Slett tilbud', 'save_quote' => 'Lagre tilbud', 'email_quote' => 'Email tilbudet', 'clone_quote' => 'Kopier tilbud', 'convert_to_invoice' => 'Konverter til en faktura', 'view_invoice' => 'Se faktura', 'view_client' => 'Vis klient', 'view_quote' => 'Se tilbud', 'updated_quote' => 'Tilbud oppdatert', 'created_quote' => 'Tilbud opprettet', 'cloned_quote' => 'Tilbud kopiert', 'emailed_quote' => 'Tilbud sendt som email', 'archived_quote' => 'Tilbud arkivert', 'archived_quotes' => 'Arkiverte :count tilbud', 'deleted_quote' => 'Tilbud slettet', 'deleted_quotes' => 'Slettet :count tilbud', 'converted_to_invoice' => 'Tilbud konvertert til faktura', 'quote_subject' => 'Nytt tilbud fra :account', 'quote_message' => 'For &#229; se ditt tilbud p&#229;lydende :amount, klikk linken nedenfor.', 'quote_link_message' => 'Hvis du vil se din klients tilbud, klikk p&#229; linken under:', 'notification_quote_sent_subject' => 'Tilbud :invoice sendt til :client', 'notification_quote_viewed_subject' => 'Tilbudet :invoice er n&#229; sett av :client', 'notification_quote_sent' => 'F&#248;lgende klient :client ble sendt tilbudsfaktura :invoice p&#229;lydende :amount.', 'notification_quote_viewed' => 'F&#248;lgende klient :client har n&#229; sett tilbudsfakturaen :invoice p&#229;lydende :amount.', 'session_expired' => '&#216;kten er utl&#248;pt.', 'invoice_fields' => 'Faktura felt', 'invoice_options' => 'Faktura alternativer', 'hide_quantity' => 'Skjul antall', 'hide_quantity_help' => 'Hvis du alltid har 1 (en) av hvert element p&#229; fakturaen, kan du velge dette alternativet for &#229; ikke vise antall p&#229; fakturaen.', 'hide_paid_to_date' => 'Skjul delbetalinger', 'hide_paid_to_date_help' => 'Bare vis delbetalinger om det har forekommet en delbetaling.', 'charge_taxes' => 'Inkluder skatt', 'user_management' => 'Brukerh&#229;ndtering', 'add_user' => 'Legg til bruker', 'send_invite' => 'Send invitasjon', 'sent_invite' => 'Invitasjon sendt', 'updated_user' => 'Bruker oppdatert', 'invitation_message' => 'Du har blitt invitert av :invitor. ', 'register_to_add_user' => 'Vennligst registrer deg for &#229; legge til en bruker', 'user_state' => 'Status', 'edit_user' => 'Endre bruker', 'delete_user' => 'Slett bruker', 'active' => 'Aktiv', 'pending' => 'Avventer', 'deleted_user' => 'Bruker slettet', 'limit_users' => 'Dessverre, vil dette overstiger grensen p&#229; ' . MAX_NUM_USERS . ' brukere', 'confirm_email_invoice' => 'Are you sure you want to email this invoice?', 'confirm_email_quote' => 'Are you sure you want to email this quote?', 'confirm_recurring_email_invoice' => 'Recurring is enabled, are you sure you want this invoice emailed?', 'cancel_account' => 'Cancel Account', 'cancel_account_message' => 'Warning: This will permanently erase all of your data, there is no undo.', 'go_back' => 'Go Back', 'data_visualizations' => 'Data Visualizations', 'sample_data' => 'Sample data shown', 'hide' => 'Hide', 'new_version_available' => 'A new version of :releases_link is available. You\'re running v:user_version, the latest is v:latest_version', 'invoice_settings' => 'Invoice Settings', 'invoice_number_prefix' => 'Invoice Number Prefix', 'invoice_number_counter' => 'Invoice Number Counter', 'quote_number_prefix' => 'Quote Number Prefix', 'quote_number_counter' => 'Quote Number Counter', 'share_invoice_counter' => 'Share invoice counter', 'invoice_issued_to' => 'Invoice issued to', 'invalid_counter' => 'To prevent a possible conflict please set either an invoice or quote number prefix', 'mark_sent' => 'Mark sent', 'gateway_help_1' => ':link to sign up for Authorize.net.', 'gateway_help_2' => ':link to sign up for Authorize.net.', 'gateway_help_17' => ':link to get your PayPal API signature.', 'gateway_help_23' => 'Note: use your secret API key, not your publishable API key.', 'gateway_help_27' => ':link to sign up for TwoCheckout.', 'more_designs' => 'More designs', 'more_designs_title' => 'Additional Invoice Designs', 'more_designs_cloud_header' => 'Go Pro for more invoice designs', 'more_designs_cloud_text' => '', 'more_designs_self_host_header' => 'Get 6 more invoice designs for just $20', 'more_designs_self_host_text' => '', 'buy' => 'Buy', 'bought_designs' => 'Successfully added additional invoice designs', 'sent' => 'sent', 'timesheets' => 'Timesheets', 'payment_title' => 'Enter Your Billing Address and Credit Card information', 'payment_cvv' => '*This is the 3-4 digit number onthe back of your card', 'payment_footer1' => '*Billing address must match address associated with credit card.', 'payment_footer2' => '*Please click "PAY NOW" only once - transaction may take up to 1 minute to process.', 'vat_number' => 'Vat Number', 'id_number' => 'ID Number', 'white_label_link' => 'White label', 'white_label_text' => 'Purchase a white label license for $'.WHITE_LABEL_PRICE.' to remove the Invoice Ninja branding from the top of the client pages.', 'white_label_header' => 'White Label', 'bought_white_label' => 'Successfully enabled white label license', 'white_labeled' => 'White labeled', 'restore' => 'Restore', 'restore_invoice' => 'Restore Invoice', 'restore_quote' => 'Restore Quote', 'restore_client' => 'Restore Client', 'restore_credit' => 'Restore Credit', 'restore_payment' => 'Restore Payment', 'restored_invoice' => 'Successfully restored invoice', 'restored_quote' => 'Successfully restored quote', 'restored_client' => 'Successfully restored client', 'restored_payment' => 'Successfully restored payment', 'restored_credit' => 'Successfully restored credit', 'reason_for_canceling' => 'Help us improve our site by telling us why you\'re leaving.', 'discount_percent' => 'Percent', 'discount_amount' => 'Amount', 'invoice_history' => 'Invoice History', 'quote_history' => 'Quote History', 'current_version' => 'Current version', 'select_versiony' => 'Select version', 'view_history' => 'View History', 'edit_payment' => 'Edit Payment', 'updated_payment' => 'Successfully updated payment', 'deleted' => 'Deleted', 'restore_user' => 'Restore User', 'restored_user' => 'Successfully restored user', 'show_deleted_users' => 'Show deleted users', 'email_templates' => 'Email Templates', 'invoice_email' => 'Invoice Email', 'payment_email' => 'Payment Email', 'quote_email' => 'Quote Email', 'reset_all' => 'Reset All', 'approve' => 'Approve', 'token_billing_type_id' => 'Token Billing', 'token_billing_help' => 'Enables you to store credit cards with your gateway, and charge them at a later date.', 'token_billing_1' => 'Disabled', 'token_billing_2' => 'Opt-in - checkbox is shown but not selected', 'token_billing_3' => 'Opt-out - checkbox is shown and selected', 'token_billing_4' => 'Always', 'token_billing_checkbox' => 'Store credit card details', 'view_in_stripe' => 'View in Stripe', 'use_card_on_file' => 'Use card on file', 'edit_payment_details' => 'Edit payment details', 'token_billing' => 'Save card details', 'token_billing_secure' => 'The data is stored securely by :stripe_link', 'support' => 'Support', 'contact_information' => 'Contact information', '256_encryption' => '256-Bit Encryption', 'amount_due' => 'Amount due', 'billing_address' => 'Billing address', 'billing_method' => 'Billing method', 'order_overview' => 'Order overview', 'match_address' => '*Address must match address associated with credit card.', 'click_once' => '*Please click "PAY NOW" only once - transaction may take up to 1 minute to process.', 'default_invoice_footer' => 'Set default invoice footer', 'invoice_footer' => 'Invoice footer', 'save_as_default_footer' => 'Save as default footer', 'token_management' => 'Token Management', 'tokens' => 'Tokens', 'add_token' => 'Add Token', 'show_deleted_tokens' => 'Show deleted tokens', 'deleted_token' => 'Successfully deleted token', 'created_token' => 'Successfully created token', 'updated_token' => 'Successfully updated token', 'edit_token' => 'Edit Token', 'delete_token' => 'Delete Token', 'token' => 'Token', 'add_gateway' => 'Add Gateway', 'delete_gateway' => 'Delete Gateway', 'edit_gateway' => 'Edit Gateway', 'updated_gateway' => 'Successfully updated gateway', 'created_gateway' => 'Successfully created gateway', 'deleted_gateway' => 'Successfully deleted gateway', 'pay_with_paypal' => 'PayPal', 'pay_with_card' => 'Credit card', 'change_password' => '<PASSWORD>', 'current_password' => '<PASSWORD>', 'new_password' => '<PASSWORD>', 'confirm_password' => '<PASSWORD>', 'password_error_incorrect' => 'The current password is incorrect.', 'password_error_invalid' => 'The new password is invalid.', 'updated_password' => '<PASSWORD>', 'api_tokens' => 'API Tokens', 'users_and_tokens' => 'Users & Tokens', 'account_login' => 'Account Login', 'recover_password' => '<PASSWORD>', 'forgot_password' => '<PASSWORD>?', 'email_address' => 'Email address', 'lets_go' => 'Letís go', 'password_recovery' => 'Password Recovery', 'send_email' => 'Send email', 'set_password' => '<PASSWORD>', 'converted' => 'Converted', 'email_approved' => 'Email me when a quote is <b>approved</b>', 'notification_quote_approved_subject' => 'Quote :invoice was approved by :client', 'notification_quote_approved' => 'The following client :client approved Quote :invoice for :amount.', 'resend_confirmation' => 'Resend confirmation email', 'confirmation_resent' => 'The confirmation email was resent', 'gateway_help_42' => ':link to sign up for BitPay.<br/>Note: use a Legacy API Key, not an API token.', 'payment_type_credit_card' => 'Credit card', 'payment_type_paypal' => 'PayPal', 'payment_type_bitcoin' => 'Bitcoin', 'knowledge_base' => 'Knowledge Base', 'partial' => 'Partial', 'partial_remaining' => ':partial of :balance', 'more_fields' => 'More Fields', 'less_fields' => 'Less Fields', 'client_name' => '<NAME>', 'pdf_settings' => 'PDF Settings', 'product_settings' => 'Product Settings', 'auto_wrap' => 'Auto Line Wrap', 'duplicate_post' => 'Warning: the previous page was submitted twice. The second submission had been ignored.', 'view_documentation' => 'View Documentation', 'app_title' => 'Free Open-Source Online Invoicing', 'app_description' => 'Invoice Ninja is a free, open-source solution for invoicing and billing customers. With Invoice Ninja, you can easily build and send beautiful invoices from any device that has access to the web. Your clients can print your invoices, download them as pdf files, and even pay you online from within the system.', 'rows' => 'rows', 'www' => 'www', 'logo' => 'Logo', 'subdomain' => 'Subdomain', 'provide_name_or_email' => 'Please provide a contact name or email', 'charts_and_reports' => 'Charts & Reports', 'chart' => 'Chart', 'report' => 'Report', 'group_by' => 'Group by', 'paid' => 'Paid', 'enable_report' => 'Report', 'enable_chart' => 'Chart', 'totals' => 'Totals', 'run' => 'Run', 'export' => 'Export', 'documentation' => 'Documentation', 'zapier' => 'Zapier <sup>Beta</sup>', 'recurring' => 'Recurring', 'last_invoice_sent' => 'Last invoice sent :date', 'processed_updates' => 'Successfully completed update', 'tasks' => 'Tasks', 'new_task' => 'New Task', 'start_time' => 'Start Time', 'created_task' => 'Successfully created task', 'updated_task' => 'Successfully updated task', 'edit_task' => 'Edit Task', 'archive_task' => 'Archive Task', 'restore_task' => 'Restore Task', 'delete_task' => 'Delete Task', 'stop_task' => 'Stop Task', 'time' => 'Time', 'start' => 'Start', 'stop' => 'Stop', 'now' => 'Now', 'timer' => 'Timer', 'manual' => 'Manual', 'date_and_time' => 'Date & Time', 'second' => 'second', 'seconds' => 'seconds', 'minute' => 'minute', 'minutes' => 'minutes', 'hour' => 'hour', 'hours' => 'hours', 'task_details' => 'Task Details', 'duration' => 'Duration', 'end_time' => 'End Time', 'end' => 'End', 'invoiced' => 'Invoiced', 'logged' => 'Logged', 'running' => 'Running', 'task_error_multiple_clients' => 'The tasks can\'t belong to different clients', 'task_error_running' => 'Please stop running tasks first', 'task_error_invoiced' => 'Tasks have already been invoiced', 'restored_task' => 'Successfully restored task', 'archived_task' => 'Successfully archived task', 'archived_tasks' => 'Successfully archived :count tasks', 'deleted_task' => 'Successfully deleted task', 'deleted_tasks' => 'Successfully deleted :count tasks', 'create_task' => 'Create Task', 'stopped_task' => 'Successfully stopped task', 'invoice_task' => 'Invoice Task', 'invoice_labels' => 'Invoice Labels', 'prefix' => 'Prefix', 'counter' => 'Counter', 'payment_type_dwolla' => 'Dwolla', 'gateway_help_43' => ':link to sign up for Dwolla.', 'partial_value' => 'Must be greater than zero and less than the total', 'more_actions' => 'More Actions', 'pro_plan_title' => 'NINJA PRO', 'pro_plan_call_to_action' => 'Upgrade Now!', 'pro_plan_feature1' => 'Create Unlimited Clients', 'pro_plan_feature2' => 'Access to 10 Beautiful Invoice Designs', 'pro_plan_feature3' => 'Custom URLs - "YourBrand.InvoiceNinja.com"', 'pro_plan_feature4' => 'Remove "Created by Invoice Ninja"', 'pro_plan_feature5' => 'Multi-user Access & Activity Tracking', 'pro_plan_feature6' => 'Create Quotes & Pro-forma Invoices', 'pro_plan_feature7' => 'Customize Invoice Field Titles & Numbering', 'pro_plan_feature8' => 'Option to Attach PDFs to Client Emails', 'resume' => 'Resume', 'break_duration' => 'Break', 'edit_details' => 'Edit Details', 'work' => 'Work', 'timezone_unset' => 'Please :link to set your timezone', 'click_here' => 'click here', 'email_receipt' => 'Email payment receipt to the client', 'created_payment_emailed_client' => 'Successfully created payment and emailed client', 'add_company' => 'Add Company', 'untitled' => 'Untitled', 'new_company' => 'New Company', 'associated_accounts' => 'Successfully linked accounts', 'unlinked_account' => 'Successfully unlinked accounts', 'login' => 'Login', 'or' => 'or', 'email_error' => 'There was a problem sending the email', 'confirm_recurring_timing' => 'Note: emails are sent at the start of the hour.', 'old_browser' => 'Please use a <a href="'.OUTDATE_BROWSER_URL.'" target="_blank">newer browser</a>', 'payment_terms_help' => 'Sets the default invoice due date', 'unlink_account' => 'Unlink Account', 'unlink' => 'Unlink', 'show_address' => 'Show Address', 'show_address_help' => 'Require client to provide their billing address', 'update_address' => 'Update Address', 'update_address_help' => 'Update client\'s address with provided details', 'times' => 'Times', 'set_now' => 'Set now', 'dark_mode' => 'Dark Mode', 'dark_mode_help' => 'Show white text on black background', 'add_to_invoice' => 'Add to invoice :invoice', 'create_new_invoice' => 'Create new invoice', 'task_errors' => 'Please correct any overlapping times', 'from' => 'From', 'to' => 'To', 'font_size' => 'Font Size', 'primary_color' => 'Primary Color', 'secondary_color' => 'Secondary Color', 'customize_design' => 'Customize Design', 'content' => 'Content', 'styles' => 'Styles', 'defaults' => 'Defaults', 'margins' => 'Margins', 'header' => 'Header', 'footer' => 'Footer', 'custom' => 'Custom', 'invoice_to' => 'Invoice to', 'invoice_no' => 'Invoice No.', 'recent_payments' => 'Recent Payments', 'outstanding' => 'Outstanding', 'manage_companies' => 'Manage Companies', 'total_revenue' => 'Total Revenue', 'current_user' => 'Current User', 'new_recurring_invoice' => 'New Recurring Invoice', 'recurring_invoice' => 'Recurring Invoice', 'recurring_too_soon' => 'It\'s too soon to create the next recurring invoice', 'created_by_invoice' => 'Created by :invoice', 'primary_user' => 'Primary User', 'help' => 'Help', 'customize_help' => '<p>We use <a href="http://pdfmake.org/" target="_blank">pdfmake</a> to define the invoice designs declaratively. The pdfmake <a href="http://pdfmake.org/playground.html" target="_blank">playground</a> provide\'s a great way to see the library in action.</p> <p>You can access any invoice field by adding <code>Value</code> to the end. For example <code>$invoiceNumberValue</code> displays the invoice number.</p> <p>To access a child property using dot notation. For example to show the client name you could use <code>$client.nameValue</code>.</p> <p>If you need help figuring something out post a question to our <a href="https://www.invoiceninja.com/forums/forum/support/" target="_blank">support forum</a>.</p>' );<file_sep>/tests/acceptance/InvoiceCest.php <?php use \AcceptanceTester; use Faker\Factory; class InvoiceCest { /** * @var \Faker\Generator */ private $faker; public function _before(AcceptanceTester $I) { $I->checkIfLogin($I); $this->faker = Factory::create(); } public function createInvoice(AcceptanceTester $I) { $clientName = $I->grabFromDatabase('clients', 'name'); $I->wantTo('create an invoice'); $I->amOnPage('/invoices/create'); $invoiceNumber = $I->grabAttributeFrom('#invoice_number', 'value'); $I->selectDropdown($I, $clientName, '.client_select .dropdown-toggle'); $I->selectDataPicker($I, '#invoice_date'); $I->selectDataPicker($I, '#due_date', '+ 15 day'); $I->fillField('#po_number', rand(100, 200)); $I->fillField('#discount', rand(0, 20)); $this->fillItems($I); $I->click('#saveButton'); $I->wait(1); $I->see($invoiceNumber); } public function createRecurringInvoice(AcceptanceTester $I) { $clientName = $I->grabFromDatabase('clients', 'name'); $I->wantTo('create a recurring invoice'); $I->amOnPage('/recurring_invoices/create'); $I->selectDropdown($I, $clientName, '.client_select .dropdown-toggle'); //$I->selectOption('#frequency_id', Helper::getRandom('Frequency')); $I->selectDataPicker($I, '#start_date'); $I->selectDataPicker($I, '#end_date', '+ 1 week'); $I->fillField('#po_number', rand(100, 200)); $I->fillField('#discount', rand(0, 20)); $this->fillItems($I); $I->executeJS('submitAction()'); $I->wait(1); $I->see($clientName); } public function editInvoice(AcceptanceTester $I) { $I->wantTo('edit an invoice'); $I->amOnPage('/invoices/1/edit'); //change po_number with random number $po_number = rand(100, 300); $I->fillField('po_number', $po_number); //save $I->executeJS('submitAction()'); $I->wait(1); //check if po_number was updated $I->seeInDatabase('invoices', ['po_number' => $po_number]); } public function cloneInvoice(AcceptanceTester $I) { $I->wantTo('clone an invoice'); $I->amOnPage('invoices/1/clone'); $invoiceNumber = $I->grabAttributeFrom('#invoice_number', 'value'); $I->executeJS('submitAction()'); $I->wait(1); $I->see($invoiceNumber); } /* public function deleteInvoice(AcceptanceTester $I) { $I->wantTo('delete an invoice'); $I->amOnPage('/invoices'); $I->seeCurrentUrlEquals('/invoices'); //delete invoice $I->executeJS(sprintf('deleteEntity(%d)', $id = Helper::getRandom('Invoice', 'public_id', ['is_quote' => 0]))); $I->acceptPopup(); $I->wait(5); //check if invoice was removed $I->seeInDatabase('invoices', ['public_id' => $id, 'is_deleted' => true]); } */ /* public function indexInvoice(AcceptanceTester $I) { $I->wantTo('list invoices'); $I->amOnPage('/invoices'); $I->seeCurrentUrlEquals('/invoices'); $random_invoice_number = Helper::getRandom('Invoice', 'invoice_number', [ 'is_quote' => 0, 'is_recurring' => false ]); if ($random_invoice_number) { $I->wait(2); $I->see($random_invoice_number); } } */ private function fillItems(AcceptanceTester $I, $max = 2) { for ($i = 1; $i <= $max; $i++) { $row_selector = sprintf('table.invoice-table tbody tr:nth-child(%d) ', $i); $product_key = $this->faker->text(10); $description = $this->faker->text(80); $unit_cost = $this->faker->randomFloat(2, 0, 100); $quantity = $this->faker->randomDigitNotNull; $I->fillField($row_selector.'#product_key', $product_key); $I->fillField($row_selector.'textarea', $description); $I->fillField($row_selector.'td:nth-child(4) input', $unit_cost); $I->fillField($row_selector.'td:nth-child(5) input', $quantity); } } } <file_sep>/tests/acceptance/ChartsAndReportsCest.php <?php use \AcceptanceTester; use Faker\Factory; class ChartsAndReportsCest { private $faker; public function _before(AcceptanceTester $I) { $I->checkIfLogin($I); $this->faker = Factory::create(); } public function _after(AcceptanceTester $I) { } // tests public function updateChartsAndReportsPage(AcceptanceTester $I) { $faker = Faker\Factory::create(); $I->wantTo("Run the report"); $I->amOnPage('/company/advanced_settings/charts_and_reports'); /* $format = 'M d,Y'; $start_date = date ( $format, strtotime ( '-7 day' . $format)); $I->fillField(['name' => 'start_date'],$start_date); $I->fillField(['name' => 'start_date'], 'April 15, 2015'); $I->fillField(['name' => 'end_date'], date('M d,Y')); $I->fillField(['name' => 'end_date'], 'August 29, 2015'); */ $I->checkOption(['name' => 'enable_report']); $I->selectOption("#report_type", 'Client'); $I->checkOption(['name' => 'enable_chart']); $rand = ['DAYOFYEAR', 'WEEK', 'MONTH']; $I->selectOption("#group_by", $rand[array_rand($rand)]); $rand = ['Bar', 'Line']; $I->selectOption("#chart_type", $rand[array_rand($rand)]); $I->click('Run'); $I->see('Start Date'); } /* public function showDataVisualization(AcceptanceTester $I) { $I->wantTo('Display pdf data'); $I->amOnPage('/company/advanced_settings/data_visualizations'); $optionTest = "1"; // This is the option to test! $I->selectOption('#groupBySelect', $optionTest); $models = ['Client', 'Invoice', 'Product']; //$all = Helper::getRandom($models[array_rand($models)], 'all'); $all = Helper::getRandom('Client', 'all'); $labels = $this->getLabels($optionTest); $all_items = true; $I->seeElement('div.svg-div svg g:nth-child(2)'); for ($i = 0; $i < count($labels); $i++) { $text = $I->grabTextFrom('div.svg-div svg g:nth-child('.($i+2).') text'); //$I->seeInField('div.svg-div svg g:nth-child('.($i+2).') text', $labels[$i]); if (!in_array($text, $labels)) { $all_items = false; break; } } if (!$all_items) { $I->see('Fail', 'Fail'); } } private function getLabels($option) { $invoices = \App\Models\Invoice::where('user_id', '1')->get(); $clients = []; foreach ($invoices as $invoice) { $clients[] = \App\Models\Client::where('public_id', $invoice->client_id)->get(); } $clientNames = []; foreach ($clients as $client) { $clientNames[] = $client[0]->name; } return $clientNames; } */ }<file_sep>/resources/lang/nl/texts.php <?php return array( // client 'organization' => 'Organisatie', 'name' => 'Naam', 'website' => 'Website', 'work_phone' => 'Telefoon', 'address' => 'Adres', 'address1' => 'Straat', 'address2' => 'Bus/Suite', 'city' => 'Gemeente', 'state' => 'Staat/Provincie', 'postal_code' => 'Postcode', 'country_id' => 'Land', 'contacts' => 'Contacten', 'first_name' => 'Voornaam', 'last_name' => 'Achternaam', 'phone' => 'Telefoon', 'email' => 'E-mail', 'additional_info' => 'Extra Informatie', 'payment_terms' => 'Betalingsvoorwaarden', 'currency_id' => 'Munteenheid', 'size_id' => 'Grootte', 'industry_id' => 'Industrie', 'private_notes' => 'Priv&eacute; Bericht', // invoice 'invoice' => 'Factuur', 'client' => 'Klant', 'invoice_date' => 'Factuurdatum', 'due_date' => 'Vervaldatum', 'invoice_number' => 'Factuurnummer', 'invoice_number_short' => 'Factuur #', 'po_number' => 'Bestelnummer', 'po_number_short' => 'Bestel #', 'frequency_id' => 'Hoe vaak', 'discount' => 'Korting', 'taxes' => 'Belastingen', 'tax' => 'Belasting', 'item' => 'Naam', 'description' => 'Omschrijving', 'unit_cost' => 'Eenheidsprijs', 'quantity' => 'Aantal', 'line_total' => 'Totaal', 'subtotal' => 'Subtotaal', 'paid_to_date' => 'Betaald', 'balance_due' => 'Te voldoen', 'invoice_design_id' => 'Ontwerp', 'terms' => 'Voorwaarden', 'your_invoice' => 'Jouw factuur', 'remove_contact' => 'Verwijder contact', 'add_contact' => 'Voeg contact toe', 'create_new_client' => 'Maak nieuwe klant', 'edit_client_details' => 'Pas klantdetails aan', 'enable' => 'Activeer', 'learn_more' => 'Meer te weten komen', 'manage_rates' => 'Beheer prijzen', 'note_to_client' => 'Bericht aan klant', 'invoice_terms' => 'Factuur voorwaarden', 'save_as_default_terms' => 'Opslaan als standaard voorwaarden', 'download_pdf' => 'Download PDF', 'pay_now' => 'Betaal nu', 'save_invoice' => 'Sla Factuur op', 'clone_invoice' => 'Kopieer Factuur', 'archive_invoice' => 'Archiveer Factuur', 'delete_invoice' => 'Verwijder Factuur', 'email_invoice' => 'E-mail Factuur', 'enter_payment' => 'Betaling ingeven', 'tax_rates' => 'BTW tarief', 'rate' => 'Tarief', 'settings' => 'Instellingen', 'enable_invoice_tax' => 'Activeer instelling van <b>BTW op volledige factuur</b>', 'enable_line_item_tax' => 'Activeer instelling van <b>BTW per lijn</b>', // navigation 'dashboard' => 'Dashboard', 'clients' => 'Klanten', 'invoices' => 'Facturen', 'payments' => 'Betalingen', 'credits' => 'Kredietnota\'s', 'history' => 'Geschiedenis', 'search' => 'Zoeken', 'sign_up' => 'Aanmelden', 'guest' => 'Gast', 'company_details' => 'Bedrijfsdetails', 'online_payments' => 'Online betalingen', 'notifications' => 'Meldingen', 'import_export' => 'Importeer/Exporteer', 'done' => 'Klaar', 'save' => 'Opslaan', 'create' => 'Aanmaken', 'upload' => 'Uploaden', 'import' => 'Importeer', 'download' => 'Downloaden', 'cancel' => 'Annuleren', 'provide_email' => 'Geef een geldig e-mailadres aub.', 'powered_by' => 'Factuur gemaakt via', 'no_items' => 'Geen artikelen', // recurring invoices 'recurring_invoices' => 'Terugkerende facturen', 'recurring_help' => '<p>Zend klanten automatisch wekelijks, twee keer per maand, maandelijks, per kwartaal of jaarlijks dezelfde facturen.</p> <p>Gebruik :MONTH, :QUARTER of :YEAR voor dynamische datums. Eenvoudige wiskunde werkt ook, bijvoorbeeld :MONTH-1.</p> <p>Voorbeelden van dynamische factuur variabelen:</p> <ul> <li>"Fitness lidmaatschap voor de maand :MONTH" => "Fitness lidmaatschap voor de maand juli"</li> <li>"Jaarlijks abonnement :YEAR+1" => "Jaarlijks abonnement 2015"</li> <li>"Betaling voor :QUARTER+1" => "Betaling voor Q2"</li> </ul>', // dashboard 'in_total_revenue' => 'in totale opbrengst', 'billed_client' => 'Gefactureerde klant', 'billed_clients' => 'Gefactureerde klanten', 'active_client' => 'Actieve klant', 'active_clients' => 'Actieve klanten', 'invoices_past_due' => 'Vervallen facturen', 'upcoming_invoices' => 'Aankomende facturen', 'average_invoice' => 'Gemiddelde factuur', // list pages 'archive' => 'Archiveer', 'delete' => 'Verwijder', 'archive_client' => 'Archiveer klant', 'delete_client' => 'Verwijder klant', 'archive_payment' => 'Archiveer betaling', 'delete_payment' => 'Verwijder betaling', 'archive_credit' => 'Archiveer kredietnota', 'delete_credit' => 'Verwijder kredietnota', 'show_archived_deleted' => 'Toon gearchiveerde/verwijderde', 'filter' => 'Filter', 'new_client' => 'Nieuwe Klant', 'new_invoice' => 'Nieuwe Factuur', 'new_payment' => 'Nieuwe Betaling', 'new_credit' => 'Nieuwe Kredietnota', 'contact' => 'Contact', 'date_created' => 'Aanmaakdatum', 'last_login' => 'Laatste login', 'balance' => 'Saldo', 'action' => 'Actie', 'status' => 'Status', 'invoice_total' => 'Factuur totaal', 'frequency' => 'Frequentie', 'start_date' => 'Startdatum', 'end_date' => 'Einddatum', 'transaction_reference' => 'Transactie Referentie', 'method' => 'Methode', 'payment_amount' => 'Betalingsbedrag', 'payment_date' => 'Betalingsdatum', 'credit_amount' => 'Kredietbedrag', 'credit_balance' => 'Kredietsaldo', 'credit_date' => 'Kredietdatum', 'empty_table' => 'Geen gegevens beschikbaar in de tabel', 'select' => 'Selecteer', 'edit_client' => 'Klant aanpassen', 'edit_invoice' => 'Factuur aanpassen', // client view page 'create_invoice' => 'Factuur aanmaken', 'enter_credit' => 'Kredietnota ingeven', 'last_logged_in' => 'Laatste login', 'details' => 'Details', 'standing' => 'Openstaand', 'credit' => 'Krediet', 'activity' => 'Activiteit', 'date' => 'Datum', 'message' => 'Bericht', 'adjustment' => 'Aanpassing', 'are_you_sure' => 'Ben je zeker?', // payment pages 'payment_type_id' => 'Betalingstype', 'amount' => 'Bedrag', // account/company pages 'work_email' => 'E-mail', 'language_id' => 'Taal', 'timezone_id' => 'Tijdszone', 'date_format_id' => 'Formaat datum', 'datetime_format_id' => 'Datum/Tijd Formaat', 'users' => 'Gebruikers', 'localization' => 'Localisatie', 'remove_logo' => 'Verwijder logo', 'logo_help' => 'Ondersteund: JPEG, GIF en PNG. Aangeraden hoogte: 120px', 'payment_gateway' => 'Betalingsmiddel', 'gateway_id' => 'Leverancier', 'email_notifications' => 'E-mail meldingen', 'email_sent' => 'E-mail me wanneer een factuur is <b>verzonden</b>', 'email_viewed' => 'E-mail me wanneer een factuur is <b>bekeken</b>', 'email_paid' => 'E-mail me wanneer een factuur is <b>betaald</b>', 'site_updates' => 'Site Aanpassingen', 'custom_messages' => 'Aangepaste berichten', 'default_invoice_terms' => 'Stel standaard factuursvoorwaarden in', 'default_email_footer' => 'Stel standaard e-mail signatuur in', 'import_clients' => 'Importeer Klant Gegevens', 'csv_file' => 'Selecteer CSV bestand', 'export_clients' => 'Exporteer Klant Gegevens', 'select_file' => 'Selecteer alstublieft een bestand', 'first_row_headers' => 'Gebruik eerste rij als hoofdding', 'column' => 'Kolom', 'sample' => 'Voorbeeld', 'import_to' => 'Importeer naar', 'client_will_create' => 'klant zal aangemaakt worden', 'clients_will_create' => 'klanten zullen aangemaakt worden', 'email_settings' => 'Email Settings', 'pdf_email_attachment' => 'Attach PDF to Emails', // application messages 'created_client' => 'Klant succesvol aangemaakt', 'created_clients' => ':count klanten succesvol aangemaakt', 'updated_settings' => 'Instellingen succesvol aangepast', 'removed_logo' => 'Logo succesvol verwijderd', 'sent_message' => 'Bericht succesvol verzonden', 'invoice_error' => 'Selecteer een klant alstublieft en corrigeer mogelijke fouten', 'limit_clients' => 'Sorry, dit zal de klantenlimiet van :count klanten overschrijden', 'payment_error' => 'Er was een fout bij het verwerken van uw betaling. Probeer later alstublieft opnieuw.', 'registration_required' => 'Meld je aan om een factuur te mailen', 'confirmation_required' => 'Bevestig je e-mail adres alstublieft', 'updated_client' => 'Klant succesvol aangepast', 'created_client' => 'Klant succesvol aangemaakt', 'archived_client' => 'Klant succesvol gearchiveerd', 'archived_clients' => ':count klanten succesvol gearchiveerd', 'deleted_client' => 'Klant succesvol verwijderd', 'deleted_clients' => ':count klanten succesvol verwijderd', 'updated_invoice' => 'Factuur succesvol aangepast', 'created_invoice' => 'Factuur succesvol aangemaakt', 'cloned_invoice' => 'Factuur succesvol gekopieerd', 'emailed_invoice' => 'Factuur succesvol gemaild', 'and_created_client' => 'en klant aangemaakt', 'archived_invoice' => 'Factuur succesvol gearchiveerd', 'archived_invoices' => ':count facturen succesvol gearchiveerd', 'deleted_invoice' => 'Factuur succesvol verwijderd', 'deleted_invoices' => ':count facturen succesvol verwijderd', 'created_payment' => 'Betaling succesvol aangemaakt', 'archived_payment' => 'Betaling succesvol gearchiveerd', 'archived_payments' => ':count betalingen succesvol gearchiveerd', 'deleted_payment' => 'Betaling succesvol verwijderd', 'deleted_payments' => ':count betalingen succesvol verwijderd', 'applied_payment' => 'Betaling succesvol toegepast', 'created_credit' => 'Kredietnota succesvol aangemaakt', 'archived_credit' => 'Kredietnota succesvol gearchiveerd', 'archived_credits' => ':count kredietnota\'s succesvol gearchiveerd', 'deleted_credit' => 'Kredietnota succesvol verwijderd', 'deleted_credits' => ':count kredietnota\'s succesvol verwijderd', // E-mails 'confirmation_subject' => 'Invoice Ninja Bevestiging Account', 'confirmation_header' => 'Bevestiging Account', 'confirmation_message' => 'Ga alstublieft naar onderstaande link om je account te bevestiging.', 'invoice_message' => 'Om je factuur voor :amount te bekijken, klik op onderstaande link.', 'payment_subject' => 'Betaling ontvangen', 'payment_message' => 'Bedankt voor je betaling van :amount.', 'email_salutation' => 'Beste :name,', 'email_signature' => 'Met vriendelijke groeten,', 'email_from' => 'Het InvoiceNinja Team', 'user_email_footer' => 'Ga alstublieft naar '.SITE_URL.'/company/notifications om je e-mail notificatie instellingen aan te passen ', 'invoice_link_message' => 'Klik op volgende link om de Factuur van je klant te bekijken:', 'notification_invoice_paid_subject' => 'Factuur :invoice is betaald door :client', 'notification_invoice_sent_subject' => 'Factuur :invoice is gezonden door :client', 'notification_invoice_viewed_subject' => 'Factuur :invoice is bekeken door :client', 'notification_invoice_paid' => 'Een betaling voor :amount is gemaakt door klant :client voor Factuur :invoice.', 'notification_invoice_sent' => 'De volgende klant :client heeft Factuur :invoice voor :amount gemaild gekregen.', 'notification_invoice_viewed' => 'De volgende klant :client heeft Factuur :invoice voor :amount bekeken.', 'reset_password' => 'Je kan het paswoord van je account resetten door op volgende link te klikken:', 'reset_password_footer' => 'Als je deze paswoord reset niet aangevraagd hebt contacteer dan onze helpdesk alstublieft: ' . CONTACT_EMAIL, // Payment page 'secure_payment' => 'Veilige betaling', 'card_number' => 'Kaart nummer', 'expiration_month' => 'Verval maand', 'expiration_year' => 'Verval jaar', 'cvv' => 'CVV', // Security alerts 'security' => [ 'too_many_attempts' => 'Te veel pogingen. Probeer opnieuw binnen enkele minuten.', 'wrong_credentials' => 'Verkeerd e-mailadres of paswoord.', 'confirmation' => 'Je account is bevestigd!', 'wrong_confirmation' => 'Verkeerde bevestigingscode.', 'password_forgot' => 'De informatie over je paswoord reset is verzonden naar je e-mailadres.', 'password_reset' => 'Je paswoord is succesvol aangepast.', 'wrong_password_reset' => '<PASSWORD>', ], // Pro Plan 'pro_plan' => [ 'remove_logo' => ':link om het Invoice Ninja logo te verwijderen door het pro plan te nemen', 'remove_logo_link' => 'Klik hier', ], 'logout' => 'Afmelden', 'sign_up_to_save' => 'Registreer je om je werk op te slaan', 'agree_to_terms' =>'Ik accepteer de Invoice Ninja :terms', 'terms_of_service' => 'Gebruiksvoorwaarden', 'email_taken' => 'Het e-mailadres is al geregistreerd', 'working' => 'Actief', 'success' => 'Succes', 'success_message' => 'Je bent succesvol geregistreerd. Ga alstublieft naar de link in de bevestigingsmail om je e-mailadres te verifi&euml;ren.', 'erase_data' => 'Dit zal uw data permanent verwijderen.', 'password' => '<PASSWORD>', 'invoice_subject' => 'Nieuwe factuur :invoice van :account', 'close' => 'Sluiten', 'pro_plan_product' => 'Pro Plan', 'pro_plan_description' => 'Één jaar abbonnement op het Invoice Ninja Pro Plan.', 'pro_plan_success' => 'Bedankt voor het aanmelden! Zodra je factuur betaald is zal je Pro Plan lidmaatschap beginnen.', 'unsaved_changes' => 'Je hebt niet bewaarde wijzigingen', 'custom_fields' => 'Aangepaste velden', 'company_fields' => 'Velden Bedrijf', 'client_fields' => 'Velden Klant', 'field_label' => 'Label Veld', 'field_value' => 'Waarde Veld', 'edit' => 'Bewerk', 'view_invoice' => 'Bekijk factuur', 'view_as_recipient' => 'Bekijk als ontvanger', // product management 'product_library' => 'Product Bibliotheek', 'product' => 'Product', 'products' => 'Producten', 'fill_products' => 'Producten Automatisch aanvullen', 'fill_products_help' => 'Een product selecteren zal automatisch <b>de beschrijving en kost instellen</b>', 'update_products' => 'Producten automatisch aanpassen', 'update_products_help' => 'Aanpassen van een factuur zal automatisch <b>de producten aanpassen</b>', 'create_product' => 'Product maken', 'edit_product' => 'Product aanpassen', 'archive_product' => 'Product Archiveren', 'updated_product' => 'Product Succesvol aangepast', 'created_product' => 'Product Succesvol aangemaakt', 'archived_product' => 'Product Succesvol gearchiveerd', 'pro_plan_custom_fields' => ':link om aangepaste velden in te schakelen door het Pro Plan te nemen', 'advanced_settings' => 'Geavanceerde instellingen', 'pro_plan_advanced_settings' => ':link om de geavanceerde instellingen te activeren door het Pro Plan te nemen', 'invoice_design' => 'Factuur ontwerp', 'specify_colors' => 'Kies kleuren', 'specify_colors_label' => 'Kies de kleuren die in de factuur gebruikt worden', 'chart_builder' => 'Grafiek bouwer', 'ninja_email_footer' => 'Gebruik :site om uw klanten gratis te factureren en betalingen te ontvangen!', 'go_pro' => 'Go Pro', // Quotes 'quote' => 'Offerte', 'quotes' => 'Offertes', 'quote_number' => 'Offerte Number', 'quote_number_short' => 'Offerte #', 'quote_date' => 'Offerte Datum', 'quote_total' => 'Offerte Totaal', 'your_quote' => 'Uw Offerte', 'total' => 'Totaal', 'clone' => 'Kloon', 'new_quote' => 'Nieuwe Offerte', 'create_quote' => 'Maak offerte aan', 'edit_quote' => 'Bewerk Offecte', 'archive_quote' => 'Archiveer Offerte', 'delete_quote' => 'Verwijder Offerte', 'save_quote' => 'Bewaar Offerte', 'email_quote' => 'Email Offerte', 'clone_quote' => 'Kloon Offerte', 'convert_to_invoice' => 'Zet om naar Factuur', 'view_invoice' => 'Bekijk Factuur', 'view_quote' => 'Bekijk Offerte', 'view_client' => 'Bekijk Klant', 'updated_quote' => 'Offerte succesvol bijgewerkt', 'created_quote' => 'Offerte succesvol aangemaakt', 'cloned_quote' => 'Offerte succesvol gekopieerd', 'emailed_quote' => 'Offerte succesvol gemaild', 'archived_quote' => 'Offerte succesvol gearchiveerd', 'archived_quotes' => ':count offertes succesvol gearchiveerd', 'deleted_quote' => 'Offerte succesvol verwijderd', 'deleted_quotes' => ':count offertes succesvol verwijderd', 'converted_to_invoice' => 'Offerte succesvol omgezet naar factuur', 'quote_subject' => 'Nieuwe offerte van :account', 'quote_message' => 'Om uw offerte voor :amount te bekijken, klik op de link hieronder.', 'quote_link_message' => 'Klik op de link hieronder om de offerte te bekijken:', 'notification_quote_sent_subject' => 'Offerte :invoice is verstuurd naar :client', 'notification_quote_viewed_subject' => 'Offerte :invoice is bekeken door :client', 'notification_quote_sent' => 'Klant :client heeft offerte :invoice voor :amount per email ontvangen.', 'notification_quote_viewed' => 'Klant :client heeft offerte :invoice voor :amount bekeken.', 'session_expired' => 'Uw sessie is verlopen.', 'invoice_fields' => 'Factuur Velden', 'invoice_options' => 'Factuur Opties', 'hide_quantity' => 'Verberg aantallen', 'hide_quantity_help' => 'Als de artikel-aantallen altijd 1 zijn, kunt u uw facturen netter maken door dit veld te verbergen.', 'hide_paid_to_date' => 'Verberg "Reeds betaald"', 'hide_paid_to_date_help' => 'Toon alleen het "Reeds betaald" gebied op je facturen als er een betaling gemaakt is.', 'charge_taxes' => 'Charge taxes', 'user_management' => 'Gebruikersbeheer', 'add_user' => 'Nieuwe gebruiker', 'send_invite' => 'Verstuur uitnodiging', 'sent_invite' => 'Uitnodiging succesvol verzonden', 'updated_user' => 'Gebruiker succesvol aangepast', 'invitation_message' => 'U bent uigenodigd door :invitor. ', 'register_to_add_user' => 'Meld u aan om een gebruiker toe te voegen', 'user_state' => 'Status', 'edit_user' => 'Bewerk Gebruiker', 'delete_user' => 'Verwijder Gebruiker', 'active' => 'Actief', 'pending' => 'Pending', 'deleted_user' => 'Gebruiker succesvol verwijderd', 'limit_users' => 'Sorry, dit zou de limiet van ' . MAX_NUM_USERS . ' gebruikers overschrijden', 'confirm_email_invoice' => 'Weet u zeker dat u deze factuur wilt mailen?', 'confirm_email_quote' => 'Weet u zeker dat u deze offerte wilt mailen?', 'confirm_recurring_email_invoice' => 'Terugkeren (herhalen) staat aan, weet u zeker dat u deze factuur wilt mailen?', 'cancel_account' => 'Zeg Account Op', 'cancel_account_message' => 'Waarschuwing: Dit zal al uw data verwijderen. Er is geen manier om dit ongedaan te maken', 'go_back' => 'Ga Terug', 'data_visualizations' => 'Data Visualisaties', 'sample_data' => 'Voorbeelddata getoond', 'hide' => 'Verberg', 'new_version_available' => 'Een nieuwe versie van :releases_link is beschikbaar. U gebruikt nu v:user_version, de laatste versie is v:latest_version', 'invoice_settings' => 'Factuur Instellingen', 'invoice_number_prefix' => 'Factuurnummer Prefix', 'invoice_number_counter' => 'Factuurnummer Teller', 'quote_number_prefix' => 'Offertenummer Prefix', 'quote_number_counter' => 'Offertenummer Teller', 'share_invoice_counter' => 'Deel factuur teller', 'invoice_issued_to' => 'Factuur uitgegeven aan', 'invalid_counter' => 'Stel een factuurnummer prefix of offertenummer prefix in om een mogelijk conflict te voorkomen.', 'mark_sent' => 'Markeer als verzonden', 'gateway_help_1' => ':link om in te schrijven voor Authorize.net.', 'gateway_help_2' => ':link om in te schrijven voor Authorize.net.', 'gateway_help_17' => ':link om je PayPal API signature te krijgen.', 'gateway_help_23' => 'Opmerking: gebruik je gehieme API key, niet je publiceerbare API key.', 'gateway_help_27' => ':link om in te schrijven voor TwoCheckout.', 'more_designs' => 'Meer ontwerpen', 'more_designs_title' => 'Aanvullende Factuur Ontwerpen', 'more_designs_cloud_header' => 'Neem Pro Plan voor meer factuur ontwerpen', 'more_designs_cloud_text' => '', 'more_designs_self_host_header' => 'Krijg 6 extra factuurontwerpen voor maar $'.INVOICE_DESIGNS_PRICE, 'more_designs_self_host_text' => '', 'buy' => 'Koop', 'bought_designs' => 'Aanvullende factuurontwerpen succesvol toegevoegd', 'sent' => 'verzonden', 'timesheets' => 'Timesheets', 'payment_title' => 'Geef je betalingsadres en kredietkaart gegevens op', 'payment_cvv' => '*Dit is de code van 3-4 tekens op de achterkant van je kaart', 'payment_footer1' => '*Betalingsadres moet overeenkomen met het adres dat aan je kaart gekoppekd is.', 'payment_footer2' => '*Klik alstublieft slechts 1 keer op "PAY NOW" - verwerking kan tot 1 minuut duren.', 'vat_number' => 'BTW Nummer', 'id_number' => 'ID Nummer', 'white_label_link' => 'White label', 'white_label_text' => 'Koop een white label licentie voor $'.WHITE_LABEL_PRICE.' om de Invoice Ninja merknaam te verwijderen uit de bovenkant van de klantenpagina\'s.', 'white_label_header' => 'White Label', 'bought_white_label' => 'White label licentie succesvol geactiveerd', 'white_labeled' => 'White labeled', 'restore' => 'Herstel', 'restore_invoice' => 'Herstel Factuur', 'restore_quote' => 'Herstel Offerte', 'restore_client' => 'Herstel Klant', 'restore_credit' => 'Herstel Kredietnota', 'restore_payment' => 'Herstel Betaling', 'restored_invoice' => 'Factuur succesvol hersteld', 'restored_quote' => 'Offerte succesvol hersteld', 'restored_client' => 'Klant succesvol hersteld', 'restored_payment' => 'Betaling succesvol hersteld', 'restored_credit' => 'Kredietnota succesvol hersteld', 'reason_for_canceling' => 'Help ons om onze site te verbeteren door ons te vertellen waarom u weggaat.', 'discount_percent' => 'Percentage', 'discount_amount' => 'Bedrag', 'invoice_history' => 'Factuur geschiedenis', 'quote_history' => 'Offerte Geschiedenis', 'current_version' => 'Huidige Versie', 'select_versiony' => 'Selecteer versie', 'view_history' => 'Bekijk Geschiedenis', 'edit_payment' => 'Bewerk Betaling', 'updated_payment' => 'Betaling succesvol bijgewerkt', 'deleted' => 'Verwijderd', 'restore_user' => 'Herstel gebruiker', 'restored_user' => 'Gebruiker succesvol hersteld', 'show_deleted_users' => 'Toon verwijderde gebruikers', 'email_templates' => 'Email Templates', 'invoice_email' => 'Factuur Email', 'payment_email' => 'Betaling Email', 'quote_email' => 'Offerte Email', 'reset_all' => 'Reset Alles', 'approve' => 'Goedkeuren', 'token_billing_type_id' => 'Betalingstoken', 'token_billing_help' => 'Laat je toe om kredietkaart gegevens bij je gateway op te slaan en ze later te gebruiken.', 'token_billing_1' => 'Inactief', 'token_billing_2' => 'Opt-in - checkbox is getoond maar niet geselecteerd', 'token_billing_3' => 'Opt-out - checkbox is getoond en geselecteerd', 'token_billing_4' => 'Altijd', 'token_billing_checkbox' => 'Sla kredietkaart gegevens op', 'view_in_stripe' => 'In Stripe bekijken', 'use_card_on_file' => 'Use card on file', 'edit_payment_details' => 'Betalingsdetails aanpassen', 'token_billing' => 'Kaartgegevens opslaan', 'token_billing_secure' => 'De gegevens zijn succesvol veilig opgeslaan door :stripe_link', 'support' => 'Ondersteuning', 'contact_information' => 'Contact informatie', '256_encryption' => '256-Bit Encryptie', 'amount_due' => 'Te betalen bedrag', 'billing_address' => 'Facturatie adres', 'billing_method' => 'Betaalmethode', 'order_overview' => 'Order overzicht', 'match_address' => '*Addres moet overeenkomen met adres van creditcard.', 'click_once' => '*Please click "PAY NOW" only once - transaction may take up to 1 minute to process.', 'default_invoice_footer' => 'Stel standaard factuur-footer in', 'invoice_footer' => 'Factuur footer', 'save_as_default_footer' => 'Bewaar als standaard footer', 'token_management' => 'Token Beheer', 'tokens' => 'Tokens', 'add_token' => 'Voeg Token Toe', 'show_deleted_tokens' => 'Toon verwijderde tokens', 'deleted_token' => 'Token succesvol verwijderd', 'created_token' => 'Token succesvol aangemaakt', 'updated_token' => 'Token succesvol aangepast', 'edit_token' => 'Bewerk Token', 'delete_token' => 'Verwijder Token', 'token' => 'Token', 'add_gateway' => 'Gateway Toevoegen', 'delete_gateway' => 'Gateway Verwijderen', 'edit_gateway' => 'Gateway Aanpassen', 'updated_gateway' => 'Gateway Succesvol aangepast', 'created_gateway' => 'Gateway Succesvol aangemaakt', 'deleted_gateway' => 'Gateway Succesvol verwijderd', 'pay_with_paypal' => 'PayPal', 'pay_with_card' => 'Kredietkaart', 'change_password' => '<PASSWORD>', 'current_password' => '<PASSWORD>', 'new_password' => '<PASSWORD>', 'confirm_password' => '<PASSWORD>', 'password_error_incorrect' => 'Het huidige wachtwoord is niet.', 'password_error_invalid' => 'Het nieuwe wachtwoord is ongeldig.', 'updated_password' => '<PASSWORD>', 'api_tokens' => 'API Tokens', 'users_and_tokens' => 'Gebruikers & Tokens', 'account_login' => 'Account Login', 'recover_password' => '<PASSWORD>', 'forgot_password' => '<PASSWORD>?', 'email_address' => 'Emailadres', 'lets_go' => 'Let’s go', 'password_recovery' => '<PASSWORD>', 'send_email' => 'Verstuur email', 'set_password' => '<PASSWORD>', 'converted' => 'Omgezet', 'email_approved' => 'Email me wanneer een offerte is <b>goedgekeurd</b>', 'notification_quote_approved_subject' => 'Offerte :invoice is goedgekeurd door :client', 'notification_quote_approved' => 'De volgende Klant :client heeft Offerte :invoice goedgekeurd voor :amount.', 'resend_confirmation' => 'Verstuurd bevestingsmail opnieuw', 'confirmation_resent' => 'De bevestigingsmail is opnieuw verstuurd', 'gateway_help_42' => ':link om te registreren voor BitPay.<br/>Opmerking: gebruik een Legacy API Key, niet een API token.', 'payment_type_credit_card' => 'Kredietkaart', 'payment_type_paypal' => 'PayPal', 'payment_type_bitcoin' => 'Bitcoin', 'knowledge_base' => 'Kennis databank', 'partial' => 'Gedeeld', 'partial_remaining' => ':partial / :balance', 'more_fields' => 'Meer velden', 'less_fields' => 'Minder velden', 'client_name' => 'Klant Naam', 'pdf_settings' => 'PDF Instellingen', 'product_settings' => 'Product Instellingen', 'auto_wrap' => 'Automatisch Lijn afbreken', 'duplicate_post' => 'Opgelet: de volgende pagina is twee keer doorgestuurd. De tweede verzending is genegeerd.', 'view_documentation' => 'Bekijk Documentatie', 'app_title' => 'Gratis Open-Source Online Facturatie', 'app_description' => 'Invoice Ninja is een gratis, open-source oplossing voor het aanmkaen en versturen van facturen aan klanten. Met Invoice Ninja, kan je gemakkelijk mooie facturen aanmaken en verzenden van om het even welk toestel met internettoegang. Je klanten kunnen je facturen afprinten, downloaden als pdf bestanden, en je zelfs online betalen vanuit het systeem.', 'rows' => 'rijen', 'www' => 'www', 'logo' => 'Logo', 'subdomain' => 'Subdomein', 'provide_name_or_email' => 'Geef aub een contact naam en email op', 'charts_and_reports' => 'Grafieken & Rapporten', 'chart' => 'Grafiek', 'report' => 'Rapport', 'group_by' => 'Groepeer per', 'paid' => 'Betaald', 'enable_report' => 'Rapport', 'enable_chart' => 'Grafiek', 'totals' => 'Totalen', 'run' => 'Uitvoeren', 'export' => 'Exporteer', 'documentation' => 'Documentatie', 'zapier' => 'Zapier <sup>Beta</sup>', 'recurring' => 'Terugkerend', 'last_invoice_sent' => 'Laatste factuur verzonden :date', 'processed_updates' => 'Update succesvol uitgevoerd', 'tasks' => 'Taken', 'new_task' => 'Nieuwe Taak', 'start_time' => 'Start Tijd', 'created_task' => 'Taak succesvol aangemaakt', 'updated_task' => 'Taak succesvol aangepast', 'edit_task' => 'Pas Taak aan', 'archive_task' => 'Archiveer Taak', 'restore_task' => 'Taak herstellen', 'delete_task' => 'Verwijder Taak', 'stop_task' => 'Stop Taak', 'time' => 'Tijd', 'start' => 'Start', 'stop' => 'Stop', 'now' => 'Nu', 'timer' => 'Timer', 'manual' => 'Manueel', 'date_and_time' => 'Datum & Tijd', 'second' => 'second', 'seconds' => 'seconden', 'minute' => 'minuut', 'minutes' => 'minuten', 'hour' => 'uur', 'hours' => 'uren', 'task_details' => 'Taak Details', 'duration' => 'Duur', 'end_time' => 'Eind Tijd', 'end' => 'Einde', 'invoiced' => 'Gefactureerd', 'logged' => 'Gelogd', 'running' => 'Lopend', 'task_error_multiple_clients' => 'Taken kunnen niet tot meerdere klanten behoren', 'task_error_running' => 'Stop aub de lopende taken eerst', 'task_error_invoiced' => 'Deze taken zijn al gefactureerd', 'restored_task' => 'Taak succesvol hersteld', 'archived_task' => 'Taak succesvol gearchiveerd', 'archived_tasks' => ':count taken succesvol gearchiveerd', 'deleted_task' => 'Taak succesvol verwijderd', 'deleted_tasks' => ':count taken succesvol verwijderd', 'create_task' => 'Taak aanmaken', 'stopped_task' => 'Taak succesvol gestopt', 'invoice_task' => 'Factuur taak', 'invoice_labels' => 'Factuur labels', 'prefix' => 'Voorvoegsel', 'counter' => 'Teller', 'payment_type_dwolla' => 'Dwolla', 'gateway_help_43' => ':link om in te schrijven voor Dwolla.', 'partial_value' => 'Moet groter zijn dan nul en minder dan het totaal', 'more_actions' => 'Meer acties', 'pro_plan_title' => 'NINJA PRO', 'pro_plan_call_to_action' => 'Nu upgraden!', 'pro_plan_feature1' => 'Maak ongelimiteerd klanten aan', 'pro_plan_feature2' => 'Toegang tot 10 mooie factuur ontwerpen', 'pro_plan_feature3' => 'Aangepaste URLs - "YourBrand.InvoiceNinja.com"', 'pro_plan_feature4' => 'Verwijder "Aangemaakt door Invoice Ninja"', 'pro_plan_feature5' => 'Multi-user toegang & Activeit Tracking', 'pro_plan_feature6' => 'Maak offertes & Pro-forma facturen aan', 'pro_plan_feature7' => 'Pas factuur veld titels & nummering aan', 'pro_plan_feature8' => 'Optie om PDFs toe te voegen aan de emails naar klanten', 'resume' => 'Doorgaan', 'break_duration' => 'Pauze', 'edit_details' => 'Details aanpassen', 'work' => 'Werk', 'timezone_unset' => ':link om je tijdszone aan te passen', 'click_here' => 'Klik hier', 'email_receipt' => 'Mail betalingsbewijs naar de klant', 'created_payment_emailed_client' => 'Betaling succesvol toegevoegd en gemaild naar de klant', 'add_company' => 'Bedrijf toevoegen', 'untitled' => 'Zonder titel', 'new_company' => 'Nieuw bedrijf', 'associated_accounts' => 'Accounts succesvol gekoppeld', 'unlinked_account' => 'Accounts succesvol losgekoppeld', 'login' => 'Login', 'or' => 'of', 'email_error' => 'Er was een probleem om de email te verzenden', 'confirm_recurring_timing' => 'Opmerking: emails worden aan het begin van het uur verzonden.', 'old_browser' => 'Gebruik aub een <a href="'.OUTDATE_BROWSER_URL.'" target="_blank">nieuwere browser</a>', 'payment_terms_help' => 'Stel de standaard factuur vervaldatum in', 'unlink_account' => 'Koppel account los', 'unlink' => 'Koppel los', 'show_address' => 'Toon Adres', 'show_address_help' => 'Verplicht de klant om zijn factuur adres op te geven', 'update_address' => 'Adres aanpassen', 'update_address_help' => 'Pas het adres van de klant aan met de ingevulde gegevens', 'times' => 'Tijden', 'set_now' => 'Start nu', 'dark_mode' => 'Donkere modus', 'dark_mode_help' => 'Toon witte tekst op een donkere achtergrond', 'add_to_invoice' => 'Toevoegen aan factuur :invoice', 'create_new_invoice' => 'Maak een nieuwe factuur', 'task_errors' => 'Pas overlappende tijden aan aub.', 'from' => 'Van', 'to' => 'Aan', 'font_size' => 'Tekstgrootte', 'primary_color' => 'Primaire kleur', 'secondary_color' => 'Secundaire kleur', 'customize_design' => 'Pas design aan', 'content' => 'Inhoud', 'styles' => 'Stijlen', 'defaults' => 'Standaardwaarden', 'margins' => 'Marges', 'header' => 'Header', 'footer' => 'Footer', 'custom' => 'Aangepast', 'invoice_to' => 'Factuur aan', 'invoice_no' => 'Factuur Nr.', 'recent_payments' => 'Recente betalingen', 'outstanding' => 'Uitstaand', 'manage_companies' => 'Beheer bedrijven', 'total_revenue' => 'Totale opbrengst', 'current_user' => 'Huidige gebruiker', 'new_recurring_invoice' => 'Nieuwe wederkerende factuur', 'recurring_invoice' => 'Wederkerende factuur', 'recurring_too_soon' => 'Het is te vroeg om de volgende wederkerende factuur aan te maken', 'created_by_invoice' => 'Aangemaakt door :invoice', 'primary_user' => 'Primaire gebruiker', 'help' => 'Help', 'customize_help' => '<p>We gebruiken <a href="http://pdfmake.org/" target="_blank">pdfmake</a> om de factuur ontwerpen declaratief te definieren. De pdfmake <a href="http://pdfmake.org/playground.html" target="_blank">playground</a> is een interessante manier om de library in actie te zien.</p> <p>Je kan elk factuur veld gebruiken door <code>Veld</code> toe te voegen op het einde. Bijvoorbeeld <code>$invoiceNumberValue</code> toont de factuur nummer.</p> <p>Gebruik dot notatie om een "kind eigenschap" te gebruiken. Bijvoorbeeld voor de klant naam te tonen gebruik je <code>$client.nameValue</code>.</p> <p>Als je ergens hulp bij nodig hebt, post dan een vraag op ons <a href="https://www.invoiceninja.com/forums/forum/support/" target="_blank">support forum</a>.</p>' ); <file_sep>/app/Http/Controllers/AccountController.php <?php namespace App\Http\Controllers; use Auth; use Event; use File; use Image; use Input; use Redirect; use Session; use Utils; use Validator; use View; use stdClass; use Cache; use Response; use parseCSV; use Request; use App\Models\Affiliate; use App\Models\License; use App\Models\User; use App\Models\Client; use App\Models\Contact; use App\Models\Invoice; use App\Models\InvoiceItem; use App\Models\Activity; use App\Models\Payment; use App\Models\Credit; use App\Models\Account; use App\Models\Country; use App\Models\Currency; use App\Models\DateFormat; use App\Models\DatetimeFormat; use App\Models\Language; use App\Models\Size; use App\Models\Timezone; use App\Models\Industry; use App\Models\InvoiceDesign; use App\Ninja\Repositories\AccountRepository; use App\Ninja\Mailers\UserMailer; use App\Ninja\Mailers\ContactMailer; use App\Events\UserLoggedIn; class AccountController extends BaseController { protected $accountRepo; protected $userMailer; protected $contactMailer; public function __construct(AccountRepository $accountRepo, UserMailer $userMailer, ContactMailer $contactMailer) { parent::__construct(); $this->accountRepo = $accountRepo; $this->userMailer = $userMailer; $this->contactMailer = $contactMailer; } public function demo() { $demoAccountId = Utils::getDemoAccountId(); if (!$demoAccountId) { return Redirect::to('/'); } $account = Account::find($demoAccountId); $user = $account->users()->first(); Auth::login($user, true); return Redirect::to('invoices/create'); } public function getStarted() { $user = false; $guestKey = Input::get('guest_key'); // local storage key to login until registered $prevUserId = Session::pull(PREV_USER_ID); // last user id used to link to new account if (Auth::check()) { return Redirect::to('invoices/create'); } if (!Utils::isNinja() && (Account::count() > 0 && !$prevUserId)) { return Redirect::to('/login'); } if ($guestKey && !$prevUserId) { $user = User::where('password', '=', $guestKey)->first(); if ($user && $user->registered) { return Redirect::to('/'); } } if (!$user) { $account = $this->accountRepo->create(); $user = $account->users()->first(); Session::forget(RECENTLY_VIEWED); if ($prevUserId) { $users = $this->accountRepo->associateAccounts($user->id, $prevUserId); Session::put(SESSION_USER_ACCOUNTS, $users); } } Auth::login($user, true); Event::fire(new UserLoggedIn()); $redirectTo = Input::get('redirect_to', 'invoices/create'); return Redirect::to($redirectTo)->with('sign_up', Input::get('sign_up')); } public function enableProPlan() { $invitation = $this->accountRepo->enableProPlan(); /* if ($invoice) { $this->contactMailer->sendInvoice($invoice); } */ return $invitation->invitation_key; } public function setTrashVisible($entityType, $visible) { Session::put("show_trash:{$entityType}", $visible == 'true'); if ($entityType == 'user') { return Redirect::to('company/'.ACCOUNT_ADVANCED_SETTINGS.'/'.ACCOUNT_USER_MANAGEMENT); } elseif ($entityType == 'token') { return Redirect::to('company/'.ACCOUNT_ADVANCED_SETTINGS.'/'.ACCOUNT_TOKEN_MANAGEMENT); } else { return Redirect::to("{$entityType}s"); } } public function getSearchData() { $data = $this->accountRepo->getSearchData(); return Response::json($data); } public function showSection($section = ACCOUNT_DETAILS, $subSection = false) { if ($section == ACCOUNT_DETAILS) { $primaryUser = Auth::user()->account->users()->orderBy('id')->first(); $data = [ 'account' => Account::with('users')->findOrFail(Auth::user()->account_id), 'countries' => Cache::get('countries'), 'sizes' => Cache::get('sizes'), 'industries' => Cache::get('industries'), 'timezones' => Cache::get('timezones'), 'dateFormats' => Cache::get('dateFormats'), 'datetimeFormats' => Cache::get('datetimeFormats'), 'currencies' => Cache::get('currencies'), 'languages' => Cache::get('languages'), 'showUser' => Auth::user()->id === $primaryUser->id, 'title' => trans('texts.company_details'), 'primaryUser' => $primaryUser, ]; return View::make('accounts.details', $data); } elseif ($section == ACCOUNT_PAYMENTS) { $account = Auth::user()->account; $account->load('account_gateways'); $count = count($account->account_gateways); if ($count == 0) { return Redirect::to('gateways/create'); } else { return View::make('accounts.payments', [ 'showAdd' => $count < 3, 'title' => trans('texts.online_payments') ]); } } elseif ($section == ACCOUNT_NOTIFICATIONS) { $data = [ 'account' => Account::with('users')->findOrFail(Auth::user()->account_id), 'title' => trans('texts.notifications'), ]; return View::make('accounts.notifications', $data); } elseif ($section == ACCOUNT_IMPORT_EXPORT) { return View::make('accounts.import_export', ['title' => trans('texts.import_export')]); } elseif ($section == ACCOUNT_ADVANCED_SETTINGS) { $account = Auth::user()->account->load('country'); $data = [ 'account' => $account, 'feature' => $subSection, 'title' => trans('texts.invoice_settings'), ]; if ($subSection == ACCOUNT_INVOICE_DESIGN || $subSection == ACCOUNT_CUSTOMIZE_DESIGN) { $invoice = new stdClass(); $client = new stdClass(); $contact = new stdClass(); $invoiceItem = new stdClass(); $client->name = '<NAME>'; $client->address1 = ''; $client->city = ''; $client->state = ''; $client->postal_code = ''; $client->work_phone = ''; $client->work_email = ''; $invoice->invoice_number = $account->getNextInvoiceNumber(); $invoice->invoice_date = Utils::fromSqlDate(date('Y-m-d')); $invoice->account = json_decode($account->toJson()); $invoice->amount = $invoice->balance = 100; $invoice->terms = trim($account->invoice_terms); $invoice->invoice_footer = trim($account->invoice_footer); $contact->email = '<EMAIL>'; $client->contacts = [$contact]; $invoiceItem->cost = 100; $invoiceItem->qty = 1; $invoiceItem->notes = 'Notes'; $invoiceItem->product_key = 'Item'; $invoice->client = $client; $invoice->invoice_items = [$invoiceItem]; $data['account'] = $account; $data['invoice'] = $invoice; $data['invoiceLabels'] = json_decode($account->invoice_labels) ?: []; $data['title'] = trans('texts.invoice_design'); $data['invoiceDesigns'] = InvoiceDesign::getDesigns(); $design = false; foreach ($data['invoiceDesigns'] as $item) { if ($item->id == $account->invoice_design_id) { $design = $item->javascript; break; } } if ($subSection == ACCOUNT_CUSTOMIZE_DESIGN) { $data['customDesign'] = ($account->custom_design && !$design) ? $account->custom_design : $design; } } else if ($subSection == ACCOUNT_EMAIL_TEMPLATES) { $data['invoiceEmail'] = $account->getEmailTemplate(ENTITY_INVOICE); $data['quoteEmail'] = $account->getEmailTemplate(ENTITY_QUOTE); $data['paymentEmail'] = $account->getEmailTemplate(ENTITY_PAYMENT); $data['emailFooter'] = $account->getEmailFooter(); $data['title'] = trans('texts.email_templates'); } else if ($subSection == ACCOUNT_USER_MANAGEMENT) { $data['title'] = trans('texts.users_and_tokens'); } return View::make("accounts.{$subSection}", $data); } elseif ($section == ACCOUNT_PRODUCTS) { $data = [ 'account' => Auth::user()->account, 'title' => trans('texts.product_library'), ]; return View::make('accounts.products', $data); } } public function doSection($section = ACCOUNT_DETAILS, $subSection = false) { if ($section == ACCOUNT_DETAILS) { return AccountController::saveDetails(); } elseif ($section == ACCOUNT_IMPORT_EXPORT) { return AccountController::importFile(); } elseif ($section == ACCOUNT_MAP) { return AccountController::mapFile(); } elseif ($section == ACCOUNT_NOTIFICATIONS) { return AccountController::saveNotifications(); } elseif ($section == ACCOUNT_EXPORT) { return AccountController::export(); } elseif ($section == ACCOUNT_ADVANCED_SETTINGS) { if ($subSection == ACCOUNT_INVOICE_SETTINGS) { return AccountController::saveInvoiceSettings(); } elseif ($subSection == ACCOUNT_INVOICE_DESIGN) { return AccountController::saveInvoiceDesign(); } elseif ($subSection == ACCOUNT_CUSTOMIZE_DESIGN) { return AccountController::saveCustomizeDesign(); } elseif ($subSection == ACCOUNT_EMAIL_TEMPLATES) { return AccountController::saveEmailTemplates(); } } elseif ($section == ACCOUNT_PRODUCTS) { return AccountController::saveProducts(); } } private function saveCustomizeDesign() { if (Auth::user()->account->isPro()) { $account = Auth::user()->account; $account->custom_design = Input::get('custom_design'); $account->invoice_design_id = CUSTOM_DESIGN; $account->save(); Session::flash('message', trans('texts.updated_settings')); } return Redirect::to('company/advanced_settings/customize_design'); } private function saveEmailTemplates() { if (Auth::user()->account->isPro()) { $account = Auth::user()->account; $account->email_template_invoice = Input::get('email_template_invoice', $account->getEmailTemplate(ENTITY_INVOICE)); $account->email_template_quote = Input::get('email_template_quote', $account->getEmailTemplate(ENTITY_QUOTE)); $account->email_template_payment = Input::get('email_template_payment', $account->getEmailTemplate(ENTITY_PAYMENT)); $account->save(); Session::flash('message', trans('texts.updated_settings')); } return Redirect::to('company/advanced_settings/email_templates'); } private function saveProducts() { $account = Auth::user()->account; $account->fill_products = Input::get('fill_products') ? true : false; $account->update_products = Input::get('update_products') ? true : false; $account->save(); Session::flash('message', trans('texts.updated_settings')); return Redirect::to('company/products'); } private function saveInvoiceSettings() { if (Auth::user()->account->isPro()) { $account = Auth::user()->account; $account->custom_label1 = trim(Input::get('custom_label1')); $account->custom_value1 = trim(Input::get('custom_value1')); $account->custom_label2 = trim(Input::get('custom_label2')); $account->custom_value2 = trim(Input::get('custom_value2')); $account->custom_client_label1 = trim(Input::get('custom_client_label1')); $account->custom_client_label2 = trim(Input::get('custom_client_label2')); $account->custom_invoice_label1 = trim(Input::get('custom_invoice_label1')); $account->custom_invoice_label2 = trim(Input::get('custom_invoice_label2')); $account->custom_invoice_taxes1 = Input::get('custom_invoice_taxes1') ? true : false; $account->custom_invoice_taxes2 = Input::get('custom_invoice_taxes2') ? true : false; $account->invoice_number_prefix = Input::get('invoice_number_prefix'); $account->invoice_number_counter = Input::get('invoice_number_counter'); $account->quote_number_prefix = Input::get('quote_number_prefix'); $account->share_counter = Input::get('share_counter') ? true : false; $account->pdf_email_attachment = Input::get('pdf_email_attachment') ? true : false; $account->auto_wrap = Input::get('auto_wrap') ? true : false; if (!$account->share_counter) { $account->quote_number_counter = Input::get('quote_number_counter'); } if (!$account->share_counter && $account->invoice_number_prefix == $account->quote_number_prefix) { Session::flash('error', trans('texts.invalid_counter')); return Redirect::to('company/advanced_settings/invoice_settings')->withInput(); } else { $account->save(); Session::flash('message', trans('texts.updated_settings')); } } return Redirect::to('company/advanced_settings/invoice_settings'); } private function saveInvoiceDesign() { if (Auth::user()->account->isPro()) { $account = Auth::user()->account; $account->hide_quantity = Input::get('hide_quantity') ? true : false; $account->hide_paid_to_date = Input::get('hide_paid_to_date') ? true : false; $account->primary_color = Input::get('primary_color'); $account->secondary_color = Input::get('secondary_color'); $account->invoice_design_id = Input::get('invoice_design_id'); if (Input::has('font_size')) { $account->font_size = intval(Input::get('font_size')); } $labels = []; foreach (['item', 'description', 'unit_cost', 'quantity'] as $field) { $labels[$field] = trim(Input::get("labels_{$field}")); } $account->invoice_labels = json_encode($labels); $account->save(); Session::flash('message', trans('texts.updated_settings')); } return Redirect::to('company/advanced_settings/invoice_design'); } private function export() { $output = fopen('php://output', 'w') or Utils::fatalError(); header('Content-Type:application/csv'); header('Content-Disposition:attachment;filename=export.csv'); $clients = Client::scope()->get(); Utils::exportData($output, $clients->toArray()); $contacts = Contact::scope()->get(); Utils::exportData($output, $contacts->toArray()); $invoices = Invoice::scope()->get(); Utils::exportData($output, $invoices->toArray()); $invoiceItems = InvoiceItem::scope()->get(); Utils::exportData($output, $invoiceItems->toArray()); $payments = Payment::scope()->get(); Utils::exportData($output, $payments->toArray()); $credits = Credit::scope()->get(); Utils::exportData($output, $credits->toArray()); fclose($output); exit; } private function importFile() { $data = Session::get('data'); Session::forget('data'); $map = Input::get('map'); $count = 0; $hasHeaders = Input::get('header_checkbox'); $countries = Cache::get('countries'); $countryMap = []; foreach ($countries as $country) { $countryMap[strtolower($country->name)] = $country->id; } foreach ($data as $row) { if ($hasHeaders) { $hasHeaders = false; continue; } $client = Client::createNew(); $contact = Contact::createNew(); $contact->is_primary = true; $contact->send_invoice = true; $count++; foreach ($row as $index => $value) { $field = $map[$index]; $value = trim($value); if ($field == Client::$fieldName && !$client->name) { $client->name = $value; } elseif ($field == Client::$fieldPhone && !$client->work_phone) { $client->work_phone = $value; } elseif ($field == Client::$fieldAddress1 && !$client->address1) { $client->address1 = $value; } elseif ($field == Client::$fieldAddress2 && !$client->address2) { $client->address2 = $value; } elseif ($field == Client::$fieldCity && !$client->city) { $client->city = $value; } elseif ($field == Client::$fieldState && !$client->state) { $client->state = $value; } elseif ($field == Client::$fieldPostalCode && !$client->postal_code) { $client->postal_code = $value; } elseif ($field == Client::$fieldCountry && !$client->country_id) { $value = strtolower($value); $client->country_id = isset($countryMap[$value]) ? $countryMap[$value] : null; } elseif ($field == Client::$fieldNotes && !$client->private_notes) { $client->private_notes = $value; } elseif ($field == Contact::$fieldFirstName && !$contact->first_name) { $contact->first_name = $value; } elseif ($field == Contact::$fieldLastName && !$contact->last_name) { $contact->last_name = $value; } elseif ($field == Contact::$fieldPhone && !$contact->phone) { $contact->phone = $value; } elseif ($field == Contact::$fieldEmail && !$contact->email) { $contact->email = strtolower($value); } } $client->save(); $client->contacts()->save($contact); Activity::createClient($client, false); } $message = Utils::pluralize('created_client', $count); Session::flash('message', $message); return Redirect::to('clients'); } private function mapFile() { $file = Input::file('file'); if ($file == null) { Session::flash('error', trans('texts.select_file')); return Redirect::to('company/import_export'); } $name = $file->getRealPath(); require_once app_path().'/Includes/parsecsv.lib.php'; $csv = new parseCSV(); $csv->heading = false; $csv->auto($name); if (count($csv->data) + Client::scope()->count() > Auth::user()->getMaxNumClients()) { $message = trans('texts.limit_clients', ['count' => Auth::user()->getMaxNumClients()]); Session::flash('error', $message); return Redirect::to('company/import_export'); } Session::put('data', $csv->data); $headers = false; $hasHeaders = false; $mapped = array(); $columns = array('', Client::$fieldName, Client::$fieldPhone, Client::$fieldAddress1, Client::$fieldAddress2, Client::$fieldCity, Client::$fieldState, Client::$fieldPostalCode, Client::$fieldCountry, Client::$fieldNotes, Contact::$fieldFirstName, Contact::$fieldLastName, Contact::$fieldPhone, Contact::$fieldEmail, ); if (count($csv->data) > 0) { $headers = $csv->data[0]; foreach ($headers as $title) { if (strpos(strtolower($title), 'name') > 0) { $hasHeaders = true; break; } } for ($i = 0; $i<count($headers); $i++) { $title = strtolower($headers[$i]); $mapped[$i] = ''; if ($hasHeaders) { $map = array( 'first' => Contact::$fieldFirstName, 'last' => Contact::$fieldLastName, 'email' => Contact::$fieldEmail, 'mobile' => Contact::$fieldPhone, 'phone' => Client::$fieldPhone, 'name|organization' => Client::$fieldName, 'street|address|address1' => Client::$fieldAddress1, 'street2|address2' => Client::$fieldAddress2, 'city' => Client::$fieldCity, 'state|province' => Client::$fieldState, 'zip|postal|code' => Client::$fieldPostalCode, 'country' => Client::$fieldCountry, 'note' => Client::$fieldNotes, ); foreach ($map as $search => $column) { foreach (explode("|", $search) as $string) { if (strpos($title, 'sec') === 0) { continue; } if (strpos($title, $string) !== false) { $mapped[$i] = $column; break(2); } } } } } } $data = array( 'data' => $csv->data, 'headers' => $headers, 'hasHeaders' => $hasHeaders, 'columns' => $columns, 'mapped' => $mapped, ); return View::make('accounts.import_map', $data); } private function saveNotifications() { $account = Auth::user()->account; $account->invoice_terms = Input::get('invoice_terms'); $account->invoice_footer = Input::get('invoice_footer'); $account->email_footer = Input::get('email_footer'); $account->save(); $user = Auth::user(); $user->notify_sent = Input::get('notify_sent'); $user->notify_viewed = Input::get('notify_viewed'); $user->notify_paid = Input::get('notify_paid'); $user->notify_approved = Input::get('notify_approved'); $user->save(); Session::flash('message', trans('texts.updated_settings')); return Redirect::to('company/notifications'); } private function saveDetails() { $rules = array( 'name' => 'required', 'logo' => 'sometimes|max:1024|mimes:jpeg,gif,png', ); $user = Auth::user()->account->users()->orderBy('id')->first(); if (Auth::user()->id === $user->id) { $rules['email'] = 'email|required|unique:users,email,'.$user->id.',id'; } $subdomain = preg_replace('/[^a-zA-Z0-9_\-]/', '', substr(strtolower(Input::get('subdomain')), 0, MAX_SUBDOMAIN_LENGTH)); if (!$subdomain || in_array($subdomain, ['www', 'app', 'mail', 'admin', 'blog', 'user', 'contact', 'payment', 'payments', 'billing', 'invoice', 'business', 'owner'])) { $subdomain = null; } if ($subdomain) { $rules['subdomain'] = "unique:accounts,subdomain,{$user->account_id},id"; } $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return Redirect::to('company/details') ->withErrors($validator) ->withInput(); } else { $account = Auth::user()->account; $account->name = trim(Input::get('name')); $account->subdomain = $subdomain; $account->id_number = trim(Input::get('id_number')); $account->vat_number = trim(Input::get('vat_number')); $account->work_email = trim(Input::get('work_email')); $account->work_phone = trim(Input::get('work_phone')); $account->address1 = trim(Input::get('address1')); $account->address2 = trim(Input::get('address2')); $account->city = trim(Input::get('city')); $account->state = trim(Input::get('state')); $account->postal_code = trim(Input::get('postal_code')); $account->country_id = Input::get('country_id') ? Input::get('country_id') : null; $account->size_id = Input::get('size_id') ? Input::get('size_id') : null; $account->industry_id = Input::get('industry_id') ? Input::get('industry_id') : null; $account->timezone_id = Input::get('timezone_id') ? Input::get('timezone_id') : null; $account->date_format_id = Input::get('date_format_id') ? Input::get('date_format_id') : null; $account->datetime_format_id = Input::get('datetime_format_id') ? Input::get('datetime_format_id') : null; $account->currency_id = Input::get('currency_id') ? Input::get('currency_id') : 1; // US Dollar $account->language_id = Input::get('language_id') ? Input::get('language_id') : 1; // English $account->save(); if (Auth::user()->id === $user->id) { $user->first_name = trim(Input::get('first_name')); $user->last_name = trim(Input::get('last_name')); $user->username = trim(Input::get('email')); $user->email = trim(strtolower(Input::get('email'))); $user->phone = trim(Input::get('phone')); if (Utils::isNinjaDev()) { $user->dark_mode = Input::get('dark_mode') ? true : false; } $user->save(); } /* Logo image file */ if ($file = Input::file('logo')) { $path = Input::file('logo')->getRealPath(); File::delete('logo/'.$account->account_key.'.jpg'); File::delete('logo/'.$account->account_key.'.png'); $mimeType = $file->getMimeType(); if ($mimeType == 'image/jpeg') { $file->move('logo/', $account->account_key . '.jpg'); } else if ($mimeType == 'image/png') { $file->move('logo/', $account->account_key . '.png'); } else { if (extension_loaded('fileinfo')) { $image = Image::make($path); $image->resize(200, 120, function ($constraint) { $constraint->aspectRatio(); }); Image::canvas($image->width(), $image->height(), '#FFFFFF') ->insert($image)->save('logo/'.$account->account_key.'.jpg'); } else { Session::flash('warning', 'Warning: To support gifs the fileinfo PHP extension needs to be enabled.'); } } } Session::flash('message', trans('texts.updated_settings')); return Redirect::to('company/details'); } } public function removeLogo() { File::delete('logo/'.Auth::user()->account->account_key.'.jpg'); File::delete('logo/'.Auth::user()->account->account_key.'.png'); Session::flash('message', trans('texts.removed_logo')); return Redirect::to('company/details'); } public function checkEmail() { $email = User::withTrashed()->where('email', '=', Input::get('email'))->where('id', '<>', Auth::user()->id)->first(); if ($email) { return "taken"; } else { return "available"; } } public function submitSignup() { $rules = array( 'new_first_name' => 'required', 'new_last_name' => 'required', 'new_password' => '<PASSWORD>', 'new_email' => 'email|required|unique:users,email,'.Auth::user()->id.',id', ); $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return ''; } $user = Auth::user(); $user->first_name = trim(Input::get('new_first_name')); $user->last_name = trim(Input::get('new_last_name')); $user->email = trim(strtolower(Input::get('new_email'))); $user->username = $user->email; $user->password = <PASSWORD>(<PASSWORD>(Input::get('new_password'))); $user->registered = true; $user->save(); if (Utils::isNinjaProd()) { $this->userMailer->sendConfirmation($user); } $activities = Activity::scope()->get(); foreach ($activities as $activity) { $activity->message = str_replace('Guest', $user->getFullName(), $activity->message); $activity->save(); } if (Input::get('go_pro') == 'true') { Session::set(REQUESTED_PRO_PLAN, true); } Session::set(SESSION_COUNTER, -1); return "{$user->first_name} {$user->last_name}"; } public function doRegister() { $affiliate = Affiliate::where('affiliate_key', '=', SELF_HOST_AFFILIATE_KEY)->first(); $email = trim(Input::get('email')); if (!$email || $email == '<EMAIL>') { return ''; } $license = new License(); $license->first_name = Input::get('first_name'); $license->last_name = Input::get('last_name'); $license->email = $email; $license->transaction_reference = Request::getClientIp(); $license->license_key = Utils::generateLicense(); $license->affiliate_id = $affiliate->id; $license->product_id = PRODUCT_SELF_HOST; $license->is_claimed = 1; $license->save(); return ''; } public function cancelAccount() { if ($reason = trim(Input::get('reason'))) { $email = Auth::user()->email; $name = Auth::user()->getDisplayName(); $data = [ 'text' => $reason, ]; $this->userMailer->sendTo(CONTACT_EMAIL, $email, $name, 'Invoice Ninja Feedback [Canceled Account]', 'contact', $data); } $account = Auth::user()->account; $this->accountRepo->unlinkAccount($account); $account->forceDelete(); Auth::logout(); Session::flush(); return Redirect::to('/')->with('clearGuestKey', true); } public function resendConfirmation() { $user = Auth::user(); $this->userMailer->sendConfirmation($user); return Redirect::to('/company/details')->with('message', trans('texts.confirmation_resent')); } } <file_sep>/app/Ninja/Repositories/AccountRepository.php <?php namespace App\Ninja\Repositories; use Auth; use Request; use Session; use Utils; use DB; use stdClass; use Schema; use App\Models\AccountGateway; use App\Models\Invitation; use App\Models\Invoice; use App\Models\InvoiceItem; use App\Models\Client; use App\Models\Language; use App\Models\Contact; use App\Models\Account; use App\Models\User; use App\Models\UserAccount; class AccountRepository { public function create($firstName = '', $lastName = '', $email = '', $password = '') { $account = new Account(); $account->ip = Request::getClientIp(); $account->account_key = str_random(RANDOM_KEY_LENGTH); if (Session::has(SESSION_LOCALE)) { $locale = Session::get(SESSION_LOCALE); if ($language = Language::whereLocale($locale)->first()) { $account->language_id = $language->id; } } $account->save(); $user = new User(); if (!$firstName && !$lastName && !$email && !$password) { $user->password = str_random(RANDOM_KEY_LENGTH); $user->username = str_random(RANDOM_KEY_LENGTH); } else { $user->first_name = $firstName; $user->last_name = $lastName; $user->email = $user->username = $email; $user->password = <PASSWORD>($password); } $user->confirmed = !Utils::isNinja(); $user->registered = !Utils::isNinja() && $user->email; if (!$user->confirmed) { $user->confirmation_code = str_random(RANDOM_KEY_LENGTH); } $account->users()->save($user); return $account; } public function getSearchData() { $clients = \DB::table('clients') ->where('clients.deleted_at', '=', null) ->where('clients.account_id', '=', \Auth::user()->account_id) ->whereRaw("clients.name <> ''") ->select(\DB::raw("'Clients' as type, clients.public_id, clients.name, '' as token")); $contacts = \DB::table('clients') ->join('contacts', 'contacts.client_id', '=', 'clients.id') ->where('clients.deleted_at', '=', null) ->where('clients.account_id', '=', \Auth::user()->account_id) ->whereRaw("CONCAT(contacts.first_name, contacts.last_name, contacts.email) <> ''") ->select(\DB::raw("'Contacts' as type, clients.public_id, CONCAT(contacts.first_name, ' ', contacts.last_name, ' ', contacts.email) as name, '' as token")); $invoices = \DB::table('clients') ->join('invoices', 'invoices.client_id', '=', 'clients.id') ->where('clients.account_id', '=', \Auth::user()->account_id) ->where('clients.deleted_at', '=', null) ->where('invoices.deleted_at', '=', null) ->select(\DB::raw("'Invoices' as type, invoices.public_id, CONCAT(invoices.invoice_number, ': ', clients.name) as name, invoices.invoice_number as token")); $data = []; foreach ($clients->union($contacts)->union($invoices)->get() as $row) { $type = $row->type; if (!isset($data[$type])) { $data[$type] = []; } $tokens = explode(' ', $row->name); $tokens[] = $type; if ($type == 'Invoices') { $tokens[] = intVal($row->token).''; } $data[$type][] = [ 'value' => $row->name, 'public_id' => $row->public_id, 'tokens' => $tokens, ]; } return $data; } public function enableProPlan() { if (Auth::user()->isPro()) { return false; } $client = $this->getNinjaClient(Auth::user()->account); $invitation = $this->createNinjaInvoice($client); return $invitation; } public function createNinjaInvoice($client) { $account = $this->getNinjaAccount(); $lastInvoice = Invoice::withTrashed()->whereAccountId($account->id)->orderBy('public_id', 'DESC')->first(); $publicId = $lastInvoice ? ($lastInvoice->public_id + 1) : 1; $invoice = new Invoice(); $invoice->account_id = $account->id; $invoice->user_id = $account->users()->first()->id; $invoice->public_id = $publicId; $invoice->client_id = $client->id; $invoice->invoice_number = $account->getNextInvoiceNumber(); $invoice->invoice_date = date_create()->format('Y-m-d'); $invoice->amount = PRO_PLAN_PRICE; $invoice->balance = PRO_PLAN_PRICE; $invoice->save(); $item = new InvoiceItem(); $item->account_id = $account->id; $item->user_id = $account->users()->first()->id; $item->public_id = $publicId; $item->qty = 1; $item->cost = PRO_PLAN_PRICE; $item->notes = trans('texts.pro_plan_description'); $item->product_key = trans('texts.pro_plan_product'); $invoice->invoice_items()->save($item); $invitation = new Invitation(); $invitation->account_id = $account->id; $invitation->user_id = $account->users()->first()->id; $invitation->public_id = $publicId; $invitation->invoice_id = $invoice->id; $invitation->contact_id = $client->contacts()->first()->id; $invitation->invitation_key = str_random(RANDOM_KEY_LENGTH); $invitation->save(); return $invitation; } public function getNinjaAccount() { $account = Account::whereAccountKey(NINJA_ACCOUNT_KEY)->first(); if ($account) { return $account; } else { $account = new Account(); $account->name = '<NAME>'; $account->work_email = '<EMAIL>'; $account->work_phone = '(800) 763-1948'; $account->account_key = NINJA_ACCOUNT_KEY; $account->save(); $random = str_random(RANDOM_KEY_LENGTH); $user = new User(); $user->registered = true; $user->confirmed = true; $user->email = '<EMAIL>'; $user->password = $<PASSWORD>; $user->username = $random; $user->first_name = 'Invoice'; $user->last_name = 'Ninja'; $user->notify_sent = true; $user->notify_paid = true; $account->users()->save($user); $accountGateway = new AccountGateway(); $accountGateway->user_id = $user->id; $accountGateway->gateway_id = NINJA_GATEWAY_ID; $accountGateway->public_id = 1; $accountGateway->config = NINJA_GATEWAY_CONFIG; $account->account_gateways()->save($accountGateway); } return $account; } public function getNinjaClient($account) { $account->load('users'); $ninjaAccount = $this->getNinjaAccount(); $client = Client::whereAccountId($ninjaAccount->id)->wherePublicId($account->id)->first(); if (!$client) { $client = new Client(); $client->public_id = $account->id; $client->user_id = $ninjaAccount->users()->first()->id; $client->currency_id = 1; foreach (['name', 'address1', 'address2', 'city', 'state', 'postal_code', 'country_id', 'work_phone'] as $field) { $client->$field = $account->$field; } $ninjaAccount->clients()->save($client); $contact = new Contact(); $contact->user_id = $ninjaAccount->users()->first()->id; $contact->account_id = $ninjaAccount->id; $contact->public_id = $account->id; $contact->is_primary = true; foreach (['first_name', 'last_name', 'email', 'phone'] as $field) { $contact->$field = $account->users()->first()->$field; } $client->contacts()->save($contact); } return $client; } public function registerUser($user) { $url = (Utils::isNinjaDev() ? '' : NINJA_APP_URL) . '/signup/register'; $data = ''; $fields = [ 'first_name' => urlencode($user->first_name), 'last_name' => urlencode($user->last_name), 'email' => urlencode($user->email), ]; foreach ($fields as $key => $value) { $data .= $key.'='.$value.'&'; } rtrim($data, '&'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, count($fields)); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_exec($ch); curl_close($ch); } public function findUserAccounts($userId1, $userId2 = false) { if (!Schema::hasTable('user_accounts')) { return false; } $query = UserAccount::where('user_id1', '=', $userId1) ->orWhere('user_id2', '=', $userId1) ->orWhere('user_id3', '=', $userId1) ->orWhere('user_id4', '=', $userId1) ->orWhere('user_id5', '=', $userId1); if ($userId2) { $query->orWhere('user_id1', '=', $userId2) ->orWhere('user_id2', '=', $userId2) ->orWhere('user_id3', '=', $userId2) ->orWhere('user_id4', '=', $userId2) ->orWhere('user_id5', '=', $userId2); } return $query->first(['id', 'user_id1', 'user_id2', 'user_id3', 'user_id4', 'user_id5']); } public function prepareUsersData($record) { if (!$record) { return false; } $userIds = []; for ($i=1; $i<=5; $i++) { $field = "user_id$i"; if ($record->$field) { $userIds[] = $record->$field; } } $users = User::with('account') ->whereIn('id', $userIds) ->get(); $data = []; foreach ($users as $user) { $item = new stdClass(); $item->id = $record->id; $item->user_id = $user->id; $item->user_name = $user->getDisplayName(); $item->account_id = $user->account->id; $item->account_name = $user->account->getDisplayName(); $item->pro_plan_paid = $user->account->pro_plan_paid; $item->logo_path = file_exists($user->account->getLogoPath()) ? $user->account->getLogoPath() : null; $data[] = $item; } return $data; } public function loadAccounts($userId) { $record = self::findUserAccounts($userId); return self::prepareUsersData($record); } public function syncAccounts($userId, $proPlanPaid) { $users = self::loadAccounts($userId); self::syncUserAccounts($users, $proPlanPaid); } public function syncUserAccounts($users, $proPlanPaid = false) { if (!$users) { return; } if (!$proPlanPaid) { foreach ($users as $user) { if ($user->pro_plan_paid && $user->pro_plan_paid != '0000-00-00') { $proPlanPaid = $user->pro_plan_paid; break; } } } if (!$proPlanPaid) { return; } $accountIds = []; foreach ($users as $user) { if ($user->pro_plan_paid != $proPlanPaid) { $accountIds[] = $user->account_id; } } if (count($accountIds)) { DB::table('accounts') ->whereIn('id', $accountIds) ->update(['pro_plan_paid' => $proPlanPaid]); } } public function associateAccounts($userId1, $userId2) { $record = self::findUserAccounts($userId1, $userId2); if ($record) { foreach ([$userId1, $userId2] as $userId) { if (!$record->hasUserId($userId)) { $record->setUserId($userId); } } } else { $record = new UserAccount(); $record->user_id1 = $userId1; $record->user_id2 = $userId2; } $record->save(); $users = self::prepareUsersData($record); self::syncUserAccounts($users); return $users; } public function unlinkAccount($account) { foreach ($account->users as $user) { if ($userAccount = self::findUserAccounts($user->id)) { $userAccount->removeUserId($user->id); $userAccount->save(); } } } public function unlinkUser($userAccountId, $userId) { $userAccount = UserAccount::whereId($userAccountId)->first(); if ($userAccount->hasUserId($userId)) { $userAccount->removeUserId($userId); $userAccount->save(); } } } <file_sep>/app/Events/InvoicePaid.php <?php namespace App\Events; use App\Events\Event; use Illuminate\Queue\SerializesModels; class InvoicePaid extends Event { use SerializesModels; public $payment; /** * Create a new event instance. * * @return void */ public function __construct($payment) { $this->payment = $payment; } } <file_sep>/app/Models/EntityModel.php <?php namespace App\Models; use Auth; use Eloquent; use Utils; class EntityModel extends Eloquent { public $timestamps = true; protected $hidden = ['id']; public static function createNew($parent = false) { $className = get_called_class(); $entity = new $className(); if ($parent) { $entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id; $entity->account_id = $parent->account_id; } elseif (Auth::check()) { $entity->user_id = Auth::user()->id; $entity->account_id = Auth::user()->account_id; } else { Utils::fatalError(); } $lastEntity = $className::withTrashed()->scope(false, $entity->account_id)->orderBy('public_id', 'DESC')->first(); if ($lastEntity) { $entity->public_id = $lastEntity->public_id + 1; } else { $entity->public_id = 1; } return $entity; } public static function getPrivateId($publicId) { $className = get_called_class(); return $className::scope($publicId)->pluck('id'); } public function getActivityKey() { return '[' . $this->getEntityType().':'.$this->public_id.':'.$this->getDisplayName() . ']'; } /* public function getEntityType() { return ''; } public function getNmae() { return ''; } */ public function scopeScope($query, $publicId = false, $accountId = false) { if (!$accountId) { $accountId = Auth::user()->account_id; } $query->where($this->getTable() .'.account_id', '=', $accountId); if ($publicId) { if (is_array($publicId)) { $query->whereIn('public_id', $publicId); } else { $query->wherePublicId($publicId); } } return $query; } public function getName() { return $this->public_id; } public function getDisplayName() { return $this->getName(); } // Remap ids to public_ids and show name public function toPublicArray() { $data = $this->toArray(); foreach ($this->attributes as $key => $val) { if (strpos($key, '_id')) { list($field, $id) = explode('_', $key); if ($field == 'account') { // do nothing } else { $entity = @$this->$field; if ($entity) { $data["{$field}_name"] = $entity->getName(); } } } } $data = Utils::hideIds($data); return $data; } } <file_sep>/app/Models/Task.php <?php namespace App\Models; use DB; use Utils; use Illuminate\Database\Eloquent\SoftDeletes; class Task extends EntityModel { use SoftDeletes; public function account() { return $this->belongsTo('App\Models\Account'); } public function invoice() { return $this->belongsTo('App\Models\Invoice'); } public function client() { return $this->belongsTo('App\Models\Client')->withTrashed(); } public static function calcStartTime($task) { $parts = json_decode($task->time_log) ?: []; if (count($parts)) { return Utils::timestampToDateTimeString($parts[0][0]); } else { return ''; } } public function getStartTime() { return self::calcStartTime($this); } public static function calcDuration($task) { $duration = 0; $parts = json_decode($task->time_log) ?: []; foreach ($parts as $part) { if (count($part) == 1 || !$part[1]) { $duration += time() - $part[0]; } else { $duration += $part[1] - $part[0]; } } return $duration; } public function getDuration() { return self::calcDuration($this); } public function getCurrentDuration() { $parts = json_decode($this->time_log) ?: []; $part = $parts[count($parts)-1]; if (count($part) == 1 || !$part[1]) { return time() - $part[0]; } else { return 0; } } public function hasPreviousDuration() { $parts = json_decode($this->time_log) ?: []; return count($parts) && (count($parts[0]) && $parts[0][1]); } public function getHours() { return round($this->getDuration() / (60 * 60), 2); } } Task::created(function ($task) { //Activity::createTask($task); }); Task::updating(function ($task) { //Activity::updateTask($task); }); Task::deleting(function ($task) { //Activity::archiveTask($task); }); Task::restoring(function ($task) { //Activity::restoreTask($task); }); <file_sep>/app/Ninja/Repositories/CreditRepository.php <?php namespace App\Ninja\Repositories; use App\Models\Credit; use App\Models\Client; use Utils; class CreditRepository { public function find($clientPublicId = null, $filter = null) { $query = \DB::table('credits') ->join('clients', 'clients.id', '=', 'credits.client_id') ->join('contacts', 'contacts.client_id', '=', 'clients.id') ->where('clients.account_id', '=', \Auth::user()->account_id) ->where('clients.deleted_at', '=', null) ->where('contacts.is_primary', '=', true) ->select('credits.public_id', 'clients.name as client_name', 'clients.public_id as client_public_id', 'credits.amount', 'credits.balance', 'credits.credit_date', 'clients.currency_id', 'contacts.first_name', 'contacts.last_name', 'contacts.email', 'credits.private_notes', 'credits.deleted_at', 'credits.is_deleted'); if ($clientPublicId) { $query->where('clients.public_id', '=', $clientPublicId); } if (!\Session::get('show_trash:credit')) { $query->where('credits.deleted_at', '=', null); } if ($filter) { $query->where(function ($query) use ($filter) { $query->where('clients.name', 'like', '%'.$filter.'%'); }); } return $query; } public function save($publicId = null, $input) { if ($publicId) { $credit = Credit::scope($publicId)->firstOrFail(); } else { $credit = Credit::createNew(); } $credit->client_id = Client::getPrivateId($input['client']); $credit->credit_date = Utils::toSqlDate($input['credit_date']); $credit->amount = Utils::parseFloat($input['amount']); $credit->balance = Utils::parseFloat($input['amount']); $credit->private_notes = trim($input['private_notes']); $credit->save(); return $credit; } public function bulk($ids, $action) { if (!$ids) { return 0; } $credits = Credit::withTrashed()->scope($ids)->get(); foreach ($credits as $credit) { if ($action == 'restore') { $credit->restore(); } else { if ($action == 'delete') { $credit->is_deleted = true; $credit->save(); } $credit->delete(); } } return count($credits); } } <file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use Response; use Request; use Redirect; use Auth; use View; use Input; use Session; use App\Models\Account; use App\Libraries\Utils; use App\Ninja\Mailers\Mailer; use Symfony\Component\Security\Core\Util\StringUtils; class HomeController extends BaseController { protected $mailer; public function __construct(Mailer $mailer) { parent::__construct(); $this->mailer = $mailer; } public function showIndex() { Session::reflash(); if (!Utils::isNinja() && (!Utils::isDatabaseSetup() || Account::count() == 0)) { return Redirect::to('/setup'); } elseif (Auth::check()) { return Redirect::to('/dashboard'); } else { return Redirect::to('/login'); } } public function showTerms() { return View::make('public.terms', ['hideHeader' => true]); } public function invoiceNow() { if (Auth::check() && Input::get('new_company')) { Session::put(PREV_USER_ID, Auth::user()->id); Auth::user()->clearSession(); Auth::logout(); } if (Auth::check()) { $redirectTo = Input::get('redirect_to', 'invoices/create'); return Redirect::to($redirectTo)->with('sign_up', Input::get('sign_up')); } else { return View::make('public.header', ['invoiceNow' => true]); } } public function newsFeed($userType, $version) { $response = Utils::getNewsFeedResponse($userType); return Response::json($response); } public function hideMessage() { if (Auth::check() && Session::has('news_feed_id')) { $newsFeedId = Session::get('news_feed_id'); if ($newsFeedId != NEW_VERSION_AVAILABLE && $newsFeedId > Auth::user()->news_feed_id) { $user = Auth::user(); $user->news_feed_id = $newsFeedId; $user->save(); } } Session::forget('news_feed_message'); return 'success'; } public function logError() { return Utils::logError(Input::get('error'), 'JavaScript'); } public function keepAlive() { return RESULT_SUCCESS; } } <file_sep>/app/Console/Commands/SendRenewalInvoices.php <?php namespace App\Console\Commands; use DB; use DateTime; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use App\Models\Account; use App\Ninja\Mailers\ContactMailer as Mailer; use App\Ninja\Repositories\AccountRepository; class SendRenewalInvoices extends Command { protected $name = 'ninja:send-renewals'; protected $description = 'Send renewal invoices'; protected $mailer; protected $accountRepo; public function __construct(Mailer $mailer, AccountRepository $repo) { parent::__construct(); $this->mailer = $mailer; $this->accountRepo = $repo; } public function fire() { $this->info(date('Y-m-d').' Running SendRenewalInvoices...'); $today = new DateTime(); $accounts = Account::whereRaw('datediff(curdate(), pro_plan_paid) = 355')->get(); $this->info(count($accounts).' accounts found'); foreach ($accounts as $account) { $client = $this->accountRepo->getNinjaClient($account); $invitation = $this->accountRepo->createNinjaInvoice($client); $this->mailer->sendInvoice($invitation->invoice); } $this->info('Done'); } protected function getArguments() { return array( //array('example', InputArgument::REQUIRED, 'An example argument.'), ); } protected function getOptions() { return array( //array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null), ); } } <file_sep>/app/Http/Controllers/CreditController.php <?php namespace App\Http\Controllers; use Datatable; use Input; use Redirect; use Session; use Utils; use View; use Validator; use App\Models\Client; use App\Ninja\Repositories\CreditRepository; class CreditController extends BaseController { protected $creditRepo; public function __construct(CreditRepository $creditRepo) { parent::__construct(); $this->creditRepo = $creditRepo; } /** * Display a listing of the resource. * * @return Response */ public function index() { return View::make('list', array( 'entityType' => ENTITY_CREDIT, 'title' => trans('texts.credits'), 'sortCol' => '4', 'columns' => Utils::trans(['checkbox', 'client', 'credit_amount', 'credit_balance', 'credit_date', 'private_notes', 'action']), )); } public function getDatatable($clientPublicId = null) { $credits = $this->creditRepo->find($clientPublicId, Input::get('sSearch')); $table = Datatable::query($credits); if (!$clientPublicId) { $table->addColumn('checkbox', function ($model) { return '<input type="checkbox" name="ids[]" value="'.$model->public_id.'" '.Utils::getEntityRowClass($model).'>'; }) ->addColumn('client_name', function ($model) { return link_to('clients/'.$model->client_public_id, Utils::getClientDisplayName($model)); }); } return $table->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id).'<span '.Utils::getEntityRowClass($model).'/>'; }) ->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id); }) ->addColumn('credit_date', function ($model) { return Utils::fromSqlDate($model->credit_date); }) ->addColumn('private_notes', function ($model) { return $model->private_notes; }) ->addColumn('dropdown', function ($model) { if ($model->is_deleted) { return '<div style="height:38px"/>'; } $str = '<div class="btn-group tr-action" style="visibility:hidden;"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> '.trans('texts.select').' <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu">'; if (!$model->deleted_at || $model->deleted_at == '0000-00-00') { $str .= '<li><a href="javascript:archiveEntity('.$model->public_id.')">'.trans('texts.archive_credit').'</a></li>'; } else { $str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans('texts.restore_credit').'</a></li>'; } return $str.'<li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans('texts.delete_credit').'</a></li></ul> </div>'; }) ->make(); } public function create($clientPublicId = 0) { $data = array( 'clientPublicId' => Input::old('client') ? Input::old('client') : $clientPublicId, //'invoicePublicId' => Input::old('invoice') ? Input::old('invoice') : $invoicePublicId, 'credit' => null, 'method' => 'POST', 'url' => 'credits', 'title' => trans('texts.new_credit'), //'invoices' => Invoice::scope()->with('client', 'invoice_status')->orderBy('invoice_number')->get(), 'clients' => Client::scope()->with('contacts')->orderBy('name')->get(), ); return View::make('credits.edit', $data); } public function edit($publicId) { $credit = Credit::scope($publicId)->firstOrFail(); $credit->credit_date = Utils::fromSqlDate($credit->credit_date); $data = array( 'client' => null, 'credit' => $credit, 'method' => 'PUT', 'url' => 'credits/'.$publicId, 'title' => 'Edit Credit', 'clients' => Client::scope()->with('contacts')->orderBy('name')->get(), ); return View::make('credit.edit', $data); } public function store() { return $this->save(); } public function update($publicId) { return $this->save($publicId); } private function save($publicId = null) { $rules = array( 'client' => 'required', 'amount' => 'required|positive', ); $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { $url = $publicId ? 'credits/'.$publicId.'/edit' : 'credits/create'; return Redirect::to($url) ->withErrors($validator) ->withInput(); } else { $this->creditRepo->save($publicId, Input::all()); $message = trans('texts.created_credit'); Session::flash('message', $message); return Redirect::to('clients/'.Input::get('client')); } } public function bulk() { $action = Input::get('action'); $ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $count = $this->creditRepo->bulk($ids, $action); if ($count > 0) { $message = Utils::pluralize($action.'d_credit', $count); Session::flash('message', $message); } return Redirect::to('credits'); } } <file_sep>/tests/acceptance/GatewayCest.php <?php use \AcceptanceTester; use Faker\Factory; class GatewayCest { private $faker; public function _before(AcceptanceTester $I) { $I->checkIfLogin($I); $this->faker = Factory::create(); } // tests public function create(AcceptanceTester $I) { $I->wantTo("create a gateway"); $I->amOnPage('/gateways/create'); $I->seeCurrentUrlEquals('/gateways/create'); $I->fillField(['name' => '23_apiKey'], $this->faker->swiftBicNumber); $I->click('Save'); $I->see('Successfully created gateway'); $I->seeInDatabase('account_gateways', array('gateway_id' => 23)); } } <file_sep>/app/Http/Controllers/ReportController.php <?php namespace App\Http\Controllers; use Auth; use Config; use Input; use Utils; use DB; use DateInterval; use DatePeriod; use Session; use View; use App\Models\Account; class ReportController extends BaseController { public function d3() { $message = ''; $fileName = storage_path() . '/dataviz_sample.txt'; if (Auth::user()->account->isPro()) { $account = Account::where('id', '=', Auth::user()->account->id) ->with(['clients.invoices.invoice_items', 'clients.contacts']) ->first(); $account = $account->hideFieldsForViz(); $clients = $account->clients->toJson(); } elseif (file_exists($fileName)) { $clients = file_get_contents($fileName); $message = trans('texts.sample_data'); } else { $clients = '[]'; } $data = [ 'feature' => ACCOUNT_DATA_VISUALIZATIONS, 'clients' => $clients, 'message' => $message, ]; return View::make('reports.d3', $data); } public function showReports() { $action = Input::get('action'); if (Input::all()) { $groupBy = Input::get('group_by'); $chartType = Input::get('chart_type'); $reportType = Input::get('report_type'); $startDate = Utils::toSqlDate(Input::get('start_date'), false); $endDate = Utils::toSqlDate(Input::get('end_date'), false); $enableReport = Input::get('enable_report') ? true : false; $enableChart = Input::get('enable_chart') ? true : false; } else { $groupBy = 'MONTH'; $chartType = 'Bar'; $reportType = ''; $startDate = Utils::today(false)->modify('-3 month'); $endDate = Utils::today(false); $enableReport = true; $enableChart = true; } $datasets = []; $labels = []; $maxTotals = 0; $width = 10; $displayData = []; $exportData = []; $reportTotals = [ 'amount' => [], 'balance' => [], 'paid' => [] ]; if ($reportType) { $columns = ['client', 'amount', 'paid', 'balance']; } else { $columns = ['client', 'invoice_number', 'invoice_date', 'amount', 'paid', 'balance']; } if (Auth::user()->account->isPro()) { if ($enableReport) { $query = DB::table('invoices') ->join('clients', 'clients.id', '=', 'invoices.client_id') ->join('contacts', 'contacts.client_id', '=', 'clients.id') ->where('invoices.account_id', '=', Auth::user()->account_id) ->where('invoices.is_deleted', '=', false) ->where('clients.is_deleted', '=', false) ->where('contacts.deleted_at', '=', null) ->where('invoices.invoice_date', '>=', $startDate->format('Y-m-d')) ->where('invoices.invoice_date', '<=', $endDate->format('Y-m-d')) ->where('invoices.is_quote', '=', false) ->where('invoices.is_recurring', '=', false) ->where('contacts.is_primary', '=', true); $select = ['clients.currency_id', 'contacts.first_name', 'contacts.last_name', 'contacts.email', 'clients.name as client_name', 'clients.public_id as client_public_id', 'invoices.public_id as invoice_public_id']; if ($reportType) { $query->groupBy('clients.id'); array_push($select, DB::raw('sum(invoices.amount) amount'), DB::raw('sum(invoices.balance) balance'), DB::raw('sum(invoices.amount - invoices.balance) paid')); } else { array_push($select, 'invoices.invoice_number', 'invoices.amount', 'invoices.balance', 'invoices.invoice_date', DB::raw('(invoices.amount - invoices.balance) paid')); $query->orderBy('invoices.id'); } $query->select($select); $data = $query->get(); foreach ($data as $record) { // web display data $displayRow = [link_to('/clients/'.$record->client_public_id, Utils::getClientDisplayName($record))]; if (!$reportType) { array_push($displayRow, link_to('/invoices/'.$record->invoice_public_id, $record->invoice_number), Utils::fromSqlDate($record->invoice_date, true) ); } array_push($displayRow, Utils::formatMoney($record->amount, $record->currency_id), Utils::formatMoney($record->paid, $record->currency_id), Utils::formatMoney($record->balance, $record->currency_id) ); // export data $exportRow = [trans('texts.client') => Utils::getClientDisplayName($record)]; if (!$reportType) { $exportRow[trans('texts.invoice_number')] = $record->invoice_number; $exportRow[trans('texts.invoice_date')] = Utils::fromSqlDate($record->invoice_date, true); } $exportRow[trans('texts.amount')] = Utils::formatMoney($record->amount, $record->currency_id); $exportRow[trans('texts.paid')] = Utils::formatMoney($record->paid, $record->currency_id); $exportRow[trans('texts.balance')] = Utils::formatMoney($record->balance, $record->currency_id); $displayData[] = $displayRow; $exportData[] = $exportRow; $accountCurrencyId = Auth::user()->account->currency_id; $currencyId = $record->currency_id ? $record->currency_id : ($accountCurrencyId ? $accountCurrencyId : DEFAULT_CURRENCY); if (!isset($reportTotals['amount'][$currencyId])) { $reportTotals['amount'][$currencyId] = 0; $reportTotals['balance'][$currencyId] = 0; $reportTotals['paid'][$currencyId] = 0; } $reportTotals['amount'][$currencyId] += $record->amount; $reportTotals['paid'][$currencyId] += $record->paid; $reportTotals['balance'][$currencyId] += $record->balance; } if ($action == 'export') { self::export($exportData, $reportTotals); } } if ($enableChart) { foreach ([ENTITY_INVOICE, ENTITY_PAYMENT, ENTITY_CREDIT] as $entityType) { // SQLite does not support the YEAR(), MONTH(), WEEK() and similar functions. // Let's see if SQLite is being used. if (Config::get('database.connections.'.Config::get('database.default').'.driver') == 'sqlite') { // Replace the unsupported function with it's date format counterpart switch ($groupBy) { case 'MONTH': $dateFormat = '%m'; // returns 01-12 break; case 'WEEK': $dateFormat = '%W'; // returns 00-53 break; case 'DAYOFYEAR': $dateFormat = '%j'; // returns 001-366 break; default: $dateFormat = '%m'; // MONTH by default break; } // Concatenate the year and the chosen timeframe (Month, Week or Day) $timeframe = 'strftime("%Y", '.$entityType.'_date) || strftime("'.$dateFormat.'", '.$entityType.'_date)'; } else { // Supported by Laravel's other DBMS drivers (MySQL, MSSQL and PostgreSQL) $timeframe = 'concat(YEAR('.$entityType.'_date), '.$groupBy.'('.$entityType.'_date))'; } $records = DB::table($entityType.'s') ->select(DB::raw('sum(amount) as total, '.$timeframe.' as '.$groupBy)) ->where('account_id', '=', Auth::user()->account_id) ->where($entityType.'s.is_deleted', '=', false) ->where($entityType.'s.'.$entityType.'_date', '>=', $startDate->format('Y-m-d')) ->where($entityType.'s.'.$entityType.'_date', '<=', $endDate->format('Y-m-d')) ->groupBy($groupBy); if ($entityType == ENTITY_INVOICE) { $records->where('is_quote', '=', false) ->where('is_recurring', '=', false); } $totals = $records->lists('total'); $dates = $records->lists($groupBy); $data = array_combine($dates, $totals); $padding = $groupBy == 'DAYOFYEAR' ? 'day' : ($groupBy == 'WEEK' ? 'week' : 'month'); $endDate->modify('+1 '.$padding); $interval = new DateInterval('P1'.substr($groupBy, 0, 1)); $period = new DatePeriod($startDate, $interval, $endDate); $endDate->modify('-1 '.$padding); $totals = []; foreach ($period as $d) { $dateFormat = $groupBy == 'DAYOFYEAR' ? 'z' : ($groupBy == 'WEEK' ? 'W' : 'n'); $date = $d->format('Y'.$dateFormat); $totals[] = isset($data[$date]) ? $data[$date] : 0; if ($entityType == ENTITY_INVOICE) { $labelFormat = $groupBy == 'DAYOFYEAR' ? 'j' : ($groupBy == 'WEEK' ? 'W' : 'F'); $label = $d->format($labelFormat); $labels[] = $label; } } $max = max($totals); if ($max > 0) { $datasets[] = [ 'totals' => $totals, 'colors' => $entityType == ENTITY_INVOICE ? '78,205,196' : ($entityType == ENTITY_CREDIT ? '199,244,100' : '255,107,107'), ]; $maxTotals = max($max, $maxTotals); } } $width = (ceil($maxTotals / 100) * 100) / 10; $width = max($width, 10); } } $dateTypes = [ 'DAYOFYEAR' => 'Daily', 'WEEK' => 'Weekly', 'MONTH' => 'Monthly', ]; $chartTypes = [ 'Bar' => 'Bar', 'Line' => 'Line', ]; $reportTypes = [ '' => '', 'Client' => trans('texts.client') ]; $params = [ 'labels' => $labels, 'datasets' => $datasets, 'scaleStepWidth' => $width, 'dateTypes' => $dateTypes, 'chartTypes' => $chartTypes, 'chartType' => $chartType, 'startDate' => $startDate->format(Session::get(SESSION_DATE_FORMAT)), 'endDate' => $endDate->format(Session::get(SESSION_DATE_FORMAT)), 'groupBy' => $groupBy, 'feature' => ACCOUNT_CHART_BUILDER, 'displayData' => $displayData, 'columns' => $columns, 'reportTotals' => $reportTotals, 'reportTypes' => $reportTypes, 'reportType' => $reportType, 'enableChart' => $enableChart, 'enableReport' => $enableReport, 'title' => trans('texts.charts_and_reports'), ]; return View::make('reports.chart_builder', $params); } private function export($data, $totals) { $output = fopen('php://output', 'w') or Utils::fatalError(); header('Content-Type:application/csv'); header('Content-Disposition:attachment;filename=ninja-report.csv'); Utils::exportData($output, $data); foreach (['amount', 'paid', 'balance'] as $type) { $csv = trans("texts.{$type}") . ','; foreach ($totals[$type] as $currencyId => $amount) { $csv .= Utils::formatMoney($amount, $currencyId) . ','; } fwrite($output, $csv . "\n"); } fclose($output); exit; } } <file_sep>/app/Models/AccountGateway.php <?php namespace App\Models; use App\Models\Gateway; use Illuminate\Database\Eloquent\SoftDeletes; class AccountGateway extends EntityModel { use SoftDeletes; protected $dates = ['deleted_at']; public function gateway() { return $this->belongsTo('App\Models\Gateway'); } public function getCreditcardTypes() { $flags = unserialize(CREDIT_CARDS); $arrayOfImages = []; foreach ($flags as $card => $name) { if (($this->accepted_credit_cards & $card) == $card) { $arrayOfImages[] = ['source' => asset($name['card']), 'alt' => $name['text']]; } } return $arrayOfImages; } public function getPaymentType() { return Gateway::getPaymentType($this->gateway_id); } public function isPaymentType($type) { return $this->getPaymentType() == $type; } public function isGateway($gatewayId) { return $this->gateway_id == $gatewayId; } } <file_sep>/app/Libraries/Utils.php <?php namespace App\Libraries; use Auth; use Cache; use DB; use App; use Schema; use Session; use Request; use View; use DateTimeZone; use Input; use Log; use DateTime; use stdClass; use Carbon; use App\Models\Currency; class Utils { public static function isRegistered() { return Auth::check() && Auth::user()->registered; } public static function isConfirmed() { return Auth::check() && Auth::user()->confirmed; } public static function isDatabaseSetup() { try { if (Schema::hasTable('accounts')) { return true; } } catch (\Exception $e) { return false; } } public static function isProd() { return App::environment() == ENV_PRODUCTION; } public static function isNinja() { return self::isNinjaProd() || self::isNinjaDev(); } public static function isNinjaProd() { return isset($_ENV['NINJA_PROD']) && $_ENV['NINJA_PROD'] == 'true'; } public static function isNinjaDev() { return isset($_ENV['NINJA_DEV']) && $_ENV['NINJA_DEV'] == 'true'; } public static function allowNewAccounts() { return Utils::isNinja() || Auth::check(); } public static function isPro() { return Auth::check() && Auth::user()->isPro(); } public static function isEnglish() { return App::getLocale() == 'en'; } public static function getUserType() { if (Utils::isNinja()) { return USER_TYPE_CLOUD_HOST; } else { return USER_TYPE_SELF_HOST; } } public static function getDemoAccountId() { return isset($_ENV[DEMO_ACCOUNT_ID]) ? $_ENV[DEMO_ACCOUNT_ID] : false; } public static function isDemo() { return Auth::check() && Auth::user()->isDemo(); } public static function getNewsFeedResponse($userType = false) { if (!$userType) { $userType = Utils::getUserType(); } $response = new stdClass(); $response->message = isset($_ENV["{$userType}_MESSAGE"]) ? $_ENV["{$userType}_MESSAGE"] : ''; $response->id = isset($_ENV["{$userType}_ID"]) ? $_ENV["{$userType}_ID"] : ''; $response->version = NINJA_VERSION; return $response; } public static function getProLabel($feature) { if (Auth::check() && !Auth::user()->isPro() && $feature == ACCOUNT_ADVANCED_SETTINGS) { return '&nbsp;<sup class="pro-label">PRO</sup>'; } else { return ''; } } public static function basePath() { return substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/') + 1); } public static function trans($input) { $data = []; foreach ($input as $field) { if ($field == "checkbox") { $data[] = $field; } else { $data[] = trans("texts.$field"); } } return $data; } public static function fatalError($message = false, $exception = false) { if (!$message) { $message = "An error occurred, please try again later."; } static::logError($message.' '.$exception); $data = [ 'showBreadcrumbs' => false, 'hideHeader' => true, ]; return View::make('error', $data)->with('error', $message); } public static function getErrorString($exception) { $class = get_class($exception); $code = method_exists($exception, 'getStatusCode') ? $exception->getStatusCode() : $exception->getCode(); return "***{$class}*** [{$code}] : {$exception->getFile()} [Line {$exception->getLine()}] => {$exception->getMessage()}"; } public static function logError($error, $context = 'PHP') { $count = Session::get('error_count', 0); Session::put('error_count', ++$count); if ($count > 100) { return 'logged'; } $data = [ 'context' => $context, 'user_id' => Auth::check() ? Auth::user()->id : 0, 'user_name' => Auth::check() ? Auth::user()->getDisplayName() : '', 'url' => Input::get('url', Request::url()), 'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '', 'ip' => Request::getClientIp(), 'count' => Session::get('error_count', 0), //'input' => Input::all() ]; Log::error($error."\n", $data); /* Mail::queue('emails.error', ['message'=>$error.' '.json_encode($data)], function($message) { $message->to($email)->subject($subject); }); */ } public static function parseFloat($value) { $value = preg_replace('/[^0-9\.\-]/', '', $value); return floatval($value); } public static function formatPhoneNumber($phoneNumber) { $phoneNumber = preg_replace('/[^0-9a-zA-Z]/', '', $phoneNumber); if (!$phoneNumber) { return ''; } if (strlen($phoneNumber) > 10) { $countryCode = substr($phoneNumber, 0, strlen($phoneNumber)-10); $areaCode = substr($phoneNumber, -10, 3); $nextThree = substr($phoneNumber, -7, 3); $lastFour = substr($phoneNumber, -4, 4); $phoneNumber = '+'.$countryCode.' ('.$areaCode.') '.$nextThree.'-'.$lastFour; } elseif (strlen($phoneNumber) == 10 && in_array(substr($phoneNumber, 0, 3), array(653, 656, 658, 659))) { /** * SG country code are 653, 656, 658, 659 * US area code consist of 650, 651 and 657 * @see http://en.wikipedia.org/wiki/Telephone_numbers_in_Singapore#Numbering_plan * @see http://www.bennetyee.org/ucsd-pages/area.html */ $countryCode = substr($phoneNumber, 0, 2); $nextFour = substr($phoneNumber, 2, 4); $lastFour = substr($phoneNumber, 6, 4); $phoneNumber = '+'.$countryCode.' '.$nextFour.' '.$lastFour; } elseif (strlen($phoneNumber) == 10) { $areaCode = substr($phoneNumber, 0, 3); $nextThree = substr($phoneNumber, 3, 3); $lastFour = substr($phoneNumber, 6, 4); $phoneNumber = '('.$areaCode.') '.$nextThree.'-'.$lastFour; } elseif (strlen($phoneNumber) == 7) { $nextThree = substr($phoneNumber, 0, 3); $lastFour = substr($phoneNumber, 3, 4); $phoneNumber = $nextThree.'-'.$lastFour; } return $phoneNumber; } public static function formatMoney($value, $currencyId = false) { if (!$currencyId) { $currencyId = Session::get(SESSION_CURRENCY, DEFAULT_CURRENCY); } foreach (Cache::get('currencies') as $currency) { if ($currency->id == $currencyId) { break; } } if (!$currency) { $currency = Currency::find(1); } if (!$value) { $value = 0; } Cache::add('currency', $currency, DEFAULT_QUERY_CACHE); return $currency->symbol.number_format($value, $currency->precision, $currency->decimal_separator, $currency->thousand_separator); } public static function pluralize($string, $count) { $field = $count == 1 ? $string : $string.'s'; $string = trans("texts.$field", ['count' => $count]); return $string; } public static function toArray($data) { return json_decode(json_encode((array) $data), true); } public static function toSpaceCase($camelStr) { return preg_replace('/([a-z])([A-Z])/s', '$1 $2', $camelStr); } public static function timestampToDateTimeString($timestamp) { $timezone = Session::get(SESSION_TIMEZONE, DEFAULT_TIMEZONE); $format = Session::get(SESSION_DATETIME_FORMAT, DEFAULT_DATETIME_FORMAT); return Utils::timestampToString($timestamp, $timezone, $format); } public static function timestampToDateString($timestamp) { $timezone = Session::get(SESSION_TIMEZONE, DEFAULT_TIMEZONE); $format = Session::get(SESSION_DATE_FORMAT, DEFAULT_DATE_FORMAT); return Utils::timestampToString($timestamp, $timezone, $format); } public static function dateToString($date) { $dateTime = new DateTime($date); $timestamp = $dateTime->getTimestamp(); $format = Session::get(SESSION_DATE_FORMAT, DEFAULT_DATE_FORMAT); return Utils::timestampToString($timestamp, false, $format); } public static function timestampToString($timestamp, $timezone = false, $format) { if (!$timestamp) { return ''; } $date = Carbon::createFromTimeStamp($timestamp); if ($timezone) { $date->tz = $timezone; } if ($date->year < 1900) { return ''; } return $date->format($format); } public static function getTiemstampOffset() { $timezone = new DateTimeZone(Session::get(SESSION_TIMEZONE, DEFAULT_TIMEZONE)); $datetime = new DateTime('now', $timezone); $offset = $timezone->getOffset($datetime); $minutes = $offset / 60; return $minutes; } public static function toSqlDate($date, $formatResult = true) { if (!$date) { return; } //$timezone = Session::get(SESSION_TIMEZONE, DEFAULT_TIMEZONE); $format = Session::get(SESSION_DATE_FORMAT, DEFAULT_DATE_FORMAT); //$dateTime = DateTime::createFromFormat($format, $date, new DateTimeZone($timezone)); $dateTime = DateTime::createFromFormat($format, $date); return $formatResult ? $dateTime->format('Y-m-d') : $dateTime; } public static function fromSqlDate($date, $formatResult = true) { if (!$date || $date == '0000-00-00') { return ''; } //$timezone = Session::get(SESSION_TIMEZONE, DEFAULT_TIMEZONE); $format = Session::get(SESSION_DATE_FORMAT, DEFAULT_DATE_FORMAT); $dateTime = DateTime::createFromFormat('Y-m-d', $date); //$dateTime->setTimeZone(new DateTimeZone($timezone)); return $formatResult ? $dateTime->format($format) : $dateTime; } public static function fromSqlDateTime($date, $formatResult = true) { if (!$date || $date == '0000-00-00 00:00:00') { return ''; } $timezone = Session::get(SESSION_TIMEZONE, DEFAULT_TIMEZONE); $format = Session::get(SESSION_DATETIME_FORMAT, DEFAULT_DATETIME_FORMAT); $dateTime = DateTime::createFromFormat('Y-m-d H:i:s', $date); $dateTime->setTimeZone(new DateTimeZone($timezone)); return $formatResult ? $dateTime->format($format) : $dateTime; } public static function today($formatResult = true) { $timezone = Session::get(SESSION_TIMEZONE, DEFAULT_TIMEZONE); $format = Session::get(SESSION_DATE_FORMAT, DEFAULT_DATE_FORMAT); $date = date_create(null, new DateTimeZone($timezone)); if ($formatResult) { return $date->format($format); } else { return $date; } } public static function trackViewed($name, $type, $url = false) { if (!$url) { $url = Request::url(); } $viewed = Session::get(RECENTLY_VIEWED); if (!$viewed) { $viewed = []; } $object = new stdClass(); $object->accountId = Auth::user()->account_id; $object->url = $url; $object->name = ucwords($type).': '.$name; $data = []; $counts = []; for ($i = 0; $i<count($viewed); $i++) { $item = $viewed[$i]; if ($object->url == $item->url || $object->name == $item->name) { continue; } // temporary fix to check for new property in session if (!property_exists($item, 'accountId')) { continue; } array_unshift($data, $item); if (isset($counts[$item->accountId])) { $counts[$item->accountId]++; } else { $counts[$item->accountId] = 1; } } array_unshift($data, $object); if (isset($counts[Auth::user()->account_id]) && $counts[Auth::user()->account_id] > RECENTLY_VIEWED_LIMIT) { array_pop($data); } Session::put(RECENTLY_VIEWED, $data); } public static function processVariables($str) { if (!$str) { return ''; } $variables = ['MONTH', 'QUARTER', 'YEAR']; for ($i = 0; $i<count($variables); $i++) { $variable = $variables[$i]; $regExp = '/:'.$variable.'[+-]?[\d]*/'; preg_match_all($regExp, $str, $matches); $matches = $matches[0]; if (count($matches) == 0) { continue; } usort($matches, function($a, $b) { return strlen($b) - strlen($a); }); foreach ($matches as $match) { $offset = 0; $addArray = explode('+', $match); $minArray = explode('-', $match); if (count($addArray) > 1) { $offset = intval($addArray[1]); } elseif (count($minArray) > 1) { $offset = intval($minArray[1]) * -1; } $val = Utils::getDatePart($variable, $offset); $str = str_replace($match, $val, $str); } } return $str; } private static function getDatePart($part, $offset) { $offset = intval($offset); if ($part == 'MONTH') { return Utils::getMonth($offset); } elseif ($part == 'QUARTER') { return Utils::getQuarter($offset); } elseif ($part == 'YEAR') { return Utils::getYear($offset); } } private static function getMonth($offset) { $months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; $month = intval(date('n')) - 1; $month += $offset; $month = $month % 12; if ($month < 0) { $month += 12; } return $months[$month]; } private static function getQuarter($offset) { $month = intval(date('n')) - 1; $quarter = floor(($month + 3) / 3); $quarter += $offset; $quarter = $quarter % 4; if ($quarter == 0) { $quarter = 4; } return 'Q'.$quarter; } private static function getYear($offset) { $year = intval(date('Y')); return $year + $offset; } public static function getEntityName($entityType) { return ucwords(str_replace('_', ' ', $entityType)); } public static function getClientDisplayName($model) { if ($model->client_name) { return $model->client_name; } elseif ($model->first_name || $model->last_name) { return $model->first_name.' '.$model->last_name; } else { return $model->email; } } public static function encodeActivity($person = null, $action, $entity = null, $otherPerson = null) { $person = $person ? $person->getDisplayName() : '<i>System</i>'; $entity = $entity ? $entity->getActivityKey() : ''; $otherPerson = $otherPerson ? 'to '.$otherPerson->getDisplayName() : ''; $token = Session::get('token_id') ? ' ('.trans('texts.token').')' : ''; return trim("$person $token $action $entity $otherPerson"); } public static function decodeActivity($message) { $pattern = '/\[([\w]*):([\d]*):(.*)\]/i'; preg_match($pattern, $message, $matches); if (count($matches) > 0) { $match = $matches[0]; $type = $matches[1]; $publicId = $matches[2]; $name = $matches[3]; $link = link_to($type.'s/'.$publicId, $name); $message = str_replace($match, "$type $link", $message); } return $message; } public static function generateLicense() { $parts = []; for ($i = 0; $i<5; $i++) { $parts[] = strtoupper(str_random(4)); } return implode('-', $parts); } public static function lookupEventId($eventName) { if ($eventName == 'create_client') { return EVENT_CREATE_CLIENT; } elseif ($eventName == 'create_invoice') { return EVENT_CREATE_INVOICE; } elseif ($eventName == 'create_quote') { return EVENT_CREATE_QUOTE; } elseif ($eventName == 'create_payment') { return EVENT_CREATE_PAYMENT; } else { return false; } } public static function notifyZapier($subscription, $data) { $curl = curl_init(); $jsonEncodedData = json_encode($data->toPublicArray()); $opts = [ CURLOPT_URL => $subscription->target_url, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $jsonEncodedData, CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Content-Length: '.strlen($jsonEncodedData)], ]; curl_setopt_array($curl, $opts); $result = curl_exec($curl); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($status == 410) { $subscription->delete(); } } public static function remapPublicIds($items) { $return = []; foreach ($items as $item) { $return[] = $item->toPublicArray(); } return $return; } public static function hideIds($data) { $publicId = null; foreach ($data as $key => $val) { if (is_array($val)) { $data[$key] = Utils::hideIds($val); } else if ($key == 'id' || strpos($key, '_id')) { if ($key == 'public_id') { $publicId = $val; } unset($data[$key]); } } if ($publicId) { $data['id'] = $publicId; } return $data; } public static function getApiHeaders($count = 0) { return [ 'Content-Type' => 'application/json', //'Access-Control-Allow-Origin' => '*', //'Access-Control-Allow-Methods' => 'GET', //'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Requested-With', //'Access-Control-Allow-Credentials' => 'true', 'X-Total-Count' => $count, //'X-Rate-Limit-Limit' - The number of allowed requests in the current period //'X-Rate-Limit-Remaining' - The number of remaining requests in the current period //'X-Rate-Limit-Reset' - The number of seconds left in the current period, ]; } public static function startsWith($haystack, $needle) { return $needle === "" || strpos($haystack, $needle) === 0; } public static function endsWith($haystack, $needle) { return $needle === "" || substr($haystack, -strlen($needle)) === $needle; } public static function getEntityRowClass($model) { $str = $model->is_deleted || ($model->deleted_at && $model->deleted_at != '0000-00-00') ? 'DISABLED ' : ''; if ($model->is_deleted) { $str .= 'ENTITY_DELETED '; } if ($model->deleted_at && $model->deleted_at != '0000-00-00') { $str .= 'ENTITY_ARCHIVED '; } return $str; } public static function exportData($output, $data) { if (count($data) > 0) { fputcsv($output, array_keys($data[0])); } foreach ($data as $record) { fputcsv($output, $record); } fwrite($output, "\n"); } public static function stringToObjectResolution($baseObject, $rawPath) { $val = ''; if (!is_object($baseObject)) { return $val; } $path = preg_split('/->/', $rawPath); $node = $baseObject; while (($prop = array_shift($path)) !== null) { if (property_exists($node, $prop)) { $val = $node->$prop; $node = $node->$prop; } else if (is_object($node) && isset($node->$prop)) { $node = $node->{$prop}; } else if ( method_exists($node, $prop)) { $val = call_user_func(array($node, $prop)); } } return $val; } public static function getFirst($values) { if (is_array($values)) { return count($values) ? $values[0] : false; } else { return $values; } } } <file_sep>/app/Http/Controllers/QuoteController.php <?php namespace App\Http\Controllers; use Auth; use Input; use Redirect; use Utils; use View; use Cache; use Event; use Session; use App\Models\Account; use App\Models\Client; use App\Models\Country; use App\Models\Currency; use App\Models\Industry; use App\Models\InvoiceDesign; use App\Models\PaymentTerm; use App\Models\Product; use App\Models\Size; use App\Models\TaxRate; use App\Models\Invitation; use App\Models\Activity; use App\Models\Invoice; use App\Ninja\Mailers\ContactMailer as Mailer; use App\Ninja\Repositories\InvoiceRepository; use App\Ninja\Repositories\ClientRepository; use App\Ninja\Repositories\TaxRateRepository; use App\Events\QuoteApproved; class QuoteController extends BaseController { protected $mailer; protected $invoiceRepo; protected $clientRepo; protected $taxRateRepo; public function __construct(Mailer $mailer, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, TaxRateRepository $taxRateRepo) { parent::__construct(); $this->mailer = $mailer; $this->invoiceRepo = $invoiceRepo; $this->clientRepo = $clientRepo; $this->taxRateRepo = $taxRateRepo; } public function index() { if (!Utils::isPro()) { return Redirect::to('/invoices/create'); } $data = [ 'title' => trans('texts.quotes'), 'entityType' => ENTITY_QUOTE, 'columns' => Utils::trans(['checkbox', 'quote_number', 'client', 'quote_date', 'quote_total', 'due_date', 'status', 'action']), ]; /* if (Invoice::scope()->where('is_recurring', '=', true)->count() > 0) { $data['secEntityType'] = ENTITY_RECURRING_INVOICE; $data['secColumns'] = Utils::trans(['checkbox', 'frequency', 'client', 'start_date', 'end_date', 'quote_total', 'action']); } */ return View::make('list', $data); } public function clientIndex() { $invitationKey = Session::get('invitation_key'); if (!$invitationKey) { return Redirect::to('/setup'); } $invitation = Invitation::with('account')->where('invitation_key', '=', $invitationKey)->first(); $account = $invitation->account; $color = $account->primary_color ? $account->primary_color : '#0b4d78'; $data = [ 'color' => $color, 'hideLogo' => $account->isWhiteLabel(), 'title' => trans('texts.quotes'), 'entityType' => ENTITY_QUOTE, 'columns' => Utils::trans(['quote_number', 'quote_date', 'quote_total', 'due_date']), ]; return View::make('public_list', $data); } public function getDatatable($clientPublicId = null) { $accountId = Auth::user()->account_id; $search = Input::get('sSearch'); return $this->invoiceRepo->getDatatable($accountId, $clientPublicId, ENTITY_QUOTE, $search); } public function getClientDatatable() { $search = Input::get('sSearch'); $invitationKey = Session::get('invitation_key'); $invitation = Invitation::where('invitation_key', '=', $invitationKey)->first(); if (!$invitation || $invitation->is_deleted) { return []; } $invoice = $invitation->invoice; if (!$invoice || $invoice->is_deleted) { return []; } return $this->invoiceRepo->getClientDatatable($invitation->contact_id, ENTITY_QUOTE, $search); } public function create($clientPublicId = 0) { if (!Utils::isPro()) { return Redirect::to('/invoices/create'); } $client = null; $invoiceNumber = Auth::user()->account->getNextInvoiceNumber(true); $account = Account::with('country')->findOrFail(Auth::user()->account_id); if ($clientPublicId) { $client = Client::scope($clientPublicId)->firstOrFail(); } $data = array( 'account' => $account, 'invoice' => null, 'data' => Input::old('data'), 'invoiceNumber' => $invoiceNumber, 'method' => 'POST', 'url' => 'invoices', 'title' => trans('texts.new_quote'), 'client' => $client, ); $data = array_merge($data, self::getViewModel()); return View::make('invoices.edit', $data); } private static function getViewModel() { return [ 'entityType' => ENTITY_QUOTE, 'account' => Auth::user()->account, 'products' => Product::scope()->orderBy('id')->get(array('product_key', 'notes', 'cost', 'qty')), 'countries' => Cache::get('countries'), 'clients' => Client::scope()->with('contacts', 'country')->orderBy('name')->get(), 'taxRates' => TaxRate::scope()->orderBy('name')->get(), 'currencies' => Cache::get('currencies'), 'sizes' => Cache::get('sizes'), 'paymentTerms' => Cache::get('paymentTerms'), 'industries' => Cache::get('industries'), 'invoiceDesigns' => InvoiceDesign::getDesigns(), 'invoiceLabels' => Auth::user()->account->getInvoiceLabels(), 'isRecurring' => false, ]; } public function bulk() { $action = Input::get('action'); if ($action == 'convert') { $invoice = Invoice::with('invoice_items')->scope(Input::get('id'))->firstOrFail(); $clone = $this->invoiceRepo->cloneInvoice($invoice, $invoice->id); Session::flash('message', trans('texts.converted_to_invoice')); return Redirect::to('invoices/'.$clone->public_id); } $statusId = Input::get('statusId'); $ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $count = $this->invoiceRepo->bulk($ids, $action, $statusId); if ($count > 0) { $key = $action == 'mark' ? "updated_quote" : "{$action}d_quote"; $message = Utils::pluralize($key, $count); Session::flash('message', $message); } if ($action == 'restore' && $count == 1) { return Redirect::to("quotes/".Utils::getFirst($ids)); } else { return Redirect::to("quotes"); } } public function approve($invitationKey) { $invitation = Invitation::with('invoice.invoice_items', 'invoice.invitations')->where('invitation_key', '=', $invitationKey)->firstOrFail(); $invoice = $invitation->invoice; if ($invoice->is_quote && !$invoice->quote_invoice_id) { Event::fire(new QuoteApproved($invoice)); Activity::approveQuote($invitation); $invoice = $this->invoiceRepo->cloneInvoice($invoice, $invoice->id); Session::flash('message', trans('texts.converted_to_invoice')); foreach ($invoice->invitations as $invitationClone) { if ($invitation->contact_id == $invitationClone->contact_id) { $invitationKey = $invitationClone->invitation_key; } } } return Redirect::to("view/{$invitationKey}"); } } <file_sep>/app/Models/Country.php <?php namespace App\Models; use Eloquent; class Country extends Eloquent { public $timestamps = false; protected $visible = ['id', 'name']; public function getName() { return $this->name; } } <file_sep>/app/Models/AccountToken.php <?php namespace App\Models; use Illuminate\Database\Eloquent\SoftDeletes; class AccountToken extends EntityModel { use SoftDeletes; protected $dates = ['deleted_at']; public function account() { return $this->belongsTo('App\Models\Account'); } } <file_sep>/.env.example APP_ENV=production APP_DEBUG=false APP_URL=http://ninja.dev APP_CIPHER=rijndael-128 APP_KEY=SomeRandomString APP_TIMEZONE DB_TYPE=mysql DB_HOST=localhost DB_DATABASE=ninja DB_USERNAME DB_PASSWORD MAIL_DRIVER=smtp MAIL_PORT=587 MAIL_ENCRYPTION=tls MAIL_HOST MAIL_USERNAME MAIL_FROM_ADDRESS MAIL_FROM_NAME MAIL_PASSWORD <file_sep>/app/Models/User.php <?php namespace App\Models; use Session; use Auth; use Event; use App\Libraries\Utils; use App\Events\UserSettingsChanged; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; use Illuminate\Database\Eloquent\SoftDeletes; class User extends Model implements AuthenticatableContract, CanResetPasswordContract { use Authenticatable, CanResetPassword; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'password']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password', 'remember_token']; use SoftDeletes; protected $dates = ['deleted_at']; public function account() { return $this->belongsTo('App\Models\Account'); } public function theme() { return $this->belongsTo('App\Models\Theme'); } public function getName() { return $this->getDisplayName(); } public function getPersonType() { return PERSON_USER; } /** * Get the unique identifier for the user. * * @return mixed */ public function getAuthIdentifier() { return $this->getKey(); } /** * Get the password for the user. * * @return string */ public function getAuthPassword() { return $this->password; } /** * Get the e-mail address where password reminders are sent. * * @return string */ public function getReminderEmail() { return $this->email; } public function isPro() { return $this->account->isPro(); } public function isDemo() { return $this->account->id == Utils::getDemoAccountId(); } public function maxInvoiceDesignId() { return $this->isPro() ? 11 : (Utils::isNinja() ? COUNT_FREE_DESIGNS : COUNT_FREE_DESIGNS_SELF_HOST); } public function getDisplayName() { if ($this->getFullName()) { return $this->getFullName(); } elseif ($this->email) { return $this->email; } else { return 'Guest'; } } public function getFullName() { if ($this->first_name || $this->last_name) { return $this->first_name.' '.$this->last_name; } else { return ''; } } public function showGreyBackground() { return !$this->theme_id || in_array($this->theme_id, [2, 3, 5, 6, 7, 8, 10, 11, 12]); } public function getRequestsCount() { return Session::get(SESSION_COUNTER, 0); } /* public function getPopOverText() { if (!Utils::isNinja() || !Auth::check() || Session::has('error')) { return false; } $count = self::getRequestsCount(); if ($count == 1 || $count % 5 == 0) { if (!Utils::isRegistered()) { return trans('texts.sign_up_to_save'); } elseif (!Auth::user()->account->name) { return trans('texts.set_name'); } } return false; } */ public function afterSave($success = true, $forced = false) { if ($this->email) { return parent::afterSave($success = true, $forced = false); } else { return true; } } public function getMaxNumClients() { return $this->isPro() ? MAX_NUM_CLIENTS_PRO : MAX_NUM_CLIENTS; } public function getRememberToken() { return $this->remember_token; } public function setRememberToken($value) { $this->remember_token = $value; } public function getRememberTokenName() { return 'remember_token'; } public function clearSession() { $keys = [ RECENTLY_VIEWED, SESSION_USER_ACCOUNTS, SESSION_TIMEZONE, SESSION_DATE_FORMAT, SESSION_DATE_PICKER_FORMAT, SESSION_DATETIME_FORMAT, SESSION_CURRENCY, SESSION_LOCALE, ]; foreach ($keys as $key) { Session::forget($key); } } public static function updateUser($user) { if ($user->password != !$user->getOriginal('password')) { $user->failed_logins = 0; } } } User::updating(function ($user) { User::updateUser($user); }); User::updated(function ($user) { Event::fire(new UserSettingsChanged()); }); <file_sep>/app/Http/Controllers/ClientApiController.php <?php namespace App\Http\Controllers; use Utils; use Response; use Input; use App\Models\Client; use App\Ninja\Repositories\ClientRepository; class ClientApiController extends Controller { protected $clientRepo; public function __construct(ClientRepository $clientRepo) { $this->clientRepo = $clientRepo; } public function ping() { $headers = Utils::getApiHeaders(); return Response::make('', 200, $headers); } public function index() { $clients = Client::scope() ->with('country', 'contacts', 'industry', 'size', 'currency') ->orderBy('created_at', 'desc') ->get(); $clients = Utils::remapPublicIds($clients); $response = json_encode($clients, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(count($clients)); return Response::make($response, 200, $headers); } public function store() { $data = Input::all(); $error = $this->clientRepo->getErrors($data); if ($error) { $headers = Utils::getApiHeaders(); return Response::make($error, 500, $headers); } else { $client = $this->clientRepo->save(isset($data['id']) ? $data['id'] : false, $data, false); $client = Client::scope($client->public_id)->with('country', 'contacts', 'industry', 'size', 'currency')->first(); $client = Utils::remapPublicIds([$client]); $response = json_encode($client, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(); return Response::make($response, 200, $headers); } } } <file_sep>/app/Http/Controllers/InvoiceApiController.php <?php namespace App\Http\Controllers; use Auth; use Utils; use Response; use Input; use App\Models\Invoice; use App\Models\Client; use App\Models\Contact; use App\Models\Product; use App\Models\Invitation; use App\Ninja\Repositories\ClientRepository; use App\Ninja\Repositories\InvoiceRepository; use App\Ninja\Mailers\ContactMailer as Mailer; class InvoiceApiController extends Controller { protected $invoiceRepo; public function __construct(InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, Mailer $mailer) { $this->invoiceRepo = $invoiceRepo; $this->clientRepo = $clientRepo; $this->mailer = $mailer; } public function index() { $invoices = Invoice::scope() ->with('client', 'invitations.account') ->where('invoices.is_quote', '=', false) ->orderBy('created_at', 'desc') ->get(); // Add the first invitation link to the data foreach ($invoices as $key => $invoice) { foreach ($invoice->invitations as $subKey => $invitation) { $invoices[$key]['link'] = $invitation->getLink(); } unset($invoice['invitations']); } $invoices = Utils::remapPublicIds($invoices); $response = json_encode($invoices, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(count($invoices)); return Response::make($response, 200, $headers); } public function store() { $data = Input::all(); $error = null; // check if the invoice number is set and unique if (!isset($data['invoice_number']) && !isset($data['id'])) { $data['invoice_number'] = Auth::user()->account->getNextInvoiceNumber(); } else if (isset($data['invoice_number'])) { $invoice = Invoice::scope()->where('invoice_number', '=', $data['invoice_number'])->first(); if ($invoice) { $error = trans('validation.unique', ['attribute' => 'texts.invoice_number']); } else { $data['id'] = $invoice->public_id; } } if (isset($data['email'])) { $client = Client::scope()->whereHas('contacts', function($query) use ($data) { $query->where('email', '=', $data['email']); })->first(); if (!$client) { $clientData = ['contact' => ['email' => $data['email']]]; foreach (['name', 'private_notes'] as $field) { if (isset($data[$field])) { $clientData[$field] = $data[$field]; } } foreach (['first_name', 'last_name'] as $field) { if (isset($data[$field])) { $clientData[$field] = $data[$field]; } } $error = $this->clientRepo->getErrors($clientData); if (!$error) { $client = $this->clientRepo->save(false, $clientData, false); } } } else if (isset($data['client_id'])) { $client = Client::scope($data['client_id'])->first(); } if (!$error) { if (!isset($data['client_id']) && !isset($data['email'])) { $error = trans('validation.', ['attribute' => 'client_id or email']); } else if (!$client) { $error = trans('validation.not_in', ['attribute' => 'client_id']); } } if ($error) { $response = json_encode($error, JSON_PRETTY_PRINT); } else { $data = self::prepareData($data); $data['client_id'] = $client->id; $invoice = $this->invoiceRepo->save(false, $data, false); if (!isset($data['id'])) { $invitation = Invitation::createNew(); $invitation->invoice_id = $invoice->id; $invitation->contact_id = $client->contacts[0]->id; $invitation->invitation_key = str_random(RANDOM_KEY_LENGTH); $invitation->save(); } if (isset($data['email_invoice']) && $data['email_invoice']) { $this->mailer->sendInvoice($invoice); } // prepare the return data $invoice = Invoice::scope($invoice->public_id)->with('client', 'invoice_items', 'invitations')->first(); $invoice = Utils::remapPublicIds([$invoice]); $response = json_encode($invoice, JSON_PRETTY_PRINT); } $headers = Utils::getApiHeaders(); return Response::make($response, $error ? 400 : 200, $headers); } private function prepareData($data) { $account = Auth::user()->account; $account->loadLocalizationSettings(); // set defaults for optional fields $fields = [ 'discount' => 0, 'is_amount_discount' => false, 'terms' => '', 'invoice_footer' => '', 'public_notes' => '', 'po_number' => '', 'invoice_design_id' => $account->invoice_design_id, 'invoice_items' => [], 'custom_value1' => 0, 'custom_value2' => 0, 'custom_taxes1' => false, 'custom_taxes2' => false, 'partial' => 0 ]; if (!isset($data['invoice_date'])) { $fields['invoice_date_sql'] = date_create()->format('Y-m-d'); } if (!isset($data['due_date'])) { $fields['due_date_sql'] = false; } foreach ($fields as $key => $val) { if (!isset($data[$key])) { $data[$key] = $val; } } // hardcode some fields $fields = [ 'is_recurring' => false ]; foreach ($fields as $key => $val) { $data[$key] = $val; } // initialize the line items if (isset($data['product_key']) || isset($data['cost']) || isset($data['notes']) || isset($data['qty'])) { $data['invoice_items'] = [self::prepareItem($data)]; } else { foreach ($data['invoice_items'] as $index => $item) { $data['invoice_items'][$index] = self::prepareItem($item); } } return $data; } private function prepareItem($item) { $fields = [ 'cost' => 0, 'product_key' => '', 'notes' => '', 'qty' => 1 ]; foreach ($fields as $key => $val) { if (!isset($item[$key])) { $item[$key] = $val; } } // if only the product key is set we'll load the cost and notes if ($item['product_key'] && (!$item['cost'] || !$item['notes'])) { $product = Product::findProductByKey($item['product_key']); if ($product) { if (!$item['cost']) { $item['cost'] = $product->cost; } if (!$item['notes']) { $item['notes'] = $product->notes; } } } return $item; } public function emailInvoice() { $data = Input::all(); $error = null; if (!isset($data['id'])) { $error = trans('validation.required', ['attribute' => 'id']); } else { $invoice = Invoice::scope($data['id'])->first(); if (!$invoice) { $error = trans('validation.not_in', ['attribute' => 'id']); } else { $this->mailer->sendInvoice($invoice); } } if ($error) { $response = json_encode($error, JSON_PRETTY_PRINT); } else { $response = json_encode(RESULT_SUCCESS, JSON_PRETTY_PRINT); } $headers = Utils::getApiHeaders(); return Response::make($response, $error ? 400 : 200, $headers); } } <file_sep>/app/Ninja/Mailers/Mailer.php <?php namespace App\Ninja\Mailers; use Exception; use Mail; use Utils; use App\Models\Invoice; class Mailer { public function sendTo($toEmail, $fromEmail, $fromName, $subject, $view, $data = []) { $views = [ 'emails.'.$view.'_html', 'emails.'.$view.'_text', ]; try { Mail::send($views, $data, function ($message) use ($toEmail, $fromEmail, $fromName, $subject, $data) { $toEmail = strtolower($toEmail); $replyEmail = $fromEmail; $fromEmail = CONTACT_EMAIL; if (isset($data['invoice_id'])) { $invoice = Invoice::with('account')->where('id', '=', $data['invoice_id'])->get()->first(); if($invoice->account->pdf_email_attachment && file_exists($invoice->getPDFPath())) { $message->attach( $invoice->getPDFPath(), array('as' => $invoice->getFileName(), 'mime' => 'application/pdf') ); } } $message->to($toEmail) ->from($fromEmail, $fromName) ->replyTo($replyEmail, $fromName) ->subject($subject); }); return true; } catch (Exception $exception) { if (isset($_ENV['POSTMARK_API_TOKEN'])) { $response = $exception->getResponse()->getBody()->getContents(); $response = json_decode($response); return nl2br($response->Message); } else { return $exception->getMessage(); } } } } <file_sep>/app/Ninja/Mailers/UserMailer.php <?php namespace App\Ninja\Mailers; use Utils; use App\Models\Invoice; use App\Models\Payment; use App\Models\User; class UserMailer extends Mailer { public function sendConfirmation(User $user, User $invitor = null) { if (!$user->email) { return; } $view = 'confirm'; $subject = trans('texts.confirmation_subject'); $data = [ 'user' => $user, 'invitationMessage' => $invitor ? trans('texts.invitation_message', ['invitor' => $invitor->getDisplayName()]) : '', ]; if ($invitor) { $fromEmail = $invitor->email; $fromName = $invitor->getDisplayName(); } else { $fromEmail = CONTACT_EMAIL; $fromName = CONTACT_NAME; } $this->sendTo($user->email, $fromEmail, $fromName, $subject, $view, $data); } public function sendNotification(User $user, Invoice $invoice, $notificationType, Payment $payment = null) { if (!$user->email) { return; } $entityType = $notificationType == 'approved' ? ENTITY_QUOTE : ENTITY_INVOICE; $view = "{$entityType}_{$notificationType}"; $data = [ 'entityType' => $entityType, 'clientName' => $invoice->client->getDisplayName(), 'accountName' => $invoice->account->getDisplayName(), 'userName' => $user->getDisplayName(), 'invoiceAmount' => Utils::formatMoney($invoice->getRequestedAmount(), $invoice->client->getCurrencyId()), 'invoiceNumber' => $invoice->invoice_number, 'invoiceLink' => SITE_URL."/{$entityType}s/{$invoice->public_id}", ]; if ($payment) { $data['paymentAmount'] = Utils::formatMoney($payment->amount, $invoice->client->getCurrencyId()); } $subject = trans("texts.notification_{$entityType}_{$notificationType}_subject", ['invoice' => $invoice->invoice_number, 'client' => $invoice->client->getDisplayName()]); $this->sendTo($user->email, CONTACT_EMAIL, CONTACT_NAME, $subject, $view, $data); } } <file_sep>/app/Http/Controllers/DashboardController.php <?php namespace App\Http\Controllers; use Auth; use DB; use View; use App\Models\Activity; use App\Models\Invoice; use App\Models\Payment; class DashboardController extends BaseController { public function index() { // total_income, billed_clients, invoice_sent and active_clients $select = DB::raw('COUNT(DISTINCT CASE WHEN invoices.id IS NOT NULL THEN clients.id ELSE null END) billed_clients, SUM(CASE WHEN invoices.invoice_status_id >= '.INVOICE_STATUS_SENT.' THEN 1 ELSE 0 END) invoices_sent, COUNT(DISTINCT clients.id) active_clients'); $metrics = DB::table('accounts') ->select($select) ->leftJoin('clients', 'accounts.id', '=', 'clients.account_id') ->leftJoin('invoices', 'clients.id', '=', 'invoices.client_id') ->where('accounts.id', '=', Auth::user()->account_id) ->where('clients.is_deleted', '=', false) ->where('invoices.is_deleted', '=', false) ->where('invoices.is_recurring', '=', false) ->where('invoices.is_quote', '=', false) ->groupBy('accounts.id') ->first(); $select = DB::raw('SUM(clients.paid_to_date) as value, clients.currency_id as currency_id'); $paidToDate = DB::table('accounts') ->select($select) ->leftJoin('clients', 'accounts.id', '=', 'clients.account_id') ->where('accounts.id', '=', Auth::user()->account_id) ->where('clients.is_deleted', '=', false) ->groupBy('accounts.id') ->groupBy(DB::raw('CASE WHEN clients.currency_id IS NULL THEN CASE WHEN accounts.currency_id IS NULL THEN 1 ELSE accounts.currency_id END ELSE clients.currency_id END')) ->get(); $select = DB::raw('AVG(invoices.amount) as invoice_avg, clients.currency_id as currency_id'); $averageInvoice = DB::table('accounts') ->select($select) ->leftJoin('clients', 'accounts.id', '=', 'clients.account_id') ->leftJoin('invoices', 'clients.id', '=', 'invoices.client_id') ->where('accounts.id', '=', Auth::user()->account_id) ->where('clients.is_deleted', '=', false) ->where('invoices.is_deleted', '=', false) ->where('invoices.is_quote', '=', false) ->where('invoices.is_recurring', '=', false) ->groupBy('accounts.id') ->groupBy(DB::raw('CASE WHEN clients.currency_id IS NULL THEN CASE WHEN accounts.currency_id IS NULL THEN 1 ELSE accounts.currency_id END ELSE clients.currency_id END')) ->get(); $select = DB::raw('SUM(clients.balance) as value, clients.currency_id as currency_id'); $balances = DB::table('accounts') ->select($select) ->leftJoin('clients', 'accounts.id', '=', 'clients.account_id') ->where('accounts.id', '=', Auth::user()->account_id) ->where('clients.is_deleted', '=', false) ->groupBy('accounts.id') ->groupBy(DB::raw('CASE WHEN clients.currency_id IS NULL THEN CASE WHEN accounts.currency_id IS NULL THEN 1 ELSE accounts.currency_id END ELSE clients.currency_id END')) ->get(); $activities = Activity::where('activities.account_id', '=', Auth::user()->account_id) ->where('activity_type_id', '>', 0) ->orderBy('created_at', 'desc') ->take(50) ->get(); $pastDue = DB::table('invoices') ->leftJoin('clients', 'clients.id', '=', 'invoices.client_id') ->leftJoin('contacts', 'contacts.client_id', '=', 'clients.id') ->where('invoices.account_id', '=', Auth::user()->account_id) ->where('clients.deleted_at', '=', null) ->where('contacts.deleted_at', '=', null) ->where('invoices.is_recurring', '=', false) ->where('invoices.is_quote', '=', false) ->where('invoices.balance', '>', 0) ->where('invoices.is_deleted', '=', false) ->where('contacts.is_primary', '=', true) ->where('invoices.due_date', '<', date('Y-m-d')) ->select(['invoices.due_date', 'invoices.balance', 'invoices.public_id', 'invoices.invoice_number', 'clients.name as client_name', 'contacts.email', 'contacts.first_name', 'contacts.last_name', 'clients.currency_id', 'clients.public_id as client_public_id']) ->orderBy('invoices.due_date', 'asc') ->take(50) ->get(); $upcoming = DB::table('invoices') ->leftJoin('clients', 'clients.id', '=', 'invoices.client_id') ->leftJoin('contacts', 'contacts.client_id', '=', 'clients.id') ->where('invoices.account_id', '=', Auth::user()->account_id) ->where('clients.deleted_at', '=', null) ->where('contacts.deleted_at', '=', null) ->where('invoices.is_recurring', '=', false) ->where('invoices.is_quote', '=', false) ->where('invoices.balance', '>', 0) ->where('invoices.is_deleted', '=', false) ->where('contacts.is_primary', '=', true) ->where('invoices.due_date', '>=', date('Y-m-d')) ->orderBy('invoices.due_date', 'asc') ->take(50) ->select(['invoices.due_date', 'invoices.balance', 'invoices.public_id', 'invoices.invoice_number', 'clients.name as client_name', 'contacts.email', 'contacts.first_name', 'contacts.last_name', 'clients.currency_id', 'clients.public_id as client_public_id']) ->get(); $payments = DB::table('payments') ->leftJoin('clients', 'clients.id', '=', 'payments.client_id') ->leftJoin('contacts', 'contacts.client_id', '=', 'clients.id') ->leftJoin('invoices', 'invoices.id', '=', 'payments.invoice_id') ->where('payments.account_id', '=', Auth::user()->account_id) ->where('clients.deleted_at', '=', null) ->where('contacts.deleted_at', '=', null) ->where('contacts.is_primary', '=', true) ->select(['payments.payment_date', 'payments.amount', 'invoices.public_id', 'invoices.invoice_number', 'clients.name as client_name', 'contacts.email', 'contacts.first_name', 'contacts.last_name', 'clients.currency_id', 'clients.public_id as client_public_id']) ->orderBy('payments.id', 'desc') ->take(50) ->get(); $data = [ 'account' => Auth::user()->account, 'paidToDate' => $paidToDate, 'balances' => $balances, 'averageInvoice' => $averageInvoice, 'invoicesSent' => $metrics ? $metrics->invoices_sent : 0, 'activeClients' => $metrics ? $metrics->active_clients : 0, 'activities' => $activities, 'pastDue' => $pastDue, 'upcoming' => $upcoming, 'payments' => $payments, 'title' => trans('texts.dashboard'), ]; return View::make('dashboard', $data); } } <file_sep>/app/Models/Invoice.php <?php namespace App\Models; use DateTime; use Illuminate\Database\Eloquent\SoftDeletes; class Invoice extends EntityModel { use SoftDeletes; protected $dates = ['deleted_at']; protected $casts = [ 'is_recurring' => 'boolean', 'has_tasks' => 'boolean', ]; public function account() { return $this->belongsTo('App\Models\Account'); } public function user() { return $this->belongsTo('App\Models\User'); } public function client() { return $this->belongsTo('App\Models\Client')->withTrashed(); } public function invoice_items() { return $this->hasMany('App\Models\InvoiceItem')->orderBy('id'); } public function invoice_status() { return $this->belongsTo('App\Models\InvoiceStatus'); } public function invoice_design() { return $this->belongsTo('App\Models\InvoiceDesign'); } public function recurring_invoice() { return $this->belongsTo('App\Models\Invoice'); } public function recurring_invoices() { return $this->hasMany('App\Models\Invoice', 'recurring_invoice_id'); } public function invitations() { return $this->hasMany('App\Models\Invitation')->orderBy('invitations.contact_id'); } public function getName() { return $this->is_recurring ? trans('texts.recurring') : $this->invoice_number; } public function getFileName() { $entityType = $this->getEntityType(); return trans("texts.$entityType") . '_' . $this->invoice_number . '.pdf'; } public function getPDFPath() { return storage_path() . '/pdfcache/cache-' . $this->id . '.pdf'; } public static function calcLink($invoice) { return link_to('invoices/' . $invoice->public_id, $invoice->invoice_number); } public function getLink() { return self::calcLink($this); } public function getEntityType() { return $this->is_quote ? ENTITY_QUOTE : ENTITY_INVOICE; } public function isSent() { return $this->invoice_status_id >= INVOICE_STATUS_SENT; } public function isViewed() { return $this->invoice_status_id >= INVOICE_STATUS_VIEWED; } public function isPaid() { return $this->invoice_status_id >= INVOICE_STATUS_PAID; } public function getRequestedAmount() { return $this->partial > 0 ? $this->partial : $this->balance; } public function hidePrivateFields() { $this->setVisible([ 'invoice_number', 'discount', 'is_amount_discount', 'po_number', 'invoice_date', 'due_date', 'terms', 'invoice_footer', 'public_notes', 'amount', 'balance', 'invoice_items', 'client', 'tax_name', 'tax_rate', 'account', 'invoice_design', 'invoice_design_id', 'is_pro', 'is_quote', 'custom_value1', 'custom_value2', 'custom_taxes1', 'custom_taxes2', 'partial', 'has_tasks', ]); $this->client->setVisible([ 'name', 'id_number', 'vat_number', 'address1', 'address2', 'city', 'state', 'postal_code', 'work_phone', 'payment_terms', 'contacts', 'country', 'currency_id', 'custom_value1', 'custom_value2', ]); $this->account->setVisible([ 'name', 'id_number', 'vat_number', 'address1', 'address2', 'city', 'state', 'postal_code', 'work_phone', 'work_email', 'country', 'currency_id', 'custom_label1', 'custom_value1', 'custom_label2', 'custom_value2', 'custom_client_label1', 'custom_client_label2', 'primary_color', 'secondary_color', 'hide_quantity', 'hide_paid_to_date', 'custom_invoice_label1', 'custom_invoice_label2', 'pdf_email_attachment', ]); foreach ($this->invoice_items as $invoiceItem) { $invoiceItem->setVisible([ 'product_key', 'notes', 'cost', 'qty', 'tax_name', 'tax_rate', ]); } foreach ($this->client->contacts as $contact) { $contact->setVisible([ 'first_name', 'last_name', 'email', 'phone', ]); } return $this; } public function shouldSendToday() { if (!$this->start_date || strtotime($this->start_date) > strtotime('now')) { return false; } if ($this->end_date && strtotime($this->end_date) < strtotime('now')) { return false; } $dayOfWeekToday = date('w'); $dayOfWeekStart = date('w', strtotime($this->start_date)); $dayOfMonthToday = date('j'); $dayOfMonthStart = date('j', strtotime($this->start_date)); if (!$this->last_sent_date) { return true; } else { $date1 = new DateTime($this->last_sent_date); $date2 = new DateTime(); $diff = $date2->diff($date1); $daysSinceLastSent = $diff->format("%a"); $monthsSinceLastSent = ($diff->format('%y') * 12) + $diff->format('%m'); if ($daysSinceLastSent == 0) { return false; } } switch ($this->frequency_id) { case FREQUENCY_WEEKLY: return $daysSinceLastSent >= 7; case FREQUENCY_TWO_WEEKS: return $daysSinceLastSent >= 14; case FREQUENCY_FOUR_WEEKS: return $daysSinceLastSent >= 28; case FREQUENCY_MONTHLY: return $monthsSinceLastSent >= 1; case FREQUENCY_THREE_MONTHS: return $monthsSinceLastSent >= 3; case FREQUENCY_SIX_MONTHS: return $monthsSinceLastSent >= 6; case FREQUENCY_ANNUALLY: return $monthsSinceLastSent >= 12; default: return false; } return false; } } Invoice::creating(function ($invoice) { if (!$invoice->is_recurring) { $invoice->account->incrementCounter($invoice->is_quote); } }); Invoice::created(function ($invoice) { Activity::createInvoice($invoice); }); Invoice::updating(function ($invoice) { Activity::updateInvoice($invoice); }); Invoice::deleting(function ($invoice) { Activity::archiveInvoice($invoice); }); Invoice::restoring(function ($invoice) { Activity::restoreInvoice($invoice); });<file_sep>/database/migrations/2014_10_13_054100_add_invoice_number_settings.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddInvoiceNumberSettings extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('accounts', function($table) { $table->text('invoice_number_prefix')->nullable(); $table->integer('invoice_number_counter')->default(1)->nullable(); $table->text('quote_number_prefix')->nullable(); $table->integer('quote_number_counter')->default(1)->nullable(); $table->boolean('share_counter')->default(true); }); // set initial counter value for accounts with invoices $accounts = DB::table('accounts')->lists('id'); foreach ($accounts as $accountId) { $invoiceNumbers = DB::table('invoices')->where('account_id', $accountId)->lists('invoice_number'); $max = 0; foreach ($invoiceNumbers as $invoiceNumber) { $number = intval(preg_replace('/[^0-9]/', '', $invoiceNumber)); $max = max($max, $number); } DB::table('accounts')->where('id', $accountId)->update(['invoice_number_counter' => ++$max]); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('accounts', function($table) { $table->dropColumn('invoice_number_prefix'); $table->dropColumn('invoice_number_counter'); $table->dropColumn('quote_number_prefix'); $table->dropColumn('quote_number_counter'); $table->dropColumn('share_counter'); }); } } <file_sep>/app/Ninja/Repositories/InvoiceRepository.php <?php namespace App\Ninja\Repositories; use Carbon; use Utils; use App\Models\Invoice; use App\Models\InvoiceItem; use App\Models\Invitation; use App\Models\Product; use App\Models\Task; class InvoiceRepository { public function getInvoices($accountId, $clientPublicId = false, $entityType = ENTITY_INVOICE, $filter = false) { $query = \DB::table('invoices') ->join('clients', 'clients.id', '=', 'invoices.client_id') ->join('invoice_statuses', 'invoice_statuses.id', '=', 'invoices.invoice_status_id') ->join('contacts', 'contacts.client_id', '=', 'clients.id') ->where('invoices.account_id', '=', $accountId) ->where('clients.deleted_at', '=', null) ->where('contacts.deleted_at', '=', null) ->where('invoices.is_recurring', '=', false) ->where('contacts.is_primary', '=', true) ->select('clients.public_id as client_public_id', 'invoice_number', 'invoice_status_id', 'clients.name as client_name', 'invoices.public_id', 'amount', 'invoices.balance', 'invoice_date', 'due_date', 'invoice_statuses.name as invoice_status_name', 'clients.currency_id', 'contacts.first_name', 'contacts.last_name', 'contacts.email', 'quote_id', 'quote_invoice_id', 'invoices.deleted_at', 'invoices.is_deleted', 'invoices.partial'); if (!\Session::get('show_trash:'.$entityType)) { $query->where('invoices.deleted_at', '=', null); } if ($clientPublicId) { $query->where('clients.public_id', '=', $clientPublicId); } if ($filter) { $query->where(function ($query) use ($filter) { $query->where('clients.name', 'like', '%'.$filter.'%') ->orWhere('invoices.invoice_number', 'like', '%'.$filter.'%') ->orWhere('invoice_statuses.name', 'like', '%'.$filter.'%') ->orWhere('contacts.first_name', 'like', '%'.$filter.'%') ->orWhere('contacts.last_name', 'like', '%'.$filter.'%') ->orWhere('contacts.email', 'like', '%'.$filter.'%'); }); } return $query; } public function getRecurringInvoices($accountId, $clientPublicId = false, $filter = false) { $query = \DB::table('invoices') ->join('clients', 'clients.id', '=', 'invoices.client_id') ->join('frequencies', 'frequencies.id', '=', 'invoices.frequency_id') ->join('contacts', 'contacts.client_id', '=', 'clients.id') ->where('invoices.account_id', '=', $accountId) ->where('invoices.is_quote', '=', false) ->where('contacts.deleted_at', '=', null) ->where('invoices.is_recurring', '=', true) ->where('contacts.is_primary', '=', true) ->where('clients.deleted_at', '=', null) ->select('clients.public_id as client_public_id', 'clients.name as client_name', 'invoices.public_id', 'amount', 'frequencies.name as frequency', 'start_date', 'end_date', 'clients.currency_id', 'contacts.first_name', 'contacts.last_name', 'contacts.email', 'invoices.deleted_at', 'invoices.is_deleted'); if ($clientPublicId) { $query->where('clients.public_id', '=', $clientPublicId); } if (!\Session::get('show_trash:invoice')) { $query->where('invoices.deleted_at', '=', null); } if ($filter) { $query->where(function ($query) use ($filter) { $query->where('clients.name', 'like', '%'.$filter.'%') ->orWhere('invoices.invoice_number', 'like', '%'.$filter.'%'); }); } return $query; } public function getClientDatatable($contactId, $entityType, $search) { $query = \DB::table('invitations') ->join('invoices', 'invoices.id', '=', 'invitations.invoice_id') ->join('clients', 'clients.id', '=', 'invoices.client_id') ->where('invitations.contact_id', '=', $contactId) ->where('invitations.deleted_at', '=', null) ->where('invoices.is_quote', '=', $entityType == ENTITY_QUOTE) ->where('invoices.is_deleted', '=', false) ->where('clients.deleted_at', '=', null) ->where('invoices.is_recurring', '=', false) ->select('invitation_key', 'invoice_number', 'invoice_date', 'invoices.balance as balance', 'due_date', 'clients.public_id as client_public_id', 'clients.name as client_name', 'invoices.public_id', 'amount', 'start_date', 'end_date', 'clients.currency_id', 'invoices.partial'); $table = \Datatable::query($query) ->addColumn('invoice_number', function ($model) use ($entityType) { return link_to('/view/'.$model->invitation_key, $model->invoice_number); }) ->addColumn('invoice_date', function ($model) { return Utils::fromSqlDate($model->invoice_date); }) ->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id); }); if ($entityType == ENTITY_INVOICE) { $table->addColumn('balance', function ($model) { return $model->partial > 0 ? trans('texts.partial_remaining', ['partial' => Utils::formatMoney($model->partial, $model->currency_id), 'balance' => Utils::formatMoney($model->balance, $model->currency_id)]) : Utils::formatMoney($model->balance, $model->currency_id); }); } return $table->addColumn('due_date', function ($model) { return Utils::fromSqlDate($model->due_date); }) ->make(); } public function getDatatable($accountId, $clientPublicId = null, $entityType, $search) { $query = $this->getInvoices($accountId, $clientPublicId, $entityType, $search) ->where('invoices.is_quote', '=', $entityType == ENTITY_QUOTE ? true : false); $table = \Datatable::query($query); if (!$clientPublicId) { $table->addColumn('checkbox', function ($model) { return '<input type="checkbox" name="ids[]" value="'.$model->public_id.'" '.Utils::getEntityRowClass($model).'>'; }); } $table->addColumn("invoice_number", function ($model) use ($entityType) { return link_to("{$entityType}s/".$model->public_id.'/edit', $model->invoice_number, ['class' => Utils::getEntityRowClass($model)]); }); if (!$clientPublicId) { $table->addColumn('client_name', function ($model) { return link_to('clients/'.$model->client_public_id, Utils::getClientDisplayName($model)); }); } $table->addColumn("invoice_date", function ($model) { return Utils::fromSqlDate($model->invoice_date); }) ->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id); }); if ($entityType == ENTITY_INVOICE) { $table->addColumn('balance', function ($model) { return $model->partial > 0 ? trans('texts.partial_remaining', ['partial' => Utils::formatMoney($model->partial, $model->currency_id), 'balance' => Utils::formatMoney($model->balance, $model->currency_id)]) : Utils::formatMoney($model->balance, $model->currency_id); }); } return $table->addColumn('due_date', function ($model) { return Utils::fromSqlDate($model->due_date); }) ->addColumn('invoice_status_name', function ($model) { return $model->quote_invoice_id ? link_to("invoices/{$model->quote_invoice_id}/edit", trans('texts.converted')) : self::getStatusLabel($model->invoice_status_id, $model->invoice_status_name); }) ->addColumn('dropdown', function ($model) use ($entityType) { if ($model->is_deleted) { return '<div style="height:38px"/>'; } $str = '<div class="btn-group tr-action" style="visibility:hidden;"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> '.trans('texts.select').' <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu">'; if (!$model->deleted_at || $model->deleted_at == '0000-00-00') { $str .= '<li><a href="'.\URL::to("{$entityType}s/".$model->public_id.'/edit').'">'.trans("texts.edit_{$entityType}").'</a></li> <li><a href="'.\URL::to("{$entityType}s/".$model->public_id.'/clone').'">'.trans("texts.clone_{$entityType}").'</a></li> <li><a href="' . \URL::to("{$entityType}s/{$entityType}_history/{$model->public_id}") . '">' . trans("texts.view_history") . '</a></li> <li class="divider"></li>'; if ($model->invoice_status_id < INVOICE_STATUS_SENT) { $str .= '<li><a href="javascript:markEntity('.$model->public_id.', '.INVOICE_STATUS_SENT.')">'.trans("texts.mark_sent").'</a></li>'; } if ($entityType == ENTITY_INVOICE) { if ($model->balance > 0) { $str .= '<li><a href="'.\URL::to('payments/create/'.$model->client_public_id.'/'.$model->public_id).'">'.trans('texts.enter_payment').'</a></li>'; } if ($model->quote_id) { $str .= '<li><a href="'.\URL::to("quotes/{$model->quote_id}/edit").'">'.trans("texts.view_quote").'</a></li>'; } } elseif ($entityType == ENTITY_QUOTE) { if ($model->quote_invoice_id) { $str .= '<li><a href="'.\URL::to("invoices/{$model->quote_invoice_id}/edit").'">'.trans("texts.view_invoice").'</a></li>'; } else { $str .= '<li><a href="javascript:convertEntity('.$model->public_id.')">'.trans("texts.convert_to_invoice").'</a></li>'; } } $str .= '<li class="divider"></li> <li><a href="javascript:archiveEntity('.$model->public_id.')">'.trans("texts.archive_{$entityType}").'</a></li> <li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans("texts.delete_{$entityType}").'</a></li>'; } else { $str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans("texts.restore_{$entityType}").'</a></li> <li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans("texts.delete_{$entityType}").'</a></li>'; } return $str.'</ul> </div>'; }) ->make(); } private function getStatusLabel($statusId, $statusName) { $label = trans("texts.{$statusName}"); $class = 'default'; switch ($statusId) { case INVOICE_STATUS_SENT: $class = 'info'; break; case INVOICE_STATUS_VIEWED: $class = 'warning'; break; case INVOICE_STATUS_PARTIAL: $class = 'primary'; break; case INVOICE_STATUS_PAID: $class = 'success'; break; } return "<h4><div class=\"label label-{$class}\">$statusName</div></h4>"; } public function getErrors($input) { $contact = (array) $input->client->contacts[0]; $rules = [ 'email' => 'email|required_without:first_name', 'first_name' => 'required_without:email', ]; $validator = \Validator::make($contact, $rules); if ($validator->fails()) { return $validator; } $invoice = (array) $input; $invoiceId = isset($invoice['public_id']) && $invoice['public_id'] ? Invoice::getPrivateId($invoice['public_id']) : null; $rules = [ 'invoice_number' => 'required|unique:invoices,invoice_number,'.$invoiceId.',id,account_id,'.\Auth::user()->account_id, 'discount' => 'positive', ]; if ($invoice['is_recurring'] && $invoice['start_date'] && $invoice['end_date']) { $rules['end_date'] = 'after:'.$invoice['start_date']; } $validator = \Validator::make($invoice, $rules); if ($validator->fails()) { return $validator; } return false; } public function save($publicId, $data, $entityType) { if ($publicId) { $invoice = Invoice::scope($publicId)->firstOrFail(); } else { $invoice = Invoice::createNew(); if ($entityType == ENTITY_QUOTE) { $invoice->is_quote = true; } } $account = \Auth::user()->account; if ((isset($data['set_default_terms']) && $data['set_default_terms']) || (isset($data['set_default_footer']) && $data['set_default_footer'])) { if (isset($data['set_default_terms']) && $data['set_default_terms']) { $account->invoice_terms = trim($data['terms']); } if (isset($data['set_default_footer']) && $data['set_default_footer']) { $account->invoice_footer = trim($data['invoice_footer']); } $account->save(); } if (isset($data['invoice_number'])) { $invoice->invoice_number = trim($data['invoice_number']); } $invoice->discount = round(Utils::parseFloat($data['discount']), 2); $invoice->is_amount_discount = $data['is_amount_discount'] ? true : false; $invoice->partial = round(Utils::parseFloat($data['partial']), 2); $invoice->invoice_date = isset($data['invoice_date_sql']) ? $data['invoice_date_sql'] : Utils::toSqlDate($data['invoice_date']); $invoice->has_tasks = isset($data['has_tasks']) ? $data['has_tasks'] : false; if (!$publicId) { $invoice->client_id = $data['client_id']; $invoice->is_recurring = $data['is_recurring'] && !Utils::isDemo() ? true : false; } if ($invoice->is_recurring) { $invoice->frequency_id = $data['frequency_id'] ? $data['frequency_id'] : 0; $invoice->start_date = Utils::toSqlDate($data['start_date']); $invoice->end_date = Utils::toSqlDate($data['end_date']); $invoice->due_date = null; } else { $invoice->due_date = isset($data['due_date_sql']) ? $data['due_date_sql'] : Utils::toSqlDate($data['due_date']); $invoice->frequency_id = 0; $invoice->start_date = null; $invoice->end_date = null; } $invoice->terms = trim($data['terms']) ? trim($data['terms']) : (!$publicId && $account->invoice_terms ? $account->invoice_terms : ''); $invoice->invoice_footer = trim($data['invoice_footer']) ? trim($data['invoice_footer']) : (!$publicId && $account->invoice_footer ? $account->invoice_footer : ''); $invoice->public_notes = trim($data['public_notes']); // process date variables $invoice->terms = Utils::processVariables($invoice->terms); $invoice->invoice_footer = Utils::processVariables($invoice->invoice_footer); $invoice->public_notes = Utils::processVariables($invoice->public_notes); $invoice->po_number = trim($data['po_number']); $invoice->invoice_design_id = $data['invoice_design_id']; if (isset($data['tax_name']) && isset($data['tax_rate']) && $data['tax_name']) { $invoice->tax_rate = Utils::parseFloat($data['tax_rate']); $invoice->tax_name = trim($data['tax_name']); } else { $invoice->tax_rate = 0; $invoice->tax_name = ''; } $total = 0; $itemTax = 0; foreach ($data['invoice_items'] as $item) { $item = (array) $item; if (!$item['cost'] && !$item['product_key'] && !$item['notes']) { continue; } $invoiceItemCost = round(Utils::parseFloat($item['cost']), 2); $invoiceItemQty = round(Utils::parseFloat($item['qty']), 2); $lineTotal = $invoiceItemCost * $invoiceItemQty; $total += round($lineTotal, 2); } foreach ($data['invoice_items'] as $item) { $item = (array) $item; if (isset($item['tax_rate']) && Utils::parseFloat($item['tax_rate']) > 0) { $invoiceItemCost = round(Utils::parseFloat($item['cost']), 2); $invoiceItemQty = round(Utils::parseFloat($item['qty']), 2); $invoiceItemTaxRate = Utils::parseFloat($item['tax_rate']); $lineTotal = $invoiceItemCost * $invoiceItemQty; if ($invoice->discount > 0) { if ($invoice->is_amount_discount) { $lineTotal -= round(($lineTotal/$total) * $invoice->discount, 2); } else { $lineTotal -= round($lineTotal * ($invoice->discount/100), 2); } } $itemTax += round($lineTotal * $invoiceItemTaxRate / 100, 2); } } if ($invoice->discount > 0) { if ($invoice->is_amount_discount) { $total -= $invoice->discount; } else { $total *= (100 - $invoice->discount) / 100; } } $invoice->custom_value1 = round($data['custom_value1'], 2); $invoice->custom_value2 = round($data['custom_value2'], 2); $invoice->custom_taxes1 = $data['custom_taxes1'] ? true : false; $invoice->custom_taxes2 = $data['custom_taxes2'] ? true : false; // custom fields charged taxes if ($invoice->custom_value1 && $invoice->custom_taxes1) { $total += $invoice->custom_value1; } if ($invoice->custom_value2 && $invoice->custom_taxes2) { $total += $invoice->custom_value2; } $total += $total * $invoice->tax_rate / 100; $total = round($total, 2); $total += $itemTax; // custom fields not charged taxes if ($invoice->custom_value1 && !$invoice->custom_taxes1) { $total += $invoice->custom_value1; } if ($invoice->custom_value2 && !$invoice->custom_taxes2) { $total += $invoice->custom_value2; } if ($publicId) { $invoice->balance = $total - ($invoice->amount - $invoice->balance); } else { $invoice->balance = $total; } $invoice->amount = $total; $invoice->save(); if ($publicId) { $invoice->invoice_items()->forceDelete(); } foreach ($data['invoice_items'] as $item) { $item = (array) $item; if (!$item['cost'] && !$item['product_key'] && !$item['notes']) { continue; } if (isset($item['task_public_id']) && $item['task_public_id']) { $task = Task::scope($item['task_public_id'])->where('invoice_id', '=', null)->firstOrFail(); $task->invoice_id = $invoice->id; $task->client_id = $invoice->client_id; $task->save(); } else if ($item['product_key'] && !$invoice->has_tasks) { $product = Product::findProductByKey(trim($item['product_key'])); if (\Auth::user()->account->update_products) { if (!$product) { $product = Product::createNew(); $product->product_key = trim($item['product_key']); } $product->notes = $item['notes']; $product->cost = $item['cost']; $product->save(); } } $invoiceItem = InvoiceItem::createNew(); $invoiceItem->product_id = isset($product) ? $product->id : null; $invoiceItem->product_key = trim($invoice->is_recurring ? $item['product_key'] : Utils::processVariables($item['product_key'])); $invoiceItem->notes = trim($invoice->is_recurring ? $item['notes'] : Utils::processVariables($item['notes'])); $invoiceItem->cost = Utils::parseFloat($item['cost']); $invoiceItem->qty = Utils::parseFloat($item['qty']); $invoiceItem->tax_rate = 0; if (isset($item['tax_rate']) && isset($item['tax_name']) && $item['tax_name']) { $invoiceItem['tax_rate'] = Utils::parseFloat($item['tax_rate']); $invoiceItem['tax_name'] = trim($item['tax_name']); } $invoice->invoice_items()->save($invoiceItem); } return $invoice; } public function cloneInvoice($invoice, $quotePublicId = null) { $invoice->load('invitations', 'invoice_items'); $account = $invoice->account; $clone = Invoice::createNew($invoice); $clone->balance = $invoice->amount; // if the invoice prefix is diff than quote prefix, use the same number for the invoice if (($account->invoice_number_prefix || $account->quote_number_prefix) && $account->invoice_number_prefix != $account->quote_number_prefix && $account->share_counter) { $invoiceNumber = $invoice->invoice_number; if ($account->quote_number_prefix && strpos($invoiceNumber, $account->quote_number_prefix) === 0) { $invoiceNumber = substr($invoiceNumber, strlen($account->quote_number_prefix)); } $clone->invoice_number = $account->invoice_number_prefix.$invoiceNumber; } else { $clone->invoice_number = $account->getNextInvoiceNumber(); } foreach ([ 'client_id', 'discount', 'is_amount_discount', 'invoice_date', 'po_number', 'due_date', 'is_recurring', 'frequency_id', 'start_date', 'end_date', 'terms', 'invoice_footer', 'public_notes', 'invoice_design_id', 'tax_name', 'tax_rate', 'amount', 'is_quote', 'custom_value1', 'custom_value2', 'custom_taxes1', 'custom_taxes2', 'partial'] as $field) { $clone->$field = $invoice->$field; } if ($quotePublicId) { $clone->is_quote = false; $clone->quote_id = $quotePublicId; } $clone->save(); if ($quotePublicId) { $invoice->quote_invoice_id = $clone->public_id; $invoice->save(); } foreach ($invoice->invoice_items as $item) { $cloneItem = InvoiceItem::createNew($invoice); foreach ([ 'product_id', 'product_key', 'notes', 'cost', 'qty', 'tax_name', 'tax_rate', ] as $field) { $cloneItem->$field = $item->$field; } $clone->invoice_items()->save($cloneItem); } foreach ($invoice->invitations as $invitation) { $cloneInvitation = Invitation::createNew($invoice); $cloneInvitation->contact_id = $invitation->contact_id; $cloneInvitation->invitation_key = str_random(RANDOM_KEY_LENGTH); $clone->invitations()->save($cloneInvitation); } return $clone; } public function bulk($ids, $action, $statusId = false) { if (!$ids) { return 0; } $invoices = Invoice::withTrashed()->scope($ids)->get(); foreach ($invoices as $invoice) { if ($action == 'mark') { $invoice->invoice_status_id = $statusId; $invoice->save(); } elseif ($action == 'restore') { $invoice->restore(); } else { if ($action == 'delete') { $invoice->is_deleted = true; $invoice->save(); } $invoice->delete(); } } return count($invoices); } public function findOpenInvoices($clientId) { return Invoice::scope() ->whereClientId($clientId) ->whereIsQuote(false) ->whereIsRecurring(false) ->whereDeletedAt(null) ->whereHasTasks(true) ->where('invoice_status_id', '<', 5) ->select(['public_id', 'invoice_number']) ->get(); } public function createRecurringInvoice($recurInvoice) { $recurInvoice->load('account.timezone', 'invoice_items', 'client', 'user'); if ($recurInvoice->client->deleted_at) { return false; } if (!$recurInvoice->user->confirmed) { return false; } if (!$recurInvoice->shouldSendToday()) { return false; } $invoice = Invoice::createNew($recurInvoice); $invoice->client_id = $recurInvoice->client_id; $invoice->recurring_invoice_id = $recurInvoice->id; $invoice->invoice_number = $recurInvoice->account->getNextInvoiceNumber(false, 'R'); $invoice->amount = $recurInvoice->amount; $invoice->balance = $recurInvoice->amount; $invoice->invoice_date = date_create()->format('Y-m-d'); $invoice->discount = $recurInvoice->discount; $invoice->po_number = $recurInvoice->po_number; $invoice->public_notes = Utils::processVariables($recurInvoice->public_notes); $invoice->terms = Utils::processVariables($recurInvoice->terms); $invoice->invoice_footer = Utils::processVariables($recurInvoice->invoice_footer); $invoice->tax_name = $recurInvoice->tax_name; $invoice->tax_rate = $recurInvoice->tax_rate; $invoice->invoice_design_id = $recurInvoice->invoice_design_id; $invoice->custom_value1 = $recurInvoice->custom_value1; $invoice->custom_value2 = $recurInvoice->custom_value2; $invoice->custom_taxes1 = $recurInvoice->custom_taxes1; $invoice->custom_taxes2 = $recurInvoice->custom_taxes2; $invoice->is_amount_discount = $recurInvoice->is_amount_discount; if ($invoice->client->payment_terms != 0) { $days = $invoice->client->payment_terms; if ($days == -1) { $days = 0; } $invoice->due_date = date_create()->modify($days.' day')->format('Y-m-d'); } $invoice->save(); foreach ($recurInvoice->invoice_items as $recurItem) { $item = InvoiceItem::createNew($recurItem); $item->product_id = $recurItem->product_id; $item->qty = $recurItem->qty; $item->cost = $recurItem->cost; $item->notes = Utils::processVariables($recurItem->notes); $item->product_key = Utils::processVariables($recurItem->product_key); $item->tax_name = $recurItem->tax_name; $item->tax_rate = $recurItem->tax_rate; $invoice->invoice_items()->save($item); } foreach ($recurInvoice->invitations as $recurInvitation) { $invitation = Invitation::createNew($recurInvitation); $invitation->contact_id = $recurInvitation->contact_id; $invitation->invitation_key = str_random(RANDOM_KEY_LENGTH); $invoice->invitations()->save($invitation); } $recurInvoice->last_sent_date = Carbon::now()->toDateTimeString(); $recurInvoice->save(); return $invoice; } } <file_sep>/app/Http/Controllers/TokenController.php <?php namespace App\Http\Controllers; /* |-------------------------------------------------------------------------- | Confide Controller Template |-------------------------------------------------------------------------- | | This is the default Confide controller template for controlling user | authentication. Feel free to change to your needs. | */ use Auth; use Session; use DB; use Validator; use Input; use View; use Redirect; use Datatable; use URL; use App\Models\AccountToken; use App\Ninja\Repositories\AccountRepository; class TokenController extends BaseController { public function getDatatable() { $query = DB::table('account_tokens') ->where('account_tokens.account_id', '=', Auth::user()->account_id); if (!Session::get('show_trash:token')) { $query->where('account_tokens.deleted_at', '=', null); } $query->select('account_tokens.public_id', 'account_tokens.name', 'account_tokens.token', 'account_tokens.public_id', 'account_tokens.deleted_at'); return Datatable::query($query) ->addColumn('name', function ($model) { return link_to('tokens/'.$model->public_id.'/edit', $model->name); }) ->addColumn('token', function ($model) { return $model->token; }) ->addColumn('dropdown', function ($model) { $actions = '<div class="btn-group tr-action" style="visibility:hidden;"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> '.trans('texts.select').' <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu">'; if (!$model->deleted_at) { $actions .= '<li><a href="'.URL::to('tokens/'.$model->public_id).'/edit">'.uctrans('texts.edit_token').'</a></li> <li class="divider"></li> <li><a href="javascript:deleteToken('.$model->public_id.')">'.uctrans('texts.delete_token').'</a></li>'; } $actions .= '</ul> </div>'; return $actions; }) ->orderColumns(['name', 'token']) ->make(); } public function edit($publicId) { $token = AccountToken::where('account_id', '=', Auth::user()->account_id) ->where('public_id', '=', $publicId)->firstOrFail(); $data = [ 'showBreadcrumbs' => false, 'token' => $token, 'method' => 'PUT', 'url' => 'tokens/'.$publicId, 'title' => trans('texts.edit_token'), ]; return View::make('accounts.token', $data); } public function update($publicId) { return $this->save($publicId); } public function store() { return $this->save(); } /** * Displays the form for account creation * */ public function create() { $data = [ 'showBreadcrumbs' => false, 'token' => null, 'method' => 'POST', 'url' => 'tokens', 'title' => trans('texts.add_token'), ]; return View::make('accounts.token', $data); } public function delete() { $tokenPublicId = Input::get('tokenPublicId'); $token = AccountToken::where('account_id', '=', Auth::user()->account_id) ->where('public_id', '=', $tokenPublicId)->firstOrFail(); $token->delete(); Session::flash('message', trans('texts.deleted_token')); return Redirect::to('company/advanced_settings/token_management'); } /** * Stores new account * */ public function save($tokenPublicId = false) { if (Auth::user()->account->isPro()) { $rules = [ 'name' => 'required', ]; if ($tokenPublicId) { $token = AccountToken::where('account_id', '=', Auth::user()->account_id) ->where('public_id', '=', $tokenPublicId)->firstOrFail(); } $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return Redirect::to($tokenPublicId ? 'tokens/edit' : 'tokens/create')->withInput()->withErrors($validator); } if ($tokenPublicId) { $token->name = trim(Input::get('name')); } else { $lastToken = AccountToken::withTrashed()->where('account_id', '=', Auth::user()->account_id) ->orderBy('public_id', 'DESC')->first(); $token = AccountToken::createNew(); $token->name = trim(Input::get('name')); $token->token = str_random(RANDOM_KEY_LENGTH); $token->public_id = $lastToken ? $lastToken->public_id + 1 : 1; } $token->save(); if ($tokenPublicId) { $message = trans('texts.updated_token'); } else { $message = trans('texts.created_token'); } Session::flash('message', $message); } return Redirect::to('company/advanced_settings/token_management'); } } <file_sep>/database/migrations/2013_11_05_180133_confide_setup_users_table.php <?php use Illuminate\Database\Migrations\Migration; class ConfideSetupUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::dropIfExists('payment_terms'); Schema::dropIfExists('themes'); Schema::dropIfExists('credits'); Schema::dropIfExists('activities'); Schema::dropIfExists('invitations'); Schema::dropIfExists('payments'); Schema::dropIfExists('account_gateways'); Schema::dropIfExists('invoice_items'); Schema::dropIfExists('products'); Schema::dropIfExists('tax_rates'); Schema::dropIfExists('contacts'); Schema::dropIfExists('invoices'); Schema::dropIfExists('password_reminders'); Schema::dropIfExists('clients'); Schema::dropIfExists('users'); Schema::dropIfExists('accounts'); Schema::dropIfExists('currencies'); Schema::dropIfExists('invoice_statuses'); Schema::dropIfExists('countries'); Schema::dropIfExists('timezones'); Schema::dropIfExists('frequencies'); Schema::dropIfExists('date_formats'); Schema::dropIfExists('datetime_formats'); Schema::dropIfExists('sizes'); Schema::dropIfExists('industries'); Schema::dropIfExists('gateways'); Schema::dropIfExists('payment_types'); Schema::create('countries', function($table) { $table->increments('id'); $table->string('capital', 255)->nullable(); $table->string('citizenship', 255)->nullable(); $table->string('country_code', 3)->default(''); $table->string('currency', 255)->nullable(); $table->string('currency_code', 255)->nullable(); $table->string('currency_sub_unit', 255)->nullable(); $table->string('full_name', 255)->nullable(); $table->string('iso_3166_2', 2)->default(''); $table->string('iso_3166_3', 3)->default(''); $table->string('name', 255)->default(''); $table->string('region_code', 3)->default(''); $table->string('sub_region_code', 3)->default(''); $table->boolean('eea')->default(0); }); Schema::create('themes', function($t) { $t->increments('id'); $t->string('name'); }); Schema::create('payment_types', function($t) { $t->increments('id'); $t->string('name'); }); Schema::create('payment_terms', function($t) { $t->increments('id'); $t->integer('num_days'); $t->string('name'); }); Schema::create('timezones', function($t) { $t->increments('id'); $t->string('name'); $t->string('location'); }); Schema::create('date_formats', function($t) { $t->increments('id'); $t->string('format'); $t->string('picker_format'); $t->string('label'); }); Schema::create('datetime_formats', function($t) { $t->increments('id'); $t->string('format'); $t->string('label'); }); Schema::create('currencies', function($t) { $t->increments('id'); $t->string('name'); $t->string('symbol'); $t->string('precision'); $t->string('thousand_separator'); $t->string('decimal_separator'); $t->string('code'); }); Schema::create('sizes', function($t) { $t->increments('id'); $t->string('name'); }); Schema::create('industries', function($t) { $t->increments('id'); $t->string('name'); }); Schema::create('accounts', function($t) { $t->increments('id'); $t->unsignedInteger('timezone_id')->nullable(); $t->unsignedInteger('date_format_id')->nullable(); $t->unsignedInteger('datetime_format_id')->nullable(); $t->unsignedInteger('currency_id')->nullable(); $t->timestamps(); $t->softDeletes(); $t->string('name')->nullable(); $t->string('ip'); $t->string('account_key')->unique(); $t->timestamp('last_login')->nullable(); $t->string('address1')->nullable(); $t->string('address2')->nullable(); $t->string('city')->nullable(); $t->string('state')->nullable(); $t->string('postal_code')->nullable(); $t->unsignedInteger('country_id')->nullable(); $t->text('invoice_terms')->nullable(); $t->text('email_footer')->nullable(); $t->unsignedInteger('industry_id')->nullable(); $t->unsignedInteger('size_id')->nullable(); $t->boolean('invoice_taxes')->default(true); $t->boolean('invoice_item_taxes')->default(false); $t->foreign('timezone_id')->references('id')->on('timezones'); $t->foreign('date_format_id')->references('id')->on('date_formats'); $t->foreign('datetime_format_id')->references('id')->on('datetime_formats'); $t->foreign('country_id')->references('id')->on('countries'); $t->foreign('currency_id')->references('id')->on('currencies'); $t->foreign('industry_id')->references('id')->on('industries'); $t->foreign('size_id')->references('id')->on('sizes'); }); Schema::create('gateways', function($t) { $t->increments('id'); $t->timestamps(); $t->string('name'); $t->string('provider'); $t->boolean('visible')->default(true); }); Schema::create('users', function($t) { $t->increments('id'); $t->unsignedInteger('account_id')->index(); $t->timestamps(); $t->softDeletes(); $t->string('first_name')->nullable(); $t->string('last_name')->nullable(); $t->string('phone')->nullable(); $t->string('username')->unique(); $t->string('email')->nullable(); $t->string('password'); $t->string('confirmation_code')->nullable(); $t->boolean('registered')->default(false); $t->boolean('confirmed')->default(false); $t->integer('theme_id')->nullable(); $t->boolean('notify_sent')->default(true); $t->boolean('notify_viewed')->default(false); $t->boolean('notify_paid')->default(true); $t->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); $t->unsignedInteger('public_id')->nullable(); $t->unique( array('account_id','public_id') ); }); Schema::create('account_gateways', function($t) { $t->increments('id'); $t->unsignedInteger('account_id'); $t->unsignedInteger('user_id'); $t->unsignedInteger('gateway_id'); $t->timestamps(); $t->softDeletes(); $t->text('config'); $t->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); $t->foreign('gateway_id')->references('id')->on('gateways'); $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $t->unsignedInteger('public_id')->index(); $t->unique( array('account_id','public_id') ); }); Schema::create('password_reminders', function($t) { $t->string('email'); $t->timestamps(); $t->string('token'); }); Schema::create('clients', function($t) { $t->increments('id'); $t->unsignedInteger('user_id'); $t->unsignedInteger('account_id')->index(); $t->unsignedInteger('currency_id')->nullable(); $t->timestamps(); $t->softDeletes(); $t->string('name')->nullable(); $t->string('address1')->nullable(); $t->string('address2')->nullable(); $t->string('city')->nullable(); $t->string('state')->nullable(); $t->string('postal_code')->nullable(); $t->unsignedInteger('country_id')->nullable(); $t->string('work_phone')->nullable(); $t->text('private_notes')->nullable(); $t->decimal('balance', 13, 2)->nullable(); $t->decimal('paid_to_date', 13, 2)->nullable(); $t->timestamp('last_login')->nullable(); $t->string('website')->nullable(); $t->unsignedInteger('industry_id')->nullable(); $t->unsignedInteger('size_id')->nullable(); $t->boolean('is_deleted')->default(false); $t->integer('payment_terms')->nullable(); $t->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $t->foreign('country_id')->references('id')->on('countries'); $t->foreign('industry_id')->references('id')->on('industries'); $t->foreign('size_id')->references('id')->on('sizes'); $t->foreign('currency_id')->references('id')->on('currencies'); $t->unsignedInteger('public_id')->index(); $t->unique( array('account_id','public_id') ); }); Schema::create('contacts', function($t) { $t->increments('id'); $t->unsignedInteger('account_id'); $t->unsignedInteger('user_id'); $t->unsignedInteger('client_id')->index(); $t->timestamps(); $t->softDeletes(); $t->boolean('is_primary')->default(0); $t->boolean('send_invoice')->default(0); $t->string('first_name')->nullable(); $t->string('last_name')->nullable(); $t->string('email')->nullable(); $t->string('phone')->nullable(); $t->timestamp('last_login')->nullable(); $t->foreign('client_id')->references('id')->on('clients')->onDelete('cascade'); $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade');; $t->unsignedInteger('public_id')->nullable(); $t->unique( array('account_id','public_id') ); }); Schema::create('invoice_statuses', function($t) { $t->increments('id'); $t->string('name'); }); Schema::create('frequencies', function($t) { $t->increments('id'); $t->string('name'); }); Schema::create('invoices', function($t) { $t->increments('id'); $t->unsignedInteger('client_id')->index(); $t->unsignedInteger('user_id'); $t->unsignedInteger('account_id')->index(); $t->unsignedInteger('invoice_status_id')->default(1); $t->timestamps(); $t->softDeletes(); $t->string('invoice_number'); $t->float('discount'); $t->string('po_number'); $t->date('invoice_date')->nullable(); $t->date('due_date')->nullable(); $t->text('terms'); $t->text('public_notes'); $t->boolean('is_deleted')->default(false); $t->boolean('is_recurring'); $t->unsignedInteger('frequency_id'); $t->date('start_date')->nullable(); $t->date('end_date')->nullable(); $t->timestamp('last_sent_date')->nullable(); $t->unsignedInteger('recurring_invoice_id')->index()->nullable(); $t->string('tax_name'); $t->decimal('tax_rate', 13, 2); $t->decimal('amount', 13, 2); $t->decimal('balance', 13, 2); $t->foreign('client_id')->references('id')->on('clients')->onDelete('cascade'); $t->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $t->foreign('invoice_status_id')->references('id')->on('invoice_statuses'); $t->foreign('recurring_invoice_id')->references('id')->on('invoices')->onDelete('cascade'); $t->unsignedInteger('public_id')->index(); $t->unique( array('account_id','public_id') ); $t->unique( array('account_id','invoice_number') ); }); Schema::create('invitations', function($t) { $t->increments('id'); $t->unsignedInteger('account_id'); $t->unsignedInteger('user_id'); $t->unsignedInteger('contact_id'); $t->unsignedInteger('invoice_id')->index(); $t->string('invitation_key')->index()->unique(); $t->timestamps(); $t->softDeletes(); $t->string('transaction_reference')->nullable(); $t->timestamp('sent_date')->nullable(); $t->timestamp('viewed_date')->nullable(); $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade');; $t->foreign('contact_id')->references('id')->on('contacts')->onDelete('cascade'); $t->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade'); $t->unsignedInteger('public_id')->index(); $t->unique( array('account_id','public_id') ); }); Schema::create('tax_rates', function($t) { $t->increments('id'); $t->unsignedInteger('account_id')->index(); $t->unsignedInteger('user_id'); $t->timestamps(); $t->softDeletes(); $t->string('name'); $t->decimal('rate', 13, 2); $t->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade');; $t->unsignedInteger('public_id'); $t->unique( array('account_id','public_id') ); }); Schema::create('products', function($t) { $t->increments('id'); $t->unsignedInteger('account_id')->index(); $t->unsignedInteger('user_id'); $t->timestamps(); $t->softDeletes(); $t->string('product_key'); $t->text('notes'); $t->decimal('cost', 13, 2); $t->decimal('qty', 13, 2)->nullable(); $t->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade');; $t->unsignedInteger('public_id'); $t->unique( array('account_id','public_id') ); }); Schema::create('invoice_items', function($t) { $t->increments('id'); $t->unsignedInteger('account_id'); $t->unsignedInteger('user_id'); $t->unsignedInteger('invoice_id')->index(); $t->unsignedInteger('product_id')->nullable(); $t->timestamps(); $t->softDeletes(); $t->string('product_key'); $t->text('notes'); $t->decimal('cost', 13, 2); $t->decimal('qty', 13, 2)->nullable(); $t->string('tax_name')->nullable(); $t->decimal('tax_rate', 13, 2)->nullable(); $t->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade'); $t->foreign('product_id')->references('id')->on('products')->onDelete('cascade'); $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade');; $t->unsignedInteger('public_id'); $t->unique( array('account_id','public_id') ); }); Schema::create('payments', function($t) { $t->increments('id'); $t->unsignedInteger('invoice_id')->nullable(); $t->unsignedInteger('account_id')->index(); $t->unsignedInteger('client_id')->index(); $t->unsignedInteger('contact_id')->nullable(); $t->unsignedInteger('invitation_id')->nullable(); $t->unsignedInteger('user_id')->nullable(); $t->unsignedInteger('account_gateway_id')->nullable(); $t->unsignedInteger('payment_type_id')->nullable(); $t->timestamps(); $t->softDeletes(); $t->boolean('is_deleted')->default(false); $t->decimal('amount', 13, 2); $t->date('payment_date')->nullable(); $t->string('transaction_reference')->nullable(); $t->string('payer_id')->nullable(); $t->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade'); $t->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); $t->foreign('client_id')->references('id')->on('clients')->onDelete('cascade'); $t->foreign('contact_id')->references('id')->on('contacts')->onDelete('cascade'); $t->foreign('account_gateway_id')->references('id')->on('account_gateways')->onDelete('cascade'); $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade');; $t->foreign('payment_type_id')->references('id')->on('payment_types'); $t->unsignedInteger('public_id')->index(); $t->unique( array('account_id','public_id') ); }); Schema::create('credits', function($t) { $t->increments('id'); $t->unsignedInteger('account_id')->index(); $t->unsignedInteger('client_id')->index(); $t->unsignedInteger('user_id'); $t->timestamps(); $t->softDeletes(); $t->boolean('is_deleted')->default(false); $t->decimal('amount', 13, 2); $t->decimal('balance', 13, 2); $t->date('credit_date')->nullable(); $t->string('credit_number')->nullable(); $t->text('private_notes'); $t->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); $t->foreign('client_id')->references('id')->on('clients')->onDelete('cascade'); $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade');; $t->unsignedInteger('public_id')->index(); $t->unique( array('account_id','public_id') ); }); Schema::create('activities', function($t) { $t->increments('id'); $t->timestamps(); $t->unsignedInteger('account_id'); $t->unsignedInteger('client_id'); $t->unsignedInteger('user_id'); $t->unsignedInteger('contact_id')->nullable(); $t->unsignedInteger('payment_id')->nullable(); $t->unsignedInteger('invoice_id')->nullable(); $t->unsignedInteger('credit_id')->nullable(); $t->unsignedInteger('invitation_id')->nullable(); $t->text('message')->nullable(); $t->text('json_backup')->nullable(); $t->integer('activity_type_id'); $t->decimal('adjustment', 13, 2)->nullable(); $t->decimal('balance', 13, 2)->nullable(); $t->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); $t->foreign('client_id')->references('id')->on('clients')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('payment_terms'); Schema::dropIfExists('themes'); Schema::dropIfExists('credits'); Schema::dropIfExists('activities'); Schema::dropIfExists('invitations'); Schema::dropIfExists('payments'); Schema::dropIfExists('account_gateways'); Schema::dropIfExists('invoice_items'); Schema::dropIfExists('products'); Schema::dropIfExists('tax_rates'); Schema::dropIfExists('contacts'); Schema::dropIfExists('invoices'); Schema::dropIfExists('password_reminders'); Schema::dropIfExists('clients'); Schema::dropIfExists('users'); Schema::dropIfExists('accounts'); Schema::dropIfExists('currencies'); Schema::dropIfExists('invoice_statuses'); Schema::dropIfExists('countries'); Schema::dropIfExists('timezones'); Schema::dropIfExists('frequencies'); Schema::dropIfExists('date_formats'); Schema::dropIfExists('datetime_formats'); Schema::dropIfExists('sizes'); Schema::dropIfExists('industries'); Schema::dropIfExists('gateways'); Schema::dropIfExists('payment_types'); } } <file_sep>/app/Models/Invitation.php <?php namespace App\Models; use Illuminate\Database\Eloquent\SoftDeletes; class Invitation extends EntityModel { use SoftDeletes; protected $dates = ['deleted_at']; public function invoice() { return $this->belongsTo('App\Models\Invoice')->withTrashed(); } public function contact() { return $this->belongsTo('App\Models\Contact')->withTrashed(); } public function user() { return $this->belongsTo('App\Models\User')->withTrashed(); } public function account() { return $this->belongsTo('App\Models\Account'); } public function getLink() { if (!$this->account) { $this->load('account'); } $url = SITE_URL; if ($this->account->subdomain) { $parsedUrl = parse_url($url); $host = explode('.', $parsedUrl['host']); $subdomain = $host[0]; $url = str_replace("://{$subdomain}.", "://{$this->account->subdomain}.", $url); } return "{$url}/view/{$this->invitation_key}"; } public function getName() { return $this->invitation_key; } } <file_sep>/app/Http/Controllers/PaymentApiController.php <?php namespace App\Http\Controllers; use Input; use Utils; use Response; use App\Models\Payment; use App\Models\Invoice; use App\Ninja\Repositories\PaymentRepository; class PaymentApiController extends Controller { protected $paymentRepo; public function __construct(PaymentRepository $paymentRepo) { $this->paymentRepo = $paymentRepo; } public function index() { $payments = Payment::scope() ->with('client', 'contact', 'invitation', 'user', 'invoice') ->orderBy('created_at', 'desc') ->get(); $payments = Utils::remapPublicIds($payments); $response = json_encode($payments, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(count($payments)); return Response::make($response, 200, $headers); } public function store() { $data = Input::all(); $error = false; if (isset($data['invoice_id'])) { $invoice = Invoice::scope($data['invoice_id'])->with('client')->first(); if ($invoice) { $data['invoice'] = $invoice->public_id; $data['client'] = $invoice->client->public_id; } else { $error = trans('validation.not_in', ['attribute' => 'invoice_id']); } } else { $error = trans('validation.not_in', ['attribute' => 'invoice_id']); } if (!isset($data['transaction_reference'])) { $data['transaction_reference'] = ''; } if (!$error) { $payment = $this->paymentRepo->save(false, $data); $payment = Payment::scope($payment->public_id)->with('client', 'contact', 'user', 'invoice')->first(); $payment = Utils::remapPublicIds([$payment]); } $response = json_encode($error ?: $payment, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(); return Response::make($response, 200, $headers); } } <file_sep>/tests/acceptance/AllPagesCept.php <?php $I = new AcceptanceTester($scenario); $I->wantTo('Test all pages load'); $I->amOnPage('/login'); //$I->see(trans('texts.forgot_password')); // Login as test user $I->fillField(['name' => 'email'], '<EMAIL>'); $I->fillField(['name' => 'password'], '<PASSWORD>'); $I->click('Let\'s go'); $I->see('Dashboard'); // Top level navigation $I->amOnPage('/dashboard'); $I->see('Total Revenue'); $I->amOnPage('/clients'); $I->see('Clients', 'li'); $I->amOnPage('/clients/create'); $I->see('Clients', 'li'); $I->see('Create'); $I->amOnPage('/credits'); $I->see('Credits', 'li'); $I->amOnPage('/credits/create'); $I->see('Credits', 'li'); $I->see('Create'); $I->amOnPage('/tasks'); $I->see('Tasks', 'li'); $I->amOnPage('/tasks/create'); $I->see('Tasks', 'li'); $I->see('Create'); $I->amOnPage('/invoices'); $I->see('Invoices', 'li'); $I->amOnPage('/invoices/create'); $I->see('Invoices', 'li'); $I->see('Create'); $I->amOnPage('/quotes'); $I->see('Quotes', 'li'); $I->amOnPage('/quotes/create'); $I->see('Quotes', 'li'); $I->see('Create'); $I->amOnPage('/payments'); $I->see('Payments', 'li'); $I->amOnPage('/payments/create'); $I->see('Payments', 'li'); $I->see('Create'); // Settings pages $I->amOnPage('/company/details'); $I->see('Details'); $I->amOnPage('/gateways/create'); $I->see('Add Gateway'); $I->amOnPage('/company/products'); $I->see('Product Settings'); $I->amOnPage('/company/import_export'); $I->see('Import'); $I->amOnPage('/company/advanced_settings/invoice_settings'); $I->see('Invoice Fields'); $I->amOnPage('/company/advanced_settings/invoice_design'); $I->see('Invoice Design'); $I->amOnPage('/company/advanced_settings/email_templates'); $I->see('Invoice Email'); $I->amOnPage('/company/advanced_settings/charts_and_reports'); $I->see('Data Visualizations'); $I->amOnPage('/company/advanced_settings/user_management'); $I->see('Add User'); //try to logout $I->click('#myAccountButton'); $I->see('Log Out'); $I->click('Log Out'); // Miscellaneous pages $I->amOnPage('/terms'); $I->see('Terms'); <file_sep>/app/Providers/AppServiceProvider.php <?php namespace App\Providers; use Session; use Auth; use Utils; use HTML; use URL; use Request; use Validator; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { HTML::macro('nav_link', function($url, $text, $url2 = '', $extra = '') { $class = ( Request::is($url) || Request::is($url.'/*') || Request::is($url2.'/*') ) ? ' class="active"' : ''; $title = ucwords(trans("texts.$text")) . Utils::getProLabel($text); return '<li'.$class.'><a href="'.URL::to($url).'" '.$extra.'>'.$title.'</a></li>'; }); HTML::macro('tab_link', function($url, $text, $active = false) { $class = $active ? ' class="active"' : ''; return '<li'.$class.'><a href="'.URL::to($url).'" data-toggle="tab">'.$text.'</a></li>'; }); HTML::macro('menu_link', function($type) { $types = $type.'s'; $Type = ucfirst($type); $Types = ucfirst($types); $class = ( Request::is($types) || Request::is('*'.$type.'*')) && !Request::is('*advanced_settings*') ? ' active' : ''; $str = '<li class="dropdown '.$class.'"> <a href="'.URL::to($types).'" class="dropdown-toggle">'.trans("texts.$types").'</a> <ul class="dropdown-menu" id="menu1">'; if ($type != ENTITY_TASK || Auth::user()->account->timezone_id) { $str .= '<li><a href="'.URL::to($types.'/create').'">'.trans("texts.new_$type").'</a></li>'; } if ($type == ENTITY_INVOICE) { $str .= '<li><a href="'.URL::to('recurring_invoices/create').'">'.trans("texts.new_recurring_invoice").'</a></li>'; if (Auth::user()->isPro()) { $str .= '<li class="divider"></li> <li><a href="'.URL::to('quotes').'">'.trans("texts.quotes").'</a></li> <li><a href="'.URL::to('quotes/create').'">'.trans("texts.new_quote").'</a></li>'; } } else if ($type == ENTITY_CLIENT) { $str .= '<li class="divider"></li> <li><a href="'.URL::to('credits').'">'.trans("texts.credits").'</a></li> <li><a href="'.URL::to('credits/create').'">'.trans("texts.new_credit").'</a></li>'; } $str .= '</ul> </li>'; return $str; }); HTML::macro('image_data', function($imagePath) { return 'data:image/jpeg;base64,' . base64_encode(file_get_contents(public_path().'/'.$imagePath)); }); HTML::macro('breadcrumbs', function() { $str = '<ol class="breadcrumb">'; // Get the breadcrumbs by exploding the current path. $basePath = Utils::basePath(); $parts = explode('?', isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''); $path = $parts[0]; if ($basePath != '/') { $path = str_replace($basePath, '', $path); } $crumbs = explode('/', $path); foreach ($crumbs as $key => $val) { if (is_numeric($val)) { unset($crumbs[$key]); } } $crumbs = array_values($crumbs); for ($i=0; $i<count($crumbs); $i++) { $crumb = trim($crumbs[$i]); if (!$crumb) { continue; } if ($crumb == 'company') { return ''; } $name = trans("texts.$crumb"); if ($i==count($crumbs)-1) { $str .= "<li class='active'>$name</li>"; } else { $str .= '<li>'.link_to($crumb, $name).'</li>'; } } return $str . '</ol>'; }); Validator::extend('positive', function($attribute, $value, $parameters) { return Utils::parseFloat($value) >= 0; }); Validator::extend('has_credit', function($attribute, $value, $parameters) { $publicClientId = $parameters[0]; $amount = $parameters[1]; $client = \App\Models\Client::scope($publicClientId)->firstOrFail(); $credit = $client->getTotalCredit(); return $credit >= $amount; }); Validator::extend('less_than', function($attribute, $value, $parameters) { return floatval($value) <= floatval($parameters[0]); }); Validator::replacer('less_than', function($message, $attribute, $rule, $parameters) { return str_replace(':value', $parameters[0], $message); }); } /** * Register any application services. * * This service provider is a great spot to register your various container * bindings with the application. As you can see, we are registering our * "Registrar" implementation here. You can add your own bindings too! * * @return void */ public function register() { $this->app->bind( 'Illuminate\Contracts\Auth\Registrar', 'App\Services\Registrar' ); } } <file_sep>/app/Ninja/Mailers/ContactMailer.php <?php namespace App\Ninja\Mailers; use Utils; use Event; use URL; use App\Models\Invoice; use App\Models\Payment; use App\Models\Activity; use App\Models\Gateway; use App\Events\InvoiceSent; class ContactMailer extends Mailer { public function sendInvoice(Invoice $invoice) { $invoice->load('invitations', 'client', 'account'); $entityType = $invoice->getEntityType(); $view = 'invoice'; $subject = trans("texts.{$entityType}_subject", ['invoice' => $invoice->invoice_number, 'account' => $invoice->account->getDisplayName()]); $accountName = $invoice->account->getDisplayName(); $emailTemplate = $invoice->account->getEmailTemplate($entityType); $invoiceAmount = Utils::formatMoney($invoice->getRequestedAmount(), $invoice->client->getCurrencyId()); $this->initClosure($invoice); foreach ($invoice->invitations as $invitation) { if (!$invitation->user || !$invitation->user->email || $invitation->user->trashed()) { return false; } if (!$invitation->contact || !$invitation->contact->email || $invitation->contact->trashed()) { return false; } $invitation->sent_date = \Carbon::now()->toDateTimeString(); $invitation->save(); $variables = [ '$footer' => $invoice->account->getEmailFooter(), '$link' => $invitation->getLink(), '$client' => $invoice->client->getDisplayName(), '$account' => $accountName, '$contact' => $invitation->contact->getDisplayName(), '$amount' => $invoiceAmount, '$advancedRawInvoice->' => '$' ]; // Add variables for available payment types foreach (Gateway::getPaymentTypeLinks() as $type) { $variables["\${$type}_link"] = URL::to("/payment/{$invitation->invitation_key}/{$type}"); } $data['body'] = str_replace(array_keys($variables), array_values($variables), $emailTemplate); $data['body'] = preg_replace_callback('/\{\{\$?(.*)\}\}/', $this->advancedTemplateHandler, $data['body']); $data['link'] = $invitation->getLink(); $data['entityType'] = $entityType; $data['invoice_id'] = $invoice->id; $fromEmail = $invitation->user->email; $response = $this->sendTo($invitation->contact->email, $fromEmail, $accountName, $subject, $view, $data); if ($response !== true) { return $response; } Activity::emailInvoice($invitation); } if (!$invoice->isSent()) { $invoice->invoice_status_id = INVOICE_STATUS_SENT; $invoice->save(); } Event::fire(new InvoiceSent($invoice)); return $response; } public function sendPaymentConfirmation(Payment $payment) { $invoice = $payment->invoice; $view = 'payment_confirmation'; $subject = trans('texts.payment_subject', ['invoice' => $invoice->invoice_number]); $accountName = $payment->account->getDisplayName(); $emailTemplate = $invoice->account->getEmailTemplate(ENTITY_PAYMENT); $variables = [ '$footer' => $payment->account->getEmailFooter(), '$client' => $payment->client->getDisplayName(), '$account' => $accountName, '$amount' => Utils::formatMoney($payment->amount, $payment->client->getCurrencyId()) ]; $data = ['body' => str_replace(array_keys($variables), array_values($variables), $emailTemplate)]; if ($payment->invitation) { $user = $payment->invitation->user; $contact = $payment->contact; } else { $user = $payment->user; $contact = $payment->client->contacts[0]; } if ($user->email && $contact->email) { $this->sendTo($contact->email, $user->email, $accountName, $subject, $view, $data); } } public function sendLicensePaymentConfirmation($name, $email, $amount, $license, $productId) { $view = 'license_confirmation'; $subject = trans('texts.payment_subject'); if ($productId == PRODUCT_ONE_CLICK_INSTALL) { $license = "Softaculous install license: $license"; } elseif ($productId == PRODUCT_INVOICE_DESIGNS) { $license = "Invoice designs license: $license"; } elseif ($productId == PRODUCT_WHITE_LABEL) { $license = "White label license: $license"; } $data = [ 'account' => trans('texts.email_from'), 'client' => $name, 'amount' => Utils::formatMoney($amount, 1), 'license' => $license ]; $this->sendTo($email, CONTACT_EMAIL, CONTACT_NAME, $subject, $view, $data); } private function initClosure($object) { $this->advancedTemplateHandler = function($match) use ($object) { for ($i = 1; $i < count($match); $i++) { $blobConversion = $match[$i]; if (isset($$blobConversion)) { return $$blobConversion; } else if (preg_match('/trans\(([\w\.]+)\)/', $blobConversion, $regexTranslation)) { return trans($regexTranslation[1]); } else if (strpos($blobConversion, '->') !== false) { return Utils::stringToObjectResolution($object, $blobConversion); } } }; } } <file_sep>/app/Models/Client.php <?php namespace App\Models; use DB; use Illuminate\Database\Eloquent\SoftDeletes; class Client extends EntityModel { use SoftDeletes; protected $dates = ['deleted_at']; public static $fieldName = 'Client - Name'; public static $fieldPhone = 'Client - Phone'; public static $fieldAddress1 = 'Client - Street'; public static $fieldAddress2 = 'Client - Apt/Floor'; public static $fieldCity = 'Client - City'; public static $fieldState = 'Client - State'; public static $fieldPostalCode = 'Client - Postal Code'; public static $fieldNotes = 'Client - Notes'; public static $fieldCountry = 'Client - Country'; public function account() { return $this->belongsTo('App\Models\Account'); } public function invoices() { return $this->hasMany('App\Models\Invoice'); } public function payments() { return $this->hasMany('App\Models\Payment'); } public function contacts() { return $this->hasMany('App\Models\Contact'); } public function projects() { return $this->hasMany('App\Models\Project'); } public function country() { return $this->belongsTo('App\Models\Country'); } public function currency() { return $this->belongsTo('App\Models\Currency'); } public function size() { return $this->belongsTo('App\Models\Size'); } public function industry() { return $this->belongsTo('App\Models\Industry'); } public function getTotalCredit() { return DB::table('credits') ->where('client_id', '=', $this->id) ->whereNull('deleted_at') ->sum('balance'); } public function getName() { return $this->name; } public function getDisplayName() { if ($this->name) { return $this->name; } $contact = $this->contacts()->first(); return $contact->getDisplayName(); } public function getEntityType() { return ENTITY_CLIENT; } public function getWebsite() { if (!$this->website) { return ''; } $link = $this->website; $title = $this->website; $prefix = 'http://'; if (strlen($link) > 7 && substr($link, 0, 7) === $prefix) { $title = substr($title, 7); } else { $link = $prefix.$link; } return link_to($link, $title, array('target' => '_blank')); } public function getDateCreated() { if ($this->created_at == '0000-00-00 00:00:00') { return '---'; } else { return $this->created_at->format('m/d/y h:i a'); } } public function getGatewayToken() { $this->account->load('account_gateways'); if (!count($this->account->account_gateways)) { return false; } $accountGateway = $this->account->getGatewayConfig(GATEWAY_STRIPE); if (!$accountGateway) { return false; } $token = AccountGatewayToken::where('client_id', '=', $this->id) ->where('account_gateway_id', '=', $accountGateway->id)->first(); return $token ? $token->token : false; } public function getGatewayLink() { $token = $this->getGatewayToken(); return $token ? "https://dashboard.stripe.com/customers/{$token}" : false; } public function getCurrencyId() { if ($this->currency_id) { return $this->currency_id; } if (!$this->account) { $this->load('account'); } return $this->account->currency_id ?: DEFAULT_CURRENCY; } } /* Client::created(function($client) { Activity::createClient($client); }); */ Client::updating(function ($client) { Activity::updateClient($client); }); Client::deleting(function ($client) { Activity::archiveClient($client); }); /*Client::restoring(function ($client) { Activity::restoreClient($client); }); */<file_sep>/app/Http/Middleware/ApiCheck.php <?php namespace App\Http\Middleware; use Closure; use Utils; use Request; use Session; use Response; use Auth; use Cache; use App\Models\AccountToken; class ApiCheck { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $headers = Utils::getApiHeaders(); // check for a valid token $token = AccountToken::where('token', '=', Request::header('X-Ninja-Token'))->first(['id', 'user_id']); if ($token) { Auth::loginUsingId($token->user_id); Session::set('token_id', $token->id); } else { sleep(3); return Response::make('Invalid token', 403, $headers); } if (!Utils::isNinja()) { return $next($request); } if (!Utils::isPro()) { return Response::make('API requires pro plan', 403, $headers); } else { $accountId = Auth::user()->account->id; // http://stackoverflow.com/questions/1375501/how-do-i-throttle-my-sites-api-users $hour = 60 * 60; $hour_limit = 100; # users are limited to 100 requests/hour $hour_throttle = Cache::get("hour_throttle:{$accountId}", null); $last_api_request = Cache::get("last_api_request:{$accountId}", 0); $last_api_diff = time() - $last_api_request; if (is_null($hour_throttle)) { $new_hour_throttle = 0; } else { $new_hour_throttle = $hour_throttle - $last_api_diff; $new_hour_throttle = $new_hour_throttle < 0 ? 0 : $new_hour_throttle; $new_hour_throttle += $hour / $hour_limit; $hour_hits_remaining = floor(( $hour - $new_hour_throttle ) * $hour_limit / $hour); $hour_hits_remaining = $hour_hits_remaining >= 0 ? $hour_hits_remaining : 0; } if ($new_hour_throttle > $hour) { $wait = ceil($new_hour_throttle - $hour); sleep(1); return Response::make("Please wait {$wait} second(s)", 403, $headers); } Cache::put("hour_throttle:{$accountId}", $new_hour_throttle, 10); Cache::put("last_api_request:{$accountId}", time(), 10); } return $next($request); } }<file_sep>/tests/acceptance/InvoiceDesignCest.php <?php require_once __DIR__ . '/../helpers/Helper.php'; use \AcceptanceTester; use Faker\Factory; class InvoiceDesignCest { private $faker; public function _before(AcceptanceTester $I) { $I->checkIfLogin($I); $this->faker = Factory::create(); } public function _after(AcceptanceTester $I) { } // tests public function updateInvoiceDesign(AcceptanceTester $I) { $I->wantTo('Design my invoice'); $I->amOnPage('/company/advanced_settings/invoice_design'); $I->click('select#invoice_design_id'); $I->click('select#invoice_design_id option:nth-child(2)'); $I->fillField('#font_size', 10); $I->click('#primary_color + .sp-replacer'); $I->executeJS('$("#primary_color").val("#7364b6")'); //$I->executeJS('$("#primary_color + .sp-replacer .sp-preview-inner").attr("style", "background-color: rgb(0,98,254);")'); $I->executeJS('$(".sp-container:nth-child(1) .sp-choose").click()'); $I->click('#secondary_color + .sp-replacer'); $I->executeJS('$("#secondary_color").val("#aa6709")'); //$I->executeJS('$("#secondary_color + .sp-replacer .sp-preview-inner").attr("style", "background-color: rgb(254,0,50);")'); $I->executeJS('$(".sp-container:nth-child(2) .sp-choose").click()'); $I->fillField(['name' => 'labels_item'], $this->faker->text(6)); $I->fillField(['name' => 'labels_description'], $this->faker->text(12)); $I->fillField(['name' => 'labels_unit_cost'], $this->faker->text(12)); $I->fillField(['name' => 'labels_quantity'], $this->faker->text(8)); $I->uncheckOption('#hide_quantity'); $I->checkOption('#hide_paid_to_date'); $I->click('Save'); $I->wait(3); $I->seeInDatabase('accounts', ['font_size' => 10]); } }<file_sep>/app/Http/Controllers/TaskController.php <?php namespace App\Http\Controllers; use Auth; use View; use URL; use Utils; use Input; use Datatable; use Validator; use Redirect; use Session; use DropdownButton; use DateTime; use DateTimeZone; use App\Models\Client; use App\Models\Task; use App\Ninja\Repositories\TaskRepository; use App\Ninja\Repositories\InvoiceRepository; class TaskController extends BaseController { protected $taskRepo; public function __construct(TaskRepository $taskRepo, InvoiceRepository $invoiceRepo) { parent::__construct(); $this->taskRepo = $taskRepo; $this->invoiceRepo = $invoiceRepo; } /** * Display a listing of the resource. * * @return Response */ public function index() { self::checkTimezone(); return View::make('list', array( 'entityType' => ENTITY_TASK, 'title' => trans('texts.tasks'), 'sortCol' => '2', 'columns' => Utils::trans(['checkbox', 'client', 'date', 'duration', 'description', 'status', 'action']), )); } public function getDatatable($clientPublicId = null) { $tasks = $this->taskRepo->find($clientPublicId, Input::get('sSearch')); $table = Datatable::query($tasks); if (!$clientPublicId) { $table->addColumn('checkbox', function ($model) { return '<input type="checkbox" name="ids[]" value="'.$model->public_id.'" '.Utils::getEntityRowClass($model).'>'; }) ->addColumn('client_name', function ($model) { return $model->client_public_id ? link_to('clients/'.$model->client_public_id, Utils::getClientDisplayName($model)) : ''; }); } return $table->addColumn('created_at', function($model) { return Task::calcStartTime($model); }) ->addColumn('time_log', function($model) { return gmdate('H:i:s', Task::calcDuration($model)); }) ->addColumn('description', function($model) { return $model->description; }) ->addColumn('invoice_number', function($model) { return self::getStatusLabel($model); }) ->addColumn('dropdown', function ($model) { $str = '<div class="btn-group tr-action" style="visibility:hidden;"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> '.trans('texts.select').' <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu">'; if (!$model->deleted_at || $model->deleted_at == '0000-00-00') { $str .= '<li><a href="'.URL::to('tasks/'.$model->public_id.'/edit').'">'.trans('texts.edit_task').'</a></li>'; } if ($model->invoice_number) { $str .= '<li>' . link_to("/invoices/{$model->invoice_public_id}/edit", trans('texts.view_invoice')) . '</li>'; } elseif ($model->is_running) { $str .= '<li><a href="javascript:stopTask('.$model->public_id.')">'.trans('texts.stop_task').'</a></li>'; } elseif (!$model->deleted_at || $model->deleted_at == '0000-00-00') { $str .= '<li><a href="javascript:invoiceTask('.$model->public_id.')">'.trans('texts.invoice_task').'</a></li>'; } if (!$model->deleted_at || $model->deleted_at == '0000-00-00') { $str .= '<li class="divider"></li> <li><a href="javascript:archiveEntity('.$model->public_id.')">'.trans('texts.archive_task').'</a></li>'; } else { $str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans('texts.restore_task').'</a></li>'; } if (!$model->is_deleted) { $str .= '<li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans('texts.delete_task').'</a></li></ul>'; } return $str . '</div>'; }) ->make(); } private function getStatusLabel($model) { if ($model->invoice_number) { $class = 'success'; $label = trans('texts.invoiced'); } elseif ($model->is_running) { $class = 'primary'; $label = trans('texts.running'); } else { $class = 'default'; $label = trans('texts.logged'); } return "<h4><div class=\"label label-{$class}\">$label</div></h4>"; } /** * Store a newly created resource in storage. * * @return Response */ public function store() { return $this->save(); } /** * Show the form for creating a new resource. * * @return Response */ public function create($clientPublicId = 0) { self::checkTimezone(); $data = [ 'task' => null, 'clientPublicId' => Input::old('client') ? Input::old('client') : $clientPublicId, 'method' => 'POST', 'url' => 'tasks', 'title' => trans('texts.new_task'), 'minuteOffset' => Utils::getTiemstampOffset(), ]; $data = array_merge($data, self::getViewModel()); return View::make('tasks.edit', $data); } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($publicId) { self::checkTimezone(); $task = Task::scope($publicId)->with('client', 'invoice')->firstOrFail(); $actions = []; if ($task->invoice) { $actions[] = ['url' => URL::to("inovices/{$task->invoice->public_id}/edit"), 'label' => trans("texts.view_invoice")]; } else { $actions[] = ['url' => 'javascript:submitAction("invoice")', 'label' => trans("texts.create_invoice")]; // check for any open invoices $invoices = $task->client_id ? $this->invoiceRepo->findOpenInvoices($task->client_id) : []; foreach ($invoices as $invoice) { $actions[] = ['url' => 'javascript:submitAction("add_to_invoice", '.$invoice->public_id.')', 'label' => trans("texts.add_to_invoice", ["invoice" => $invoice->invoice_number])]; } } $actions[] = DropdownButton::DIVIDER; if (!$task->trashed()) { $actions[] = ['url' => 'javascript:submitAction("archive")', 'label' => trans('texts.archive_task')]; $actions[] = ['url' => 'javascript:onDeleteClick()', 'label' => trans('texts.delete_task')]; } else { $actions[] = ['url' => 'javascript:submitAction("restore")', 'label' => trans('texts.restore_task')]; } $data = [ 'task' => $task, 'clientPublicId' => $task->client ? $task->client->public_id : 0, 'method' => 'PUT', 'url' => 'tasks/'.$publicId, 'title' => trans('texts.edit_task'), 'duration' => $task->is_running ? $task->getCurrentDuration() : $task->getDuration(), 'actions' => $actions, 'minuteOffset' => Utils::getTiemstampOffset(), ]; $data = array_merge($data, self::getViewModel()); return View::make('tasks.edit', $data); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($publicId) { return $this->save($publicId); } private static function getViewModel() { return [ 'clients' => Client::scope()->with('contacts')->orderBy('name')->get() ]; } private function save($publicId = null) { $action = Input::get('action'); if (in_array($action, ['archive', 'delete', 'invoice', 'restore', 'add_to_invoice'])) { return self::bulk(); } $task = $this->taskRepo->save($publicId, Input::all()); Session::flash('message', trans($publicId ? 'texts.updated_task' : 'texts.created_task')); return Redirect::to("tasks/{$task->public_id}/edit"); } public function bulk() { $action = Input::get('action'); $ids = Input::get('id') ? Input::get('id') : Input::get('ids'); if ($action == 'stop') { $this->taskRepo->save($ids, ['action' => $action]); Session::flash('message', trans('texts.stopped_task')); return Redirect::to('tasks'); } else if ($action == 'invoice' || $action == 'add_to_invoice') { $tasks = Task::scope($ids)->with('client')->get(); $clientPublicId = false; $data = []; foreach ($tasks as $task) { if ($task->client) { if (!$clientPublicId) { $clientPublicId = $task->client->public_id; } else if ($clientPublicId != $task->client->public_id) { Session::flash('error', trans('texts.task_error_multiple_clients')); return Redirect::to('tasks'); } } if ($task->is_running) { Session::flash('error', trans('texts.task_error_running')); return Redirect::to('tasks'); } else if ($task->invoice_id) { Session::flash('error', trans('texts.task_error_invoiced')); return Redirect::to('tasks'); } $data[] = [ 'publicId' => $task->public_id, 'description' => $task->description, 'startTime' => $task->getStartTime(), 'duration' => $task->getHours(), ]; } if ($action == 'invoice') { return Redirect::to("invoices/create/{$clientPublicId}")->with('tasks', $data); } else { $invoiceId = Input::get('invoice_id'); return Redirect::to("invoices/{$invoiceId}/edit")->with('tasks', $data); } } else { $count = $this->taskRepo->bulk($ids, $action); $message = Utils::pluralize($action.'d_task', $count); Session::flash('message', $message); if ($action == 'restore' && $count == 1) { return Redirect::to('tasks/'.$ids[0].'/edit'); } else { return Redirect::to('tasks'); } } } private function checkTimezone() { if (!Auth::user()->account->timezone) { $link = link_to('/company/details?focus=timezone_id', trans('texts.click_here'), ['target' => '_blank']); Session::flash('warning', trans('texts.timezone_unset', ['link' => $link])); } } } <file_sep>/readme.md # Invoice Ninja ### [https://www.invoiceninja.com](https://www.invoiceninja.com) If you'd like to use our code to sell your own invoicing app email us for details about our affiliate program. ### Installation Options * [Zip - Free](https://www.invoiceninja.com/knowledgebase/self-host/) * [Bitnami - Free](https://bitnami.com/stack/invoice-ninja) * [Softaculous - $30](https://www.softaculous.com/apps/ecommerce/Invoice_Ninja) ### Getting Started If you have any questions or comments please use our [support forum](https://www.invoiceninja.com/forums/forum/support/). For updates follow [@invoiceninja](https://twitter.com/invoiceninja) or join the [Facebook Group](https://www.facebook.com/invoiceninja). If you'd like to translate the site please use [caouecs/Laravel4-long](https://github.com/caouecs/Laravel4-lang) for the starter files. ### Features * Built using Laravel 5 * Live PDF generation * Integrates with 30+ payment providers * Recurring invoices * Tasks with time-tracking * Multi-user support * Tax rates and payment terms * Partial payments * Custom email templates * [Zapier](https://zapier.com/) integration * [D3.js](http://d3js.org/) visualizations ### Contributors * [<NAME>](https://github.com/tlbdk) * [<NAME>](https://github.com/JeramyMywork) - [MyWork](https://www.mywork.com.au) * [<NAME>](https://lt.linkedin.com/in/sigitaslimontas) ### Documentation * [Ubuntu and Apache](http://blog.technerdservices.com/index.php/2015/04/techpop-how-to-install-invoice-ninja-on-ubuntu-14-04/) * [Debian and Nginx](https://www.rosehosting.com/blog/install-invoice-ninja-on-a-debian-7-vps/) * [API Documentation](https://www.invoiceninja.com/knowledgebase/api-documentation/) * [User Guide](https://www.invoiceninja.com/user-guide/) * [Developer Guide](https://www.invoiceninja.com/knowledgebase/developer-guide/) ### Frameworks/Libraries * [laravel/laravel](https://github.com/laravel/laravel) - A PHP Framework For Web Artisans * [twbs/bootstrap](https://github.com/twbs/bootstrap) - Sleek, intuitive, and powerful front-end framework for faster and easier web development. * [patricktalmadge/bootstrapper](https://github.com/patricktalmadge/bootstrapper) - Laravel Twitter Bootstrap Bundle * [danielfarrell/bootstrap-combobox](https://github.com/danielfarrell/bootstrap-combobox) - A combobox plugin * [jquery/jquery](https://github.com/jquery/jquery) - jQuery JavaScript Library * [eternicode/bootstrap-datepicker](https://github.com/eternicode/bootstrap-datepicker) - A datepicker for @twitter bootstrap * [jquery/jquery-ui](https://github.com/jquery/jquery-ui) - The official jQuery user interface library * [knockout/knockout](https://github.com/knockout/knockout) - Knockout makes it easier to create rich, responsive UIs with JavaScript * [rniemeyer/knockout-sortable](https://github.com/rniemeyer/knockout-sortable) - A Knockout.js binding to connect observableArrays with jQuery UI sortable functionality * [MrRio/jsPDF](https://github.com/MrRio/jsPDF) - Generate PDF files in JavaScript. HTML5 FTW. * [bpampuch/pdfmake](https://github.com/bpampuch/pdfmake) - Client/server side PDF printing in pure JavaScript * [FortAwesome/Font-Awesome](https://github.com/FortAwesome/Font-Awesome) - The iconic font designed for Bootstrap that works with twitter bootstrap * [Anahkiasen/former](https://github.com/Anahkiasen/former) - A powerful form builder, for Laravel and other frameworks (stand-alone too) * [barryvdh/laravel-debugbar](https://github.com/barryvdh/laravel-debugbar) - Laravel debugbar * [DataTables/DataTables](https://github.com/DataTables/DataTables) - Tables plug-in for jQuery * [Chumper/Datatable](https://github.com/Chumper/Datatable) - This is a laravel 4 package for the server and client side of datatables * [omnipay/omnipay](https://github.com/omnipay/omnipay) - A framework agnostic, multi-gateway payment processing library for PHP 5.3+ * [Intervention/image](https://github.com/Intervention/image) - PHP Image Manipulation * [webpatser/laravel-countries](https://github.com/webpatser/laravel-countries) - Almost ISO 3166_2, 3166_3, currency, Capital and more for all countries * [briannesbitt/Carbon](https://github.com/briannesbitt/Carbon) - A simple API extension for DateTime with PHP 5.3+ * [thomaspark/bootswatch](https://github.com/thomaspark/bootswatch) - Themes for Bootstrap * [mozilla/pdf.js](https://github.com/mozilla/pdf.js) - PDF Reader in JavaScript * [nnnick/Chart.js](https://github.com/nnnick/Chart.js) - Simple HTML5 Charts using the canvas tag * [josscrowcroft/accounting.js](https://github.com/josscrowcroft/accounting.js) - A lightweight JavaScript library for number, money and currency formatting * [jashkenas/underscore](https://github.com/jashkenas/underscore) - JavaScript's utility _ belt * [caouecs/Laravel4-long](https://github.com/caouecs/Laravel4-lang) - List of languages ​​for Laravel4 * [bgrins/spectrum](https://github.com/bgrins/spectrum) - The No Hassle JavaScript Colorpicker * [lokesh/lightbox2](https://github.com/lokesh/lightbox2/) - The original lightbox script * [josdejong/jsoneditor](https://github.com/josdejong/jsoneditor/) - A web-based tool to view, edit and format JSON<file_sep>/database/seeds/SecurePaymentFormSeeder.php <?php /** * Adds data to invitation for a user/client so that the * public/payment/{aaabbb} page is accessable (aaabbb is the invitation_key) **/ class SecurePaymentFormSeeder extends Seeder { public function run() { Eloquent::unguard(); //Delete table content DB::table('invitations')->delete(); DB::table('invoices')->delete(); DB::table('contacts')->delete(); DB::table('clients')->delete(); DB::table('account_gateways')->delete(); //To reset the auto increment $statement = " ALTER TABLE invitations AUTO_INCREMENT = 1; ALTER TABLE invoices AUTO_INCREMENT = 1; ALTER TABLE contacts AUTO_INCREMENT = 1; ALTER TABLE clients AUTO_INCREMENT = 1; ALTER TABLE account_gateways AUTO_INCREMENT = 1; "; DB::unprepared($statement); //$firstName = 'Oscar'; // $lastName = 'Thompson'; // $firstName_2 = 'Philip'; // $lastName_2 = 'Jonsson'; // // $user = AccountGateway::create(array( // 'account_id' => 1, // 'user_id' => 1, // 'gateway_id' => 4, // 'config' => '{"bla":"vla","bli":"cla"}', // 'public_id' => 1, // 'accepted_credit_cards' => 8 // )); // // $user2 = AccountGateway::create(array( // 'account_id' => 2, // 'user_id' => 2, // 'gateway_id' => 5, // 'config' => '{"bla":"vla","bli":"cla"}', // 'public_id' => 2, // 'accepted_credit_cards' => 7 // )); // // $client = Client::create(array( // 'user_id' => 1, // 'account_id' => 1, // 'currency_id' => 1, // 'name' => $firstName.' '.$lastName, // 'address1' => '2119 Howe Course', // 'address2' => '2118 Howe Course', // 'city' => 'West Chazport', // 'state' => 'Utah', // 'postal_code' => '31572', // 'country_id' => 752, // 'work_phone' => '012-345678', // 'private_notes' => 'bla bla bla bla bla bla bla', // 'balance' => 10.4, // 'paid_to_date' => 10.2, // 'website' => 'awebsite.com', // 'industry_id' => 8, // 'is_deleted' => 0, // 'payment_terms' => 2, // 'public_id' => 1, // 'custom_value1' => $firstName, // 'custom_value2' => $firstName // )); // // $client2 = Client::create(array( // 'user_id' => 2, // 'account_id' => 2, // 'currency_id' => 1, // 'name' => $firstName_2.' '.$lastName_2, // 'address1' => '1118 Muma Road', // 'address2' => '1118 Muma Road', // 'city' => 'New Orleans', // 'state' => 'Arizona', // 'postal_code' => '31572', // 'country_id' => 752, // 'work_phone' => '012-345678', // 'private_notes' => 'bla bla bla bla bla bla bla', // 'balance' => 10.4, // 'paid_to_date' => 10.2, // 'website' => 'bodosite.com', // 'industry_id' => 8, // 'is_deleted' => 0, // 'payment_terms' => 2, // 'public_id' => 1, // 'custom_value1' => $firstName_2, // 'custom_value2' => $firstName_2 // )); // // $contact = Contact::create(array( // 'account_id' => 1, // 'user_id' => 1, // 'client_id' => 1, // 'is_primary' => 0, // 'send_invoice' => 0, // 'first_name' => $firstName, // 'last_name' => $lastName, // 'email' => '<EMAIL>', // 'phone' => '012-345678', // 'public_id' => 1 // )); // // $contact2 = Contact::create(array( // 'account_id' => 2, // 'user_id' => 2, // 'client_id' => 2, // 'is_primary' => 0, // 'send_invoice' => 0, // 'first_name' => $firstName_2, // 'last_name' => $lastName_2, // 'email' => '<EMAIL>', // 'phone' => '012-345678', // 'public_id' => 2 // )); // // $invoice = Invoice::create(array( // 'client_id' => 1, // 'user_id' => 1, // 'account_id' => 1, // 'invoice_number' => 1, // 'discount' => 0.4, // 'po_number' => $firstName, // 'terms' => 'bla bla bla bla bla bla bla', // 'public_notes' => 'bla bla bla bla bla bla bla', // 'is_deleted' => 0, // 'is_recurring' => 0, // 'frequency_id' => 1, // 'tax_name' => 'moms', // 'tax_rate' => 33.0, // 'amount' => 10.0, // 'balance' => 8.0, // 'public_id' => 1, // 'is_quote' => 0 // )); // // $invoice2 = Invoice::create(array( // 'client_id' => 2, // 'user_id' => 2, // 'account_id' => 2, // 'invoice_number' => 2, // 'discount' => 0.4, // 'po_number' => $firstName_2, // 'terms' => 'bla bla bla bla bla bla bla', // 'public_notes' => 'bla bla bla bla bla bla bla', // 'is_deleted' => 0, // 'is_recurring' => 0, // 'frequency_id' => 1, // 'tax_name' => 'moms', // 'tax_rate' => 33.0, // 'amount' => 10.0, // 'balance' => 8.0, // 'public_id' => 2, // 'is_quote' => 0 // )); // // $invitation = Invitation::create(array( // 'account_id' => 1, // 'user_id' => 1, // 'contact_id' => 1, // 'invoice_id' => 1, // 'invitation_key' => 'aaabbb', // 'transaction_reference' => 'bla bla bla bla bla bla bla', // 'public_id' => 1 // )); // // $invitation2 = Invitation::create(array( // 'account_id' => 2, // 'user_id' => 2, // 'contact_id' => 2, // 'invoice_id' => 2, // 'invitation_key' => 'cccddd', // 'transaction_reference' => 'bla bla bla bla bla bla bla', // 'public_id' => 2 // )); } }<file_sep>/app/Http/Controllers/AppController.php <?php namespace App\Http\Controllers; use Auth; use Artisan; use Cache; use Config; use DB; use Exception; use Input; use Utils; use View; use Session; use Cookie; use Response; use App\Models\User; use App\Models\Account; use App\Models\Industry; use App\Ninja\Mailers\Mailer; use App\Ninja\Repositories\AccountRepository; use Redirect; class AppController extends BaseController { protected $accountRepo; protected $mailer; public function __construct(AccountRepository $accountRepo, Mailer $mailer) { parent::__construct(); $this->accountRepo = $accountRepo; $this->mailer = $mailer; } public function showSetup() { if (Utils::isNinjaProd() || (Utils::isDatabaseSetup() && Account::count() > 0)) { return Redirect::to('/'); } return View::make('setup'); } public function doSetup() { if (Utils::isNinjaProd() || (Utils::isDatabaseSetup() && Account::count() > 0)) { return Redirect::to('/'); } $valid = false; $test = Input::get('test'); $app = Input::get('app'); $app['key'] = str_random(RANDOM_KEY_LENGTH); $database = Input::get('database'); $dbType = $database['default']; $database['connections'] = [$dbType => $database['type']]; $mail = Input::get('mail'); $email = $mail['username']; $mail['from']['address'] = $email; if ($test == 'mail') { return self::testMail($mail); } $valid = self::testDatabase($database); if ($test == 'db') { return $valid === true ? 'Success' : $valid; } elseif (!$valid) { return Redirect::to('/setup')->withInput(); } $config = "APP_ENV=production\n". "APP_DEBUG=false\n". "APP_URL={$app['url']}\n". "APP_KEY={$app['key']}\n\n". "DB_TYPE={$dbType}\n". "DB_HOST={$database['type']['host']}\n". "DB_DATABASE={$database['type']['database']}\n". "DB_USERNAME={$database['type']['username']}\n". "DB_PASSWORD={$database['type']['password']}\n\n". "MAIL_DRIVER={$mail['driver']}\n". "MAIL_PORT={$mail['port']}\n". "MAIL_ENCRYPTION={$mail['encryption']}\n". "MAIL_HOST={$mail['host']}\n". "MAIL_USERNAME={$mail['username']}\n". "MAIL_FROM_NAME={$mail['from']['name']}\n". "MAIL_PASSWORD={$mail['password']}"; // Write Config Settings $fp = fopen(base_path()."/.env", 'w'); fwrite($fp, $config); fclose($fp); // == DB Migrate & Seed == // // Artisan::call('migrate:rollback', array('--force' => true)); // Debug Purposes Artisan::call('migrate', array('--force' => true)); if (Industry::count() == 0) { Artisan::call('db:seed', array('--force' => true)); } Artisan::call('optimize', array('--force' => true)); $firstName = trim(Input::get('first_name')); $lastName = trim(Input::get('last_name')); $email = trim(strtolower(Input::get('email'))); $password = trim(Input::get('password')); $account = $this->accountRepo->create($firstName, $lastName, $email, $password); $user = $account->users()->first(); return Redirect::to('/login'); } private function testDatabase($database) { $dbType = $database['default']; Config::set('database.default', $dbType); foreach ($database['connections'][$dbType] as $key => $val) { Config::set("database.connections.{$dbType}.{$key}", $val); } try { $valid = DB::connection()->getDatabaseName() ? true : false; } catch (Exception $e) { return $e->getMessage(); } return $valid; } private function testMail($mail) { $email = $mail['username']; $fromName = $mail['from']['name']; foreach ($mail as $key => $val) { Config::set("mail.{$key}", $val); } Config::set('mail.from.address', $email); Config::set('mail.from.name', $fromName); $data = [ 'text' => 'Test email', ]; try { $this->mailer->sendTo($email, $email, $fromName, 'Test email', 'contact', $data); return 'Sent'; } catch (Exception $e) { return $e->getMessage(); } } public function install() { if (!Utils::isNinjaProd() && !Utils::isDatabaseSetup()) { try { Artisan::call('migrate', array('--force' => true)); if (Industry::count() == 0) { Artisan::call('db:seed', array('--force' => true)); } Artisan::call('optimize', array('--force' => true)); } catch (Exception $e) { Response::make($e->getMessage(), 500); } } return Redirect::to('/'); } public function update() { if (!Utils::isNinjaProd()) { try { Artisan::call('migrate', array('--force' => true)); Artisan::call('db:seed', array('--force' => true, '--class' => 'PaymentLibrariesSeeder')); Artisan::call('optimize', array('--force' => true)); Cache::flush(); Session::flash('message', trans('texts.processed_updates')); } catch (Exception $e) { Response::make($e->getMessage(), 500); } } return Redirect::to('/'); } } <file_sep>/database/migrations/2015_02_17_131714_support_token_billing.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class SupportTokenBilling extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('accounts', function($table) { $table->smallInteger('token_billing_type_id')->default(TOKEN_BILLING_OPT_IN); }); Schema::create('account_gateway_tokens', function($table) { $table->increments('id'); $table->unsignedInteger('account_id'); $table->unsignedInteger('contact_id'); $table->unsignedInteger('account_gateway_id'); $table->unsignedInteger('client_id'); $table->string('token'); $table->timestamps(); $table->softDeletes(); $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); $table->foreign('contact_id')->references('id')->on('contacts')->onDelete('cascade'); $table->foreign('account_gateway_id')->references('id')->on('account_gateways')->onDelete('cascade'); $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade'); }); DB::table('accounts')->update(['token_billing_type_id' => TOKEN_BILLING_OPT_IN]); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('accounts', function($table) { $table->dropColumn('token_billing_type_id'); }); Schema::drop('account_gateway_tokens'); } }<file_sep>/tests/acceptance/TaskCest.php <?php use \AcceptanceTester; use Faker\Factory; class TaskCest { /** * @var \Faker\Generator */ private $faker; public function _before(AcceptanceTester $I) { $I->checkIfLogin($I); $this->faker = Factory::create(); } public function createTimerTask(AcceptanceTester $I) { $description = $this->faker->text(100); $I->wantTo('create a timed task'); $I->amOnPage('/tasks/create'); $I->seeCurrentUrlEquals('/tasks/create'); $I->fillField('#description', $description); $I->click('Start'); $I->wait(rand(2, 5)); $I->click('Stop'); $I->click('Save'); $I->seeInDatabase('tasks', ['description' => $description]); } public function createManualTask(AcceptanceTester $I) { $description = $this->faker->text(100); $I->wantTo('create a manual task'); $I->amOnPage('/tasks/create'); $I->seeCurrentUrlEquals('/tasks/create'); $I->selectOption('#task_type3', 'Manual'); $I->fillField('#description', $description); $I->click('Save'); $I->seeInDatabase('tasks', ['description' => $description]); } public function editTask(AcceptanceTester $I) { $description = $this->faker->text(100); $I->wantTo('edit a task'); $I->amOnPage('/tasks/1/edit'); $I->seeCurrentUrlEquals('/tasks/1/edit'); $I->fillField('#description', $description); $I->click('Save'); $I->seeInDatabase('tasks', ['description' => $description]); } public function listTasks(AcceptanceTester $I) { $I->wantTo("list tasks"); $I->amOnPage('/tasks'); $I->seeNumberOfElements('tbody tr[role=row]', [1, 10]); } /* public function deleteTask(AcceptanceTester $I) { $I->wantTo('delete a Task'); $I->amOnPage('/tasks'); $task_id = Helper::getRandom('Task', 'public_id'); //delete task $I->executeJS(sprintf('deleteEntity(%d)', $task_id)); $I->acceptPopup(); //check if Task was delete $I->wait(2); $I->seeInDatabase('tasks', ['public_id' => $task_id, 'is_deleted' => true]); } */ } <file_sep>/app/Http/Controllers/ProductController.php <?php namespace App\Http\Controllers; use Auth; use Str; use DB; use Datatable; use Utils; use URL; use View; use Input; use Session; use Redirect; use App\Models\Product; class ProductController extends BaseController { public function getDatatable() { $query = DB::table('products') ->where('products.account_id', '=', Auth::user()->account_id) ->where('products.deleted_at', '=', null) ->select('products.public_id', 'products.product_key', 'products.notes', 'products.cost'); return Datatable::query($query) ->addColumn('product_key', function ($model) { return link_to('products/'.$model->public_id.'/edit', $model->product_key); }) ->addColumn('notes', function ($model) { return nl2br(Str::limit($model->notes, 100)); }) ->addColumn('cost', function ($model) { return Utils::formatMoney($model->cost); }) ->addColumn('dropdown', function ($model) { return '<div class="btn-group tr-action" style="visibility:hidden;"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> '.trans('texts.select').' <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu"> <li><a href="'.URL::to('products/'.$model->public_id).'/edit">'.uctrans('texts.edit_product').'</a></li> <li class="divider"></li> <li><a href="'.URL::to('products/'.$model->public_id).'/archive">'.uctrans('texts.archive_product').'</a></li> </ul> </div>'; }) ->orderColumns(['cost', 'product_key', 'cost']) ->make(); } public function edit($publicId) { $data = [ 'showBreadcrumbs' => false, 'product' => Product::scope($publicId)->firstOrFail(), 'method' => 'PUT', 'url' => 'products/'.$publicId, 'title' => trans('texts.edit_product'), ]; return View::make('accounts.product', $data); } public function create() { $data = [ 'showBreadcrumbs' => false, 'product' => null, 'method' => 'POST', 'url' => 'products', 'title' => trans('texts.create_product'), ]; return View::make('accounts.product', $data); } public function store() { return $this->save(); } public function update($publicId) { return $this->save($publicId); } private function save($productPublicId = false) { if ($productPublicId) { $product = Product::scope($productPublicId)->firstOrFail(); } else { $product = Product::createNew(); } $product->product_key = trim(Input::get('product_key')); $product->notes = trim(Input::get('notes')); $product->cost = trim(Input::get('cost')); $product->save(); $message = $productPublicId ? trans('texts.updated_product') : trans('texts.created_product'); Session::flash('message', $message); return Redirect::to('company/products'); } public function archive($publicId) { $product = Product::scope($publicId)->firstOrFail(); $product->delete(); Session::flash('message', trans('texts.archived_product')); return Redirect::to('company/products'); } } <file_sep>/app/Http/Controllers/AccountGatewayController.php <?php namespace App\Http\Controllers; use Auth; use Datatable; use DB; use Input; use Redirect; use Session; use View; use Validator; use stdClass; use URL; use Utils; use App\Models\Gateway; use App\Models\Account; use App\Models\AccountGateway; use App\Ninja\Repositories\AccountRepository; class AccountGatewayController extends BaseController { public function getDatatable() { $query = DB::table('account_gateways') ->join('gateways', 'gateways.id', '=', 'account_gateways.gateway_id') ->where('account_gateways.deleted_at', '=', null) ->where('account_gateways.account_id', '=', Auth::user()->account_id) ->select('account_gateways.public_id', 'gateways.name', 'account_gateways.deleted_at', 'account_gateways.gateway_id'); return Datatable::query($query) ->addColumn('name', function ($model) { return link_to('gateways/'.$model->public_id.'/edit', $model->name); }) ->addColumn('payment_type', function ($model) { return Gateway::getPrettyPaymentType($model->gateway_id); }) ->addColumn('dropdown', function ($model) { $actions = '<div class="btn-group tr-action" style="visibility:hidden;"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> '.trans('texts.select').' <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu">'; if (!$model->deleted_at) { $actions .= '<li><a href="'.URL::to('gateways/'.$model->public_id).'/edit">'.uctrans('texts.edit_gateway').'</a></li> <li class="divider"></li> <li><a href="javascript:deleteAccountGateway('.$model->public_id.')">'.uctrans('texts.delete_gateway').'</a></li>'; } $actions .= '</ul> </div>'; return $actions; }) ->orderColumns(['name']) ->make(); } public function edit($publicId) { $accountGateway = AccountGateway::scope($publicId)->firstOrFail(); $config = $accountGateway->config; $selectedCards = $accountGateway->accepted_credit_cards; $configFields = json_decode($config); foreach ($configFields as $configField => $value) { $configFields->$configField = str_repeat('*', strlen($value)); } $data = self::getViewModel($accountGateway); $data['url'] = 'gateways/'.$publicId; $data['method'] = 'PUT'; $data['title'] = trans('texts.edit_gateway') . ' - ' . $accountGateway->gateway->name; $data['config'] = $configFields; $data['hiddenFields'] = Gateway::$hiddenFields; $data['paymentTypeId'] = $accountGateway->getPaymentType(); $data['selectGateways'] = Gateway::where('id', '=', $accountGateway->gateway_id)->get(); return View::make('accounts.account_gateway', $data); } public function update($publicId) { return $this->save($publicId); } public function store() { return $this->save(); } /** * Displays the form for account creation * */ public function create() { $data = self::getViewModel(); $data['url'] = 'gateways'; $data['method'] = 'POST'; $data['title'] = trans('texts.add_gateway'); $data['selectGateways'] = Gateway::where('payment_library_id', '=', 1)->where('id', '!=', GATEWAY_PAYPAL_EXPRESS)->where('id', '!=', GATEWAY_PAYPAL_EXPRESS)->orderBy('name')->get(); $data['hiddenFields'] = Gateway::$hiddenFields; return View::make('accounts.account_gateway', $data); } private function getViewModel($accountGateway = false) { $selectedCards = $accountGateway ? $accountGateway->accepted_credit_cards : 0; $account = Auth::user()->account; $paymentTypes = []; foreach (Gateway::$paymentTypes as $type) { if ($accountGateway || !$account->getGatewayByType($type)) { $paymentTypes[$type] = trans('texts.'.strtolower($type)); if ($type == PAYMENT_TYPE_BITCOIN) { $paymentTypes[$type] .= ' - BitPay'; } } } $creditCardsArray = unserialize(CREDIT_CARDS); $creditCards = []; foreach ($creditCardsArray as $card => $name) { if ($selectedCards > 0 && ($selectedCards & $card) == $card) { $creditCards[$name['text']] = ['value' => $card, 'data-imageUrl' => asset($name['card']), 'checked' => 'checked']; } else { $creditCards[$name['text']] = ['value' => $card, 'data-imageUrl' => asset($name['card'])]; } } $account->load('account_gateways'); $currentGateways = $account->account_gateways; $gateways = Gateway::where('payment_library_id', '=', 1)->orderBy('name')->get(); foreach ($gateways as $gateway) { $fields = $gateway->getFields(); asort($fields); $gateway->fields = $fields; if ($accountGateway && $accountGateway->gateway_id == $gateway->id) { $accountGateway->fields = $gateway->fields; } } $tokenBillingOptions = []; for ($i=1; $i<=4; $i++) { $tokenBillingOptions[$i] = trans("texts.token_billing_{$i}"); } return [ 'paymentTypes' => $paymentTypes, 'account' => $account, 'accountGateway' => $accountGateway, 'config' => false, 'gateways' => $gateways, 'creditCardTypes' => $creditCards, 'tokenBillingOptions' => $tokenBillingOptions, 'showBreadcrumbs' => false, 'countGateways' => count($currentGateways) ]; } public function delete() { $accountGatewayPublicId = Input::get('accountGatewayPublicId'); $gateway = AccountGateway::scope($accountGatewayPublicId)->firstOrFail(); $gateway->delete(); Session::flash('message', trans('texts.deleted_gateway')); return Redirect::to('company/payments'); } /** * Stores new account * */ public function save($accountGatewayPublicId = false) { $rules = array(); $paymentType = Input::get('payment_type_id'); $gatewayId = Input::get('gateway_id'); if ($paymentType == PAYMENT_TYPE_PAYPAL) { $gatewayId = GATEWAY_PAYPAL_EXPRESS; } elseif ($paymentType == PAYMENT_TYPE_BITCOIN) { $gatewayId = GATEWAY_BITPAY; } elseif ($paymentType == PAYMENT_TYPE_DWOLLA) { $gatewayId = GATEWAY_DWOLLA; } if (!$gatewayId) { Session::flash('error', trans('validation.required', ['attribute' => 'gateway'])); return Redirect::to('gateways/create') ->withInput(); } $gateway = Gateway::findOrFail($gatewayId); $fields = $gateway->getFields(); $optional = array_merge(Gateway::$hiddenFields, Gateway::$optionalFields); if ($gatewayId == GATEWAY_DWOLLA) { $optional = array_merge($optional, ['key', 'secret']); } foreach ($fields as $field => $details) { if (!in_array($field, $optional)) { if (strtolower($gateway->name) == 'beanstream') { if (in_array($field, ['merchant_id', 'passCode'])) { $rules[$gateway->id.'_'.$field] = 'required'; } } else { $rules[$gateway->id.'_'.$field] = 'required'; } } } $creditcards = Input::get('creditCardTypes'); $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return Redirect::to('gateways/create') ->withErrors($validator) ->withInput(); } else { $account = Account::with('account_gateways')->findOrFail(Auth::user()->account_id); $oldConfig = null; if ($accountGatewayPublicId) { $accountGateway = AccountGateway::scope($accountGatewayPublicId)->firstOrFail(); $oldConfig = json_decode($accountGateway->config); } else { $accountGateway = AccountGateway::createNew(); $accountGateway->gateway_id = $gatewayId; } $config = new stdClass(); foreach ($fields as $field => $details) { $value = trim(Input::get($gateway->id.'_'.$field)); // if the new value is masked use the original value if ($value && $value === str_repeat('*', strlen($value))) { $value = $oldConfig->$field; } if (!$value && ($field == 'testMode' || $field == 'developerMode')) { // do nothing } else { $config->$field = $value; } } $cardCount = 0; if ($creditcards) { foreach ($creditcards as $card => $value) { $cardCount += intval($value); } } $accountGateway->accepted_credit_cards = $cardCount; $accountGateway->show_address = Input::get('show_address') ? true : false; $accountGateway->update_address = Input::get('update_address') ? true : false; $accountGateway->config = json_encode($config); if ($accountGatewayPublicId) { $accountGateway->save(); } else { $account->account_gateways()->save($accountGateway); } if (Input::get('token_billing_type_id')) { $account->token_billing_type_id = Input::get('token_billing_type_id'); $account->save(); } if ($accountGatewayPublicId) { $message = trans('texts.updated_gateway'); } else { $message = trans('texts.created_gateway'); } Session::flash('message', $message); return Redirect::to("gateways/{$accountGateway->public_id}/edit"); } } } <file_sep>/app/Listeners/HandleUserLoggedIn.php <?php namespace App\Listeners; use Utils; use Auth; use Carbon; use Session; use App\Events\UserLoggedIn; use App\Ninja\Repositories\AccountRepository; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldBeQueued; class HandleUserLoggedIn { protected $accountRepo; /** * Create the event handler. * * @return void */ public function __construct(AccountRepository $accountRepo) { $this->accountRepo = $accountRepo; } /** * Handle the event. * * @param UserLoggedIn $event * @return void */ public function handle(UserLoggedIn $event) { $account = Auth::user()->account; if (!Utils::isNinja() && Auth::user()->id == 1 && empty($account->last_login)) { $this->accountRepo->registerUser(Auth::user()); } $account->last_login = Carbon::now()->toDateTimeString(); $account->save(); $users = $this->accountRepo->loadAccounts(Auth::user()->id); Session::put(SESSION_USER_ACCOUNTS, $users); $account->loadLocalizationSettings(); } } <file_sep>/resources/lang/pt_BR/texts.php <?php return array( 'organization' => 'Organização', 'name' => 'Nome', 'website' => 'Website', 'work_phone' => 'Telefone', 'address' => 'Endereço', 'address1' => 'Rua', 'address2' => 'Bloco/apto', 'city' => 'Cidade', 'state' => 'Estado', 'postal_code' => 'CEP', 'country_id' => 'País', 'contacts' => 'Contatos', 'first_name' => '<NAME>', 'last_name' => '<NAME>', 'phone' => 'Telefone', 'email' => 'Email', 'additional_info' => 'Informações Adicionais', 'payment_terms' => 'Termos de Pagamento', 'currency_id' => 'Moeda', 'size_id' => 'Tamanho', 'industry_id' => 'Empresa', 'private_notes' => 'Notas Privadas', // invoice 'invoice' => 'Fatura', 'client' => 'Cliente', 'invoice_date' => 'Data da Fatura', 'due_date' => 'Data de Vencimento', 'invoice_number' => 'Número da Fatura', 'invoice_number_short' => 'Fatura #', 'po_number' => 'Núm. Ordem de Compra', 'po_number_short' => 'OC #', 'frequency_id' => 'Quantas vezes', 'discount' => 'Desconto', 'taxes' => 'Taxas', 'tax' => 'Taxa', 'item' => 'Item', 'description' => 'Descrição', 'unit_cost' => 'Custo Unitário', 'quantity' => 'Quantidade', 'line_total' => 'Linha Total', 'subtotal' => 'Subtotal', 'paid_to_date' => 'Pagamento até', 'balance_due' => 'Saldo Devedor', 'invoice_design_id' => 'Design', 'terms' => 'Termos', 'your_invoice' => 'Sua Fatura', 'remove_contact' => 'Remover contato', 'add_contact' => 'Adicionar contato', 'create_new_client' => 'Criar novo cliente', 'edit_client_details' => 'Editar detalhes do cliente', 'enable' => 'Habilitar', 'learn_more' => 'Aprender mais', 'manage_rates' => 'Gerenciar impostos', 'note_to_client' => 'Nota para o cliente', 'invoice_terms' => 'Termos da Fatura', 'save_as_default_terms' => 'Salvar como termo padrão', 'download_pdf' => 'Baixar PDF', 'pay_now' => 'Pagar agora', 'save_invoice' => 'Salvar Fatura', 'clone_invoice' => 'Clonar Fatura', 'archive_invoice' => 'Arquivar Fatura', 'delete_invoice' => 'Apagar Fatura', 'email_invoice' => 'Enviar Fatura', 'enter_payment' => 'Entre com o Pagamento', 'tax_rates' => 'Taxas de Impostos', 'rate' => 'Imposto', 'settings' => 'Configurações', 'enable_invoice_tax' => 'Permitir especificar a <b>taxa da fatura</b>', 'enable_line_item_tax' => 'Permitir especificar o <b>item da linha de taxas</b>', // navigation 'dashboard' => 'Painel de Controle', 'clients' => 'Clientes', 'invoices' => 'Faturas', 'payments' => 'Pagamentos', 'credits' => 'Créditos', 'history' => 'Histórico', 'search' => 'Pesquisa', 'sign_up' => 'Cadastrar', 'guest' => 'Convidado', 'company_details' => 'Detalhes da Empresa', 'online_payments' => 'Pagamentos Online', 'notifications' => 'Notificações', 'import_export' => 'Importar/Exportar', 'done' => 'Feito', 'save' => 'Salvar', 'create' => 'Criar', 'upload' => 'Upload', 'import' => 'Importar', 'download' => 'Download', 'cancel' => 'Cancelar', 'provide_email' => 'Favor fornecer um endereço de e-mail válido', 'powered_by' => 'Powered by', 'no_items' => 'Sem itens', // recurring invoices 'recurring_invoices' => 'Faturas Recorrentes', 'recurring_help' => '<p>Enviar automaticamente aos clientes as mesmas faturas semanalmente, mensalmente, bimenstralmente, trimestralmente ou anualmente. </p> <p>Use :MONTH, :QUARTER ou :YEAR para datas dinâmicas. Matemática básica também funciona, por exemplo :MONTH-1.</p> <p>Exemplo de variáveis de uma fatura dinâmica:</p> <ul> <li>"Mensalidade da academia para o mês de :MONTH" => "Mensalidade da academia para o mês de Julho"</li> <li>"Plano anual de :YEAR+1" => "Plano anual de 2015"</li> <li>"Pagamento retido para :QUARTER+1" => "Pagamento retido para Q2"</li> </ul>', // dashboard 'in_total_revenue' => 'no total de rendimento', 'billed_client' => 'cliente faturado', 'billed_clients' => 'clientes faturados', 'active_client' => 'cliente ativo', 'active_clients' => 'clientes ativos', 'invoices_past_due' => 'Faturas Vencidas', 'upcoming_invoices' => 'Próximas Faturas', 'average_invoice' => 'Média da fatura', // list pages 'archive' => 'Arquivos', 'delete' => 'Apagar', 'archive_client' => 'Arquivar cliente', 'delete_client' => 'Apagar cliente', 'archive_payment' => 'Arquivar pagamento', 'delete_payment' => 'Apagar pagamento', 'archive_credit' => 'Arquivar crédito', 'delete_credit' => 'Apagar crédito', 'show_archived_deleted' => 'Mostrar arquivados/apagados', 'filter' => 'Filtrar', 'new_client' => 'Novo Cliente', 'new_invoice' => 'Nova Fatura', 'new_payment' => 'Novo Pagamento', 'new_credit' => 'Novo Crédito', 'contact' => 'Contato', 'date_created' => 'Data de Criação', 'last_login' => 'Último Login', 'balance' => 'Balanço', 'action' => 'Ação', 'status' => 'Status', 'invoice_total' => 'Total da Fatura', 'frequency' => 'Frequência', 'start_date' => 'Data Inicial', 'end_date' => 'Data Final', 'transaction_reference' => 'Referência da Transação', 'method' => 'Método', 'payment_amount' => 'Qtde do Pagamento', 'payment_date' => 'Data do Pagamento', 'credit_amount' => 'Qtde do Crédito', 'credit_balance' => 'Balanço do Crédito', 'credit_date' => 'Data do Crédito', 'empty_table' => 'Sem data disponível na tabela', 'select' => 'Selecionar', 'edit_client' => 'Editar Cliente', 'edit_invoice' => 'Editar Fatura', // client view page 'create_invoice' => 'Criar Fatura', 'enter_credit' => 'Digitar Crédito', 'last_logged_in' => 'Último login em', 'details' => 'Detalhes', 'standing' => 'Constante', 'credit' => 'Crédito', 'activity' => 'Atividade', 'date' => 'Data', 'message' => 'Mensagem', 'adjustment' => 'Ajustes', 'are_you_sure' => 'Você tem certeza?', // payment pages 'payment_type_id' => 'Tipo de pagamento', 'amount' => 'Quantidade', // account/company pages 'work_email' => 'Email', 'language_id' => 'Idioma', 'timezone_id' => 'Fuso Horário', 'date_format_id' => 'Formato da Data', 'datetime_format_id' => 'Formato da Data/Hora', 'users' => 'Usuários', 'localization' => 'Localização', 'remove_logo' => 'Remover logo', 'logo_help' => 'Suportados: JPEG, GIF and PNG. Altura recomendada: 120px', 'payment_gateway' => 'Provedor de Pagamento', 'gateway_id' => 'Provedor', 'email_notifications' => 'Notificações por Email', 'email_sent' => 'Me avise por email quando a fatura for <b>enviada</b>', 'email_viewed' => 'Me avise por email quando a fatura for <b>visualizada</b>', 'email_paid' => 'Me avise por email quando a fatura for <b>paga</b>', 'site_updates' => 'Atualizações do Site', 'custom_messages' => 'Mensagens Customizadas', 'default_invoice_terms' => 'Definir termos padrões da fatura', 'default_email_footer' => 'Definir assinatura de email padrão', 'import_clients' => 'Importar Dados do Cliente', 'csv_file' => 'Selecionar arquivo CSV', 'export_clients' => 'Exportar Dados do Cliente', 'select_file' => 'Favor selecionar um arquivo', 'first_row_headers' => 'Usar as primeiras linhas como cabeçalho', 'column' => 'Coluna', 'sample' => 'Exemplo', 'import_to' => 'Importar para', 'client_will_create' => 'cliente será criado', 'clients_will_create' => 'clientes serão criados', 'email_settings' => 'Email Settings', 'pdf_email_attachment' => 'Attach PDF to Emails', // application messages 'created_client' => 'Cliente criado com sucesso', 'created_clients' => ':count clientes criados com sucesso', 'updated_settings' => 'Configurações atualizadas com sucesso', 'removed_logo' => 'Logo removida com sucesso', 'sent_message' => 'Mensagem enviada com sucesso', 'invoice_error' => 'Verifique se você selecionou algum cliente e que não há nenhum outro erro', 'limit_clients' => 'Desculpe, isto irá exceder o limite de :count clientes', 'payment_error' => 'Ocorreu um erro ao processar o pagamento. Por favor tente novamente mais tarde.', 'registration_required' => 'Favor logar-se para enviar uma fatura por email', 'confirmation_required' => 'Favor confirmar o seu endereço de email', 'updated_client' => 'Cliente atualizado com sucesso', 'created_client' => 'Cliente criado com sucesso', 'archived_client' => 'Cliente arquivado com sucesso', 'archived_clients' => ':count clientes arquivados com sucesso', 'deleted_client' => 'Clientes removidos com sucesso', 'deleted_clients' => ':count clientes removidos com sucesso', 'updated_invoice' => 'Fatura atualizado com sucesso', 'created_invoice' => 'Fatura criada com sucesso', 'cloned_invoice' => 'Fatura clonada com sucesso', 'emailed_invoice' => 'Fatura enviada por email com sucesso', 'and_created_client' => 'e o cliente foi criado', 'archived_invoice' => 'Fatura arquivado com sucesso', 'archived_invoices' => ':count faturas arquivados com sucesso', 'deleted_invoice' => 'Fatura apagados com sucesso', 'deleted_invoices' => ':count faturas apagados com sucesso', 'created_payment' => 'Pagamento criado com sucesso', 'archived_payment' => 'Pagamento arquivado com sucesso', 'archived_payments' => ':count pagamentos arquivados com sucesso', 'deleted_payment' => 'Pagamento apagado com sucesso', 'deleted_payments' => ':count pagamentos apagados com sucesso', 'applied_payment' => 'Pagamentos aplicados com sucesso', 'created_credit' => 'Crédito criado com sucesso', 'archived_credit' => 'Crédito arquivado com sucesso', 'archived_credits' => ':count créditos arquivados com sucesso', 'deleted_credit' => 'Crédito apagado com sucesso', 'deleted_credits' => ':count créditos apagados com sucesso', // Emails 'confirmation_subject' => 'Confirmação de Conta do Invoice Ninja', 'confirmation_header' => 'Confirmação de Conta', 'confirmation_message' => 'Favor acessar o link abaixo para confirmar a sua conta.', 'invoice_message' => 'Para visualizar a sua fatura de :amount, clique no link abaixo.', 'payment_message' => 'Obrigado pelo seu pagamento de :amount.', 'email_salutation' => 'Caro :name,', 'email_signature' => 'Até mais,', 'email_from' => 'Equipe InvoiceNinja', 'user_email_footer' => 'Para ajustar suas configurações de notificações de email acesse '.SITE_URL.'/company/notifications', 'invoice_link_message' => 'Para visualizar a fatura do seu cliente clique no link abaixo:', 'notification_invoice_paid_subject' => 'Fatura :invoice foi pago por :client', 'notification_invoice_sent_subject' => 'Fatura :invoice foi enviado por :client', 'notification_invoice_viewed_subject' => 'Fatura :invoice foi visualizada por :client', 'notification_invoice_paid' => 'Um pagamento de :amount foi realizado pelo cliente :client através da fatura :invoice.', 'notification_invoice_sent' => 'O cliente :client foi notificado por email referente à fatura :invoice de :amount.', 'notification_invoice_viewed' => 'O cliente :client visualizou a fatura :invoice de :amount.', 'reset_password' => 'Você pode redefinir a sua senha clicando no seguinte link:', 'reset_password_footer' => 'Se você não solicitou a redefinição de sua senha por favor envie um email para o nosso suporte: ' . CONTACT_EMAIL, // Payment page 'secure_payment' => 'Pagamento Seguro', 'card_number' => 'Número do cartão', 'expiration_month' => 'Mês de expiração', 'expiration_year' => 'Ano de expiração', 'cvv' => 'CVV', // This File was missing the security alerts. I'm not familiar with this language, Can someone translate? // Security alerts /*'security' => [ 'too_many_attempts' => 'Too many attempts. Try again in few minutes.', 'wrong_credentials' => 'Incorrect email or password.', 'confirmation' => 'Your account has been confirmed!', 'wrong_confirmation' => 'Wrong confirmation code.', 'password_forgot' => 'The information regarding password reset was sent to your email.', 'password_reset' => 'Your <PASSWORD> been changed successfully.', 'wrong_password_reset' => 'Invalid password. Try again', ],*/ // Pro Plan 'pro_plan' => [ 'remove_logo' => ':link para remover a logo do Invoice Ninja contratando o plano profissional', 'remove_logo_link' => 'Clique aqui', ], 'logout' => 'Sair', 'sign_up_to_save' => 'Faça login para salvar o seu trabalho', 'agree_to_terms' =>'Eu concordo com os :terms do Invoice Ninja', 'terms_of_service' => 'Termos do Serviço', 'email_taken' => 'O endereço de e-mail já está registrado', 'working' => 'Processando', 'success' => 'Successo', 'success_message' => 'Você se registrou com sucesso. Por favor acesse o link de confirmação recebido para confirmar o seu endereço de e-mail.', 'erase_data' => 'Isto irá apagar completamente todos os seus dados.', 'password' => '<PASSWORD>', 'close' => 'Fechar', 'invoice_subject' => 'Nova fatura :invoice de :account', 'payment_subject' => 'Recebido Pagamento de', 'pro_plan_product' => 'Pro Plan', 'pro_plan_description' => 'One year enrollment in the Invoice Ninja Pro Plan.', 'pro_plan_success' => 'Thanks for joining! Once the invoice is paid your Pro Plan membership will begin.', 'unsaved_changes' => 'You have unsaved changes', 'custom_fields' => 'Custom fields', 'company_fields' => 'Company Fields', 'client_fields' => 'Client Fields', 'field_label' => 'Field Label', 'field_value' => 'Field Value', 'edit' => 'Edit', 'view_invoice' => 'View invoice', 'view_as_recipient' => 'View as recipient', // product management 'product_library' => 'Product Library', 'product' => 'Product', 'products' => 'Products', 'fill_products' => 'Auto-fill products', 'fill_products_help' => 'Selecting a product will automatically <b>set the description and cost</b>', 'update_products' => 'Auto-update products', 'update_products_help' => 'Updating an invoice will automatically <b>update the products</b>', 'create_product' => 'Create Product', 'edit_product' => 'Edit Product', 'archive_product' => 'Archive Product', 'updated_product' => 'Successfully updated product', 'created_product' => 'Successfully created product', 'archived_product' => 'Successfully archived product', 'pro_plan_custom_fields' => ':link to enable custom fields by joining the Pro Plan', 'advanced_settings' => 'Advanced Settings', 'pro_plan_advanced_settings' => ':link to enable the advanced settings by joining the Pro Plan', 'invoice_design' => 'Invoice Design', 'specify_colors' => 'Specify colors', 'specify_colors_label' => 'Select the colors used in the invoice', 'chart_builder' => 'Chart Builder', 'ninja_email_footer' => 'Use :site to invoice your clients and get paid online for free!', 'go_pro' => 'Go Pro', // Quotes 'quote' => 'Quote', 'quotes' => 'Quotes', 'quote_number' => 'Quote Number', 'quote_number_short' => 'Quote #', 'quote_date' => 'Quote Date', 'quote_total' => 'Quote Total', 'your_quote' => 'Your Quote', 'total' => 'Total', 'clone' => 'Clone', 'new_quote' => 'New Quote', 'create_quote' => 'Create Quote', 'edit_quote' => 'Edit Quote', 'archive_quote' => 'Archive Quote', 'delete_quote' => 'Delete Quote', 'save_quote' => 'Save Quote', 'email_quote' => 'Email Quote', 'clone_quote' => 'Clone Quote', 'convert_to_invoice' => 'Convert to Invoice', 'view_invoice' => 'View Invoice', 'view_quote' => 'View Quote', 'view_client' => 'View Client', 'updated_quote' => 'Successfully updated quote', 'created_quote' => 'Successfully created quote', 'cloned_quote' => 'Successfully cloned quote', 'emailed_quote' => 'Successfully emailed quote', 'archived_quote' => 'Successfully archived quote', 'archived_quotes' => 'Successfully archived :count quotes', 'deleted_quote' => 'Successfully deleted quote', 'deleted_quotes' => 'Successfully deleted :count quotes', 'converted_to_invoice' => 'Successfully converted quote to invoice', 'quote_subject' => 'New quote from :account', 'quote_message' => 'To view your quote for :amount, click the link below.', 'quote_link_message' => 'To view your client quote click the link below:', 'notification_quote_sent_subject' => 'Quote :invoice was sent to :client', 'notification_quote_viewed_subject' => 'Quote :invoice was viewed by :client', 'notification_quote_sent' => 'The following client :client was emailed Quote :invoice for :amount.', 'notification_quote_viewed' => 'The following client :client viewed Quote :invoice for :amount.', 'session_expired' => 'Your session has expired.', 'invoice_fields' => 'Invoice Fields', 'invoice_options' => 'Invoice Options', 'hide_quantity' => 'Hide quantity', 'hide_quantity_help' => 'If your line items quantities are always 1, then you can declutter invoices by no longer displaying this field.', 'hide_paid_to_date' => 'Hide paid to date', 'hide_paid_to_date_help' => 'Only display the "Paid to Date" area on your invoices once a payment has been received.', 'charge_taxes' => 'Charge taxes', 'user_management' => 'User Management', 'add_user' => 'Add User', 'send_invite' => 'Send invitation', 'sent_invite' => 'Successfully sent invitation', 'updated_user' => 'Successfully updated user', 'invitation_message' => 'You\'ve been invited by :invitor. ', 'register_to_add_user' => 'Please sign up to add a user', 'user_state' => 'State', 'edit_user' => 'Edit User', 'delete_user' => 'Delete User', 'active' => 'Active', 'pending' => 'Pending', 'deleted_user' => 'Successfully deleted user', 'limit_users' => 'Sorry, this will exceed the limit of ' . MAX_NUM_USERS . ' users', 'confirm_email_invoice' => 'Are you sure you want to email this invoice?', 'confirm_email_quote' => 'Are you sure you want to email this quote?', 'confirm_recurring_email_invoice' => 'Recurring is enabled, are you sure you want this invoice emailed?', 'cancel_account' => 'Cancel Account', 'cancel_account_message' => 'Warning: This will permanently erase all of your data, there is no undo.', 'go_back' => 'Go Back', 'data_visualizations' => 'Data Visualizations', 'sample_data' => 'Sample data shown', 'hide' => 'Hide', 'new_version_available' => 'A new version of :releases_link is available. You\'re running v:user_version, the latest is v:latest_version', 'invoice_settings' => 'Invoice Settings', 'invoice_number_prefix' => 'Invoice Number Prefix', 'invoice_number_counter' => 'Invoice Number Counter', 'quote_number_prefix' => 'Quote Number Prefix', 'quote_number_counter' => 'Quote Number Counter', 'share_invoice_counter' => 'Share invoice counter', 'invoice_issued_to' => 'Invoice issued to', 'invalid_counter' => 'To prevent a possible conflict please set either an invoice or quote number prefix', 'mark_sent' => 'Mark sent', 'gateway_help_1' => ':link to sign up for Authorize.net.', 'gateway_help_2' => ':link to sign up for Authorize.net.', 'gateway_help_17' => ':link to get your PayPal API signature.', 'gateway_help_23' => 'Note: use your secret API key, not your publishable API key.', 'gateway_help_27' => ':link to sign up for TwoCheckout.', 'more_designs' => 'More designs', 'more_designs_title' => 'Additional Invoice Designs', 'more_designs_cloud_header' => 'Go Pro for more invoice designs', 'more_designs_cloud_text' => '', 'more_designs_self_host_header' => 'Get 6 more invoice designs for just $'.INVOICE_DESIGNS_PRICE, 'more_designs_self_host_text' => '', 'buy' => 'Buy', 'bought_designs' => 'Successfully added additional invoice designs', 'sent' => 'sent', 'timesheets' => 'Timesheets', 'payment_title' => 'Enter Your Billing Address and Credit Card information', 'payment_cvv' => '*This is the 3-4 digit number onthe back of your card', 'payment_footer1' => '*Billing address must match address associated with credit card.', 'payment_footer2' => '*Please click "PAY NOW" only once - transaction may take up to 1 minute to process.', 'vat_number' => 'Vat Number', 'id_number' => 'ID Number', 'white_label_link' => 'White label', 'white_label_text' => 'Purchase a white label license for $'.WHITE_LABEL_PRICE.' to remove the Invoice Ninja branding from the top of the client pages.', 'white_label_header' => 'White Label', 'bought_white_label' => 'Successfully enabled white label license', 'white_labeled' => 'White labeled', 'restore' => 'Restore', 'restore_invoice' => 'Restore Invoice', 'restore_quote' => 'Restore Quote', 'restore_client' => 'Restore Client', 'restore_credit' => 'Restore Credit', 'restore_payment' => 'Restore Payment', 'restored_invoice' => 'Successfully restored invoice', 'restored_quote' => 'Successfully restored quote', 'restored_client' => 'Successfully restored client', 'restored_payment' => 'Successfully restored payment', 'restored_credit' => 'Successfully restored credit', 'reason_for_canceling' => 'Help us improve our site by telling us why you\'re leaving.', 'discount_percent' => 'Percent', 'discount_amount' => 'Amount', 'invoice_history' => 'Invoice History', 'quote_history' => 'Quote History', 'current_version' => 'Current version', 'select_versiony' => 'Select version', 'view_history' => 'View History', 'edit_payment' => 'Edit Payment', 'updated_payment' => 'Successfully updated payment', 'deleted' => 'Deleted', 'restore_user' => 'Restore User', 'restored_user' => 'Successfully restored user', 'show_deleted_users' => 'Show deleted users', 'email_templates' => 'Email Templates', 'invoice_email' => 'Invoice Email', 'payment_email' => 'Payment Email', 'quote_email' => 'Quote Email', 'reset_all' => 'Reset All', 'approve' => 'Approve', 'token_billing_type_id' => 'Token Billing', 'token_billing_help' => 'Enables you to store credit cards with your gateway, and charge them at a later date.', 'token_billing_1' => 'Disabled', 'token_billing_2' => 'Opt-in - checkbox is shown but not selected', 'token_billing_3' => 'Opt-out - checkbox is shown and selected', 'token_billing_4' => 'Always', 'token_billing_checkbox' => 'Store credit card details', 'view_in_stripe' => 'View in Stripe', 'use_card_on_file' => 'Use card on file', 'edit_payment_details' => 'Edit payment details', 'token_billing' => 'Save card details', 'token_billing_secure' => 'The data is stored securely by :stripe_link', 'support' => 'Support', 'contact_information' => 'Contact information', '256_encryption' => '256-Bit Encryption', 'amount_due' => 'Amount due', 'billing_address' => 'Billing address', 'billing_method' => 'Billing method', 'order_overview' => 'Order overview', 'match_address' => '*Address must match address associated with credit card.', 'click_once' => '*Please click "PAY NOW" only once - transaction may take up to 1 minute to process.', 'default_invoice_footer' => 'Set default invoice footer', 'invoice_footer' => 'Invoice footer', 'save_as_default_footer' => 'Save as default footer', 'token_management' => 'Token Management', 'tokens' => 'Tokens', 'add_token' => 'Add Token', 'show_deleted_tokens' => 'Show deleted tokens', 'deleted_token' => 'Successfully deleted token', 'created_token' => 'Successfully created token', 'updated_token' => 'Successfully updated token', 'edit_token' => 'Edit Token', 'delete_token' => 'Delete Token', 'token' => 'Token', 'add_gateway' => 'Add Gateway', 'delete_gateway' => 'Delete Gateway', 'edit_gateway' => 'Edit Gateway', 'updated_gateway' => 'Successfully updated gateway', 'created_gateway' => 'Successfully created gateway', 'deleted_gateway' => 'Successfully deleted gateway', 'pay_with_paypal' => 'PayPal', 'pay_with_card' => 'Credit card', 'change_password' => '<PASSWORD>', 'current_password' => '<PASSWORD>', 'new_password' => '<PASSWORD>', 'confirm_password' => '<PASSWORD>', 'password_error_incorrect' => 'The current password is incorrect.', 'password_error_invalid' => 'The new password is invalid.', 'updated_password' => 'Successfully updated password', 'api_tokens' => 'API Tokens', 'users_and_tokens' => 'Users & Tokens', 'account_login' => 'Account Login', 'recover_password' => '<PASSWORD>', 'forgot_password' => '<PASSWORD>?', 'email_address' => 'Email address', 'lets_go' => 'Let’s go', 'password_recovery' => '<PASSWORD>', 'send_email' => 'Send email', 'set_password' => '<PASSWORD>', 'converted' => 'Converted', 'email_approved' => 'Email me when a quote is <b>approved</b>', 'notification_quote_approved_subject' => 'Quote :invoice was approved by :client', 'notification_quote_approved' => 'The following client :client approved Quote :invoice for :amount.', 'resend_confirmation' => 'Resend confirmation email', 'confirmation_resent' => 'The confirmation email was resent', 'gateway_help_42' => ':link to sign up for BitPay.<br/>Note: use a Legacy API Key, not an API token.', 'payment_type_credit_card' => 'Credit card', 'payment_type_paypal' => 'PayPal', 'payment_type_bitcoin' => 'Bitcoin', 'knowledge_base' => 'Knowledge Base', 'partial' => 'Partial', 'partial_remaining' => ':partial of :balance', 'more_fields' => 'More Fields', 'less_fields' => 'Less Fields', 'client_name' => '<NAME>', 'pdf_settings' => 'PDF Settings', 'product_settings' => 'Product Settings', 'auto_wrap' => 'Auto Line Wrap', 'duplicate_post' => 'Warning: the previous page was submitted twice. The second submission had been ignored.', 'view_documentation' => 'View Documentation', 'app_title' => 'Free Open-Source Online Invoicing', 'app_description' => 'Invoice Ninja is a free, open-source solution for invoicing and billing customers. With Invoice Ninja, you can easily build and send beautiful invoices from any device that has access to the web. Your clients can print your invoices, download them as pdf files, and even pay you online from within the system.', 'rows' => 'rows', 'www' => 'www', 'logo' => 'Logo', 'subdomain' => 'Subdomain', 'provide_name_or_email' => 'Please provide a contact name or email', 'charts_and_reports' => 'Charts & Reports', 'chart' => 'Chart', 'report' => 'Report', 'group_by' => 'Group by', 'paid' => 'Paid', 'enable_report' => 'Report', 'enable_chart' => 'Chart', 'totals' => 'Totals', 'run' => 'Run', 'export' => 'Export', 'documentation' => 'Documentation', 'zapier' => 'Zapier <sup>Beta</sup>', 'recurring' => 'Recurring', 'last_invoice_sent' => 'Last invoice sent :date', 'processed_updates' => 'Successfully completed update', 'tasks' => 'Tasks', 'new_task' => 'New Task', 'start_time' => 'Start Time', 'created_task' => 'Successfully created task', 'updated_task' => 'Successfully updated task', 'edit_task' => 'Edit Task', 'archive_task' => 'Archive Task', 'restore_task' => 'Restore Task', 'delete_task' => 'Delete Task', 'stop_task' => 'Stop Task', 'time' => 'Time', 'start' => 'Start', 'stop' => 'Stop', 'now' => 'Now', 'timer' => 'Timer', 'manual' => 'Manual', 'date_and_time' => 'Date & Time', 'second' => 'second', 'seconds' => 'seconds', 'minute' => 'minute', 'minutes' => 'minutes', 'hour' => 'hour', 'hours' => 'hours', 'task_details' => 'Task Details', 'duration' => 'Duration', 'end_time' => 'End Time', 'end' => 'End', 'invoiced' => 'Invoiced', 'logged' => 'Logged', 'running' => 'Running', 'task_error_multiple_clients' => 'The tasks can\'t belong to different clients', 'task_error_running' => 'Please stop running tasks first', 'task_error_invoiced' => 'Tasks have already been invoiced', 'restored_task' => 'Successfully restored task', 'archived_task' => 'Successfully archived task', 'archived_tasks' => 'Successfully archived :count tasks', 'deleted_task' => 'Successfully deleted task', 'deleted_tasks' => 'Successfully deleted :count tasks', 'create_task' => 'Create Task', 'stopped_task' => 'Successfully stopped task', 'invoice_task' => 'Invoice Task', 'invoice_labels' => 'Invoice Labels', 'prefix' => 'Prefix', 'counter' => 'Counter', 'payment_type_dwolla' => 'Dwolla', 'gateway_help_43' => ':link to sign up for Dwolla.', 'partial_value' => 'Must be greater than zero and less than the total', 'more_actions' => 'More Actions', 'pro_plan_title' => 'NINJA PRO', 'pro_plan_call_to_action' => 'Upgrade Now!', 'pro_plan_feature1' => 'Create Unlimited Clients', 'pro_plan_feature2' => 'Access to 10 Beautiful Invoice Designs', 'pro_plan_feature3' => 'Custom URLs - "YourBrand.InvoiceNinja.com"', 'pro_plan_feature4' => 'Remove "Created by Invoice Ninja"', 'pro_plan_feature5' => 'Multi-user Access & Activity Tracking', 'pro_plan_feature6' => 'Create Quotes & Pro-forma Invoices', 'pro_plan_feature7' => 'Customize Invoice Field Titles & Numbering', 'pro_plan_feature8' => 'Option to Attach PDFs to Client Emails', 'resume' => 'Resume', 'break_duration' => 'Break', 'edit_details' => 'Edit Details', 'work' => 'Work', 'timezone_unset' => 'Please :link to set your timezone', 'click_here' => 'click here', 'email_receipt' => 'Email payment receipt to the client', 'created_payment_emailed_client' => 'Successfully created payment and emailed client', 'add_company' => 'Add Company', 'untitled' => 'Untitled', 'new_company' => 'New Company', 'associated_accounts' => 'Successfully linked accounts', 'unlinked_account' => 'Successfully unlinked accounts', 'login' => 'Login', 'or' => 'or', 'email_error' => 'There was a problem sending the email', 'confirm_recurring_timing' => 'Note: emails are sent at the start of the hour.', 'old_browser' => 'Please use a <a href="'.OUTDATE_BROWSER_URL.'" target="_blank">newer browser</a>', 'payment_terms_help' => 'Sets the default invoice due date', 'unlink_account' => 'Unlink Account', 'unlink' => 'Unlink', 'show_address' => 'Show Address', 'show_address_help' => 'Require client to provide their billing address', 'update_address' => 'Update Address', 'update_address_help' => 'Update client\'s address with provided details', 'times' => 'Times', 'set_now' => 'Set now', 'dark_mode' => 'Dark Mode', 'dark_mode_help' => 'Show white text on black background', 'add_to_invoice' => 'Add to invoice :invoice', 'create_new_invoice' => 'Create new invoice', 'task_errors' => 'Please correct any overlapping times', 'from' => 'From', 'to' => 'To', 'font_size' => 'Font Size', 'primary_color' => 'Primary Color', 'secondary_color' => 'Secondary Color', 'customize_design' => 'Customize Design', 'content' => 'Content', 'styles' => 'Styles', 'defaults' => 'Defaults', 'margins' => 'Margins', 'header' => 'Header', 'footer' => 'Footer', 'custom' => 'Custom', 'invoice_to' => 'Invoice to', 'invoice_no' => 'Invoice No.', 'recent_payments' => 'Recent Payments', 'outstanding' => 'Outstanding', 'manage_companies' => 'Manage Companies', 'total_revenue' => 'Total Revenue', 'current_user' => 'Current User', 'new_recurring_invoice' => 'New Recurring Invoice', 'recurring_invoice' => 'Recurring Invoice', 'recurring_too_soon' => 'It\'s too soon to create the next recurring invoice', 'created_by_invoice' => 'Created by :invoice', 'primary_user' => 'Primary User', 'help' => 'Help', 'customize_help' => '<p>We use <a href="http://pdfmake.org/" target="_blank">pdfmake</a> to define the invoice designs declaratively. The pdfmake <a href="http://pdfmake.org/playground.html" target="_blank">playground</a> provide\'s a great way to see the library in action.</p> <p>You can access any invoice field by adding <code>Value</code> to the end. For example <code>$invoiceNumberValue</code> displays the invoice number.</p> <p>To access a child property using dot notation. For example to show the client name you could use <code>$client.nameValue</code>.</p> <p>If you need help figuring something out post a question to our <a href="https://www.invoiceninja.com/forums/forum/support/" target="_blank">support forum</a>.</p>' ); <file_sep>/app/Listeners/HandleUserSettingsChanged.php <?php namespace App\Listeners; use Auth; use Session; use App\Events\UserSettingsChanged; use App\Ninja\Repositories\AccountRepository; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldBeQueued; class HandleUserSettingsChanged { /** * Create the event handler. * * @return void */ public function __construct(AccountRepository $accountRepo) { $this->accountRepo = $accountRepo; } /** * Handle the event. * * @param UserSettingsChanged $event * @return void */ public function handle(UserSettingsChanged $event) { if (Auth::check()) { $account = Auth::user()->account; $account->loadLocalizationSettings(); $users = $this->accountRepo->loadAccounts(Auth::user()->id); Session::put(SESSION_USER_ACCOUNTS, $users); } } } <file_sep>/app/Http/Controllers/Auth/AuthController.php <?php namespace App\Http\Controllers\Auth; use Auth; use Event; use Utils; use Session; use Illuminate\Http\Request; use App\Models\User; use App\Events\UserLoggedIn; use App\Http\Controllers\Controller; use App\Ninja\Repositories\AccountRepository; use Illuminate\Contracts\Auth\Guard; use Illuminate\Contracts\Auth\Registrar; use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers; class AuthController extends Controller { /* |-------------------------------------------------------------------------- | Registration & Login Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users, as well as the | authentication of existing users. By default, this controller uses | a simple trait to add these behaviors. Why don't you explore it? | */ use AuthenticatesAndRegistersUsers; protected $loginPath = '/login'; protected $redirectTo = '/dashboard'; protected $accountRepo; /** * Create a new authentication controller instance. * * @param \Illuminate\Contracts\Auth\Guard $auth * @param \Illuminate\Contracts\Auth\Registrar $registrar * @return void */ public function __construct(Guard $auth, Registrar $registrar, AccountRepository $repo) { $this->auth = $auth; $this->registrar = $registrar; $this->accountRepo = $repo; //$this->middleware('guest', ['except' => 'getLogout']); } public function getLoginWrapper() { if (!Utils::isNinja() && !User::count()) { return redirect()->to('invoice_now'); } return self::getLogin(); } public function postLoginWrapper(Request $request) { $userId = Auth::check() ? Auth::user()->id : null; $user = User::where('email', '=', $request->input('email'))->first(); if ($user && $user->failed_logins >= 3) { Session::flash('error', 'These credentials do not match our records.'); return redirect()->to('login'); } $response = self::postLogin($request); if (Auth::check()) { Event::fire(new UserLoggedIn()); $users = false; // we're linking a new account if ($userId && Auth::user()->id != $userId) { $users = $this->accountRepo->associateAccounts($userId, Auth::user()->id); Session::flash('message', trans('texts.associated_accounts')); // check if other accounts are linked } else { $users = $this->accountRepo->loadAccounts(Auth::user()->id); } Session::put(SESSION_USER_ACCOUNTS, $users); } elseif ($user) { $user->failed_logins = $user->failed_logins + 1; $user->save(); } return $response; } public function getLogoutWrapper() { if (Auth::check() && !Auth::user()->registered) { $account = Auth::user()->account; $this->accountRepo->unlinkAccount($account); $account->forceDelete(); } $response = self::getLogout(); Session::flush(); return $response; } } <file_sep>/app/Models/Product.php <?php namespace App\Models; use Illuminate\Database\Eloquent\SoftDeletes; class Product extends EntityModel { use SoftDeletes; protected $dates = ['deleted_at']; public static function findProductByKey($key) { return Product::scope()->where('product_key', '=', $key)->first(); } } <file_sep>/app/Ninja/Repositories/PaymentRepository.php <?php namespace App\Ninja\Repositories; use App\Models\Payment; use App\Models\Credit; use App\Models\Invoice; use App\Models\Client; use Utils; class PaymentRepository { public function find($clientPublicId = null, $filter = null) { $query = \DB::table('payments') ->join('clients', 'clients.id', '=', 'payments.client_id') ->join('invoices', 'invoices.id', '=', 'payments.invoice_id') ->join('contacts', 'contacts.client_id', '=', 'clients.id') ->leftJoin('payment_types', 'payment_types.id', '=', 'payments.payment_type_id') ->leftJoin('account_gateways', 'account_gateways.id', '=', 'payments.account_gateway_id') ->leftJoin('gateways', 'gateways.id', '=', 'account_gateways.gateway_id') ->where('payments.account_id', '=', \Auth::user()->account_id) ->where('clients.deleted_at', '=', null) ->where('contacts.is_primary', '=', true) ->where('contacts.deleted_at', '=', null) ->select('payments.public_id', 'payments.transaction_reference', 'clients.name as client_name', 'clients.public_id as client_public_id', 'payments.amount', 'payments.payment_date', 'invoices.public_id as invoice_public_id', 'invoices.invoice_number', 'clients.currency_id', 'contacts.first_name', 'contacts.last_name', 'contacts.email', 'payment_types.name as payment_type', 'payments.account_gateway_id', 'payments.deleted_at', 'payments.is_deleted', 'invoices.is_deleted as invoice_is_deleted', 'gateways.name as gateway_name'); if (!\Session::get('show_trash:payment')) { $query->where('payments.deleted_at', '=', null) ->where('invoices.deleted_at', '=', null); } if ($clientPublicId) { $query->where('clients.public_id', '=', $clientPublicId); } if ($filter) { $query->where(function ($query) use ($filter) { $query->where('clients.name', 'like', '%'.$filter.'%'); }); } return $query; } public function findForContact($contactId = null, $filter = null) { $query = \DB::table('payments') ->join('clients', 'clients.id', '=', 'payments.client_id') ->join('invoices', 'invoices.id', '=', 'payments.invoice_id') ->join('contacts', 'contacts.client_id', '=', 'clients.id') ->leftJoin('invitations', function ($join) { $join->on('invitations.invoice_id', '=', 'invoices.id') ->on('invitations.contact_id', '=', 'contacts.id'); }) ->leftJoin('payment_types', 'payment_types.id', '=', 'payments.payment_type_id') ->where('clients.is_deleted', '=', false) ->where('payments.is_deleted', '=', false) ->where('invitations.deleted_at', '=', null) ->where('invoices.deleted_at', '=', null) ->where('invitations.contact_id', '=', $contactId) ->select('invitations.invitation_key', 'payments.public_id', 'payments.transaction_reference', 'clients.name as client_name', 'clients.public_id as client_public_id', 'payments.amount', 'payments.payment_date', 'invoices.public_id as invoice_public_id', 'invoices.invoice_number', 'clients.currency_id', 'contacts.first_name', 'contacts.last_name', 'contacts.email', 'payment_types.name as payment_type', 'payments.account_gateway_id'); if ($filter) { $query->where(function ($query) use ($filter) { $query->where('clients.name', 'like', '%'.$filter.'%'); }); } return $query; } public function getErrors($input) { $rules = array( 'client' => 'required', 'invoice' => 'required', 'amount' => 'required', ); if ($input['payment_type_id'] == PAYMENT_TYPE_CREDIT) { $rules['payment_type_id'] = 'has_credit:'.$input['client'].','.$input['amount']; } if (isset($input['invoice']) && $input['invoice']) { $invoice = Invoice::scope($input['invoice'])->firstOrFail(); $rules['amount'] .= "|less_than:{$invoice->balance}"; } $validator = \Validator::make($input, $rules); if ($validator->fails()) { return $validator; } return false; } public function save($publicId = null, $input) { if ($publicId) { $payment = Payment::scope($publicId)->firstOrFail(); } else { $payment = Payment::createNew(); } $paymentTypeId = false; if (isset($input['payment_type_id'])) { $paymentTypeId = $input['payment_type_id'] ? $input['payment_type_id'] : null; $payment->payment_type_id = $paymentTypeId; } if (isset($input['payment_date_sql'])) { $payment->payment_date = $input['payment_date_sql']; } elseif (isset($input['payment_date'])) { $payment->payment_date = Utils::toSqlDate($input['payment_date']); } else { $payment->payment_date = date('Y-m-d'); } $payment->transaction_reference = trim($input['transaction_reference']); if (!$publicId) { $clientId = Client::getPrivateId($input['client']); $amount = Utils::parseFloat($input['amount']); if ($paymentTypeId == PAYMENT_TYPE_CREDIT) { $credits = Credit::scope()->where('client_id', '=', $clientId) ->where('balance', '>', 0)->orderBy('created_at')->get(); $applied = 0; foreach ($credits as $credit) { $applied += $credit->apply($amount); if ($applied >= $amount) { break; } } } $payment->client_id = $clientId; $payment->invoice_id = isset($input['invoice']) && $input['invoice'] != "-1" ? Invoice::getPrivateId($input['invoice']) : null; $payment->amount = $amount; } $payment->save(); return $payment; } public function bulk($ids, $action) { if (!$ids) { return 0; } $payments = Payment::withTrashed()->scope($ids)->get(); foreach ($payments as $payment) { if ($action == 'restore') { $payment->restore(); } else { if ($action == 'delete') { $payment->is_deleted = true; $payment->save(); } $payment->delete(); } } return count($payments); } } <file_sep>/app/Models/Language.php <?php namespace App\Models; use Eloquent; class Language extends Eloquent { public $timestamps = false; } <file_sep>/tests/acceptance/PaymentCest.php <?php use \AcceptanceTester; use App\Models\Payment; use Faker\Factory; class PaymentCest { private $faker; public function _before(AcceptanceTester $I) { $I->checkIfLogin($I); $this->faker = Factory::create(); } public function create(AcceptanceTester $I) { $clientName = $I->grabFromDatabase('clients', 'name'); $amount = rand(1, 30); $I->wantTo("enter a payment"); $I->amOnPage('/payments/create'); $I->selectDropdown($I, $clientName, '.client-select .dropdown-toggle'); $I->selectDropdownRow($I, 1, '.invoice-select .combobox-container'); $I->fillField(['name' => 'amount'], $amount); $I->selectDropdownRow($I, 1, 'div.panel-body div.form-group:nth-child(4) .combobox-container'); $I->selectDataPicker($I, '#payment_date', 'now + 1 day'); $I->fillField(['name' => 'transaction_reference'], $this->faker->text(12)); $I->click('Save'); $I->see('Successfully created payment'); $I->seeInDatabase('payments', ['amount' => number_format($amount, 2)]); } public function editPayment(AcceptanceTester $I) { $ref = $this->faker->text(12); $I->wantTo("edit a payment"); $I->amOnPage('/payments/1/edit'); $I->selectDataPicker($I, '#payment_date', 'now + 2 day'); $I->fillField(['name' => 'transaction_reference'], $ref); $I->click('Save'); $I->seeInDatabase('payments', ['transaction_reference' => $ref]); } public function listPayments(AcceptanceTester $I) { $I->wantTo("list payments"); $I->amOnPage('/payments'); $I->seeNumberOfElements('tbody tr[role=row]', [1, 10]); } /* public function delete(AcceptanceTester $I) { $I->wantTo('delete a payment'); $I->amOnPage('/payments'); $I->seeCurrentUrlEquals('/payments'); $I->wait(3); if ($num_payments = Payment::all()->count()) { $row_rand = sprintf('tbody tr:nth-child(%d)', rand(1, $num_payments)); //show button $I->executeJS(sprintf('$("%s div").css("visibility", "visible")', $row_rand)); //dropdown $I->click($row_rand . ' button'); //click to delete button $I->click($row_rand . ' ul li:nth-last-child(1) a'); $I->acceptPopup(); } } */ } <file_sep>/database/seeds/UserTableSeeder.php <?php use App\Models\User; use App\Models\Account; class UserTableSeeder extends Seeder { public function run() { $this->command->info('Running UserTableSeeder'); Eloquent::unguard(); $account = Account::create([ 'name' => 'Test Account', 'account_key' => str_random(16), 'timezone_id' => 1, ]); User::create([ 'email' => TEST_USERNAME, 'username' => TEST_USERNAME, 'account_id' => $account->id, 'password' => <PASSWORD>(<PASSWORD>), ]); } }<file_sep>/resources/lang/nb_NO/reminders.php <?php return array( /* |-------------------------------------------------------------------------- | Password Reminder Language Lines |-------------------------------------------------------------------------- | | The following language lines are the default lines which match reasons | that are given by the password broker for a password update attempt | has failed, such as for an invalid token or invalid new password. | */ "password" => "<PASSWORD>.", "user" => "Vi kan ikke finne en bruker med den e-postadressen.", "token" => "Denne til<PASSWORD>n&#248;kkelen <PASSWORD>ldig.", "sent" => "Passord p&#229;minnelse sendt!", );<file_sep>/app/Ninja/Repositories/TaskRepository.php <?php namespace App\Ninja\Repositories; use Auth; use Carbon; use Session; use App\Models\Client; use App\Models\Contact; use App\Models\Activity; use App\Models\Task; class TaskRepository { public function find($clientPublicId = null, $filter = null) { $query = \DB::table('tasks') ->leftJoin('clients', 'tasks.client_id', '=', 'clients.id') ->leftJoin('contacts', 'contacts.client_id', '=', 'clients.id') ->leftJoin('invoices', 'invoices.id', '=', 'tasks.invoice_id') ->where('tasks.account_id', '=', Auth::user()->account_id) ->where(function ($query) { $query->where('contacts.is_primary', '=', true) ->orWhere('contacts.is_primary', '=', null); }) ->where('contacts.deleted_at', '=', null) ->where('clients.deleted_at', '=', null) ->select('tasks.public_id', 'clients.name as client_name', 'clients.public_id as client_public_id', 'contacts.first_name', 'contacts.email', 'contacts.last_name', 'invoices.invoice_status_id', 'tasks.description', 'tasks.is_deleted', 'tasks.deleted_at', 'invoices.invoice_number', 'invoices.public_id as invoice_public_id', 'tasks.is_running', 'tasks.time_log', 'tasks.created_at'); if ($clientPublicId) { $query->where('clients.public_id', '=', $clientPublicId); } if (!Session::get('show_trash:task')) { $query->where('tasks.deleted_at', '=', null); } if ($filter) { $query->where(function ($query) use ($filter) { $query->where('clients.name', 'like', '%'.$filter.'%') ->orWhere('contacts.first_name', 'like', '%'.$filter.'%') ->orWhere('contacts.last_name', 'like', '%'.$filter.'%') ->orWhere('tasks.description', 'like', '%'.$filter.'%'); }); } return $query; } public function save($publicId, $data) { if ($publicId) { $task = Task::scope($publicId)->firstOrFail(); } else { $task = Task::createNew(); } if (isset($data['client']) && $data['client']) { $task->client_id = Client::getPrivateId($data['client']); } if (isset($data['description'])) { $task->description = trim($data['description']); } if (isset($data['time_log'])) { $timeLog = json_decode($data['time_log']); } elseif ($task->time_log) { $timeLog = json_decode($task->time_log); } else { $timeLog = []; } if ($data['action'] == 'start') { $task->is_running = true; $timeLog[] = [strtotime('now'), false]; } else if ($data['action'] == 'resume') { $task->is_running = true; $timeLog[] = [strtotime('now'), false]; } else if ($data['action'] == 'stop' && $task->is_running) { $timeLog[count($timeLog)-1][1] = time(); $task->is_running = false; } $task->time_log = json_encode($timeLog); $task->save(); return $task; } public function bulk($ids, $action) { $tasks = Task::withTrashed()->scope($ids)->get(); foreach ($tasks as $task) { if ($action == 'restore') { $task->restore(); $task->is_deleted = false; $task->save(); } else { if ($action == 'delete') { $task->is_deleted = true; $task->save(); } $task->delete(); } } return count($tasks); } } <file_sep>/database/migrations/2014_10_06_195330_add_invoice_design_table.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddInvoiceDesignTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('invoice_designs', function($table) { $table->text('javascript')->nullable(); }); Schema::table('accounts', function($table) { $table->text('invoice_design')->nullable(); }); DB::table('invoice_designs')->where('id', 1)->update([ 'javascript' => "var GlobalY=0;//Y position of line at current page var client = invoice.client; var account = invoice.account; var currencyId = client.currency_id; layout.headerRight = 550; layout.rowHeight = 15; doc.setFontSize(9); if (invoice.image) { var left = layout.headerRight - invoice.imageWidth; doc.addImage(invoice.image, 'JPEG', layout.marginLeft, 30); } if (!invoice.is_pro && logoImages.imageLogo1) { pageHeight=820; y=pageHeight-logoImages.imageLogoHeight1; doc.addImage(logoImages.imageLogo1, 'JPEG', layout.marginLeft, y, logoImages.imageLogoWidth1, logoImages.imageLogoHeight1); } doc.setFontSize(9); SetPdfColor('LightBlue', doc, 'primary'); displayAccount(doc, invoice, 220, layout.accountTop, layout); SetPdfColor('LightBlue', doc, 'primary'); doc.setFontSize('11'); doc.text(50, layout.headerTop, (invoice.is_quote ? invoiceLabels.quote : invoiceLabels.invoice).toUpperCase()); SetPdfColor('Black',doc); //set black color doc.setFontSize(9); var invoiceHeight = displayInvoice(doc, invoice, 50, 170, layout); var clientHeight = displayClient(doc, invoice, 220, 170, layout); var detailsHeight = Math.max(invoiceHeight, clientHeight); layout.tableTop = Math.max(layout.tableTop, layout.headerTop + detailsHeight + (3 * layout.rowHeight)); doc.setLineWidth(0.3); doc.setDrawColor(200,200,200); doc.line(layout.marginLeft - layout.tablePadding, layout.headerTop + 6, layout.marginRight + layout.tablePadding, layout.headerTop + 6); doc.line(layout.marginLeft - layout.tablePadding, layout.headerTop + detailsHeight + 14, layout.marginRight + layout.tablePadding, layout.headerTop + detailsHeight + 14); doc.setFontSize(10); doc.setFontType('bold'); displayInvoiceHeader(doc, invoice, layout); var y = displayInvoiceItems(doc, invoice, layout); doc.setFontSize(9); doc.setFontType('bold'); GlobalY=GlobalY+25; doc.setLineWidth(0.3); doc.setDrawColor(241,241,241); doc.setFillColor(241,241,241); var x1 = layout.marginLeft - 12; var y1 = GlobalY-layout.tablePadding; var w2 = 510 + 24; var h2 = doc.internal.getFontSize()*3+layout.tablePadding*2; if (invoice.discount) { h2 += doc.internal.getFontSize()*2; } if (invoice.tax_amount) { h2 += doc.internal.getFontSize()*2; } //doc.rect(x1, y1, w2, h2, 'FD'); doc.setFontSize(9); displayNotesAndTerms(doc, layout, invoice, y); y += displaySubtotals(doc, layout, invoice, y, layout.unitCostRight); doc.setFontSize(10); Msg = invoice.is_quote ? invoiceLabels.total : invoiceLabels.balance_due; var TmpMsgX = layout.unitCostRight-(doc.getStringUnitWidth(Msg) * doc.internal.getFontSize()); doc.text(TmpMsgX, y, Msg); SetPdfColor('LightBlue', doc, 'primary'); AmountText = formatMoney(invoice.balance_amount, currencyId); headerLeft=layout.headerRight+400; var AmountX = layout.lineTotalRight - (doc.getStringUnitWidth(AmountText) * doc.internal.getFontSize()); doc.text(AmountX, y, AmountText);" ]); DB::table('invoice_designs')->where('id', 2)->update([ 'javascript' => " var GlobalY=0;//Y position of line at current page var client = invoice.client; var account = invoice.account; var currencyId = client.currency_id; layout.headerRight = 150; layout.rowHeight = 15; layout.headerTop = 125; layout.tableTop = 300; doc.setLineWidth(0.5); if (NINJA.primaryColor) { setDocHexFill(doc, NINJA.primaryColor); setDocHexDraw(doc, NINJA.primaryColor); } else { doc.setFillColor(46,43,43); } var x1 =0; var y1 = 0; var w2 = 595; var h2 = 100; doc.rect(x1, y1, w2, h2, 'FD'); if (invoice.image) { var left = layout.headerRight - invoice.imageWidth; doc.addImage(invoice.image, 'JPEG', layout.marginLeft, 30); } doc.setLineWidth(0.5); if (NINJA.primaryColor) { setDocHexFill(doc, NINJA.primaryColor); setDocHexDraw(doc, NINJA.primaryColor); } else { doc.setFillColor(46,43,43); doc.setDrawColor(46,43,43); } // return doc.setTextColor(240,240,240);//select color Custom Report GRAY Colour var x1 = 0;//tableLeft-tablePadding ; var y1 = 750; var w2 = 596; var h2 = 94;//doc.internal.getFontSize()*length+length*1.1;//+h;//+tablePadding; doc.rect(x1, y1, w2, h2, 'FD'); if (!invoice.is_pro && logoImages.imageLogo2) { pageHeight=820; var left = 250;//headerRight ; y=pageHeight-logoImages.imageLogoHeight2; var headerRight=370; var left = headerRight - logoImages.imageLogoWidth2; doc.addImage(logoImages.imageLogo2, 'JPEG', left, y, logoImages.imageLogoWidth2, logoImages.imageLogoHeight2); } doc.setFontSize(7); doc.setFontType('bold'); SetPdfColor('White',doc); displayAccount(doc, invoice, 300, layout.accountTop, layout); var y = layout.accountTop; var left = layout.marginLeft; var headerY = layout.headerTop; SetPdfColor('GrayLogo',doc); //set black color doc.setFontSize(7); //show left column SetPdfColor('Black',doc); //set black color doc.setFontType('normal'); //publish filled box doc.setDrawColor(200,200,200); if (NINJA.secondaryColor) { setDocHexFill(doc, NINJA.secondaryColor); } else { doc.setFillColor(54,164,152); } GlobalY=190; doc.setLineWidth(0.5); var BlockLenght=220; var x1 =595-BlockLenght; var y1 = GlobalY-12; var w2 = BlockLenght; var h2 = getInvoiceDetailsHeight(invoice, layout) + layout.tablePadding + 2; doc.rect(x1, y1, w2, h2, 'FD'); SetPdfColor('SomeGreen', doc, 'secondary'); doc.setFontSize('14'); doc.setFontType('bold'); doc.text(50, GlobalY, (invoice.is_quote ? invoiceLabels.your_quote : invoiceLabels.your_invoice).toUpperCase()); var z=GlobalY; z=z+30; doc.setFontSize('8'); SetPdfColor('Black',doc); var clientHeight = displayClient(doc, invoice, layout.marginLeft, z, layout); layout.tableTop += Math.max(0, clientHeight - 75); marginLeft2=395; //publish left side information SetPdfColor('White',doc); doc.setFontSize('8'); var detailsHeight = displayInvoice(doc, invoice, marginLeft2, z-25, layout) + 75; layout.tableTop = Math.max(layout.tableTop, layout.headerTop + detailsHeight + (2 * layout.tablePadding)); y=z+60; x = GlobalY + 100; doc.setFontType('bold'); doc.setFontSize(12); doc.setFontType('bold'); SetPdfColor('Black',doc); displayInvoiceHeader(doc, invoice, layout); var y = displayInvoiceItems(doc, invoice, layout); doc.setLineWidth(0.3); displayNotesAndTerms(doc, layout, invoice, y); y += displaySubtotals(doc, layout, invoice, y, layout.unitCostRight); doc.setFontType('bold'); doc.setFontSize(12); x += doc.internal.getFontSize()*4; Msg = invoice.is_quote ? invoiceLabels.total : invoiceLabels.balance_due; var TmpMsgX = layout.unitCostRight-(doc.getStringUnitWidth(Msg) * doc.internal.getFontSize()); doc.text(TmpMsgX, y, Msg); //SetPdfColor('LightBlue',doc); AmountText = formatMoney(invoice.balance_amount , currencyId); headerLeft=layout.headerRight+400; var AmountX = headerLeft - (doc.getStringUnitWidth(AmountText) * doc.internal.getFontSize()); SetPdfColor('SomeGreen', doc, 'secondary'); doc.text(AmountX, y, AmountText);" ]); DB::table('invoice_designs')->where('id', 3)->update([ 'javascript' => " var client = invoice.client; var account = invoice.account; var currencyId = client.currency_id; layout.headerRight = 400; layout.rowHeight = 15; doc.setFontSize(7); // add header doc.setLineWidth(0.5); if (NINJA.primaryColor) { setDocHexFill(doc, NINJA.primaryColor); setDocHexDraw(doc, NINJA.primaryColor); } else { doc.setDrawColor(242,101,34); doc.setFillColor(242,101,34); } var x1 =0; var y1 = 0; var w2 = 595; var h2 = Math.max(110, getInvoiceDetailsHeight(invoice, layout) + 30); doc.rect(x1, y1, w2, h2, 'FD'); SetPdfColor('White',doc); //second column doc.setFontType('bold'); var name = invoice.account.name; if (name) { doc.setFontSize('30'); doc.setFontType('bold'); doc.text(40, 50, name); } if (invoice.image) { y=130; var left = layout.headerRight - invoice.imageWidth; doc.addImage(invoice.image, 'JPEG', layout.marginLeft, y); } // add footer doc.setLineWidth(0.5); if (NINJA.primaryColor) { setDocHexFill(doc, NINJA.primaryColor); setDocHexDraw(doc, NINJA.primaryColor); } else { doc.setDrawColor(242,101,34); doc.setFillColor(242,101,34); } var x1 = 0;//tableLeft-tablePadding ; var y1 = 750; var w2 = 596; var h2 = 94;//doc.internal.getFontSize()*length+length*1.1;//+h;//+tablePadding; doc.rect(x1, y1, w2, h2, 'FD'); if (!invoice.is_pro && logoImages.imageLogo3) { pageHeight=820; // var left = 25;//250;//headerRight ; y=pageHeight-logoImages.imageLogoHeight3; //var headerRight=370; //var left = headerRight - invoice.imageLogoWidth3; doc.addImage(logoImages.imageLogo3, 'JPEG', 40, y, logoImages.imageLogoWidth3, logoImages.imageLogoHeight3); } doc.setFontSize(10); var marginLeft = 340; displayAccount(doc, invoice, marginLeft, 780, layout); SetPdfColor('White',doc); doc.setFontSize('8'); var detailsHeight = displayInvoice(doc, invoice, layout.headerRight, layout.accountTop-10, layout); layout.headerTop = Math.max(layout.headerTop, detailsHeight + 50); layout.tableTop = Math.max(layout.tableTop, detailsHeight + 150); SetPdfColor('Black',doc); //set black color doc.setFontSize(7); doc.setFontType('normal'); displayClient(doc, invoice, layout.headerRight, layout.headerTop, layout); SetPdfColor('White',doc); doc.setFontType('bold'); doc.setLineWidth(0.3); if (NINJA.secondaryColor) { setDocHexFill(doc, NINJA.secondaryColor); setDocHexDraw(doc, NINJA.secondaryColor); } else { doc.setDrawColor(63,60,60); doc.setFillColor(63,60,60); } var left = layout.marginLeft - layout.tablePadding; var top = layout.tableTop - layout.tablePadding; var width = layout.marginRight - (2 * layout.tablePadding); var height = 20; doc.rect(left, top, width, height, 'FD'); displayInvoiceHeader(doc, invoice, layout); SetPdfColor('Black',doc); var y = displayInvoiceItems(doc, invoice, layout); var height1 = displayNotesAndTerms(doc, layout, invoice, y); var height2 = displaySubtotals(doc, layout, invoice, y, layout.unitCostRight); y += Math.max(height1, height2); var left = layout.marginLeft - layout.tablePadding; var top = y - layout.tablePadding; var width = layout.marginRight - (2 * layout.tablePadding); var height = 20; if (NINJA.secondaryColor) { setDocHexFill(doc, NINJA.secondaryColor); setDocHexDraw(doc, NINJA.secondaryColor); } else { doc.setDrawColor(63,60,60); doc.setFillColor(63,60,60); } doc.rect(left, top, width, height, 'FD'); doc.setFontType('bold'); SetPdfColor('White', doc); doc.setFontSize(12); var label = invoice.is_quote ? invoiceLabels.total : invoiceLabels.balance_due; var labelX = layout.unitCostRight-(doc.getStringUnitWidth(label) * doc.internal.getFontSize()); doc.text(labelX, y+2, label); doc.setFontType('normal'); var amount = formatMoney(invoice.balance_amount , currencyId); headerLeft=layout.headerRight+400; var amountX = layout.lineTotalRight - (doc.getStringUnitWidth(amount) * doc.internal.getFontSize()); doc.text(amountX, y+2, amount);" ]); DB::table('invoice_designs')->where('id', 4)->update([ 'javascript' => " var client = invoice.client; var account = invoice.account; var currencyId = client.currency_id; layout.accountTop += 25; layout.headerTop += 25; layout.tableTop += 25; if (invoice.image) { var left = layout.headerRight - invoice.imageWidth; doc.addImage(invoice.image, 'JPEG', left, 50); } /* table header */ doc.setDrawColor(200,200,200); doc.setFillColor(230,230,230); var detailsHeight = getInvoiceDetailsHeight(invoice, layout); var left = layout.headerLeft - layout.tablePadding; var top = layout.headerTop + detailsHeight - layout.rowHeight - layout.tablePadding; var width = layout.headerRight - layout.headerLeft + (2 * layout.tablePadding); var height = layout.rowHeight + 1; doc.rect(left, top, width, height, 'FD'); doc.setFontSize(10); doc.setFontType('normal'); displayAccount(doc, invoice, layout.marginLeft, layout.accountTop, layout); displayClient(doc, invoice, layout.marginLeft, layout.headerTop, layout); displayInvoice(doc, invoice, layout.headerLeft, layout.headerTop, layout, layout.headerRight); layout.tableTop = Math.max(layout.tableTop, layout.headerTop + detailsHeight + (2 * layout.tablePadding)); var headerY = layout.headerTop; var total = 0; doc.setDrawColor(200,200,200); doc.setFillColor(230,230,230); var left = layout.marginLeft - layout.tablePadding; var top = layout.tableTop - layout.tablePadding; var width = layout.headerRight - layout.marginLeft + (2 * layout.tablePadding); var height = layout.rowHeight + 2; doc.rect(left, top, width, height, 'FD'); displayInvoiceHeader(doc, invoice, layout); var y = displayInvoiceItems(doc, invoice, layout); doc.setFontSize(10); displayNotesAndTerms(doc, layout, invoice, y+20); y += displaySubtotals(doc, layout, invoice, y+20, 480) + 20; doc.setDrawColor(200,200,200); doc.setFillColor(230,230,230); var left = layout.footerLeft - layout.tablePadding; var top = y - layout.tablePadding; var width = layout.headerRight - layout.footerLeft + (2 * layout.tablePadding); var height = layout.rowHeight + 2; doc.rect(left, top, width, height, 'FD'); doc.setFontType('bold'); doc.text(layout.footerLeft, y, invoice.is_quote ? invoiceLabels.total : invoiceLabels.balance_due); total = formatMoney(invoice.balance_amount, currencyId); var totalX = layout.headerRight - (doc.getStringUnitWidth(total) * doc.internal.getFontSize()); doc.text(totalX, y, total); if (!invoice.is_pro) { doc.setFontType('normal'); doc.text(layout.marginLeft, 790, 'Created by InvoiceNinja.com'); }" ]); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('invoice_designs', function($table) { $table->dropColumn('javascript'); }); Schema::table('accounts', function($table) { $table->dropColumn('invoice_design'); }); } } <file_sep>/tests/_support/AcceptanceTester.php <?php use Codeception\Util\Fixtures; /** * Inherited Methods * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = null) * * @SuppressWarnings(PHPMD) */ class AcceptanceTester extends \Codeception\Actor { use _generated\AcceptanceTesterActions; /** * Define custom actions here */ function checkIfLogin(\AcceptanceTester $I) { //if ($I->loadSessionSnapshot('login')) return; $I->amOnPage('/login'); $I->fillField(['name' => 'email'], Fixtures::get('username')); $I->fillField(['name' => 'password'], Fixtures::get('password')); $I->click('Let\'s go'); //$I->saveSessionSnapshot('login'); } function selectDataPicker(\AcceptanceTester $I, $element, $date = 'now') { $_date = date('Y, m, d', strtotime($date)); $I->executeJS(sprintf('$(\'%s\').datepicker(\'update\', new Date(%s))', $element, $_date)); } function selectDropdown(\AcceptanceTester $I, $option, $dropdownSelector) { $I->click($dropdownSelector); $I->click(sprintf('ul.typeahead li[data-value="%s"]', $option)); } function selectDropdownRow(\AcceptanceTester $I, $option, $dropdownSelector) { $I->click("$dropdownSelector span.dropdown-toggle"); $I->click("$dropdownSelector ul li:nth-child($option)"); } } <file_sep>/app/Ninja/Repositories/TaxRateRepository.php <?php namespace App\Ninja\Repositories; use App\Models\TaxRate; use Utils; class TaxRateRepository { public function save($taxRates) { $taxRateIds = []; foreach ($taxRates as $record) { if (!isset($record->rate) || (isset($record->is_deleted) && $record->is_deleted)) { continue; } if (!isset($record->name) || !trim($record->name)) { continue; } if ($record->public_id) { $taxRate = TaxRate::scope($record->public_id)->firstOrFail(); } else { $taxRate = TaxRate::createNew(); } $taxRate->rate = Utils::parseFloat($record->rate); $taxRate->name = trim($record->name); $taxRate->save(); $taxRateIds[] = $taxRate->public_id; } $taxRates = TaxRate::scope()->get(); foreach ($taxRates as $taxRate) { if (!in_array($taxRate->public_id, $taxRateIds)) { $taxRate->delete(); } } } } <file_sep>/tests/acceptance/CreditCest.php <?php use \AcceptanceTester; use App\Models\Credit; use Faker\Factory; use Codeception\Util\Fixtures; class CreditCest { private $faker; public function _before(AcceptanceTester $I) { $I->checkIfLogin($I); $this->faker = Factory::create(); } public function create(AcceptanceTester $I) { $note = $this->faker->catchPhrase; $clientName = $I->grabFromDatabase('clients', 'name'); $I->wantTo('Create a credit'); $I->amOnPage('/credits/create'); $I->selectDropdown($I, $clientName, '.client-select .dropdown-toggle'); $I->fillField(['name' => 'amount'], rand(50, 200)); $I->fillField(['name' => 'private_notes'], $note); $I->selectDataPicker($I, '#credit_date', 'now + 1 day'); $I->click('Save'); $I->see('Successfully created credit'); $I->seeInDatabase('credits', array('private_notes' => $note)); $I->amOnPage('/credits'); $I->seeCurrentUrlEquals('/credits'); $I->see($clientName); } }<file_sep>/app/Models/Payment.php <?php namespace App\Models; use Illuminate\Database\Eloquent\SoftDeletes; class Payment extends EntityModel { use SoftDeletes; protected $dates = ['deleted_at']; public function invoice() { return $this->belongsTo('App\Models\Invoice')->withTrashed(); } public function invitation() { return $this->belongsTo('App\Models\Invitation'); } public function client() { return $this->belongsTo('App\Models\Client')->withTrashed(); } public function user() { return $this->belongsTo('App\Models\User')->withTrashed(); } public function account() { return $this->belongsTo('App\Models\Account'); } public function contact() { return $this->belongsTo('App\Models\Contact'); } public function getAmount() { return Utils::formatMoney($this->amount, $this->client->getCurrencyId()); } public function getName() { return trim("payment {$this->transaction_reference}"); } public function getEntityType() { return ENTITY_PAYMENT; } } Payment::created(function ($payment) { Activity::createPayment($payment); }); Payment::updating(function ($payment) { Activity::updatePayment($payment); }); Payment::deleting(function ($payment) { Activity::archivePayment($payment); }); Payment::restoring(function ($payment) { Activity::restorePayment($payment); }); <file_sep>/storage/templates/clean.js { "content": [{ "columns": [ { "image": "$accountLogo", "fit": [120, 80] }, { "stack": "$accountDetails", "margin": [40, 0, 0, 0] }, { "stack": "$accountAddress" } ] }, { "text": "$entityTypeUC", "margin": [8, 30, 8, 5], "style": "entityTypeLabel" }, { "table": { "headerRows": 1, "widths": ["auto", "auto", "*"], "body": [ [ { "table": { "body": "$invoiceDetails" }, "margin": [0, 4, 12, 4], "layout": "noBorders" }, { "stack": "$clientDetails" }, { "text": "" } ] ] }, "layout": { "hLineWidth": "$firstAndLast:.5", "vLineWidth": "$none", "hLineColor": "#D8D8D8", "paddingLeft": "$amount:8", "paddingRight": "$amount:8", "paddingTop": "$amount:4", "paddingBottom": "$amount:4" } }, { "style": "invoiceLineItemsTable", "table": { "headerRows": 1, "widths": "$invoiceLineItemColumns", "body": "$invoiceLineItems" }, "layout": { "hLineWidth": "$notFirst:.5", "vLineWidth": "$none", "hLineColor": "#D8D8D8", "paddingLeft": "$amount:8", "paddingRight": "$amount:8", "paddingTop": "$amount:14", "paddingBottom": "$amount:14" } }, { "columns": [ "$notesAndTerms", { "table": { "widths": ["*", "40%"], "body": "$subtotals" }, "layout": { "hLineWidth": "$none", "vLineWidth": "$none", "paddingLeft": "$amount:34", "paddingRight": "$amount:8", "paddingTop": "$amount:4", "paddingBottom": "$amount:4" } } ] } ], "defaultStyle": { "fontSize": "$fontSize", "margin": [8, 4, 8, 4] }, "footer": { "columns": [ { "text": "$invoiceFooter", "alignment": "left" } ], "margin": [40, -20, 40, 0] }, "styles": { "entityTypeLabel": { "fontSize": "$fontSizeLargest", "color": "$primaryColor:#37a3c6" }, "primaryColor":{ "color": "$primaryColor:#37a3c6" }, "accountName": { "color": "$primaryColor:#37a3c6", "bold": true }, "invoiceDetails": { "margin": [0, 0, 8, 0] }, "accountDetails": { "margin": [0, 2, 0, 2] }, "clientDetails": { "margin": [0, 2, 0, 2] }, "notesAndTerms": { "margin": [0, 2, 0, 2] }, "accountAddress": { "margin": [0, 2, 0, 2] }, "odd": { "fillColor": "#fbfbfb" }, "productKey": { "color": "$primaryColor:#37a3c6", "bold": true }, "balanceDueLabel": { "fontSize": "$fontSizeLarger" }, "balanceDue": { "fontSize": "$fontSizeLarger", "color": "$primaryColor:#37a3c6" }, "invoiceNumber": { "bold": true }, "tableHeader": { "bold": true, "fontSize": "$fontSizeLarger" }, "invoiceLineItemsTable": { "margin": [0, 16, 0, 16] }, "clientName": { "bold": true }, "cost": { "alignment": "right" }, "quantity": { "alignment": "right" }, "tax": { "alignment": "right" }, "lineTotal": { "alignment": "right" }, "subtotals": { "alignment": "right" }, "termsLabel": { "bold": true } }, "pageMargins": [40, 40, 40, 60] }<file_sep>/resources/lang/de/texts.php <?php return array( // client 'organization' => 'Organisation', 'name' => 'Name', 'website' => 'Webseite', 'work_phone' => 'Telefon', 'address' => 'Adresse', 'address1' => 'Straße', 'address2' => 'Adresszusatz', 'city' => 'Stadt', 'state' => 'Bundesland', 'postal_code' => 'Postleitzahl', 'country_id' => 'Land', 'contacts' => 'Kontakte', 'first_name' => 'Vorname', 'last_name' => 'Nachname', 'phone' => 'Telefon', 'email' => 'Email', 'additional_info' => 'Zusätzliche Info', 'payment_terms' => 'Zahlungsbedingungen', 'currency_id' => 'Währung', 'size_id' => 'Größe', 'industry_id' => 'Kategorie', 'private_notes' => 'Notizen', // invoice 'invoice' => 'Rechnung', 'client' => 'Kunde', 'invoice_date' => 'Rechnungsdatum', 'due_date' => 'Fällig am', 'invoice_number' => 'Rechungsnummer', 'invoice_number_short' => 'Rechnung #', 'po_number' => 'Bestellnummer', 'po_number_short' => 'BN #', 'frequency_id' => 'Wie oft', 'discount' => 'Rabatt', 'taxes' => 'Steuern', 'tax' => 'Steuer', 'item' => 'Artikel', 'description' => 'Beschreibung', 'unit_cost' => 'Kosten pro Einheit', 'quantity' => 'Menge', 'line_total' => 'Summe', 'subtotal' => 'Zwischensumme', 'paid_to_date' => 'Bereits gezahlt', 'balance_due' => 'Geschuldeter Betrag', 'invoice_design_id' => 'Design', 'terms' => 'Bedingungen', 'your_invoice' => 'Ihre Rechnung', 'remove_contact' => 'Kontakt löschen', 'add_contact' => 'Kontakt hinzufügen', 'create_new_client' => 'Einen neuen Kunden erstellen', 'edit_client_details' => 'Kundendetails bearbeiten', 'enable' => 'Aktivieren', 'learn_more' => 'Mehr erfahren', 'manage_rates' => 'Steuersätze verwalten', 'note_to_client' => 'Notiz an den Kunden', 'invoice_terms' => 'Zahlungsbedingungen', 'save_as_default_terms' => 'Als Standardbedingungen speichern', 'download_pdf' => 'PDF herunterladen', 'pay_now' => 'Jetzt bezahlen', 'save_invoice' => 'Rechnung speichern', 'clone_invoice' => 'Rechnung duplizieren', 'archive_invoice' => 'Rechnung archivieren', 'delete_invoice' => 'Rechnung löschen', 'email_invoice' => 'Rechnung versenden', 'enter_payment' => 'Zahlung eingeben', 'tax_rates' => 'Steuersätze', 'rate' => 'Satz', 'settings' => 'Einstellungen', 'enable_invoice_tax' => 'Ermögliche das Bestimmen einer <strong>Rechnungssteuer</strong>', 'enable_line_item_tax' => 'Ermögliche das Bestimmen von <strong>Steuern für Belegpositionen</strong>', // navigation 'dashboard' => 'Dashboard', 'clients' => 'Kunden', 'invoices' => 'Rechnungen', 'payments' => 'Zahlungen', 'credits' => 'Guthaben', 'history' => 'Verlauf', 'search' => 'Suche', 'sign_up' => 'Anmeldung', 'guest' => 'Gast', 'company_details' => 'Firmendaten', 'online_payments' => 'Online-Zahlungen', 'notifications' => 'Benachrichtigungen', 'import_export' => 'Import/Export', 'done' => 'Erledigt', 'save' => 'Speichern', 'create' => 'Erstellen', 'upload' => 'Hochladen', 'import' => 'Importieren', 'download' => 'Downloaden', 'cancel' => 'Abbrechen', 'provide_email' => 'Bitte gib eine gültige E-Mail-Adresse an', 'powered_by' => 'Powered by', 'no_items' => 'Keine Objekte', // recurring invoices 'recurring_invoices' => 'Wiederkehrende Rechnungen', 'recurring_help' => '<p>Sende deinem Kunden wöchentlich, zwei mal im Monat, monatlich, vierteljährlich oder jährlich automatisch die gleiche Rechnung.</p> <p>Benutze :MONTH, :QUARTER oder :YEAR für ein dynamisches Datum. Grundlegende Mathematik funktioniert genauso gut, zum Beispiel :MONTH-1.</p> <p>Beispiel zu dynamischen Rechnungs-Variabeln:</p> <ul> <li>"Fitnessstudio-Mitgliedschaft für den Monat :MONTH" => "Fitnessstudio-Mitgliedschaft für den Monat Juli"</li> <li>":YEAR+1 Jahresbeitrag" => "2015 Jahresbeitrag"</li> <li>"Vorschusszahlung für :QUARTER+1" => "Vorschusszahlung für Q2"</li> </ul>', // dashboard 'in_total_revenue' => 'Gesamtumsatz', 'billed_client' => 'abgerechneter Kunde', 'billed_clients' => 'abgerechnete Kunden', 'active_client' => 'aktiver Kunde', 'active_clients' => 'aktive Kunden', 'invoices_past_due' => 'Fällige Rechnungen', 'upcoming_invoices' => 'Kommende Rechnungen', 'average_invoice' => 'Durchschnittlicher Rechnungsbetrag', // list pages 'archive' => 'archivieren', 'delete' => 'löschen', 'archive_client' => 'Kunde archivieren', 'delete_client' => 'Kunde löschen', 'archive_payment' => 'Zahlung archivieren', 'delete_payment' => 'Zahlung löschen', 'archive_credit' => 'Guthaben archivieren', 'delete_credit' => 'Guthaben löschen', 'show_archived_deleted' => 'Zeige archivierte/gelöschte', 'filter' => 'Filter', 'new_client' => 'Neuer Kunde', 'new_invoice' => 'Neue Rechnung', 'new_payment' => 'Neue Zahlung', 'new_credit' => 'Neues Guthaben', 'contact' => 'Kontakt', 'date_created' => 'Erstellungsdatum', 'last_login' => 'Letzter Login', 'balance' => 'Saldo', 'action' => 'Aktion', 'status' => 'Status', 'invoice_total' => 'Rechnungsbetrag', 'frequency' => 'Häufigkeit', 'start_date' => 'Startdatum', 'end_date' => 'Enddatum', 'transaction_reference' => 'Abwicklungsreferenz', 'method' => 'Verfahren', 'payment_amount' => 'Zahlungsbetrag', 'payment_date' => 'Zahlungsdatum', 'credit_amount' => 'Guthabenbetrag', 'credit_balance' => 'Guthabenstand', 'credit_date' => 'Guthabendatum', 'empty_table' => 'Es sind keine Daten vorhanden', 'select' => 'Wählen', 'edit_client' => 'Kunde bearbeiten', 'edit_invoice' => 'Rechnung bearbeiten', // client view page 'create_invoice' => 'Rechnung erstellen', 'enter_credit' => 'Guthaben eingeben', 'last_logged_in' => 'Zuletzt eingeloggt', 'details' => 'Details', 'standing' => 'Aktueller Stand', 'credit' => 'Guthaben', 'activity' => 'Aktivität', 'date' => 'Datum', 'message' => 'Nachricht', 'adjustment' => 'Anpassung', 'are_you_sure' => 'Bist du dir sicher?', // payment pages 'payment_type_id' => 'Zahlungsart', 'amount' => 'Betrag', // account/company pages 'work_email' => 'E-Mail', 'language_id' => 'Sprache', 'timezone_id' => 'Zeitzone', 'date_format_id' => 'Datumsformat', 'datetime_format_id' => 'Datums-/Zeitformat', 'users' => 'Benutzer', 'localization' => 'Lokalisierung', 'remove_logo' => 'Logo entfernen', 'logo_help' => 'Unterstützt: JPEG, GIF und PNG. Empfohlene Höhe: 120px', 'payment_gateway' => 'Zahlungseingang', 'gateway_id' => 'Provider', 'email_notifications' => 'E-Mail Benachrichtigungen', 'email_sent' => 'Benachrichtigen, wenn eine Rechnung <strong>versendet</strong> wurde', 'email_viewed' => 'Benachrichtigen, wenn eine Rechnung <strong>betrachtet</strong> wurde', 'email_paid' => 'Benachrichtigen, wenn eine Rechnung <strong>bezahlt</strong> wurde', 'site_updates' => 'Seiten Updates', 'custom_messages' => 'Benutzerdefinierte Nachrichten', 'default_invoice_terms' => 'Standard Rechnungsbedingungen', 'default_email_footer' => 'Standard E-Mail Signatur', 'import_clients' => 'Importiere Kundendaten', 'csv_file' => 'Wähle CSV Datei', 'export_clients' => 'Exportiere Kundendaten', 'select_file' => 'Bitte wähle eine Datei', 'first_row_headers' => 'Benutze erste Zeile als Kopfzeile', 'column' => 'Spalte', 'sample' => 'Beispiel', 'import_to' => 'Importieren nach', 'client_will_create' => 'Kunde wird erstellt', 'clients_will_create' => 'Kunden werden erstellt', 'email_settings' => 'E-Mail-Einstellungen', 'pdf_email_attachment' => 'PDF an E-Mails anhängen', // application messages 'created_client' => 'Kunde erfolgreich angelegt', 'created_clients' => ':count Kunden erfolgreich angelegt', 'updated_settings' => 'Einstellungen erfolgreich aktualisiert', 'removed_logo' => 'Logo erfolgreich entfernt', 'sent_message' => 'Nachricht erfolgreich versendet', 'invoice_error' => 'Bitte stelle sicher, dass ein Kunde ausgewählt und alle Fehler behoben wurden', 'limit_clients' => 'Entschuldige, das überschreitet das Limit von :count Kunden', 'payment_error' => 'Es ist ein Fehler während der Zahlung aufgetreten. Bitte versuche es später noch einmal.', 'registration_required' => 'Bitte melde dich an um eine Rechnung zu versenden', 'confirmation_required' => 'Bitte bestätige deine E-Mail-Adresse', 'updated_client' => 'Kunde erfolgreich aktualisiert', 'created_client' => 'Kunde erfolgreich erstellt', 'archived_client' => 'Kunde erfolgreich archiviert', 'archived_clients' => ':count Kunden erfolgreich archiviert', 'deleted_client' => 'Kunde erfolgreich gelöscht', 'deleted_clients' => ':count Kunden erfolgreich gelöscht', 'updated_invoice' => 'Rechnung erfolgreich aktualisiert', 'created_invoice' => 'Rechnung erfolgreich erstellt', 'cloned_invoice' => 'Rechnung erfolgreich dupliziert', 'emailed_invoice' => 'Rechnung erfolgreich versendet', 'and_created_client' => 'und Kunde erstellt', 'archived_invoice' => 'Rechnung erfolgreich archiviert', 'archived_invoices' => ':count Rechnungen erfolgreich archiviert', 'deleted_invoice' => 'Rechnung erfolgreich gelöscht', 'deleted_invoices' => ':count Rechnungen erfolgreich gelöscht', 'created_payment' => 'Zahlung erfolgreich erstellt', 'archived_payment' => 'Zahlung erfolgreich archiviert', 'archived_payments' => ':count Zahlungen erfolgreich archiviert', 'deleted_payment' => 'Zahlung erfolgreich gelöscht', 'deleted_payments' => ':count Zahlungen erfolgreich gelöscht', 'applied_payment' => 'Zahlung erfolgreich angewandt', 'created_credit' => 'Guthaben erfolgreich erstellt', 'archived_credit' => 'Guthaben erfolgreich archiviert', 'archived_credits' => ':count Guthaben erfolgreich archiviert', 'deleted_credit' => 'Guthaben erfolgreich gelöscht', 'deleted_credits' => ':count Guthaben erfolgreich gelöscht', // Emails 'confirmation_subject' => 'InvoiceNinja Kontobestätigung', 'confirmation_header' => 'Kontobestätigung', 'confirmation_message' => 'Bitte klicke auf den folgenden Link um dein Konto zu bestätigen.', 'invoice_message' => 'Um Ihre Rechnung über :amount einzusehen, klicken Sie bitte auf den folgenden Link:', 'payment_subject' => 'Zahlungseingang', 'payment_message' => 'Vielen Dank für Ihre Zahlung von :amount.', 'email_salutation' => 'Sehr geehrte/r :name,', 'email_signature' => 'Mit freundlichen Grüßen,', 'email_from' => 'Das InvoiceNinja Team', 'user_email_footer' => 'Um deine E-Mail-Benachrichtigungen anzupassen besuche bitte '.SITE_URL.'/company/notifications', 'invoice_link_message' => 'Um deine Kundenrechnung anzuschauen, klicke auf den folgenden Link:', 'notification_invoice_paid_subject' => 'Die Rechnung :invoice wurde von :client bezahlt', 'notification_invoice_sent_subject' => 'Die Rechnung :invoice wurde an :client versendet', 'notification_invoice_viewed_subject' => 'Die Rechnung :invoice wurde von :client angeschaut', 'notification_invoice_paid' => 'Eine Zahlung von :amount wurde von :client bezüglich Rechnung :invoice getätigt.', 'notification_invoice_sent' => 'Dem folgenden Kunden :client wurde die Rechnung :invoice über :amount zugesendet.', 'notification_invoice_viewed' => 'Der folgende Kunde :client hat sich Rechnung :invoice über :amount angesehen.', 'reset_password' => 'Du kannst dein Passwort zurücksetzen, indem du auf den folgenden Link klickst:', 'reset_password_footer' => 'Wenn du das Zurücksetzen des Passworts nicht beantragt hast, benachrichtige bitte unseren Support: ' . CONTACT_EMAIL, // Payment page 'secure_payment' => 'Sichere Zahlung', 'card_number' => 'Kartennummer', 'expiration_month' => 'Ablaufmonat', 'expiration_year' => 'Ablaufjahr', 'cvv' => 'Kartenprüfziffer', // Security alerts 'security' => array( 'too_many_attempts' => 'Zu viele Versuche. Bitte probiere es in ein paar Minuten erneut.', 'wrong_credentials' => 'Falsche E-Mail-Adresse oder falsches Passwort.', 'confirmation' => 'Dein Konto wurde bestätigt!', 'wrong_confirmation' => 'Falscher Bestätigungscode.', 'password_forgot' => 'Weitere Informationen um das Passwort zurückzusetzen wurden dir per E-Mail zugeschickt.', 'password_reset' => 'Dein Passwort wurde erfolgreich geändert.', 'wrong_password_reset' => 'Ungültiges Passwort. Versuche es erneut', ), // Pro Plan 'pro_plan' => [ 'remove_logo' => ':link, um das InvoiceNinja-Logo zu entfernen, indem du dem Pro Plan beitrittst', 'remove_logo_link' => 'Klicke hier', ], 'logout' => 'Ausloggen', 'sign_up_to_save' => 'Melde dich an, um deine Arbeit zu speichern', 'agree_to_terms' =>'Ich akzeptiere die InvoiceNinja :terms', 'terms_of_service' => 'Service-Bedingungen', 'email_taken' => 'Diese E-Mail-Adresse ist bereits registriert', 'working' => 'Wird bearbeitet', 'success' => 'Erfolg', 'success_message' => 'Du hast dich erfolgreich registriert. Bitte besuche den Link in deiner Bestätigungsmail um deine E-Mail-Adresse zu verifizieren.', 'erase_data' => 'Diese Aktion wird deine Daten dauerhaft löschen.', 'password' => '<PASSWORD>', 'invoice_subject' => 'Neue Rechnung :invoice von :account', 'close' => 'Schließen', 'pro_plan_product' => 'Pro Plan', 'pro_plan_description' => 'Jahresmitgliedschaft beim Invoice Ninja Pro Plan.', 'pro_plan_success' => 'Danke für den Beitritt! Sobald die Rechnung bezahlt wurde, beginnt deine Pro Plan Mitgliedschaft.', 'pro_plan_success' => 'Danke für den Beitritt! Sobald die Rechnung bezahlt wurde,Beim Auswählen eines Produktes werden beginnt deine Pro Plan Mitgliedschaft.', 'unsaved_changes' => 'Es liegen ungespeicherte Änderungen vor', 'custom_fields' => 'Benutzerdefinierte Felder', 'company_fields' => 'Firmenfelder', 'client_fields' => 'Kundenfelder', 'field_label' => 'Feldbezeichnung', 'field_value' => 'Feldwert', 'edit' => 'Bearbeiten', 'view_as_recipient' => 'Als Empfänger betrachten', // product management 'product' => 'Produkt', 'products' => 'Produkte', 'fill_products' => 'Produkte automatisch ausfüllen', 'fill_products_help' => 'Beim Auswählen eines Produktes werden automatisch <strong>Beschreibung und Kosten ausgefüllt</strong>', 'update_products' => 'Produkte automatisch aktualisieren', 'update_products_help' => 'Beim Aktualisieren einer Rechnung werden die <strong>Produkte automatisch aktualisiert</strong>', 'create_product' => 'Produkt erstellen', 'edit_product' => 'Produkt bearbeiten', 'archive_product' => 'Produkt archivieren', 'updated_product' => 'Produkt erfolgreich aktualisiert', 'created_product' => 'Produkt erfolgreich erstellt', 'archived_product' => 'Produkt erfolgreich archiviert', 'product_library' => 'Produktbibliothek', 'pro_plan_custom_fields' => ':link um durch eine Pro-Mitgliedschaft erweiterte Felder zu aktivieren', 'advanced_settings' => 'Erweiterte Einstellungen', 'pro_plan_advanced_settings' => ':link um durch eine Pro-Mitgliedschaft erweiterte Einstellungen zu aktivieren', 'invoice_design' => 'Rechnungsvorlage', 'specify_colors' => 'Farben wählen', 'specify_colors_label' => 'Wähle die in der Rechnung verwendeten Farben', 'chart_builder' => 'Diagrammersteller', 'ninja_email_footer' => 'Nutze :site um Kunden Rechnungen zu stellen und online bezahlt zu werden, kostenlos!', 'go_pro' => 'Werde Pro-Mitglied', // Quotes 'quote' => 'Angebot', 'quotes' => 'Angebote', 'quote_number' => 'Angebotsnummer', 'quote_number_short' => 'Angebot #', 'quote_date' => 'Angebotsdatum', 'quote_total' => 'Gesamtanzahl Angebote', 'your_quote' => 'Ihr Angebot', 'total' => 'Gesamt', 'clone' => 'Duplizieren', 'new_quote' => 'Neues Angebot', 'create_quote' => 'Angebot erstellen', 'edit_quote' => 'Angebot bearbeiten', 'archive_quote' => 'Angebot archivieren', 'delete_quote' => 'Angebot löschen', 'save_quote' => 'Angebot speichern', 'email_quote' => 'Angebot per E-Mail senden', 'clone_quote' => 'Angebot duplizieren', 'convert_to_invoice' => 'In Rechnung umwandeln', 'view_invoice' => 'Rechnung anschauen', 'view_quote' => 'Angebot anschauen', 'view_client' => 'Kunde anschauen', 'updated_quote' => 'Angebot erfolgreich aktualisiert', 'created_quote' => 'Angebot erfolgreich erstellt', 'cloned_quote' => 'Angebot erfolgreich dupliziert', 'emailed_quote' => 'Angebot erfolgreich versendet', 'archived_quote' => 'Angebot erfolgreich archiviert', 'archived_quotes' => ':count Angebote erfolgreich archiviert', 'deleted_quote' => 'Angebot erfolgreich gelöscht', 'deleted_quotes' => ':count Angebote erfolgreich gelöscht', 'converted_to_invoice' => 'Angebot erfolgreich in Rechnung umgewandelt', 'quote_subject' => 'Neues Angebot von :account', 'quote_message' => 'Klicken Sie auf den folgenden Link um das Angebot über :amount anzuschauen.', 'quote_link_message' => 'Klicke auf den folgenden Link um das Angebot deines Kunden anzuschauen:', 'notification_quote_sent_subject' => 'Angebot :invoice wurde an :client versendet', 'notification_quote_viewed_subject' => 'Angebot :invoice wurde von :client angeschaut', 'notification_quote_sent' => 'Der folgende Kunde :client erhielt das Angebot :invoice über :amount.', 'notification_quote_viewed' => 'Der folgende Kunde :client hat sich das Angebot :client über :amount angesehen.', 'session_expired' => 'Deine Sitzung ist abgelaufen.', 'invoice_fields' => 'Rechnungsfelder', 'invoice_options' => 'Rechnungsoptionen', 'hide_quantity' => 'Menge verbergen', 'hide_quantity_help' => 'Wenn deine Menge immer 1 beträgt, kannst du deine Rechnung einfach halten, indem du dieses Feld entfernst.', 'hide_paid_to_date' => '"Bereits gezahlt" ausblenden', 'hide_paid_to_date_help' => '"Bereits gezahlt" nur anzeigen, wenn eine Zahlung eingegangen ist.', 'charge_taxes' => 'Steuern erheben', 'user_management' => 'Benutzerverwaltung', 'add_user' => 'Add User', 'send_invite' => 'Einladung senden', 'sent_invite' => 'Einladung erfolgreich gesendet', 'updated_user' => 'Benutzer erfolgreich aktualisiert', 'invitation_message' => 'Du wurdest von :invitor eingeladen.', 'register_to_add_user' => 'Bitte registrieren, um einen Benutzer hinzuzufügen', 'user_state' => 'Status', 'edit_user' => 'Benutzer bearbeiten', 'delete_user' => 'Benutzer löschen', 'active' => 'Aktiv', 'pending' => 'Ausstehend', 'deleted_user' => 'Benutzer erfolgreich gelöscht', 'limit_users' => 'Entschuldige, das würde das Limit von ' . MAX_NUM_USERS . ' Benutzern überschreiten', 'confirm_email_invoice' => 'Bist du sicher, dass du diese Rechnung per E-Mail versenden möchtest?', 'confirm_email_quote' => 'Bist du sicher, dass du dieses Angebot per E-Mail versenden möchtest', 'confirm_recurring_email_invoice' => 'Wiederkehrende Rechnung ist aktiv. Bis du sicher, dass du diese Rechnung weiterhin als E-Mail verschicken möchtest?', 'cancel_account' => 'Konto Kündigen', 'cancel_account_message' => 'Warnung: Alle Daten werden unwiderruflich und vollständig gelöscht, es gibt kein zurück.', 'go_back' => 'Zurück', 'data_visualizations' => 'Datenvisualisierungen', 'sample_data' => 'Beispieldaten werden angezeigt', 'hide' => 'Verbergen', 'new_version_available' => 'Eine neue Version von :releases_link ist verfügbar. Du benutzt v:user_version, die aktuelle ist v:latest_version', 'invoice_settings' => 'Rechnungseinstellungen', 'invoice_number_prefix' => 'Präfix für Rechnungsnummer', 'invoice_number_counter' => 'Zähler für Rechnungsnummer', 'quote_number_prefix' => 'Präfix für Angebotsnummer', 'quote_number_counter' => 'Zähler für Angebotsnummer', 'share_invoice_counter' => 'Zähler der Rechnung teilen', 'invoice_issued_to' => 'Rechnung ausgestellt für', 'invalid_counter' => 'Bitte setze, um Probleme zu vermeiden, entweder ein Rechnungs- oder Angebotspräfix.', 'mark_sent' => 'Als gesendet markieren', 'gateway_help_1' => ':link um sich bei Authorize.net anzumelden.', 'gateway_help_2' => ':link um sich bei Authorize.net anzumelden.', 'gateway_help_17' => ':link um deine PayPal API-Signatur zu erhalten.', 'gateway_help_23' => 'Anmerkung: benutze deinen secret API key, nicht deinen publishable API key.', 'gateway_help_27' => ':link um sich bei TwoCheckout anzumelden.', 'more_designs' => 'Weitere Vorlagen', 'more_designs_title' => 'Zusätzliche Rechnungsvorlagen', 'more_designs_cloud_header' => 'Werde Pro-Mitglied für zusätzliche Rechnungsvorlagen', 'more_designs_cloud_text' => '', 'more_designs_self_host_header' => 'Erhalte 6 zusätzliche Rechnungsvorlagen für nur $'.INVOICE_DESIGNS_PRICE, 'more_designs_self_host_text' => '', 'buy' => 'Kaufen', 'bought_designs' => 'Die zusätzliche Rechnungsvorlagen wurden erfolgreich hinzugefügt', 'sent' => 'gesendet', 'timesheets' => 'Timesheets', 'payment_title' => 'Geben Sie Ihre Rechnungsadresse und Ihre Kreditkarteninformationen ein', 'payment_cvv' => '*Dies ist die 3-4-stellige Nummer auf der Rückseite Ihrer Kreditkarte', 'payment_footer1' => '*Die Rechnungsadresse muss mit der Adresse der Kreditkarte übereinstimmen.', 'payment_footer2' => '*Bitte drücken Sie nur einmal auf "Jetzt bezahlen" - die Verarbeitung der Transaktion kann bis zu einer Minute dauern.', 'vat_number' => 'USt-IdNr.', 'id_number' => 'ID-Nummer', 'white_label_link' => 'Branding entfernen', 'white_label_text' => 'Um das Invoice Ninja Logo auf der Kundenseite zu entfernen, kaufe bitte eine Lizenz für $'.WHITE_LABEL_PRICE, 'white_label_header' => 'Branding entfernen', 'bought_white_label' => 'Branding-freie Lizenz erfolgreich aktiviert', 'white_labeled' => 'Branding entfernt', 'restore' => 'Wiederherstellen', 'restore_invoice' => 'Rechnung wiederherstellen', 'restore_quote' => 'Angebot wiederherstellen', 'restore_client' => 'Kunde wiederherstellen', 'restore_credit' => 'Guthaben wiederherstellen', 'restore_payment' => 'Zahlung wiederherstellen', 'restored_invoice' => 'Rechnung erfolgreich wiederhergestellt', 'restored_quote' => 'Angebot erfolgreich wiederhergestellt', 'restored_client' => 'Kunde erfolgreich wiederhergestellt', 'restored_payment' => 'Zahlung erfolgreich wiederhergestellt', 'restored_credit' => 'Guthaben erfolgreich wiederhergestellt', 'reason_for_canceling' => 'Hilf uns, unser Angebot zu verbessern, indem du uns mitteilst, weswegen du dich dazu entschieden hast, unseren Service nicht länger zu nutzen.', 'discount_percent' => 'Prozent', 'discount_amount' => 'Wert', 'invoice_history' => 'Rechnungshistorie', 'quote_history' => 'Angebotshistorie', 'current_version' => 'Aktuelle Version', 'select_versiony' => 'Version auswählen', 'view_history' => 'Historie anzeigen', 'edit_payment' => 'Zahlung bearbeiten', 'updated_payment' => 'Zahlung erfolgreich aktualisiert', 'deleted' => 'Gelöscht', 'restore_user' => 'Benutzer wiederherstellen', 'restored_user' => 'Benutzer erfolgreich wiederhergestellt', 'show_deleted_users' => 'Zeige gelöschte Benutzer', 'email_templates' => 'E-Mail Vorlagen', 'invoice_email' => 'Rechnungsmail', 'payment_email' => 'Zahlungsmail', 'quote_email' => 'Angebotsmail', 'reset_all' => 'Alle zurücksetzen', 'approve' => 'Zustimmen', 'token_billing_type_id' => 'Token Billing', 'token_billing_help' => 'Enables you to store credit cards with your gateway, and charge them at a later date.', 'token_billing_1' => 'Deaktiviert', 'token_billing_2' => 'Opt-in - Kontrollkästchen wird angezeigt ist aber nicht ausgewählt', 'token_billing_3' => 'Opt-out - Kontrollkästchen wird angezeigt und ist ausgewählt', 'token_billing_4' => 'Immer', 'token_billing_checkbox' => 'Kreditkarteninformationen speichern', 'view_in_stripe' => 'Auf Stripe anzeigen', 'use_card_on_file' => 'Verwende gespeicherte Kreditkarte', 'edit_payment_details' => 'Zahlungsdetails bearbeiten', 'token_billing' => 'Kreditkarte merken', 'token_billing_secure' => 'Die Daten werden sicher von :stripe_link gespeichert.', 'support' => 'Support', 'contact_information' => 'Kontakt-Informationen', '256_encryption' => '256-Bit-Verschlüsselung', 'amount_due' => 'Fälliger Betrag', 'billing_address' => 'Rechnungsadresse', 'billing_method' => 'Abrechnungsmethode', 'order_overview' => 'Bestellübersicht', 'match_address' => '*Die Rechnungsadresse muss mit der Adresse der Kreditkarte übereinstimmen.', 'click_once' => '*Bitte drücken Sie nur einmal auf "Jetzt bezahlen" - die Verarbeitung der Transaktion kann bis zu einer Minute dauern.', 'default_invoice_footer' => 'Standard-Fußzeile festlegen', 'invoice_footer' => 'Fußzeile', 'save_as_default_footer' => 'Als Standard-Fußzeile speichern', 'token_management' => 'Token Verwaltung', 'tokens' => 'Token', 'add_token' => 'Token hinzufügen', 'show_deleted_tokens' => 'Zeige gelöschte Token', 'deleted_token' => 'Token erfolgreich gelöscht', 'created_token' => 'Token erfolgreich erstellt', 'updated_token' => 'Token erfolgreich aktualisiert', 'edit_token' => 'Token bearbeiten', 'delete_token' => 'Token löschen', 'token' => 'Token', 'add_gateway' => 'Zahlungsanbieter hinzufügen', 'delete_gateway' => 'Zahlungsanbieter löschen', 'edit_gateway' => 'Zahlungsanbieter bearbeiten', 'updated_gateway' => 'Zahlungsanbieter aktualisiert', 'created_gateway' => 'Zahlungsanbieter erfolgreich hinzugefügt', 'deleted_gateway' => 'Zahlungsanbieter erfolgreich gelöscht', 'pay_with_paypal' => 'PayPal', 'pay_with_card' => 'Kreditkarte', 'change_password' => '<PASSWORD>', 'current_password' => '<PASSWORD>', 'new_password' => '<PASSWORD>', 'confirm_password' => '<PASSWORD>', 'password_error_incorrect' => 'Das aktuelle Passwort ist nicht korrekt.', 'password_error_invalid' => 'Das neue Passwort ist ungültig.', 'updated_password' => 'Passwort erfolgreich aktualisiert', 'api_tokens' => 'API Token', 'users_and_tokens' => 'Benutzer & Token', 'account_login' => 'Konto Login', 'recover_password' => '<PASSWORD>', 'forgot_password' => '<PASSWORD>?', 'email_address' => 'E-Mail-Adresse', 'lets_go' => "Auf geht's", 'password_recovery' => '<PASSWORD>', 'send_email' => 'E-Mail verschicken', 'set_password' => '<PASSWORD>', 'converted' => 'Umgewandelt', 'email_approved' => 'Per E-Mail benachrichtigen, wenn ein Angebot <b>angenommen</b> wurde', 'notification_quote_approved_subject' => 'Angebot :invoice wurde von :client angenommen.', 'notification_quote_approved' => 'Der folgende Kunde :client nahm das Angebot :invoice über :amount an.', 'resend_confirmation' => 'Bestätigungsmail erneut senden', 'confirmation_resent' => 'Bestätigungsemail wurde erneut gesendet', 'gateway_help_42' => ':link to sign up for BitPay.<br/>Note: use a Legacy API Key, not an API token.', 'payment_type_credit_card' => 'Kreditkarte', 'payment_type_paypal' => 'PayPal', 'payment_type_bitcoin' => 'Bitcoin', 'knowledge_base' => 'FAQ', 'partial' => 'Partiell', 'partial_remaining' => ':partial von :balance', 'more_fields' => 'Weitere Felder', 'less_fields' => 'Weniger Felder', 'client_name' => 'Kundenname', 'pdf_settings' => 'PDF Einstellungen', 'product_settings' => 'Produkt Einstellungen', 'auto_wrap' => 'Automatischer Zeilenumbruch', 'duplicate_post' => 'Achtung: Die vorherige Seite wurde zweimal abgeschickt. Das zweite Abschicken wurde ignoriert.', 'view_documentation' => 'Dokumentation anzeigen', 'app_title' => 'Kostenlose Online Open-Source Rechnungsausstellung', 'app_description' => 'InvoiceNinja is a free, open-source solution for invoicing and billing customers. With Invoice Ninja, you can easily build and send beautiful invoices from any device that has access to the web. Your clients can print your invoices, download them as pdf files, and even pay you online from within the system.', 'rows' => 'Zeilen', 'www' => 'www', 'logo' => 'Logo', 'subdomain' => 'Subdomain', 'provide_name_or_email' => 'Bitte geben Sie einen Kontaktnamen oder eine E-Mail-Adresse an', 'charts_and_reports' => 'Diagramme & Berichte', 'chart' => 'Diagramm', 'report' => 'Bericht', 'group_by' => 'Gruppieren nach', 'paid' => 'Bezahlt', 'enable_report' => 'Bericht', 'enable_chart' => 'Diagramm', 'totals' => 'Summe', 'run' => 'Ausführen', 'export' => 'Exportieren', 'documentation' => 'Dokumentation', 'zapier' => 'Zapier <sup>Beta</sup>', 'recurring' => 'Wiederkehrend', 'last_invoice_sent' => 'Letzte Rechnung verschickt am :date', 'processed_updates' => 'Update erfolgreich abgeschlossen', 'tasks' => 'Zeiterfassung', 'new_task' => 'Neue Aufgabe', 'start_time' => 'Start Time', 'created_task' => 'Aufgabe erfolgreich erstellt', 'updated_task' => 'Aufgabe erfolgreich aktualisiert', 'edit_task' => 'Aufgabe bearbeiten', 'archive_task' => 'Aufgabe archivieren', 'restore_task' => 'Aufgabe wiederherstellen', 'delete_task' => 'Aufgabe löschen', 'stop_task' => 'Aufgabe Anhalten', 'time' => 'Zeit', 'start' => 'Starten', 'stop' => 'Anhalten', 'now' => 'Jetzt', 'timer' => 'Zeitmesser', 'manual' => 'Manuell', 'date_and_time' => 'Datum & Uhrzeit', 'second' => 'Sekunde', 'seconds' => 'Sekunden', 'minute' => 'Minute', 'minutes' => 'Minuten', 'hour' => 'Stunde', 'hours' => 'Stunden', 'task_details' => 'Aufgaben-Details', 'duration' => 'Dauer', 'end_time' => 'Endzeit', 'end' => 'Ende', 'invoiced' => 'In Rechnung gestellt', 'logged' => 'Protokolliert', 'running' => 'Läuft', 'task_error_multiple_clients' => 'Die Aufgaben können nicht zu verschiedenen Kunden gehören', 'task_error_running' => 'Bitte beenden Sie laufende Aufgaben zuerst', 'task_error_invoiced' => 'Aufgaben wurden bereits in Rechnung gestellt', 'restored_task' => 'Aufgabe erfolgreich wiederhergestellt', 'archived_task' => 'Aufgabe erfolgreich archiviert', 'archived_tasks' => ':count Aufgaben wurden erfolgreich archiviert', 'deleted_task' => 'Aufgabe erfolgreich gelöscht', 'deleted_tasks' => ':count Aufgaben wurden erfolgreich gelöscht', 'create_task' => 'Aufgabe erstellen', 'stopped_task' => 'Aufgabe erfolgreich angehalten', 'invoice_task' => 'Aufgabe in Rechnung stellen', 'invoice_labels' => 'Rechnung Spaltenüberschriften', 'prefix' => 'Präfix', 'counter' => 'Zähler', 'payment_type_dwolla' => 'Dwolla', 'gateway_help_43' => ':link to sign up for Dwolla.', 'partial_value' => 'Muss größer als Null und kleiner als der Gesamtbetrag sein', 'more_actions' => 'Weitere Aktionen', 'pro_plan_title' => 'NINJA PRO', 'pro_plan_call_to_action' => 'Jetzt Upgraden!', 'pro_plan_feature1' => 'Unlimitierte Anzahl Kunden erstellen', 'pro_plan_feature2' => 'Zugriff auf 10 schöne Rechnungsdesigns', 'pro_plan_feature3' => 'Benutzerdefinierte URLs - "DeineFirma.InvoiceNinja.com"', 'pro_plan_feature4' => '"Erstellt durch Invoice Ninja" entfernen', 'pro_plan_feature5' => 'Multi-Benutzer Zugriff & Aktivitätstracking', 'pro_plan_feature6' => 'Angebote & pro-forma Rechnungen erstellen', 'pro_plan_feature7' => 'Rechungstitelfelder und Nummerierung anpassen', 'pro_plan_feature8' => 'PDFs an E-Mails zu Kunden anhängen', 'resume' => 'Fortfahren', 'break_duration' => 'Pause', 'edit_details' => 'Details bearbeiten', 'work' => 'Arbeiten', 'timezone_unset' => 'Bitte :link um deine Zeitzone zu setzen', 'click_here' => 'hier klicken', 'email_receipt' => 'Zahlungsbestätigung an Kunden per E-Mail senden', 'created_payment_emailed_client' => 'Zahlung erfolgreich erstellt und Kunde per E-Mail benachrichtigt', 'add_company' => 'Konto hinzufügen', 'untitled' => 'Unbenannt', 'new_company' => 'Neues Konto', 'associated_accounts' => 'Konten erfolgreich verlinkt', 'unlinked_account' => 'Konten erfolgreich getrennt', 'login' => 'Login', 'or' => 'oder', 'email_error' => 'Es gab ein Problem beim Senden dieses E-Mails.', 'confirm_recurring_timing' => 'Beachten Sie: E-Mails werden zu Beginn der Stunde gesendet.', 'old_browser' => 'Bitte verwenden Sie einen <a href="'.OUTDATE_BROWSER_URL.'" target="_blank">neueren Browser</a>', 'payment_terms_help' => 'Setzt das Standardfälligkeitsdatum', 'unlink_account' => 'Konten Trennen', 'unlink' => 'Trennen', 'show_address' => 'Adresse Anzeigen', 'show_address_help' => 'Verlange von Kunden ihre Rechnungsadresse anzugeben', 'update_address' => 'Adresse Aktualisieren', 'update_address_help' => 'Kundenadresse mit den gemachten Angaben aktualisieren', 'times' => 'Zeiten', 'set_now' => 'Jetzt setzen', 'dark_mode' => 'Dunkler Modus', 'dark_mode_help' => 'Weißer Text auf schwarzem Hintergrund anzeigen', 'add_to_invoice' => 'Zur Rechnung :invoice hinzufügen', 'create_new_invoice' => 'Neue Rechnung erstellen', 'task_errors' => 'Bitte korrigieren Sie alle überlappenden Zeiten', 'from' => 'Von', 'to' => 'An', 'font_size' => 'Schriftgröße', 'primary_color' => 'Primäre Farbe', 'secondary_color' => 'Sekundäre Farbe', 'customize_design' => 'Design Anpassen', 'content' => 'Inhalt', 'styles' => 'Stile', 'defaults' => 'Standards', 'margins' => 'Außenabstände', 'header' => 'Kopfzeile', 'footer' => 'Fußzeile', 'custom' => 'Benutzerdefiniert', 'invoice_to' => 'Rechnung an', 'invoice_no' => 'Rechnung Nr.', 'recent_payments' => 'Kürzliche Zahlungen', 'outstanding' => 'Ausstehend', 'manage_companies' => 'Unternehmen verwalten', 'total_revenue' => 'Gesamteinnahmen', 'current_user' => 'Aktueller Benutzer', 'new_recurring_invoice' => 'Neue wiederkehrende Rechnung', 'recurring_invoice' => 'Wiederkehrende Rechnung', 'recurring_too_soon' => 'Es ist zu früh, um die nächste wiederkehrende Rechnung zu erstellen', 'created_by_invoice' => 'Erstellt durch :invoice', 'primary_user' => 'Primary User', 'help' => 'Help', 'customize_help' => '<p>We use <a href="http://pdfmake.org/" target="_blank">pdfmake</a> to define the invoice designs declaratively. The pdfmake <a href="http://pdfmake.org/playground.html" target="_blank">playground</a> provide\'s a great way to see the library in action.</p> <p>You can access any invoice field by adding <code>Value</code> to the end. For example <code>$invoiceNumberValue</code> displays the invoice number.</p> <p>To access a child property using dot notation. For example to show the client name you could use <code>$client.nameValue</code>.</p> <p>If you need help figuring something out post a question to our <a href="https://www.invoiceninja.com/forums/forum/support/" target="_blank">support forum</a>.</p>' ); <file_sep>/tests/_bootstrap.php <?php // This is global bootstrap for autoloading use Codeception\Util\Fixtures; Fixtures::add('username', '<EMAIL>'); Fixtures::add('password', '<PASSWORD>');<file_sep>/app/Listeners/HandleInvoiceSent.php <?php namespace App\Listeners; use App\Events\InvoiceSent; use App\Ninja\Mailers\UserMailer; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldBeQueued; class HandleInvoiceSent { protected $userMailer; /** * Create the event handler. * * @return void */ public function __construct(UserMailer $userMailer) { $this->userMailer = $userMailer; } /** * Handle the event. * * @param InvoiceSent $event * @return void */ public function handle(InvoiceSent $event) { $invoice = $event->invoice; foreach ($invoice->account->users as $user) { if ($user->{'notify_sent'}) { $this->userMailer->sendNotification($user, $invoice, 'sent'); } } } } <file_sep>/public/js/script.js // http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+ var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0; var isChrome = !!window.chrome && !isOpera; // Chrome 1+ var isChromium = isChrome && navigator.userAgent.indexOf('Chromium') >= 0; var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6 var invoiceOld; var refreshTimer; function generatePDF(invoice, javascript, force, cb) { if (!invoice || !javascript) { return; } //console.log('== generatePDF - force: %s', force); if (force || !invoiceOld) { refreshTimer = null; } else { if (refreshTimer) { clearTimeout(refreshTimer); } refreshTimer = setTimeout(function() { generatePDF(invoice, javascript, true, cb); }, 500); return; } invoice = calculateAmounts(invoice); var a = copyObject(invoice); var b = copyObject(invoiceOld); if (!force && _.isEqual(a, b)) { return; } invoiceOld = invoice; pdfmakeMarker = "{"; if(javascript.slice(0, pdfmakeMarker.length) === pdfmakeMarker) { doc = GetPdfMake(invoice, javascript, cb); } else { doc = GetPdf(invoice, javascript); doc.getDataUrl = function(cb) { cb( this.output("datauristring")); }; } if (cb) { doc.getDataUrl(cb); } return doc; } function copyObject(orig) { if (!orig) return false; return JSON.parse(JSON.stringify(orig)); } function GetPdf(invoice, javascript){ var layout = { accountTop: 40, marginLeft: 50, marginRight: 550, headerTop: 150, headerLeft: 360, headerRight: 550, rowHeight: 15, tableRowHeight: 10, footerLeft: 420, tablePadding: 12, tableTop: 250, descriptionLeft: 150, unitCostRight: 410, qtyRight: 480, taxRight: 480, lineTotalRight: 550 }; /* if (invoice.has_taxes) { layout.descriptionLeft -= 20; layout.unitCostRight -= 40; layout.qtyRight -= 40; } */ /* @param orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l") @param unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in" @param format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal' @returns {jsPDF} */ var doc = new jsPDF('portrait', 'pt', 'a4'); //doc.getStringUnitWidth = function(param) { console.log('getStringUnitWidth: %s', param); return 0}; //Set PDF properities doc.setProperties({ title: 'Invoice ' + invoice.invoice_number, subject: '', author: 'InvoiceNinja.com', keywords: 'pdf, invoice', creator: 'InvoiceNinja.com' }); //set default style for report doc.setFont('Helvetica',''); // For partial payments show "Amount Due" rather than "Balance Due" if (!invoiceLabels.balance_due_orig) { invoiceLabels.balance_due_orig = invoiceLabels.balance_due; } invoiceLabels.balance_due = NINJA.parseFloat(invoice.partial) ? invoiceLabels.amount_due : invoiceLabels.balance_due_orig; eval(javascript); // add footer if (invoice.invoice_footer) { doc.setFontType('normal'); doc.setFontSize('8'); SetPdfColor(invoice.invoice_design_id == 2 || invoice.invoice_design_id == 3 ? 'White' : 'Black',doc); var top = doc.internal.pageSize.height - layout.marginLeft; if (!invoice.is_pro) top -= 25; var footer = doc.splitTextToSize(processVariables(invoice.invoice_footer), 500); var numLines = footer.length - 1; doc.text(layout.marginLeft, top - (numLines * 8), footer); } return doc; } function SetPdfColor(color, doc, role) { if (role === 'primary' && NINJA.primaryColor) { return setDocHexColor(doc, NINJA.primaryColor); } else if (role === 'secondary' && NINJA.secondaryColor) { return setDocHexColor(doc, NINJA.secondaryColor); } if (color=='LightBlue') { return doc.setTextColor(41,156, 194); } if (color=='Black') { return doc.setTextColor(46,43,43);//select color black } if (color=='GrayLogo') { return doc.setTextColor(207,241, 241);//select color Custom Report GRAY } if (color=='GrayBackground') { return doc.setTextColor(251,251, 251);//select color Custom Report GRAY } if (color=='GrayText') { return doc.setTextColor(161,160,160);//select color Custom Report GRAY Colour } if (color=='White') { return doc.setTextColor(255,255,255);//select color Custom Report GRAY Colour } if (color=='SomeGreen') { return doc.setTextColor(54,164,152);//select color Custom Report GRAY Colour } if (color=='LightGrayReport2-gray') { return doc.setTextColor(240,240,240);//select color Custom Report GRAY Colour } if (color=='LightGrayReport2-white') { return doc.setTextColor(251,251,251);//select color Custom Report GRAY Colour } if (color=='orange') { return doc.setTextColor(234,121,45);//select color Custom Report GRAY Colour } if (color=='Green') { return doc.setTextColor(55,109,69); } } /* Handle converting variables in the invoices (ie, MONTH+1) */ function processVariables(str) { if (!str) return ''; var variables = ['MONTH','QUARTER','YEAR']; for (var i=0; i<variables.length; i++) { var variable = variables[i]; var regexp = new RegExp(':' + variable + '[+-]?[\\d]*', 'g'); var matches = str.match(regexp); if (!matches) { continue; } for (var j=0; j<matches.length; j++) { var match = matches[j]; var offset = 0; if (match.split('+').length > 1) { offset = match.split('+')[1]; } else if (match.split('-').length > 1) { offset = parseInt(match.split('-')[1]) * -1; } str = str.replace(match, getDatePart(variable, offset)); } } return str; } function getDatePart(part, offset) { offset = parseInt(offset); if (!offset) { offset = 0; } if (part == 'MONTH') { return getMonth(offset); } else if (part == 'QUARTER') { return getQuarter(offset); } else if (part == 'YEAR') { return getYear(offset); } } function getMonth(offset) { var today = new Date(); var months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var month = today.getMonth(); month = parseInt(month) + offset; month = month % 12; if (month < 0) { month += 12; } return months[month]; } function getYear(offset) { var today = new Date(); var year = today.getFullYear(); return parseInt(year) + offset; } function getQuarter(offset) { var today = new Date(); var quarter = Math.floor((today.getMonth() + 3) / 3); quarter += offset; quarter = quarter % 4; if (quarter == 0) { quarter = 4; } return 'Q' + quarter; } /* Default class modification */ if ($.fn.dataTableExt) { $.extend( $.fn.dataTableExt.oStdClasses, { "sWrapper": "dataTables_wrapper form-inline" } ); /* API method to get paging information */ $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) }; }; /* Bootstrap style pagination control */ $.extend( $.fn.dataTableExt.oPagination, { "bootstrap": { "fnInit": function( oSettings, nPaging, fnDraw ) { var oLang = oSettings.oLanguage.oPaginate; var fnClickHandler = function ( e ) { e.preventDefault(); if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { fnDraw( oSettings ); } }; $(nPaging).addClass('pagination').append( '<ul class="pagination">'+ '<li class="prev disabled"><a href="#">&laquo;</a></li>'+ '<li class="next disabled"><a href="#">&raquo;</a></li>'+ '</ul>' ); var els = $('a', nPaging); $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler ); $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler ); }, "fnUpdate": function ( oSettings, fnDraw ) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); if ( oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if ( oPaging.iPage <= iHalf ) { iStart = 1; iEnd = iListLength; } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for ( i=0, ien=an.length ; i<ien ; i++ ) { // Remove the middle elements $('li:gt(0)', an[i]).filter(':not(:last)').remove(); // Add the new list items and their event handlers for ( j=iStart ; j<=iEnd ; j++ ) { sClass = (j==oPaging.iPage+1) ? 'class="active"' : ''; $('<li '+sClass+'><a href="#">'+j+'</a></li>') .insertBefore( $('li:last', an[i])[0] ) .bind('click', function (e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; fnDraw( oSettings ); } ); } // Add / remove disabled classes from the static elements if ( oPaging.iPage === 0 ) { $('li:first', an[i]).addClass('disabled'); } else { $('li:first', an[i]).removeClass('disabled'); } if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('li:last', an[i]).addClass('disabled'); } else { $('li:last', an[i]).removeClass('disabled'); } } } } } ); } /* * TableTools Bootstrap compatibility * Required TableTools 2.1+ */ if ( $.fn.DataTable.TableTools ) { // Set the classes that TableTools uses to something suitable for Bootstrap $.extend( true, $.fn.DataTable.TableTools.classes, { "container": "DTTT btn-group", "buttons": { "normal": "btn", "disabled": "disabled" }, "collection": { "container": "DTTT_dropdown dropdown-menu", "buttons": { "normal": "", "disabled": "disabled" } }, "print": { "info": "DTTT_print_info modal" }, "select": { "row": "active" } } ); // Have the collection use a bootstrap compatible dropdown $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, { "collection": { "container": "ul", "button": "li", "liner": "a" } } ); } function isStorageSupported() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } function isValidEmailAddress(emailAddress) { var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i); return pattern.test(emailAddress); }; $(function() { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); }); function enableHoverClick($combobox, $entityId, url) { /* $combobox.mouseleave(function() { $combobox.css('text-decoration','none'); }).on('mouseenter', function(e) { setAsLink($combobox, $combobox.closest('.combobox-container').hasClass('combobox-selected')); }).on('focusout mouseleave', function(e) { setAsLink($combobox, false); }).on('click', function() { var clientId = $entityId.val(); if ($(combobox).closest('.combobox-container').hasClass('combobox-selected')) { if (parseInt(clientId) > 0) { window.open(url + '/' + clientId, '_blank'); } else { $('#myModal').modal('show'); } }; }); */ } function setAsLink($input, enable) { if (enable) { $input.css('text-decoration','underline'); $input.css('cursor','pointer'); } else { $input.css('text-decoration','none'); $input.css('cursor','text'); } } function setComboboxValue($combobox, id, name) { $combobox.find('input').val(id); $combobox.find('input.form-control').val(name); if (id && name) { $combobox.find('select').combobox('setSelected'); $combobox.find('.combobox-container').addClass('combobox-selected'); } else { $combobox.find('.combobox-container').removeClass('combobox-selected'); } } var BASE64_MARKER = ';base64,'; function convertDataURIToBinary(dataURI) { var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length; var base64 = dataURI.substring(base64Index); return base64DecToArr(base64); } if (window.ko) { ko.bindingHandlers.dropdown = { init: function (element, valueAccessor, allBindingsAccessor) { var options = allBindingsAccessor().dropdownOptions|| {}; var value = ko.utils.unwrapObservable(valueAccessor()); var id = (value && value.public_id) ? value.public_id() : (value && value.id) ? value.id() : value ? value : false; if (id) $(element).val(id); //console.log("combo-init: %s", id); $(element).combobox(options); /* ko.utils.registerEventHandler(element, "change", function () { console.log("change: %s", $(element).val()); //var valueAccessor($(element).val()); //$(element).combobox('refresh'); }); */ }, update: function (element, valueAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); var id = (value && value.public_id) ? value.public_id() : (value && value.id) ? value.id() : value ? value : false; //console.log("combo-update: %s", id); if (id) { $(element).val(id); $(element).combobox('refresh'); } else { $(element).combobox('clearTarget'); $(element).combobox('clearElement'); } } }; ko.bindingHandlers.datePicker = { init: function (element, valueAccessor, allBindingsAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); if (value) $(element).datepicker('update', value); $(element).change(function() { var value = valueAccessor(); value($(element).val()); }) }, update: function (element, valueAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); if (value) $(element).datepicker('update', value); } }; ko.bindingHandlers.placeholder = { init: function (element, valueAccessor, allBindingsAccessor) { var underlyingObservable = valueAccessor(); ko.applyBindingsToNode(element, { attr: { placeholder: underlyingObservable } } ); } }; } function getClientDisplayName(client) { var contact = client.contacts ? client.contacts[0] : false; if (client.name) { return client.name; } else if (contact) { if (contact.first_name || contact.last_name) { return contact.first_name + ' ' + contact.last_name; } else { return contact.email; } } return ''; } function populateInvoiceComboboxes(clientId, invoiceId) { var clientMap = {}; var invoiceMap = {}; var invoicesForClientMap = {}; var $clientSelect = $('select#client'); for (var i=0; i<invoices.length; i++) { var invoice = invoices[i]; var client = invoice.client; if (!invoicesForClientMap.hasOwnProperty(client.public_id)) { invoicesForClientMap[client.public_id] = []; } invoicesForClientMap[client.public_id].push(invoice); invoiceMap[invoice.public_id] = invoice; } for (var i=0; i<clients.length; i++) { var client = clients[i]; clientMap[client.public_id] = client; } $clientSelect.append(new Option('', '')); for (var i=0; i<clients.length; i++) { var client = clients[i]; $clientSelect.append(new Option(getClientDisplayName(client), client.public_id)); } if (clientId) { $clientSelect.val(clientId); } $clientSelect.combobox(); $clientSelect.on('change', function(e) { var clientId = $('input[name=client]').val(); var invoiceId = $('input[name=invoice]').val(); var invoice = invoiceMap[invoiceId]; if (invoice && invoice.client.public_id == clientId) { e.preventDefault(); return; } setComboboxValue($('.invoice-select'), '', ''); $invoiceCombobox = $('select#invoice'); $invoiceCombobox.find('option').remove().end().combobox('refresh'); $invoiceCombobox.append(new Option('', '')); var list = clientId ? (invoicesForClientMap.hasOwnProperty(clientId) ? invoicesForClientMap[clientId] : []) : invoices; for (var i=0; i<list.length; i++) { var invoice = list[i]; var client = clientMap[invoice.client.public_id]; if (!client) continue; // client is deleted/archived $invoiceCombobox.append(new Option(invoice.invoice_number + ' - ' + invoice.invoice_status.name + ' - ' + getClientDisplayName(client) + ' - ' + formatMoney(invoice.amount, client.currency_id) + ' | ' + formatMoney(invoice.balance, client.currency_id), invoice.public_id)); } $('select#invoice').combobox('refresh'); }); var $invoiceSelect = $('select#invoice').on('change', function(e) { $clientCombobox = $('select#client'); var invoiceId = $('input[name=invoice]').val(); if (invoiceId) { var invoice = invoiceMap[invoiceId]; var client = clientMap[invoice.client.public_id]; setComboboxValue($('.client-select'), client.public_id, getClientDisplayName(client)); if (!parseFloat($('#amount').val())) { $('#amount').val(parseFloat(invoice.balance).toFixed(2)); } } }); $invoiceSelect.combobox(); if (invoiceId) { var invoice = invoiceMap[invoiceId]; var client = clientMap[invoice.client.public_id]; setComboboxValue($('.invoice-select'), invoice.public_id, (invoice.invoice_number + ' - ' + invoice.invoice_status.name + ' - ' + getClientDisplayName(client) + ' - ' + formatMoney(invoice.amount, client.currency_id) + ' | ' + formatMoney(invoice.balance, client.currency_id))); $invoiceSelect.trigger('change'); } else if (clientId) { var client = clientMap[clientId]; setComboboxValue($('.client-select'), client.public_id, getClientDisplayName(client)); $clientSelect.trigger('change'); } else { $clientSelect.trigger('change'); } } var CONSTS = {}; CONSTS.INVOICE_STATUS_DRAFT = 1; CONSTS.INVOICE_STATUS_SENT = 2; CONSTS.INVOICE_STATUS_VIEWED = 3; CONSTS.INVOICE_STATUS_PARTIAL = 4; CONSTS.INVOICE_STATUS_PAID = 5; $.fn.datepicker.defaults.autoclose = true; $.fn.datepicker.defaults.todayHighlight = true; function displayAccount(doc, invoice, x, y, layout) { var account = invoice.account; if (!account) { return; } var data1 = [ account.name, account.id_number, account.vat_number, account.work_email, account.work_phone ]; var data2 = [ concatStrings(account.address1, account.address2), concatStrings(account.city, account.state, account.postal_code), account.country ? account.country.name : false, invoice.account.custom_value1 ? invoice.account['custom_label1'] + ' ' + invoice.account.custom_value1 : false, invoice.account.custom_value2 ? invoice.account['custom_label2'] + ' ' + invoice.account.custom_value2 : false, ]; if (layout.singleColumn) { displayGrid(doc, invoice, data1.concat(data2), x, y, layout, {hasHeader:true}); } else { displayGrid(doc, invoice, data1, x, y, layout, {hasHeader:true}); var nameWidth = account.name ? (doc.getStringUnitWidth(account.name) * doc.internal.getFontSize() * 1.1) : 0; var emailWidth = account.work_email ? (doc.getStringUnitWidth(account.work_email) * doc.internal.getFontSize() * 1.1) : 0; width = Math.max(emailWidth, nameWidth, 120); x += width; displayGrid(doc, invoice, data2, x, y, layout); } } function displayClient(doc, invoice, x, y, layout) { var client = invoice.client; if (!client) { return; } var data = [ getClientDisplayName(client), client.id_number, client.vat_number, concatStrings(client.address1, client.address2), concatStrings(client.city, client.state, client.postal_code), client.country ? client.country.name : false, invoice.contact && getClientDisplayName(client) != invoice.contact.email ? invoice.contact.email : false, invoice.client.custom_value1 ? invoice.account['custom_client_label1'] + ' ' + invoice.client.custom_value1 : false, invoice.client.custom_value2 ? invoice.account['custom_client_label2'] + ' ' + invoice.client.custom_value2 : false, ]; return displayGrid(doc, invoice, data, x, y, layout, {hasheader:true}); } function displayInvoice(doc, invoice, x, y, layout, rightAlignX) { if (!invoice) { return; } var data = getInvoiceDetails(invoice); var options = { hasheader: true, rightAlignX: rightAlignX, }; return displayGrid(doc, invoice, data, x, y, layout, options); } function getInvoiceDetails(invoice) { var fields = [ {'invoice_number': invoice.invoice_number}, {'po_number': invoice.po_number}, {'invoice_date': invoice.invoice_date}, {'due_date': invoice.due_date}, ]; if (NINJA.parseFloat(invoice.balance) < NINJA.parseFloat(invoice.amount)) { fields.push({'total': formatMoney(invoice.amount, invoice.client.currency_id)}); } if (NINJA.parseFloat(invoice.partial)) { fields.push({'balance': formatMoney(invoice.total_amount, invoice.client.currency_id)}); } fields.push({'balance_due': formatMoney(invoice.balance_amount, invoice.client.currency_id)}) return fields; } function getInvoiceDetailsHeight(invoice, layout) { var data = getInvoiceDetails(invoice); var count = 0; for (var key in data) { if (!data.hasOwnProperty(key)) { continue; } var obj = data[key]; for (var subKey in obj) { if (!obj.hasOwnProperty(subKey)) { continue; } if (obj[subKey]) { count++; } } } return count * layout.rowHeight; } function displaySubtotals(doc, layout, invoice, y, rightAlignTitleX) { if (!invoice) { return; } var data = [ {'subtotal': formatMoney(invoice.subtotal_amount, invoice.client.currency_id)}, {'discount': invoice.discount_amount != 0 ? formatMoney(invoice.discount_amount, invoice.client.currency_id) : false} ]; if (NINJA.parseFloat(invoice.custom_value1) && invoice.custom_taxes1 == '1') { data.push({'custom_invoice_label1': formatMoney(invoice.custom_value1, invoice.client.currency_id) }) } if (NINJA.parseFloat(invoice.custom_value2) && invoice.custom_taxes2 == '1') { data.push({'custom_invoice_label2': formatMoney(invoice.custom_value2, invoice.client.currency_id) }) } data.push({'tax': (invoice.tax && invoice.tax.name) || invoice.tax_name ? formatMoney(invoice.tax_amount, invoice.client.currency_id) : false}); if (NINJA.parseFloat(invoice.custom_value1) && invoice.custom_taxes1 != '1') { data.push({'custom_invoice_label1': formatMoney(invoice.custom_value1, invoice.client.currency_id) }) } if (NINJA.parseFloat(invoice.custom_value2) && invoice.custom_taxes2 != '1') { data.push({'custom_invoice_label2': formatMoney(invoice.custom_value2, invoice.client.currency_id) }) } var paid = invoice.amount - invoice.balance; if (paid) { data.push({'total': formatMoney(invoice.amount, invoice.client.currency_id)}); } if (invoice.account.hide_paid_to_date != '1' || paid) { data.push({'paid_to_date': formatMoney(paid, invoice.client.currency_id)}); } if (NINJA.parseFloat(invoice.partial) && invoice.total_amount != invoice.subtotal_amount) { data.push({'balance': formatMoney(invoice.total_amount, invoice.client.currency_id)}); } var options = { hasheader: true, rightAlignX: 550, rightAlignTitleX: rightAlignTitleX }; return displayGrid(doc, invoice, data, 300, y, layout, options) + 10; } function concatStrings() { var concatStr = ''; var data = []; for (var i=0; i<arguments.length; i++) { var string = arguments[i]; if (string) { data.push(string); } } for (var i=0; i<data.length; i++) { concatStr += data[i]; if (i == 0 && data.length > 1) { concatStr += ', '; } else if (i < data.length -1) { concatStr += ' '; } } return data.length ? concatStr : ""; } function displayGrid(doc, invoice, data, x, y, layout, options) { var numLines = 0; var origY = y; for (var i=0; i<data.length; i++) { doc.setFontType('normal'); if (invoice.invoice_design_id == 1 && i > 0 && origY === layout.accountTop) { SetPdfColor('GrayText',doc); } var row = data[i]; if (!row) { continue; } if (options && (options.hasheader && i === 0 && !options.rightAlignTitleX)) { doc.setFontType('bold'); } if (typeof row === 'object') { for (var key in row) { if (row.hasOwnProperty(key)) { var value = row[key] ? row[key] + '' : false; } } if (!value) { continue; } var marginLeft; if (options.rightAlignX) { marginLeft = options.rightAlignX - (doc.getStringUnitWidth(value) * doc.internal.getFontSize()); } else { marginLeft = x + 80; } doc.text(marginLeft, y, value); doc.setFontType('normal'); if (invoice.is_quote) { if (key == 'invoice_number') { key = 'quote_number'; } else if (key == 'invoice_date') { key = 'quote_date'; } else if (key == 'balance_due') { key = 'total'; } } if (key.substring(0, 6) === 'custom') { key = invoice.account[key]; } else if (key === 'tax' && invoice.tax_name) { key = invoice.tax_name + ' ' + (invoice.tax_rate*1).toString() + '%'; } else if (key === 'discount' && NINJA.parseFloat(invoice.discount) && !parseInt(invoice.is_amount_discount)) { key = invoiceLabels[key] + ' ' + parseFloat(invoice.discount) + '%'; } else { key = invoiceLabels[key]; } if (options.rightAlignTitleX) { marginLeft = options.rightAlignTitleX - (doc.getStringUnitWidth(key) * doc.internal.getFontSize()); } else { marginLeft = x; } doc.text(marginLeft, y, key); } else { doc.text(x, y, row); } numLines++; y += layout.rowHeight; } return numLines * layout.rowHeight; } function displayNotesAndTerms(doc, layout, invoice, y) { doc.setFontType("normal"); var origY = y; if (invoice.public_notes) { var notes = doc.splitTextToSize(processVariables(invoice.public_notes), 260); doc.text(layout.marginLeft, y, notes); y += 16 + (notes.length * doc.internal.getFontSize()); } if (invoice.terms) { var terms = doc.splitTextToSize(processVariables(invoice.terms), 260); doc.setFontType("bold"); doc.text(layout.marginLeft, y, invoiceLabels.terms); y += 16; doc.setFontType("normal"); doc.text(layout.marginLeft, y, terms); y += 16 + (terms.length * doc.internal.getFontSize()); } return y - origY; } function calculateAmounts(invoice) { var total = 0; var hasTaxes = false; var taxes = {}; // sum line item for (var i=0; i<invoice.invoice_items.length; i++) { var item = invoice.invoice_items[i]; var lineTotal = roundToTwo(NINJA.parseFloat(item.cost)) * roundToTwo(NINJA.parseFloat(item.qty)); if (lineTotal) { total += lineTotal; } } for (var i=0; i<invoice.invoice_items.length; i++) { var item = invoice.invoice_items[i]; var taxRate = 0; var taxName = ''; // the object structure differs if it's read from the db or created by knockoutJS if (item.tax && parseFloat(item.tax.rate)) { taxRate = parseFloat(item.tax.rate); taxName = item.tax.name; } else if (item.tax_rate && parseFloat(item.tax_rate)) { taxRate = parseFloat(item.tax_rate); taxName = item.tax_name; } // calculate line item tax var lineTotal = roundToTwo(NINJA.parseFloat(item.cost)) * roundToTwo(NINJA.parseFloat(item.qty)); if (invoice.discount != 0) { if (parseInt(invoice.is_amount_discount)) { lineTotal -= roundToTwo((lineTotal/total) * invoice.discount); } else { lineTotal -= roundToTwo(lineTotal * (invoice.discount/100)); } } var taxAmount = roundToTwo(lineTotal * taxRate / 100); if (taxRate) { var key = taxName + taxRate; if (taxes.hasOwnProperty(key)) { taxes[key].amount += taxAmount; } else { taxes[key] = {name: taxName, rate:taxRate, amount:taxAmount}; } } if ((item.tax && item.tax.name) || item.tax_name) { hasTaxes = true; } } invoice.subtotal_amount = total; var discount = 0; if (invoice.discount != 0) { if (parseInt(invoice.is_amount_discount)) { discount = roundToTwo(invoice.discount); } else { discount = roundToTwo(total * (invoice.discount/100)); } total -= discount; } // custom fields with taxes if (NINJA.parseFloat(invoice.custom_value1) && invoice.custom_taxes1 == '1') { total += roundToTwo(invoice.custom_value1); } if (NINJA.parseFloat(invoice.custom_value2) && invoice.custom_taxes2 == '1') { total += roundToTwo(invoice.custom_value2); } var tax = 0; if (invoice.tax && parseFloat(invoice.tax.rate)) { tax = parseFloat(invoice.tax.rate); } else if (invoice.tax_rate && parseFloat(invoice.tax_rate)) { tax = parseFloat(invoice.tax_rate); } if (tax) { var tax = roundToTwo(total * (tax/100)); total = parseFloat(total) + parseFloat(tax); } for (var key in taxes) { if (taxes.hasOwnProperty(key)) { total += taxes[key].amount; } } // custom fields w/o with taxes if (NINJA.parseFloat(invoice.custom_value1) && invoice.custom_taxes1 != '1') { total += roundToTwo(invoice.custom_value1); } if (NINJA.parseFloat(invoice.custom_value2) && invoice.custom_taxes2 != '1') { total += roundToTwo(invoice.custom_value2); } invoice.total_amount = roundToTwo(total) - (roundToTwo(invoice.amount) - roundToTwo(invoice.balance)); invoice.discount_amount = discount; invoice.tax_amount = tax; invoice.item_taxes = taxes; if (NINJA.parseFloat(invoice.partial)) { invoice.balance_amount = roundToTwo(invoice.partial); } else { invoice.balance_amount = invoice.total_amount; } return invoice; } function getInvoiceTaxRate(invoice) { var tax = 0; if (invoice.tax && parseFloat(invoice.tax.rate)) { tax = parseFloat(invoice.tax.rate); } else if (invoice.tax_rate && parseFloat(invoice.tax_rate)) { tax = parseFloat(invoice.tax_rate); } return tax; } function displayInvoiceHeader(doc, invoice, layout) { if (invoice.invoice_design_id == 6 || invoice.invoice_design_id == 8 || invoice.invoice_design_id == 10) { invoiceLabels.item = invoiceLabels.item.toUpperCase(); invoiceLabels.description = invoiceLabels.description.toUpperCase(); invoiceLabels.unit_cost = invoiceLabels.unit_cost.toUpperCase(); invoiceLabels.quantity = invoiceLabels.quantity.toUpperCase(); invoiceLabels.line_total = invoiceLabels.total.toUpperCase(); invoiceLabels.tax = invoiceLabels.tax.toUpperCase(); } var costX = layout.unitCostRight - (doc.getStringUnitWidth(invoiceLabels.unit_cost) * doc.internal.getFontSize()); var qtyX = layout.qtyRight - (doc.getStringUnitWidth(invoiceLabels.quantity) * doc.internal.getFontSize()); var taxX = layout.taxRight - (doc.getStringUnitWidth(invoiceLabels.tax) * doc.internal.getFontSize()); var totalX = layout.lineTotalRight - (doc.getStringUnitWidth(invoiceLabels.line_total) * doc.internal.getFontSize()); doc.text(layout.marginLeft, layout.tableTop, invoiceLabels.item); doc.text(layout.descriptionLeft, layout.tableTop, invoiceLabels.description); doc.text(costX, layout.tableTop, invoiceLabels.unit_cost); if (invoice.account.hide_quantity != '1') { doc.text(qtyX, layout.tableTop, invoiceLabels.quantity); } doc.text(totalX, layout.tableTop, invoiceLabels.line_total); /* if (invoice.has_taxes) { doc.text(taxX, layout.tableTop, invoiceLabels.tax); } */ } function displayInvoiceItems(doc, invoice, layout) { doc.setFontType("normal"); var line = 1; var total = 0; var shownItem = false; var currencyId = invoice && invoice.client ? invoice.client.currency_id : 1; var tableTop = layout.tableTop; var hideQuantity = invoice.account.hide_quantity == '1'; doc.setFontSize(8); for (var i=0; i<invoice.invoice_items.length; i++) { var item = invoice.invoice_items[i]; var cost = formatMoney(item.cost, currencyId, true); var qty = NINJA.parseFloat(item.qty) ? roundToTwo(NINJA.parseFloat(item.qty)) + '' : ''; var notes = item.notes; var productKey = item.product_key; var tax = 0; if (item.tax && parseFloat(item.tax.rate)) { tax = parseFloat(item.tax.rate); } else if (item.tax_rate && parseFloat(item.tax_rate)) { tax = parseFloat(item.tax_rate); } // show at most one blank line if (shownItem && (!cost || cost == '0.00') && !notes && !productKey) { continue; } shownItem = true; var numLines = Math.max(doc.splitTextToSize(item.notes, 200).length, doc.splitTextToSize(item.product_key, 60).length) + 2; //console.log('num lines %s', numLines); var y = tableTop + (line * layout.tableRowHeight) + (2 * layout.tablePadding); var top = y - layout.tablePadding; var newTop = top + (numLines * layout.tableRowHeight); if (newTop > 770) { line = 0; tableTop = layout.accountTop + layout.tablePadding; y = tableTop + (2 * layout.tablePadding); top = y - layout.tablePadding; newTop = top + (numLines * layout.tableRowHeight); doc.addPage(); } var left = layout.marginLeft - layout.tablePadding; var width = layout.marginRight + layout.tablePadding; // process date variables if (invoice.is_recurring) { notes = processVariables(notes); productKey = processVariables(productKey); } var lineTotal = roundToTwo(NINJA.parseFloat(item.cost)) * roundToTwo(NINJA.parseFloat(item.qty)); if (tax) { lineTotal += lineTotal * tax / 100; } if (lineTotal) { total += lineTotal; } lineTotal = formatMoney(lineTotal, currencyId); var costX = layout.unitCostRight - (doc.getStringUnitWidth(cost) * doc.internal.getFontSize()); var qtyX = layout.qtyRight - (doc.getStringUnitWidth(qty) * doc.internal.getFontSize()); var taxX = layout.taxRight - (doc.getStringUnitWidth(tax+'%') * doc.internal.getFontSize()); var totalX = layout.lineTotalRight - (doc.getStringUnitWidth(lineTotal) * doc.internal.getFontSize()); //if (i==0) y -= 4; line += numLines; if (invoice.invoice_design_id == 1) { if (i%2 == 0) { doc.setDrawColor(255,255,255); doc.setFillColor(246,246,246); doc.rect(left, top, width-left, newTop-top, 'FD'); doc.setLineWidth(0.3); doc.setDrawColor(200,200,200); doc.line(left, top, width, top); doc.line(left, newTop, width, newTop); } } else if (invoice.invoice_design_id == 2) { if (i%2 == 0) { left = 0; width = 1000; doc.setDrawColor(255,255,255); doc.setFillColor(235,235,235); doc.rect(left, top, width-left, newTop-top, 'FD'); } } else if (invoice.invoice_design_id == 5) { if (i%2 == 0) { doc.setDrawColor(255,255,255); doc.setFillColor(247,247,247); doc.rect(left, top, width-left+17, newTop-top, 'FD'); } else { doc.setDrawColor(255,255,255); doc.setFillColor(232,232,232); doc.rect(left, top, width-left+17, newTop-top, 'FD'); } } else if (invoice.invoice_design_id == 6) { if (i%2 == 0) { doc.setDrawColor(232,232,232); doc.setFillColor(232,232,232); doc.rect(left, top, width-left, newTop-top, 'FD'); } else { doc.setDrawColor(255,255,255); doc.setFillColor(255,255,255); doc.rect(left, top, width-left, newTop-top, 'FD'); } } else if (invoice.invoice_design_id == 7) { doc.setLineWidth(1); doc.setDrawColor(45,35,32); for(var k = 1; k<=width-20; k++) { doc.line(left+4+k,newTop,left+4+1+k,newTop); k = k+3; } } else if (invoice.invoice_design_id == 8) { } else if (invoice.invoice_design_id == 9) { doc.setLineWidth(1); doc.setDrawColor(0,157,145); for(var j = 1; j<=width-40; j++) { doc.line(left+j,newTop,left+2+j,newTop); j = j+5; } } else if (invoice.invoice_design_id == 10) { doc.setLineWidth(0.3); doc.setDrawColor(63,60,60); doc.line(left, newTop, width, newTop); } else { doc.setLineWidth(0.3); doc.setDrawColor(150,150,150); doc.line(left, newTop, width, newTop); } y += 4; if (invoice.invoice_design_id == 1) { SetPdfColor('LightBlue', doc, 'primary'); } else if (invoice.invoice_design_id == 2) { SetPdfColor('SomeGreen', doc, 'primary'); } else if (invoice.invoice_design_id == 3) { doc.setFontType('bold'); } else if (invoice.invoice_design_id == 4) { SetPdfColor('Black', doc); } else if (invoice.invoice_design_id == 5) { SetPdfColor('Black', doc); } else if (invoice.invoice_design_id == 6) { SetPdfColor('Black', doc); } var splitTitle = doc.splitTextToSize(productKey, 60); if(invoice.invoice_design_id == 6) { doc.setFontType('bold'); } if(invoice.invoice_design_id == 9) { doc.setTextColor(187,51,40); } if(invoice.invoice_design_id == 10) { doc.setTextColor(205,81,56); } doc.text(layout.marginLeft, y+2, splitTitle); if (invoice.invoice_design_id == 5) { doc.setDrawColor(255, 255, 255); doc.setLineWidth(1); doc.line(layout.descriptionLeft-8, y-16,layout.descriptionLeft-8, y+55); doc.line(costX-30, y-16,costX-30, y+55); doc.line(qtyX-45, y-16,qtyX-45, y+55); /* if (invoice.has_taxes) { doc.line(taxX-15, y-16,taxX-15, y+55); } */ doc.line(totalX-27, y-16,totalX-27, y+55); } /* if (invoice.invoice_design_id == 8) { doc.setDrawColor(30, 30, 30); doc.setLineWidth(0.5); doc.line(layout.marginLeft-10, y-60,layout.marginLeft-10, y+20); doc.line(layout.descriptionLeft-8, y-60,layout.descriptionLeft-8, y+20); doc.line(costX-30, y-60,costX-30, y+20); console.log('CostX: %s', costX); doc.line(qtyX-45, y-60,qtyX-45, y+20); if (invoice.has_taxes) { doc.line(taxX-10, y-60,taxX-10, y+20); } doc.line(totalX-27, y-60,totalX-27, y+120); doc.line(totalX+35, y-60,totalX+35, y+120); } */ SetPdfColor('Black', doc); doc.setFontType('normal'); var splitDescription = doc.splitTextToSize(notes, 190); doc.text(layout.descriptionLeft, y+2, splitDescription); doc.text(costX, y+2, cost); if (!hideQuantity) { doc.text(qtyX, y+2, qty); } if(invoice.invoice_design_id == 9) { doc.setTextColor(187,51,40); doc.setFontType('bold'); } if(invoice.invoice_design_id == 10) { doc.setTextColor(205,81,56); } doc.text(totalX, y+2, lineTotal); doc.setFontType('normal'); SetPdfColor('Black', doc); if (tax) { doc.text(taxX, y+2, tax+'%'); } } y = tableTop + (line * layout.tableRowHeight) + (3 * layout.tablePadding); if (invoice.invoice_design_id == 8) { doc.setDrawColor(30, 30, 30); doc.setLineWidth(0.5); var topX = tableTop - 14; doc.line(layout.marginLeft-10, topX,layout.marginLeft-10, y); doc.line(layout.descriptionLeft-8, topX,layout.descriptionLeft-8, y); doc.line(layout.unitCostRight-55, topX,layout.unitCostRight-55, y); doc.line(layout.qtyRight-50, topX,layout.qtyRight-50, y); /* if (invoice.has_taxes) { doc.line(layout.taxRight-28, topX,layout.taxRight-28, y); } */ doc.line(totalX-25, topX,totalX-25, y+90); doc.line(totalX+45, topX,totalX+45, y+90); } var cutoff = 700; if (invoice.terms) { cutoff -= 50; } if (invoice.public_notes) { cutoff -= 50; } if (y > cutoff) { doc.addPage(); return layout.marginLeft; } return y; } // http://stackoverflow.com/questions/11941876/correctly-suppressing-warnings-in-datatables window.alert = (function() { var nativeAlert = window.alert; return function(message) { window.alert = nativeAlert; message && message.indexOf("DataTables warning") === 0 ? console.error(message) : nativeAlert(message); } })(); // http://stackoverflow.com/questions/1068834/object-comparison-in-javascript function objectEquals(x, y) { // if both are function if (x instanceof Function) { if (y instanceof Function) { return x.toString() === y.toString(); } return false; } if (x === null || x === undefined || y === null || y === undefined) { return x === y; } if (x === y || x.valueOf() === y.valueOf()) { return true; } // if one of them is date, they must had equal valueOf if (x instanceof Date) { return false; } if (y instanceof Date) { return false; } // if they are not function or strictly equal, they both need to be Objects if (!(x instanceof Object)) { return false; } if (!(y instanceof Object)) { return false; } var p = Object.keys(x); return Object.keys(y).every(function (i) { return p.indexOf(i) !== -1; }) ? p.every(function (i) { return objectEquals(x[i], y[i]); }) : false; } /*\ |*| |*| Base64 / binary data / UTF-8 strings utilities |*| |*| https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding |*| \*/ /* Array of bytes to base64 string decoding */ function b64ToUint6 (nChr) { return nChr > 64 && nChr < 91 ? nChr - 65 : nChr > 96 && nChr < 123 ? nChr - 71 : nChr > 47 && nChr < 58 ? nChr + 4 : nChr === 43 ? 62 : nChr === 47 ? 63 : 0; } function base64DecToArr (sBase64, nBlocksSize) { var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length, nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen); for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) { nMod4 = nInIdx & 3; nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4; if (nMod4 === 3 || nInLen - nInIdx === 1) { for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) { taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255; } nUint24 = 0; } } return taBytes; } /* Base64 string to array encoding */ function uint6ToB64 (nUint6) { return nUint6 < 26 ? nUint6 + 65 : nUint6 < 52 ? nUint6 + 71 : nUint6 < 62 ? nUint6 - 4 : nUint6 === 62 ? 43 : nUint6 === 63 ? 47 : 65; } function base64EncArr (aBytes) { var nMod3 = 2, sB64Enc = ""; for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) { nMod3 = nIdx % 3; if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; } nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24); if (nMod3 === 2 || aBytes.length - nIdx === 1) { sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63)); nUint24 = 0; } } return sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? '' : nMod3 === 1 ? '=' : '=='); } /* UTF-8 array to DOMString and vice versa */ function UTF8ArrToStr (aBytes) { var sView = ""; for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) { nPart = aBytes[nIdx]; sView += String.fromCharCode( nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */ /* (nPart - 252 << 32) is not possible in ECMAScript! So...: */ (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */ (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */ (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */ (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */ (nPart - 192 << 6) + aBytes[++nIdx] - 128 : /* nPart < 127 ? */ /* one byte */ nPart ); } return sView; } function strToUTF8Arr (sDOMStr) { var aBytes, nChr, nStrLen = sDOMStr.length, nArrLen = 0; /* mapping... */ for (var nMapIdx = 0; nMapIdx < nStrLen; nMapIdx++) { nChr = sDOMStr.charCodeAt(nMapIdx); nArrLen += nChr < 0x80 ? 1 : nChr < 0x800 ? 2 : nChr < 0x10000 ? 3 : nChr < 0x200000 ? 4 : nChr < 0x4000000 ? 5 : 6; } aBytes = new Uint8Array(nArrLen); /* transcription... */ for (var nIdx = 0, nChrIdx = 0; nIdx < nArrLen; nChrIdx++) { nChr = sDOMStr.charCodeAt(nChrIdx); if (nChr < 128) { /* one byte */ aBytes[nIdx++] = nChr; } else if (nChr < 0x800) { /* two bytes */ aBytes[nIdx++] = 192 + (nChr >>> 6); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x10000) { /* three bytes */ aBytes[nIdx++] = 224 + (nChr >>> 12); aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x200000) { /* four bytes */ aBytes[nIdx++] = 240 + (nChr >>> 18); aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x4000000) { /* five bytes */ aBytes[nIdx++] = 248 + (nChr >>> 24); aBytes[nIdx++] = 128 + (nChr >>> 18 & 63); aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else /* if (nChr <= 0x7fffffff) */ { /* six bytes */ aBytes[nIdx++] = 252 + /* (nChr >>> 32) is not possible in ECMAScript! So...: */ (nChr / 1073741824); aBytes[nIdx++] = 128 + (nChr >>> 24 & 63); aBytes[nIdx++] = 128 + (nChr >>> 18 & 63); aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); aBytes[nIdx++] = 128 + (nChr & 63); } } return aBytes; } function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)} function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)} function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)} function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h} function setDocHexColor(doc, hex) { var r = hexToR(hex); var g = hexToG(hex); var b = hexToB(hex); return doc.setTextColor(r, g, b); } function setDocHexFill(doc, hex) { var r = hexToR(hex); var g = hexToG(hex); var b = hexToB(hex); return doc.setFillColor(r, g, b); } function setDocHexDraw(doc, hex) { var r = hexToR(hex); var g = hexToG(hex); var b = hexToB(hex); return doc.setDrawColor(r, g, b); } function toggleDatePicker(field) { $('#'+field).datepicker('show'); } function roundToTwo(num, toString) { var val = +(Math.round(num + "e+2") + "e-2"); return toString ? val.toFixed(2) : (val || 0); } function truncate(str, length) { return (str && str.length > length) ? (str.substr(0, length-1) + '...') : str; } // http://codeaid.net/javascript/convert-seconds-to-hours-minutes-and-seconds-%28javascript%29 function secondsToTime(secs) { secs = Math.round(secs); var hours = Math.floor(secs / (60 * 60)); var divisor_for_minutes = secs % (60 * 60); var minutes = Math.floor(divisor_for_minutes / 60); var divisor_for_seconds = divisor_for_minutes % 60; var seconds = Math.ceil(divisor_for_seconds); var obj = { "h": hours, "m": minutes, "s": seconds }; return obj; } function twoDigits(value) { if (value < 10) { return '0' + value; } return value; } function toSnakeCase(str) { if (!str) return ''; return str.replace(/([A-Z])/g, function($1){return "_"+$1.toLowerCase();}); } function getDescendantProp(obj, desc) { var arr = desc.split("."); while(arr.length && (obj = obj[arr.shift()])); return obj; } function doubleDollarSign(str) { if (!str) return ''; return str.replace(/\$/g, '\$\$\$'); }<file_sep>/app/Ninja/Repositories/ClientRepository.php <?php namespace App\Ninja\Repositories; use App\Models\Client; use App\Models\Contact; use App\Models\Activity; class ClientRepository { public function find($filter = null) { $query = \DB::table('clients') ->join('contacts', 'contacts.client_id', '=', 'clients.id') ->where('clients.account_id', '=', \Auth::user()->account_id) ->where('contacts.is_primary', '=', true) ->where('contacts.deleted_at', '=', null) ->select('clients.public_id', 'clients.name', 'contacts.first_name', 'contacts.last_name', 'clients.balance', 'clients.last_login', 'clients.created_at', 'clients.work_phone', 'contacts.email', 'clients.currency_id', 'clients.deleted_at', 'clients.is_deleted'); if (!\Session::get('show_trash:client')) { $query->where('clients.deleted_at', '=', null); } if ($filter) { $query->where(function ($query) use ($filter) { $query->where('clients.name', 'like', '%'.$filter.'%') ->orWhere('contacts.first_name', 'like', '%'.$filter.'%') ->orWhere('contacts.last_name', 'like', '%'.$filter.'%') ->orWhere('contacts.email', 'like', '%'.$filter.'%'); }); } return $query; } public function getErrors($data) { $contact = isset($data['contacts']) ? (array) $data['contacts'][0] : (isset($data['contact']) ? $data['contact'] : []); $validator = \Validator::make($contact, [ 'email' => 'email|required_without:first_name', 'first_name' => 'required_without:email', ]); if ($validator->fails()) { return $validator->messages(); } return false; } public function save($publicId, $data, $notify = true) { if (!$publicId || $publicId == "-1") { $client = Client::createNew(); $contact = Contact::createNew(); $contact->is_primary = true; $contact->send_invoice = true; } else { $client = Client::scope($publicId)->with('contacts')->firstOrFail(); $contact = $client->contacts()->where('is_primary', '=', true)->firstOrFail(); } if (isset($data['name'])) { $client->name = trim($data['name']); } if (isset($data['id_number'])) { $client->id_number = trim($data['id_number']); } if (isset($data['vat_number'])) { $client->vat_number = trim($data['vat_number']); } if (isset($data['work_phone'])) { $client->work_phone = trim($data['work_phone']); } if (isset($data['custom_value1'])) { $client->custom_value1 = trim($data['custom_value1']); } if (isset($data['custom_value2'])) { $client->custom_value2 = trim($data['custom_value2']); } if (isset($data['address1'])) { $client->address1 = trim($data['address1']); } if (isset($data['address2'])) { $client->address2 = trim($data['address2']); } if (isset($data['city'])) { $client->city = trim($data['city']); } if (isset($data['state'])) { $client->state = trim($data['state']); } if (isset($data['postal_code'])) { $client->postal_code = trim($data['postal_code']); } if (isset($data['country_id'])) { $client->country_id = $data['country_id'] ? $data['country_id'] : null; } if (isset($data['private_notes'])) { $client->private_notes = trim($data['private_notes']); } if (isset($data['size_id'])) { $client->size_id = $data['size_id'] ? $data['size_id'] : null; } if (isset($data['industry_id'])) { $client->industry_id = $data['industry_id'] ? $data['industry_id'] : null; } if (isset($data['currency_id'])) { $client->currency_id = $data['currency_id'] ? $data['currency_id'] : null; } if (isset($data['payment_terms'])) { $client->payment_terms = $data['payment_terms']; } if (isset($data['website'])) { $client->website = trim($data['website']); } $client->save(); $isPrimary = true; $contactIds = []; if (isset($data['contact'])) { $info = $data['contact']; if (isset($info['email'])) { $contact->email = trim($info['email']); } if (isset($info['first_name'])) { $contact->first_name = trim($info['first_name']); } if (isset($info['last_name'])) { $contact->last_name = trim($info['last_name']); } if (isset($info['phone'])) { $contact->phone = trim($info['phone']); } $contact->is_primary = true; $contact->send_invoice = true; $client->contacts()->save($contact); } else { foreach ($data['contacts'] as $record) { $record = (array) $record; if ($publicId != "-1" && isset($record['public_id']) && $record['public_id']) { $contact = Contact::scope($record['public_id'])->firstOrFail(); } else { $contact = Contact::createNew(); } if (isset($record['email'])) { $contact->email = trim($record['email']); } if (isset($record['first_name'])) { $contact->first_name = trim($record['first_name']); } if (isset($record['last_name'])) { $contact->last_name = trim($record['last_name']); } if (isset($record['phone'])) { $contact->phone = trim($record['phone']); } $contact->is_primary = $isPrimary; $contact->send_invoice = isset($record['send_invoice']) ? $record['send_invoice'] : true; $isPrimary = false; $client->contacts()->save($contact); $contactIds[] = $contact->public_id; } foreach ($client->contacts as $contact) { if (!in_array($contact->public_id, $contactIds)) { $contact->delete(); } } } $client->save(); if (!$publicId || $publicId == "-1") { Activity::createClient($client, $notify); } return $client; } public function bulk($ids, $action) { $clients = Client::withTrashed()->scope($ids)->get(); foreach ($clients as $client) { if ($action == 'restore') { $client->restore(); $client->is_deleted = false; $client->save(); } else { if ($action == 'delete') { $client->is_deleted = true; $client->save(); } $client->delete(); } } return count($clients); } } <file_sep>/app/Models/Account.php <?php namespace App\Models; use Eloquent; use Utils; use Session; use DateTime; use Event; use App; use App\Events\UserSettingsChanged; use Illuminate\Database\Eloquent\SoftDeletes; class Account extends Eloquent { use SoftDeletes; protected $dates = ['deleted_at']; /* protected $casts = [ 'hide_quantity' => 'boolean', ]; */ public function users() { return $this->hasMany('App\Models\User'); } public function clients() { return $this->hasMany('App\Models\Client'); } public function invoices() { return $this->hasMany('App\Models\Invoice'); } public function account_gateways() { return $this->hasMany('App\Models\AccountGateway'); } public function tax_rates() { return $this->hasMany('App\Models\TaxRate'); } public function country() { return $this->belongsTo('App\Models\Country'); } public function timezone() { return $this->belongsTo('App\Models\Timezone'); } public function language() { return $this->belongsTo('App\Models\Language'); } public function date_format() { return $this->belongsTo('App\Models\DateFormat'); } public function datetime_format() { return $this->belongsTo('App\Models\DatetimeFormat'); } public function size() { return $this->belongsTo('App\Models\Size'); } public function currency() { return $this->belongsTo('App\Models\Currency'); } public function industry() { return $this->belongsTo('App\Models\Industry'); } public function isGatewayConfigured($gatewayId = 0) { $this->load('account_gateways'); if ($gatewayId) { return $this->getGatewayConfig($gatewayId) != false; } else { return count($this->account_gateways) > 0; } } public function isEnglish() { return !$this->language_id || $this->language_id == DEFAULT_LANGUAGE; } public function getDisplayName() { if ($this->name) { return $this->name; } $this->load('users'); $user = $this->users()->first(); return $user->getDisplayName(); } public function getTimezone() { if ($this->timezone) { return $this->timezone->name; } else { return 'US/Eastern'; } } public function getGatewayByType($type = PAYMENT_TYPE_ANY) { foreach ($this->account_gateways as $gateway) { if (!$type || $type == PAYMENT_TYPE_ANY) { return $gateway; } elseif ($gateway->isPaymentType($type)) { return $gateway; } } return false; } public function getGatewayConfig($gatewayId) { foreach ($this->account_gateways as $gateway) { if ($gateway->gateway_id == $gatewayId) { return $gateway; } } return false; } /* public function hasLogo() { file_exists($this->getLogoPath()); } */ public function getLogoPath() { $fileName = 'logo/' . $this->account_key; return file_exists($fileName.'.png') ? $fileName.'.png' : $fileName.'.jpg'; } public function getLogoWidth() { $path = $this->getLogoPath(); if (!file_exists($path)) { return 0; } list($width, $height) = getimagesize($path); return $width; } public function getLogoHeight() { $path = $this->getLogoPath(); if (!file_exists($path)) { return 0; } list($width, $height) = getimagesize($path); return $height; } public function getNextInvoiceNumber($isQuote = false, $prefix = '') { $counter = $isQuote && !$this->share_counter ? $this->quote_number_counter : $this->invoice_number_counter; $prefix .= $isQuote ? $this->quote_number_prefix : $this->invoice_number_prefix; $counterOffset = 0; // confirm the invoice number isn't already taken do { $number = $prefix.str_pad($counter, 4, "0", STR_PAD_LEFT); $check = Invoice::scope(false, $this->id)->whereInvoiceNumber($number)->withTrashed()->first(); $counter++; $counterOffset++; } while ($check); // update the invoice counter to be caught up if ($counterOffset > 1) { if ($isQuote && !$this->share_counter) { $this->quote_number_counter += $counterOffset - 1; } else { $this->invoice_number_counter += $counterOffset - 1; } $this->save(); } return $number; } public function incrementCounter($isQuote = false) { if ($isQuote && !$this->share_counter) { $this->quote_number_counter += 1; } else { $this->invoice_number_counter += 1; } $this->save(); } public function getLocale() { $language = Language::where('id', '=', $this->account->language_id)->first(); return $language->locale; } public function loadLocalizationSettings() { $this->load('timezone', 'date_format', 'datetime_format', 'language'); Session::put(SESSION_TIMEZONE, $this->timezone ? $this->timezone->name : DEFAULT_TIMEZONE); Session::put(SESSION_DATE_FORMAT, $this->date_format ? $this->date_format->format : DEFAULT_DATE_FORMAT); Session::put(SESSION_DATE_PICKER_FORMAT, $this->date_format ? $this->date_format->picker_format : DEFAULT_DATE_PICKER_FORMAT); Session::put(SESSION_DATETIME_FORMAT, $this->datetime_format ? $this->datetime_format->format : DEFAULT_DATETIME_FORMAT); Session::put(SESSION_CURRENCY, $this->currency_id ? $this->currency_id : DEFAULT_CURRENCY); Session::put(SESSION_LOCALE, $this->language_id ? $this->language->locale : DEFAULT_LOCALE); App::setLocale(session(SESSION_LOCALE)); } public function getInvoiceLabels() { $data = []; $custom = (array) json_decode($this->invoice_labels); $fields = [ 'invoice', 'invoice_date', 'due_date', 'invoice_number', 'po_number', 'discount', 'taxes', 'tax', 'item', 'description', 'unit_cost', 'quantity', 'line_total', 'subtotal', 'paid_to_date', 'balance_due', 'amount_due', 'terms', 'your_invoice', 'quote', 'your_quote', 'quote_date', 'quote_number', 'total', 'invoice_issued_to', 'date', 'rate', 'hours', 'balance', 'from', 'to', 'invoice_to', 'details', 'invoice_no', ]; foreach ($fields as $field) { if (isset($custom[$field]) && $custom[$field]) { $data[$field] = $custom[$field]; } else { $data[$field] = $this->isEnglish() ? uctrans("texts.$field") : trans("texts.$field"); } } foreach (['item', 'quantity', 'unit_cost'] as $field) { $data["{$field}_orig"] = $data[$field]; } return $data; } public function isPro() { if (!Utils::isNinjaProd()) { return true; } if ($this->account_key == NINJA_ACCOUNT_KEY) { return true; } $datePaid = $this->pro_plan_paid; if (!$datePaid || $datePaid == '0000-00-00') { return false; } elseif ($datePaid == NINJA_DATE) { return true; } $today = new DateTime('now'); $datePaid = DateTime::createFromFormat('Y-m-d', $datePaid); $interval = $today->diff($datePaid); return $interval->y == 0; } public function isWhiteLabel() { if (Utils::isNinjaProd()) { return self::isPro() && $this->pro_plan_paid != NINJA_DATE; } else { return $this->pro_plan_paid == NINJA_DATE; } } public function getSubscription($eventId) { return Subscription::where('account_id', '=', $this->id)->where('event_id', '=', $eventId)->first(); } public function hideFieldsForViz() { foreach ($this->clients as $client) { $client->setVisible([ 'public_id', 'name', 'balance', 'paid_to_date', 'invoices', 'contacts', ]); foreach ($client->invoices as $invoice) { $invoice->setVisible([ 'public_id', 'invoice_number', 'amount', 'balance', 'invoice_status_id', 'invoice_items', 'created_at', 'is_recurring', 'is_quote', ]); foreach ($invoice->invoice_items as $invoiceItem) { $invoiceItem->setVisible([ 'product_key', 'cost', 'qty', ]); } } foreach ($client->contacts as $contact) { $contact->setVisible([ 'public_id', 'first_name', 'last_name', 'email', ]); } } return $this; } public function getEmailTemplate($entityType, $message = false) { $field = "email_template_$entityType"; $template = $this->$field; if ($template) { return $template; } $template = "\$client,<p/>\r\n\r\n" . trans("texts.{$entityType}_message", ['amount' => '$amount']) . "<p/>\r\n\r\n"; if ($entityType != ENTITY_PAYMENT) { $template .= "<a href=\"\$link\">\$link</a><p/>\r\n\r\n"; } if ($message) { $template .= "$message<p/>\r\n\r\n"; } return $template . "\$footer"; } public function getEmailFooter() { if ($this->email_footer) { // Add line breaks if HTML isn't already being used return strip_tags($this->email_footer) == $this->email_footer ? nl2br($this->email_footer) : $this->email_footer; } else { return "<p>" . trans('texts.email_signature') . "<br>\$account</p>"; } } public function showTokenCheckbox() { if (!$this->isGatewayConfigured(GATEWAY_STRIPE)) { return false; } return $this->token_billing_type_id == TOKEN_BILLING_OPT_IN || $this->token_billing_type_id == TOKEN_BILLING_OPT_OUT; } public function selectTokenCheckbox() { return $this->token_billing_type_id == TOKEN_BILLING_OPT_OUT; } } Account::updated(function ($account) { Event::fire(new UserSettingsChanged()); }); <file_sep>/database/seeds/PaymentLibrariesSeeder.php <?php use App\Models\Gateway; use App\Models\PaymentTerm; use App\Models\Currency; use App\Models\DateFormat; use App\Models\DatetimeFormat; use App\Models\InvoiceDesign; class PaymentLibrariesSeeder extends Seeder { public function run() { Eloquent::unguard(); $this->createGateways(); $this->createPaymentTerms(); $this->createDateFormats(); $this->createDatetimeFormats(); $this->createInvoiceDesigns(); } private function createGateways() { $gateways = [ ['name' => 'BeanStream', 'provider' => 'BeanStream', 'payment_library_id' => 2], ['name' => 'Psigate', 'provider' => 'Psigate', 'payment_library_id' => 2], ['name' => 'moolah', 'provider' => 'AuthorizeNet_AIM', 'sort_order' => 1, 'recommended' => 1, 'site_url' => 'https://invoiceninja.mymoolah.com/', 'payment_library_id' => 1], ['name' => 'Alipay', 'provider' => 'Alipay_Express', 'payment_library_id' => 1], ['name' => 'Buckaroo', 'provider' => 'Buckaroo_CreditCard', 'payment_library_id' => 1], ['name' => 'Coinbase', 'provider' => 'Coinbase', 'payment_library_id' => 1], ['name' => 'DataCash', 'provider' => 'DataCash', 'payment_library_id' => 1], ['name' => 'Neteller', 'provider' => 'Neteller', 'payment_library_id' => 1], ['name' => 'Pacnet', 'provider' => 'Pacnet', 'payment_library_id' => 1], ['name' => 'PaymentSense', 'provider' => 'PaymentSense', 'payment_library_id' => 1], ['name' => 'Realex', 'provider' => 'Realex_Remote', 'payment_library_id' => 1], ['name' => 'Sisow', 'provider' => 'Sisow', 'payment_library_id' => 1], ['name' => 'Skrill', 'provider' => 'Skrill', 'payment_library_id' => 1], ['name' => 'BitPay', 'provider' => 'BitPay', 'payment_library_id' => 1], ['name' => 'Dwolla', 'provider' => 'Dwolla', 'payment_library_id' => 1], ]; foreach ($gateways as $gateway) { if (!DB::table('gateways')->where('name', '=', $gateway['name'])->get()) { Gateway::create($gateway); } } } private function createPaymentTerms() { $paymentTerms = [ ['num_days' => -1, 'name' => 'Net 0'], ]; foreach ($paymentTerms as $paymentTerm) { if (!DB::table('payment_terms')->where('name', '=', $paymentTerm['name'])->get()) { PaymentTerm::create($paymentTerm); } } $currencies = [ ['name' => 'US Dollar', 'code' => 'USD', 'symbol' => '$', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Pound Sterling', 'code' => 'GBP', 'symbol' => '£', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Euro', 'code' => 'EUR', 'symbol' => '€', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'South African Rand', 'code' => 'ZAR', 'symbol' => 'R', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => '<NAME>', 'code' => 'DKK', 'symbol' => 'kr ', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => '<NAME>', 'code' => 'ILS', 'symbol' => 'NIS ', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Swedish Krona', 'code' => 'SEK', 'symbol' => 'kr ', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => '<NAME>', 'code' => 'KES', 'symbol' => 'KSh ', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Canadian Dollar', 'code' => 'CAD', 'symbol' => 'C$', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => '<NAME>', 'code' => 'PHP', 'symbol' => 'P ', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Indian Rupee', 'code' => 'INR', 'symbol' => 'Rs. ', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Australian Dollar', 'code' => 'AUD', 'symbol' => '$', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Singapore Dollar', 'code' => 'SGD', 'symbol' => 'SGD ', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => '<NAME>', 'code' => 'NOK', 'symbol' => 'kr ', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'New Zealand Dollar', 'code' => 'NZD', 'symbol' => '$', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Vietnamese Dong', 'code' => 'VND', 'symbol' => 'VND ', 'precision' => '0', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Swiss Franc', 'code' => 'CHF', 'symbol' => 'CHF ', 'precision' => '2', 'thousand_separator' => '\'', 'decimal_separator' => '.'], ['name' => 'Guatemalan Quetzal', 'code' => 'GTQ', 'symbol' => 'Q', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Malaysian Ringgit', 'code' => 'MYR', 'symbol' => 'RM', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Brazilian Real', 'code' => 'BRL', 'symbol' => 'R$', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => '<NAME>', 'code' => 'THB', 'symbol' => 'THB ', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Nigerian Naira', 'code' => 'NGN', 'symbol' => 'NGN ', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['name' => 'Argentine Peso', 'code' => 'ARS', 'symbol' => '$', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ]; foreach ($currencies as $currency) { $record = Currency::whereCode($currency['code'])->first(); if ($record) { $record->name = $currency['name']; $record->save(); } else { Currency::create($currency); } } } private function createDateFormats() { $formats = [ ['format' => 'd/M/Y', 'picker_format' => 'dd/M/yyyy', 'label' => '10/Mar/2013'], ['format' => 'd-M-Y', 'picker_format' => 'dd-M-yyyy', 'label' => '10-Mar-2013'], ['format' => 'd/F/Y', 'picker_format' => 'dd/MM/yyyy', 'label' => '10/March/2013'], ['format' => 'd-F-Y', 'picker_format' => 'dd-MM-yyyy', 'label' => '10-March-2013'], ['format' => 'M j, Y', 'picker_format' => 'M d, yyyy', 'label' => 'Mar 10, 2013'], ['format' => 'F j, Y', 'picker_format' => 'MM d, yyyy', 'label' => 'March 10, 2013'], ['format' => 'D M j, Y', 'picker_format' => 'D MM d, yyyy', 'label' => 'Mon March 10, 2013'], ['format' => 'Y-M-d', 'picker_format' => 'yyyy-M-dd', 'label' => '2013-03-10'], ['format' => 'd/m/Y', 'picker_format' => 'dd/mm/yyyy', 'label' => '20/03/2013'], ]; foreach ($formats as $format) { if (!DB::table('date_formats')->whereLabel($format['label'])->get()) { DateFormat::create($format); } } } private function createDatetimeFormats() { $formats = [ ['format' => 'd/M/Y g:i a', 'label' => '10/Mar/2013'], ['format' => 'd-M-Yk g:i a', 'label' => '10-Mar-2013'], ['format' => 'd/F/Y g:i a', 'label' => '10/March/2013'], ['format' => 'd-F-Y g:i a', 'label' => '10-March-2013'], ['format' => 'M j, Y g:i a', 'label' => 'Mar 10, 2013 6:15 pm'], ['format' => 'F j, Y g:i a', 'label' => 'March 10, 2013 6:15 pm'], ['format' => 'D M jS, Y g:ia', 'label' => 'Mon March 10th, 2013 6:15 pm'], ['format' => 'Y-M-d g:i a', 'label' => '2013-03-10 6:15 pm'], ['format' => 'd/m/Y g:i a', 'label' => '20/03/2013 6:15 pm'], ]; foreach ($formats as $format) { if (!DB::table('datetime_formats')->whereLabel($format['label'])->get()) { DatetimeFormat::create($format); } } } private function createInvoiceDesigns() { $designs = [ 'Clean', 'Bold', 'Modern', 'Plain', 'Business', 'Creative', 'Elegant', 'Hipster', 'Playful', 'Photo', ]; for ($i=0; $i<count($designs); $i++) { $design = $designs[$i]; $fileName = storage_path() . '/templates/' . strtolower($design) . '.js'; if (file_exists($fileName)) { $pdfmake = file_get_contents($fileName); if ($pdfmake) { $record = InvoiceDesign::whereName($design)->first(); if (!$record) { $record = new InvoiceDesign; $record->id = $i + 1; $record->name = $design; } $record->pdfmake = $pdfmake; $record->save(); } } } } } <file_sep>/app/Listeners/HandleInvoicePaid.php <?php namespace App\Listeners; use App\Events\InvoicePaid; use App\Ninja\Mailers\UserMailer; use App\Ninja\Mailers\ContactMailer; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldBeQueued; class HandleInvoicePaid { protected $userMailer; protected $contactMailer; /** * Create the event handler. * * @return void */ public function __construct(UserMailer $userMailer, ContactMailer $contactMailer) { $this->userMailer = $userMailer; $this->contactMailer = $contactMailer; } /** * Handle the event. * * @param InvoicePaid $event * @return void */ public function handle(InvoicePaid $event) { $payment = $event->payment; $invoice = $payment->invoice; $this->contactMailer->sendPaymentConfirmation($payment); foreach ($invoice->account->users as $user) { if ($user->{'notify_paid'}) { $this->userMailer->sendNotification($user, $invoice, 'paid', $payment); } } } } <file_sep>/app/Models/Activity.php <?php namespace App\Models; use Auth; use Eloquent; use Utils; use Session; use Request; use Carbon; class Activity extends Eloquent { public $timestamps = true; public function scopeScope($query) { return $query->whereAccountId(Auth::user()->account_id); } public function account() { return $this->belongsTo('App\Models\Account'); } public function user() { return $this->belongsTo('App\Models\User'); } private static function getBlank($entity = false) { $activity = new Activity(); if ($entity) { $activity->user_id = $entity instanceof User ? $entity->id : $entity->user_id; $activity->account_id = $entity->account_id; } elseif (Auth::check()) { $activity->user_id = Auth::user()->id; $activity->account_id = Auth::user()->account_id; } else { Utils::fatalError(); } $activity->token_id = Session::get('token_id', null); $activity->ip = Request::getClientIp(); return $activity; } public static function createClient($client, $notify = true) { $activity = Activity::getBlank(); $activity->client_id = $client->id; $activity->activity_type_id = ACTIVITY_TYPE_CREATE_CLIENT; $activity->message = Utils::encodeActivity(Auth::user(), 'created', $client); $activity->save(); if ($notify) { Activity::checkSubscriptions(EVENT_CREATE_CLIENT, $client); } } public static function updateClient($client) { if ($client->is_deleted && !$client->getOriginal('is_deleted')) { $activity = Activity::getBlank(); $activity->client_id = $client->id; $activity->activity_type_id = ACTIVITY_TYPE_DELETE_CLIENT; $activity->message = Utils::encodeActivity(Auth::user(), 'deleted', $client); $activity->balance = $client->balance; $activity->save(); } } public static function archiveClient($client) { if (!$client->is_deleted) { $activity = Activity::getBlank(); $activity->client_id = $client->id; $activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_CLIENT; $activity->message = Utils::encodeActivity(Auth::user(), 'archived', $client); $activity->balance = $client->balance; $activity->save(); } } public static function restoreClient($client) { $activity = Activity::getBlank(); $activity->client_id = $client->id; $activity->activity_type_id = ACTIVITY_TYPE_RESTORE_CLIENT; $activity->message = Utils::encodeActivity(Auth::user(), 'restored', $client); $activity->balance = $client->balance; $activity->save(); } public static function createInvoice($invoice) { if (Auth::check()) { $message = Utils::encodeActivity(Auth::user(), 'created', $invoice); } else { $message = Utils::encodeActivity(null, 'created', $invoice); } $adjustment = 0; $client = $invoice->client; if (!$invoice->is_quote && !$invoice->is_recurring) { $adjustment = $invoice->amount; $client->balance = $client->balance + $adjustment; $client->save(); } $activity = Activity::getBlank($invoice); $activity->invoice_id = $invoice->id; $activity->client_id = $invoice->client_id; $activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_CREATE_QUOTE : ACTIVITY_TYPE_CREATE_INVOICE; $activity->message = $message; $activity->balance = $client->balance; $activity->adjustment = $adjustment; $activity->save(); Activity::checkSubscriptions($invoice->is_quote ? EVENT_CREATE_QUOTE : EVENT_CREATE_INVOICE, $invoice); } public static function archiveInvoice($invoice) { if (!$invoice->is_deleted) { $activity = Activity::getBlank(); $activity->invoice_id = $invoice->id; $activity->client_id = $invoice->client_id; $activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_ARCHIVE_QUOTE : ACTIVITY_TYPE_ARCHIVE_INVOICE; $activity->message = Utils::encodeActivity(Auth::user(), 'archived', $invoice); $activity->balance = $invoice->client->balance; $activity->save(); } } public static function restoreInvoice($invoice) { $activity = Activity::getBlank(); $activity->invoice_id = $invoice->id; $activity->client_id = $invoice->client_id; $activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_RESTORE_QUOTE : ACTIVITY_TYPE_RESTORE_INVOICE; $activity->message = Utils::encodeActivity(Auth::user(), 'restored', $invoice); $activity->balance = $invoice->client->balance; $activity->save(); } public static function emailInvoice($invitation) { $adjustment = 0; $client = $invitation->invoice->client; $activity = Activity::getBlank($invitation); $activity->client_id = $invitation->invoice->client_id; $activity->invoice_id = $invitation->invoice_id; $activity->contact_id = $invitation->contact_id; $activity->activity_type_id = $invitation->invoice ? ACTIVITY_TYPE_EMAIL_QUOTE : ACTIVITY_TYPE_EMAIL_INVOICE; $activity->message = Utils::encodeActivity(Auth::check() ? Auth::user() : null, 'emailed', $invitation->invoice, $invitation->contact); $activity->balance = $client->balance; $activity->save(); } public static function updateInvoice($invoice) { $client = $invoice->client; if ($invoice->is_deleted && !$invoice->getOriginal('is_deleted')) { $adjustment = 0; if (!$invoice->is_quote && !$invoice->is_recurring) { $adjustment = $invoice->balance * -1; $client->balance = $client->balance - $invoice->balance; $client->paid_to_date = $client->paid_to_date - ($invoice->amount - $invoice->balance); $client->save(); } $activity = Activity::getBlank(); $activity->client_id = $invoice->client_id; $activity->invoice_id = $invoice->id; $activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_DELETE_QUOTE : ACTIVITY_TYPE_DELETE_INVOICE; $activity->message = Utils::encodeActivity(Auth::user(), 'deleted', $invoice); $activity->balance = $invoice->client->balance; $activity->adjustment = $adjustment; $activity->save(); } else { $diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount')); $fieldChanged = false; foreach (['invoice_number', 'po_number', 'invoice_date', 'due_date', 'terms', 'public_notes', 'invoice_footer', 'partial'] as $field) { if ($invoice->$field != $invoice->getOriginal($field)) { $fieldChanged = true; break; } } if ($diff != 0 || $fieldChanged) { $backupInvoice = Invoice::with('invoice_items', 'client.account', 'client.contacts')->find($invoice->id); if ($diff != 0 && !$invoice->is_quote && !$invoice->is_recurring) { $client->balance = $client->balance + $diff; $client->save(); } $activity = Activity::getBlank($invoice); $activity->client_id = $invoice->client_id; $activity->invoice_id = $invoice->id; $activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_UPDATE_QUOTE : ACTIVITY_TYPE_UPDATE_INVOICE; $activity->message = Utils::encodeActivity(Auth::user(), 'updated', $invoice); $activity->balance = $client->balance; $activity->adjustment = $invoice->is_quote || $invoice->is_recurring ? 0 : $diff; $activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON(); $activity->save(); if ($invoice->isPaid() && $invoice->balance > 0) { $invoice->invoice_status_id = INVOICE_STATUS_PARTIAL; } elseif ($invoice->invoice_status_id && $invoice->balance == 0) { $invoice->invoice_status_id = INVOICE_STATUS_PAID; } } } } public static function viewInvoice($invitation) { if (Session::get($invitation->invitation_key)) { return; } Session::put($invitation->invitation_key, true); $invoice = $invitation->invoice; if (!$invoice->isViewed()) { $invoice->invoice_status_id = INVOICE_STATUS_VIEWED; $invoice->save(); } $now = Carbon::now()->toDateTimeString(); $invitation->viewed_date = $now; $invitation->save(); $client = $invoice->client; $client->last_login = $now; $client->save(); $activity = Activity::getBlank($invitation); $activity->client_id = $invitation->invoice->client_id; $activity->invitation_id = $invitation->id; $activity->contact_id = $invitation->contact_id; $activity->invoice_id = $invitation->invoice_id; $activity->activity_type_id = $invitation->invoice->is_quote ? ACTIVITY_TYPE_VIEW_QUOTE : ACTIVITY_TYPE_VIEW_INVOICE; $activity->message = Utils::encodeActivity($invitation->contact, 'viewed', $invitation->invoice); $activity->balance = $invitation->invoice->client->balance; $activity->save(); } public static function approveQuote($invitation) { $activity = Activity::getBlank($invitation); $activity->client_id = $invitation->invoice->client_id; $activity->invitation_id = $invitation->id; $activity->contact_id = $invitation->contact_id; $activity->invoice_id = $invitation->invoice_id; $activity->activity_type_id = ACTIVITY_TYPE_APPROVE_QUOTE; $activity->message = Utils::encodeActivity($invitation->contact, 'approved', $invitation->invoice); $activity->balance = $invitation->invoice->client->balance; $activity->save(); } public static function createPayment($payment) { $client = $payment->client; $client->balance = $client->balance - $payment->amount; $client->paid_to_date = $client->paid_to_date + $payment->amount; $client->save(); if ($payment->contact_id) { $activity = Activity::getBlank($client); $activity->contact_id = $payment->contact_id; $activity->message = Utils::encodeActivity($payment->invitation->contact, 'entered '.$payment->getName().' for ', $payment->invoice); } else { $activity = Activity::getBlank($client); $message = $payment->payment_type_id == PAYMENT_TYPE_CREDIT ? 'applied credit for ' : 'entered '.$payment->getName().' for '; $activity->message = Utils::encodeActivity(Auth::user(), $message, $payment->invoice); } $activity->payment_id = $payment->id; if ($payment->invoice_id) { $activity->invoice_id = $payment->invoice_id; $invoice = $payment->invoice; $invoice->balance = $invoice->balance - $payment->amount; $invoice->invoice_status_id = ($invoice->balance > 0) ? INVOICE_STATUS_PARTIAL : INVOICE_STATUS_PAID; if ($invoice->partial > 0) { $invoice->partial = max(0, $invoice->partial - $payment->amount); } $invoice->save(); } $activity->payment_id = $payment->id; $activity->client_id = $payment->client_id; $activity->activity_type_id = ACTIVITY_TYPE_CREATE_PAYMENT; $activity->balance = $client->balance; $activity->adjustment = $payment->amount * -1; $activity->save(); Activity::checkSubscriptions(EVENT_CREATE_PAYMENT, $payment); } public static function updatePayment($payment) { if ($payment->is_deleted && !$payment->getOriginal('is_deleted')) { $client = $payment->client; $client->balance = $client->balance + $payment->amount; $client->paid_to_date = $client->paid_to_date - $payment->amount; $client->save(); $invoice = $payment->invoice; $invoice->balance = $invoice->balance + $payment->amount; if ($invoice->isPaid() && $invoice->balance > 0) { $invoice->invoice_status_id = ($invoice->balance == $invoice->amount ? INVOICE_STATUS_DRAFT : INVOICE_STATUS_PARTIAL); } $invoice->save(); // deleting a payment from credit creates a new credit if ($payment->payment_type_id == PAYMENT_TYPE_CREDIT) { $credit = Credit::createNew(); $credit->client_id = $client->id; $credit->credit_date = Carbon::now()->toDateTimeString(); $credit->balance = $credit->amount = $payment->amount; $credit->private_notes = $payment->transaction_reference; $credit->save(); } $activity = Activity::getBlank(); $activity->payment_id = $payment->id; $activity->client_id = $invoice->client_id; $activity->invoice_id = $invoice->id; $activity->activity_type_id = ACTIVITY_TYPE_DELETE_PAYMENT; $activity->message = Utils::encodeActivity(Auth::user(), 'deleted '.$payment->getName()); $activity->balance = $client->balance; $activity->adjustment = $payment->amount; $activity->save(); } else { /* $diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount')); if ($diff == 0) { return; } $client = $invoice->client; $client->balance = $client->balance + $diff; $client->save(); $activity = Activity::getBlank($invoice); $activity->client_id = $invoice->client_id; $activity->invoice_id = $invoice->id; $activity->activity_type_id = ACTIVITY_TYPE_UPDATE_INVOICE; $activity->message = Utils::encodeActivity(Auth::user(), 'updated', $invoice); $activity->balance = $client->balance; $activity->adjustment = $diff; $activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON(); $activity->save(); */ } } public static function archivePayment($payment) { if ($payment->is_deleted) { return; } $client = $payment->client; $invoice = $payment->invoice; $activity = Activity::getBlank(); $activity->payment_id = $payment->id; $activity->invoice_id = $invoice->id; $activity->client_id = $client->id; $activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_PAYMENT; $activity->message = Utils::encodeActivity(Auth::user(), 'archived '.$payment->getName()); $activity->balance = $client->balance; $activity->adjustment = 0; $activity->save(); } public static function restorePayment($payment) { $client = $payment->client; $invoice = $payment->invoice; $activity = Activity::getBlank(); $activity->payment_id = $payment->id; $activity->invoice_id = $invoice->id; $activity->client_id = $client->id; $activity->activity_type_id = ACTIVITY_TYPE_RESTORE_PAYMENT; $activity->message = Utils::encodeActivity(Auth::user(), 'restored '.$payment->getName()); $activity->balance = $client->balance; $activity->adjustment = 0; $activity->save(); } public static function createCredit($credit) { $activity = Activity::getBlank(); $activity->message = Utils::encodeActivity(Auth::user(), 'entered '.Utils::formatMoney($credit->amount, $credit->client->getCurrencyId()).' credit'); $activity->credit_id = $credit->id; $activity->client_id = $credit->client_id; $activity->activity_type_id = ACTIVITY_TYPE_CREATE_CREDIT; $activity->balance = $credit->client->balance; $activity->save(); } public static function updateCredit($credit) { if ($credit->is_deleted && !$credit->getOriginal('is_deleted')) { $activity = Activity::getBlank(); $activity->credit_id = $credit->id; $activity->client_id = $credit->client_id; $activity->activity_type_id = ACTIVITY_TYPE_DELETE_CREDIT; $activity->message = Utils::encodeActivity(Auth::user(), 'deleted '.Utils::formatMoney($credit->balance, $credit->client->getCurrencyId()).' credit'); $activity->balance = $credit->client->balance; $activity->save(); } else { /* $diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount')); if ($diff == 0) { return; } $client = $invoice->client; $client->balance = $client->balance + $diff; $client->save(); $activity = Activity::getBlank($invoice); $activity->client_id = $invoice->client_id; $activity->invoice_id = $invoice->id; $activity->activity_type_id = ACTIVITY_TYPE_UPDATE_INVOICE; $activity->message = Utils::encodeActivity(Auth::user(), 'updated', $invoice); $activity->balance = $client->balance; $activity->adjustment = $diff; $activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON(); $activity->save(); */ } } public static function archiveCredit($credit) { if ($credit->is_deleted) { return; } $activity = Activity::getBlank(); $activity->client_id = $credit->client_id; $activity->credit_id = $credit->id; $activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_CREDIT; $activity->message = Utils::encodeActivity(Auth::user(), 'archived '.Utils::formatMoney($credit->balance, $credit->client->getCurrencyId()).' credit'); $activity->balance = $credit->client->balance; $activity->save(); } public static function restoreCredit($credit) { $activity = Activity::getBlank(); $activity->client_id = $credit->client_id; $activity->credit_id = $credit->id; $activity->activity_type_id = ACTIVITY_TYPE_RESTORE_CREDIT; $activity->message = Utils::encodeActivity(Auth::user(), 'restored '.Utils::formatMoney($credit->balance, $credit->client->getCurrencyId()).' credit'); $activity->balance = $credit->client->balance; $activity->save(); } private static function checkSubscriptions($event, $data) { if (!Auth::check()) { return; } $subscription = Auth::user()->account->getSubscription($event); if ($subscription) { Utils::notifyZapier($subscription, $data); } } } <file_sep>/tests/acceptance/ClientCest.php <?php use \AcceptanceTester; use Faker\Factory; use Codeception\Util\Fixtures; class ClientCest { /** * @var \Faker\Generator */ private $faker; public function _before(AcceptanceTester $I) { $I->checkIfLogin($I); $this->faker = Factory::create(); } public function createClient(AcceptanceTester $I) { $I->wantTo('Create a client'); //Organization $I->amOnPage('/clients/create'); $I->fillField(['name' => 'name'], $name = $this->faker->name); $I->fillField(['name' => 'id_number'], rand(0, 10000)); $I->fillField(['name' => 'vat_number'], rand(0, 10000)); $I->fillField(['name' => 'website'], $this->faker->url); $I->fillField(['name' => 'work_phone'], $this->faker->phoneNumber); //Contacts $I->fillField(['name' => 'first_name'], $this->faker->firstName); $I->fillField(['name' => 'last_name'], $this->faker->lastName); $I->fillField(['name' => 'email'], $this->faker->companyEmail); $I->fillField(['name' => 'phone'], $this->faker->phoneNumber); //Additional Contact //$I->click('Add contact +'); //$I->fillField('.form-group:nth-child(6) #first_name', $this->faker->firstName); //$I->fillField('.form-group:nth-child(7) #last_name', $this->faker->lastName); //$I->fillField('.form-group:nth-child(8) #email1', $this->faker->companyEmail); //$I->fillField('.form-group:nth-child(9) #phone', $this->faker->phoneNumber); //Address $I->see('Street'); $I->fillField(['name' => 'address1'], $this->faker->streetAddress); $I->fillField(['name' => 'address2'], $this->faker->streetAddress); $I->fillField(['name' => 'city'], $this->faker->city); $I->fillField(['name' => 'state'], $this->faker->state); $I->fillField(['name' => 'postal_code'], $this->faker->postcode); //$I->executeJS('$(\'input[name="country_id"]\').val('. Helper::getRandom('Country').')'); //Additional Info //$I->selectOption(['name' => 'currency_id'], Helper::getRandom('Currency'));; //$I->selectOption(['name' => 'payment_terms'], Helper::getRandom('PaymentTerm', 'num_days')); //$I->selectOption(['name' => 'size_id'], Helper::getRandom('Size')); //$I->selectOption(['name' => 'industry_id'], Helper::getRandom('Industry')); //$I->fillField(['name' => 'private_notes'], 'Private Notes'); $I->click('Save'); $I->see($name); } public function editClient(AcceptanceTester $I) { $I->wantTo('Edit a client'); //$id = Helper::getRandom('Client', 'public_id'); //$url = sprintf('/clients/%d/edit', $id); $url = '/clients/1/edit'; $I->amOnPage($url); $I->seeCurrentUrlEquals($url); //update fields $name = $this->faker->firstName; $I->fillField(['name' => 'name'], $name); $I->click('Save'); $I->see($name); } /* public function deleteClient(AcceptanceTester $I) { $I->wantTo('delete a client'); $I->amOnPage('/clients'); $I->seeCurrentUrlEquals('/clients'); $I->executeJS(sprintf('deleteEntity(%s)', $id = Helper::getRandom('Client', 'public_id'))); $I->acceptPopup(); //check if client was removed from database $I->wait(5); $I->seeInDatabase('clients', ['public_id' => $id, 'is_deleted' => true]); } */ } <file_sep>/app/Http/Controllers/UserController.php <?php namespace App\Http\Controllers; use Auth; use Config; use Datatable; use DB; use Event; use Input; use View; use Request; use Redirect; use Session; use URL; use Utils; use Validator; use Illuminate\Auth\Passwords\TokenRepositoryInterface; use App\Models\User; use App\Http\Requests; use App\Ninja\Repositories\AccountRepository; use App\Ninja\Mailers\ContactMailer; use App\Ninja\Mailers\UserMailer; class UserController extends BaseController { protected $accountRepo; protected $contactMailer; protected $userMailer; public function __construct(AccountRepository $accountRepo, ContactMailer $contactMailer, UserMailer $userMailer) { parent::__construct(); $this->accountRepo = $accountRepo; $this->contactMailer = $contactMailer; $this->userMailer = $userMailer; } public function getDatatable() { $query = DB::table('users') ->where('users.account_id', '=', Auth::user()->account_id); if (!Session::get('show_trash:user')) { $query->where('users.deleted_at', '=', null); } $query->where('users.public_id', '>', 0) ->select('users.public_id', 'users.first_name', 'users.last_name', 'users.email', 'users.confirmed', 'users.public_id', 'users.deleted_at'); return Datatable::query($query) ->addColumn('first_name', function ($model) { return link_to('users/'.$model->public_id.'/edit', $model->first_name.' '.$model->last_name); }) ->addColumn('email', function ($model) { return $model->email; }) ->addColumn('confirmed', function ($model) { return $model->deleted_at ? trans('texts.deleted') : ($model->confirmed ? trans('texts.active') : trans('texts.pending')); }) ->addColumn('dropdown', function ($model) { $actions = '<div class="btn-group tr-action" style="visibility:hidden;"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> '.trans('texts.select').' <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu">'; if ($model->deleted_at) { $actions .= '<li><a href="'.URL::to('restore_user/'.$model->public_id).'">'.uctrans('texts.restore_user').'</a></li>'; } else { $actions .= '<li><a href="'.URL::to('users/'.$model->public_id).'/edit">'.uctrans('texts.edit_user').'</a></li>'; if (!$model->confirmed) { $actions .= '<li><a href="'.URL::to('send_confirmation/'.$model->public_id).'">'.uctrans('texts.send_invite').'</a></li>'; } $actions .= '<li class="divider"></li> <li><a href="javascript:deleteUser('.$model->public_id.')">'.uctrans('texts.delete_user').'</a></li>'; } $actions .= '</ul> </div>'; return $actions; }) ->orderColumns(['first_name', 'email', 'confirmed']) ->make(); } public function setTheme() { $user = User::find(Auth::user()->id); $user->theme_id = Input::get('theme_id'); $user->save(); return Redirect::to(Input::get('path')); } public function forcePDFJS() { $user = Auth::user(); $user->force_pdfjs = true; $user->save(); Session::flash('message', trans('texts.updated_settings')); return Redirect::to('/dashboard'); } public function edit($publicId) { $user = User::where('account_id', '=', Auth::user()->account_id) ->where('public_id', '=', $publicId)->firstOrFail(); $data = [ 'showBreadcrumbs' => false, 'user' => $user, 'method' => 'PUT', 'url' => 'users/'.$publicId, 'title' => trans('texts.edit_user'), ]; return View::make('users.edit', $data); } public function update($publicId) { return $this->save($publicId); } public function store() { return $this->save(); } /** * Displays the form for account creation * */ public function create() { if (!Auth::user()->registered) { Session::flash('error', trans('texts.register_to_add_user')); return Redirect::to('company/advanced_settings/user_management'); } if (!Auth::user()->confirmed) { Session::flash('error', trans('texts.confirmation_required')); return Redirect::to('company/advanced_settings/user_management'); } if (Utils::isNinja()) { $count = User::where('account_id', '=', Auth::user()->account_id)->count(); if ($count >= MAX_NUM_USERS) { Session::flash('error', trans('texts.limit_users')); return Redirect::to('company/advanced_settings/user_management'); } } $data = [ 'showBreadcrumbs' => false, 'user' => null, 'method' => 'POST', 'url' => 'users', 'title' => trans('texts.add_user'), ]; return View::make('users.edit', $data); } public function delete() { $userPublicId = Input::get('userPublicId'); $user = User::where('account_id', '=', Auth::user()->account_id) ->where('public_id', '=', $userPublicId)->firstOrFail(); $user->delete(); Session::flash('message', trans('texts.deleted_user')); return Redirect::to('company/advanced_settings/user_management'); } public function restoreUser($userPublicId) { $user = User::where('account_id', '=', Auth::user()->account_id) ->where('public_id', '=', $userPublicId) ->withTrashed()->firstOrFail(); $user->restore(); Session::flash('message', trans('texts.restored_user')); return Redirect::to('company/advanced_settings/user_management'); } /** * Stores new account * */ public function save($userPublicId = false) { if (Auth::user()->account->isPro()) { $rules = [ 'first_name' => 'required', 'last_name' => 'required', ]; if ($userPublicId) { $user = User::where('account_id', '=', Auth::user()->account_id) ->where('public_id', '=', $userPublicId)->firstOrFail(); $rules['email'] = 'required|email|unique:users,email,'.$user->id.',id'; } else { $rules['email'] = 'required|email|unique:users'; } $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return Redirect::to($userPublicId ? 'users/edit' : 'users/create')->withInput()->withErrors($validator); } if ($userPublicId) { $user->first_name = trim(Input::get('first_name')); $user->last_name = trim(Input::get('last_name')); $user->username = trim(Input::get('email')); $user->email = trim(Input::get('email')); } else { $lastUser = User::withTrashed()->where('account_id', '=', Auth::user()->account_id) ->orderBy('public_id', 'DESC')->first(); $user = new User(); $user->account_id = Auth::user()->account_id; $user->first_name = trim(Input::get('first_name')); $user->last_name = trim(Input::get('last_name')); $user->username = trim(Input::get('email')); $user->email = trim(Input::get('email')); $user->registered = true; $user->password = str_random(RANDOM_KEY_LENGTH); $user->confirmation_code = str_random(RANDOM_KEY_LENGTH); $user->public_id = $lastUser->public_id + 1; } $user->save(); if (!$user->confirmed) { $this->userMailer->sendConfirmation($user, Auth::user()); $message = trans('texts.sent_invite'); } else { $message = trans('texts.updated_user'); } Session::flash('message', $message); } return Redirect::to('company/advanced_settings/user_management'); } public function sendConfirmation($userPublicId) { $user = User::where('account_id', '=', Auth::user()->account_id) ->where('public_id', '=', $userPublicId)->firstOrFail(); $this->userMailer->sendConfirmation($user, Auth::user()); Session::flash('message', trans('texts.sent_invite')); return Redirect::to('company/advanced_settings/user_management'); } /** * Attempt to confirm account with code * * @param string $code */ public function confirm($code, TokenRepositoryInterface $tokenRepo) { $user = User::where('confirmation_code', '=', $code)->get()->first(); if ($user) { $notice_msg = trans('texts.security.confirmation'); $user->confirmed = true; $user->confirmation_code = ''; $user->save(); if ($user->public_id) { //Auth::login($user); $token = $tokenRepo->create($user); return Redirect::to("/password/reset/{$token}"); } else { if (Session::has(REQUESTED_PRO_PLAN)) { Session::forget(REQUESTED_PRO_PLAN); $invitation = $this->accountRepo->enableProPlan(); return Redirect::to($invitation->getLink()); } else { return Redirect::to(Auth::check() ? '/dashboard' : '/login')->with('message', $notice_msg); } } } else { $error_msg = trans('texts.security.wrong_confirmation'); return Redirect::to('/login')->with('error', $error_msg); } } /** * Log the user out of the application. * */ /* public function logout() { if (Auth::check()) { if (!Auth::user()->registered) { $account = Auth::user()->account; $this->accountRepo->unlinkAccount($account); $account->forceDelete(); } } Auth::logout(); Session::flush(); return Redirect::to('/')->with('clearGuestKey', true); } */ public function changePassword() { // check the current password is correct if (!Auth::validate([ 'email' => Auth::user()->email, 'password' => Input::get('current_password') ])) { return trans('texts.password_error_incorrect'); } // validate the new password $password = Input::get('new_password'); $confirm = Input::get('confirm_password'); if (strlen($password) < 6 || $password != $confirm) { return trans('texts.password_error_invalid'); } // save the new password $user = Auth::user(); $user->password = <PASSWORD>($password); $user->save(); return RESULT_SUCCESS; } public function switchAccount($newUserId) { $oldUserId = Auth::user()->id; $referer = Request::header('referer'); $account = $this->accountRepo->findUserAccounts($newUserId, $oldUserId); if ($account) { if ($account->hasUserId($newUserId) && $account->hasUserId($oldUserId)) { Auth::loginUsingId($newUserId); Auth::user()->account->loadLocalizationSettings(); // regenerate token to prevent open pages // from saving under the wrong account Session::put('_token', str_random(40)); } } return Redirect::to($referer); } public function unlinkAccount($userAccountId, $userId) { $this->accountRepo->unlinkUser($userAccountId, $userId); $referer = Request::header('referer'); $users = $this->accountRepo->loadAccounts(Auth::user()->id); Session::put(SESSION_USER_ACCOUNTS, $users); Session::flash('message', trans('texts.unlinked_account')); return Redirect::to('/dashboard'); } public function manageCompanies() { return View::make('users.account_management'); } } <file_sep>/app/Http/Middleware/DuplicateSubmissionCheck.php <?php namespace app\Http\Middleware; use Closure; class DuplicateSubmissionCheck { // Prevent users from submitting forms twice public function handle($request, Closure $next) { $path = $request->path(); if (strpos($path, 'charts_and_reports') !== false) { return $next($request); } if (in_array($request->method(), ['POST', 'PUT', 'DELETE'])) { $lastPage = session(SESSION_LAST_REQUEST_PAGE); $lastTime = session(SESSION_LAST_REQUEST_TIME); if ($lastPage == $path && (microtime(true) - $lastTime <= 1)) { return redirect('/')->with('warning', trans('texts.duplicate_post')); } session([SESSION_LAST_REQUEST_PAGE => $request->path()]); session([SESSION_LAST_REQUEST_TIME => microtime(true)]); } return $next($request); } }<file_sep>/app/Http/routes.php <?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ //Cache::flush(); //apc_clear_cache(); //dd(DB::getQueryLog()); //dd(Client::getPrivateId(1)); //dd(new DateTime()); //dd(App::environment()); //dd(gethostname()); //Log::error('test'); // Application setup Route::get('setup', 'AppController@showSetup'); Route::post('setup', 'AppController@doSetup'); Route::get('install', 'AppController@install'); Route::get('update', 'AppController@update'); /* // Codeception code coverage Route::get('/c3.php', function () { include '../c3.php'; }); */ // Public pages Route::get('/', 'HomeController@showIndex'); Route::get('terms', 'HomeController@showTerms'); Route::get('log_error', 'HomeController@logError'); Route::get('invoice_now', 'HomeController@invoiceNow'); Route::get('keep_alive', 'HomeController@keepAlive'); Route::post('get_started', 'AccountController@getStarted'); // Client visible pages Route::get('view/{invitation_key}', 'InvoiceController@view'); Route::get('approve/{invitation_key}', 'QuoteController@approve'); Route::get('payment/{invitation_key}/{payment_type?}', 'PaymentController@show_payment'); Route::post('payment/{invitation_key}', 'PaymentController@do_payment'); Route::get('complete', 'PaymentController@offsite_payment'); Route::get('client/quotes', 'QuoteController@clientIndex'); Route::get('client/invoices', 'InvoiceController@clientIndex'); Route::get('client/payments', 'PaymentController@clientIndex'); Route::get('api/client.quotes', array('as'=>'api.client.quotes', 'uses'=>'QuoteController@getClientDatatable')); Route::get('api/client.invoices', array('as'=>'api.client.invoices', 'uses'=>'InvoiceController@getClientDatatable')); Route::get('api/client.payments', array('as'=>'api.client.payments', 'uses'=>'PaymentController@getClientDatatable')); Route::get('license', 'PaymentController@show_license_payment'); Route::post('license', 'PaymentController@do_license_payment'); Route::get('claim_license', 'PaymentController@claim_license'); Route::post('signup/validate', 'AccountController@checkEmail'); Route::post('signup/submit', 'AccountController@submitSignup'); // Laravel auth routes /* Route::controllers([ 'auth' => 'Auth\AuthController', 'password' => '<PASSWORD>', ]); */ get('/signup', array('as' => 'signup', 'uses' => 'Auth\AuthController@getRegister')); post('/signup', array('as' => 'signup', 'uses' => 'Auth\AuthController@postRegister')); get('/login', array('as' => 'login', 'uses' => 'Auth\AuthController@getLoginWrapper')); post('/login', array('as' => 'login', 'uses' => 'Auth\AuthController@postLoginWrapper')); get('/logout', array('as' => 'logout', 'uses' => 'Auth\AuthController@getLogoutWrapper')); get('/forgot', array('as' => 'forgot', 'uses' => 'Auth\PasswordController@getEmail')); post('/forgot', array('as' => 'forgot', 'uses' => 'Auth\PasswordController@postEmail')); get('/password/reset/{token}', array('as' => 'forgot', 'uses' => 'Auth\PasswordController@getReset')); post('/password/reset', array('as' => 'forgot', 'uses' => 'Auth\PasswordController@postReset')); get('/user/confirm/{code}', 'UserController@confirm'); if (Utils::isNinja()) { Route::post('/signup/register', 'AccountController@doRegister'); Route::get('/news_feed/{user_type}/{version}/', 'HomeController@newsFeed'); Route::get('/demo', 'AccountController@demo'); } Route::group(['middleware' => 'auth'], function() { Route::get('dashboard', 'DashboardController@index'); Route::get('view_archive/{entity_type}/{visible}', 'AccountController@setTrashVisible'); Route::get('hide_message', 'HomeController@hideMessage'); Route::get('force_inline_pdf', 'UserController@forcePDFJS'); Route::get('api/users', array('as'=>'api.users', 'uses'=>'UserController@getDatatable')); Route::resource('users', 'UserController'); Route::post('users/delete', 'UserController@delete'); Route::get('send_confirmation/{user_id}', 'UserController@sendConfirmation'); Route::get('restore_user/{user_id}', 'UserController@restoreUser'); Route::post('users/change_password', 'UserController@changePassword'); Route::get('/switch_account/{user_id}', 'UserController@switchAccount'); Route::get('/unlink_account/{user_account_id}/{user_id}', 'UserController@unlinkAccount'); Route::get('/manage_companies', 'UserController@manageCompanies'); Route::get('api/tokens', array('as'=>'api.tokens', 'uses'=>'TokenController@getDatatable')); Route::resource('tokens', 'TokenController'); Route::post('tokens/delete', 'TokenController@delete'); Route::get('api/products', array('as'=>'api.products', 'uses'=>'ProductController@getDatatable')); Route::resource('products', 'ProductController'); Route::get('products/{product_id}/archive', 'ProductController@archive'); Route::get('company/advanced_settings/data_visualizations', 'ReportController@d3'); Route::get('company/advanced_settings/charts_and_reports', 'ReportController@showReports'); Route::post('company/advanced_settings/charts_and_reports', 'ReportController@showReports'); Route::post('company/cancel_account', 'AccountController@cancelAccount'); Route::get('account/getSearchData', array('as' => 'getSearchData', 'uses' => 'AccountController@getSearchData')); Route::get('company/{section?}/{sub_section?}', 'AccountController@showSection'); Route::post('company/{section?}/{sub_section?}', 'AccountController@doSection'); Route::post('user/setTheme', 'UserController@setTheme'); Route::post('remove_logo', 'AccountController@removeLogo'); Route::post('account/go_pro', 'AccountController@enableProPlan'); Route::resource('gateways', 'AccountGatewayController'); Route::get('api/gateways', array('as'=>'api.gateways', 'uses'=>'AccountGatewayController@getDatatable')); Route::post('gateways/delete', 'AccountGatewayController@delete'); Route::resource('clients', 'ClientController'); Route::get('api/clients', array('as'=>'api.clients', 'uses'=>'ClientController@getDatatable')); Route::get('api/activities/{client_id?}', array('as'=>'api.activities', 'uses'=>'ActivityController@getDatatable')); Route::post('clients/bulk', 'ClientController@bulk'); Route::resource('tasks', 'TaskController'); Route::get('api/tasks/{client_id?}', array('as'=>'api.tasks', 'uses'=>'TaskController@getDatatable')); Route::get('tasks/create/{client_id?}', 'TaskController@create'); Route::post('tasks/bulk', 'TaskController@bulk'); Route::get('api/recurring_invoices/{client_id?}', array('as'=>'api.recurring_invoices', 'uses'=>'InvoiceController@getRecurringDatatable')); Route::get('invoices/invoice_history/{invoice_id}', 'InvoiceController@invoiceHistory'); Route::get('quotes/quote_history/{invoice_id}', 'InvoiceController@invoiceHistory'); Route::resource('invoices', 'InvoiceController'); Route::get('api/invoices/{client_id?}', array('as'=>'api.invoices', 'uses'=>'InvoiceController@getDatatable')); Route::get('invoices/create/{client_id?}', 'InvoiceController@create'); Route::get('recurring_invoices/create/{client_id?}', 'InvoiceController@createRecurring'); Route::get('invoices/{public_id}/clone', 'InvoiceController@cloneInvoice'); Route::post('invoices/bulk', 'InvoiceController@bulk'); Route::get('quotes/create/{client_id?}', 'QuoteController@create'); Route::get('quotes/{public_id}/clone', 'InvoiceController@cloneInvoice'); Route::get('quotes/{public_id}/edit', 'InvoiceController@edit'); Route::put('quotes/{public_id}', 'InvoiceController@update'); Route::get('quotes/{public_id}', 'InvoiceController@edit'); Route::post('quotes', 'InvoiceController@store'); Route::get('quotes', 'QuoteController@index'); Route::get('api/quotes/{client_id?}', array('as'=>'api.quotes', 'uses'=>'QuoteController@getDatatable')); Route::post('quotes/bulk', 'QuoteController@bulk'); Route::resource('payments', 'PaymentController'); Route::get('payments/create/{client_id?}/{invoice_id?}', 'PaymentController@create'); Route::get('api/payments/{client_id?}', array('as'=>'api.payments', 'uses'=>'PaymentController@getDatatable')); Route::post('payments/bulk', 'PaymentController@bulk'); Route::get('credits/{id}/edit', function() { return View::make('header'); }); Route::resource('credits', 'CreditController'); Route::get('credits/create/{client_id?}/{invoice_id?}', 'CreditController@create'); Route::get('api/credits/{client_id?}', array('as'=>'api.credits', 'uses'=>'CreditController@getDatatable')); Route::post('credits/bulk', 'CreditController@bulk'); get('/resend_confirmation', 'AccountController@resendConfirmation'); //Route::resource('timesheets', 'TimesheetController'); }); // Route group for API Route::group(['middleware' => 'api', 'prefix' => 'api/v1'], function() { Route::resource('ping', 'ClientApiController@ping'); Route::resource('clients', 'ClientApiController'); Route::resource('invoices', 'InvoiceApiController'); Route::resource('quotes', 'QuoteApiController'); Route::resource('payments', 'PaymentApiController'); Route::post('hooks', 'IntegrationController@subscribe'); Route::post('email_invoice', 'InvoiceApiController@emailInvoice'); }); // Redirects for legacy links Route::get('/rocksteady', function() { return Redirect::to(NINJA_WEB_URL, 301); }); Route::get('/about', function() { return Redirect::to(NINJA_WEB_URL, 301); }); Route::get('/contact', function() { return Redirect::to(NINJA_WEB_URL.'/contact', 301); }); Route::get('/plans', function() { return Redirect::to(NINJA_WEB_URL.'/pricing', 301); }); Route::get('/faq', function() { return Redirect::to(NINJA_WEB_URL.'/how-it-works', 301); }); Route::get('/features', function() { return Redirect::to(NINJA_WEB_URL.'/features', 301); }); Route::get('/testimonials', function() { return Redirect::to(NINJA_WEB_URL, 301); }); Route::get('/compare-online-invoicing{sites?}', function() { return Redirect::to(NINJA_WEB_URL, 301); }); Route::get('/forgot_password', function() { return Redirect::to(NINJA_APP_URL.'/forgot', 301); }); define('CONTACT_EMAIL', Config::get('mail.from.address')); define('CONTACT_NAME', Config::get('mail.from.name')); define('SITE_URL', Config::get('app.url')); define('ENV_DEVELOPMENT', 'local'); define('ENV_STAGING', 'staging'); define('ENV_PRODUCTION', 'fortrabbit'); define('RECENTLY_VIEWED', 'RECENTLY_VIEWED'); define('ENTITY_CLIENT', 'client'); define('ENTITY_INVOICE', 'invoice'); define('ENTITY_RECURRING_INVOICE', 'recurring_invoice'); define('ENTITY_PAYMENT', 'payment'); define('ENTITY_CREDIT', 'credit'); define('ENTITY_QUOTE', 'quote'); define('ENTITY_TASK', 'task'); define('PERSON_CONTACT', 'contact'); define('PERSON_USER', 'user'); define('ACCOUNT_DETAILS', 'details'); define('ACCOUNT_NOTIFICATIONS', 'notifications'); define('ACCOUNT_IMPORT_EXPORT', 'import_export'); define('ACCOUNT_PAYMENTS', 'payments'); define('ACCOUNT_MAP', 'import_map'); define('ACCOUNT_EXPORT', 'export'); define('ACCOUNT_PRODUCTS', 'products'); define('ACCOUNT_ADVANCED_SETTINGS', 'advanced_settings'); define('ACCOUNT_INVOICE_SETTINGS', 'invoice_settings'); define('ACCOUNT_INVOICE_DESIGN', 'invoice_design'); define('ACCOUNT_CHART_BUILDER', 'chart_builder'); define('ACCOUNT_USER_MANAGEMENT', 'user_management'); define('ACCOUNT_DATA_VISUALIZATIONS', 'data_visualizations'); define('ACCOUNT_EMAIL_TEMPLATES', 'email_templates'); define('ACCOUNT_TOKEN_MANAGEMENT', 'token_management'); define('ACCOUNT_CUSTOMIZE_DESIGN', 'customize_design'); define('ACTIVITY_TYPE_CREATE_CLIENT', 1); define('ACTIVITY_TYPE_ARCHIVE_CLIENT', 2); define('ACTIVITY_TYPE_DELETE_CLIENT', 3); define('ACTIVITY_TYPE_CREATE_INVOICE', 4); define('ACTIVITY_TYPE_UPDATE_INVOICE', 5); define('ACTIVITY_TYPE_EMAIL_INVOICE', 6); define('ACTIVITY_TYPE_VIEW_INVOICE', 7); define('ACTIVITY_TYPE_ARCHIVE_INVOICE', 8); define('ACTIVITY_TYPE_DELETE_INVOICE', 9); define('ACTIVITY_TYPE_CREATE_PAYMENT', 10); define('ACTIVITY_TYPE_UPDATE_PAYMENT', 11); define('ACTIVITY_TYPE_ARCHIVE_PAYMENT', 12); define('ACTIVITY_TYPE_DELETE_PAYMENT', 13); define('ACTIVITY_TYPE_CREATE_CREDIT', 14); define('ACTIVITY_TYPE_UPDATE_CREDIT', 15); define('ACTIVITY_TYPE_ARCHIVE_CREDIT', 16); define('ACTIVITY_TYPE_DELETE_CREDIT', 17); define('ACTIVITY_TYPE_CREATE_QUOTE', 18); define('ACTIVITY_TYPE_UPDATE_QUOTE', 19); define('ACTIVITY_TYPE_EMAIL_QUOTE', 20); define('ACTIVITY_TYPE_VIEW_QUOTE', 21); define('ACTIVITY_TYPE_ARCHIVE_QUOTE', 22); define('ACTIVITY_TYPE_DELETE_QUOTE', 23); define('ACTIVITY_TYPE_RESTORE_QUOTE', 24); define('ACTIVITY_TYPE_RESTORE_INVOICE', 25); define('ACTIVITY_TYPE_RESTORE_CLIENT', 26); define('ACTIVITY_TYPE_RESTORE_PAYMENT', 27); define('ACTIVITY_TYPE_RESTORE_CREDIT', 28); define('ACTIVITY_TYPE_APPROVE_QUOTE', 29); define('DEFAULT_INVOICE_NUMBER', '0001'); define('RECENTLY_VIEWED_LIMIT', 8); define('LOGGED_ERROR_LIMIT', 100); define('RANDOM_KEY_LENGTH', 32); define('MAX_NUM_CLIENTS', 500); define('MAX_NUM_CLIENTS_PRO', 20000); define('MAX_NUM_USERS', 20); define('MAX_SUBDOMAIN_LENGTH', 30); define('DEFAULT_FONT_SIZE', 9); define('INVOICE_STATUS_DRAFT', 1); define('INVOICE_STATUS_SENT', 2); define('INVOICE_STATUS_VIEWED', 3); define('INVOICE_STATUS_PARTIAL', 4); define('INVOICE_STATUS_PAID', 5); define('PAYMENT_TYPE_CREDIT', 1); define('CUSTOM_DESIGN', 11); define('FREQUENCY_WEEKLY', 1); define('FREQUENCY_TWO_WEEKS', 2); define('FREQUENCY_FOUR_WEEKS', 3); define('FREQUENCY_MONTHLY', 4); define('FREQUENCY_THREE_MONTHS', 5); define('FREQUENCY_SIX_MONTHS', 6); define('FREQUENCY_ANNUALLY', 7); define('SESSION_TIMEZONE', 'timezone'); define('SESSION_CURRENCY', 'currency'); define('SESSION_DATE_FORMAT', 'dateFormat'); define('SESSION_DATE_PICKER_FORMAT', 'datePickerFormat'); define('SESSION_DATETIME_FORMAT', 'datetimeFormat'); define('SESSION_COUNTER', 'sessionCounter'); define('SESSION_LOCALE', 'sessionLocale'); define('SESSION_USER_ACCOUNTS', 'userAccounts'); define('SESSION_LAST_REQUEST_PAGE', 'SESSION_LAST_REQUEST_PAGE'); define('SESSION_LAST_REQUEST_TIME', 'SESSION_LAST_REQUEST_TIME'); define('DEFAULT_TIMEZONE', 'US/Eastern'); define('DEFAULT_CURRENCY', 1); // US Dollar define('DEFAULT_LANGUAGE', 1); // English define('DEFAULT_DATE_FORMAT', 'M j, Y'); define('DEFAULT_DATE_PICKER_FORMAT', 'M d, yyyy'); define('DEFAULT_DATETIME_FORMAT', 'F j, Y, g:i a'); define('DEFAULT_QUERY_CACHE', 120); // minutes define('DEFAULT_LOCALE', 'en'); define('RESULT_SUCCESS', 'success'); define('RESULT_FAILURE', 'failure'); define('PAYMENT_LIBRARY_OMNIPAY', 1); define('PAYMENT_LIBRARY_PHP_PAYMENTS', 2); define('GATEWAY_AUTHORIZE_NET', 1); define('GATEWAY_AUTHORIZE_NET_SIM', 2); define('GATEWAY_PAYPAL_EXPRESS', 17); define('GATEWAY_PAYPAL_PRO', 18); define('GATEWAY_STRIPE', 23); define('GATEWAY_TWO_CHECKOUT', 27); define('GATEWAY_BEANSTREAM', 29); define('GATEWAY_PSIGATE', 30); define('GATEWAY_MOOLAH', 31); define('GATEWAY_BITPAY', 42); define('GATEWAY_DWOLLA', 43); define('EVENT_CREATE_CLIENT', 1); define('EVENT_CREATE_INVOICE', 2); define('EVENT_CREATE_QUOTE', 3); define('EVENT_CREATE_PAYMENT', 4); define('REQUESTED_PRO_PLAN', 'REQUESTED_PRO_PLAN'); define('DEMO_ACCOUNT_ID', 'DEMO_ACCOUNT_ID'); define('PREV_USER_ID', 'PREV_USER_ID'); define('NINJA_ACCOUNT_KEY', '<KEY>'); define('NINJA_GATEWAY_ID', GATEWAY_STRIPE); define('NINJA_GATEWAY_CONFIG', ''); define('NINJA_WEB_URL', 'https://www.invoiceninja.com'); define('NINJA_APP_URL', 'https://app.invoiceninja.com'); define('NINJA_VERSION', '2.3.3'); define('NINJA_DATE', '2000-01-01'); define('NINJA_FROM_EMAIL', '<EMAIL>'); define('RELEASES_URL', 'https://github.com/hillelcoren/invoice-ninja/releases/'); define('ZAPIER_URL', 'https://zapier.com/developer/invite/11276/85cf0ee4beae8e802c6c579eb4e351f1/'); define('OUTDATE_BROWSER_URL', 'http://browsehappy.com/'); define('PDFMAKE_DOCS', 'http://pdfmake.org/playground.html'); define('COUNT_FREE_DESIGNS', 4); define('COUNT_FREE_DESIGNS_SELF_HOST', 5); // include the custom design define('PRODUCT_ONE_CLICK_INSTALL', 1); define('PRODUCT_INVOICE_DESIGNS', 2); define('PRODUCT_WHITE_LABEL', 3); define('PRODUCT_SELF_HOST', 4); define('WHITE_LABEL_AFFILIATE_KEY', '92D2J5'); define('INVOICE_DESIGNS_AFFILIATE_KEY', 'T3RS74'); define('SELF_HOST_AFFILIATE_KEY', '8S69AD'); define('PRO_PLAN_PRICE', 50); define('WHITE_LABEL_PRICE', 20); define('INVOICE_DESIGNS_PRICE', 10); define('USER_TYPE_SELF_HOST', 'SELF_HOST'); define('USER_TYPE_CLOUD_HOST', 'CLOUD_HOST'); define('NEW_VERSION_AVAILABLE', 'NEW_VERSION_AVAILABLE'); define('TEST_USERNAME', '<EMAIL>'); define('TEST_PASSWORD', '<PASSWORD>'); define('TOKEN_BILLING_DISABLED', 1); define('TOKEN_BILLING_OPT_IN', 2); define('TOKEN_BILLING_OPT_OUT', 3); define('TOKEN_BILLING_ALWAYS', 4); define('PAYMENT_TYPE_PAYPAL', 'PAYMENT_TYPE_PAYPAL'); define('PAYMENT_TYPE_CREDIT_CARD', 'PAYMENT_TYPE_CREDIT_CARD'); define('PAYMENT_TYPE_BITCOIN', 'PAYMENT_TYPE_BITCOIN'); define('PAYMENT_TYPE_DWOLLA', 'PAYMENT_TYPE_DWOLLA'); define('PAYMENT_TYPE_TOKEN', 'PAYMENT_TYPE_TOKEN'); define('PAYMENT_TYPE_ANY', 'PAYMENT_TYPE_ANY'); $creditCards = [ 1 => ['card' => 'images/credit_cards/Test-Visa-Icon.png', 'text' => 'Visa'], 2 => ['card' => 'images/credit_cards/Test-MasterCard-Icon.png', 'text' => 'Master Card'], 4 => ['card' => 'images/credit_cards/Test-AmericanExpress-Icon.png', 'text' => 'American Express'], 8 => ['card' => 'images/credit_cards/Test-Diners-Icon.png', 'text' => 'Diners'], 16 => ['card' => 'images/credit_cards/Test-Discover-Icon.png', 'text' => 'Discover'] ]; define('CREDIT_CARDS', serialize($creditCards)); function uctrans($text) { return ucwords(trans($text)); } // optional trans: only return the string if it's translated function otrans($text) { $locale = Session::get(SESSION_LOCALE); if ($locale == 'en') { return trans($text); } else { $string = trans($text); $english = trans($text, [], 'en'); return $string != $english ? $string : ''; } } /* // Log all SQL queries to laravel.log Event::listen('illuminate.query', function($query, $bindings, $time, $name) { $data = compact('bindings', 'time', 'name'); // Format binding data for sql insertion foreach ($bindings as $i => $binding) { if ($binding instanceof \DateTime) { $bindings[$i] = $binding->format('\'Y-m-d H:i:s\''); } else if (is_string($binding)) { $bindings[$i] = "'$binding'"; } } // Insert bindings into query $query = str_replace(array('%', '?'), array('%%', '%s'), $query); $query = vsprintf($query, $bindings); Log::info($query, $data); }); */ /* if (Auth::check() && Auth::user()->id === 1) { Auth::loginUsingId(1); } */<file_sep>/app/Console/Commands/CheckData.php <?php namespace App\Console\Commands; use DB; use DateTime; use Carbon; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; /* ################################################################## WARNING: Please backup your database before running this script ################################################################## Since the application was released a number of bugs have inevitably been found. Although the bugs have always been fixed in some cases they've caused the client's balance, paid to date and/or activity records to become inaccurate. This script will check for errors and correct the data. If you have any questions please email us at <EMAIL> Usage: php artisan ninja:check-data Options: --client_id:<value> Limits the script to a single client --fix=true By default the script only checks for errors, adding this option makes the script apply the fixes. */ class CheckData extends Command { protected $name = 'ninja:check-data'; protected $description = 'Check/fix data'; public function fire() { $this->info(date('Y-m-d') . ' Running CheckData...'); $today = new DateTime(); if (!$this->option('client_id')) { // update client paid_to_date value $clients = DB::table('clients') ->join('payments', 'payments.client_id', '=', 'clients.id') ->join('invoices', 'invoices.id', '=', 'payments.invoice_id') ->where('payments.is_deleted', '=', 0) ->where('invoices.is_deleted', '=', 0) ->groupBy('clients.id') ->havingRaw('clients.paid_to_date != sum(payments.amount) and clients.paid_to_date != 999999999.9999') ->get(['clients.id', 'clients.paid_to_date', DB::raw('sum(payments.amount) as amount')]); $this->info(count($clients) . ' clients with incorrect paid to date'); if ($this->option('fix') == 'true') { foreach ($clients as $client) { DB::table('clients') ->where('id', $client->id) ->update(['paid_to_date' => $client->amount]); } } } // find all clients where the balance doesn't equal the sum of the outstanding invoices $clients = DB::table('clients') ->join('invoices', 'invoices.client_id', '=', 'clients.id') ->join('accounts', 'accounts.id', '=', 'clients.account_id'); if ($this->option('client_id')) { $clients->where('clients.id', '=', $this->option('client_id')); } else { $clients->where('invoices.is_deleted', '=', 0) ->where('invoices.is_quote', '=', 0) ->where('invoices.is_recurring', '=', 0) ->havingRaw('abs(clients.balance - sum(invoices.balance)) > .01 and clients.balance != 999999999.9999'); } $clients = $clients->groupBy('clients.id', 'clients.balance', 'clients.created_at') ->orderBy('clients.id', 'DESC') ->get(['clients.account_id', 'clients.id', 'clients.balance', 'clients.paid_to_date', DB::raw('sum(invoices.balance) actual_balance')]); $this->info(count($clients) . ' clients with incorrect balance/activities'); foreach ($clients as $client) { $this->info("=== Client:{$client->id} Balance:{$client->balance} Actual Balance:{$client->actual_balance} ==="); $foundProblem = false; $lastBalance = 0; $lastAdjustment = 0; $lastCreatedAt = null; $clientFix = false; $activities = DB::table('activities') ->where('client_id', '=', $client->id) ->orderBy('activities.id') ->get(['activities.id', 'activities.created_at', 'activities.activity_type_id', 'activities.message', 'activities.adjustment', 'activities.balance', 'activities.invoice_id']); //$this->info(var_dump($activities)); foreach ($activities as $activity) { $activityFix = false; if ($activity->invoice_id) { $invoice = DB::table('invoices') ->where('id', '=', $activity->invoice_id) ->first(['invoices.amount', 'invoices.is_recurring', 'invoices.is_quote', 'invoices.deleted_at', 'invoices.id', 'invoices.is_deleted']); // Check if this invoice was once set as recurring invoice if (!$invoice->is_recurring && DB::table('invoices') ->where('recurring_invoice_id', '=', $activity->invoice_id) ->first(['invoices.id'])) { $invoice->is_recurring = 1; // **Fix for enabling a recurring invoice to be set as non-recurring** if ($this->option('fix') == 'true') { DB::table('invoices') ->where('id', $invoice->id) ->update(['is_recurring' => 1]); } } } if ($activity->activity_type_id == ACTIVITY_TYPE_CREATE_INVOICE || $activity->activity_type_id == ACTIVITY_TYPE_CREATE_QUOTE) { // Get original invoice amount $update = DB::table('activities') ->where('invoice_id', '=', $activity->invoice_id) ->where('activity_type_id', '=', ACTIVITY_TYPE_UPDATE_INVOICE) ->orderBy('id') ->first(['json_backup']); if ($update) { $backup = json_decode($update->json_backup); $invoice->amount = floatval($backup->amount); } $noAdjustment = $activity->activity_type_id == ACTIVITY_TYPE_CREATE_INVOICE && $activity->adjustment == 0 && $invoice->amount > 0; // **Fix for allowing converting a recurring invoice to a normal one without updating the balance** if ($noAdjustment && !$invoice->is_quote && !$invoice->is_recurring) { $this->info("No adjustment for new invoice:{$activity->invoice_id} amount:{$invoice->amount} isQuote:{$invoice->is_quote} isRecurring:{$invoice->is_recurring}"); $foundProblem = true; $clientFix += $invoice->amount; $activityFix = $invoice->amount; // **Fix for updating balance when creating a quote or recurring invoice** } elseif ($activity->adjustment != 0 && ($invoice->is_quote || $invoice->is_recurring)) { $this->info("Incorrect adjustment for new invoice:{$activity->invoice_id} adjustment:{$activity->adjustment} isQuote:{$invoice->is_quote} isRecurring:{$invoice->is_recurring}"); $foundProblem = true; $clientFix -= $activity->adjustment; $activityFix = 0; } } elseif ($activity->activity_type_id == ACTIVITY_TYPE_DELETE_INVOICE) { // **Fix for updating balance when deleting a recurring invoice** if ($activity->adjustment != 0 && $invoice->is_recurring) { $this->info("Incorrect adjustment for deleted invoice adjustment:{$activity->adjustment}"); $foundProblem = true; if ($activity->balance != $lastBalance) { $clientFix -= $activity->adjustment; } $activityFix = 0; } } elseif ($activity->activity_type_id == ACTIVITY_TYPE_ARCHIVE_INVOICE) { // **Fix for updating balance when archiving an invoice** if ($activity->adjustment != 0 && !$invoice->is_recurring) { $this->info("Incorrect adjustment for archiving invoice adjustment:{$activity->adjustment}"); $foundProblem = true; $activityFix = 0; $clientFix += $activity->adjustment; } } elseif ($activity->activity_type_id == ACTIVITY_TYPE_UPDATE_INVOICE) { // **Fix for updating balance when updating recurring invoice** if ($activity->adjustment != 0 && $invoice->is_recurring) { $this->info("Incorrect adjustment for updated recurring invoice adjustment:{$activity->adjustment}"); $foundProblem = true; $clientFix -= $activity->adjustment; $activityFix = 0; } else if ((strtotime($activity->created_at) - strtotime($lastCreatedAt) <= 1) && $activity->adjustment > 0 && $activity->adjustment == $lastAdjustment) { $this->info("Duplicate adjustment for updated invoice adjustment:{$activity->adjustment}"); $foundProblem = true; $clientFix -= $activity->adjustment; $activityFix = 0; } } elseif ($activity->activity_type_id == ACTIVITY_TYPE_UPDATE_QUOTE) { // **Fix for updating balance when updating a quote** if ($activity->balance != $lastBalance) { $this->info("Incorrect adjustment for updated quote adjustment:{$activity->adjustment}"); $foundProblem = true; $clientFix += $lastBalance - $activity->balance; $activityFix = 0; } } else if ($activity->activity_type_id == ACTIVITY_TYPE_DELETE_PAYMENT) { // **Fix for delting payment after deleting invoice** if ($activity->adjustment != 0 && $invoice->is_deleted && $activity->created_at > $invoice->deleted_at) { $this->info("Incorrect adjustment for deleted payment adjustment:{$activity->adjustment}"); $foundProblem = true; $activityFix = 0; $clientFix -= $activity->adjustment; } } if ($activityFix !== false || $clientFix !== false) { $data = [ 'balance' => $activity->balance + $clientFix ]; if ($activityFix !== false) { $data['adjustment'] = $activityFix; } if ($this->option('fix') == 'true') { DB::table('activities') ->where('id', $activity->id) ->update($data); } } $lastBalance = $activity->balance; $lastAdjustment = $activity->adjustment; $lastCreatedAt = $activity->created_at; } if ($activity->balance + $clientFix != $client->actual_balance) { $this->info("** Creating 'recovered update' activity **"); if ($this->option('fix') == 'true') { DB::table('activities')->insert([ 'created_at' => new Carbon, 'updated_at' => new Carbon, 'account_id' => $client->account_id, 'client_id' => $client->id, 'message' => 'Recovered update to invoice [<a href="https://github.com/hillelcoren/invoice-ninja/releases/tag/v1.7.1" target="_blank">details</a>]', 'adjustment' => $client->actual_balance - $activity->balance, 'balance' => $client->actual_balance, ]); } } $data = ['balance' => $client->actual_balance]; $this->info("Corrected balance:{$client->actual_balance}"); if ($this->option('fix') == 'true') { DB::table('clients') ->where('id', $client->id) ->update($data); } } $this->info('Done'); } protected function getArguments() { return array( //array('example', InputArgument::REQUIRED, 'An example argument.'), ); } protected function getOptions() { return array( array('fix', null, InputOption::VALUE_OPTIONAL, 'Fix data', null), array('client_id', null, InputOption::VALUE_OPTIONAL, 'Client id', null), ); } }<file_sep>/app/Http/Middleware/StartupCheck.php <?php namespace app\Http\Middleware; use Request; use Closure; use Utils; use App; use Auth; use Input; use Redirect; use Cache; use Session; use Event; use App\Models\Language; use App\Models\InvoiceDesign; use App\Events\UserSettingsChanged; class StartupCheck { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { // Ensure all request are over HTTPS in production if (App::environment() == ENV_PRODUCTION) { if (!Request::secure()) { return Redirect::secure(Request::getRequestUri()); } } // If the database doens't yet exist we'll skip the rest if (!Utils::isNinja() && !Utils::isDatabaseSetup()) { return $next($request); } // Check data has been cached $cachedTables = [ 'currencies' => 'App\Models\Currency', 'sizes' => 'App\Models\Size', 'industries' => 'App\Models\Industry', 'timezones' => 'App\Models\Timezone', 'dateFormats' => 'App\Models\DateFormat', 'datetimeFormats' => 'App\Models\DatetimeFormat', 'languages' => 'App\Models\Language', 'paymentTerms' => 'App\Models\PaymentTerm', 'paymentTypes' => 'App\Models\PaymentType', 'countries' => 'App\Models\Country', 'invoiceDesigns' => 'App\Models\InvoiceDesign', ]; foreach ($cachedTables as $name => $class) { if (Input::has('clear_cache')) { Session::flash('message', 'Cache cleared'); } if (Input::has('clear_cache') || !Cache::has($name)) { if ($name == 'paymentTerms') { $orderBy = 'num_days'; } elseif (in_array($name, ['currencies', 'sizes', 'industries', 'languages', 'countries'])) { $orderBy = 'name'; } else { $orderBy = 'id'; } $tableData = $class::orderBy($orderBy)->get(); if (count($tableData)) { Cache::forever($name, $tableData); } } } // check the application is up to date and for any news feed messages if (Auth::check()) { $count = Session::get(SESSION_COUNTER, 0); Session::put(SESSION_COUNTER, ++$count); if (isset($_SERVER['REQUEST_URI']) && !Utils::startsWith($_SERVER['REQUEST_URI'], '/news_feed') && !Session::has('news_feed_id')) { $data = false; if (Utils::isNinja()) { $data = Utils::getNewsFeedResponse(); } else { $file = @file_get_contents(NINJA_APP_URL.'/news_feed/'.Utils::getUserType().'/'.NINJA_VERSION); $data = @json_decode($file); } if ($data) { if (version_compare(NINJA_VERSION, $data->version, '<')) { $params = [ 'user_version' => NINJA_VERSION, 'latest_version' => $data->version, 'releases_link' => link_to(RELEASES_URL, 'Invoice Ninja', ['target' => '_blank']), ]; Session::put('news_feed_id', NEW_VERSION_AVAILABLE); Session::put('news_feed_message', trans('texts.new_version_available', $params)); } else { Session::put('news_feed_id', $data->id); if ($data->message && $data->id > Auth::user()->news_feed_id) { Session::put('news_feed_message', $data->message); } } } else { Session::put('news_feed_id', true); } } } // Check if we're requesting to change the account's language if (Input::has('lang')) { $locale = Input::get('lang'); App::setLocale($locale); Session::set(SESSION_LOCALE, $locale); if (Auth::check()) { if ($language = Language::whereLocale($locale)->first()) { $account = Auth::user()->account; $account->language_id = $language->id; $account->save(); } } } elseif (Auth::check()) { $locale = Session::get(SESSION_LOCALE, DEFAULT_LOCALE); App::setLocale($locale); } // Make sure the account/user localization settings are in the session if (Auth::check() && !Session::has(SESSION_TIMEZONE)) { Event::fire(new UserSettingsChanged()); } // Check if the user is claiming a license (ie, additional invoices, white label, etc.) if (isset($_SERVER['REQUEST_URI'])) { $claimingLicense = Utils::startsWith($_SERVER['REQUEST_URI'], '/claim_license'); if (!$claimingLicense && Input::has('license_key') && Input::has('product_id')) { $licenseKey = Input::get('license_key'); $productId = Input::get('product_id'); $data = trim(file_get_contents((Utils::isNinjaDev() ? SITE_URL : NINJA_APP_URL)."/claim_license?license_key={$licenseKey}&product_id={$productId}")); if ($productId == PRODUCT_INVOICE_DESIGNS) { if ($data = json_decode($data)) { foreach ($data as $item) { $design = new InvoiceDesign(); $design->id = $item->id; $design->name = $item->name; $design->javascript = $item->javascript; $design->save(); } Session::flash('message', trans('texts.bought_designs')); } } elseif ($productId == PRODUCT_WHITE_LABEL) { if ($data == 'valid') { $account = Auth::user()->account; $account->pro_plan_paid = NINJA_DATE; $account->save(); Session::flash('message', trans('texts.bought_white_label')); } } } } if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/(?i)msie [2-8]/', $_SERVER['HTTP_USER_AGENT'])) { Session::flash('error', trans('texts.old_browser')); } // for security prevent displaying within an iframe $response = $next($request); $response->headers->set('X-Frame-Options', 'DENY'); return $response; } }
8a41d148a458a898a29e4eb75cede1a8a0814db1
[ "Markdown", "JavaScript", "PHP", "Shell" ]
91
PHP
ninjaparade/invoice-ninja
ff0a37f1d8a8a80b940ebf2ee5e66ac3b5af3ba5
5cddeadec1a674d5e8cf2cf083aaa6bc1f8204e2
refs/heads/master
<file_sep>def augment(precios, aumentos) precios_aumentados = [] precios.each do |actuales| precios_aumentados.push actuales * aumentos end precios_aumentados end print "Los nuevos precios han sido aumentados en un 20% a: \t#{augment([35, 1249, 8100, 10502, 4, 79], 1.20)}\n.\t\t\t\s\s\s\Los antiguos precios son: [35, 1249, 8100, 10502, 4, 79]\n"
ef61e5f78e1de6b3ccec6abb09ce78757572fb18
[ "Ruby" ]
1
Ruby
rgonzalezj/19_aumento
d8e588f7d405b415f4dee3a74da8293c520ee075
61c6489120d0292fbf9d78a972e2edfe664bc37a
refs/heads/master
<repo_name>chuckbergeron/pooltogether-landing-site<file_sep>/lib/fetchers/getPools.js import { fetchData } from 'lib/fetchers/fetchData' import { deserializeBigNumbers, getNetworkNameAliasByChainId } from '@pooltogether/utilities' const API_URI = 'https://pooltogether-api.com' /** * Fetches the data for a single pool and converts big number data to BigNumbers * @param {*} chainId * @param {*} poolAddress * @returns */ export const getPool = async (chainId, poolAddress) => await fetchData(`${API_URI}/pools/${chainId}/${poolAddress}.json`).then((pool) => formatPool(pool, chainId) ) /** * Fetches the data for all pools and converts big number data to BigNumbers * @param {*} chainIds * @returns */ export const getPoolsByChainIds = async (chainIds) => Promise.all( chainIds.map( async (chainId) => await fetchData(`${API_URI}/pools/${chainId}.json`).then((pools) => pools.map((pool) => formatPool(pool, chainId)) ) ) ).then(keyPoolsByChainId) /** * Fetches the data for all pools and converts big number data to BigNumbers * @param {*} chainId * @returns */ export const getPoolsByChainId = async (chainId) => await fetchData(`${API_URI}/pools/${chainId}.json`) .then((pools) => pools.map((pool) => formatPool(pool, chainId))) .then((pools) => { return pools }) /** * Adds chain id and converts big numbers into BigNumbers * @param {*} pool * @param {*} chainId * @returns */ const formatPool = (pool, chainId) => ({ chainId, networkName: getNetworkNameAliasByChainId(chainId), ...deserializeBigNumbers(pool) }) /** * Keys the lists of pools by their chain id * @param {*} allPools * @returns */ const keyPoolsByChainId = (allPools) => { const arrayOfArrayOfPools = Object.values(allPools) return arrayOfArrayOfPools.reduce((sortedPools, pools) => { const chainId = pools?.[0].chainId if (chainId) { sortedPools[chainId] = pools } return sortedPools }, {}) } <file_sep>/lib/components/IndexHowItWorks.jsx import React from 'react' import SquigglePurple from 'assets/images/squiggle-purple.svg' const HowItWorksBox = (props) => { return <> <div className={`bg-default rounded-lg shadow-xl trans how-it-works-box bg-secondary px-6 py-8 sm:px-8 sm:py-12 lg:pb-20 sm:-mx-8 mb-10 sm:mb-10 sm:max-w-1/3 lg:max-w-sm`} > <h4 className='how-it-works-box-title text-highlight-2 uppercase sm:pb-2'> {props.title} </h4> <img src={SquigglePurple} className='mt-2 sm:mt-4 mb-5 sm:mb-8' /> <div className='text-xs xs:text-sm sm:text-base lg:text-xl'> {props.description} </div> </div> </> } export const IndexHowItWorks = () => { return <> <div className='bg-secondary'> <div className='bg-how-art-waves pt-24 px-4 sm:px-0' > <div className='pool-container mx-auto pb-8'> <div className='flex items-center justify-between'> <h1 className='leading-10 sm:leading-tight' > <div className='text-flashy' >How</div> <div className='block -mt-2'>it works</div> </h1> </div> </div> <div className='pool-container mx-auto flex flex-col sm:flex-row justify-between'> <HowItWorksBox title='Get tickets' description='Deposit into any prize pool and instantly get tickets.' /> <HowItWorksBox title='Win prizes' description={`As long as you have deposits you're eligible to win prizes. Prizes are made up of the all the interest earned on deposited money in the pools.`} /> <HowItWorksBox title='Never lose' description='Remove your deposit at anytime. As long as you stay in the pools you continue to be eligible to win.' /> </div> </div> </div> </> } <file_sep>/lib/components/GridItem.jsx import React from 'react' import { motion } from 'framer-motion' const itemVariants = { hidden: { opacity: 0, scale: 1 }, visible: { opacity: 1, scale: 1 } } export const GridItem = (props) => { const { attribution, description, img, title, url, imgStyle } = props return ( <> <motion.a href={url} title={`View ${title}`} target='_blank' rel='noopener noreferrer' className='w-full sm:w-1/3 rounded-lg p-2 trans flex flex-col no-underline px-4 lg:px-8 mx-auto' variants={itemVariants} whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} > <div className='interactable-chip-alt-bg text-white interactable-chip hover:shadow-xl flex flex-col justify-center trans py-4 px-10 sm:px-8 h-32'> <div className='flex items-center justify-between w-full'> <div className='font-bold text-xl sm:text-lg lg:text-xl'>{title}</div> <img src={img} className='w-6 h-6 lg:w-8 lg:h-8' title={attribution || ''} style={imgStyle} /> </div> <div className='mt-2 sm:mt-4 no-underline text-gray-600 text-xxs'>{description}</div> </div> </motion.a> </> ) } <file_sep>/lib/fetchers/fetchData.js /** * Very basic wrapper for fetch * @param {*} request * @returns */ export const fetchData = async (request) => { const response = await fetch(request) return await response.json() } <file_sep>/lib/components/IndexPoolToken.jsx import React from 'react' import { ButtonLink } from 'lib/components/ButtonLink' export const IndexPoolToken = (props) => { return ( <> <div id='token' className='bg-darkened text-center pt-12 pb-6 sm:pt-20 sm:pb-16'> <div className='pool-container mx-auto'> <h1 className='text-center'> <span role='img' aria-label='sparkles emoji' className='relative mx-2 text-2xl lg:text-3xl -t-1 lg:-t-2' > ✨ </span>{' '} <span className='text-flashy'>POOL</span> Token{' '} <span role='img' aria-label='sparkles emoji' className='relative mx-2 text-2xl lg:text-3xl -t-1 lg:-t-2' > ✨ </span> </h1> <p className='text-sm xs:text-xl sm:text-xl lg:text-3xl text-center mt-10 mx-auto lg:max-w-4xl'> The PoolTogether Protocol is controlled by POOL token holders. <br className='hidden lg:block' /> &nbsp;All changes to the protocol are submitted and approved. <br className='hidden lg:block' /> &nbsp;The protocol automatically distributes the POOL token to anyone who deposits into the protocol. </p> <div className='mt-10'> <div className='sm:w-7/12 lg:w-1/2 sm:mx-auto my-6'> <ButtonLink textSize='xl' width='w-full' as={`https://app.pooltogether.com`} href={`https://app.pooltogether.com`} > Deposit to receive POOL tokens </ButtonLink> </div> <div className='sm:w-7/12 lg:w-1/2 sm:mx-auto my-6'> <ButtonLink tertiary textSize='xl' width='w-full' as={`https://medium.com/p/fca9ab8b8ba2`} href={`https://medium.com/p/fca9ab8b8ba2`} > Learn about governance </ButtonLink> </div> </div> </div> </div> </> ) } <file_sep>/lib/hooks/useReadProvider.js import { useContext, useEffect, useState } from 'react' import { AuthControllerContext } from 'lib/components/contextProviders/AuthControllerContextProvider' import { readProvider } from 'lib/services/readProvider' export function useReadProvider() { const { networkName } = useContext(AuthControllerContext) const [defaultReadProvider, setDefaultReadProvider] = useState({}) useEffect(() => { const getReadProvider = async () => { const defaultReadProvider = await readProvider(networkName) setDefaultReadProvider(defaultReadProvider) } getReadProvider() }, [networkName]) const isLoaded = Object.keys(defaultReadProvider).length > 0 return { readProvider: defaultReadProvider, isLoaded } } <file_sep>/lib/components/BannerUILoader.jsx import React from 'react' import ContentLoader from 'react-content-loader' import { isMobile } from 'react-device-detect' const UI_LOADER_ANIM_DEFAULTS = { gradientRatio: 2.5, interval: 0.05, speed: 0.6 } export const BannerUILoader = (props) => { const bgColor = '#401C94' const foreColor = '#501C94' if (isMobile) { return ( <ContentLoader {...UI_LOADER_ANIM_DEFAULTS} viewBox='0 0 600 300' backgroundColor={bgColor} foregroundColor={foreColor} > <rect x='0' y='0' rx='15' ry='15' width='600' height='300' /> </ContentLoader> ) } return ( <ContentLoader {...UI_LOADER_ANIM_DEFAULTS} viewBox='0 0 600 50' backgroundColor={bgColor} foregroundColor={foreColor} > <rect x='0' y='0' rx='5' ry='5' width='600' height='50' /> </ContentLoader> ) } <file_sep>/lib/components/IndexHero.jsx import React, { useState } from 'react' import { ReactFitty } from 'react-fitty' import { ButtonLink } from 'lib/components/ButtonLink' import { TVLAndWeeklyPrizesBanner } from 'lib/components/TVLAndWeeklyPrizesBanner' import { WistiaPlayer } from 'lib/components/WistiaPlayer' import { IndexHeroFeaturedIn } from 'lib/components/IndexHeroFeaturedIn' import Squiggle from 'assets/images/squiggle.svg' import SquiggleMobile from 'assets/images/squiggle-mobile.svg' export const IndexHero = (props) => { const [playVideo, setPlayVideo] = useState(false) const startVideo = (e) => { e.preventDefault() setPlayVideo(true) setTimeout(() => { setPlayVideo(false) }, 500) } return ( <> <div className='relative'> <div className='pool-container flex flex-col sm:flex-row justify-between pt-12 mx-auto'> <div className='relative hero-text-left mb-12 sm:mb-0'> <div className='w-3/4 xs:w-7/12 sm:w-full mx-auto'> <ReactFitty className='font-bold leading-none text-center'> <span className='text-flashy'>Save, pool funds,</span> </ReactFitty> <ReactFitty className='mt-2 font-bold leading-none text-center'> <span className='text-flashy'>& win prizes together</span> </ReactFitty> <div className='text-center mt-6 sm:mt-12'> <ButtonLink width='w-full' textSize='xl' href='https://app.pooltogether.com' as='https://app.pooltogether.com' > Join the Pool </ButtonLink> </div> </div> </div> <div> <button onClick={startVideo} className='bg-vid-holo flex items-start justify-center trans' role='img' > <div className='bg-vid-holo--inner flex items-center justify-center'> <WistiaPlayer play={playVideo} /> <div className='bg-vid-circle rounded-full flex items-center justify-center hover:bg-highlight-2 trans'> <div className='bg-vid-tri' /> </div> </div> </button> </div> </div> <TVLAndWeeklyPrizesBanner /> <IndexHeroFeaturedIn /> <div className='pool-container text-center relative flex flex-col sm:flex-row mt-10 mb-16 sm:my-20 mx-auto'> <div className='bg-card rounded-xl mx-auto w-full sm:w-full py-8 sm:py-8 lg:px-12 lg:py-12 text-center sm:text-left'> <h1 className='text-center'>PoolTogether</h1> <img src={Squiggle} className='hidden xs:block mx-auto my-4' /> <img src={SquiggleMobile} className='xs:hidden mx-auto my-4' /> <div className='text-xs sm:text-2xl text-center mt-7'> is an open source and decentralized <br /> protocol for no-loss prize games </div> </div> </div> </div> </> ) } <file_sep>/lib/components/IndexHeroFeaturedIn.jsx import React, { useEffect } from 'react' import classnames from 'classnames' import { useInView } from 'react-intersection-observer' import { motion, useAnimation } from 'framer-motion' import { GridItemSupportedBy } from 'lib/components/GridItemSupportedBy' import BinanceAcademySvg from 'assets/images/binance-academy.svg' import EthereumPng from 'assets/images/ethereum-org.png' import BanklessPng from 'assets/images/bankless.png' import CoinDeskPng from 'assets/images/coindesk.png' import ZapperFiSvg from 'assets/images/zapper-white.svg' export const IndexHeroFeaturedIn = () => { const controls = useAnimation() const [ref, inView] = useInView() useEffect(() => { if (inView) { controls.start('visible') } }, [controls, inView]) const containerVariants = { visible: { transition: { staggerChildren: 0.12 } }, hidden: {} } return ( <div id='featured-in' className='text-center pt-10'> <div className='pool-container mx-auto'> <h5 className='my-0 sm:mt-4 leading-tight'>Featured in:</h5> <motion.div className={classnames( 'flex flex-col xs:flex-row xs:flex-wrap justify-start items-start', 'mt-2 mb-4 px-4 xs:px-8 rounded-xl -mx-4 sm:-mx-12 lg:-mx-16' )} ref={ref} animate={controls} initial='hidden' variants={containerVariants} > <GridItemSupportedBy altBg title={'Binance Academy'} img={BinanceAcademySvg} url='https://academy.binance.com/en/articles/how-pool-together-turns-saving-money-into-a-game' /> <GridItemSupportedBy altBg title={'Zapper'} img={ZapperFiSvg} url='https://learn.zapper.fi/articles/how-to-tranfer-eth-from-coinbase-to-defi' /> <GridItemSupportedBy altBg title={'Ethereum.org'} img={EthereumPng} url='https://ethereum.org/en/dapps/' /> <GridItemSupportedBy altBg title={'Bankless'} img={BanklessPng} url='https://shows.banklesshq.com/p/early-access-meet-the-nation-pooltogether' /> <GridItemSupportedBy altBg title={'CoinDesk'} img={CoinDeskPng} url='https://www.coindesk.com/tag/pooltogether' /> </motion.div> </div> </div> ) } <file_sep>/lib/components/Nav.jsx import React from 'react' import classnames from 'classnames' import Link from 'next/link' import { useRouter } from 'next/router' import { useTranslation } from 'lib/../i18n' export const Nav = (props) => { const { t } = useTranslation() const router = useRouter() const developersPage = router.pathname.match('developers') const navLinkClasses = 'capitalize text-center leading-none rounded-full flex justify-start items-center text-lg py-3 px-4 lg:px-8 trans tracking-wider outline-none focus:outline-none active:outline-none text-white' return <> <nav className='justify-end items-center hidden sm:flex w-2/3' > <Link href='/developers' as='/developers' shallow > <a className={classnames( 'mr-3', navLinkClasses, { 'text-white hover:text-highlight-2': !developersPage, 'text-highlight-2 hover:text-highlight-2': developersPage } )} > {t('developers')} </a> </Link> <Link href='https://app.pooltogether.com' as='https://app.pooltogether.com' > <a className={classnames( 'inline-flex items-center justify-center uppercase font-bold tracking-wider outline-none focus:outline-none active:outline-none', 'hover:bg-default rounded-full border-2 border-highlight-2 px-10 py-1 trans trans-fast text-lg', )} > {t('app')} </a> </Link> </nav> </> } <file_sep>/lib/components/IndexUI.jsx import React from 'react' import { IndexGetInvolved } from 'lib/components/IndexGetInvolved' import { IndexHero } from 'lib/components/IndexHero' import { IndexPoolToken } from 'lib/components/IndexPoolToken' import { IndexHowItWorks } from 'lib/components/IndexHowItWorks' import { IndexIntegrations } from 'lib/components/IndexIntegrations' import { IndexSupportedBy } from 'lib/components/IndexSupportedBy' import { IndexSecurity } from 'lib/components/IndexSecurity' export const IndexUI = (props) => { return ( <> <IndexHero /> <IndexIntegrations /> <IndexHowItWorks /> <IndexPoolToken /> <IndexSecurity /> <IndexSupportedBy /> <IndexGetInvolved /> </> ) } <file_sep>/lib/components/IndexIntegrations.jsx import React, { useEffect } from 'react' import classnames from 'classnames' import { useInView } from 'react-intersection-observer' import { motion, useAnimation } from 'framer-motion' import { ButtonLink } from 'lib/components/ButtonLink' import { GridItem } from 'lib/components/GridItem' import BotSvg from 'assets/images/logo-ttbot@2x.png' import DharmaSvg from 'assets/images/dharma-logo.png' import ZerionSvg from 'assets/images/zerion.svg' import ZapperFiSvg from 'assets/images/zapperfi.svg' export const IndexIntegrations = () => { const controls = useAnimation() const [ref, inView] = useInView() useEffect(() => { if (inView) { controls.start('visible') } }, [controls, inView]) const containerVariants = { visible: { transition: { staggerChildren: 0.2 } }, hidden: {} } return ( <> <div className='bg-secondary'> <div className='pool-container mx-auto pt-12 pb-6 sm:pt-20 sm:pb-16'> <div className='lg:px-20'> <div className='flex items-center justify-between'> <h1 className='leading-10 sm:leading-tight'> <div className='text-flashy'>Protocol</div>{' '} <div className='block -mt-2'>Integrations</div> </h1> </div> <div className='flex flex-col py-4'> <p className='text-sm xs:text-xl sm:text-xl lg:text-3xl lg:max-w-3xl'> Try community-built interfaces and get inspired by what you can build on the PoolTogether protocol. </p> <motion.div className={classnames( 'flex flex-col sm:flex-row sm:flex-wrap', 'mt-8 mb-4 rounded-xl text-base lg:text-lg -mx-4 sm:-mx-4 lg:-mx-8' )} ref={ref} animate={controls} initial='hidden' variants={containerVariants} > {/* <GridItem title={'Argent'} description={`Use the Argent app to join the pool.`} img={ArgentSvg} url='https://www.argent.xyz/' /> */} <GridItem altBg title={'Dharma'} description={`Deposit into PoolTogether from your US bank.`} img={DharmaSvg} url='https://www.dharma.io/' /> <GridItem altBg title={'ZapperFi'} description={`Join PoolTogether using this portal to DeFi.`} img={ZapperFiSvg} url='https://www.zapper.fi/#/dashboard' /> <GridItem altBg title={'Zerion'} description={`Access DeFi & view your PoolTogether deposits.`} img={ZerionSvg} url='https://zerion.io/' /> <GridItem altBg title={'Twitter Bot'} description={`Updates each time someone joins or wins!`} img={BotSvg} url='https://twitter.com/PoolTogetherBot' attribution={`bot icon by <NAME> from the Noun Project`} /> {/* <GridItem title={'EBO'} description={`EBO Finance is a wallet app for joining the pool.`} img={EBOSvg} url='https://ebo.io/' /> */} </motion.div> </div> </div> <div className='bg-card rounded-xl mx-auto text-center p-4 xs:p-12 sm:pt-12 sm:pb-12 sm:mt-10'> <div className='flex flex-col items-center'> <h2 className='mt-4 mb-8 text-center'>Check out our developer documentation</h2> <p className='text-sm xs:text-lg sm:text-xl max-w-lg text-center'> Learn about the PoolTogether protocol and emerging use cases </p> <ButtonLink secondary textSize='2xl' href='https://docs.pooltogether.com' as='https://docs.pooltogether.com' className='my-8 w-3/4 sm:w-1/2' > Go to docs </ButtonLink> </div> </div> </div> </div> </> ) } <file_sep>/lib/hooks/usePools.js import { useContext } from 'react' import { useQuery } from 'react-query' import { NETWORK } from '@pooltogether/utilities' import { QUERY_KEYS } from 'lib/constants' import { AuthControllerContext } from 'lib/components/contextProviders/AuthControllerContextProvider' import { MAINNET_POLLING_INTERVAL } from 'lib/constants' import { getPoolsByChainId } from 'lib/fetchers/getPools' /** * Fetches pool graph data, chain data, token prices, lootbox data & merges it all. * Returns a flat list of pools * @returns */ export const useAllPools = () => { const { data: poolsByChainId, ...useAllPoolsResponse } = useAllPoolsKeyedByChainId() const pools = poolsByChainId ? Object.values(poolsByChainId).flat() : null return { ...useAllPoolsResponse, data: pools } } /** * Fetches pool graph data, chain data, token prices, lootbox data & merges it all * @returns */ export const useAllPoolsKeyedByChainId = () => { const { pauseQueries } = useContext(AuthControllerContext) const ethereumChainId = NETWORK.mainnet const polygonChainId = NETWORK.matic const enabled = !pauseQueries const { data: ethereumPools, ...ethereumUseQuery } = useQuery( [QUERY_KEYS.usePools, ethereumChainId], async () => await getPoolsByChainId(ethereumChainId), { enabled, refetchInterval: MAINNET_POLLING_INTERVAL } ) const { data: polygonPools, ...polygonUseQuery } = useQuery( [QUERY_KEYS.usePools, polygonChainId], async () => await getPoolsByChainId(polygonChainId), { enabled, refetchInterval: MAINNET_POLLING_INTERVAL } ) const refetch = () => { ethereumUseQuery.refetch() polygonUseQuery.refetch() } const isFetched = ethereumUseQuery.isFetched && polygonUseQuery.isFetched const isFetching = ethereumUseQuery.isFetching && polygonUseQuery.isFetching let data = null if (ethereumUseQuery.isFetched) { if (!data) { data = {} } data[ethereumChainId] = ethereumPools } if (polygonUseQuery.isFetched) { if (!data) { data = {} } data[polygonChainId] = polygonPools } return { data, isFetched, isFetching, refetch } }
21c444c8a632875c3b9c5936d0dd05b818548b53
[ "JavaScript" ]
13
JavaScript
chuckbergeron/pooltogether-landing-site
03410d579b4fe07486eed70882e607a9901bfd66
6234419b7fbbdc56e0b4c37922964e5627b5fa24
refs/heads/master
<repo_name>johnayeni/owo-fe<file_sep>/src/pages/home/home.ts import { Component, NgZone, ViewChild } from '@angular/core'; import { IonicPage, NavController, NavParams, ToastController, LoadingController, ModalController, App, } from 'ionic-angular'; import { HTTP } from '@ionic-native/http'; import { Storage } from '@ionic/storage'; import { ModalPage } from '../modal/modal'; import { LoginPage } from '../login/login'; import { Chart } from 'chart.js'; @IonicPage() @Component({ selector: 'page-home', templateUrl: 'home.html', }) export class HomePage { @ViewChild('doughnutCanvas') doughnutCanvas; userDetails = { balance: 0.0, total_income: 0.0, total_expenses: 0.0 }; url = 'https://owo-be.herokuapp.com'; doughnutChart: any; constructor( public app: App, public navCtrl: NavController, public navParams: NavParams, private storage: Storage, private toastCtrl: ToastController, public loadingCtrl: LoadingController, public modalCtrl: ModalController, private http: HTTP, private zone: NgZone, ) {} ionViewDidEnter() { this.getUserDetails(); } async getUserDetails() { const token = await this.storage.get('token'); if (!token) { this.navCtrl.popToRoot(); } const headers = { Authorization: `Bearer ${token}` }; let loading = this.loadingCtrl.create({ content: 'Please wait...' }); loading.present(); try { const response = await this.http.get(`${this.url}/api/user`, {}, headers); const responseData = await JSON.parse(response.data); this.zone.run(() => { this.userDetails = { ...responseData.user }; this.doughnutChart = new Chart(this.doughnutCanvas.nativeElement, { type: 'pie', data: { labels: ['Income', 'Expense'], datasets: [ { label: 'Ratio of Income to Expense', data: [responseData.user.total_income, responseData.user.total_expenses], backgroundColor: ['rgb(105, 204, 154)', 'rgb(247, 134, 138)'], hoverBackgroundColor: ['#00d86c', '#ff3e45'], }, ], }, }); }); } catch (error) { if (error.status === 401) { this.logout(); } else { this.toast('Error fetching data'); } } loading.dismiss(); } showModal() { const modal = this.modalCtrl.create(ModalPage); modal.present(); modal.onDidDismiss(() => { this.getUserDetails(); }); } toast(message) { const toast = this.toastCtrl.create({ message, duration: 3000, }); toast.present(); } logout() { this.storage.remove('token'); this.app.getRootNav().setRoot(LoginPage); this.navCtrl.popToRoot(); } } <file_sep>/src/pages/editmodal/editmodal.ts import { Component } from '@angular/core'; import { App, IonicPage, NavController, NavParams, ViewController, ToastController, LoadingController, } from 'ionic-angular'; import { HTTP } from '@ionic-native/http'; import { Storage } from '@ionic/storage'; import { TabsPage } from '../tabs/tabs'; import { LoginPage } from '../login/login'; /** * Generated class for the ModalPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-editmodal', templateUrl: 'editmodal.html', }) export class EditmodalPage { constructor( public app: App, public navCtrl: NavController, public viewCtrl: ViewController, public navParams: NavParams, private toastCtrl: ToastController, public loadingCtrl: LoadingController, private http: HTTP, private storage: Storage, ) {} formData = { id: this.navParams.get('id'), type: this.navParams.get('type'), amount: this.navParams.get('amount'), description: this.navParams.get('description'), }; url = 'https://owo-be.herokuapp.com'; async submit() { const token = await this.storage.get('token'); const headers = { Authorization: `Bearer ${token}` }; let loading = this.loadingCtrl.create({ content: 'Please wait...' }); loading.present(); try { const response = await this.http.put( `${this.url}/api/transaction/${this.formData.id}`, this.formData, headers, ); const responseData = JSON.parse(response.data); this.toast(responseData.message); this.dismiss(); } catch (error) { console.log(error); if (error.status === 401) { this.logout(); } else if (error.status === 400) { const errorData = JSON.parse(error.error); this.toast(errorData.messages[0].message || 'Error editing transaction'); } else { this.toast('Error editing transaction'); } } loading.dismiss(); } toast(message) { const toast = this.toastCtrl.create({ message, duration: 3000, }); toast.present(); } dismiss() { this.viewCtrl.dismiss(); } logout() { this.storage.remove('token'); this.app.getRootNav().setRoot(LoginPage); this.navCtrl.popToRoot(); } } <file_sep>/src/pages/login/login.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ToastController, LoadingController, AlertController, } from 'ionic-angular'; import { HTTP } from '@ionic-native/http'; import { Storage } from '@ionic/storage'; import { TabsPage } from '../tabs/tabs'; import { RegisterPage } from '../register/register'; /** * Generated class for the LoginPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-login', templateUrl: 'login.html', }) export class LoginPage { constructor( public navCtrl: NavController, public navParams: NavParams, private storage: Storage, private toastCtrl: ToastController, public loadingCtrl: LoadingController, public alertCtrl: AlertController, private http: HTTP, ) {} formData = {}; url = 'https://owo-be.herokuapp.com'; async ionViewDidEnter() { const token = await this.storage.get('token'); if (token) { this.navCtrl.push(TabsPage); } } async login() { let loading = this.loadingCtrl.create({ content: 'Please wait...' }); loading.present(); try { const response = await this.http.post(`${this.url}/auth/login`, this.formData, {}); const responseData = await JSON.parse(response.data); this.toast(responseData.message); await this.storage.set('token', String(responseData.token)); this.navCtrl.push(TabsPage); } catch (error) { if (error.status === 400) { const errorData = await JSON.parse(error.error); this.toast(errorData.messages[0].message || 'Error occured logging in'); } else { this.toast('Error occured logging in'); } } loading.dismiss(); } goToRegisterPage() { this.navCtrl.push(RegisterPage); } toast(message) { const toast = this.toastCtrl.create({ message, duration: 3000, }); toast.present(); } } <file_sep>/src/pages/contact/contact.ts import { Component, NgZone } from '@angular/core'; import { App, IonicPage, NavController, ToastController, LoadingController } from 'ionic-angular'; import { LoginPage } from '../login/login'; import { Storage } from '@ionic/storage'; import { HTTP } from '@ionic-native/http'; @IonicPage() @Component({ selector: 'page-contact', templateUrl: 'contact.html', }) export class ContactPage { user = { fullname: '', email: '', balance: 0.0, created_at: '', }; url = 'https://owo-be.herokuapp.com'; constructor( private navCtrl: NavController, public app: App, private http: HTTP, private storage: Storage, private toastCtrl: ToastController, public loadingCtrl: LoadingController, private zone: NgZone, ) {} ionViewDidEnter() { this.getUserDetails(); } async getUserDetails() { const token = await this.storage.get('token'); if (!token) { this.navCtrl.popToRoot(); } const headers = { Authorization: `Bearer ${token}` }; let loading = this.loadingCtrl.create({ content: 'Please wait...' }); loading.present(); try { const response = await this.http.get(`${this.url}/api/user`, {}, headers); const responseData = await JSON.parse(response.data); this.zone.run(() => { this.user = { ...responseData.user }; this.user = { ...this.user, created_at: new Date(this.user.created_at).toDateString() }; }); } catch (error) { if (error.status === 401) { this.logout(); } else { this.toast('Error fetching data'); } } loading.dismiss(); } toast(message) { const toast = this.toastCtrl.create({ message, duration: 3000, }); toast.present(); } logout() { this.storage.remove('token'); this.app.getRootNav().setRoot(LoginPage); this.navCtrl.popToRoot(); } } <file_sep>/src/pages/tabs/tabs.ts import { Component, forwardRef, Inject } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { Storage } from '@ionic/storage'; import { AboutPage } from '../about/about'; import { ContactPage } from '../contact/contact'; import { HomePage } from '../home/home'; import { LoginPage } from '../login/login'; @IonicPage() @Component({ templateUrl: 'tabs.html', }) export class TabsPage { tab1Root = HomePage; tab2Root = AboutPage; tab3Root = ContactPage; constructor(private navCtrl: NavController, private storage: Storage) {} async ionViewDidEnter() { const token = await this.storage.get('token'); if (!token) { this.navCtrl.popToRoot(); } } } <file_sep>/src/pages/register/register.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ToastController, LoadingController, } from 'ionic-angular'; import { HTTP } from '@ionic-native/http'; import { Storage } from '@ionic/storage'; import { LoginPage } from '../login/login'; import { TabsPage } from '../tabs/tabs'; /** * Generated class for the RegisterPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-register', templateUrl: 'register.html', }) export class RegisterPage { constructor( public navCtrl: NavController, public navParams: NavParams, private storage: Storage, private toastCtrl: ToastController, public loadingCtrl: LoadingController, private http: HTTP, ) {} formData = { fullname: '', email: '', password: '', }; url = 'https://owo-be.herokuapp.com'; async ionViewDidEnter() { const token = await this.storage.get('token'); if (token) { this.navCtrl.push(TabsPage); } } async register() { let loading = this.loadingCtrl.create({ content: 'Please wait...', }); loading.present(); try { const response = await this.http.post(`${this.url}/auth/register`, this.formData, {}); const responseData = await JSON.parse(response.data); this.toast(responseData.message); this.navCtrl.push(LoginPage); } catch (error) { console.log(error); if (error.status === 400) { const errorData = await JSON.parse(error.error); this.toast(errorData.messages[0].message || 'Error occured in registration'); } else { this.toast('Error occured in registration'); } } loading.dismiss(); } goToLoginPage() { this.navCtrl.push(LoginPage); } toast(message) { const toast = this.toastCtrl.create({ message, duration: 3000, }); toast.present(); } } <file_sep>/src/pages/modal/modal.ts import { Component } from '@angular/core'; import { App, IonicPage, NavController, NavParams, ViewController, ToastController, LoadingController, } from 'ionic-angular'; import { HTTP } from '@ionic-native/http'; import { Storage } from '@ionic/storage'; import { TabsPage } from '../tabs/tabs'; import { LoginPage } from '../login/login'; /** * Generated class for the ModalPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-modal', templateUrl: 'modal.html', }) export class ModalPage { constructor( public app: App, public navCtrl: NavController, public viewCtrl: ViewController, public navParams: NavParams, private toastCtrl: ToastController, public loadingCtrl: LoadingController, private http: HTTP, private storage: Storage, ) {} formData = { type: '', amount: 0, description: '' }; url = 'https://owo-be.herokuapp.com'; async submit() { const token = await this.storage.get('token'); const headers = { Authorization: `Bearer ${token}` }; let loading = this.loadingCtrl.create({ content: 'Please wait...' }); loading.present(); try { const response = await this.http.post(`${this.url}/api/transaction`, this.formData, headers); const responseData = JSON.parse(response.data); this.toast(responseData.message); this.dismiss(); } catch (error) { console.log(error); if (error.status === 401) { this.logout(); } else if (error.status === 400) { const errorData = JSON.parse(error.error); this.toast(errorData.messages[0].message || 'Error creating transaction'); } else { this.toast('Error creating transaction'); } } loading.dismiss(); } toast(message) { const toast = this.toastCtrl.create({ message, duration: 3000, }); toast.present(); } dismiss() { this.viewCtrl.dismiss(); } logout() { this.storage.remove('token'); this.app.getRootNav().setRoot(LoginPage); this.navCtrl.popToRoot(); } } <file_sep>/src/providers/providers-auth/providers-auth.ts import { HTTP } from '@ionic-native/http'; import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; import { ToastController, LoadingController } from 'ionic-angular'; import { TabsPage } from '../../pages/tabs/tabs'; import { LoginPage } from '../../pages/login/login'; /* Generated class for the ProvidersAuthProvider provider. See https://angular.io/guide/dependency-injection for more info on providers and Angular DI. */ @Injectable() export class ProvidersAuthProvider { constructor( private http: HTTP, private storage: Storage, private toastCtrl: ToastController, public loadingCtrl: LoadingController, ) {} } <file_sep>/src/pages/about/about.ts import { Component, NgZone } from '@angular/core'; import { App, IonicPage, NavController, NavParams, ToastController, LoadingController, AlertController, ModalController, } from 'ionic-angular'; import { HTTP } from '@ionic-native/http'; import { Storage } from '@ionic/storage'; import { EditmodalPage } from '../editmodal/editmodal'; import { LoginPage } from '../login/login'; @IonicPage() @Component({ selector: 'page-about', templateUrl: 'about.html', }) export class AboutPage { url = 'https://owo-be.herokuapp.com'; transactions = []; incomeTransactions = []; expenseTransactions = []; constructor( public app: App, public navCtrl: NavController, public navParams: NavParams, private storage: Storage, private toastCtrl: ToastController, public loadingCtrl: LoadingController, public alertCtrl: AlertController, public modalCtrl: ModalController, private http: HTTP, private zone: NgZone, ) {} transactionTab = 'all'; ionViewDidEnter() { this.getTransactions(); } async getTransactions() { const token = await this.storage.get('token'); if (!token) { this.navCtrl.popToRoot(); } const headers = { Authorization: `Bearer ${token}` }; let loading = this.loadingCtrl.create({ content: 'Please wait...' }); loading.present(); try { const response = await this.http.get(`${this.url}/api/transactions`, {}, headers); const responseData = await JSON.parse(response.data); this.zone.run(() => { this.transactions = [...responseData.transactions]; this.incomeTransactions = this.transactions.filter((transaction) => { return transaction.type == 'income'; }); this.expenseTransactions = this.transactions.filter((transaction) => { return transaction.type == 'expense'; }); }); } catch (error) { if (error.status === 401) { this.logout(); } else { this.toast('Error fetching data'); } } loading.dismiss(); } editTransaction(data) { const modal = this.modalCtrl.create(EditmodalPage, data); modal.present(); modal.onDidDismiss(() => { this.getTransactions(); }); } async deleteTransaction(id) { const self = this; const confirm = this.alertCtrl.create({ title: 'Delete Transaction record?', message: 'You cannot undo this action?', buttons: [ { text: 'Cancel', handler: function() { self.toast('Operation aborted'); }, }, { text: 'Continue', handler: async function() { const token = await self.storage.get('token'); const headers = { Authorization: `Bearer ${token}` }; let loading = self.loadingCtrl.create({ content: 'Please wait...' }); loading.present(); try { const response = await self.http.delete( `${self.url}/api/transaction/${id}`, {}, headers, ); const responseData = await JSON.parse(response.data); self.toast(responseData.message); self.getTransactions(); } catch (error) { if (error.status === 401) { self.logout(); } else { self.toast('Error deleting transaction'); } } loading.dismiss(); }, }, ], }); confirm.present(); } toast(message) { const toast = this.toastCtrl.create({ message, duration: 3000, }); toast.present(); } logout() { this.storage.remove('token'); this.app.getRootNav().setRoot(LoginPage); this.navCtrl.popToRoot(); } }
0a5eea339c8ff665439130a7aee4f9206950ca93
[ "TypeScript" ]
9
TypeScript
johnayeni/owo-fe
06f830cf3908dbdd3b89f1676af5a342d93e2db1
bc59324e22f0d5dfe9a6f51ec062a29e41a1f464
refs/heads/master
<file_sep>/* @jsx jsx */ 'use strict' // Configuracion esencial para el proyecto encuento a css. // Autor: Ghobbit. // Desarrollador Frontend y Diseñador gráfico: <NAME>. // Email: <EMAIL>; // Twitter: @duwahiner. import { jsx, css } from '@emotion/core'; import { colors, fonts, dimensions } from '../public/global.config'; import uniqid from 'uniqid'; const styles = { containerSalida: css ` width: ${ dimensions.containers.width }%; height: auto; background-color: ${ colors.rgbAlette.rgb1( 0 ) }; display: flex; justify-content: center; flex: auto; `, containerSalidaTareas: css ` width: ${ 50 }%; height: auto; background-color: ${ colors.rgbAlette.rgb1( 0 ) }; display: flex; flex-direction: column; align-items: center; flex: none; `, containerSalidaTareasItem: css ` width: ${ 550 }px; height: 40px; background-color: ${ colors.rgbAlette.rgb12Blanco( 1 ) }; border-radius: 3px; display: flex; align-items: center; flex: none; margin-bottom: 6px; `, containerSalidaTareasVista: css ` width: auto; height: 40px; background-color: ${ colors.rgbAlette.rgb12Blanco( 1 ) }; border-radius: 3px; display: flex; flex: auto; `, containerEntradaTitleTareas: css ` ${ fonts.fontAeonikLight() }; width: auto; height: 40px; font-family: fontAeonikLight, sans-serif; line-height: 40px; font-size: ${fonts.fontSize * 2}px; font-weight: 0; color: ${ colors.rgbAlette.rgb25( 1 ) }; letter-spacing: 0px; margin-bottom: 0px; margin-left: 10px; margin-top: 0px; box-sizing: border-box; background-color: ${ colors.rgbAlette.rgb4( 0 ) }; `, contactoFormInputItemTareas: css` ${ fonts.fontAeonikLight() }; ${ fonts.fontAeonikRegular() }; width: 100%; height: 40px; outline: none; border: none; font-family: fontAeonikLight, sans-serif; color: ${colors.rgbAlette.rgb13Negro(1)}; font-size: ${ fonts.fontSize * 1.7 }px; line-height: 40px; border-radius: 3px 0px 0px 3px; padding: 0px; padding-left: 10px; padding-right: 10px; flex: auto; transition: all 0.2s linear; &:focus{ color: ${ colors.rgbAlette.rgb26(1) }; font-family: fontAeonikRegular, sans-serif; background-color: ${ colors.rgbAlette.rgb12Blanco(1) }; } &:disabled{ background-color: ${ colors.rgbAlette.rgb12Blanco(1) }; } &::placeholder{ color: ${colors.rgbAlette.rgb13Negro(1)}; } `, contactoFormBottonAtionEditar: css ` ${ fonts.fontAeonikRegular() };; width: 70px; height: 25px; outline: none; font-family: fontAeonikRegular, sans-serif; color: ${ colors.rgbAlette.rgb25(1) }; font-size: ${ fonts.fontSize* 1.6 }px; line-height: 20px; border: 0px; border: solid 1px ${ colors.rgbAlette.rgb25(1) }; padding: 0px; margin-right: 10px; box-sizing: border-box; border-radius: 3px; background-color: ${ colors.rgbAlette.rgb25(0) }; flex: none; cursor: pointer; transition: all 0.3s ease; :hover{ background-color: ${ colors.rgbAlette.rgb26(1) }; color: ${ colors.rgbAlette.rgb12Blanco(1) }; border: solid 1px ${ colors.rgbAlette.rgb1(0) }; } `, contactoFormBottonAtionELiminar: css ` ${ fonts.fontAeonikRegular() };; width: 70px; height: 25px; outline: none; font-family: fontAeonikRegular, sans-serif; color: ${ colors.rgbAlette.rgb25(1) }; font-size: ${ fonts.fontSize* 1.3 }px; line-height: 20px; border: 0px; border: solid 1px ${ colors.rgbAlette.rgb25(1) }; padding: 0px; margin-right: 10px; box-sizing: border-box; border-radius: 3px; background-color: ${ colors.rgbAlette.rgb25(0) }; flex: none; cursor: pointer; transition: all 0.3s ease; :hover{ background-color: ${ colors.rgbAlette.rgb1(1) }; color: ${ colors.rgbAlette.rgb12Blanco(1) }; border: solid 1px ${ colors.rgbAlette.rgb1(0) }; } `, } export default ( props ) => { return ( <div css={styles.containerSalida}> <div css={styles.containerSalidaTareas}> <div css={styles.containerSalidaTareasItem} > <div css={styles.containerSalidaTareasVista}> <input type='text' name='' disabled placeholder={ props.value } css={styles.contactoFormInputItemTareas} /> </div> <button css={styles.contactoFormBottonAtionEditar} name='editar' type="" onClick={ props.handleEditarTask } > Editar </button> <button css={styles.contactoFormBottonAtionELiminar} name='eliminar' type="" onClick={ props.handleRemoveTask } > Eliminar </button> </div> </div> </div> ) } <file_sep>export default { apiKey: "<KEY>", authDomain: "task-641d2.firebaseapp.com", databaseURL: "https://task-641d2.firebaseio.com", projectId: "task-641d2", storageBucket: "task-641d2.appspot.com", messagingSenderId: "519131542761", appId: "1:519131542761:web:2b8f91ad616c75ae786c78" }<file_sep>// Configuracion esencial para el proyecto encuento a css. // Autor: Ghobbit. // Desarrollador Frontend y Diseñador gráfico: <NAME>. // Email: <EMAIL>; // Twitter: @duwahiner. import Deehk from '../components/Deehk'; export default Deehk;
8b7f1179d6f0fa35503bfe0866a2b522c022ad4c
[ "JavaScript" ]
3
JavaScript
Duwahiner/deehk-firebase
3cd46598d235b6fc61d18c3965224c8417ccf955
2d3825d5f103840dc0d5b115bedfa764960d38ed
refs/heads/master
<file_sep>from model import * from data_import import * import sys, getopt from scipy.io import wavfile from scipy import signal import os class Denoising(): """ Denoising Class holds all the necessary functions for denoising the noisy samples. """ def __init__(self, noisy_speech_folder='', sampled_noisy_speech_folder='', modfolder=''): self.modfolder = modfolder self.noisy_speech_folder = noisy_speech_folder self.sampled_noisy_speech_folder = sampled_noisy_speech_folder # SAMPLING FUNCTION def sampling(self): ''' Converts the input noisy audio files into required format and samples it to 16kHz. ''' fs = 16000 filelist = os.listdir("%s"%(self.noisy_speech_folder)) filelist = [f for f in filelist if f.endswith(".wav")] if not os.path.exists(self.sampled_noisy_speech_folder): os.makedirs(self.sampled_noisy_speech_folder) for i in tqdm(filelist): sr, y = wavfile.read("%s/%s" % (self.noisy_speech_folder, i)) if y.dtype == 'int16': nb_bits = 16 # -> 16-bit wav files elif y.dtype == 'int32': nb_bits = 32 # -> 32-bit wav files # converting to 32 point floating values y_float = y.astype(float) / (2.0**(nb_bits-1) + 1) # sampling to 16kHz samples = round(len(y_float) * fs/sr) # Number of samples to downsample Y = signal.resample(y_float, int(samples)) wavfile.write(os.path.join(self.sampled_noisy_speech_folder, str(i)), fs, Y) print "Converted all the input noisy samples to required format. The corresponding sampled audio files are present in the specified folder." # INFERENCE FUNCTION def inference(self, SE_LAYERS = 13, SE_CHANNELS = 64, SE_NORM = "NM", fs = 16000): ''' Denoises the noisy samples and produces the corresponding denoised samples in the specified path. Args: SE_LAYERS (int) : Number of Internal Layers of the SENET model SE_CHANNELS (int) : Number of feature channels per layer SE_NORM (string) : Type of layer normalization (NM, SBN or None) fs (int) : Sampling frequency or rate ''' datafolder = self.sampled_noisy_speech_folder if datafolder[-1] == '/': datafolder = datafolder[:-1] if not os.path.exists(datafolder+'_denoised'): os.makedirs(datafolder+'_denoised') # LOAD DATA dataset = load_noisy_data_list(valfolder = datafolder) dataset = load_noisy_data(dataset) # SET LOSS FUNCTIONS AND PLACEHOLDERS with tf.variable_scope(tf.get_variable_scope()): input=tf.placeholder(tf.float32,shape=[None,1,None,1]) clean=tf.placeholder(tf.float32,shape=[None,1,None,1]) enhanced=senet(input, n_layers=SE_LAYERS, norm_type=SE_NORM, n_channels=SE_CHANNELS) # INITIALIZE GPU CONFIG config=tf.ConfigProto() # config.gpu_options.allow_growth=True sess=tf.Session(config=config) print "Config ready" sess.run(tf.global_variables_initializer()) print "Session initialized" saver = tf.train.Saver([var for var in tf.trainable_variables() if var.name.startswith("se_")]) saver.restore(sess, "%s/se_model.ckpt" % self.modfolder) for id in tqdm(range(0, len(dataset["innames"]))): i = id # NON-RANDOMIZED ITERATION INDEX inputData = dataset["inaudio"][i] # LOAD DEGRADED INPUT # VALIDATION ITERATION output = sess.run([enhanced], feed_dict={input: inputData}) output = np.reshape(output, -1) wavfile.write("%s_denoised/%s" % (datafolder,dataset["shortnames"][i]), fs, output) print "Denoised samples of the corresponding noisy samples have been created in the mentioned folder." # MAIN # if __name__ == '__main__': # noisy_speech_folder = 'datasets/noisy_speech' # sampled_noisy_speech_folder = 'datasets/sampled_noisy_speech' # modfolder = "models" # denoise = Denoising(noisy_speech_folder=noisy_speech_folder, sampled_noisy_speech_folder=sampled_noisy_speech_folder, modfolder=modfolder) # denoise.sampling() # denoise.inference() # datafolder = sampled_noisy_speech_folder # inference(valfolder=datafolder, modfolder=modfolder) <file_sep>absl-py==0.8.0 aniso8601==8.0.0 astor==0.8.0 backports.weakref==1.0.post1 Click==7.0 enum34==1.1.6 Flask==1.1.1 Flask-HTTPAuth==3.3.0 Flask-RESTful==0.3.7 funcsigs==1.0.2 futures==3.3.0 gast==0.3.2 google-pasta==0.1.7 grpcio==1.23.0 h5py==2.10.0 itsdangerous==1.1.0 Jinja2==2.10.1 Keras-Applications==1.0.8 Keras-Preprocessing==1.1.0 Markdown==3.1.1 MarkupSafe==1.1.1 mock==3.0.5 numpy==1.16.5 protobuf==3.9.1 pytz==2019.2 scipy==1.2.2 six==1.12.0 tensorboard==1.14.0 tensorflow==1.14.0 tensorflow-estimator==1.14.0 termcolor==1.1.0 tqdm==4.36.0 Werkzeug==0.15.6 wrapt==1.11.2 <file_sep>from flask import Flask, flash, request, redirect, render_template, send_from_directory import os from werkzeug.utils import secure_filename from denoising import Denoising path = os.path.dirname( os.path.realpath(__file__) ) noisy_speech_folder = os.path.join(path, 'datasets/noisy_speech') sampled_noisy_speech_folder = os.path.join(path, 'datasets/sampled_noisy_speech') modfolder = os.path.join(path, 'models') denoise = Denoising(noisy_speech_folder=noisy_speech_folder, sampled_noisy_speech_folder=sampled_noisy_speech_folder, modfolder=modfolder) UPLOAD_FOLDER = noisy_speech_folder DOWNLOAD_FOLDER = os.path.join(path,'datasets/sampled_noisy_speech_denoised') app = Flask(__name__) app.secret_key = "speech denoising" app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024 def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ['wav'] @app.route('/') def upload_form(): return render_template('upload.html') @app.route('/upload', methods=['POST']) def upload_file(): if request.method == 'POST': file = request.files['file'] if allowed_file(file.filename): filename = file.filename filename = secure_filename(filename) if os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], filename)): flash('File already exists. Please choose a different file') return render_template('upload.html') else: file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) flash('File successfully uploaded') return render_template('denoised_speech.html') else: flash('Only wav files are supported currently') return render_template('upload.html') else: return redirect(request.url) @app.route('/denoised_speech', methods=['GET', 'POST']) def speech_denoising(): denoise.sampling() denoise.inference() return render_template('success.html') @app.route('/download', methods=['GET']) def download_file(): return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename=filename, as_attachment=True) if __name__ == "__main__": app.run(debug=True)
540e5e344cbe3f6221aca96d1033d9543b04400f
[ "Python", "Text" ]
3
Python
zk1001/speechdenoising-1
fe4096d5c69f525bcdd6eb5e3976648728622fae
961a754b2c8a4baae1e3762ff849995814fa059d
refs/heads/master
<repo_name>RyanDool/google-map-csv-plotter<file_sep>/README.md # Google Map CSV Plotter A web application to aid in tracking current customers/users. The appliation accepts a .csv of 4 columns (Street, City, State and Zipcode) and connects to Google Maps API to obtain the coordinates and then plot the locations on a single map. For added functionality you may also enter a location into an input field and upload an additional csv so that you may check if your customers/users are sharing the same geographic area. ## Getting Started 1. Obtain a Google Maps API Key, instructions can be found [here](https://developers.google.com/maps/documentation/javascript/get-api-key). 2. Update this line: ``` <script src='//maps.google.com/maps/api/js?key=[API KEY]'></script> ``` replacing [API KEY] with the key obtained. 3. Update $upload_location (location where your csv files will be stored) to reflect your file structure. 4. Testing. 4. Style to meet your needs. ## Authors <NAME><file_sep>/plotter.php <?php $csv = array(); $addy_arr = []; $addy_arr_two = []; $upload_location = '[PATH TO CSV UPLOAD LOCATION]'; if(isset($_POST["submit"])){ if(!empty($_POST["location_address"]) || !empty($_POST["location_address_two"])){ $fac_array = []; $location_address = ""; if(!empty($_POST["location_address"])){ $location_address = $_POST["location_address"]; $location_address = str_replace(" ", "+", $location_address); array_push($fac_array, $location_address); } if(!empty($_POST["location_address_two"])){ $location_address = $_POST["location_address_two"]; $location_address = str_replace(" ", "+", $location_address); array_push($fac_array, $location_address); } $fac_array = json_encode($fac_array); echo "<script> var fac_array = ". $fac_array . ";\n </script>"; } if(empty($_FILES["file"]["type"])){ echo "No file selected"; }else{ $storagename = $_FILES["file"]["name"]; move_uploaded_file($_FILES["file"]["tmp_name"], $upload_location . $storagename); $storedin = $upload_location . $_FILES["file"]["name"]; $handle = fopen($storedin, "r"); if(($handle = fopen($storedin, 'r')) !== FALSE){ set_time_limit(0); $row = 0; while(($line = fgetcsv($handle)) !== FALSE){ $line = str_replace(" ", "+", $line); $immmp = implode("+", $line); array_push($addy_arr, $immmp); } fclose($handle); $js_array = json_encode($addy_arr); echo "<script> var javascript_array = ". $js_array . ";\n </script>"; if(!empty($_FILES["file_two"]["type"])){ $storagename_two = $_FILES["file_two"]["name"]; move_uploaded_file($_FILES["file_two"]["tmp_name"], $upload_location . $storagename_two); $storedin_two = $upload_location . $_FILES["file_two"]["name"]; $handle_two = fopen($storedin_two, "r"); if(($handle_two = fopen($storedin_two, 'r')) !== FALSE){ set_time_limit(0); $row_two = 0; while(($line_two = fgetcsv($handle_two)) !== FALSE){ $line_two = str_replace(" ", "+", $line_two); $immmp_two = implode("+", $line_two); array_push($addy_arr_two, $immmp_two); } fclose($handle_two); $js_array_two = json_encode($addy_arr_two); echo "<script> var javascript_array_two = ". $js_array_two . ";\n </script>"; echo "<script type='text/javascript'> window.onload = function(){ myCustomers(); } </script>"; } }else{ echo "<script type='text/javascript'> window.onload = function(){ myCustomers(); } </script>"; } } } } ?> <html lang="en-US" class="external-links ua-brand-icons"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=yes"> <meta name="MobileOptimized" content="width"> <meta name="HandheldFriendly" content="true"> <title>Plotting Tool</title> <link href='//fonts.googleapis.com/css?family=Open Sans:300,400,600,700' rel='stylesheet' type='text/css'> <!-- <script src='//maps.google.com/maps/api/js?key=[API KEY]'></script> --> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <link href='styles.css' rel='stylesheet' type='text/css'> </head> <body> <div id="plotter_container"> <div id="plotter_inner"> <header></header> <div id="plooter" class="plotter_container"> <form action="" method="POST" enctype="multipart/form-data" class="plotter_form wrapper"> <fieldset> <input type="text" name="location_address" id="location_address" class="plotter_input" /> <label for="location_address" class="plotter_label">OPTIONAL: Facility Address (Street City, State Zip)<img src="http://maps.google.com/mapfiles/ms/icons/red-pushpin.png"></label> <input type="file" name="file" value="file" id="file_select" class="plotter_input" /> <label for="file_select" class="plotter_label">File Containing Customer Addresses (must be CSV)</label> <div id="hideme"> <input type="text" name="location_address_two" id="location_address_two" class="plotter_input" /> <label for="location_address_two" class="plotter_label">OPTIONAL: Facility Address (Street City, State Zip)<img src="http://maps.google.com/mapfiles/ms/icons/blue-pushpin.png"></label> <input type="file" name="file_two" value="file_two" id="file_select_two" class="plotter_input" /> <label for="file_select_two" class="plotter_label">File Containing Customer Addresses (must be CSV)</label> </div> <div class="multiple_warning"> <span>Do you have an additional customer list you would like plotted on the same map? <input type="checkbox" class="additional_locations" value="1" name="additional" /></span> <strong>NOTE:</strong> this feature should be used sparingly, its inteded use is for facilities in close proximity with one another. </div> <input type="submit" name="submit" value="Submit" class="plotter_submit" /> </fieldset> </form> <div id="map_canvas"></div> </div> </div> </div> <footer></footer> <script> $(function(){ $('.additional_locations').click(function(){ if($('input.additional_locations').prop('checked') == false) { $('input#location_address_two').val(''); $('input#file_select_two').val(''); } $('#hideme').slideToggle(); }) }) function myCustomers(){ let address_index = 1; let address_two_index = 0; let fac_addy_index = 0; let geocoder; let map; let elevator; let myOptions = { zoom: 2, center: new google.maps.LatLng(0, 0), }; map = new google.maps.Map($('#map_canvas')[0], myOptions); let addresses = javascript_array; let bounds = new google.maps.LatLngBounds(); if(typeof fac_array !== 'undefined'){ let fac_addresses = fac_array; addfacilitymarkers(); } if(typeof javascript_array_two !== 'undefined'){ let addresses_two = javascript_array_two; addMapMarker(addresses_two, 'blue'); } addMapMarker(addresses, 'red'); // function addfacilitymarkers(){ let fac_address = fac_addresses[fac_addy_index]; if(fac_address.length){ $.getJSON('//maps.googleapis.com/maps/api/geocode/json?address='+fac_address, null, function (data){ if(data.results.length > 0){ let fp = data.results[0].geometry.location; let latlng = new google.maps.LatLng(fp.lat, fp.lng); bounds.extend(latlng); if(fac_addy_index == 0){ icon = "http://maps.google.com/mapfiles/ms/icons/red-pushpin.png"; } if(fac_addy_index == 1){ icon = "http://maps.google.com/mapfiles/ms/icons/blue-pushpin.png"; } new google.maps.Marker({ position: latlng, map: map, icon: new google.maps.MarkerImage(icon) }); map.fitBounds(bounds); } nextFacAddress(); }); } } function nextFacAddress(){ fac_addy_index++; if(fac_addy_index < fac_addresses.length){ addfacilitymarkers(); } } function addMapMarker(address_arr, pincolor){ let address = address_arr[address_arr_index]; if(address.length){ $.getJSON('//maps.googleapis.com/maps/api/geocode/json?address='+address, null, function(data){ if(data.results.length > 0){ let p = data.results[0].geometry.location; let latlng = new google.maps.LatLng(p.lat, p.lng); bounds.extend(latlng); icon = "http://maps.google.com/mapfiles/ms/icons/"+pincolor+"-dot.png"; new google.maps.Marker({ position: latlng, map: map, icon: new google.maps.MarkerImage(icon) }); map.fitBounds(bounds); } address_arr_index++; if(address_arr_index < address_arr.length){ addMapMarker(address_arr, pincolor); } }); }else{ address_arr_index++; if(address_arr_index < address_arr.length){ addMapMarker(address_arr, pincolor); } } } } </script> </body> </html>
d8cac42c06f96b7d212c608fd9152c1d0825daef
[ "Markdown", "PHP" ]
2
Markdown
RyanDool/google-map-csv-plotter
398e220fbc20bff1e4aa5b9d063647f3469eeac5
da6c48dd3e6bc803b8cd5955b07af8f8956b600c
refs/heads/master
<repo_name>CharnjeetIotasol/ProtectedBrowser<file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/DummyFileUpload/DummyTableForFileViewModel.cs using ProtectedBrowser.Framework.ViewModels.Upload; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.DummyFileUpload { public class DummyTableForFileViewModel:BaseViewEntity { [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("createdBy")] public long? CreatedBy { get; set; } [JsonProperty("updatedBy")] public long? UpdatedBy { get; set; } [JsonProperty("createdOn")] public DateTimeOffset? CreatedOn { get; set; } [JsonProperty("updatedOn")] public DateTimeOffset? UpdatedOn { get; set; } [JsonProperty("isDeleted")] public bool? IsDeleted { get; set; } [JsonProperty("isActive")] public bool? IsActive { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("fileGroupItems")] public List<FileGroupItemsViewModel> FileGroupItems { get; set; } [JsonProperty("fileGroupItem")] public FileGroupItemsViewModel FileGroupItem { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/PublicHoliday/PublicHolidayService.cs using ProtectedBrowser.DBRepository.PublicHoliday; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ProtectedBrowser.Domain; using ProtectedBrowser.Domain.PublicHoliday; namespace ProtectedBrowser.Service.PublicHoliday { public class PublicHolidayService : IPublicHolidayService { private PublicHolidayDBService _publicHolidayDBService; public PublicHolidayService() { _publicHolidayDBService = new PublicHolidayDBService(); } public long PublicHolidayInsert(PublicHolidaysModel model) { return _publicHolidayDBService.PublicHolidayInsert(model); } public List<PublicHolidaysModel> PublicHolidaysSelect(SearchParam param) { return _publicHolidayDBService.PublicHolidaysSelect(param); } public void PublicHolidayUpdate(PublicHolidaysModel model) { _publicHolidayDBService.PublicHolidayUpdate(model); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Common/Extensions/XmlExtension.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace ProtectedBrowser.Common.Extensions { public static class XmlExtension { public static T? GetValue<T>(this XElement xAttr) where T : struct { if (xAttr == null) return default(T); return (T)Convert.ChangeType(xAttr.Value, typeof(T)); } public static string GetStrValue(this XElement xAttr) { if (xAttr == null) return null; return xAttr.Value; } public static DateTimeOffset? GetDateOffset(this XElement element) { if (element == null) return null; try { return DateTimeOffset.Parse(element.Value); } catch { return null; } } public static DateTime? GetDate(this XElement element) { if (element == null) return null; try { return DateTime.Parse(element.Value); } catch { return null; } } public static bool? GetBoolVal(this XElement element) { if (element == null) return null; int a = 0; if (!int.TryParse(element.Value, out a)) return null; else if(element.Value == "1" || element.Value=="0" ) return element.Value == "1"? true :false; bool b; if (!bool.TryParse(element.Value, out b)) return null; return b; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Common/Enums/EmailConfigurationKey.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Common.Enums { public enum EmailConfigurationKey { EmailVerification, AccountActivated, AccountDeactivated, ForgotPassword, ContactEnquiry } public enum UserRegistered { AlreadyRegister, NowRegitered, Failed } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/Category/CategoryViewModel.cs using Newtonsoft.Json; using System; namespace IotasmartBuild.Framework.ViewModels.Category { public class CategoryViewModel { [JsonProperty("id")] public long CategoryId { get; set; } [JsonProperty("name")] public string CategoryName { get; set; } [JsonProperty("isActive")] public bool IsActive { get; set; } [JsonProperty("isDeleted")] public bool IsDeleted { get; set; } [JsonProperty("createdBy")] public long? CreatedBy { get; set; } [JsonProperty("createdOn")] public DateTimeOffset CreateOn { get; set; } [JsonProperty("updatedOn")] public DateTimeOffset UpdatedOn { get; set; } [JsonProperty("overallCount")] public int OverAllCount { get; set; } [JsonProperty("updatedBy")] public long? UpdatedBy { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/Appointment/AppointmentViewModel.cs using ProtectedBrowser.Framework.ViewModels.User; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.Appointment { public class AppointmentViewModel:BaseViewEntity { [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("createdBy")] public long? CreatedBy { get; set; } [JsonProperty("updatedBy")] public long? UpdatedBy { get; set; } [JsonProperty("createdOn")] public DateTimeOffset? CreatedOn { get; set; } [JsonProperty("updatedOn")] public DateTimeOffset? UpdatedOn { get; set; } [JsonProperty("isDeleted")] public bool? IsDeleted { get; set; } [JsonProperty("isActive")] public bool? IsActive { get; set; } [JsonProperty("appointmentDate")] public DateTimeOffset? AppointmentDate { get; set; } [JsonProperty("note")] public string Note { get; set; } [JsonProperty("status")] public string Status { get; set; } [JsonProperty("isCancel")] public bool? IsCancel { get; set; } [JsonProperty("cancellationReason")] public string CancellationReason { get; set; } [JsonProperty("startTime")] public TimeSpan? StartTime { get; set; } [JsonProperty("endTime")] public TimeSpan? EndTime { get; set; } [JsonProperty("isAppointmentDone")] public bool? isAppointmentDone { get; set; } [JsonProperty("toUserId")] public long? ToUserId { get; set; } [JsonProperty("fromUserId")] public long? FromUserId { get; set; } [JsonProperty("totalCount")] public int TotalCount { get; set; } [JsonProperty("isRescheduled")] public bool? IsRescheduled { get; set; } [JsonProperty("toUser")] public UserViewModel ToUser { get; set; } [JsonProperty("fromUser")] public UserViewModel FromUser { get; set; } } public class AppointmentTimeSlotViewModel { [JsonProperty("startTime")] public string StartTime { get; set; } [JsonProperty("endTime")] public string EndTime { get; set; } [JsonProperty("isBooked")] public bool IsBooked { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/Configuration/EmailConfigurationDBService.cs using ProtectedBrowser.Domain.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.Configuration { public class EmailConfigurationDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public EmailConfigurationModel EmailConfigurationSelect(string configurationKey) { using (var dbctx = DbContext) { return dbctx.EmailConfigurationSelect(configurationKey).Select(x => new EmailConfigurationModel { ConfigurationKey = x.ConfigurationKey, ConfigurationValue = x.ConfigurationValue, EmailSubject = x.EmailSubject, Id = x.Id }).FirstOrDefault(); } } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Exception/IExceptionService.cs using ProtectedBrowser.Domain.Exception; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Exception { public interface IExceptionService { void InsertLog(ExceptionModel exception); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/Exception/ExceptionModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.Exception { public class ExceptionModel { public string Source { get; set; } public string Message { get; set; } public string StackTrace { get; set; } public string Uri { get; set; } public string Method { get; set; } public long? CreatedBy { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/BasicEntityToBasicViewEntity.cs using ProtectedBrowser.Domain; using ProtectedBrowser.Framework.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework { public static class BasicEntityToBasicViewEntity { public static CreatedUserViewModel ToViewModel(this CreatedUserModel x) { if (x == null) return new CreatedUserViewModel(); return new CreatedUserViewModel { UserId = x.UserId, FirstName = x.FirstName, LastName = x.LastName, PhoneNumber = x.PhoneNumber, FullName = x.FirstName + " " + x.LastName }; } public static UpdatedUserViewModel ToViewModel(this UpdatedUserModel x) { if (x == null) return new UpdatedUserViewModel(); return new UpdatedUserViewModel { UserId = x.UserId, FirstName = x.FirstName, LastName = x.LastName, PhoneNumber = x.PhoneNumber, FullName = x.FirstName + " " + x.LastName }; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/DailyWorkSetting/DailyWorkSettingViewModel.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.DailyWorkSetting { public class DailyWorkSettingViewModel { [JsonProperty("id")] public int? Id { get; set; } [JsonProperty("sunday")] public bool? Sunday { get; set; } [JsonProperty("monday")] public bool? Monday { get; set; } [JsonProperty("tuesday")] public bool? Tuesday { get; set; } [JsonProperty("wednesday")] public bool? Wednesday { get; set; } [JsonProperty("thursday")] public bool? Thursday { get; set; } [JsonProperty("friday")] public bool? Friday { get; set; } [JsonProperty("saturday")] public bool? Saturday { get; set; } [JsonProperty("startTime")] public TimeSpan? StartTime { get; set; } [JsonProperty("endTime")] public TimeSpan? EndTime { get; set; } [JsonProperty("startLunchTime")] public TimeSpan? StartLunchTime { get; set; } [JsonProperty("endLunchTime")] public TimeSpan? EndLunchTime { get; set; } [JsonProperty("createdBy")] public long? CreatedBy { get; set; } [JsonProperty("updatedBy")] public long? UpdatedBy { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/Directory/DirectoryModelViewModelConverter.cs using ProtectedBrowser.Domain.Directory; using ProtectedBrowser.Framework.ViewModels.Directory; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.WebExtensions { public static class DirectoryModelViewModelConverter { public static DirectoryViewModel ToViewModel(this DirectoryModel x) { if (x == null) return new DirectoryViewModel(); return new DirectoryViewModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, RootPath = x.RootPath, UserName = x.UserName, Password = <PASSWORD>, Name = x.Name, TotalCount=x.TotalCount }; } public static DirectoryModel ToModel(this DirectoryViewModel x) { if (x == null) return new DirectoryModel(); return new DirectoryModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, RootPath = x.RootPath, UserName = x.UserName, Password = <PASSWORD>, Name = x.Name, }; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Common/Constants/EmailConstants.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Common.Constants { public class EmailConstants { public const string CONFIRM_YOUR_ACCOUNT = "Confirm Your Account"; public const string FORGOT_PASSWORD = "<PASSWORD>"; public const string ACCOUNT_ACTIVATED = "Account Activated"; public const string ACCOUNT_DEACTIVATED = "Account Deactivated"; public const string CONTACT_ENQUIRY = "Contact Enquiry"; } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Exception/ExceptionService.cs using ProtectedBrowser.DBRepository.Exception; using ProtectedBrowser.Domain.Exception; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Exception { public class ExceptionService { public ExceptionDBService _ExceptionDBService; public ExceptionService() { _ExceptionDBService = new ExceptionDBService(); } public void InsertLog(ExceptionModel exception ) { _ExceptionDBService.ExceptionLogInsert(exception); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/Blog/BlogModelViewModelConverter.cs using IotasmartBuild.Framework.ViewModels.Category; using ProtectedBrowser.Domain.Blog; using ProtectedBrowser.Framework.WebExtensions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IotasmartBuild.Framework.ViewModels.Blog { public static class BlogModelViewModelConverter { public static BlogModel ToModel(this BlogViewModel x) { if (x == null) return new BlogModel(); return new BlogModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsActive = x.IsActive, Title = x.Title, Description = x.Description, CategoryId = x.CategoryId, Category = x.Category != null ? x.Category.ToModel() : null, FileGroupItem = x.FileGroupItem != null ? x.FileGroupItem.ToModel() : null, FileId=x.FileId, FileName=x.FileName, FileUrl=x.FileUrl, CategoryName=x.CategoryName, IsDeleted=x.IsDeleted }; } public static BlogViewModel ToViewModel(this BlogModel x) { if (x == null) return new BlogViewModel(); return new BlogViewModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsActive = x.IsActive, Title = x.Title, Description = x.Description, CategoryId = x.CategoryId, Category = x.Category != null ? x.Category.ToViewModel() : null, FileGroupItem = x.FileGroupItem != null ? x.FileGroupItem.ToViewModel() : null, FileId = x.FileId, FileName = x.FileName, FileUrl = x.FileUrl, CategoryName=x.CategoryName, IsDeleted = x.IsDeleted }; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/SearchParam.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain { public class SearchParam { public long? Id { get; set; } public long? CategoryId { get; set; } public long? UserId { get; set; } public long? ToUserId { get; set; } public long? FromUserId { get; set; } public string Type { get; set; } public int? Next { get; set; } public int? Offset { get; set; } public DateTimeOffset? AppointmentDate { get; set; } public DateTimeOffset? StartDate { get; set; } public DateTimeOffset? EndDate { get; set; } public DateTimeOffset? ToDayDate { get; set; } } } <file_sep>/ProtectedBrowser/EmailSender/EmailSenders.cs using System; using System.Threading.Tasks; using SendGrid.Helpers.Mail; using System.Configuration; namespace IotasmartBuild.EmailSender { public class EmailSenders { public static async Task SendEmail(string toMail, string subject, string messageBody, string filepath = null, string CC = "", string BCC = "" ,string fromName = "Vanworld") { String apiKey = MailInfo.SENDGRIDAPIKEY; dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://api.sendgrid.com"); Email from = new Email(MailInfo.FROMEMAILADDRESS); Email to = new Email(toMail); Content content = new Content("text/html", messageBody); Mail mail = new Mail(from, subject, to, content); // Email email = new Email("<EMAIL>", fromName); // mail.Personalization[0].AddTo(email); dynamic response = await sg.client.mail.send.post(requestBody: mail.Get()); } } internal class MailInfo { public readonly static string FROMEMAILADDRESS = ConfigurationManager.AppSettings["FROMEMAILADDRESS"]; public readonly static string SMTPUSERNAME = ConfigurationManager.AppSettings["SMTPUSERNAME"]; public readonly static string SMTPPASSWORD = ConfigurationManager.AppSettings["SMTPPASSWORD"]; public readonly static string SMTPSERVER = ConfigurationManager.AppSettings["SMTPSERVER"]; public readonly static bool SMTPISSSL = Boolean.Parse(ConfigurationManager.AppSettings["SMTPISSSL"]); public readonly static int SMTPSERVERPORT = int.Parse(ConfigurationManager.AppSettings["SMTPSERVERPORT"]); public readonly static string SENDGRIDAPIKEY = ConfigurationManager.AppSettings["SENDGRIDAPIKEY"]; } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/Blog/BlogModel.cs using ProtectedBrowser.Domain.Category; using ProtectedBrowser.Domain.Upload; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.Blog { public class BlogModel { public long Id { get; set; } public string Title { get; set; } public string Description { get; set; } public Nullable<long> CategoryId { get; set; } public string CategoryName { get; set; } public bool IsActive { get; set; } public Nullable<System.DateTimeOffset> CreatedOn { get; set; } public Nullable<long> CreatedBy { get; set; } public Nullable<System.DateTimeOffset> UpdatedOn { get; set; } public Nullable<long> UpdatedBy { get; set; } public Nullable<int> TotalCount { get; set; } public bool IsDeleted { get; set; } public CategoryModel Category { get; set; } public FileGroupItemsModel FileGroupItem { get; set; } public long? FileId { get; set; } public string FileUrl { get; set; } public string FileName { get; set; } } } <file_sep>/ProtectedBrowser/wwwroot/angular/pages/Blog/BlogEditController.js (function () { var applicationApp = angular.module("applicationApp"); applicationApp.controller("BlogEditController", blogController); blogController.$inject = ["$scope", "$state", "$timeout", "BlogRepository", "$filter", "$stateParams", "FileUploader", "$q"]; function blogController($scope, $state, $timeout, AccessRepository, $filter, $stateParams, FileUploader, $q) { var vm = this; vm.save = save; vm.cancel = cancel; vm.remove = remove; vm.tinymceOptions = { menubar: false, plugins: 'link image code', min_height: 250, resize: false }; function init() { vm.record = { isActive: true }; vm.record.file = {}; var promies = []; vm.isNewRecord = $stateParams.id == 0; promies.push(AccessRepository.fetchAll().$promise); if (!vm.isNewRecord) { promies.push(AccessRepository.getBlogById({ "id": vm.recordId }).$promise); } $q.all(promies).then(function (response) { vm.loading = false; vm.categoryList = response[0].data; if (!vm.isNewRecord) { vm.record = response[1].data; } }).catch(function (error) { vm.loading = false; }); } init(); vm.uploader = $scope.uploader = new FileUploader({ url: secureApiBaseUrl + 'file/upload', autoUpload: true }); vm.uploader.onSuccessItem = function (fileItem, response, status, headers) { response.targetType = "Catalog"; vm.record.file = response; }; function save(bol) { vm.onClickValidation = !bol; if (!bol) { return; } if (vm.record.file == null) { showTost("Error:", "Image is Required", "danger"); return; } if (vm.uploader.progress > 0 && vm.uploader.progress < 100) { showTost("Error:", "image upload in processing", "danger"); return; } var method = "addBlogs"; if (!vm.isNewRecord) { method = "updateBlogs" } AccessRepository[method](vm.record, function (data) { if (!data.status) { showTost("Error:", data.message, "danger"); return; } showTost("Success:", data.message, "success"); vm.cancel(); }, function (error) { showTost("Error:", error.data.message, "danger"); }); } function cancel() { $state.go("BlogList"); } function remove(id) { customDeleteConfirmation(removeRecordCallback, id); } function removeRecordCallback(recordId) { AttachmentRepository.remove({ id: recordId }, function (response) { sweetAlert.close(); if (!response.status) { showTost("Error:", response.message, "danger"); return; } showTost("Success:", "Record Deleted Successfully", "success"); vm.record.file = {}; }, function (error) { sweetAlert.close(); showTost("Error:", "Some Things went wrong.", "danger"); }); } } }()); <file_sep>/ProtectedBrowser/API/CategoryController.cs using IotasmartBuild.Framework.ViewModels.Category; using ProtectedBrowser.Domain; using ProtectedBrowser.Framework.CustomFilters; using ProtectedBrowser.Framework.GenericResponse; using ProtectedBrowser.Framework.WebExtensions; using ProtectedBrowser.Service.Category; using Microsoft.AspNet.Identity; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ProtectedBrowser.API { [RoutePrefix("api")] [CustomExceptionFilter] public class CategoryController : ApiController { private ICategoryService _categoryService; public CategoryController(ICategoryService categoryService) { _categoryService = categoryService; } /// <summary> /// Api use for get all categories /// </summary> /// <returns></returns> [Route("categories")] [HttpGet] public IHttpActionResult GetAllCategories([FromUri] SearchParam param) { if (param != null && param.Next != null && param.Offset != null) { var categoriesInternal = _categoryService.CategorySelect(null, null, param.Next, param.Offset).Select(x => x.ToViewModel()); return Ok(categoriesInternal.SuccessResponse()); } var categories = _categoryService.CategorySelect(null, null, null, null).Select(x => x.ToViewModel()); return Ok(categories.SuccessResponse()); } [Route("active-categories/{pageSize:int}/{pageNumber:int}")] [HttpGet] public IHttpActionResult ActiveCategories(int pageSize = 10, int pageNumber = 1) { var categories = _categoryService.CategorySelect(null, true, pageSize, pageNumber).Select(x => x.ToViewModel()); ; return Ok(categories.SuccessResponse()); } /// <summary> /// Api use for get category by id /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("category/{id:long}")] [HttpGet] public IHttpActionResult GetCategory(long id) { var category = _categoryService.CategorySelect(id, null).FirstOrDefault().ToViewModel(); return Ok(category.SuccessResponse()); } /// <summary> /// Api use for save category /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("category")] [Authorize(Roles = "ROLE_ADMIN")] [HttpPost] public IHttpActionResult SaveCategory(CategoryViewModel model) { model.CreatedBy = User.Identity.GetUserId<long>(); var categoryId = _categoryService.CategoryInsert(model.ToModel()); return Ok(categoryId.SuccessResponse("Category save successfully")); } /// <summary> /// Api use for update category /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("category")] [Authorize(Roles = "ROLE_ADMIN")] [HttpPut] public IHttpActionResult UpdateCategory(CategoryViewModel model) { model.UpdatedBy = User.Identity.GetUserId<long>(); _categoryService.CategoryUpdate(model.ToModel()); return Ok("Category Update successfully".SuccessResponse()); } /// <summary> /// Api use for delete category by id /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("category/{id:long}")] [Authorize(Roles = "ROLE_ADMIN")] [HttpDelete] public IHttpActionResult DeleteCategory(long id) { CategoryViewModel model = new CategoryViewModel(); model.CategoryId = id; model.IsDeleted = true; model.UpdatedBy = User.Identity.GetUserId<long>(); _categoryService.CategoryUpdate(model.ToModel()); return Ok("Category Deleted successfully".SuccessResponse()); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/Leave/LeaveViewModel.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.Leave { public class LeaveViewModel { [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("createdBy")] public long? CreatedBy { get; set; } [JsonProperty("updatedBy")] public long? UpdatedBy { get; set; } [JsonProperty("createdOn")] public DateTimeOffset? CreatedOn { get; set; } [JsonProperty("updatedOn")] public DateTimeOffset? UpdatedOn { get; set; } [JsonProperty("isDeleted")] public bool? IsDeleted { get; set; } [JsonProperty("isActive")] public bool? IsActive { get; set; } [JsonProperty("startDate")] public DateTimeOffset? StartDate { get; set; } [JsonProperty("endDate")] public DateTimeOffset? EndDate { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("userId")] public long? UserId { get; set; } [JsonProperty("startTime")] public TimeSpan? StartTime { get; set; } [JsonProperty("endTime")] public TimeSpan? EndTime { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("totalCount")] public int TotalCount { get; set; } [JsonProperty("fullName")] public string FullName { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Database/dbo/Stored Procedures/DirectoryUpdate.sql -- ============================================= -- Author: <Author,,Name> -- Create date: <Create Date,,> -- Description: <Description,,> -- ============================================= CREATE PROCEDURE DirectoryUpdate @Id BIGINT=NULL, @CreatedBy BIGINT=NULL, @UpdatedBy BIGINT=NULL, @CreatedOn DATETIMEOFFSET(7)=NULL, @UpdatedOn DATETIMEOFFSET(7)=NULL, @IsDeleted BIT=NULL, @IsActive BIT=NULL, @RootPath NVARCHAR(MAX)=NULL, @UserName NVARCHAR(MAX)=NULL, @Password NVARCHAR(MAX)=NULL, @Name NVARCHAR(MAX)=NULL AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; UPDATE [Directory] SET [UpdatedBy] = ISNULL(@UpdatedBy,[UpdatedBy]), [UpdatedOn] = switchoffset(sysdatetimeoffset(),'+00:00'), [IsDeleted] = ISNULL(@IsDeleted,[IsDeleted]), [IsActive] = ISNULL(@IsActive,[IsActive]), [RootPath] = ISNULL(@RootPath,[RootPath]), [UserName] = ISNULL(@UserName,[UserName]), [Password] = ISNULL(@Password,[Password]), [Name] = ISNULL(@Name,[Name]) WHERE ( Id=@Id ) END<file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/ContactUs/IContactUsService.cs using ProtectedBrowser.Domain.ContactUs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.ContactUs { public interface IContactUsService { void ContactUsInsert(ContactUsModel model); void ContactUsDelete(long? id); List<ContactUsModel> ContactUsSelect(long? id, int? next = null, int? offset = null); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Leave/LeaveService.cs using ProtectedBrowser.DBRepository.Leave; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ProtectedBrowser.Domain; using ProtectedBrowser.Domain.Leave; namespace ProtectedBrowser.Service.Leave { public class LeaveService:ILeaveService { private LeaveDBService _leaveDBService; public LeaveService() { _leaveDBService = new LeaveDBService(); } public long LeaveInsert(LeaveModel model) { return _leaveDBService.LeaveInsert(model); } public List<LeaveModel> LeaveSelect(SearchParam param) { return _leaveDBService.LeaveSelect(param); } public void LeaveUpdate(LeaveModel model) { _leaveDBService.LeaveUpdate(model); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/FileGroup/IFileGroupService.cs using ProtectedBrowser.Domain.Upload; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.FileGroup { public interface IFileGroupService { /// <summary> /// Save list of attachement image/file /// </summary> /// <param name="userId"></param> /// <param name="galleryId"></param> /// <param name="attachmentFileXml"></param> void FileGroupItemsInsertXml(long? userId, long? typeId, string attachmentFileXml); /// <summary> /// Soft Delete image/file from DB /// </summary> /// <param name="id"></param> /// <param name="updatedBy"></param> void FileGroupItemsDelete(long? id, long? updatedBy); /// <summary> /// Set the target path and move the file from temp folder to target folder /// </summary> /// <param name="model"></param> /// <param name="userId"></param> /// <returns>List Attachment file model</returns> List<FileGroupItemsModel> SetPathAndMoveFile(List<FileGroupItemsModel> model, long? userId); /// <summary> /// Save single file in DB /// </summary> /// <param name="model"></param> /// <returns></returns> long FileGroupItemsInsert(FileGroupItemsModel model); /// <summary> /// Set the target path and move the single file from temp folder to target folder /// </summary> /// <param name="model"></param> /// <param name="id"></param> /// <returns></returns> FileGroupItemsModel SetPathAndMoveSingleFile(FileGroupItemsModel model, long? id); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/UploadFile/UploadFileModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IotasmartBuild.Domain.UploadFile { public class UploadFileModel { public long Id { get; set; } public string FileName { get; set; } public string FileUrl { get; set; } public Nullable<System.DateTimeOffset> CreatedOn { get; set; } public bool IsDeleted { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Common/Constants/UserRole.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Common.Constants { public class UserRole { public const string Admin = "ROLE_ADMIN"; public const string User = "ROLE_USER"; } } <file_sep>/ProtectedBrowser/API/DirectoryController - Copy.cs using ProtectedBrowser.Framework.CustomFilters; using ProtectedBrowser.Framework.GenericResponse; using ProtectedBrowser.Framework.ViewModels.Directory; using ProtectedBrowser.Framework.WebExtensions; using ProtectedBrowser.Service.Directory; using Microsoft.AspNet.Identity; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.IO; using System.Runtime.InteropServices; using System.ComponentModel; using ProtectedBrowser.Domain.Directory; namespace ProtectedBrowser.API { [RoutePrefix("api")] [CustomExceptionFilter] public class DirectoryController : ApiController { private IDirectoryService _directoryService; public DirectoryController(IDirectoryService directoryService) { _directoryService = directoryService; } /// <summary> /// Api use for get all Directory /// </summary> /// <returns></returns> [Route("Directorys")] [Authorize(Roles = "ROLE_ADMIN")] [HttpGet] public IHttpActionResult GetAllDirectorys() { var directorys = _directoryService.SelectDirectory(null).Select(x => x.ToViewModel()); ; return Ok(directorys.SuccessResponse()); } /// <summary> /// Api use for get all Active Directory with Limit and Offset /// </summary> /// <returns></returns> [Route("active-directorys/{pageSize:int}/{pageNumber:int}")] [HttpGet] public IHttpActionResult ActiveDirectorys(int pageSize = 10, int pageNumber = 1) { var directorys = _directoryService.SelectDirectory(null, true, pageSize, pageNumber).Select(x => x.ToViewModel()); ; return Ok(directorys.SuccessResponse()); } /// <summary> /// Api use for get directory by id /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("directory/{id:long}")] [HttpGet] public IHttpActionResult GetDirectory(long id) { var directory = _directoryService.SelectDirectory(id).FirstOrDefault().ToViewModel(); return Ok(directory.SuccessResponse()); } /// <summary> /// Api use for save directory /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("directory")] [Authorize(Roles = "ROLE_ADMIN")] [HttpPost] public IHttpActionResult SaveDirectory(DirectoryViewModel model) { model.CreatedBy = User.Identity.GetUserId<long>(); model.UpdatedBy = User.Identity.GetUserId<long>(); var responseId = _directoryService.DirectoryInsert(model.ToModel()); return Ok(responseId.SuccessResponse("Directory save successfully")); } /// <summary> /// Api use for update directory /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("directory")] [Authorize(Roles = "ROLE_ADMIN")] [CustomExceptionFilter] [HttpPut] public IHttpActionResult UpdateDirectory(DirectoryViewModel model) { _directoryService.DirectoryUpdate(model.ToModel()); return Ok("Directory Update successfully".SuccessResponse()); } /// <summary> /// Api use for delete directory by id /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("directory/{id:long}")] [Authorize(Roles = "ROLE_ADMIN")] [CustomExceptionFilter] [HttpDelete] public IHttpActionResult DeleteDirectory(long id) { DirectoryViewModel model = new DirectoryViewModel(); model.Id = id; model.IsDeleted = true; _directoryService.DirectoryUpdate(model.ToModel()); return Ok("Directory Deleted successfully".SuccessResponse()); } [Route("getrootpath")] [HttpGet] [AllowAnonymous] public IHttpActionResult GetRootPath() { var directory = _directoryService.SelectDirectory(10002).FirstOrDefault().ToViewModel(); return Ok(directory.SuccessResponse()); } [Route("folderjson")] [HttpGet] [AllowAnonymous] public IHttpActionResult GetFolderJson(string sDir) { List<RawData> Files = new List<RawData>(); List<RawData> Folders = new List<RawData>(); var directory = _directoryService.SelectDirectory(10002).FirstOrDefault().ToViewModel(); string networkPath = directory.RootPath; NetworkCredential theNetworkCredential = new NetworkCredential(@directory.UserName, directory.Password); //using (new ConnectToSharedFolder(networkPath, theNetworkCredential)) //{ string[] files = Directory.GetFiles(sDir); string[] folders = Directory.GetDirectories(sDir); foreach (string file in files) { string[] x = file.Split('\\'); string name = x[x.Length - 1]; var f = new RawData { Name = name, Path = file, Type = "file", Ext = name.Split('.')[1] }; Files.Add(f); } foreach (string folder in folders) { string[] x = folder.Split('\\'); string name = x[x.Length - 1]; var f = new RawData { Name = name, Path = folder, Type = "folder", Ext = "" }; Folders.Add(f); } //} return Ok(new GetFilesFolder { Files = Files, Folders = Folders}.SuccessResponse()); } [Route("filereader")] [HttpGet] [AllowAnonymous] public IHttpActionResult Base64Encode(string sDir) { FileStream fs; var directory = _directoryService.SelectDirectory(10002).FirstOrDefault().ToViewModel(); string networkPath = directory.RootPath; NetworkCredential theNetworkCredential = new NetworkCredential(@directory.UserName, directory.Password); //using (new ConnectToSharedFolder(networkPath, theNetworkCredential)) //{ fs = File.Open(sDir, FileMode.Open); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); string str = Convert.ToBase64String(buffer); return Ok(new { stream = str }.SuccessResponse()); //} } } public class ConnectToSharedFolder : IDisposable { readonly string _networkName; public ConnectToSharedFolder(string networkName, NetworkCredential credentials) { _networkName = networkName; var netResource = new NetResource { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplaytype.Share, RemoteName = networkName }; var userName = string.IsNullOrEmpty(credentials.Domain) ? credentials.UserName : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName); var result = WNetAddConnection2( netResource, credentials.Password, userName, 0); if (result != 0) { throw new Win32Exception(result, "Error connecting to remote share"); } } ~ConnectToSharedFolder() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { WNetCancelConnection2(_networkName, 0, true); } [DllImport("mpr.dll")] private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flags); [DllImport("mpr.dll")] private static extern int WNetCancelConnection2(string name, int flags, bool force); [StructLayout(LayoutKind.Sequential)] public class NetResource { public ResourceScope Scope; public ResourceType ResourceType; public ResourceDisplaytype DisplayType; public int Usage; public string LocalName; public string RemoteName; public string Comment; public string Provider; } public enum ResourceScope : int { Connected = 1, GlobalNetwork, Remembered, Recent, Context }; public enum ResourceType : int { Any = 0, Disk = 1, Print = 2, Reserved = 8, } public enum ResourceDisplaytype : int { Generic = 0x0, Domain = 0x01, Server = 0x02, Share = 0x03, File = 0x04, Group = 0x05, Network = 0x06, Root = 0x07, Shareadmin = 0x08, Directory = 0x09, Tree = 0x0a, Ndscontainer = 0x0b } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Blog/IBlogService.cs using ProtectedBrowser.Domain.Blog; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Blog { public interface IBlogService { long BlogInsert(BlogModel model); void BlogUpdate(BlogModel model); List<BlogModel> BlogSelect(long? blogId, long? categoryId, bool? isActive = null, int? next = null, int? offset = null); } } <file_sep>/ProtectedBrowser/wwwroot/angular/pages/User/UserListController.js (function () { var applicationApp = angular.module("applicationApp"); applicationApp.controller("UserListController", userListController); userListController.$inject = ["UserRepository", "CommonUtils", "$scope", "$timeout"]; function userListController(UserRepository, CommonUtils, $scope, $timeout) { var vm = this; vm.init = init; vm.init(); showDetails = showDetails; vm.selectRecord = selectRecord; vm.userList = []; vm.selectedRecord = {}; vm.selectedRecords = []; vm.selectAll = selectAll; function init() { CommonUtils.logging("Error", "Got Error", "Init()", "UserListController.js"); vm.loading = true; vm.userList = undefined; UserRepository.fetchAll(function (resp) { if (!resp.status) { showTost("Error:", resp.message, "danger"); vm.loading = false; return; } vm.userList = resp.data; vm.loading = false; }, function (error) { showTost("Error:", "Somethings went wrong.", "danger"); }); vm.userStatusChange = userStatusChange; } //fetch all users function fetchAllUsers() { } function showDetails(record) { vm.selectedRecord = angular.copy(record); } $scope.$on('ngRepeatBroadcast1', function () { $timeout(function () { $('#sampleTable').DataTable({ "destroy": true }); }); $('[data-toggle="tooltip"]').tooltip(); }); //single record select function selectRecord(record) { if (!angular.isDefined(record)) { return; } if (record.isSelected) { vm.selectedRecord.id = record.id; vm.selectedRecords.push({ "id": record.id }); if (vm.selectedRecords.length == vm.userList.length) { vm.allSelected = true; } return; } vm.allSelected = false; vm.selectedRecords.splice(vm.selectedRecords.indexOf(record.id), 1); } //select all records function selectAll(val) { if (!val) { vm.selectedRecords = []; } angular.forEach(vm.userList, function (record, indx) { record.isSelected = val; if (val) { vm.selectedRecords.push({ id: record.id }); } }); }; //user status update function userStatusChange(obj) { var user = angular.copy(obj); if (!obj.isActive) { user.isActive = true; } else { user.isActive = false; } UserRepository.updateUser(user, function (resp) { if (!resp.status) { showTost("Error:", resp.message, "danger"); return; } if (!user.isActive) { showTost("Success:", "User deactivated", "success"); } else { showTost("Success:", "User activated", "success"); } obj.isActive = user.isActive; }, function (error) { showTost("Error:", "Somethings went wrong.", "danger"); }); } } }()); <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/Leave/LeaveDBService.cs using ProtectedBrowser.Domain; using ProtectedBrowser.Domain.Leave; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.Leave { public class LeaveDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public long LeaveInsert(LeaveModel model) { using (var dbctx = DbContext) { var id = dbctx.LeaveInsert(model.CreatedBy, model.StartDate, model.EndDate, model.StartTime, model.EndTime, model.Type, model.Description, model.UserId).FirstOrDefault(); return Convert.ToInt64(id ?? 0); } } public void LeaveUpdate(LeaveModel model) { using (var dbctx = DbContext) { dbctx.LeaveUpdate(model.Id, model.UpdatedBy, model.UpdatedOn, model.IsDeleted, model.IsActive, model.StartDate, model.EndDate, model.StartTime, model.EndTime, model.Type, model.Description, model.UserId); } } public List<LeaveModel> LeaveSelect(SearchParam param) { using (var dbctx = DbContext) { return dbctx.LeaveSelect(param.Id, param.UserId, param.AppointmentDate, param.Next, param.Offset).Select(x => new LeaveModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, StartDate = x.StartDate, EndDate = x.EndDate, StartTime = x.StartTime, EndTime = x.EndTime, Type = x.Type, Description = x.Description, UserId = x.UserId, TotalCount = x.overall_count.GetValueOrDefault(), FullName = x.FirstName + " " + x.LastName }).ToList(); } } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/CustomFilters/UserTimeZoneAttribute.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Http.Filters; namespace ProtectedBrowser.Framework.CustomFilters { public class UserTimeZoneAttribute : ActionFilterAttribute { public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { var currUserTimeZone = actionContext.Request.Headers.FirstOrDefault(x => x.Key.Equals("userTimeZone")); if (currUserTimeZone.Value == null) { actionContext.ActionArguments["timeZone"] = 0; } else { int a = 0; if (int.TryParse(currUserTimeZone.Value.FirstOrDefault(), out a)) actionContext.ActionArguments["timeZone"] = a; else actionContext.ActionArguments["timeZone"] = currUserTimeZone.Value.FirstOrDefault(); } base.OnActionExecuting(actionContext); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/PublicHoliday/PublicHolidaysModelToViewModel.cs using ProtectedBrowser.Domain.PublicHoliday; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.PublicHoliday { public static class PublicHolidaysModelToViewModel { public static PublicHolidaysModel ToModel(this PublicHolidayViewModel x) { if (x == null) return new PublicHolidaysModel(); return new PublicHolidaysModel { Id = x.Id, CreatedBy = x.CreatedBy, Description = x.Description, UpdatedBy = x.UpdatedBy, IsDeleted = x.IsDeleted, StartDate = x.StartDate, EndDate = x.EndDate, TodayDate = x.TodayDate, IsOnlyView = x.IsOnlyView, StartHolidayDate = x.StartHolidayDate, EndHolidayDate = x.EndHolidayDate }; } public static PublicHolidayViewModel ToViewModel(this PublicHolidaysModel x) { if (x == null) return new PublicHolidayViewModel(); return new PublicHolidayViewModel { Id = x.Id, CreatedBy = x.CreatedBy, Description = x.Description, StartHolidayDate = x.StartHolidayDate, EndHolidayDate = x.EndHolidayDate, UpdatedBy = x.UpdatedBy, IsDeleted = x.IsDeleted, UpdatedDate = x.UpdatedDate, CreatedDate = x.CreatedDate, IsOnlyView = x.IsOnlyView }; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser/API/LeaveController.cs using ProtectedBrowser.Common.Constants; using ProtectedBrowser.Domain; using ProtectedBrowser.Framework.GenericResponse; using ProtectedBrowser.Framework.ViewModels.Leave; using ProtectedBrowser.Service.Leave; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ProtectedBrowser.API { [RoutePrefix("api")] public class LeaveController : ApiController { private ILeaveService _leaveService; public LeaveController(ILeaveService leaveService) { _leaveService = leaveService; } /// <summary> /// Api use for get all Leave /// </summary> /// <returns></returns> [Route("leaves")] [Authorize(Roles = UserRole.Admin)] [HttpGet] public IHttpActionResult GetAllLeaves([FromUri] SearchParam param) { param = param ?? new SearchParam(); var leaves = _leaveService.LeaveSelect(param).Select(x => x.ToViewModel()); ; return Ok(leaves.SuccessResponse()); } /// <summary> /// Api use for get leave by id /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("leave/{id:long}")] [Authorize(Roles = UserRole.Admin)] [HttpGet] public IHttpActionResult SelectLeave(long id) { SearchParam param = new SearchParam(); param.Id = id; var leave = _leaveService.LeaveSelect(param).FirstOrDefault().ToViewModel(); return Ok(leave.SuccessResponse()); } /// <summary> /// Api use for save leave /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("leave")] [Authorize(Roles = UserRole.Admin)] [HttpPost] public IHttpActionResult LeaveSave(LeaveViewModel model) { model.CreatedBy = User.Identity.GetUserId<long>(); var responseId = _leaveService.LeaveInsert(model.ToModel()); return Ok(responseId.SuccessResponse("Leave Saved successfully")); } [Route("leave")] [Authorize(Roles = UserRole.Admin)] [HttpPut] public IHttpActionResult UpdateLeave(LeaveViewModel model) { _leaveService.LeaveUpdate(model.ToModel()); return Ok("Leave Updated successfully".SuccessResponse()); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/ContactUs/ContactUsModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.ContactUs { public class ContactUsModel { public long? Id { get; set; } public string Name { get; set; } public string PhoneNumber { get; set; } public string EmailAddress { get; set; } public DateTimeOffset? CreatedOn { get; set; } public bool? IsDeleted { get; set; } public string Message { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Configuration/IEmailConfigurationService.cs using ProtectedBrowser.Domain.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Configuration { public interface IEmailConfigurationService { EmailConfigurationModel EmailConfigurationSelect(string configuraionKey); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/CustomFilters/FileResult.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace ProtectedBrowser.Framework.CustomFilters { public class FileResult : IHttpActionResult { private readonly string filePath; private readonly byte[] fileStream; private readonly string contentType; readonly string fileName; public FileResult(string filePath, string filename = null) { this.filePath = filePath; this.fileName = filename; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { return Task.Run(() => { HttpResponseMessage response; //if file is returned as file path if (!string.IsNullOrEmpty(filePath)) { response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(File.OpenRead(filePath)) }; var contentType = this.contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(filePath)); response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); }//else file is returing through byte array else { response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(fileStream) }; response.Content.Headers.ContentType = this.contentType == null ? new MediaTypeHeaderValue("application/pdf") : new MediaTypeHeaderValue(contentType); } //adding header for custom file name of response if (!string.IsNullOrEmpty(fileName)) { response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; } return response; }, cancellationToken); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser/API/AccountController.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web; using Microsoft.AspNet.Identity.Owin; using Newtonsoft.Json; using ProtectedBrowser.Models; using ProtectedBrowser.Framework.ViewModels.User; using System.Threading.Tasks; using ProtectedBrowser.Framework.CustomFilters; using ProtectedBrowser.Framework.GenericResponse; using Microsoft.AspNet.Identity; using ProtectedBrowser.Service.Users; using ProtectedBrowser.GenericResponse; using ProtectedBrowser.Common.Constants; using ProtectedBrowser.Core.Mailer; using ProtectedBrowser.Common.Success; using ProtectedBrowser.Framework.WebExtensions; using ProtectedBrowser.Service.Configuration; using ProtectedBrowser.Common.Enums; using ProtectedBrowser.Common.Extensions; namespace ProtectedBrowser.API { [RoutePrefix("api/account")] public class AccountController : ApiController { private IUserService _userService; private IEmailConfigurationService _emailConfiguration; public AccountController(IUserService userService, IEmailConfigurationService emailConfiguration) { _userService = userService; _emailConfiguration = emailConfiguration; } ApplicationUserManager UserManager { get { return HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); } } /// <summary> /// Register new user /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("register")] [HttpPost] [Authorize(Roles = UserRole.Admin)] public IHttpActionResult RegisterUser([FromBody] UserViewModel model) { try { if (!ModelState.IsValid) { return Ok(ModelState.ErrorResponse()); } if (UserManager.Users.Any(x => x.Email.Equals(model.Email) && !x.IsDeleted)) { return Ok(string.Format(ErrorMessage.AccountError.EMAIL_ALREADY_REGISTERED, model.Email).ErrorResponse()); } var user = new ApplicationUser() { UserName = model.Email, Email = model.Email, PhoneNumber = model.MobileNo, PhoneNumberConfirmed = false, EmailConfirmed = false, IsActive = true, TwoFactorEnabled = model.RoleName == "" ? true : false, FirstName = model.FirstName, LastName = model.LastName, }; IdentityResult result = UserManager.Create(user); if (!result.Succeeded) { if (result == null) { return Ok(InternalServerError().ErrorResponse()); } if (result.Errors != null) { foreach (string error in result.Errors) { return Ok(error.ErrorResponse()); } } } UserManager.AddToRole(user.Id, model.RoleName); SendEmailForEmailConfirm(user.Id, user.Email, model.FirstName + " " + model.LastName, user.UniqueCode); return Ok(SuccessMessage.AccountSuccess.USER_REGISTERED.SuccessResponse()); } catch (Exception ex) { return Ok(ex.Message.ErrorResponse()); } } /// <summary> /// Method for send email for email varification and password reset. /// </summary> /// <param name="userId"></param> /// <param name="toEmail"></param> /// <param name="fullName"></param> /// <param name="uniqueCode"></param> public void SendEmailForEmailConfirm(long userId, string toEmail, string fullName, string uniqueCode) { var configData = _emailConfiguration.EmailConfigurationSelect(EmailConfigurationKey.EmailVerification.ToString()); string code = UserManager.GenerateEmailConfirmationToken(userId); code = HttpUtility.UrlEncode(code); var callbackUrl = UrlConstants.baseUrl + "/reset-password?p=" + uniqueCode + "&code=" + code; var emailBody = string.Format(configData.ConfigurationValue, fullName, callbackUrl); MailSender.SendEmail(toEmail, EmailConstants.CONFIRM_YOUR_ACCOUNT, emailBody).Wait(); } #region Login /// <summary> /// api use to login the app /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("login")] [HttpPost] [AllowAnonymous] public async Task<IHttpActionResult> Login(UserViewModel model) { var userFound = UserManager.Find(model.Email, model.Password); if (userFound == null) { return Ok(ErrorMessage.AccountError.INCORRECT.ErrorResponse()); } if (userFound.IsDeleted) { return Ok(ErrorMessage.AccountError.DELETED.ErrorResponse()); } return await GetLoginJson(userFound); } /// <summary> /// get login user detail /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task<IHttpActionResult> GetLoginJson(ApplicationUser user) { var token = await CreateToken(user.Email); if (string.IsNullOrEmpty(token.Error)) //if error is not found return token { if (user != null) { token.TokenData = new tokenData { Token = new tokenObj { Expires = DateTimeOffset.Now.AddDays(14), AccessToken = token.AccessToken, TokenType = token.TokenType }, User = new UserViewModel { Id=user.Id, FirstName = user.FirstName, LastName = user.LastName, UserName = user.Email, FullName = user.FirstName+" "+ user.LastName, Roles = UserManager.GetRoles(user.Id).ToList(), ProfileImageUrl = user.ProfilePic, UniqueCode = user.UniqueCode, IsActive=user.IsActive, IsDeleted=user.IsDeleted, EmailConfirmed=user.EmailConfirmed }, }; } return Ok(token.TokenData.SuccessResponse()); } return Ok(token.ErrorDescription.ErrorResponse()); } #endregion #region Forgot-Password /// <summary> /// send mail for forget password /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("forgot/password")] [HttpPost] [AllowAnonymous] public IHttpActionResult ForgotPassword(UserViewModel model) { try { string host = HttpContext.Current.Request.Url.Host; var user = GetUser(model.UserName); if (user == null) return Ok(ErrorMessage.AccountError.INVALID_EMAIL.ErrorResponse()); string code = UserManager.GeneratePasswordResetToken(user.Id); code = HttpUtility.UrlEncode(code); var callbackUrl = "http://" + host + "/account/recover/" + user.UniqueCode + "?code=" + code; // var userData = _userService.SelectUserByUniqueCode(user.UniqueCode); var configData = _emailConfiguration.EmailConfigurationSelect(EmailConfigurationKey.ForgotPassword.ToString()); //var configData = _emailConfiguration.GetEmailConfiguration(EmailConfigurationKey.ForgotPassword.ToString()); var emailBody = string.Format(configData.ConfigurationValue, user.FirstName, callbackUrl); MailSender.SendEmail(user.Email, EmailConstants.FORGOT_PASSWORD, emailBody).Wait(); return Ok(SuccessMessage.AccountSuccess.FORGOT_PASSWORD_LINK.SuccessResponse()); } catch (Exception ex) { return Ok(ex.Message.ErrorResponse()); } } /// <summary> /// api use for reset the password /// </summary> /// <param name="model"></param> /// <returns></returns> [AllowAnonymous] [HttpPost] [Route("reset/password")] public IHttpActionResult ResetPassword(UserViewModel model) { try { if (string.IsNullOrWhiteSpace(model.UniqueCode)) { return Ok(ErrorMessage.AccountError.INVALID.ErrorResponse()); } var user = _userService.SelectUserByUniqueCode(model.UniqueCode); if (user == null) return Ok(ErrorMessage.AccountError.INVALID_LINK.ErrorResponse()); IdentityResult result = UserManager.ResetPassword(Convert.ToInt64(user.Id), HttpUtility.UrlDecode(model.Code), model.Password); if (result.Succeeded) { return Ok(SuccessMessage.AccountSuccess.PASSWORD_CHANGED.SuccessResponse()); } else { return Ok(result.Errors.FirstOrDefault().ErrorResponse()); } } catch (Exception ex) { return Ok(ex.Message.ErrorResponse()); } } /// <summary> /// Email confirmation and password reset api /// </summary> /// <param name="model"></param> /// <returns></returns> [AllowAnonymous] [HttpPost] [Route("confirm/email")] public async Task<IHttpActionResult> ConfirmEmail(UserViewModel model) { try { if (string.IsNullOrWhiteSpace(model.UniqueCode)) { return Ok(ErrorMessage.AccountError.INVALID.ErrorResponse()); } var user = _userService.SelectUserByUniqueCode(model.UniqueCode); if (user == null) return Ok(ErrorMessage.AccountError.INVALID_LINK.ErrorResponse()); IdentityResult result = await this.UserManager.ConfirmEmailAsync(Convert.ToInt64(user.Id), HttpUtility.UrlDecode(model.Code)); if (result.Succeeded) { var appUser = UserManager.FindByEmail(user.Email); appUser.PasswordHash = UserManager.PasswordHasher.HashPassword(model.Password); appUser.IsActive = true; await UserManager.UpdateAsync(appUser); //string code = UserManager.GenerateEmailConfirmationToken(user.Id); return Ok(SuccessMessage.AccountSuccess.PASSWORD_CHANGED.SuccessResponse()); } else { return Ok(ErrorMessage.AccountError.INVALID_LINK.ErrorResponse()); } } catch (Exception ex) { return Ok(ex.Message.ErrorResponse()); } } /// <summary> /// Change password api /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("changePassword")] [Authorize] [HttpPost] public async Task<IHttpActionResult> ChangePassword(UserViewModel model) { try { var user = UserManager.FindById(User.Identity.GetUserId<long>()); var userFound = UserManager.Find(user.UserName, model.OldPassword); if(userFound == null) { return Ok("Old password does not match".ErrorResponse()); } //var user = UserManager.FindById(User.Identity.GetUserId<long>()); if (user != null) { user.IsActive = true; user.PasswordHash = UserManager.PasswordHasher.HashPassword(model.Password); await UserManager.UpdateAsync(user); return Ok("Password has been changed successfully".SuccessResponse()); } return Ok("Invalid user please login.".ErrorResponse()); } catch (Exception ex) { return Ok(ex.Message.ErrorResponse()); } } /// <summary> /// User details api /// </summary> /// <returns></returns> [Route("user")] [Authorize] [HttpGet] public IHttpActionResult GetUserDetail() { var userId = User.Identity.GetUserId<long>(); var userProfile = UserManager.FindById(userId); if (userProfile != null) { var User = new UserViewModel { FirstName = userProfile.FirstName, Roles = UserManager.GetRoles(userId).ToList(), LastName = userProfile.LastName, UserName = userProfile.Email, FullName = userProfile.FirstName+" "+ userProfile.LastName, Id = userId, ProfileImageUrl = userProfile.ProfilePic, UniqueCode = userProfile.UniqueCode, PhoneNumber = userProfile.PhoneNumber }; return Ok(User.SuccessResponse()); } return Ok("Could Not Fetch Profile".ErrorResponse()); } /// <summary> /// Update user details api /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("user")] [Authorize] [HttpPut] public IHttpActionResult UpdateUserDetail(UserViewModel model) { try { if (model == null) return Ok("Invalid data".ErrorResponse()); var user = UserManager.FindById(Convert.ToInt64(model.Id)); var userEmailCheck = UserManager.FindByEmail(user.Email); if (userEmailCheck != null && userEmailCheck.Id != user.Id && !user.IsDeleted) { return Ok(string.Format("{0} Email already registered with another account.", user.Email).ErrorResponse()); } UserManager.Update(user); return Ok("User details updated successfully.".SuccessResponse()); } catch (Exception ex) { return Ok(ex.Message.ErrorResponse()); } } #endregion #region Helper methods /// <summary> /// Create Token object for user /// </summary> /// <param name="user">Login model for User</param> /// <returns>Token View Model</returns> async Task<TokenViewModel> CreateToken(string email) { IEnumerable<KeyValuePair<string, string>> postData = new Dictionary<string, string> { {"username",email}, {"password","<PASSWORD>"}, {"grant_type","password"} }; var WWW_FORM_URLENCODED = "application/x-www-form-urlencoded"; using (var httpClient = new HttpClient()) { using (var content = new FormUrlEncodedContent(postData)) { content.Headers.Clear(); content.Headers.Add("Content-Type", WWW_FORM_URLENCODED); content.Headers.Add("user-found", "true"); HttpResponseMessage response = await httpClient.PostAsync(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/api/token", content); var respo = await response.Content.ReadAsStringAsync(); try { return JsonConvert.DeserializeObject<TokenViewModel>(respo); } catch (JsonReaderException ex) { return null;//throw new ("Internal Error Occured during Json Deserialization. " + respo, ex); } } } } /// <summary> /// User activation and de-activation /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("user/activate-deactivate")] [Authorize] [HttpPut] public IHttpActionResult UserActivateAndDeActivate(UserViewModel model) { try { var appUser = UserManager.FindById(Convert.ToInt64(model.Id)); if (Convert.ToBoolean(model.IsActive)) { appUser.IsActive = true; UserManager.Update(appUser); SendEmailForAccountActivation(model.Id, appUser.Email, model.FullName); return Ok(SuccessMessage.AccountSuccess.ACTIVATED.SuccessResponse()); } else { appUser.IsActive = false; UserManager.Update(appUser); SendEmailForAccountDeactivation(model.Id, appUser.Email, model.FullName); return Ok(SuccessMessage.AccountSuccess.DEACTIVATED.SuccessResponse()); } } catch (Exception ex) { return Ok(ex.Message.ErrorResponse()); } } public void SendEmailForAccountActivation(long? userId, string toEmail, string fullName) { var configData = _emailConfiguration.EmailConfigurationSelect(EmailConfigurationKey.AccountActivated.ToString()); var emailBody = string.Format(configData.ConfigurationValue, fullName); MailSender.SendEmail(toEmail, EmailConstants.ACCOUNT_ACTIVATED, emailBody).Wait(); } public void SendEmailForAccountDeactivation(long? userId, string toEmail, string fullName) { var configData = _emailConfiguration.EmailConfigurationSelect(EmailConfigurationKey.AccountDeactivated.ToString()); var emailBody = string.Format(configData.ConfigurationValue, fullName); MailSender.SendEmail(toEmail, EmailConstants.ACCOUNT_DEACTIVATED, emailBody).Wait(); } [Route("user")] [Authorize] [HttpDelete] public IHttpActionResult DeleteUser(UserViewModel model) { try { var user = UserManager.FindById(Convert.ToInt64(model.Id)); user.IsDeleted = true; user.Email = user.UserName = user.Email + "deleted" + CommonMethods.GetUniqueKey(6); UserManager.Update(user); return Ok(SuccessMessage.AccountSuccess.DELETED.SuccessResponse()); } catch (Exception ex) { return Ok(ex.Message.ErrorResponse()); } } ApplicationUser GetUser(string email) { var user = UserManager.FindByEmail(email); if (user != null) return user; return UserManager.Users.Where(x => x.PhoneNumber.Equals(email)).FirstOrDefault(); } #endregion [AllowAnonymous] [HttpPost] [Route("user/social/register")] public async Task<IHttpActionResult> Register(UserViewModel model) { string roleName = UserRole.Admin; #region Intializing ApplicationUser var user = new ApplicationUser() { UserName = model.Email, Email = model.Email, FacebookId = model.FacebookId, IsFacebookConnected = model.FacebookId != null ? true : false, GoogleId = model.GoogleId, IsGoogleConnected = model.GoogleId != null ? true : false, PhoneNumber = model.PhoneNumber, FirstName = model.FirstName, LastName = model.LastName }; #endregion #region Social Login user.EmailConfirmed = true; var returnVal = await SaveExternalLoginInfo(user, roleName); if (returnVal.UserRegistered == UserRegistered.Failed) return Ok("Failed".ErrorResponse()); return await GetLoginJson(returnVal.User); #endregion } private async Task<UserDetails> SaveExternalLoginInfo(ApplicationUser user, string roleName) { var idenityresult = await UserManager.CreateAsync(user); UserRegistered UserRegistered; ApplicationUser userModel = null; if (!idenityresult.Succeeded) { UserRegistered = UserRegistered.AlreadyRegister; /*Check for user is already registered*/ userModel = UserManager.FindByEmail(user.Email); if (userModel == null) UserRegistered = UserRegistered.Failed; if ((Convert.ToBoolean(userModel.IsFacebookConnected) && Convert.ToBoolean(user.IsFacebookConnected) && (userModel.FacebookId == user.FacebookId)) || (Convert.ToBoolean(userModel.IsGoogleConnected) && Convert.ToBoolean(user.IsGoogleConnected) && (userModel.GoogleId == user.GoogleId))) { UserRegistered = UserRegistered.AlreadyRegister; } else if (Convert.ToBoolean(user.IsGoogleConnected)) { userModel.IsGoogleConnected = user.IsGoogleConnected; userModel.GoogleId = user.GoogleId; await UserManager.UpdateAsync(userModel); } else if (Convert.ToBoolean(user.IsFacebookConnected)) { userModel.IsFacebookConnected = user.IsFacebookConnected; userModel.FacebookId = user.FacebookId; await UserManager.UpdateAsync(userModel); } else { UserRegistered = UserRegistered.Failed; } } else { userModel = UserManager.FindByEmail(user.Email); UserRegistered = UserRegistered.NowRegitered; UserManager.AddToRole(user.Id, roleName); } return new UserDetails { User = userModel, UserRegistered = UserRegistered }; } } public class UserDetails { public ApplicationUser User { get; set; } public UserRegistered UserRegistered { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/PublicHoliday/IPublicHolidayService.cs using ProtectedBrowser.Domain; using ProtectedBrowser.Domain.PublicHoliday; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.PublicHoliday { public interface IPublicHolidayService { long PublicHolidayInsert(PublicHolidaysModel model); void PublicHolidayUpdate(PublicHolidaysModel model); List<PublicHolidaysModel> PublicHolidaysSelect(SearchParam param); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/UploadFile/UploadFileService.cs using IotasmartBuild.DBRepository.UploadFile; using IotasmartBuild.Domain.UploadFile; using IotasmartBuild.Service.UploadFile; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace iotasolProject.Service.UploadFile { public class UploadFileService:IUploadService { public UploadFileDbService _uploadFileDBService; public UploadFileService() { _uploadFileDBService = new UploadFileDbService(); } public long UploadFileInsert(UploadFileModel model) { return _uploadFileDBService.UploadedFileInsert(model); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/DummyFileUpload/DummyFileUploadDBService.cs using ProtectedBrowser.Domain; using ProtectedBrowser.Domain.DummyFileUpload; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.DummyFileUpload { public class DummyFileUploadDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public long DummyTableForFileInsert(DummyTableForFileModel model) { using (var dbctx = DbContext) { var id = dbctx.DummyTableForFileSave(model.Name, model.CreatedBy).FirstOrDefault(); return Convert.ToInt64(id ?? 0); } } public void DummyTableForFileUpdate(DummyTableForFileModel model) { using (var dbctx = DbContext) { dbctx.DummyTableForFileUpdate(model.Name, model.UpdatedBy, model.IsDeleted, model.IsActive, model.Id); } } public List<DummyTableForFileModel> DummyTableForFileSelect(SearchParam param) { using (var dbctx = DbContext) { return dbctx.DummyTableForFileSelect(param.Id, param.Type, param.Next, param.Offset).Select(x => new DummyTableForFileModel { Id=x.Id, Name=x.Name, IsActive=x.IsActive, CreatedUser = new Domain.CreatedUserModel { UserId = x.CreatedBy, FirstName = x.CreatedByFirstName, LastName = x.CreatedByLastName, PhoneNumber = x.CreatedByPhoneNumber }, UpdatedUser = new Domain.UpdatedUserModel { UserId = x.UpdatedBy, FirstName = x.UpdatedByFirstName, LastName = x.UpdatedByLastName, PhoneNumber = x.UpdatedByPhoneNumber }, FileGroupItemsXml=x.FileGroupItemsXml }).ToList(); } } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/GenericResponses/ApiResponse.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.GenericResponse { /// <summary> /// It represent the error and success response /// </summary> /// <typeparam name="T">Type of data for response</typeparam> public class ApiRespone<T> { [JsonProperty("status")] public bool Status { get; set; } [JsonProperty("data")] public T Data { get; set; } [JsonProperty("message")] public string Message { get; set; } #region Conditional Response public bool ShouldSerializeMessage() { return Message != null; } public bool ShouldSerializeData() { return Data != null; } #endregion } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser/API/DirectoryController.cs using ProtectedBrowser.Framework.CustomFilters; using ProtectedBrowser.Framework.GenericResponse; using ProtectedBrowser.Framework.ViewModels.Directory; using ProtectedBrowser.Framework.WebExtensions; using ProtectedBrowser.Service.Directory; using Microsoft.AspNet.Identity; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ProtectedBrowser.API { [RoutePrefix("api")] [CustomExceptionFilter] public class DirectoryController : ApiController { private IDirectoryService _directoryService; public DirectoryController(IDirectoryService directoryService) { _directoryService = directoryService; } /// <summary> /// Api use for get all Directory /// </summary> /// <returns></returns> [Route("Directorys")] [Authorize(Roles = "ROLE_ADMIN")] [HttpGet] public IHttpActionResult GetAllDirectorys() { var directorys = _directoryService.SelectDirectory(null).Select(x => x.ToViewModel()); ; return Ok(directorys.SuccessResponse()); } /// <summary> /// Api use for get all Active Directory with Limit and Offset /// </summary> /// <returns></returns> [Route("active-directorys/{pageSize:int}/{pageNumber:int}")] [HttpGet] public IHttpActionResult ActiveDirectorys(int pageSize = 10, int pageNumber = 1) { var directorys = _directoryService.SelectDirectory(null, true, pageSize, pageNumber).Select(x => x.ToViewModel()); ; return Ok(directorys.SuccessResponse()); } /// <summary> /// Api use for get directory by id /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("directory/{id:long}")] [HttpGet] public IHttpActionResult GetDirectory(long id) { var directory = _directoryService.SelectDirectory(id).FirstOrDefault().ToViewModel(); return Ok(directory.SuccessResponse()); } /// <summary> /// Api use for save directory /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("directory")] [Authorize(Roles = "ROLE_ADMIN")] [HttpPost] public IHttpActionResult SaveDirectory(DirectoryViewModel model) { model.CreatedBy = User.Identity.GetUserId<long>(); model.UpdatedBy = User.Identity.GetUserId<long>(); var responseId = _directoryService.DirectoryInsert(model.ToModel()); return Ok(responseId.SuccessResponse("Directory save successfully")); } /// <summary> /// Api use for update directory /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("directory")] [Authorize(Roles = "ROLE_ADMIN")] [CustomExceptionFilter] [HttpPut] public IHttpActionResult UpdateDirectory(DirectoryViewModel model) { _directoryService.DirectoryUpdate(model.ToModel()); return Ok("Directory Update successfully".SuccessResponse()); } /// <summary> /// Api use for delete directory by id /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("directory/{id:long}")] [Authorize(Roles = "ROLE_ADMIN")] [CustomExceptionFilter] [HttpDelete] public IHttpActionResult DeleteDirectory(long id) { DirectoryViewModel model = new DirectoryViewModel(); model.Id = id; model.IsDeleted = true; _directoryService.DirectoryUpdate(model.ToModel()); return Ok("Directory Deleted successfully".SuccessResponse()); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/UploadFile/UploadFileDbService.cs using IotasmartBuild.Domain.UploadFile; using ProtectedBrowser.DBRepository; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IotasmartBuild.DBRepository.UploadFile { public class UploadFileDbService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public long UploadedFileInsert(UploadFileModel model) { using (var dbctx = DbContext) { var id = dbctx.UploadedFileInsert(model.FileName, model.FileUrl).FirstOrDefault(); return Convert.ToInt64(id ?? 0); } } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Common/Extensions/CommonExtensions.cs using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace ProtectedBrowser.Common.Extensions { public static class CommonExtensions { public static T? CastTo<T>(this string str) where T : struct { try { return (T)Convert.ChangeType(str, typeof(T)); } catch { return null; } } public static bool BoolValue(this bool? val) { return val ?? false; } public static DateTime? GetDateYYYYMMDD(this string dateTimeStr) { if (string.IsNullOrEmpty(dateTimeStr)) return null; if (new Regex("^[0-9]{4}-[0-9]{2}-[0-9]{2}").IsMatch(dateTimeStr)) { return DateTime.ParseExact(dateTimeStr, "yyyy-MM-dd", CultureInfo.InvariantCulture); } return null; //if (new Regex("^[0-9]{2}-[0-9]{2}-[0-9]{4}T[0-9]{2}:[0-9]{2}:[0-9]{2}").IsMatch(dateTimeStr))//MM-dd-YYYYTHH:mm:ssZ+5:30 // return DateTime.ParseExact(dateTimeStr, "MM-dd-yyyyTHH:mm:ss", CultureInfo.InvariantCulture); //if (new Regex("^[0-9]{1}-[0-9]{2}-[0-9]{4}T[0-9]{2}:[0-9]{2}:[0-9]{2}").IsMatch(dateTimeStr))//M-dd-YYYYTHH:mm:ss // return DateTime.ParseExact(dateTimeStr, "M-dd-yyyyTHH:mm:ss", CultureInfo.InvariantCulture); //if (new Regex("^[0-9]{2}-[0-9]{2}-[0-9]{4}").IsMatch(dateTimeStr))//MM-dd-YYYY // return DateTime.ParseExact(dateTimeStr, "MM-dd-yyyy", CultureInfo.InvariantCulture); //if (new Regex("^[0-9]{1}-[0-9]{2}-[0-9]{4}").IsMatch(dateTimeStr))//M-dd-YYYY // return DateTime.ParseExact(dateTimeStr, "M-dd-yyyy", CultureInfo.InvariantCulture); //return null; } public static string XmlSerialize<T>(this T obj) { if (obj == null) return null; var xmlSerializer = new XmlSerializer(typeof(T)); var xmlNamespace = new XmlSerializerNamespaces(); xmlNamespace.Add("", ""); using (var stringWriter = new StringWriter()) { var writer = XmlWriter.Create(stringWriter); xmlSerializer.Serialize(writer, obj, xmlNamespace); return stringWriter.ToString(); } } public static string GetDescription(this Enum en) { if (en == null) return string.Empty; Type type = en.GetType(); MemberInfo[] memInfo = type.GetMember(en.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = memInfo[0].GetCustomAttributes(typeof(EnumDescription)).ToArray(); if (attrs != null && attrs.Length > 0) return ((EnumDescription)attrs[0]).Text; } return en.ToString(); } public static T GetValueOrDefault<T>(this T? val) where T : struct { if (val.HasValue) return val.Value; return default(T); } public static List<TSource> ToList<TSource>(this DataTable dataTable) where TSource : new() { var dataList = new List<TSource>(); const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic; var objFieldNames = (from PropertyInfo aProp in typeof(TSource).GetProperties(flags) select new { Name = aProp.Name, Type = Nullable.GetUnderlyingType(aProp.PropertyType) ?? aProp.PropertyType }).ToList(); var dataTblFieldNames = (from DataColumn aHeader in dataTable.Columns select new { Name = aHeader.ColumnName, Type = aHeader.DataType }).ToList(); var commonFields = objFieldNames.Intersect(dataTblFieldNames).ToList(); foreach (DataRow dataRow in dataTable.AsEnumerable().ToList()) { var aTSource = new TSource(); foreach (var aField in commonFields) { PropertyInfo propertyInfos = aTSource.GetType().GetProperty(aField.Name); var value = (dataRow[aField.Name] == DBNull.Value) ? null : dataRow[aField.Name]; //if database field is nullable propertyInfos.SetValue(aTSource, value, null); } dataList.Add(aTSource); } return dataList; } /// <summary> /// To Get List /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TDest"></typeparam> /// <param name="source"></param> /// <param name="converter"></param> /// <returns></returns> public static List<TDest> ToCustomList<TSource, TDest>(this List<TSource> source, Func<TSource, TDest> converter) { if (source == null) return null; if (!source.Any()) return null; return source.Select(x => converter(x)).ToList(); } public static Dictionary<string, string> EnumToJson(this Type type) { if (!type.IsEnum) throw new InvalidOperationException("enum expected"); return Enum.GetValues(type).Cast<object>() .ToDictionary(enumValue => enumValue.ToString()[0].ToString().ToLower() + enumValue.ToString().Substring(1), enumValue => ((short)enumValue).ToString()); } public static DateTimeOffset? AddMinutes(this DateTimeOffset? dt, int minute) { if (dt.HasValue) return dt.Value.AddMinutes(minute); return null; } } public class EnumDescription : Attribute { public string Text; public EnumDescription(string text) { Text = text; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Common/Extensions/MoveFileToTarget.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Common.Extensions { public static class MoveFileToTarget { public static string MoveFile(string sourcePath, string targetPath, string fileName, long? id) { // To copy a folder's contents to a new location: // Create a new target folder, if necessary. if (!System.IO.Directory.Exists(targetPath)) { System.IO.Directory.CreateDirectory(targetPath); } Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri); string pathQuery = myuri.PathAndQuery; string hostName = myuri.ToString().Replace(pathQuery, ""); // Use Path class to manipulate file and directory paths. //string sourceFile = System.IO.Path.Combine(sourcePath, fileName); string destFile = System.IO.Path.Combine(targetPath, fileName); if (System.IO.File.Exists(destFile)) { fileName = Guid.NewGuid().ToString() + fileName; destFile = System.IO.Path.Combine(targetPath, fileName); } // To move a file or folder to a new location: System.IO.File.Move(sourcePath, destFile); targetPath = hostName + "/" + "file/" + id + "/" + fileName; return targetPath; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Category/CategoryService.cs using ProtectedBrowser.DBRepository.Category; using ProtectedBrowser.Domain.Category; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Category { public class CategoryService : ICategoryService { public CategoryDBService _categoryDBService; public CategoryService() { _categoryDBService = new CategoryDBService(); } public long CategoryInsert(CategoryModel model) { return _categoryDBService.CategoryInsert(model); } public void CategoryUpdate(CategoryModel model) { _categoryDBService.CategoryUpdate(model); } public List<CategoryModel> CategorySelect(long? categoryId, bool? isActive = null, int? next = null, int? offset = null) { return _categoryDBService.CategorySelect(categoryId, isActive, next, offset); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/Category/CategoryModelViewModelConverter.cs using ProtectedBrowser.Domain.Category; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IotasmartBuild.Framework.ViewModels.Category { public static class CategoryModelViewModelConverter { public static CategoryModel ToModel(this CategoryViewModel x) { if (x == null) return new CategoryModel(); return new CategoryModel { CreatedBy = x.CreatedBy, IsActive = x.IsActive, Name = x.CategoryName, IsDeleted = x.IsDeleted, Id = x.CategoryId, UpdatedBy = x.UpdatedBy }; } public static CategoryViewModel ToViewModel(this CategoryModel x) { if (x == null) return new CategoryViewModel(); return new CategoryViewModel { CreatedBy = x.CreatedBy, IsActive = x.IsActive, CategoryName = x.Name, CategoryId = x.Id, CreateOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, OverAllCount = x.TotalCount, UpdatedBy = x.UpdatedBy }; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Database/dbo/Stored Procedures/InsertExceptionLog.sql /****** created by = <NAME> ******/ /****** created date = 06-06-2017 ******/ CREATE PROCEDURE InsertExceptionLog( @Source NVARCHAR(1000)=NULL, @Message Nvarchar(1000)=NULL, @StackTrace NVARCHAR(MAX)=NULL, @Uri NVARCHAR(1000)=NULL, @method NVARCHAR(50)=NULL, @CreatedBy BIGINT=NULL ) AS BEGIN INSERT INTO ExceptionLog ( Source, Message, StackTrace, Uri, method, CreatedBy ) Values ( @Source, @Message, @StackTrace, @Uri, @method, @CreatedBy ) SELECT SCOPE_IDENTITY() END <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/Upload/FileUpload.cs using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.Upload { public partial class FileUpload { public bool IsComplete { get; set; } public string FileName { get; set; } public string LocalFilePath { get; set; } public NameValueCollection FileMetadata { get; set; } public string FileId { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/Upload/FileGroupModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.Upload { public class FileGroupModel { public long? Id { get; set; } public long? CreatedBy { get; set; } public long? UpdatedBy { get; set; } public DateTimeOffset? CreatedOn { get; set; } public DateTimeOffset? UpdatedOn { get; set; } public bool? IsDeleted { get; set; } public bool? IsActive { get; set; } public string Name { get; set; } public string Type { get; set; } } } <file_sep>/ProtectedBrowser/Models/IdentityModels.cs using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using ProtectedBrowser.Common.Extensions; namespace ProtectedBrowser.Models { public class CustomUserRole : IdentityUserRole<long> { } public class CustomUserClaim : IdentityUserClaim<long> { } public class CustomUserLogin : IdentityUserLogin<long> { } public class CustomRole : IdentityRole<long, CustomUserRole> { public CustomRole() { } public CustomRole(string name) { Name = name; } } public class CustomUserStore : UserStore<ApplicationUser, CustomRole, long, CustomUserLogin, CustomUserRole, CustomUserClaim> { public CustomUserStore(ApplicationDbContext context) : base(context) { } } public class CustomRoleStore : RoleStore<CustomRole, long, CustomUserRole> { public CustomRoleStore(ApplicationDbContext context) : base(context) { } } // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser<long, CustomUserLogin, CustomUserRole, CustomUserClaim> { public ApplicationUser() { IsActive = true; IsDeleted = false; UniqueCode = CommonMethods.GetUniqueKey(); IsFacebookConnected = false; IsGoogleConnected = false; } public bool IsActive { get; set; } public bool IsDeleted { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string ProfilePic { get; set; } public string UniqueCode { get; set; } public bool? IsFacebookConnected { get; set; } public bool? IsGoogleConnected { get; set; } public string FacebookId { get; set; } public string GoogleId { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager userManager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await userManager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, long> manager, string authenticationType) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); // Add custom user claims here return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, long, CustomUserLogin, CustomUserRole, CustomUserClaim> { public ApplicationDbContext() : base("DefaultConnection") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<ApplicationUser>() .ToTable("Users"); modelBuilder.Entity<CustomRole>() .ToTable("Roles"); modelBuilder.Entity<CustomUserRole>() .ToTable("UserRoles"); modelBuilder.Entity<CustomUserClaim>() .ToTable("UserClaims"); modelBuilder.Entity<CustomUserLogin>() .ToTable("UserLogins"); } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/Upload/FileGroupItemsModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.Upload { public class FileGroupItemsModel { public long? Id { get; set; } public long? CreatedBy { get; set; } public long? UpdatedBy { get; set; } public DateTimeOffset? CreatedOn { get; set; } public DateTimeOffset? UpdatedOn { get; set; } public bool? IsDeleted { get; set; } public bool? IsActive { get; set; } public string Filename { get; set; } public string MimeType { get; set; } public string Thumbnail { get; set; } public long? Size { get; set; } public string Path { get; set; } public string OriginalName { get; set; } public string OnServer { get; set; } public string Type { get; set; } public long? TypeId { get; set; } public int TotalCount { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Xml/IXmlService.cs using ProtectedBrowser.Domain.Upload; using ProtectedBrowser.Domain.Directory;//@@ADD_NEW_NAMESPACE_XML_CODE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Xml { public interface IXmlService { List<FileGroupItemsModel> GetFileGroupItemsByXml(string attachmentFileXml); List<DirectoryModel> GetDirectoryByXml(string attachmentFileXml); //@@ADD_NEW_XML_CODE } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser/API/DummyTableForFileController.cs using ProtectedBrowser.Common.Constants; using ProtectedBrowser.Common.Extensions; using ProtectedBrowser.Domain; using ProtectedBrowser.Domain.Upload; using ProtectedBrowser.Framework.GenericResponse; using ProtectedBrowser.Framework.ViewModels.DummyFileUpload; using ProtectedBrowser.Framework.WebExtensions; using ProtectedBrowser.Service.DummyFileUpload; using ProtectedBrowser.Service.FileGroup; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ProtectedBrowser.API { [RoutePrefix("api")] public class DummyTableForFileController : ApiController { private IFileGroupService _fileGroupService; private IDummyFileUploadService _dummyFileUploadService; public DummyTableForFileController(IFileGroupService fileGroupService, IDummyFileUploadService dummyFileUploadService) { _fileGroupService = fileGroupService; _dummyFileUploadService = dummyFileUploadService; } /// <summary> /// Save list of flies /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("dummy/table")] [Authorize(Roles = "ROLE_ADMIN")] [HttpPost] public IHttpActionResult DummyTableForFileSave(DummyTableForFileViewModel model) { if (model == null) return Ok("Invalid data.".ErrorResponse()); var userId = model.CreatedBy = User.Identity.GetUserId<long>(); //convert view model to model //save dummy table data var modelConvert = model.ToModel(); var dummyId = _dummyFileUploadService.DummyTableForFileInsert(modelConvert); return Ok("Saved successfully".SuccessResponse()); } /// <summary> /// Update list of files /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("dummy/table")] [Authorize] [HttpPut] public IHttpActionResult DummyTableForFileUpdate(DummyTableForFileViewModel model) { if (model == null) return Ok("Invalid data.".ErrorResponse()); var userId = model.UpdatedBy = User.Identity.GetUserId<long>(); //convert view model to model //save dummy table data var modelConvert = model.ToModel(); _dummyFileUploadService.DummyTableForFileUpdate(modelConvert); return Ok("updated successfully".SuccessResponse()); } [Route("dummy/table/singlefile")] [Authorize] [HttpPost] public IHttpActionResult DummyTableForSingleFileSave(DummyTableForFileViewModel model) { if (model == null) return Ok("Invalid data.".ErrorResponse()); var userId = model.CreatedBy = User.Identity.GetUserId<long>(); //convert view model to model //save dummy table data var modelConvert = model.ToModel(); var dummyId = _dummyFileUploadService.DummyTableForFileInsert(modelConvert); return Ok("Saved successfully".SuccessResponse()); } /// <summary> /// Get all records with list of files /// </summary> /// <param name="param"></param> /// <returns></returns> [Route("dummy/table")] [Authorize] [HttpGet] public IHttpActionResult DummyTableForFileSelect([FromUri] SearchParam param) { param = param ?? new SearchParam(); var returnVal = _dummyFileUploadService.DummyTableForFileSelect(param); return Ok(returnVal.SuccessResponse()); } /// <summary> /// Get by id with list of files /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("dummy/table/{id}")] [Authorize] [HttpGet] public IHttpActionResult DummyTableForFileSelectById(long? id) { SearchParam param = new SearchParam(); param.Id = id; var returnVal = _dummyFileUploadService.DummyTableForFileSelectById(param); return Ok(returnVal.SuccessResponse()); } [Route("dummy/table/singlefile")] [Authorize] [HttpGet] public IHttpActionResult DummyTableForFileSelectBySingleFile(SearchParam param) { param = param ?? new SearchParam(); var returnVal = _dummyFileUploadService.DummyTableForFileSelectBySingleFile(param); return Ok(returnVal.SuccessResponse()); } } } <file_sep>/ProtectedBrowser/API/FileUploadController.cs using ProtectedBrowser.Framework.GenericResponse; using ProtectedBrowser.Framework.ViewModels.Upload; using ProtectedBrowser.Framework.WebExtensions; using ProtectedBrowser.Service.FileGroup; using ProtectedBrowser.Service.Upload; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace ProtectedBrowser.API { [RoutePrefix("api")] public class FileUploadController : ApiController { private IFileGroupService _fileGroupService; private IFileUploadService _fileUploadService; private readonly string _uploadPath; private readonly MultipartFormDataStreamProvider _streamProvider; public FileUploadController(IFileGroupService fileGroupService, IFileUploadService fileUploadService) { _fileGroupService = fileGroupService; _fileUploadService = fileUploadService; _uploadPath = UserLocalPath; _streamProvider = new MultipartFormDataStreamProvider(_uploadPath); } private string UserLocalPath { get { return HttpContext.Current.Server.MapPath("/tempfolder"); //return the path where you want to upload the file } } [Route("file/group/items/upload")] [HttpPost] public async Task<IEnumerable<FileGroupItemsViewModel>> FileGroupItemsAdd(HttpRequestMessage request) { var provider = new PhotoMultipartFormDataStreamProvider(_uploadPath); await request.Content.ReadAsMultipartAsync(provider); var bodylength = request.Content.Headers.ContentLength; return _fileUploadService.ProcessDocs(provider.FileData, Convert.ToInt32(bodylength)).Select(x => x.ToViewModel()).ToList(); } [Route("file/group/item/delete/{id}")] [HttpDelete] public IHttpActionResult FileGroupItemDelete(long? id) { var userId = User.Identity.GetUserId<long>(); _fileGroupService.FileGroupItemsDelete(id, userId); return Ok("File Deleted".SuccessResponse()); } } } <file_sep>/ProtectedBrowser/Global.asax.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System.Web.Http; using ProtectedBrowser.App_Start; using Autofac.Integration.WebApi; using ProtectedBrowser.Core.Infrastructure; namespace ProtectedBrowser { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { var engine = EngineContext.Initialize(false); GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(engine.ContainerManager.Container); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } protected void Application_BeginRequest(object sender, EventArgs e) { if (this.Context.Request.Path.Contains("signalr/")) { this.Context.Response.AddHeader("Access-Control-Allow-Headers", "accept,origin,authorization,content-type"); } //SqlDependency.Stop(connString); if (ReferenceEquals(null, HttpContext.Current.Request.Headers["Authorization"])) { var token = HttpContext.Current.Request.Params["a_t"]; if (!string.IsNullOrEmpty(token)) { HttpContext.Current.Request.Headers.Add("Authorization", "Bearer " + token); } } //Response.Redirect(""),j } } } <file_sep>/ProtectedBrowser/wwwroot/angular/pages/Contact/ContactUsRepository.js (function () { var commonService = angular.module("common.services"); commonService.factory("ContactUsRepository", blogRepository); blogRepository.$inject = ["$resource"]; function blogRepository($resource) { return $resource(apiBaseUrl + "", {}, { addContact: { method: 'POST', params: {}, isArray: false, url: secureApiBaseUrl + "contact-us" }, deleteContact: { method: 'DELETE', params: { id: '@id' }, isArray: false, url: secureApiBaseUrl + "admin/contact-us/:id" }, getAllContacts: { method: 'GET', params: {}, isArray: false, url: secureApiBaseUrl + "admin/contact-us" } }); } }()); <file_sep>/ProtectedBrowserCopy/ProtectedBrowser/API/BlogController.cs using IotasmartBuild.Framework.ViewModels.Blog; using ProtectedBrowser.Domain; using ProtectedBrowser.Framework.GenericResponse; using ProtectedBrowser.Framework.WebExtensions; using ProtectedBrowser.Service.Blog; using ProtectedBrowser.Service.FileGroup; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ProtectedBrowser.API { [RoutePrefix("api")] public class BlogController : ApiController { private IBlogService _blogService; private IFileGroupService _fileGroupService; public BlogController(IBlogService blogService, IFileGroupService fileGroupService) { _blogService = blogService; _fileGroupService = fileGroupService; } /// <summary> /// Api use for get all blogs /// </summary> /// <returns></returns> [Route("admin/blogs")] [Authorize(Roles = "ROLE_ADMIN")] [HttpGet] public IHttpActionResult GetAllBlogsForAdmin([FromUri]SearchParam param) { var blogs = _blogService.BlogSelect(null, param.CategoryId, null, param.Next, param.Offset).Select(x => x.ToViewModel()); return Ok(blogs.SuccessResponse()); } [Route("admin/blog/{id:long}")] [Authorize(Roles = "ROLE_ADMIN")] [HttpGet] public IHttpActionResult GetBlogbyId(long id) { var blog = _blogService.BlogSelect(id, null).FirstOrDefault().ToViewModel(); return Ok(blog.SuccessResponse()); } [Route("blogs/{id:long}/category")] [HttpGet] public IHttpActionResult GetAllBlogsbyCategoryId([FromUri]SearchParam param) { var blogs = _blogService.BlogSelect(null, param.CategoryId, true, param.Next, param.Offset).Select(x => x.ToViewModel()); return Ok(blogs.SuccessResponse()); } /// <summary> /// Api use for get blog by id /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("blog/{id:long}")] [HttpGet] public IHttpActionResult GetBlogById(long id) { var blog = _blogService.BlogSelect(id, null).FirstOrDefault().ToViewModel(); return Ok(blog.SuccessResponse()); } /// <summary> /// Api use for save blog /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("admin/blog")] [Authorize(Roles = "ROLE_ADMIN")] [HttpPost] public IHttpActionResult SaveBlog(BlogViewModel model) { model.CreatedBy = User.Identity.GetUserId<long>(); var blogId = _blogService.BlogInsert(model.ToModel()); var fileGroupsItem = model.FileGroupItem != null ? model.FileGroupItem.ToModel() : null; if (fileGroupsItem != null) { //set target path and move file from target location fileGroupsItem = _fileGroupService.SetPathAndMoveSingleFile(fileGroupsItem, blogId); //Save list of file in our DB _fileGroupService.FileGroupItemsInsert(fileGroupsItem); } return Ok(blogId.SuccessResponse("Blog save successfully")); } /// <summary> /// Api use for update category /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("admin/blog")] [Authorize(Roles = "ROLE_ADMIN")] [HttpPut] public IHttpActionResult UpdateBlog(BlogViewModel model) { model.UpdatedBy = User.Identity.GetUserId<long>(); _blogService.BlogUpdate(model.ToModel()); var fileGroupsItem = model.FileGroupItem != null ? model.FileGroupItem.ToModel() : null; if (fileGroupsItem != null && (fileGroupsItem.Id == null || fileGroupsItem.Id == 0)) { //set target path and move file from target location fileGroupsItem = _fileGroupService.SetPathAndMoveSingleFile(fileGroupsItem, model.Id); //Save list of file in our DB _fileGroupService.FileGroupItemsInsert(fileGroupsItem); } return Ok("Blog Update successfully".SuccessResponse()); } /// <summary> /// Api use for delete blog by id /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("admin/blog/{id:long}")] [Authorize(Roles = "ROLE_ADMIN")] [HttpDelete] public IHttpActionResult DeleteBlog(long id) { BlogViewModel model = new BlogViewModel(); model.Id = id; model.IsDeleted = true; model.UpdatedBy = User.Identity.GetUserId<long>(); _blogService.BlogUpdate(model.ToModel()); return Ok("Blog Deleted successfully".SuccessResponse()); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/UploadFile/UploadFileViewModel.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.Blog { public class UploadFileViewModel { [JsonProperty("id")] public long Id { get; set; } [JsonProperty("fileName")] public string FileName { get; set; } [JsonProperty("fileUrl")] public string FileUrl { get; set; } [JsonProperty("baseUrl")] public string BaseUrl { get; set; } [JsonProperty("isDeleted")] public bool IsDeleted { get; set; } [JsonProperty("createdOn")] public Nullable<System.DateTimeOffset> CreatedOn { get; set; } } } <file_sep>/ProtectedBrowser/wwwroot/angular/pages/User/UserRepository.js (function () { var commonService = angular.module("common.services"); commonService.factory("UserRepository", userRepository); userRepository.$inject = ["$resource"]; function userRepository($resource) { return $resource(apiBaseUrl + "api", {}, { saveUser: { method: 'POST', params: {}, isArray: false, url: secureApiBaseUrl + "account/register" }, fetchAll: { method: 'GET', params: {}, isArray: false, url: secureApiBaseUrl + "account/users" }, getUserById: { method: 'GET', params: {}, isArray: false, url: secureApiBaseUrl + "account/user/:id" }, updateUser: { method: 'PUT', params: {}, isArray: false, url: secureApiBaseUrl + "account/updateUser" }, }); } }()); <file_sep>/ProtectedBrowserCopy/ProtectedBrowser/API/DailyWorkSettingController.cs using ProtectedBrowser.Framework.GenericResponse; using ProtectedBrowser.Framework.ViewModels.DailyWorkSetting; using ProtectedBrowser.Framework.WebExtensions; using ProtectedBrowser.Service.DailyWorkSetting; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ProtectedBrowser.API { [RoutePrefix("api")] public class DailyWorkSettingController : ApiController { private IDailyWorkSettingService _dailyWorkSettingService; public DailyWorkSettingController(IDailyWorkSettingService dailyWorkSettingService) { _dailyWorkSettingService = dailyWorkSettingService; } /// <summary> /// Get work setting /// </summary> /// <returns></returns> [Route("daily/work/setting")] [HttpGet] [Authorize] public IHttpActionResult DailyWorkSettingSelect() { var dailyWorkSetting = _dailyWorkSettingService.DailyWorkSettingSelect().ToViewModel(); return Ok(dailyWorkSetting.SuccessResponse()); } /// <summary> /// Save and update work setting /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("daily/work/setting")] [HttpPost] [Authorize] public IHttpActionResult DailyWorkSettingAction(DailyWorkSettingViewModel model) { model.CreatedBy = User.Identity.GetUserId<long>(); long id = _dailyWorkSettingService.DailyWorkSettingAction(model.ToModel()); if (model.Id == null) return Ok(id.SuccessResponse("Work setting saved successfully.")); else return Ok(id.SuccessResponse("Work setting updated successfully.")); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/Configuration/EmailConfigurationModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.Configuration { public class EmailConfigurationModel { public int Id { get; set; } public string ConfigurationKey { get; set; } public string ConfigurationValue { get; set; } public string EmailSubject { get; set; } public System.DateTimeOffset CreatedDate { get; set; } public Nullable<long> CreatedBy { get; set; } public int IsDeleted { get; set; } } } <file_sep>/ProtectedBrowser/wwwroot/angular/pages/Blog/BlogCategoryListControlle.js (function () { var applicationApp = angular.module("applicationApp"); applicationApp.controller("BlogCategoryListcontroller", blogCategoryListcontroller); blogCategoryListcontroller.$inject = ["$state", "$timeout", "BlogRepository", "$filter", "$scope", "CommonUtils"]; function blogCategoryListcontroller($state, $timeout, AccessRepository, $filter, $scope, CommonUtils) { var vm = this; vm.remove = remove; vm.openCategoryPopup = openCategoryPopup; vm.editCategory = editCategory; vm.save = save; function init() { vm.loading = true; vm.recordList = undefined; vm.onClickValidation = false; vm.isNewRecord = false; vm.category = {}; AccessRepository.fetchAll(function (response) { vm.recordList = response.data; vm.loading = false; }, function (error) { vm.errorResponse = error.data; vm.isError = true; vm.loading = false; return; }); } init(); $scope.$on('ngRepeatBroadcast1', function () { $timeout(function () { $('#sampleTable').DataTable({ "destroy": true }); }); }); function remove(id) { customDeleteConfirmation(removeRecordCallback, id); } function removeRecordCallback(id) { AccessRepository.deleteBlogCategory({ id: id }, function (response) { sweetAlert.close(); if (!response.status) { showTost("Error:", response.message, "danger"); return; } showTost("Success:", "Record Deleted Successfully", "success"); vm.init(); }, function (error) { sweetAlert.close(); showTost("Error:", "Somethings went wrong.", "danger"); }); } function openCategoryPopup() { vm.isNewRecord = true; $("#categoryModel").modal('show'); } function editCategory(obj) { vm.isNewRecord = false; vm.category = angular.copy(obj); $("#categoryModel").modal('show'); } function save(bol) { vm.onClickValidation = !bol; if (!bol) { return; } var method = vm.isNewRecord ? "addBlogCategory" : "updateBlogCategory"; AccessRepository[method](vm.category, function (data) { if (!data.status) { showTost("Error:", data.message, "danger"); return; } showTost("Success:", data.message, "success"); $("#categoryModel").modal('hide'); init(); }, function (error) { vm.disabledSaveButton = false; showTost("Error:", error.message, "danger"); }); } } }()); <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/PublicHoliday/PublicHolidayViewModel.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.PublicHoliday { public class PublicHolidayViewModel { [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("startHolidayDate")] public Nullable<System.DateTimeOffset> StartHolidayDate { get; set; } [JsonProperty("endHolidayDate")] public Nullable<System.DateTimeOffset> EndHolidayDate { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("isDeleted")] public bool? IsDeleted { get; set; } [JsonProperty("createdBy")] public Nullable<long> CreatedBy { get; set; } [JsonProperty("updatedBy")] public Nullable<long> UpdatedBy { get; set; } [JsonProperty("createdDate")] public System.DateTimeOffset CreatedDate { get; set; } [JsonProperty("updatedDate")] public System.DateTimeOffset UpdatedDate { get; set; } [JsonProperty("createdByName")] public string CreatedByName { get; set; } [JsonProperty("updatedByName")] public string UpdatedByName { get; set; } [JsonProperty("startDate")] public Nullable<System.DateTimeOffset> StartDate { get; set; } [JsonProperty("endDate")] public Nullable<System.DateTimeOffset> EndDate { get; set; } [JsonProperty("isOnlyView")] public Nullable<bool> IsOnlyView { get; set; } [JsonProperty("todayDate")] public Nullable<System.DateTimeOffset> TodayDate { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/Blog/BlogDBService.cs using ProtectedBrowser.Domain.Blog; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.Blog { public class BlogDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public long BlogInsert(BlogModel model) { using (var dbctx = DbContext) { var id = dbctx.BlogInsert(model.Title, model.Description, model.CategoryId, model.IsActive, model.CreatedBy, model.FileId).FirstOrDefault(); return Convert.ToInt64(id ?? 0); } } public void BlogUpdate(BlogModel model) { using (var dbctx = DbContext) { dbctx.BlogUpdate(model.Id, model.Title, model.Description, model.CategoryId, model.IsDeleted, model.IsActive, model.UpdatedBy, model.FileId); } } public List<BlogModel> BlogSelect(long? blogId, long? categoryId, bool? isActive = null, int? next = null, int? offset = null) { using (var dbctx = DbContext) { return dbctx.BlogSelect(blogId, isActive, categoryId, next, offset).Select(x => new BlogModel { IsActive = x.IsActive, Title = x.Title, Description = x.Description, CreatedBy = x.CreatedBy, Id = x.Id, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, UpdatedBy = x.UpdatedBy, CategoryId = x.CategoryId, FileId = x.FileId, FileName = x.FileName, FileUrl = x.FileUrl, CategoryName = x.CategoryName }).ToList(); } } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/DummyFileUpload/DummyFileUploadService.cs using ProtectedBrowser.DBRepository.DummyFileUpload; using System.Collections.Generic; using System.Linq; using ProtectedBrowser.Domain.DummyFileUpload; using ProtectedBrowser.Service.Xml; using ProtectedBrowser.Domain; using ProtectedBrowser.Service.FileGroup; using ProtectedBrowser.Common.Extensions; namespace ProtectedBrowser.Service.DummyFileUpload { public class DummyFileUploadService:IDummyFileUploadService { private DummyFileUploadDBService _dummyFileUploadDBService; private IXmlService _xmlService; private IFileGroupService _fileGroupService; public DummyFileUploadService(IXmlService xmlService, IFileGroupService fileGroupService) { _xmlService = xmlService; _fileGroupService = fileGroupService; _dummyFileUploadDBService = new DummyFileUploadDBService(); } public long DummyTableForFileInsert(DummyTableForFileModel model) { var id= _dummyFileUploadDBService.DummyTableForFileInsert(model); if (model.FileGroupItems != null) { //set target path and move file from target location model.FileGroupItems = _fileGroupService.SetPathAndMoveFile(model.FileGroupItems, id); //Save list of file in our DB _fileGroupService.FileGroupItemsInsertXml(model.CreatedBy, id, model.FileGroupItems.XmlSerialize()); } if (model.FileGroupItem != null) { //set target path and move file from target location model.FileGroupItem = _fileGroupService.SetPathAndMoveSingleFile(model.FileGroupItem, id); //Save list of file in our DB _fileGroupService.FileGroupItemsInsert(model.FileGroupItem); } return id; } public List<DummyTableForFileModel> DummyTableForFileSelect(SearchParam param) { var DummyTableForFiles = _dummyFileUploadDBService.DummyTableForFileSelect(param); DummyTableForFiles.ForEach(x => { x.FileGroupItems = _xmlService.GetFileGroupItemsByXml(x.FileGroupItemsXml); }); return DummyTableForFiles; } public DummyTableForFileModel DummyTableForFileSelectById(SearchParam param) { var DummyTableForFile = _dummyFileUploadDBService.DummyTableForFileSelect(param).FirstOrDefault(); DummyTableForFile.FileGroupItem = _xmlService.GetFileGroupItemsByXml(DummyTableForFile.FileGroupItemsXml).FirstOrDefault(); return DummyTableForFile; } public void DummyTableForFileUpdate(DummyTableForFileModel model) { _dummyFileUploadDBService.DummyTableForFileUpdate(model); if (model.FileGroupItems != null) { //set target path and move file from target location model.FileGroupItems = _fileGroupService.SetPathAndMoveFile(model.FileGroupItems, model.Id); //Save list of file in our DB _fileGroupService.FileGroupItemsInsertXml(model.UpdatedBy, model.Id, model.FileGroupItems.XmlSerialize()); } if (model.FileGroupItem != null) { //set target path and move file from target location model.FileGroupItem = _fileGroupService.SetPathAndMoveSingleFile(model.FileGroupItem, model.Id); //Save list of file in our DB _fileGroupService.FileGroupItemsInsertXml(model.UpdatedBy, model.Id, model.FileGroupItem.XmlSerialize()); } } public List<DummyTableForFileModel> DummyTableForFileSelectBySingleFile(SearchParam param) { var DummyTableForFiles = _dummyFileUploadDBService.DummyTableForFileSelect(param); DummyTableForFiles.ForEach(x => { x.FileGroupItem = _xmlService.GetFileGroupItemsByXml(x.FileGroupItemsXml).FirstOrDefault(); }); return DummyTableForFiles; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Directory/IDirectoryService.cs using ProtectedBrowser.Domain.Directory; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Directory { public interface IDirectoryService { /// <summary> /// used for insertion directory /// </summary> /// <param name="model"></param> /// <returns></returns> long DirectoryInsert(DirectoryModel model); /// <summary> /// Method for update directory /// </summary> /// <param name="model"></param> void DirectoryUpdate(DirectoryModel model); /// <summary> /// use to select all directory or select directory by id /// </summary> /// <param name="directoryId"></param> /// <param name="isActive"></param> /// <param name="next"></param> /// <param name="offset"></param> /// <returns></returns> List<DirectoryModel> SelectDirectory(long? directoryId, bool? isActive = null, int? next = null, int? offset = null); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/ContactUs/ContactUsService.cs using ProtectedBrowser.DBRepository.ContactUs; using ProtectedBrowser.Domain.ContactUs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.ContactUs { public class ContactUsService : IContactUsService { public ContactUsDBService _contactUsDbService; public ContactUsService() { _contactUsDbService = new ContactUsDBService(); } public void ContactUsInsert(ContactUsModel model) { _contactUsDbService.ContactUsInsert(model); } public void ContactUsDelete(long? id) { _contactUsDbService.ContactUsDelete(id); } public List<ContactUsModel> ContactUsSelect(long? id, int? next = null, int? offset = null) { return _contactUsDbService.ContactUsSelect(id, next, offset); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/CustomFilters/ValidateModelStateAttribute.cs using ProtectedBrowser.Framework.GenericResponse; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Text; using System.Threading.Tasks; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace ProtectedBrowser.Framework.CustomFilters { /// <summary> /// This action filter validate the ModelState from request body. If ModelState is invalid it create error response with validation error /// </summary> public class ValidateModelStateAttribute : ActionFilterAttribute, IActionFilter { public bool CheckForModelNull { get; set; } public string ModelName { get; set; } public override void OnActionExecuting(HttpActionContext actionContext) { var modelState = actionContext.ModelState; if (CheckForModelNull) { var obj = actionContext.ActionArguments[ModelName]; if (obj == null) { actionContext.Response = new HttpResponseMessage { Content = new ObjectContent<ApiRespone<string>>(new ApiRespone<string> { Data = AppConstant.Messages.MODEL_NULL_ERROR, Status = false, Message = "Validation Error" }, new JsonMediaTypeFormatter(), "application/json"), }; } } if (!modelState.IsValid) { //get all error from modelState var errors = modelState.SelectMany(v => v.Value.Errors.Select(x => x.ErrorMessage)).ToList(); if (errors.All(x => string.IsNullOrEmpty(x))) { //if error is not found, select all exception messages from modelState errors = modelState.SelectMany(v => v.Value.Errors.Select(x => x.Exception.Message)).ToList(); } actionContext.Response = new HttpResponseMessage { //create error reponse from modelState Error Content = new ObjectContent<ApiRespone<List<string>>>(new ApiRespone<List<string>> { Data = errors, Status = false, Message = "Validation Error" }, new JsonMediaTypeFormatter(), "application/json"), ReasonPhrase = "Invalid ModelState", }; } base.OnActionExecuting(actionContext); } } public partial class AppConstant { public class Messages { public const string MODEL_NULL_ERROR = "No data submitted"; } } } <file_sep>/ProtectedBrowser/wwwroot/angular/signIn/oAuthValidateService.js (function () { var commonService = angular.module("common.services"); commonService.factory("AuthServerProvider", authServerProvider); authServerProvider.$inject = ["$http", "localStorageService", "$rootScope", "$state", "$timeout", "$location", "CONSTANTS"]; function authServerProvider($http, localStorageService, $rootScope, $state, $timeout, $location, CONSTANTS) { //var userRoles = this.getUser().roles; return { authenticate: function () { var token = this.getToken(); var isAuthenticated = token && token.expires_at && token.expires_at > new Date().getTime(); if (isAuthenticated) { $rootScope.$broadcast('event:auth-authConfirmed'); } else { $rootScope.$broadcast('event:auth-authRequired'); } }, signOff: function () { localStorageService.clearAll(); window.location.href = "/signIn"; }, getToken: function () { return localStorageService.get('token'); }, getUser: function () { return localStorageService.get('user'); }, hasValidToken: function () { var token = this.getToken(); return token && token.accessToken && token.expires_at && token.expires_at > new Date().getTime(); }, isAnonymous: function () { if (this.hasValidToken()) { $state.go('/'); } }, isAuthorizedRoleUser: function (roles, $q) { var deferred = $q.defer(); if (!this.hasValidToken()) { localStorageService.clearAll(); $timeout(deferred.reject); window.location.href = "/signIn"; return deferred.promise; } var userRoles = this.getUser().roles; var result = userRoles.filter(function (item) { return roles.indexOf(item) > -1 }); if (result.length <= 0) { $timeout(deferred.reject); $state.go('403'); return deferred.promise; } $timeout(deferred.resolve); return deferred.promise; }, isAccessible: isAccessible, isDisabled: isDisabled }; function isAccessible(VIEW) { //var allowedRoles = CONSTANTS.VIEW_USER_MAPPING[VIEW].SHOW_TO_ROLE; //return allowedRoles.some(function (ele) { // return userRoles.includes(ele); //}); return true; }; function isDisabled(VIEW) { //console.log(VIEW); //var allowedRoles = CONSTANTS.VIEW_USER_MAPPING[VIEW].ENABLED_FOR_ROLE; //return !allowedRoles.some(function (ele) { // return userRoles.includes(ele); //}); return true; }; } }()); <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Appointment/AppointmentSlotManage.cs using ProtectedBrowser.Domain.Appointment; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Appointment { public class AppointmentSlotManage { public static List<AppointmentTimeSlot> SlotManage(List<AppointmentModel> bookedAppointment, TimeSpan? StartTime, TimeSpan? StartLunchTime, TimeSpan? EndLunchTime, TimeSpan? EndTime, int TimeSlot) { List<AppointmentTimeSlot> timeSloatList = new List<AppointmentTimeSlot>(); TimeSpan? startLunchTime = StartLunchTime; TimeSpan? startTime = StartTime; TimeSpan minutes = TimeSpan.FromMinutes(TimeSlot); do { if (startTime < startLunchTime) { timeSloatList.Add(new AppointmentTimeSlot() { StartTime = startTime, EndTime = startTime = startTime.Value.Add(minutes), }); } } while (startTime < startLunchTime); TimeSpan? endLunchTime = EndLunchTime; TimeSpan? endTime = EndTime; do { if (endLunchTime < endTime) { timeSloatList.Add(new AppointmentTimeSlot() { StartTime = endLunchTime, EndTime = endLunchTime = endLunchTime.Value.Add(minutes), }); } } while (endLunchTime < endTime); foreach (var item in bookedAppointment) { TimeSpan? bookedStartSpan = item.StartTime; TimeSpan? bookedEndSpan = item.EndTime; foreach (var slot in timeSloatList) { TimeSpan? sloatStartSpan = slot.StartTime; TimeSpan? sloatEndSpan = slot.EndTime; if (bookedStartSpan == sloatStartSpan || (sloatStartSpan > bookedStartSpan && sloatStartSpan < bookedEndSpan)) { slot.IsBooked = true; } } } return timeSloatList; } public static bool CheckingLeaveTimeSlot(TimeSpan? startTime, TimeSpan? endTime, TimeSpan? leaveStartTime, TimeSpan? LeaveEndTime) { if (((startTime >= leaveStartTime) && (startTime < LeaveEndTime)) || ((endTime > leaveStartTime) && (endTime < LeaveEndTime))) { return true; } return false; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Appointment/AppointmentService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ProtectedBrowser.Domain; using ProtectedBrowser.Domain.Appointment; using ProtectedBrowser.DBRepository.Appointment; using ProtectedBrowser.DBRepository.DailyWorkSetting; using ProtectedBrowser.DBRepository.PublicHoliday; using ProtectedBrowser.DBRepository.Leave; namespace ProtectedBrowser.Service.Appointment { public class AppointmentService : IAppointmentService { private AppointmentDBService _appointmentDBService; private DailyWorkSettingDBService _dailyWorkSettingDBService; private PublicHolidayDBService _publicHolidayDBService; private LeaveDBService _leaveDBService; public AppointmentService() { _appointmentDBService = new AppointmentDBService(); _dailyWorkSettingDBService = new DailyWorkSettingDBService(); _publicHolidayDBService = new PublicHolidayDBService(); _leaveDBService = new LeaveDBService(); } public long AppointmentInsert(AppointmentModel model) { return _appointmentDBService.AppointmentInsert(model); } public List<AppointmentModel> AppointmentSelect(SearchParam param) { return _appointmentDBService.AppointmentSelect(param); } public void AppointmentUpdate(AppointmentModel model) { _appointmentDBService.AppointmentUpdate(model); } public List<AppointmentTimeSlot> GetUserAppointmentSlot(DateTimeOffset? appointmentDate, long? toUserId) { List<AppointmentTimeSlot> appointmentTimeSlot = new List<AppointmentTimeSlot>(); SearchParam param = new SearchParam(); param.AppointmentDate = appointmentDate; var appointments = AppointmentSelect(param); var dailyWorkSetting = _dailyWorkSettingDBService.DailyWorkSettingSelect(); if (dailyWorkSetting == null) return new List<AppointmentTimeSlot>(); param.UserId = toUserId; var userLeave = _leaveDBService.LeaveSelect(param); var userAppointments = appointments.Where(x => x.ToUserId == toUserId).ToList(); if (userLeave.Count == 0) { var timeSlot = AppointmentSlotManage.SlotManage(userAppointments, dailyWorkSetting.StartTime, dailyWorkSetting.StartLunchTime, dailyWorkSetting.EndLunchTime, dailyWorkSetting.EndTime, 30); appointmentTimeSlot.AddRange(timeSlot); } else { var fullDayLeave = userLeave.Where(x => x.StartDate.Value.Date < appointmentDate.Value.Date && x.EndDate.Value.Date > appointmentDate.Value.Date).ToList(); if (fullDayLeave.Count != 0) { return new List<AppointmentTimeSlot>(); } var timeSlot = AppointmentSlotManage.SlotManage(userAppointments, dailyWorkSetting.StartTime, dailyWorkSetting.StartLunchTime, dailyWorkSetting.EndLunchTime, dailyWorkSetting.EndTime, 30); appointmentTimeSlot.AddRange(timeSlot); foreach (var leave in userLeave) { if (leave.StartTime == null) { break; } else { if (leave.StartDate.Value.Date == appointmentDate.Value.Date && (leave.StartDate.Value.Date != leave.EndDate.Value.Date)) { leave.EndTime = dailyWorkSetting.EndTime; } if (leave.EndDate.Value.Date == appointmentDate.Value.Date && (leave.StartDate.Value.Date != leave.EndDate.Value.Date)) { leave.StartTime = dailyWorkSetting.StartTime; } for (int j = 0; j < timeSlot.Count; j++) { if (AppointmentSlotManage.CheckingLeaveTimeSlot(timeSlot[j].StartTime, timeSlot[j].EndTime, leave.StartTime, leave.EndTime)) { timeSlot.RemoveAt(j); j--; } } } } if (timeSlot.Count != 0) appointmentTimeSlot.AddRange(timeSlot); } return appointmentTimeSlot; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Configuration/EmailConfigurationService.cs using ProtectedBrowser.DBRepository.Configuration; using ProtectedBrowser.Domain.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Configuration { public class EmailConfigurationService: IEmailConfigurationService { public EmailConfigurationDBService _emailConfigurationDBServicee; public EmailConfigurationService() { _emailConfigurationDBServicee = new EmailConfigurationDBService(); } public EmailConfigurationModel EmailConfigurationSelect(string configuraionKey) { return _emailConfigurationDBServicee.EmailConfigurationSelect(configuraionKey); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/DummyFileUpload/DummyTableForFileModel.cs using ProtectedBrowser.Domain.Upload; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.DummyFileUpload { public class DummyTableForFileModel:BaseEntity { public long? Id { get; set; } public long? CreatedBy { get; set; } public long? UpdatedBy { get; set; } public DateTimeOffset? CreatedOn { get; set; } public DateTimeOffset? UpdatedOn { get; set; } public bool? IsDeleted { get; set; } public bool? IsActive { get; set; } public string Name { get; set; } public string FileGroupItemsXml { get; set; } public List<FileGroupItemsModel> FileGroupItems { get; set; } public FileGroupItemsModel FileGroupItem { get; set; } } } <file_sep>/ProtectedBrowser/API/AppointmentController.cs using ProtectedBrowser.Common.Constants; using ProtectedBrowser.Domain; using ProtectedBrowser.Framework.GenericResponse; using ProtectedBrowser.Framework.ViewModels.Appointment; using ProtectedBrowser.Service.Appointment; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ProtectedBrowser.API { [RoutePrefix("api")] public class AppointmentController : ApiController { private IAppointmentService _appointmentService; public AppointmentController(IAppointmentService appointmentService) { _appointmentService = appointmentService; } [Route("appointment")] // [Authorize(Roles = UserRole.Admin)] [HttpPost] public IHttpActionResult SaveAppointment(AppointmentViewModel model) { var userId = model.CreatedBy = User.Identity.GetUserId<long>(); var responseId = _appointmentService.AppointmentInsert(model.ToModel()); return Ok(responseId.SuccessResponse("Appointment saved successfully")); } [Route("appointment/timeslot")] //[Authorize(Roles = UserRole.Admin)] [HttpGet] public IHttpActionResult AppointmentSlot([FromUri]SearchParam param) { param = param ?? new SearchParam(); var timeSlot = _appointmentService.GetUserAppointmentSlot(param.AppointmentDate, param.ToUserId).Select(x => x.ToViewModel()); return Ok(timeSlot.SuccessResponse()); } [Route("appointment")] [Authorize(Roles = UserRole.Admin)] [HttpPut] public IHttpActionResult UpdateAppointment(AppointmentViewModel model) { var userId = User.Identity.GetUserId<long>(); string message = "Appointment Updated successfully"; _appointmentService.AppointmentUpdate(model.ToModel()); if (Convert.ToBoolean(model.IsCancel)) { message = "Appointment Cancelled successfully"; } return Ok(message.SuccessResponse()); } [Route("appointments")] [Authorize(Roles = UserRole.Admin)] public IHttpActionResult GetAllAppointments(SearchParam param) { param = param ?? new SearchParam(); var appointments = _appointmentService.AppointmentSelect(param).Select(x => x.ToViewModel()); return Ok(appointments.SuccessResponse()); } [Route("appointment/{id}")] [Authorize(Roles = UserRole.Admin)] public IHttpActionResult GetAppointmentById(long? id) { SearchParam param = new SearchParam(); param.Id = id; var appointment = _appointmentService.AppointmentSelect(param).FirstOrDefault().ToViewModel(); return Ok(appointment.SuccessResponse()); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/UploadFile/UploadFileModelViewModelConverter.cs using IotasmartBuild.Domain.UploadFile; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.Blog { public static class UploadFileModelViewModelConverter { public static UploadFileModel ToModel(this UploadFileViewModel x) { if (x == null) return new UploadFileModel(); return new UploadFileModel { Id = x.Id, FileName = x.FileName, FileUrl = x.FileUrl, CreatedOn = x.CreatedOn, IsDeleted = x.IsDeleted }; } public static UploadFileViewModel ToViewModel(this UploadFileModel x) { if (x == null) return new UploadFileViewModel(); return new UploadFileViewModel { Id = x.Id, FileName = x.FileName, FileUrl = x.FileUrl, CreatedOn = x.CreatedOn, IsDeleted = x.IsDeleted }; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/ContactUs/ContactUsViewModel.cs using Newtonsoft.Json; using System; namespace IotasmartBuild.Framework.ViewModels.ContactUs { public class ContactUsViewModel { [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("phoneNumber")] public string PhoneNumber { get; set; } [JsonProperty("emailAddress")] public string EmailAddress { get; set; } [JsonProperty("createdOn")] public DateTimeOffset? CreatedOn { get; set; } [JsonProperty("isDeleted")] public bool? IsDeleted { get; set; } [JsonProperty("message")] public string Message { get; set; } } } <file_sep>/ProtectedBrowser/wwwroot/angular/signIn/signInController.js (function () { var applicationApp = angular.module("applicationApp"); applicationApp.controller("SignInController", signInController); signInController.$inject = ["$scope", "$state", "$filter", "localStorageService", "$timeout", "SignInRepository", "CommonUtils"]; function signInController($scope, $state, $filter, localStorageService, $timeout, SignInRepository, CommonUtils) { var vm = this; vm.signIn = signIn; vm.resetPassword = <PASSWORD>; vm.onClickValidation = false; vm._view = 'LOGIN'; function signIn(bol, form) { vm.onClickValidation = !bol; if (!bol) { if (form.username.$error.email) { showTost("Error:", "Please enter valid email", "danger"); } return false; } SignInRepository.signIn({ email: vm.username, password: <PASSWORD> }, function (data) { if (!data.status) { showTost("Error:", data.message, "danger"); vm.result = data; return; } var response = data.data; response.token.expires_at = new Date(response.token.expires).getTime(); localStorageService.set('token', response.token); localStorageService.set('user', response.user); $timeout(function () { window.location.href = "/dashboard"; }, 100); }); } function resetPassword(bol, form) { vm.onClickValidation = !bol; if (!bol) { if (form.remail.$error.email) { showTost("Error:", "Please enter valid email", "danger"); } return false; } SignInRepository.resetPassword({ userName: vm.recoverEmail, }, function (data) { if (!data.status) { showTost("Error:", data.message, "danger"); return; } vm.recoverEmail = ""; showTost("Success:", data.message, "success"); $('.login-box').toggleClass('flipped'); }); } vm.loadForgotPage = loadForgotPage; function loadForgotPage() { vm.onClickValidation = false; $("#loginContainer").slideUp(); $("#forgotContainer").fadeIn(); } vm.loadLoginPage = loadLoginPage; function loadLoginPage() { vm.onClickValidation = false; $("#forgotContainer").fadeOut(); $("#loginContainer").slideDown(); } } }()); <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/FileGroup/FileGroupDBService.cs using ProtectedBrowser.Domain.Upload; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.FileGroup { public class FileGroupDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public void FileGroupItemsInsertXml(long? userId, long? typeId, string attachmentFile) { using (var dbctx = DbContext) { dbctx.FileGroupItemsInsertXml(userId, typeId, attachmentFile); } } public long FileGroupItemsInsert(FileGroupItemsModel model) { using (var dbctx = DbContext) { var id = dbctx.FileGroupItemInsert(model.CreatedBy, model.Filename, model.MimeType, model.Thumbnail, model.Size, model.Path, model.OriginalName, model.OnServer, model.TypeId, model.Type).FirstOrDefault(); return Convert.ToInt64(id ?? 0); } } public void FileGroupItemsDelete(long? id, long? updatedBy) { using (var dbctx = DbContext) { dbctx.FileGroupItemsDelete(id, updatedBy); } } } } <file_sep>/ProtectedBrowser/wwwroot/angular/pages/Blog/BlogListController.js (function () { var applicationApp = angular.module("applicationApp"); applicationApp.controller("BlogListController", blogListcontroller); blogListcontroller.$inject = ["$state", "$timeout", "BlogRepository", "$filter", "$scope", "CommonUtils"]; function blogListcontroller($state, $timeout, RecordRepository, $filter, $scope, CommonUtils) { var vm = this; vm.remove = remove; function init() { vm.loading = true; vm.recordList = undefined; var pagination_obj = {}; pagination_obj.Next = 10; pagination_obj.Offset = 1; RecordRepository.getAllBlogs(pagination_obj, function (response) { vm.recordList = response.data; vm.loading = false; }, function (error) { vm.errorResponse = error.data; vm.isError = true; vm.loading = false; return; }); } init(); $scope.$on('ngRepeatBroadcast1', function () { $timeout(function () { $('#sampleTable').DataTable({ "destroy": true }); }); $('[data-toggle="tooltip"]').tooltip(); }); function remove(id) { customDeleteConfirmation(removeRecordCallback, id); } function removeRecordCallback(id) { RecordRepository.deleteBlog({ id: id }, function (response) { sweetAlert.close(); if (!response.status) { showTost("Error:", response.message, "danger"); return; } showTost("Success:", "Record Deleted Successfully", "success"); vm.init(); }, function (error) { sweetAlert.close(); showTost("Error:", "Somethings went wrong.", "danger"); }); } } }()); <file_sep>/ProtectedBrowser/wwwroot/angular/pages/Directory/DirectoryEditController.js (function () { var applicationApp = angular.module("applicationApp"); applicationApp.controller("DirectoryEditController", directoryEditController); directoryEditController.$inject = ["$scope", "$state", "$timeout", "DirectoryRepository", "$filter","FileUploader", "$stateParams", "AuthServerProvider"]; function directoryEditController($scope, $state, $timeout, AccessRepository, $filter,FileUploader, $stateParams, AuthRepository) { var vm = this; vm.save = save; vm.cancel = cancel; vm.remove = remove; init(); function init() { vm.record = { isActive: true }; vm.recordId = $stateParams.id; vm.isNewRecord = true; if (vm.recordId <= 0) { autoSelected(); return; } AccessRepository.fetch({ "id": vm.recordId }, function (response) { vm.loading = false; vm.isNewRecord = false; vm.record = response.data; postprocessing(); }, function (error) { vm.errorResponse = error.data; vm.isError = true; vm.loading = false; }); } function postprocessing(){ autoSelected(); } function autoSelected(value) { $('.select-2').select2(); $('.datepicker').datepicker({ format: "dd/mm/yyyy", autoclose: true, todayHighlight: true }); } function save(bol) { vm.onClickValidation = !bol; if (!bol) { return; } var method="save"; if (!vm.isNewRecord) { method="update" } AccessRepository[method](vm.record, function (data) { if (!data.status) { showTost("Error:", data.message, "danger"); return; } showTost("Success:", data.message, "success"); vm.cancel(); }, function (error) { showTost("Error:", error.data.message, "danger"); }); } function cancel() { $state.go("DirectoryList"); } function remove() { customDeleteConfirmation(removeRecordCallback, vm.recordId); } function removeRecordCallback(recordId) { AccessRepository.remove({ id: recordId }, function (response) { sweetAlert.close(); if (!response.status) { showTost("Error:", response.message, "danger"); return; } showTost("Success:", "Record Deleted Successfully", "success"); vm.cancel(); }, function (error) { sweetAlert.close(); showTost("Error:", "Some Things went wrong.", "danger"); }); } vm.loadAssociatedPopup = loadAssociatedPopup; function loadAssociatedPopup(name, fieldName) { vm.associated = { isActive: true }; $("#" + name).modal("show"); } vm.onSelectAssociated = onSelectAssociated; function onSelectAssociated(value, name, popUpName) { vm.record[name] = value; setTimeout(function () { $('.' + name).val(value).trigger("change"); }); vm.associated = undefined; $("#" + popUpName).modal("hide"); } vm.onRemoveAssociated = onRemoveAssociated; function onRemoveAssociated(id, fieldName) { customDeleteConfirmation(removeAssociatedRecordCallback, id, fieldName); } function removeAssociatedRecordCallback(recordId, fieldName) { vm.repository.remove({ id: recordId }, function (response) { sweetAlert.close(); if (!response.status) { showTost("Error:", response.message, "danger"); return; } showTost("Success:", "Record Deleted Successfully", "success"); vm.loadAssociatedAll(fieldName); }, function (error) { sweetAlert.close(); showTost("Error:", "Some Things went wrong.", "danger"); }); } vm.loadAssociatedAll = loadAssociatedAll; function loadAssociatedAll() { vm.repository.fetchAll(function (response) { }); } vm.onSaveAssociated = onSaveAssociated; function onSaveAssociated(fieldName) { vm.repository.save(vm.associated, function (response) { if (!response.status) { showTost("Error:", response.message, "danger"); return; } vm.associated = { isActive: true }; vm.showAddForm = false; vm.loadAssociatedAll(fieldName); }); } } }()); <file_sep>/ProtectedBrowser/wwwroot/angular/signIn/signInRepository.js (function () { var commonService = angular.module("common.services"); commonService.factory("SignInRepository", signInRepository); signInRepository.$inject = ["$resource"]; function signInRepository($resource) { return $resource("", {}, { signIn: { method: 'POST', params: {}, isArray: false, url: secureApiBaseUrl + "account/login" }, resetPassword: { method: 'POST', params: {}, isArray: false, url: secureApiBaseUrl + "account/forgotPassword" } }); } }()); <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/ContactUs/ContactUsModelViewModelConverter.cs using ProtectedBrowser.Domain.ContactUs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IotasmartBuild.Framework.ViewModels.ContactUs { public static class ContactUsModelViewModelConverter { public static ContactUsModel ToModel(this ContactUsViewModel x) { if (x == null) return new ContactUsModel(); return new ContactUsModel { Name = x.Name, EmailAddress = x.EmailAddress, PhoneNumber = x.PhoneNumber, Message = x.Message, IsDeleted = x.IsDeleted, CreatedOn=x.CreatedOn, Id=x.Id }; } public static ContactUsViewModel ToViewModel(this ContactUsModel x) { if (x == null) return new ContactUsViewModel(); return new ContactUsViewModel { Id = x.Id, CreatedOn = x.CreatedOn, Name = x.Name, EmailAddress = x.EmailAddress, PhoneNumber = x.PhoneNumber, Message = x.Message, IsDeleted=x.IsDeleted }; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/Directory/DirectoryDBService.cs using ProtectedBrowser.Domain.Directory; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.Directory { public class DirectoryDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public long DirectoryInsert(DirectoryModel model) { using (var dbctx = DbContext) { var id = dbctx.DirectoryInsert(model.CreatedBy,model.UpdatedBy,model.IsActive,model.RootPath,model.UserName,model.Password,model.Name).FirstOrDefault(); return Convert.ToInt64(id ?? 0); } } public void DirectoryUpdate(DirectoryModel model) { using (var dbctx = DbContext) { dbctx.DirectoryUpdate(model.Id,model.CreatedBy,model.UpdatedBy,model.CreatedOn,model.UpdatedOn,model.IsDeleted,model.IsActive,model.RootPath,model.UserName,model.Password,model.Name); } } public List<DirectoryModel> SelectDirectory(long? id, bool? isActive = null, int? next = null, int? offset = null) { using (var dbctx = DbContext) { return dbctx.DirectorySelect(id, isActive, next, offset).Select(x => new DirectoryModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, RootPath = x.RootPath, UserName = x.UserName, Password = <PASSWORD>, Name = x.Name, TotalCount = x.overall_count.GetValueOrDefault(), }).ToList(); } } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Database/dbo/Stored Procedures/FileGroupItemInsert.sql -- ============================================= -- Author: <Author,,Name> -- Create date: <Create Date,,> -- Description: <Description,,> -- ============================================= CREATE PROCEDURE dbo.FileGroupItemInsert @CreatedBy BIGINT=NULL, @FileName NVARCHAR(250)=NULL, @MimeType NVARCHAR(250)=NULL, @Thumbnail NVARCHAR(250)=NULL, @Size BIGINT=NULL, @Path NVARCHAR(250)=NULL, @OriginalName NVARCHAR(250)=NULL, @OnServer NVARCHAR(250)=NULL, @TypeId BIGINT=NULL, @Type NVARCHAR(50)=NULL AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; INSERT INTO FileGroupItems ( CreatedBy, UpdatedBy, FileName, MimeType, Thumbnail, Size, Path, OriginalName, OnServer, TypeId, Type ) VALUES ( @CreatedBy, @CreatedBy, @FileName, @MimeType, @Thumbnail, @Size, @Path, @OriginalName, @OnServer, @TypeId, @Type ) SELECT SCOPE_IDENTITY() END <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/Users/UserDBService.cs using ProtectedBrowser.Domain.Users; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.Users { public class UserDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public UserModel UserProfileByUniqueCode(string uniqueCode) { using (var dbctx = DbContext) { return dbctx.SelectUserProfileByUniqueCode(uniqueCode).Select(x => new UserModel { Email = x.Email, FirstName = x.firstName, FullName = x.firstName + " " + x.lastName, LastName = x.lastName, IsActive = x.IsActive, Id = x.Id, PhoneNumber = x.PhoneNumber, ProfileImageUrl = x.ProfilePic, UniqueCode = x.UniqueCode }).FirstOrDefault(); } } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Appointment/IAppointmentService.cs using ProtectedBrowser.Domain; using ProtectedBrowser.Domain.Appointment; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Appointment { public interface IAppointmentService { long AppointmentInsert(AppointmentModel model); void AppointmentUpdate(AppointmentModel model); List<AppointmentModel> AppointmentSelect(SearchParam param); List<AppointmentTimeSlot> GetUserAppointmentSlot(DateTimeOffset? appointmentDate, long? toUserId); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Common/Constants/FileType.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Common.Constants { public class FileType { public const string TYPE_DEMO = "DEMO"; } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/Appointment/AppointmentDBService.cs using ProtectedBrowser.Domain; using ProtectedBrowser.Domain.Appointment; using ProtectedBrowser.Domain.Users; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.Appointment { public class AppointmentDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public long AppointmentInsert(AppointmentModel model) { using (var dbctx = DbContext) { var id = dbctx.AppointmentInsert(model.CreatedBy, model.AppointmentDate, model.Note, model.StartTime, model.EndTime, model.ToUserId, model.FromUserId, model.Status).FirstOrDefault(); return Convert.ToInt64(id ?? 0); } } public void AppointmentUpdate(AppointmentModel model) { using (var dbctx = DbContext) { dbctx.AppointmentUpdate(model.Id, model.UpdatedBy, model.UpdatedOn, model.IsActive, model.AppointmentDate, model.Note, model.ToUserId, model.FromUserId, model.IsCancel, model.CancellationReason, model.StartTime, model.EndTime, model.isAppointmentDone, model.Status); } } public List<AppointmentModel> AppointmentSelect(SearchParam param) { using (var dbctx = DbContext) { return dbctx.AppointmentSelect(param.Id, param.ToUserId, param.FromUserId, param.AppointmentDate, param.StartDate, param.EndDate, param.Next, param.Offset).Select(x => new AppointmentModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, AppointmentDate = x.AppointmentDate, Note = x.Note, Status = x.Status, CancellationReason = x.CancellationReason, EndTime = x.EndTime, IsCancel = x.IsCancel, StartTime = x.StartTime, isAppointmentDone = x.isAppointmentDone, TotalCount = x.overall_count.GetValueOrDefault(), ToUserId = x.ToUserId, FromUserId = x.FromUserId, FromUser = new UserModel { Id = x.FromUserId, FirstName = x.FromUserFirstName, LastName = x.FromUserLastName, PhoneNumber = x.FromUserPhoneNumber }, ToUser = new UserModel { Id = x.ToUserId, FirstName = x.ToUserFirstName, LastName = x.ToUserLastName, PhoneNumber = x.ToUserPhoneNumber }, CreatedUser = new Domain.CreatedUserModel { UserId = x.CreatedBy, FirstName = x.CreatedByFirstName, LastName = x.CreatedByLastName, PhoneNumber = x.CreatedByPhoneNumber }, UpdatedUser = new Domain.UpdatedUserModel { UserId = x.UpdatedBy, FirstName = x.UpdatedByFirstName, LastName = x.UpdatedByLastName, PhoneNumber = x.UpdatedByPhoneNumber }, }).ToList(); } } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/Exception/ExceptionDBService.cs using ProtectedBrowser.Domain.Exception; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.Exception { public class ExceptionDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public void ExceptionLogInsert(ExceptionModel exception) { using (var dbctx = DbContext) { dbctx.InsertExceptionLog(exception.Source, exception.Message, exception.StackTrace, exception.Uri, exception.Method, exception.CreatedBy); } } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/PublicHoliday/PublicHolidayDBService.cs using ProtectedBrowser.Domain; using ProtectedBrowser.Domain.PublicHoliday; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.PublicHoliday { public class PublicHolidayDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public long PublicHolidayInsert(PublicHolidaysModel model) { using (var dbctx = DbContext) { var id = dbctx.PublicHolidaysInsert(model.StartHolidayDate, model.EndHolidayDate, model.Description, model.CreatedBy).FirstOrDefault(); return Convert.ToInt64(id ?? 0); } } public void PublicHolidayUpdate(PublicHolidaysModel model) { using (var dbctx = DbContext) { dbctx.PublicHolidaysUpdate(model.StartHolidayDate, model.EndHolidayDate, model.Description, model.UpdatedBy, model.IsDeleted, model.Id); } } public List<PublicHolidaysModel> PublicHolidaysSelect(SearchParam param) { using (var dbctx = DbContext) { return dbctx.PublicHolidaysSelect(param.Id, param.ToDayDate, param.StartDate, param.EndDate).Select(x => new PublicHolidaysModel { CreatedBy = x.CreatedBy, CreatedDate = x.CreatedDate, Description = x.Description, Id = x.Id, IsDeleted = x.IsDeleted, UpdatedBy = x.UpdatedBy, UpdatedDate = x.UpdatedDate, IsOnlyView = x.IsOnlyView, StartHolidayDate = x.StartHoliday, EndHolidayDate = x.EndHoliday }).ToList(); } } } } <file_sep>/ProtectedBrowser/wwwroot/angular/custom/customController.js (function () { "use strict"; var applicationApp = angular.module("applicationApp"); applicationApp.controller("CustomController", customController); customController.$inject = ["$compile", "$scope", "$state", "$timeout", "$rootScope", "CustomRepository", "FileUploader", "localStorageService", "$window", "$q"]; function customController($compile, $scope, $state, $timeout, $rootScope, CustomRepository, FileUploader, localStorageService, $window, $q) { var vm = this; vm.getChildFolderDetails = getChildFolderDetails; vm.appendChildHtml = appendChildHtml; vm.viewFile = viewFile; vm.encrypt = encrypt; vm.decrypt = decrypt; vm.showMiniLoader = showMiniLoader; vm.hideMiniLoader = hideMiniLoader; vm.loadHtmlWithPagination = loadHtmlWithPagination; vm.cropImage = cropImage; vm.print = print; vm.openNav = openNav; vm.closeNav = closeNav; vm.clearCrop = clearCrop; init(); function init() { vm.folderData = []; vm.childLevel = 0; vm.currentBase = ''; CustomRepository.getRootPath({}, function (response) { if (!response.status) return; vm.path = encodeURIComponent(response.data.rootPath); getFolderDetails(vm.path, true, null, null, null); }); vm.pdfUrl = ''; vm.isProcessInrequesting = false; vm.pageCount = []; vm.paginateData = []; vm.isCropInProcess = false; vm.currentViewFileType = ''; vm.paginationValue = 200; vm.cropper; vm.jcropApi; vm.cropApi; prepareCanvasForAreaSelect(); } function getFolderDetails(path, isRootCall, stringToAppend, hrefVal, element) { vm.isProcessInrequesting = true; CustomRepository.getFolderJson({ sDir: decodeURIComponent(path) }, function (response) { if (!response.status) { showTost("Error:", response.message, "danger"); return; } if (isRootCall) { vm.folderData = response.data; vm.isProcessInrequesting = false; } else { vm.childLevel += 1; vm.appendChildHtml(response.data, stringToAppend, hrefVal, element); } }); } function loadHtmlWithPagination(hrefVal, callFrom) { if (!vm.pageCount[hrefVal]) vm.pageCount[hrefVal] = 0; var html = ``, startFrom = (vm.pageCount[hrefVal] * vm.paginationValue + (vm.pageCount[hrefVal] > 0 ? 1 : 0)), endTo = ((vm.pageCount[hrefVal] + 1) * vm.paginationValue); if (vm.paginateData[hrefVal].length < endTo) endTo = vm.paginateData[hrefVal].length; for (var i = startFrom; i < endTo; i++) { html += `<li class="file-li"><span class="full-display" ng-click='vm.viewFile("` + encrypt(vm.paginateData[hrefVal][i].Path) + `" , "` + vm.paginateData[hrefVal][i].Ext + `", "` + vm.paginateData[hrefVal][i].Name + `", $event);$event.stopPropagation();$event.preventDefault();'><img class ="height-17 margin-right-5" src="images/file.png" /><span>` + vm.paginateData[hrefVal][i].Name + `</span></span></li>` } $('#' + hrefVal + ' #load-more').remove(); if (vm.paginateData[hrefVal].length > endTo) html += `<li id="load-more" ng-click='vm.loadHtmlWithPagination("` + hrefVal + `", "");$event.stopPropagation();$event.preventDefault();'> Load More +</li>`; vm.pageCount[hrefVal]++; if (callFrom == 'innerCall') return html; $("#" + hrefVal).append($compile(html)($scope)); } function appendChildHtml(data, stringToAppend, hrefVal, element) { var html = ``; html += `<ul id="${hrefVal}" class ="collapse in">`; /*Folder append*/ if (data.Folders.length > 0) { for (var i = 0; i < data.Folders.length; i++) { var path = (stringToAppend ? decodeURIComponent(stringToAppend) + '\\\\' : '') + data.Folders[i].Name + ""; html += `<li><a data-toggle="collapse" href=` + '#child-' + vm.childLevel + '-' + i + `><span class="full-display" ng-click='vm.getChildFolderDetails("` + encodeURIComponent(path) + `" , "child-` + vm.childLevel + `-` + i + `", $event);$event.stopPropagation();$event.preventDefault();'><img class ="height-25 margin-right-5" src="images/folder.png" /><span>` + data.Folders[i].Name + `</span></span></a></li>` } } /*Files append*/ if (data.Files.length > 0) { if (data.Files.length > vm.paginationValue) { vm.paginateData[hrefVal] = data.Files; html += loadHtmlWithPagination(hrefVal, 'innerCall'); } else { for (var i = 0; i < data.Files.length; i++) { html += `<li class="file-li"><span class="full-display" ng-click='vm.viewFile("` + encrypt(data.Files[i].Path) + `", "` + data.Files[i].Ext + `", "` + data.Files[i].Name + `", $event);$event.stopPropagation();$event.preventDefault();'><img class ="height-17 margin-right-5" src="images/file.png" /><span>` + data.Files[i].Name + `</span></span></li>` } } } html += `</ul>`; $("[href=#" + hrefVal + "]").parent('li').append($compile(html)($scope)); vm.isProcessInrequesting = false; hideMiniLoader(element, 'folder'); } function getChildFolderDetails(stringToAppend, hrefVal, object) { var element = angular.element(object.target); showMiniLoader(element); if ($('#' + hrefVal + '').length > 0) { $('#' + hrefVal + '').toggle(); hideMiniLoader(element, 'folder'); return; } var path = vm.path + '\\' + stringToAppend; getFolderDetails(path, false, stringToAppend, hrefVal, element); } function viewFile(path, ext, name, object) { var html = ``, memeType = ''; var element = angular.element(object.target); showMiniLoader(element); CustomRepository.getFile({ sDir: decrypt(path), ext: ext, name: name }, function (response) { if (!response.status) return; $("#file-container").html(''); $("#c").remove(); $("#file-container").after('<canvas id="c"></canvas>'); prepareCanvasForAreaSelect(); if (ext == 'jpg' || ext == 'tif' || ext == 'png') { var id = 'image'; vm.currentViewFileType = '#' + id; b64toBlob(response.data.stream, 'image/png').then(function (resp) { vm.currentBase = URL.createObjectURL(resp); // Grab the Canvas and Drawing Context var canvas = document.getElementById('c'); var ctx = canvas.getContext('2d'); // Create an image element var img = document.createElement('IMG'); // When the image is loaded, draw it img.onload = function () { $('#c').attr('width', img.width); $('#c').attr('height', img.height); ctx.drawImage(img, 0, 0); var panzoom = $('#c').panzoom({ $reset: $("#revertZoom"), maxZoom: 1, minZoom: 0.1 }); panzoom.parent().on('mousewheel.focal', function (e) { e.preventDefault(); var delta = e.delta || e.originalEvent.wheelDelta; var zoomOut = delta ? delta < 0 : e.originalEvent.deltaY > 0; panzoom.panzoom('zoom', zoomOut, { increment: 0.1, focal: e }); }); } img.src = vm.currentBase; }); } if (ext == 'pdf') { vm.currentViewFileType = 'canvas'; b64toBlob(response.data.stream, 'application/pdf').then(function (resp) { var blobUrl = URL.createObjectURL(resp); $scope.pdfUrl = blobUrl; html = `<ng-pdf template-url="wwwroot/viewer.html"></ng-pdf>`; $("#file-container").html($compile(html)($scope)); }); } hideMiniLoader(element, 'file'); }); } function print() { var html = ''; html += '<html><head><title></title>'; html += '</head><body>'; html += '<img src="' + $('#crop-viewer').attr('src') + '"/>'; html += '</body></html>'; setTimeout(() => { var myWindow = window.open('', 'PRINT', 'height=400,width=600'); myWindow.document.write(html); myWindow.print(); myWindow.close(); vm.isCropInProcess = false; $('#crop-viewer').css('display', 'none'); $('canvas').css('display', 'inline-block'); }, 1000); } function encrypt(data) { return btoa(JSON.stringify(data)); }; function decrypt(data) { return JSON.parse(atob(data)); }; function _base64ToArrayBuffer(base64) { var deferred = $q.defer(); var binary_string = window.atob(base64); var len = binary_string.length; var bytes = new Uint8Array(len); for (var i = 0; i < len; i++) { bytes[i] = binary_string.charCodeAt(i); } deferred.resolve(bytes.buffer); return deferred.promise; } function b64toBlob(b64Data, contentType, sliceSize) { var deferred = $q.defer(); contentType = contentType || ''; sliceSize = sliceSize || 512; var byteCharacters = atob(b64Data); var byteArrays = []; for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } var blob = new Blob(byteArrays, { type: contentType }); deferred.resolve(blob); return deferred.promise; } function showMiniLoader(object) { vm.isCropInProcess = false; clearCrop(); $('#crop-viewer').css('display', 'none'); $('canvas').css('display', 'inline-block'); $(object).parent('.full-display').children('img').remove(); $(object).prepend('<i class="margin-right-5 font-size-15 fa fa-spinner fa-spin"></i>'); } function hideMiniLoader(object, callFrom) { $(object).children('i').remove(); $(object).parent('.full-display').prepend(callFrom == "folder" ? '<img class="margin-right-5 height-25" src="images/folder.png" />' : '<img class="margin-right-5 height-17" src="images/file.png" />'); closeNav(); } function updatePreviewForPdf(c) { if (parseInt(c.w) > 0) { var canvas = $(vm.currentViewFileType), tempCanvas = document.createElement("canvas"), tCtx = tempCanvas.getContext("2d"); tempCanvas.width = 640; tempCanvas.height = 480; tCtx.drawImage(canvas[0], c.x, c.y, c.w, c.h, 0, 0, c.w, c.h); var img = tempCanvas.toDataURL("image/png"); $('#crop-viewer').attr('src', img).css('display', 'block'); } } function updatePreviewForTif(selection) { if (!selection.width || !selection.height) { return; } var canvas = $('#c'), tempCanvas = document.createElement("canvas"), tCtx = tempCanvas.getContext("2d"); tempCanvas.width = 640; tempCanvas.height = 480; tCtx.drawImage(canvas[0], selection.x1, selection.y1, selection.width, selection.height, 0, 0, selection.width, selection.height); var img = tempCanvas.toDataURL("image/png"); $('#crop-viewer').attr('src', img).css('display', 'block'); } function prepareCanvasForAreaSelect() { vm.cropApi = $('#c').imgAreaSelect({ instance: true, handles: true, disable: true, onSelectEnd: function (img, selection) { updatePreviewForTif(selection); }, onSelectStart: function (img, selection) { updatePreviewForTif(selection); }, onSelectChange: function (img, selection) { updatePreviewForTif(selection); } }); } function cropImage() { vm.isCropInProcess = true; if (vm.currentViewFileType == '#image') { $('#c').panzoom("reset"); $('#c').panzoom("disable"); // $('#c')[0].style.cssText = ""; vm.cropApi.setOptions({ enable: true }); return; } vm.jcropApi = $.Jcrop(vm.currentViewFileType, { onChange: updatePreviewForPdf, onSelect: updatePreviewForPdf, allowSelect: true, allowMove: true, allowResize: true, aspectRatio: 0 }); } function clearCrop() { // Disable crop Pdf's if (vm.jcropApi) vm.jcropApi.destroy(); // Disable crop Images vm.cropApi.setOptions({ hide: true, disable: true }); $('#c').panzoom("enable"); } function openNav() { $('#mySidenav').css('width', '65px'); } function closeNav() { $('#mySidenav').css('width', '0'); } } }());<file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/User/TokenViewModel.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.User { public class TokenViewModel { [JsonProperty("access_token")] public string AccessToken { get; set; } [JsonProperty("token_type")] public string TokenType { get; set; } [JsonIgnore] [JsonProperty("expires_in")] public int ExpiresIn { get; set; } [JsonIgnore] [JsonProperty(".issued")] public string Issued { get; set; } [JsonIgnore] [JsonProperty("expires")] public DateTimeOffset Expires { get; set; } [JsonIgnore] [JsonProperty("error")] public string Error { get; set; } [JsonIgnore] [JsonProperty("error_description")] public string ErrorDescription { get; set; } [JsonIgnore] [JsonProperty("roles")] public IList<string> Role { get; set; } [JsonProperty("RoleString")] public string RoleString { get { return _roleString; } set { _roleString = value; if (!string.IsNullOrEmpty(_roleString)) Role = JsonConvert.DeserializeObject<IList<string>>(_roleString); } } string _roleString; public bool ShouldSerializeRoleString() { return false; } [JsonProperty("tokenData")] public tokenData TokenData { get; set; } } public class tokenData { [JsonProperty("user")] public UserViewModel User { get; set; } [JsonProperty("token")] public tokenObj Token { get; set; } } public class tokenObj { [JsonProperty("accessToken")] public string AccessToken { get; set; } [JsonProperty("tokenType")] public string TokenType { get; set; } [JsonProperty("expires")] public DateTimeOffset Expires { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/CustomFilters/ValidateMimeMultipartContentFilter.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Filters; namespace ProtectedBrowser.Framework.CustomFilters { public class ValidateMimeMultipartContentFilter : ActionFilterAttribute { public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { if (!actionContext.Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } } public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/WebExtensions/ViewModelToModel.cs using ProtectedBrowser.Common.Extensions; using ProtectedBrowser.Domain.DailyWorkSetting; using ProtectedBrowser.Domain.DummyFileUpload; using ProtectedBrowser.Domain.Upload; using ProtectedBrowser.Framework.ViewModels.DailyWorkSetting; using ProtectedBrowser.Framework.ViewModels.DummyFileUpload; using ProtectedBrowser.Framework.ViewModels.Upload; using System.Linq; namespace ProtectedBrowser.Framework.WebExtensions { public static class ViewModelToModel { public static DailyWorkSettingModel ToModel(this DailyWorkSettingViewModel x) { if (x == null) return new DailyWorkSettingModel(); return new DailyWorkSettingModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, StartLunchTime = x.StartLunchTime, Saturday = x.Saturday, Monday = x.Monday, Friday = x.Friday, EndTime = x.EndTime, EndLunchTime = x.EndLunchTime, StartTime = x.StartTime, Sunday = x.Sunday, Thursday = x.Thursday, Tuesday = x.Tuesday, Wednesday = x.Wednesday }; } public static FileGroupItemsModel ToModel(this FileGroupItemsViewModel x) { if (x == null) return new FileGroupItemsModel(); return new FileGroupItemsModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, Filename = x.Filename, MimeType = x.MimeType, Thumbnail = x.Thumbnail, Size = x.Size, Path = x.Path, OriginalName = x.OriginalName, OnServer = x.OnServer, TypeId = x.TypeId, Type=x.Type }; } public static DummyTableForFileModel ToModel(this DummyTableForFileViewModel x) { if (x == null) return new DummyTableForFileModel(); return new DummyTableForFileModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, Name = x.Name, FileGroupItems=x.FileGroupItems != null ? x.FileGroupItems.Select(y => y.ToModel()).ToList() : null, FileGroupItem = x.FileGroupItem != null ? x.FileGroupItem.ToModel() : null, FileGroupItemsXml =x.FileGroupItems.XmlSerialize(), }; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/BaseViewEntity.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels { public class BaseViewEntity { [JsonProperty("createdUser")] public CreatedUserViewModel CreatedUser { get; set; } [JsonProperty("updatedUser")] public UpdatedUserViewModel UpdatedUser { get; set; } } /// <summary> /// It represent the common auditable field for a record /// </summary> /// public class CreatedUserViewModel { [JsonProperty("firstName")] public string FirstName { get; set; } [JsonProperty("lastName")] public string LastName { get; set; } [JsonProperty("phoneNumber")] public string PhoneNumber { get; set; } [JsonProperty("userId")] public long? UserId { get; set; } [JsonProperty("fullName")] public string FullName { get; set; } } public class UpdatedUserViewModel { [JsonProperty("firstName")] public string FirstName { get; set; } [JsonProperty("lastName")] public string LastName { get; set; } [JsonProperty("phoneNumber")] public string PhoneNumber { get; set; } [JsonProperty("userId")] public long? UserId { get; set; } [JsonProperty("fullName")] public string FullName { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Blog/BlogService.cs using ProtectedBrowser.DBRepository.Blog; using ProtectedBrowser.Domain.Blog; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Blog { public class BlogService : IBlogService { public BlogDBService _blogDBService; public BlogService() { _blogDBService = new BlogDBService(); } public long BlogInsert(BlogModel model) { return _blogDBService.BlogInsert(model); } public void BlogUpdate(BlogModel model) { _blogDBService.BlogUpdate(model); } public List<BlogModel> BlogSelect(long? blogId, long? categoryId, bool? isActive = null, int? next = null, int? offset = null) { return _blogDBService.BlogSelect(blogId, categoryId, isActive, next, offset); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/Category/CategoryDbService.cs using ProtectedBrowser.Domain.Category; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.Category { public class CategoryDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public long CategoryInsert(CategoryModel model) { using (var dbctx = DbContext) { var id = dbctx.CategoryInsert(model.Name, model.IsActive, model.CreatedBy).FirstOrDefault(); return Convert.ToInt64(id ?? 0); } } public void CategoryUpdate(CategoryModel model) { using (var dbctx = DbContext) { dbctx.CategoryUpdate(model.Id, model.Name, model.IsActive, model.IsDeleted, model.UpdatedBy); } } public List<CategoryModel> CategorySelect(long? categoryId, bool? isActive = null, int? next = null, int? offset = null) { using (var dbctx = DbContext) { return dbctx.CategorySelect(categoryId, isActive, next, offset).Select(x => new CategoryModel { IsActive = x.IsActive, Name = x.Name, CreatedBy = x.CreatedBy, Id = x.Id, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, TotalCount = x.overall_count.GetValueOrDefault(), UpdatedBy = x.UpdatedBy }).ToList(); } } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Users/IUserService.cs using ProtectedBrowser.Domain.Users; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Users { public interface IUserService { UserModel SelectUserByUniqueCode(string uniqueCode); } } <file_sep>/ProtectedBrowser/wwwroot/js/common.js function customDeleteConfirmation(callback, param1, param2, param3) { swal({ title: "Are you sure?", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, delete it!", closeOnConfirm: true, allowEscapeKey: false }, function () { callback(param1, param2, param3); }); } function customTextConfirmation(mainText, subText, callback, param1, param2) { swal({ title: mainText, type: "info", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: subText, closeOnConfirm: false, allowEscapeKey: false }, function () { callback(param1, param2); }); } function customMessageAlert(_message, _type) { swal({ title: _message, type: _type, html: true, allowEscapeKey: false }); } function showTost(title, message, type) { $.notify({ title: title, message: message, icon: (type == "info" || type == "success") ? 'fa fa-check' : 'fa fa-times' }, { type: type, allow_dismiss: false, placement: { from: "top", align: "right" }, newest_on_top: true, offset: 20, z_index: 1031, delay: 5000, timer: 1000, }); } <file_sep>/ProtectedBrowser/wwwroot/angular/common/commonUtils.js (function () { var commonService = angular.module("common.services"); commonService.factory("CommonUtils", commonUtils); commonUtils.$inject = ["$resource", "CONSTANTS", "localStorageService", "$translate"]; function commonUtils($resource, CONSTANTS, localStorageService, $translate) { var chosenLanguage = CONSTANTS.DEFAULT_LANGUAGE; return { logging: logging, setChosenLanguage: setChosenLanguage, getChosenLanguage: getChosenLanguage }; function logging(type, message, functionName, fileName) { if (!CONSTANTS.IS_PRODUCTION) { console.log("Type:" + type + " In Function:" + functionName + " In File: " + fileName); console.log(message); } } function setChosenLanguage(language) { $translate.use(language); localStorageService.set('chosenLanguage', language); chosenLanguage = language; } function getChosenLanguage() { /* if (localStorageService.get('chosenLanguage') !== null) { chosenLanguage = localStorageService.get('chosenLanguage'); }*/ return chosenLanguage; } } }()); <file_sep>/ProtectedBrowser/wwwroot/angular/custom/customRepository.js (function () { var commonService = angular.module("common.services"); commonService.factory("CustomRepository", customRepository); customRepository.$inject = ["$resource"]; function customRepository($resource) { return $resource("", {}, { getRootPath: { method: 'GET', params: {}, isArray: false, url: secureApiBaseUrl + "getrootpath" }, getFolderJson: { method: 'GET', params: {}, isArray: false, url: secureApiBaseUrl + "folderjson" }, getFile: { method: 'GET', params: {}, isArray: false, url: secureApiBaseUrl + "filereader" } }); } }()); <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/FileGroup/FileGroupService.cs using ProtectedBrowser.Common.Extensions; using ProtectedBrowser.DBRepository.FileGroup; using ProtectedBrowser.Domain.Upload; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace ProtectedBrowser.Service.FileGroup { public class FileGroupService:IFileGroupService { public FileGroupDBService _fileGroupDBService; public FileGroupService() { _fileGroupDBService = new FileGroupDBService(); } public void FileGroupItemsDelete(long? id, long? updatedBy) { _fileGroupDBService.FileGroupItemsDelete(id, updatedBy); } public long FileGroupItemsInsert(FileGroupItemsModel model) { return _fileGroupDBService.FileGroupItemsInsert(model); } public void FileGroupItemsInsertXml(long? userId, long? typeId, string attachmentFileXml) { _fileGroupDBService.FileGroupItemsInsertXml(userId, typeId, attachmentFileXml); } public List<FileGroupItemsModel> SetPathAndMoveFile(List<FileGroupItemsModel> model, long? id) { string path = HttpContext.Current.Server.MapPath("\\file"); string sourecPath = HttpContext.Current.Server.MapPath("\\tempfolder"); foreach (var item in model) { if (item.Id == 0 || item.Id == null) { item.Path = MoveFileToTarget.MoveFile(sourecPath + "\\" + item.Filename, path + "\\" + id.ToString(), item.OriginalName, id); item.Filename = item.OriginalName; item.Thumbnail = item.Path; } } return model; } public FileGroupItemsModel SetPathAndMoveSingleFile(FileGroupItemsModel model, long? id) { string path = HttpContext.Current.Server.MapPath("\\file"); string sourecPath = HttpContext.Current.Server.MapPath("\\tempfolder"); model.Path = MoveFileToTarget.MoveFile(sourecPath + "\\" + model.Filename, path + "\\" + id.ToString(), model.OriginalName, id); model.Filename = model.OriginalName; model.Thumbnail = model.Path; return model; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/Users/UserModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.Users { public class UserModel { public long? Id { get; set; } public string Email { get; set; } public bool EmailConfirmed { get; set; } public string PhoneNumber { get; set; } public string UserName { get; set; } public string FullName { get; set; } public string UserProfileEmail { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string ProfileImageUrl { get; set; } public string RoleName { get; set; } public bool IsActive { get; set; } public string MobileNo { get; set; } public Nullable<long> CreatedBy { get; set; } public Nullable<long> UpdatedBy { get; set; } public string Gender { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public int? Pin { get; set; } public string Address { get; set; } public string UniqueCode { get; set; } public string Password { get; set; } public string Code { get; set; } public bool IsDeleted { get; set; } public string Base64String { get; set; } public string OldPassword { get; set; } public IList<string> Roles { get; set; } public bool? IsFacebookConnected { get; set; } public bool? IsGoogleConnected { get; set; } public string FacebookId { get; set; } public string GoogleId { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/PublicHoliday/PublicHolidaysModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.PublicHoliday { public class PublicHolidaysModel { public long? Id { get; set; } public Nullable<System.DateTimeOffset> StartHolidayDate { get; set; } public Nullable<System.DateTimeOffset> EndHolidayDate { get; set; } public string Description { get; set; } public bool? IsDeleted { get; set; } public Nullable<long> CreatedBy { get; set; } public Nullable<long> UpdatedBy { get; set; } public System.DateTimeOffset CreatedDate { get; set; } public System.DateTimeOffset UpdatedDate { get; set; } public Nullable<System.DateTimeOffset> StartDate { get; set; } public Nullable<System.DateTimeOffset> EndDate { get; set; } public Nullable<bool> IsOnlyView { get; set; } public Nullable<System.DateTimeOffset> TodayDate { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser/TextTemplate/TextTemplateDemo.cs  // This is generated code: <file_sep>/ProtectedBrowser/API/DirectoryController.cs using ProtectedBrowser.Framework.CustomFilters; using ProtectedBrowser.Framework.GenericResponse; using ProtectedBrowser.Framework.ViewModels.Directory; using ProtectedBrowser.Framework.WebExtensions; using ProtectedBrowser.Service.Directory; using Microsoft.AspNet.Identity; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.IO; using System.Runtime.InteropServices; using System.ComponentModel; using ProtectedBrowser.Domain.Directory; using System.Security.Cryptography; using System.IO.MemoryMappedFiles; using System.Web; using System.Text; using System.Drawing; using PdfSharp.Pdf; using System.Drawing.Imaging; using PdfSharp.Drawing; using PdfSharp; //using System.Windows.Media.Imaging; namespace ProtectedBrowser.API { [RoutePrefix("api")] [CustomExceptionFilter] public class DirectoryController : ApiController { private IDirectoryService _directoryService; public DirectoryController(IDirectoryService directoryService) { _directoryService = directoryService; } /// <summary> /// Api use for get all Directory /// </summary> /// <returns></returns> [Route("Directorys")] [Authorize(Roles = "ROLE_ADMIN")] [HttpGet] public IHttpActionResult GetAllDirectorys() { var directorys = _directoryService.SelectDirectory(null).Select(x => x.ToViewModel()); ; return Ok(directorys.SuccessResponse()); } /// <summary> /// Api use for get all Active Directory with Limit and Offset /// </summary> /// <returns></returns> [Route("active-directorys/{pageSize:int}/{pageNumber:int}")] [HttpGet] public IHttpActionResult ActiveDirectorys(int pageSize = 10, int pageNumber = 1) { var directorys = _directoryService.SelectDirectory(null, true, pageSize, pageNumber).Select(x => x.ToViewModel()); ; return Ok(directorys.SuccessResponse()); } /// <summary> /// Api use for get directory by id /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("directory/{id:long}")] [HttpGet] public IHttpActionResult GetDirectory(long id) { var directory = _directoryService.SelectDirectory(id).FirstOrDefault().ToViewModel(); return Ok(directory.SuccessResponse()); } /// <summary> /// Api use for save directory /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("directory")] [Authorize(Roles = "ROLE_ADMIN")] [HttpPost] public IHttpActionResult SaveDirectory(DirectoryViewModel model) { model.CreatedBy = User.Identity.GetUserId<long>(); model.UpdatedBy = User.Identity.GetUserId<long>(); var responseId = _directoryService.DirectoryInsert(model.ToModel()); return Ok(responseId.SuccessResponse("Directory save successfully")); } /// <summary> /// Api use for update directory /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("directory")] [Authorize(Roles = "ROLE_ADMIN")] [CustomExceptionFilter] [HttpPut] public IHttpActionResult UpdateDirectory(DirectoryViewModel model) { _directoryService.DirectoryUpdate(model.ToModel()); return Ok("Directory Update successfully".SuccessResponse()); } /// <summary> /// Api use for delete directory by id /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("directory/{id:long}")] [Authorize(Roles = "ROLE_ADMIN")] [CustomExceptionFilter] [HttpDelete] public IHttpActionResult DeleteDirectory(long id) { DirectoryViewModel model = new DirectoryViewModel(); model.Id = id; model.IsDeleted = true; _directoryService.DirectoryUpdate(model.ToModel()); return Ok("Directory Deleted successfully".SuccessResponse()); } [Route("getrootpath")] [HttpGet] [AllowAnonymous] public IHttpActionResult GetRootPath() { var directory = _directoryService.SelectDirectory(10002).FirstOrDefault().ToViewModel(); return Ok(directory.SuccessResponse()); } [Route("folderjson")] [HttpGet] [AllowAnonymous] public IHttpActionResult GetFolderJson(string sDir) { List<RawData> Files = new List<RawData>(); List<RawData> Folders = new List<RawData>(); var directory = _directoryService.SelectDirectory(10002).FirstOrDefault().ToViewModel(); string networkPath = directory.RootPath; NetworkCredential theNetworkCredential = new NetworkCredential(@directory.UserName, directory.Password); //using (new ConnectToSharedFolder(networkPath, theNetworkCredential)) //{ string[] files = Directory.GetFiles(sDir); string[] folders = Directory.GetDirectories(sDir); foreach (string file in files) { string[] x = file.Split('\\'); string name = x[x.Length - 1]; var f = new RawData { Name = name, Path = file, Type = "file", Ext = name.Split('.')[name.Split('.').Length - 1] }; Files.Add(f); } foreach (string folder in folders) { string[] x = folder.Split('\\'); string name = x[x.Length - 1]; var f = new RawData { Name = name, Path = folder, Type = "folder", Ext = "" }; Folders.Add(f); } //} return Ok(new GetFilesFolder { Files = Files, Folders = Folders }.SuccessResponse()); } private ImageCodecInfo GetEncoderInfo(string mimeType) { // Get image codecs for all image formats ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); // Find the correct image codec for (int i = 0; i < codecs.Length; i++) if (codecs[i].MimeType == mimeType) return codecs[i]; return null; } [Route("filereader")] [HttpGet] [AllowAnonymous] public IHttpActionResult Base64Encode(string sDir, string ext, string name) { FileStream fs; var directory = _directoryService.SelectDirectory(10002).FirstOrDefault().ToViewModel(); string networkPath = directory.RootPath; NetworkCredential theNetworkCredential = new NetworkCredential(@directory.UserName, directory.Password); //using (new ConnectToSharedFolder(networkPath, theNetworkCredential)) //{ if (ext == "tif" && !File.Exists("C:\\op\\" + name.Split('.')[0] + ".png")) { string destinaton = @"C:\\op\\"+ name.Split('.')[0] +".png"; Bitmap bitmap = (Bitmap)Image.FromFile(sDir); MemoryStream byteStream = new MemoryStream(); bitmap.Save(byteStream, ImageFormat.Tiff); Image tiff = Image.FromStream(byteStream); ImageCodecInfo encoderInfo = GetEncoderInfo("image/png"); EncoderParameters encoderParams = new EncoderParameters(2); EncoderParameter parameter = new EncoderParameter( System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4); encoderParams.Param[0] = parameter; parameter = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame); encoderParams.Param[1] = parameter; tiff.Save(destinaton, encoderInfo, encoderParams); } try { byte[] buffer; FileStream fileStream = new FileStream((ext == "tif" ? "C:\\op\\" + name.Split('.')[0] + ".png" : sDir), FileMode.Open, FileAccess.Read); fileStream.Flush(); try { int length = (int)fileStream.Length; // get file length buffer = new byte[length]; // create buffer int count; // actual number of bytes read int sum = 0; // total number of bytes read // read until Read method returns 0 (end of the stream has been reached) while ((count = fileStream.Read(buffer, sum, length - sum)) > 0) sum += count; // sum is a buffer offset for next reading } finally { fileStream.Close(); } return Ok(new { stream = Convert.ToBase64String(buffer.ToArray()) }.SuccessResponse()); } catch (Exception ex) { return Ok(ex.InnerException.Message.ErrorResponse()); } //} } } public class ConnectToSharedFolder : IDisposable { readonly string _networkName; public ConnectToSharedFolder(string networkName, NetworkCredential credentials) { _networkName = networkName; var netResource = new NetResource { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplaytype.Share, RemoteName = networkName }; var userName = string.IsNullOrEmpty(credentials.Domain) ? credentials.UserName : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName); var result = WNetAddConnection2( netResource, credentials.Password, userName, 0); if (result != 0) { throw new Win32Exception(result, "Error connecting to remote share"); } } ~ConnectToSharedFolder() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { WNetCancelConnection2(_networkName, 0, true); } [DllImport("mpr.dll")] private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flags); [DllImport("mpr.dll")] private static extern int WNetCancelConnection2(string name, int flags, bool force); [StructLayout(LayoutKind.Sequential)] public class NetResource { public ResourceScope Scope; public ResourceType ResourceType; public ResourceDisplaytype DisplayType; public int Usage; public string LocalName; public string RemoteName; public string Comment; public string Provider; } public enum ResourceScope : int { Connected = 1, GlobalNetwork, Remembered, Recent, Context }; public enum ResourceType : int { Any = 0, Disk = 1, Print = 2, Reserved = 8, } public enum ResourceDisplaytype : int { Generic = 0x0, Domain = 0x01, Server = 0x02, Share = 0x03, File = 0x04, Group = 0x05, Network = 0x06, Root = 0x07, Shareadmin = 0x08, Directory = 0x09, Tree = 0x0a, Ndscontainer = 0x0b } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/DailyWorkSetting/DailyWorkSettingService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ProtectedBrowser.Domain.DailyWorkSetting; using ProtectedBrowser.DBRepository.DailyWorkSetting; namespace ProtectedBrowser.Service.DailyWorkSetting { public class DailyWorkSettingService : IDailyWorkSettingService { private DailyWorkSettingDBService _dailyWorkSettingDBService; public DailyWorkSettingService() { _dailyWorkSettingDBService = new DailyWorkSettingDBService(); } public int DailyWorkSettingAction(DailyWorkSettingModel model) { return _dailyWorkSettingDBService.DailyWorkSettingAction(model); } public DailyWorkSettingModel DailyWorkSettingSelect() { return _dailyWorkSettingDBService.DailyWorkSettingSelect(); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Leave/ILeaveService.cs using ProtectedBrowser.Domain; using ProtectedBrowser.Domain.Leave; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Leave { public interface ILeaveService { long LeaveInsert(LeaveModel model); void LeaveUpdate(LeaveModel model); List<LeaveModel> LeaveSelect(SearchParam param); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/DailyWorkSetting/IDailyWorkSettingService.cs using ProtectedBrowser.Domain.DailyWorkSetting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.DailyWorkSetting { public interface IDailyWorkSettingService { int DailyWorkSettingAction(DailyWorkSettingModel model); DailyWorkSettingModel DailyWorkSettingSelect(); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/DailyWorkSetting/DailyWorkSettingModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.DailyWorkSetting { public class DailyWorkSettingModel { public int? Id { get; set; } public bool? Sunday { get; set; } public bool? Monday { get; set; } public bool? Tuesday { get; set; } public bool? Wednesday { get; set; } public bool? Thursday { get; set; } public bool? Friday { get; set; } public bool? Saturday { get; set; } public TimeSpan? StartTime { get; set; } public TimeSpan? EndTime { get; set; } public TimeSpan? StartLunchTime { get; set; } public TimeSpan? EndLunchTime { get; set; } public long? CreatedBy { get; set; } public long? UpdatedBy { get; set; } public DateTimeOffset? UpdatedDate { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/Appointment/AppointmentModel.cs using ProtectedBrowser.Domain.Users; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.Appointment { public class AppointmentModel : BaseEntity { public long? Id { get; set; } public long? CreatedBy { get; set; } public long? UpdatedBy { get; set; } public DateTimeOffset? CreatedOn { get; set; } public DateTimeOffset? UpdatedOn { get; set; } public bool? IsDeleted { get; set; } public bool? IsActive { get; set; } public DateTimeOffset? AppointmentDate { get; set; } public string Note { get; set; } public string Status { get; set; } public long? ToUserId { get; set; } public long? FromUserId { get; set; } public bool? IsCancel { get; set; } public string CancellationReason { get; set; } public TimeSpan? StartTime { get; set; } public TimeSpan? EndTime { get; set; } public bool? isAppointmentDone { get; set; } public int TotalCount { get; set; } public UserModel FromUser { get; set; } public UserModel ToUser { get; set; } } public class AppointmentTimeSlot { public TimeSpan? StartTime { get; set; } public TimeSpan? EndTime { get; set; } public bool IsBooked { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/ContactUs/ContactUsDBService.cs using ProtectedBrowser.Domain.ContactUs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.ContactUs { public class ContactUsDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public void ContactUsInsert(ContactUsModel model) { using (var dbctx = DbContext) { dbctx.ContactUsInsert(model.Name, model.PhoneNumber, model.EmailAddress, model.Message); } } public void ContactUsDelete(long? id) { using (var dbctx = DbContext) { dbctx.ContactUsDelete(id); } } public List<ContactUsModel> ContactUsSelect(long? id, int? next = null, int? offset = null) { using (var dbctx = DbContext) { return dbctx.ContactUsSelect(id, next, offset).Select(x => new ContactUsModel { Id = x.Id, Name = x.Name, CreatedOn = x.CreatedOn, PhoneNumber = x.PhoneNumber, EmailAddress = x.EmailAddress, Message = x.Message }).ToList(); } } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Category/ICategoryService.cs using ProtectedBrowser.Domain.Category; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Category { public interface ICategoryService { /// <summary> /// use for insert user /// </summary> /// <param name="model"></param> /// <returns></returns> long CategoryInsert(CategoryModel model); /// <summary> /// Method for update category /// </summary> /// <param name="model"></param> void CategoryUpdate(CategoryModel model); /// <summary> /// use for select all category or select category by id /// </summary> /// <param name="model"></param> /// <returns></returns> List<CategoryModel> CategorySelect(long? categoryId, bool? isActive = null, int? next = null, int? offset = null); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser/GenericResponse/GenericResponseExtension.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ProtectedBrowser.GenericResponse { public static class GenericResponseExtension { /// <summary> /// It create success response /// </summary> /// <typeparam name="T">Type of data for response</typeparam> /// <param name="obj">Object for create response</param> /// <param name="message">Additional string message for response</param> /// <returns><see cref="ApiRespone{T}"/></returns> public static ApiResponse<T> SuccessResponse<T>(this T obj, string message = null) { //if obj is string message then send it as message if (typeof(T) == typeof(string)) { return new ApiResponse<T> { Status = true, Message = obj as string }; } return new ApiResponse<T> { Data = obj, Status = true, Message = message }; } /// <summary> /// It Create error resposne /// </summary> /// <typeparam name="T">Type of data for response</typeparam> /// <param name="obj">Object for create response</param> /// <param name="message">Additional string message for response</param> /// <returns><see cref="ApiRespone{T}"/></returns> public static ApiResponse<T> ErrorResponse<T>(this T obj, string message = null) { if (typeof(T) == typeof(string)) { return new ApiResponse<T> { Status = false, Message = obj as string }; } return new ApiResponse<T> { Data = obj, Status = false, Message = message }; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.DBRepository/DailyWorkSetting/DailyWorkSettingDBService.cs using ProtectedBrowser.Domain.DailyWorkSetting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.DBRepository.DailyWorkSetting { public class DailyWorkSettingDBService { ProtectedBrowserEntities DbContext { get { return new ProtectedBrowserEntities(); } } public int DailyWorkSettingAction(DailyWorkSettingModel model) { using (var dbctx = DbContext) { var id = dbctx.DailyWorkSettingAction(model.Sunday, model.Monday, model.Tuesday, model.Wednesday, model.Thursday, model.Friday, model.Saturday, model.StartTime, model.EndTime, model.StartLunchTime, model.EndLunchTime, model.CreatedBy, model.Id).FirstOrDefault(); return Convert.ToInt32(id ?? 0); } } public DailyWorkSettingModel DailyWorkSettingSelect() { using (var dbctx = DbContext) { return dbctx.DailyWorkSettingSelect().Select(x => new DailyWorkSettingModel { CreatedBy = x.CreatedBy, EndLunchTime = x.EndLunchTime, EndTime = x.EndTime, Friday = x.Friday, Id = x.Id, Monday = x.Monday, Saturday = x.Satureday, StartLunchTime = x.StartLunchTime, StartTime = x.StartTime, Sunday = x.Sunday, Thursday = x.Thursday, Tuesday = x.Tuesday, UpdatedBy = x.UpdatedBy, Wednesday = x.Wednesday, UpdatedDate = x.UpdatedDate }).FirstOrDefault(); } } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/User/UserViewModel.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.User { public class UserViewModel { [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("emailConfirmed")] public bool? EmailConfirmed { get; set; } [JsonProperty("phoneNumber")] public string PhoneNumber { get; set; } [JsonProperty("userName")] public string UserName { get; set; } [JsonProperty("fullName")] public string FullName { get; set; } [JsonProperty("userProfileEmail")] public string UserProfileEmail { get; set; } [JsonProperty("firstName")] public string FirstName { get; set; } [JsonProperty("lastName")] public string LastName { get; set; } [JsonProperty("profileImageUrl")] public string ProfileImageUrl { get; set; } [JsonProperty("roleName")] public string RoleName { get; set; } [JsonProperty("isActive")] public bool? IsActive { get; set; } [JsonProperty("mobileNo")] public string MobileNo { get; set; } [JsonProperty("createdBy")] public Nullable<long> CreatedBy { get; set; } [JsonProperty("updatedBy")] public Nullable<long> UpdatedBy { get; set; } [JsonProperty("gender")] public string Gender { get; set; } [JsonProperty("city")] public string City { get; set; } [JsonProperty("state")] public string State { get; set; } [JsonProperty("country")] public string Country { get; set; } [JsonProperty("pin")] public int? Pin { get; set; } [JsonProperty("address")] public string Address { get; set; } [JsonProperty("uniqueCode")] public string UniqueCode { get; set; } [JsonProperty("password")] public string Password { get; set; } [JsonProperty("code")] public string Code { get; set; } [JsonProperty("isDeleted")] public bool IsDeleted { get; set; } [JsonProperty("base64String")] public string Base64String { get; set; } [JsonProperty("oldPassword")] public string OldPassword { get; set; } [JsonProperty("roles")] public IList<string> Roles { get; set; } [JsonProperty("isFacebookConnected")] public bool? IsFacebookConnected { get; set; } [JsonProperty("isGoogleConnected")] public bool? IsGoogleConnected { get; set; } [JsonProperty("facebookId")] public string FacebookId { get; set; } [JsonProperty("googleId")] public string GoogleId { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Upload/IFileUploadService.cs using ProtectedBrowser.Domain.Upload; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Upload { public interface IFileUploadService { Task<FileUpload> HandleRequest(HttpRequestMessage request); List<FileUpload> ProcessFile(Collection<MultipartFileData> FileData); List<FileGroupItemsModel> ProcessDocs(Collection<MultipartFileData> FileData, int length); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/WebExtensions/ModelToViewModel.cs using ProtectedBrowser.Domain.DailyWorkSetting; using ProtectedBrowser.Domain.DummyFileUpload; using ProtectedBrowser.Domain.Upload; using ProtectedBrowser.Domain.Users; using ProtectedBrowser.Framework.ViewModels.DailyWorkSetting; using ProtectedBrowser.Framework.ViewModels.DummyFileUpload; using ProtectedBrowser.Framework.ViewModels.Upload; using ProtectedBrowser.Framework.ViewModels.User; using System.Linq; namespace ProtectedBrowser.Framework.WebExtensions { public static class ModelToViewModel { public static DailyWorkSettingViewModel ToViewModel(this DailyWorkSettingModel x) { if (x == null) return new DailyWorkSettingViewModel(); return new DailyWorkSettingViewModel { Id = x.Id, UpdatedBy = x.UpdatedBy, CreatedBy = x.CreatedBy, Wednesday = x.Wednesday, Tuesday = x.Tuesday, Thursday = x.Thursday, Sunday = x.Sunday, StartTime = x.StartTime, EndLunchTime = x.EndLunchTime, EndTime = x.EndTime, Friday = x.Friday, Monday = x.Monday, Saturday = x.Saturday, StartLunchTime = x.StartLunchTime, }; } public static FileGroupItemsViewModel ToViewModel(this FileGroupItemsModel x) { if (x == null) return new FileGroupItemsViewModel(); return new FileGroupItemsViewModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, Filename = x.Filename, MimeType = x.MimeType, Thumbnail = x.Thumbnail, Size = x.Size, Path = x.Path, OriginalName = x.OriginalName, OnServer = x.OnServer, TypeId = x.TypeId, }; } public static DummyTableForFileViewModel ToViewModel(this DummyTableForFileModel x) { if (x == null) return new DummyTableForFileViewModel(); return new DummyTableForFileViewModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, Name = x.Name, CreatedUser = x.CreatedUser != null ? x.CreatedUser.ToViewModel() : null, UpdatedUser = x.UpdatedUser != null ? x.UpdatedUser.ToViewModel() : null, FileGroupItems = x.FileGroupItems != null ? x.FileGroupItems.Select(y => y.ToViewModel()).ToList() : null, FileGroupItem = x.FileGroupItem != null ? x.FileGroupItem.ToViewModel() : null }; } public static UserViewModel ToViewModel(this UserModel x) { if (x == null) return new UserViewModel(); return new UserViewModel { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, FullName = x.FirstName + " " + x.LastName, PhoneNumber = x.PhoneNumber, Email = x.Email, Address=x.Address, City=x.City, Code=x.Code, Country=x.Country, CreatedBy=x.CreatedBy, FacebookId=x.FacebookId, Gender=x.Gender, GoogleId=x.GoogleId, IsActive=x.IsActive, IsDeleted=x.IsDeleted, IsFacebookConnected=x.IsFacebookConnected, IsGoogleConnected=x.IsGoogleConnected, ProfileImageUrl=x.ProfileImageUrl }; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/DependancyRegisterar.cs using Autofac; using Autofac.Integration.Mvc; using Autofac.Integration.WebApi; using ProtectedBrowser.Core.Infrastructure; using ProtectedBrowser.Service.Upload; using ProtectedBrowser.Service.Users; using ProtectedBrowser.Service.Xml; using ProtectedBrowser.Service.FileGroup; using ProtectedBrowser.Service.Directory; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ProtectedBrowser.Service.Configuration; namespace ProtectedBrowser.Framework { public class DependancyRegisterar : IDependencyRegistrar { public int Order { get { return 0; } } public void Register(ContainerBuilder builder, ITypeFinder typeFinder) { var assemblyArr = typeFinder.GetAssemblies().ToArray(); builder.RegisterControllers(assemblyArr); builder.RegisterApiControllers(assemblyArr); builder.RegisterType<UserService>().As<IUserService>().InstancePerLifetimeScope(); builder.RegisterType<FileUploadService>().As<IFileUploadService>().InstancePerLifetimeScope(); builder.RegisterType<XmlService>().As<IXmlService>().InstancePerLifetimeScope(); builder.RegisterType<EmailConfigurationService>().As<IEmailConfigurationService>().InstancePerLifetimeScope(); builder.RegisterType<FileGroupService>().As<IFileGroupService>().InstancePerLifetimeScope(); builder.RegisterType<DirectoryService>().As<IDirectoryService>().InstancePerLifetimeScope(); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Common/Success/SuccessMessage.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Common.Success { public class SuccessMessage { public class AccountSuccess { public const string USER_REGISTERED = "Account Registered Successfully"; public const string PASSWORD_CHANGED = "Password Changed Successfully. Please login"; public const string EMAIL_CONFIRM = "Your email confirm"; public const string ACTIVATED = "User Activated Successfully"; public const string DEACTIVATED = "User DeActivated Successfully"; public const string DELETED = "User Deleted SuccessFully"; public const string FORGOT_PASSWORD_LINK = "We have sent password change link to your email"; public const string PROFILE_UPDATE = "Profile Updated Successfully"; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/Upload/FileGroupItemsViewModel.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.Upload { public class FileGroupItemsViewModel { [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("createdBy")] public long? CreatedBy { get; set; } [JsonProperty("updatedBy")] public long? UpdatedBy { get; set; } [JsonProperty("createdOn")] public DateTimeOffset? CreatedOn { get; set; } [JsonProperty("updatedOn")] public DateTimeOffset? UpdatedOn { get; set; } [JsonProperty("isDeleted")] public bool? IsDeleted { get; set; } [JsonProperty("isActive")] public bool? IsActive { get; set; } [JsonProperty("filename")] public string Filename { get; set; } [JsonProperty("mimeType")] public string MimeType { get; set; } [JsonProperty("thumbnail")] public string Thumbnail { get; set; } [JsonProperty("size")] public long? Size { get; set; } [JsonProperty("path")] public string Path { get; set; } [JsonProperty("originalName")] public string OriginalName { get; set; } [JsonProperty("onServer")] public string OnServer { get; set; } [JsonProperty("typeId")] public long? TypeId { get; set; } [JsonProperty("type")] public string Type { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser/App_Start/RouteConfig.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace ProtectedBrowser { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "dashboard", url: "dashboard", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "changePassword", url: "dashboard/changePassword", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "recoverPassword", url: "recoverPassword", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "accountSettings", url: "dashboard/accountSettings", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "signIn", url: "signIn", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "404", url: "404", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "403", url: "403", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "DirectoryList", url: "dashboard/DirectoryList", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "DirectoryEdit", url: "dashboard/Directory/edit/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "DirectoryDetail", url: "dashboard/Directory/detail/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Users/UserService.cs using ProtectedBrowser.DBRepository.Users; using ProtectedBrowser.Domain.Users; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Users { public class UserService : IUserService { public UserDBService _userDBService; public UserService() { _userDBService = new UserDBService(); } public UserModel SelectUserByUniqueCode(string uniqueCode) { return _userDBService.UserProfileByUniqueCode(uniqueCode); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/BaseEntity.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain { public class BaseEntity { public long? Id { get; set; } public CreatedUserModel CreatedUser { get; set; } public UpdatedUserModel UpdatedUser { get; set; } } /// <summary> /// It represent the common auditable field for a record /// </summary> /// public class CreatedUserModel { public string FirstName { get; set; } public string LastName { get; set; } public string PhoneNumber { get; set; } public long? UserId { get; set; } } public class UpdatedUserModel { public string FirstName { get; set; } public string LastName { get; set; } public string PhoneNumber { get; set; } public long? UserId { get; set; } } public class AuditModel { public DateTimeOffset? OnDate { get; set; } public string ByUser { get; set; } public long? UserId { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/DummyFileUpload/IDummyFileUploadService.cs using ProtectedBrowser.Domain; using ProtectedBrowser.Domain.DummyFileUpload; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.DummyFileUpload { public interface IDummyFileUploadService { long DummyTableForFileInsert(DummyTableForFileModel model); void DummyTableForFileUpdate(DummyTableForFileModel model); List<DummyTableForFileModel> DummyTableForFileSelect(SearchParam param); DummyTableForFileModel DummyTableForFileSelectById(SearchParam param); List<DummyTableForFileModel> DummyTableForFileSelectBySingleFile(SearchParam param); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Upload/FileUploadService.cs using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using ProtectedBrowser.Domain.Upload; using System.Web; using System.IO; using System.Collections.ObjectModel; namespace ProtectedBrowser.Service.Upload { public class FileUploadService : IFileUploadService { private readonly string _uploadPath; private readonly MultipartFormDataStreamProvider _streamProvider; public FileUploadService() { _uploadPath = UserLocalPath; _streamProvider = new MultipartFormDataStreamProvider(_uploadPath); } public async Task<FileUpload> HandleRequest(HttpRequestMessage request) { await request.Content.ReadAsMultipartAsync(_streamProvider); return null; } #region Private implementation public List<FileUpload> ProcessFile(Collection<MultipartFileData> FileData) { var photos = new List<FileUpload>(); Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri); string pathQuery = myuri.PathAndQuery; string hostName = myuri.ToString().Replace(pathQuery, ""); foreach (var file in FileData) { var FileName = Path.GetFileName(file.LocalFileName); var FullPath = Path.GetFullPath(file.LocalFileName); string lastFolderName = Path.GetFileName(Path.GetDirectoryName(FullPath)); var localFileInfo = new FileInfo(file.LocalFileName); string guidFileName = Guid.NewGuid().ToString() + localFileInfo.Name; File.Move(localFileInfo.FullName, Path.Combine(localFileInfo.DirectoryName, guidFileName)); photos.Add(new FileUpload() { //IsComplete = chunkMetaData.IsLastChunk, FileName = guidFileName, LocalFilePath = hostName + "/" + lastFolderName + "/" + guidFileName, //FileMetadata = _streamProvider.FormData }); } return photos; } private FileUpload ProcessChunk(HttpRequestMessage request) { //use the unique identifier sent from client to identify the file FileChunkMetaData chunkMetaData = request.GetChunkMetaData(); string filePath = Path.Combine(_uploadPath, string.Format("{0}.temp", chunkMetaData.ChunkIdentifier)); //append chunks to construct original file using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate | FileMode.Append)) { var localFileInfo = new FileInfo(LocalFileName); var localFileStream = localFileInfo.OpenRead(); localFileStream.CopyToAsync(fileStream); fileStream.FlushAsync(); fileStream.Close(); localFileStream.Close(); //delete chunk localFileInfo.Delete(); } return new FileUpload() { IsComplete = chunkMetaData.IsLastChunk, FileName = OriginalFileName, LocalFilePath = chunkMetaData.IsLastChunk ? filePath : null, FileMetadata = _streamProvider.FormData }; } public List<FileGroupItemsModel> ProcessDocs(Collection<MultipartFileData> FileData, int length) { var attachment = new List<FileGroupItemsModel>(); Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri); string pathQuery = myuri.PathAndQuery; string hostName = myuri.ToString().Replace(pathQuery, ""); foreach (var file in FileData) { var FileName = Path.GetFileName(file.LocalFileName); var FullPath = Path.GetFullPath(file.LocalFileName); string lastFolderName = Path.GetFileName(Path.GetDirectoryName(FullPath)); var localFileInfo = new FileInfo(file.LocalFileName); string guidFileName = Guid.NewGuid().ToString() + localFileInfo.Name; File.Move(localFileInfo.FullName, Path.Combine(localFileInfo.DirectoryName, guidFileName)); string[] fileType = localFileInfo.Name.Split('.'); attachment.Add(new FileGroupItemsModel() { Filename = guidFileName, Path = hostName + "/" + lastFolderName + "/" + guidFileName, MimeType = fileType[fileType.Length - 1],//file.Headers.ContentType.MediaType, Size = length,//file.Headers.ContentLength, OriginalName = localFileInfo.Name }); } return attachment; } #endregion #region Properties private string LocalFileName { get { MultipartFileData fileData = _streamProvider.FileData.FirstOrDefault(); return fileData.LocalFileName; } } private string OriginalFileName { get { MultipartFileData fileData = _streamProvider.FileData.FirstOrDefault(); return fileData.Headers.ContentDisposition.FileName.Replace("\"", string.Empty); } } private string UserLocalPath { get { return HttpContext.Current.Server.MapPath("/tempfolder"); //return the path where you want to upload the file } } #endregion } public static class HttpRequestMessageExtensions { public static bool IsChunkUpload(this HttpRequestMessage request) { return request.Content.Headers.ContentRange != null; } public static FileChunkMetaData GetChunkMetaData(this HttpRequestMessage request) { return new FileChunkMetaData() { ChunkIdentifier = request.Headers.Contains("X-DS-Identifier") ? request.Headers.GetValues("X-File-Identifier").FirstOrDefault() : null, ChunkStart = request.Content.Headers.ContentRange.From, ChunkEnd = request.Content.Headers.ContentRange.To, TotalLength = request.Content.Headers.ContentRange.Length }; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/Directory/DirectoryViewModel.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.Directory { public class DirectoryViewModel { [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("createdBy")] public long? CreatedBy { get; set; } [JsonProperty("updatedBy")] public long? UpdatedBy { get; set; } [JsonProperty("createdOn")] public DateTimeOffset? CreatedOn { get; set; } [JsonProperty("updatedOn")] public DateTimeOffset? UpdatedOn { get; set; } [JsonProperty("isDeleted")] public bool? IsDeleted { get; set; } [JsonProperty("isActive")] public bool? IsActive { get; set; } [JsonProperty("rootPath")] public string RootPath { get; set; } [JsonProperty("userName")] public string UserName { get; set; } [JsonProperty("password")] public string Password { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("totalCount")] public int TotalCount { get; set; } } } <file_sep>/ProtectedBrowser/wwwroot/angular/pages/Directory/DirectoryRepository.js (function () { var commonService = angular.module("common.services"); commonService.factory("DirectoryRepository", directoryRepository); directoryRepository.$inject = ["$resource"]; function directoryRepository($resource) { return $resource(apiBaseUrl + "api/", {}, { fetchAll: { method: 'GET', params: {}, isArray: false, url: secureApiBaseUrl + "directorys" }, fetch: { method: 'GET', params: { id: '@id' }, isArray: false, url: secureApiBaseUrl + "directory/:id" }, save: { method: 'POST', params: {}, isArray: false, url: secureApiBaseUrl + "directory" }, update: { method: 'PUT', params: { id: '@id' }, isArray: false, url: secureApiBaseUrl + "directory" }, remove: { method: 'DELETE', params: { id: '@id' }, isArray: false, url: secureApiBaseUrl + "directory/:id" }, removeAll: { method: 'POST', params: {}, isArray: false, url: secureApiBaseUrl + "directory/remove" } }); } }()); <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Directory/DirectoryService.cs using ProtectedBrowser.DBRepository.Directory; using ProtectedBrowser.Domain.Directory; using ProtectedBrowser.Service.FileGroup; using ProtectedBrowser.Service.Upload; using ProtectedBrowser.Service.Xml; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Service.Directory { public class DirectoryService : IDirectoryService { public DirectoryDBService _directoryDBService; private IXmlService _xmlService; private IFileGroupService _fileGroupService; public DirectoryService(IFileGroupService fileGroupService, IXmlService xmlService) { _directoryDBService = new DirectoryDBService(); _fileGroupService = fileGroupService; _xmlService = xmlService; } public long DirectoryInsert(DirectoryModel model) { var id = _directoryDBService.DirectoryInsert(model); return id; } public void DirectoryUpdate(DirectoryModel model) { _directoryDBService.DirectoryUpdate(model); } public List<DirectoryModel> SelectDirectory(long? directoryId, bool? isActive = null, int? next = null, int? offset = null) { var response= _directoryDBService.SelectDirectory(directoryId, isActive, next, offset); response.ForEach(x => { }); return response; } } } <file_sep>/ProtectedBrowser/wwwroot/angular/pages/User/AddUserController.js (function () { var applicationApp = angular.module("applicationApp"); applicationApp.controller("AddUserController", addUserController); addUserController.$inject = ["$stateParams", "UserRepository","$state"]; function addUserController($stateParams, UserRepository,$state) { var vm = this; init(); function init() { vm.user = {}; vm.save = save; vm.onClickValidation = false; vm.roleList = [ { name: "Admin", value: "ROLE_ADMIN" }, { name: "Receptionist", value: "ROLE_RECEPTIONIST" } ]; vm.salutation = [ { name: "Mr", value: "Mr" }, { name: "Mrs", value: "Mrs" } ]; vm.recordId = $stateParams.id; vm.isNewRecord = true; if ($stateParams.id != '0') { UserRepository.getUserById({id:$stateParams.id}, function (resp) { if (resp.data) { vm.isNewRecord = false; vm.user = resp.data; } }, function (error) { showTost("Error:", "Somethings went wrong.", "danger"); }); }; vm.disableSaveButton = false; }; //save or update user Detail function save(valid) { if (!valid) { vm.onClickValidation = true; return; } vm.disableSaveButton = true; if (vm.isNewRecord) { UserRepository.saveUser(vm.user, function (resp) { if (!resp.status) { showTost("Error:", resp.message, "danger"); vm.disableSaveButton = false; return; } showTost("Success:", resp.message, "success"); $state.go("UserList"); }, function (error) { vm.disableSaveButton = false; showTost("Error:", "Somethings went wrong.", "danger"); }); } else { UserRepository.updateUser(vm.user, function (resp) { if (!resp.status) { showTost("Error:", resp.message, "danger"); vm.disableSaveButton = false; return; } showTost("Success:", resp.message, "success"); $state.go("UserList"); }, function (error) { vm.disableSaveButton = false; showTost("Error:", "Somethings went wrong.", "danger"); }); } }; } }()); <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Common/Constants/ErrorMessage.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ProtectedBrowser.Common.Constants { public partial class ErrorMessage { public class AccountError { public const string INCORRECT = "Username or password incorrect."; public const string ACTIVATE = "Your account is not activated by admin."; public const string DELETED = "User Does not Exist."; public const string INVALID_LINK = "Invalid Confirmation Link."; public const string INVALID_EMAIL = "Invalid EmailId."; public const string INVALID = "Invalid Request."; public const string EMAIL_ALREADY_REGISTERED = "Email Id {0} is already registered with another account."; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/Category/CategoryModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.Category { public class CategoryModel { public long Id { get; set; } public string Name { get; set; } public bool IsActive { get; set; } public bool IsDeleted { get; set; } public long? CreatedBy { get; set; } public DateTimeOffset CreatedOn { get; set; } public DateTimeOffset UpdatedOn { get; set; } public int TotalCount { get; set; } public string AdminEmail { get; set; } public long? UpdatedBy { get; set; } } } <file_sep>/ProtectedBrowser/wwwroot/angular/pages/Blog/BlogRepository.js (function () { var commonService = angular.module("common.services"); commonService.factory("BlogRepository", blogRepository); blogRepository.$inject = ["$resource"]; function blogRepository($resource) { return $resource(apiBaseUrl + "api/", {}, { fetchAll: { method: 'GET', params: {}, isArray: false, url: secureApiBaseUrl + "Blog/categories" }, addBlogCategory: { method: 'POST', params: {}, isArray: false, url: secureApiBaseUrl + "Admin/Blog" }, updateBlogCategory: { method: 'PUT', params: {}, isArray: false, url: secureApiBaseUrl + "admin/Blog" }, deleteBlogCategory: { method: 'DELETE', params: { id: '@id' }, isArray: false, url: secureApiBaseUrl + "Admin/Blog/:id/Category" }, getBlogCategoryById: { method: 'GET', params: { id: '@id' }, isArray: false, url: secureApiBaseUrl + "blogs/:id/category" }, getAllBlogs: { method: 'GET', params: {}, isArray: false, url: secureApiBaseUrl + "admin/blogs" }, addBlogs: { method: 'POST', isArray: false, url: secureApiBaseUrl + "admin/blog" }, updateBlogs: { method: 'PUT', isArray: false, url: secureApiBaseUrl + "admin/blog" }, getBlogById: { method: 'GET', params: { id: '@id' }, isArray: false, url: secureApiBaseUrl + "blog/:id" }, deleteBlog: { method: 'DELETE', params: { id: '@id' }, isArray: false, url: secureApiBaseUrl + "admin/blog/:id" }, uploadImage: { method: 'POST', params: {}, isArray: false, url: secureApiBaseUrl + "Admin/uploadFile" } }); } }()); <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Core/Mailer/MailSender.cs using ProtectedBrowser.Common.Extensions; using ProtectedBrowser.Common.Extensions; using SendGrid.Helpers.Mail; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net.Mail; using System.Net.Mime; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Core.Mailer { public class MailSender { /// <summary> /// Send Email To The Email Specified in To Email /// </summary> /// <param name="toMail"></param> /// <param name="subject"></param> /// <param name="messageBody"></param> /// <param name="CC"></param> /// <param name="BCC"></param> /// <returns></returns> /// <exception cref="System.ArgumentException"> /// Thrown if <paramref cref="subject,messageBody"/> is null or empty string /// </exception> //public static async Task SendEmail(string toMail, string subject, string messageBody, string filepath = null, string CC = "", string BCC = "", List<AttachmentInMail> listOfAttachment = null, string fromName = "iCat") //{ // //#if (!DEBUG) // ValidateEmailParams(toMail, subject, messageBody); // SmtpClient objSmptClient = null; // MailMessage objMailMessage; // try // { // byte[] buffer; // string fileName = ""; // objSmptClient = new SmtpClient(MailInfo.SMTPSERVER, MailInfo.SMTPSERVERPORT); // objSmptClient.EnableSsl = MailInfo.SMTPISSSL; // objSmptClient.Credentials = new System.Net.NetworkCredential(MailInfo.SMTPUSERNAME, MailInfo.SMTPPASSWORD); // objMailMessage = new MailMessage(MailInfo.FROMEMAILADDRESS, toMail, subject, messageBody); // if (!string.IsNullOrWhiteSpace(fromName)) // objMailMessage.From = new MailAddress(MailInfo.FROMEMAILADDRESS, fromName); // if (listOfAttachment != null) // { // foreach (var item in listOfAttachment) // { // buffer = item.byteArray; // fileName = item.name; // System.Net.Mime.ContentType a = new System.Net.Mime.ContentType(); // a.Name = item.contenttype != "" ? item.contenttype : ""; // MemoryStream stream = new MemoryStream(item.byteArray); // if (a.Name != "") // { // Attachment objAttachment = null; // ContentDisposition objContentDisposition = null; // objAttachment = new Attachment(stream, fileName, a.Name); // objContentDisposition = objAttachment.ContentDisposition; // objMailMessage.Attachments.Add(objAttachment); // } // else // { // objMailMessage.Attachments.Add(new Attachment(stream, fileName)); // } // } // } // //if ToCC is not null and empty // if (CC.IsNotNullOrEmpty()) // { // foreach (var address in CC.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) // { // objMailMessage.CC.Add(address); // } // } // //if ToBCC is not null and empty // if (BCC.IsNotNullOrEmpty()) // { // foreach (var address in BCC.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) // { // objMailMessage.Bcc.Add(address); // } // } // //Specify that body is html type // objMailMessage.IsBodyHtml = true; // if (!string.IsNullOrWhiteSpace(filepath)) // { // Attachment objAttachment = null; // ContentDisposition objContentDisposition = null; // objAttachment = new Attachment(filepath, "text/calendar"); // objContentDisposition = objAttachment.ContentDisposition; // objMailMessage.Attachments.Add(objAttachment); // } // try // { // objSmptClient.Send(objMailMessage); // } // catch (Exception ex) // { // //WriteException.WriteExceptionInFile(ex.ToString()); // //throw ex; // } // } // catch (Exception ex) // { // //WriteException.WriteExceptionInFile(ex.ToString()); // //return false; // } // //#else // //return true; // //#endif //} public static async Task SendEmail(string toMail, string subject, string messageBody, string filepath = null, string CC = "", string BCC = "", List<AttachmentInMail> listOfAttachment = null, string fromName = "ICat") { String apiKey = MailInfo.SENDGRIDAPIKEY; dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://api.sendgrid.com"); Email from = new Email(MailInfo.FROMEMAILADDRESS); Email to = new Email(toMail); Content content = new Content("text/html", messageBody); Mail mail = new Mail(from, subject, to, content); // Email email = new Email("<EMAIL>", fromName); // mail.Personalization[0].AddTo(email); dynamic response = await sg.client.mail.send.post(requestBody: mail.Get()); } /// <summary> /// Validate Email Parameters and Throws an exception /// </summary> /// <param name="toEmail"></param> /// <param name="subject"></param> /// <param name="messageBody"></param> private static void ValidateEmailParams(string toEmail, string subject, string messageBody) { Ensure.Argument.NotNullOrEmpty(toEmail, "toEmail"); Ensure.Argument.NotNullOrEmpty(subject, "subject"); Ensure.Argument.NotNullOrEmpty(messageBody, "messageBody"); if (!StringValidationExtensions.IsValidEmail(toEmail)) { throw new ArgumentException("Email is not a valid email"); } } } internal class MailInfo { public readonly static string FROMEMAILADDRESS = ConfigurationManager.AppSettings["FROMEMAILADDRESS"]; public readonly static string SMTPUSERNAME = ConfigurationManager.AppSettings["SMTPUSERNAME"]; public readonly static string SMTPPASSWORD = ConfigurationManager.AppSettings["SMTPPASSWORD"]; public readonly static string SMTPSERVER = ConfigurationManager.AppSettings["SMTPSERVER"]; public readonly static bool SMTPISSSL = Boolean.Parse(ConfigurationManager.AppSettings["SMTPISSSL"]); public readonly static int SMTPSERVERPORT = int.Parse(ConfigurationManager.AppSettings["SMTPSERVERPORT"]); public readonly static string SENDGRIDAPIKEY = ConfigurationManager.AppSettings["SENDGRIDAPIKEY"]; } public class AttachmentInMail { public byte[] byteArray { get; set; } public string name { get; set; } public string contenttype { get; set; } } } <file_sep>/ProtectedBrowser/wwwroot/angular/account/accountSettingsController.js (function () { "use strict"; var applicationApp = angular.module("applicationApp"); applicationApp.controller("AccountSettingsController", accountSettingsController); accountSettingsController.$inject = ["$scope", "$state", "$timeout", "$rootScope", "AccountRepository", "FileUploader", "localStorageService", "$window"]; function accountSettingsController($scope, $state, $timeout, $rootScope, AccountRepository, FileUploader, localStorageService, $window) { var vm = this; vm.updateUserDetail = updateUserDetail; vm.userDetail = {}; vm.onClickValidation = false; init(); function init() { getUserDetails(); } function getUserDetails() { AccountRepository.fetch(function (response) { if (!response.status) { showTost("Error:", data.message, "danger"); return; } vm.userDetail = response.data; }); } function updateUserDetail(bol) { vm.onClickValidation = !bol; if (!bol) { return false; } AccountRepository.updateUserDetail(vm.userDetail, function (response) { if (!response.status) { showTost("Error:", response.message, "danger"); return; } showTost("Success:", response.message, "success"); $(".user-fullName").html(vm.userDetail.firstName + " " + vm.userDetail.lastName); }); } vm.uploader = $scope.uploader = new FileUploader({ url: secureApiBaseUrl + 'file/upload', autoUpload: true }); vm.uploader.onSuccessItem = function (fileItem, response, status, headers) { if (vm.userDetail.profileId != null || vm.userDetail.profileId != "") { vm.userDetail.isProfilePicChanged = true; } vm.userDetail.profileId = response.id; console.info('onSuccessItem', fileItem, response, status, headers); }; } }()); <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/Leave/LeaveModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Domain.Leave { public class LeaveModel { public long? Id { get; set; } public long? CreatedBy { get; set; } public long? UpdatedBy { get; set; } public DateTimeOffset? CreatedOn { get; set; } public DateTimeOffset? UpdatedOn { get; set; } public bool? IsDeleted { get; set; } public bool? IsActive { get; set; } public DateTimeOffset? StartDate { get; set; } public DateTimeOffset? EndDate { get; set; } public string Description { get; set; } public TimeSpan? StartTime { get; set; } public TimeSpan? EndTime { get; set; } public string Type { get; set; } public long? UserId { get; set; } public int TotalCount { get; set; } public string FullName { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Domain/Directory/DirectoryModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ProtectedBrowser.Domain.Upload; namespace ProtectedBrowser.Domain.Directory { public class DirectoryModel { public long? Id { get; set; } public long? CreatedBy { get; set; } public long? UpdatedBy { get; set; } public DateTimeOffset? CreatedOn { get; set; } public DateTimeOffset? UpdatedOn { get; set; } public bool? IsDeleted { get; set; } public bool? IsActive { get; set; } public string RootPath { get; set; } public string UserName { get; set; } public string Password { get; set; } public string Name { get; set; } public int TotalCount { get; set; } } public class RawData { public string Path { get; set; } public string Name { get; set; } public string Type { get; set; } public string Ext { get; set; } } public class GetFilesFolder { public List<RawData> Files { get; set; } public List<RawData> Folders { get; set; } } public class GetRootPath { public string RootPath { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/Blog/BlogViewModel.cs using IotasmartBuild.Framework.ViewModels.Category; using ProtectedBrowser.Framework.ViewModels.Upload; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IotasmartBuild.Framework.ViewModels.Blog { public class BlogViewModel { [JsonProperty("id")] public long Id { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("categoryName")] public string CategoryName { get; set; } [JsonProperty("categoryId")] public Nullable<long> CategoryId { get; set; } [JsonProperty("isActive")] public bool IsActive { get; set; } [JsonProperty("isDeleted")] public bool IsDeleted { get; set; } [JsonProperty("createdOn")] public Nullable<System.DateTimeOffset> CreatedOn { get; set; } [JsonProperty("createdBy")] public Nullable<long> CreatedBy { get; set; } [JsonProperty("updatedOn")] public Nullable<System.DateTimeOffset> UpdatedOn { get; set; } [JsonProperty("updatedBy")] public Nullable<long> UpdatedBy { get; set; } [JsonProperty("overall_count")] public Nullable<int> overall_count { get; set; } [JsonProperty("category")] public CategoryViewModel Category { get; set; } [JsonProperty("fileGroupItem")] public FileGroupItemsViewModel FileGroupItem { get; set; } [JsonProperty("fileId")] public long? FileId { get; set; } [JsonProperty("fileUrl")] public string FileUrl { get; set; } [JsonProperty("fileName")] public string FileName { get; set; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/Appointment/AppointmentModelViewModelConverter.cs using ProtectedBrowser.Domain.Appointment; using ProtectedBrowser.Framework.WebExtensions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.Appointment { public static class AppointmentModelViewModelConverter { public static AppointmentViewModel ToViewModel(this AppointmentModel x) { if (x == null) return new AppointmentViewModel(); return new AppointmentViewModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, AppointmentDate = x.AppointmentDate, Note = x.Note, CancellationReason = x.CancellationReason, isAppointmentDone = x.isAppointmentDone, EndTime = x.EndTime, StartTime = x.StartTime, Status = x.Status, IsCancel = x.IsCancel, ToUserId = x.ToUserId, FromUserId = x.FromUserId, FromUser = x.FromUser != null ? x.FromUser.ToViewModel() : null, ToUser = x.ToUser != null ? x.ToUser.ToViewModel() : null, CreatedUser = x.CreatedUser != null ? x.CreatedUser.ToViewModel() : null, UpdatedUser = x.UpdatedUser != null ? x.UpdatedUser.ToViewModel() : null, }; } public static AppointmentModel ToModel(this AppointmentViewModel x) { if (x == null) return new AppointmentModel(); return new AppointmentModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, AppointmentDate = x.AppointmentDate, Note = x.Note, CancellationReason = x.CancellationReason, EndTime = x.EndTime, isAppointmentDone = x.isAppointmentDone, IsCancel = x.IsCancel, StartTime = x.StartTime, TotalCount = x.TotalCount, FromUserId = x.FromUserId, ToUserId = x.ToUserId, Status = x.Status }; } public static AppointmentTimeSlotViewModel ToViewModel(this AppointmentTimeSlot x) { if (x == null) return new AppointmentTimeSlotViewModel(); return new AppointmentTimeSlotViewModel { StartTime = x.StartTime.HasValue ? x.StartTime.Value.ToString(@"hh\:mm") : null,//x.StartTime.ToString(@"hh\:mm"), EndTime = x.EndTime.HasValue ? x.EndTime.Value.ToString(@"hh\:mm") : null, //x.EndTime.ToString(@"hh\:mm"), IsBooked = x.IsBooked }; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/Xml/XmlService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ProtectedBrowser.Domain.Upload; using System.Xml.Linq; using ProtectedBrowser.Common.Extensions; using ProtectedBrowser.Domain.Directory; namespace ProtectedBrowser.Service.Xml { public class XmlService : IXmlService { #region Attachement file XML to List public List<FileGroupItemsModel> GetFileGroupItemsByXml(string attachmentFileXml) { if (string.IsNullOrEmpty(attachmentFileXml)) return new List<FileGroupItemsModel>(); return XDocument.Parse(attachmentFileXml).Element("root").Elements("AF").Select(x => new FileGroupItemsModel { Id = x.Element("Id").GetValue<long>(), CreatedBy = x.Element("CreatedBy").GetValue<long>(), UpdatedBy = x.Element("UpdatedBy").GetValue<long>(), CreatedOn = x.Element("CreatedOn").GetDateOffset(), IsDeleted = x.Element("CreatedBy").GetBoolVal(), IsActive = x.Element("IsActive").GetBoolVal(), UpdatedOn = x.Element("UpdatedOn").GetDateOffset(), Filename = x.Element("Filename").GetStrValue(), MimeType = x.Element("MimeType").GetStrValue(), Thumbnail = x.Element("Thumbnail").GetStrValue(), Path = x.Element("Path").GetStrValue(), OriginalName = x.Element("OriginalName").GetStrValue(), OnServer = x.Element("OnServer").GetStrValue(), TypeId = x.Element("TypeId").GetValue<long>(), Type = x.Element("Type").GetStrValue(), Size = x.Element("Size").GetValue<long>(), }).ToList(); } public List<DirectoryModel> GetDirectoryByXml(string attachmentFileXml) { if (string.IsNullOrEmpty(attachmentFileXml)) return new List<DirectoryModel>(); return XDocument.Parse(attachmentFileXml).Element("root").Elements("R").Select(x => new DirectoryModel { Id = x.Element("Id").GetValue<long>(), CreatedBy = x.Element("CreatedBy").GetValue<long>(), UpdatedBy = x.Element("UpdatedBy").GetValue<long>(), CreatedOn = x.Element("CreatedOn").GetDateOffset(), UpdatedOn = x.Element("UpdatedOn").GetDateOffset(), IsDeleted = x.Element("IsDeleted").GetBoolVal(), IsActive = x.Element("IsActive").GetBoolVal(), RootPath = x.Element("RootPath").GetStrValue(), UserName = x.Element("UserName").GetStrValue(), Password = x.Element("Password").GetStrValue(), Name = x.Element("Name").GetStrValue(), }).ToList(); }//@@ADD_NEW_XML_CODE #endregion } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Service/UploadFile/IUploadService.cs using IotasmartBuild.Domain.UploadFile; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IotasmartBuild.Service.UploadFile { public interface IUploadService { long UploadFileInsert(UploadFileModel model); } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser/API/PublicHolidayController.cs using ProtectedBrowser.Common.Constants; using ProtectedBrowser.Common.Success; using ProtectedBrowser.Domain; using ProtectedBrowser.Framework.GenericResponse; using ProtectedBrowser.Framework.ViewModels.PublicHoliday; using ProtectedBrowser.Service.PublicHoliday; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ProtectedBrowser.API { [RoutePrefix("api")] public class PublicHolidayController : ApiController { private IPublicHolidayService _publicHolidayService; public PublicHolidayController(IPublicHolidayService publicHolidayService) { _publicHolidayService = publicHolidayService; } [Route("holiday")] [HttpPost] [Authorize(Roles = UserRole.Admin)] public IHttpActionResult HolidaySave([FromBody] PublicHolidayViewModel model) { model.CreatedBy = User.Identity.GetUserId<long>(); long id = _publicHolidayService.PublicHolidayInsert(model.ToModel()); return Ok(id.SuccessResponse()); } [Route("holiday")] [HttpPut] [Authorize(Roles = UserRole.Admin)] public IHttpActionResult HolidayUpdate([FromBody] PublicHolidayViewModel model) { model.UpdatedBy = User.Identity.GetUserId<long>(); _publicHolidayService.PublicHolidayUpdate(model.ToModel()); return Ok("Updated successfully.".SuccessResponse()); } [Route("holiday")] [HttpGet] [Authorize(Roles = UserRole.Admin)] public IHttpActionResult HolidaysSelect([FromUri] SearchParam param) { param = param ?? new SearchParam(); var holidaysList = _publicHolidayService.PublicHolidaysSelect(param).Select(x => x.ToViewModel()); return Ok(holidaysList.SuccessResponse()); } [Route("holiday/{id}")] [HttpGet] [Authorize(Roles = UserRole.Admin)] public IHttpActionResult HolidaySelectById(long? id) { SearchParam param = new SearchParam(); param.Id = id; var holiday = _publicHolidayService.PublicHolidaysSelect(param).Select(x => x.ToViewModel()); return Ok(holiday.SuccessResponse()); } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/CustomFilters/CustomExceptionFilter.cs using System.Web.Http.Filters; using System.Net; using System.Web.UI.WebControls; using System.Net.Http; using ProtectedBrowser.Service.Exception; using ProtectedBrowser.Domain.Exception; using System.Web; namespace ProtectedBrowser.Framework.CustomFilters { public class CustomExceptionFilter : ExceptionFilterAttribute { //private IExceptionService _IExceptionService; //public CustomExceptionFilter(IExceptionService exceptionService) //{ // _IExceptionService = exceptionService; //} public async override void OnException(HttpActionExecutedContext actionExecutedContext) { string exceptionMessage = string.Empty; if (actionExecutedContext.Exception.InnerException == null) { exceptionMessage = actionExecutedContext.Exception.Message; } else { exceptionMessage = actionExecutedContext.Exception.InnerException.Message; } ExceptionModel exception = new ExceptionModel(); exception.Message = actionExecutedContext.Exception.Message; exception.Source = actionExecutedContext.Exception.Source; exception.StackTrace = actionExecutedContext.Exception.StackTrace; exception.Method = actionExecutedContext.Request.Method.ToString(); exception.Uri = actionExecutedContext.Request.RequestUri.ToString(); ExceptionService obj = new ExceptionService(); obj.InsertLog(exception); //We can log this exception message to the file or database. var response = new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("An unhandled exception was thrown by service."), ReasonPhrase = "Internal Server Error.Please Contact your Administrator.", }; actionExecutedContext.Response = response; } } } <file_sep>/ProtectedBrowserCopy/ProtectedBrowser.Framework/ViewModels/Leave/LeaveModelViewModelConverter.cs using ProtectedBrowser.Domain.Leave; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtectedBrowser.Framework.ViewModels.Leave { public static class LeaveModelViewModelConverter { public static LeaveViewModel ToViewModel(this LeaveModel x) { if (x == null) return new LeaveViewModel(); return new LeaveViewModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, StartDate = x.StartDate, EndDate = x.EndDate, Description = x.Description, UserId = x.UserId, TotalCount = x.TotalCount, StartTime = x.StartTime, EndTime = x.EndTime, Type = x.Type, FullName = x.FullName }; } public static LeaveModel ToModel(this LeaveViewModel x) { if (x == null) return new LeaveModel(); return new LeaveModel { Id = x.Id, CreatedBy = x.CreatedBy, UpdatedBy = x.UpdatedBy, CreatedOn = x.CreatedOn, UpdatedOn = x.UpdatedOn, IsDeleted = x.IsDeleted, IsActive = x.IsActive, StartDate = x.StartDate, EndDate = x.EndDate, Description = x.Description, UserId = x.UserId, StartTime = x.StartTime, EndTime = x.EndTime, Type = x.Type }; } } }
56b94d79e4279579f8d6a0f051229bf6e0abcc05
[ "JavaScript", "C#", "SQL" ]
146
C#
CharnjeetIotasol/ProtectedBrowser
275ff5c110fd1fccf0b6ff94020eeaf4fac3a8b0
cbb9dcdb966e7c8fe3afa4176a14c995abdc5f73
refs/heads/master
<file_sep>#Ex 2 dicionario={1:'domingo',2:'segunda',3:'terça',4:'quarta',5:'quinta',6:'sexta',7:'sábado'} numero_aleatorio=int(input("Digite um número de 1 a 7: ")) if numero_aleatorio <=7 and numero_aleatorio>0: print(dicionario[numero_aleatorio]) else: print('Número inválido') <file_sep>#Ex 5 try: raio_circulo=float(input('Digite o valor do raio: ')) pi=float(3.1416) area = float((raio_circulo**2)*pi) comprimento = float((raio_circulo*pi)*2) print('Area :',round(area,2)) print('Comprimento: ',round(comprimento,2)) except: print('Inserir um valor numérico') <file_sep>#Ex 3 import random as rd quantidade_lista=int(input('Digite o número de itens que a lista deve ter: ')) lista=[] linha=1 if quantidade_lista<=0: print('O número de itens da lista não pode ser igual ou menor que 0') else: while linha<= quantidade_lista: lista.append(rd.randrange(0,100)) linha+=1 print('Essa é a lista',lista) print('Maior número: ',max(lista)) print('Menor número: ',min(lista)) <file_sep>#Ex 1 import datetime as date def dias(data_inicial,data_final): idade =(data_inicial-data_final)/365.25 return idade data_inicial=date.date.today() dia=int(input('Insira seu dia de nascimento: ')) mes=int(input('Insira seu mês de nascimento: ')) ano=int(input('Insira seu ano de nascimento: ')) data_final=date.date(ano,mes,dia) resultado=dias(data_inicial,data_final) print('Sua idade é: ',resultado,'anos')
c1e7d97eb03db474328fd3c2769651b5b820fe77
[ "Python" ]
4
Python
brunafrjardim/aula3
7a3857a72a0c5097f8df282259eea00bd1909114
d43b5e679fc459b16a28e9897ca0afe256fa879e
refs/heads/master
<file_sep>package test; public class DoubleEqualsToStringBuffer { public static void main(String args[]) { StringBuffer s1 = new StringBuffer("Navatha"); System.out.println(s1); StringBuffer s2 = new StringBuffer("Navatha"); System.out.println(s2); //== equal operator compares the reference System.out.println(s1==s2); System.out.println(s1.equals(s2)); } } <file_sep>package test; public class C extends B{ public void methodOfC() { System.out.println("This is method of class C"); } public static void main(String[] args) { A ca = new C(); ca.methodOfA(); B cb = new C(); cb.methodOfA(); cb.methodOfB(); C cc = new C(); cc.methodOfA(); } }
373062b594804e673b4c6370d6ab768473c101f2
[ "Java" ]
2
Java
navathak/Git-Demo
7a293827e404f2b96a7987d68f3aa8ae678e30de
e2413f26107acf4b5062900f8292a70ffad14845
refs/heads/master
<repo_name>mpalathingal/hand-and-brain<file_sep>/Hand_and_Brain.py from stockfish import Stockfish stockfish_path = "C:/Users/mpala/Downloads/stockfish-11-win/stockfish-11-win/Windows/stockfish_20011801_x64" def getMove(): move = input("Enter next move: ") return move def main(): stockfish = Stockfish(stockfish_path) moves = [] while(stockfish.get_evaluation() != {"type":"mate", "value":0}): # display updated board print(stockfish.get_board_visual()) # make moves as white next_move = getMove() if stockfish.is_move_correct(next_move): moves.append(next_move) else: print("not a valid move") getMove() stockfish.set_position(moves) print(stockfish.get_board_visual()) # get bot's move bot_move = stockfish.get_best_move() print("Bot moves: " + bot_move) moves.append(bot_move) stockfish.set_position(moves) if __name__ == "__main__": main()
04569ce5d837ddf420779de94d7fbc979c341aea
[ "Python" ]
1
Python
mpalathingal/hand-and-brain
97704002c06599f19b31b31fe50f8fe3f13a4394
874575e0537d11be313ed356c86f1b0be6c5bf57
refs/heads/master
<file_sep>"use strict" let fragenliste, i = 0; // Funktionen DEFINIEREN function printFrage(i) { // Parameter i = Index let request = new XMLHttpRequest(); // 6 Schritte (Verbindung mit JSON-File): 1.Instanz erstellen request.onload = function() { // 2.Handler-Funktion registrieren - wenn Ergebniss geladen wurde ... if(request.status === 200) { // HTTP-Statuscode: Wert 200 -> Anfrage ist erfolgreich let json; if(request.responseType === "json"){ json = request.response; // Variable json ist mein JSON-File, hier erfolgt die Zuweisung } else { json = JSON.parse(request.responseText); // HTML-Antwort als Zeichenkette } fragenliste = json.bergquiz; // json File.key -> value von bergquiz in Variable fragenliste speichern document.querySelector("#frage").innerHTML = fragenliste[i].nummer + fragenliste[i].frage; //DOM-Manipulation mit querySelector (ID), weise Frage meinem innterhtml zu // Shuffle array let answers = ["#label0","#label1","#label2"]; let shuffled = answers.sort(() => 0.5 - Math.random()); // antworten durcheinander mischen in Variable shuffled console.log(shuffled) document.querySelector(shuffled[0]).innerHTML = fragenliste[i].richtig; // shuffled0 könnte dann "#label1" sein document.querySelector(shuffled[1]).innerHTML = fragenliste[i].falsch1; // Zuweisung document.querySelector(shuffled[2]).innerHTML = fragenliste[i].falsch2; console.log(fragenliste[i].frage) } }; request.open("GET","quiz.json"); // 3.Anfrage-Methode mit GET und URL (laden der JSON-Datei) request.responseType = "json"; // 4.JSON zurückgeben request.setRequestHeader("Accept","application/json"); // 5. nur JSON zulassen request.send(); // 6. Anfrage absenden }; function next() { if(i < fragenliste.length - 1) { auswertung(); i++; // ähnlich wie Schleife, nach eine Frage wiederholt sich alles -> i wird 1 größer, solange bis i 5 ist printFrage(i); } else { auswertung(); showResult(); } }; let auswertung = function() { // Auswertung - Funktion suchen welcher button gechecked ist + Sicherung des labels in Variable userAnswer let userAnswer; // Variable userAnwer erstellen (leer), in der Funktion global if(document.querySelector("#answer0").checked) { let label0 = document.querySelector("#label0"); userAnswer = label0.innerHTML; // Variable userAnswer befüllen }; if(document.querySelector("#answer1").checked) { let label1 = document.querySelector("#label1"); userAnswer = label1.innerHTML; }; if(document.querySelector("#answer2").checked) { let label2 = document.querySelector("#label2"); userAnswer = label2.innerHTML; }; // Prüfung ob Antwort richtig ist - Ergebnis zeigen und in Webstorage abspeichern if(userAnswer == fragenliste[i].richtig){ document.querySelector("#frageResult").innerHTML = "Die Antwort ist richtig"; sessionStorage.setItem(`antwort ${i}`, "richtig"); // i -> für jede Iteration neuen Key mit Value-Ergebnis } else { document.querySelector("#frageResult").innerHTML ="Die Antwort ist falsch"; sessionStorage.setItem(`antwort ${i}`, "falsch"); } // alle radio button nicht checken document.querySelector("#answer0").checked = false; document.querySelector("#answer1").checked = false; document.querySelector("#answer2").checked = false; }; let showResult = function() { // Iteriere über Webstorage und Sicherung aller richtigen Antworten let sammelRichtig = 0; // man geht von 0 richtigen Antworten aus for (let i = 0; i < sessionStorage.length; i++) { let key = sessionStorage.key(i); // speichere key in Variable let wert = sessionStorage.getItem(key); // gibt mir Wert zurück -> richtig oder falsch. wenn i = 0, dann ist key "antwort 0" und value zb. "richtig" if(wert == "richtig"){ sammelRichtig++; // um 1 erhöhen wenn richtig } } console.log(sammelRichtig); // Zeigt dem user das Ergebnis document.querySelector("#showResult").innerHTML = "Du hast richtig: " + sammelRichtig; // Button restart wird freigeschalten document.querySelector("#restartbutton").disabled = false; // Bestätigungs-Button ausgegraut document.querySelector("#button").disabled = true; }; // wird ausgeführt beim Klicken von Button restart let restart = function() { i = 0; // damit es wieder von vorne losgeht -> bei Index 0 printFrage(i); // Buttons wieder umkehren document.querySelector("#restartbutton").disabled = true; // restart-Button ist ausgegraut document.querySelector("#button").disabled = false; // bestätigen ist aktiviert // Deaktivieren von Ergebnis document.querySelector("#showResult").innerHTML = ""; document.querySelector("#frageResult").innerHTML = ""; }; // Funktionen AUSFÜHREN printFrage(i); document.querySelector("#button").addEventListener("click", next); // mit addEventlistener weiter klicken registrieren document.querySelector("#restartbutton").addEventListener("click", restart);
0d12fb26695e248cd7ccd7495b6e4584564e8d4a
[ "JavaScript" ]
1
JavaScript
samanthavoegel/Abschlussprojekt_Javascriptkurs
5870f51d02b8630ba416ba7a46b18885bc381fbb
4a5f4a8126841f6cb232988d9b3fcb30b640024a
refs/heads/master
<file_sep>--- title: 'Futility of Utility: Common Ratio Effect Example' author: <NAME> date: '`r format(Sys.time(), "%d %B %Y")`' output: html_document: toc: true toc_depth: 3 --- --- Draw Figure 3 from Stewart, Canic, and Mullett (2020) ```{r setup} library(tidyverse) library(ggExtra) library(data.table) library(boot) library(doMC) library(dplyr) #library(cowplot) registerDoMC(cores=20) options(width=100) ``` ```{r} sessionInfo() ``` --- # Choice Set Make a choice set with gambles of the form ``$p$ chance of $x$ otherwise $y$`` Use probabilities where some are scaled up (i.e., large) and some are scaled down (i.e., small) Make all possible choices Throw out choices where one gamble dominates the other Add flags "Scaled Down", "Scaled Up" and "Common", indicating whether the probability $p$ for a gamble is unique to the scaled-up set of probabilities, unique to the scaled-down set of probabilities, or is common to both sets ```{r} amounts <- c(10,20,50,100,200,500) scaled.up.probs <- c(5,10,25,50,75,100) / 100 ( scaled.down.probs <- scaled.up.probs/5 ) ( all.probs <- unique(c(scaled.down.probs, scaled.up.probs)) ) # A is a pA chance of xA otherwise yA choices <- CJ(pA=all.probs, xA=amounts, yA=amounts, pB=all.probs, xB=amounts, yB=amounts) choices <- choices[xA>yA & xB>yB,] # x > y for both choices A and B choices <- choices[pA>pB,] # Make A the high probability choice # Remove dominated choices choices <- choices[!((xA>xB & yA>yB & pA>pB) | (xA<xB & yA<yB & pA<pB)),] choices[,EV.A:=pA*xA + (1-pA)*yA] choices[,EV.B:=pB*xB + (1-pB)*yB] choices <- choices[EV.A<EV.B, ] # Make A (which is the high probability choice) have lower EV than B ``` ```{r} # Flags for scaled up or scaled down ( unique.scaled.down.probs <- setdiff(scaled.down.probs, scaled.up.probs) ) ( unique.scaled.up.probs <- setdiff(scaled.up.probs, scaled.down.probs) ) ( common.probs <- intersect(scaled.down.probs, scaled.up.probs) ) p.flag <- function(p) { ifelse(p %in% unique.scaled.down.probs, "Scaled Down", ifelse(p %in% unique.scaled.up.probs, "Scaled Up", ifelse(p %in% common.probs, "Common", NA) ) ) } choices[,pA.flag:=p.flag(pA)] choices[,pB.flag:=p.flag(pB)] head(choices) ggplot(choices, aes(y=pB, x=pA)) + geom_point(alpha=0.01, size=3) + geom_abline(intercept=0, slope=1) + facet_grid(pA.flag ~pB.flag) ``` # CPT Model Implement straight CPT with logit stochastic function DANGER!: Because we are using `data.table`s and passing is by reference, the `CPT.prediction` function is adding columns to the global variable `choices` ```{r} v <- function(x, alpha, beta, lambda, eta) { # Tversky and Kahmeman (1992) Equation 5 ifelse(x>=0, (eta*x)^alpha, -lambda*abs(eta*x)^beta) } #inverse.v <- function(v, alpha, beta, lambda) { # ifelse(v>=0, v^(1/alpha), -(abs(v)/lambda)^(1/beta)) #} w <- function(p, gamma) { # Tversky and Kahmeman (1992) Equation 6 p^gamma /((p^gamma + (1-p)^gamma)^(1/gamma)) } logit <- function(x) { 1/(1+exp(-x)) } CPT.prediction <- function(alpha, beta, lambda, gamma, eta, choices) { # Danger! Adds columns to data.table choices choices[,CPT.A:=w(pA, gamma) * v(xA, alpha, beta, lambda, eta) + (1-w(pA, gamma))*v(yA, alpha, beta, lambda, eta)] #choices[,CPT.CE.A:=inverse.v(CPT.A, alpha, beta, lambda, eta)] choices[,CPT.B:=w(pB, gamma) * v(xB, alpha, beta, lambda, eta) + (1-w(pB, gamma))*v(yB, alpha, beta, lambda, eta)] #choices[,CPT.CE.B:=inverse.v(CPT.B, alpha, beta, lambda)] #choices[,CPT.prob.A:=logit(eta*(CPT.CE.A-CPT.CE.B))] choices[,CPT.prob.A:=logit(eta*(CPT.A-CPT.B))] } ``` # EU Model Implement EU ```{r} v.EU <- function(x, alpha, eta) { (eta*x)^alpha } EU.predictions <- function(alpha, eta, choices) { # Danger! Adds columns to data.table choices choices[,EU.A:=pA*v.EU(xA, alpha, eta)+(1-pA)*v.EU(yA, alpha, eta)] #choices[,EU.CE.A:=inverse.v.EU(EU.A, alpha)] choices[,EU.B:=pB*v.EU(xB, alpha, eta)+(1-pB)*v.EU(yB, alpha, eta)] #choices[,EU.CE.B:=inverse.v.EU(EU.B, alpha)] #choices[,EU.prob.A:=logit(eta*(EU.CE.A-EU.CE.B))] choices[,EU.prob.A:=logit(eta*(EU.A-EU.B))] } #EU.predictions(alpha=0.5, eta=1, choices) lnL <- function(data.probs, model.probs) { sum(data.probs*log(model.probs) + (1-data.probs)*log(1-model.probs)) } EU.lnL <- function(alpha, eta, choices) { EU.predictions(alpha, eta, choices) lnL(choices$CPT.prob.A, choices$EU.prob.A) } EU.lnL.wrapper <- function(p, choices) { EU.lnL(alpha=p[1], eta=p[2], choices) } ``` # Simulation of 500 participants each making 200 choices There are 3006 choices. Make 500 fake participants, each with a random sample of 200 of the 3006 choices ```{r cache=TRUE} no.choices <- 200 no.subjects <- 500 subject <- rep(1:no.subjects, times=no.choices) choices.index <- c(replicate(no.choices, sample(1:nrow(choices), size=no.subjects))) # Add CPT predictions to the data.table choices CPT.prediction(alpha=1,beta=1,lambda=1,gamma=0.5,eta=0.1,choices) simulated.choices <- choices[choices.index][,`:=`(subject=subject, choice=choices.index)] simulated.choices[,CPT.choice.A:=ifelse(runif(.N)<CPT.prob.A, 1, 0)] # Check creation of simulated binary choices simulated.choices[,CPT.prob.A.cut:=cut(CPT.prob.A, breaks=seq(0,1,.1), include.lowest=TRUE)] simulated.choices[,.(CPT.prop.A=mean(CPT.choice.A)),by=CPT.prob.A.cut][order(CPT.prob.A.cut),] simulated.choices[,CPT.prob.A.cut:=NULL] EU.lnL <- function(alpha, eta, choices) { EU.predictions(alpha, eta, choices) lnL(choices$CPT.choice.A, choices$EU.prob.A) } fit.one.subject <- function(simulated.choices) { sol.all <- optim(par=c(alpha=1,eta=0.1), fn=EU.lnL.wrapper, control=list(fnscale= -1), choices=simulated.choices) sol.not.up <- optim(par=c(alpha=1,eta=0.1), fn=EU.lnL.wrapper, control=list(fnscale= -1), choices=simulated.choices[pA.flag!="Scaled Up" & pB.flag!="Scaled Up",]) sol.not.down <- optim(par=c(alpha=1,eta=0.1), fn=EU.lnL.wrapper, control=list(fnscale= -1), choices=simulated.choices[pA.flag!="Scaled Down" & pB.flag!="Scaled Down",]) data.frame(subject=simulated.choices$subject[1],alpha.all=sol.all$par["alpha"], eta.all=sol.all$par["eta"], alpha.scaled.down=sol.not.up$par["alpha"], eta.scaled.down=sol.not.up$par["eta"], alpha.scaled.up=sol.not.down$par["alpha"], eta.scaled.up=sol.not.down$par["eta"] ) } params.for.each.subject <- foreach(s=1:no.subjects, .combine=rbind) %dopar% { fit.one.subject(simulated.choices[subject==s,]) } ``` # Bootstrapping and Figure 3 ```{r} boot.wrapper <- function(data, index) { sapply(data[index,], median) } boot.result <- boot(data=params.for.each.subject[,-1], statistic=boot.wrapper, R=1001, parallel="multicore", ncpus=23) boot.ci.wrapper <- function(i, boot.result) { boot.ci(boot.result, index=i, type="norm")$norm[2:3] } CIs.norm <- t(sapply(1:length(boot.result$t0), FUN=boot.ci.wrapper, boot.result=boot.result)) colnames(CIs.norm) <- c("lower", "upper") point.estimates <- boot.wrapper(params.for.each.subject[,-1], 1:nrow(params.for.each.subject)) booted.parameters <- as.data.table(cbind(mean=point.estimates, CIs.norm)) booted.parameters[,label:=names(point.estimates)] booted.parameters[,parameter:=str_replace(label, "\\.(.+)", "")] booted.parameters[,choice.set:=str_replace(label, "(.+?)\\.", "")] booted.parameters booted.parameters[,parameter.label:=factor(parameter, levels=c("alpha", "eta"), labels=c(expression(alpha), expression(phi)))] ggplot(booted.parameters, aes(x=choice.set, y=mean, ymin=lower, ymax=upper)) + geom_point() + geom_linerange() + facet_wrap(~parameter.label, scales="free_y", labeller=label_parsed) + theme_classic() + scale_color_brewer(palette = "Dark2") + labs(x="Choice Subset", y="Parameter Value") + scale_x_discrete(labels=c("All Choices", "Scaled Down", "Scaled Up")) + theme(strip.background = element_blank(), strip.text=element_text(size=20)) ggsave("simulation_common_ratio_booted_parameter_medians.pdf", width=6, height=4) ``` <file_sep># Example 2 First run make_clean_data.Rmd Then run analysis.Rmd <file_sep>analysis.html: analysis.Rmd Rscript -e 'library(rmarkdown); rmarkdown::render("analysis.Rmd", "html_document")' analysis.R: analysis.Rmd Rscript -e 'library(knitr); knitr::purl("analysis.Rmd", documentation=2)' make_clean_data.html: make_clean_data.Rmd Rscript -e 'library(rmarkdown); rmarkdown::render("make_clean_data.Rmd", "html_document")' make_clean_data.R: make_clean_data.Rmd Rscript -e 'library(knitr); knitr::purl("make_clean_data.Rmd", documentation=2)' <file_sep>analysis.html: analysis.Rmd Rscript -e 'library(rmarkdown); rmarkdown::render("analysis.Rmd", "html_document")' analysis.R: analysis.Rmd Rscript -e 'library(knitr); knitr::purl("analysis.Rmd", documentation=2)' <file_sep>--- title: 'Futility of Utility Modelling' author: <NAME> #date: '`r format(Sys.time(), "%d %B %Y")`' #bibliography: refs.bib #csl: https://raw.githubusercontent.com/citation-style-language/styles/master/apa.csl output: html_document: toc: true toc_depth: 3 --- --- ```{r setup, echo=FALSE} library(data.table) library(ggplot2) library(boot) ``` ```{r} sessionInfo() ``` This code generates Figures 5 and 6 in Stewart, Canic, and Mullett (2020) "On the futility of estimating utility functions: Why the parameters we measure are wrong, and why they do not generalize" # Read in data $px$ is the risky choice ```{r Load data and delete columns} load("cleaned_data.RData") data <- as.data.table(data) # Delete unnecessary columns data[, left.prob:=NULL] data[, left.amount:=NULL] data[, right.prob:=NULL] data[, right.amount:=NULL] data[, button:=NULL] data[, RT:=NULL] data[, location:=NULL] data[, risky.choice:=NULL] data[, prev.button:=NULL] data[, alternation:=NULL] data[, condition:=NULL] # It matched cond data[, sub.no:=NULL] # We still have sub.id data[, PA.id:=NULL] data[, choice:=NULL] # We still have safe.choice dummy str(data) ``` ```{r Identify choice sets} # Make sure we are working with integers for amounts str( positive.amounts <- as.integer(c(10, 20, 50, 100, 200, 500)) ) str( uniform.amounts <- as.integer(c(100, 200, 300, 400, 500)) ) data[, choice.set.positive:= ifelse((x %in% positive.amounts) & (y %in% positive.amounts), 1L, 0L)] data[, choice.set.uniform:= ifelse((x %in% uniform.amounts) & (y %in% uniform.amounts), 1L, 0L)] data[cond=="Both" & choice.set.positive & choice.set.uniform, choice.set:="Common"] data[cond=="Both" & !choice.set.positive & !choice.set.uniform, choice.set:="Unique"] data[cond=="Both" & !choice.set.positive & choice.set.uniform, choice.set:="Uniform"] data[cond=="Both" & choice.set.positive & !choice.set.uniform, choice.set:="Positive"] ``` ```{r Check numbers of people and choices} # 89 people in the Both Condition unique(data[,.(sub.id, cond)])[,.N,by=.(cond)] # 140 choices in the Both Condition; 150 in Positive and Uniform Conditions unique(data[,.N, by=.(sub.id, cond)][order(cond),][,.(cond, N)]) ``` # Figure 6 ```{r Figure 6} log.odds <- function(p) { log(p/(1 - p)) } #log.odds(0.01+0.98*safe.choice) log.odds.safe <- data[cond=="Both", .(prop.safe.choice=mean(safe.choice)), by=.(log.y.over.x=log(y/x), choice.set, y, x)][order(log.y.over.x, choice.set),] log.odds.safe[, log.odds.safe.choice:=log.odds(prop.safe.choice)] retro.split <- rbind( log.odds.safe[choice.set %in% c("Positive", "Common"),][,choice.subset:="Positive"], log.odds.safe[choice.set %in% c("Uniform", "Common"),][,choice.subset:="Uniform"] ) labels <- data.frame(x=c(-2.5, -0.78), y=c(0.13, 1.36), label=c("alpha==0.62 95\\% CI[0.54-0.70]", "alpha=0.94 95\\% CI[0.78-1.10]")) labels <- data.frame(x=c(-3.2, -0.8), y=c(0.1, -0.6), label=c('atop(alpha[Positive]==0.62*",",95*"%"~CI~bgroup("[",0.54-"0.70","]"))', 'atop(alpha[Uniform]==0.94*",",95*"%"~CI~bgroup("[",0.78-"1.10","]"))'), choice.subset=c("Positive", "Uniform")) x.axis.labels <- rbind(CJ(y=positive.amounts, x=positive.amounts), CJ(y=uniform.amounts, x=uniform.amounts)) x.axis.labels <- x.axis.labels[y<x,] x.axis.labels <- unique(x.axis.labels) x.axis.labels[,log.y.over.x:=log(y/x)] x.axis.labels[,label:=paste("log(",y,"/",x,")",sep="")] x.axis.labels <- aggregate(label ~ log.y.over.x, FUN=paste, data=x.axis.labels, collapse="\n") ggplot(retro.split, aes(x=log.y.over.x, y=log.odds.safe.choice, col=choice.subset, shape=choice.subset)) + geom_point(size=2) + geom_smooth(method="lm", se=FALSE) + labs(col="Choice Set", shape="Choice Set", x=expression(log(y/x))) + geom_text(data=labels, mapping=aes(x=x, y=y, label=label,col=choice.subset, shape=NULL), parse=TRUE, show.legend=FALSE) + ylab(expression(log*bgroup("[",over(P(Safe),1-P(Safe)),"]"))) + scale_x_continuous(breaks=x.axis.labels$log.y.over.x, labels=x.axis.labels$label) + theme_classic() + theme(axis.text.x=element_text(angle=90, hjust=0, vjust=0.5)) + scale_color_brewer(palette="Dark2") ggsave("log_odds_safe_by_log_y_over_x.pdf", width=9, height=6)#, scale=0.5) ``` # Run logistic regressions to fit free utility model to generate Figure 5 Fits to participants in the Both Condition, separately for the Positive and Uniform choice sets. Fits are of a non-parameteric model from Appendix A of <NAME>, and Harris (2015), and estimate the utility of each sum of money as a free parameter, rather than imposing a power-law functional form ```{r Add amount dummies} # Add amount dummies map <- read.csv("amount_map.csv") map$cond <- factor(map$cond, levels=c("Positive", "Uniform", "Both")) map$name <- paste("w", map$x, ".", map$cond, sep="") map data <- merge(data, map, by.x=c("x", "cond"), by.y=c("x", "cond")) data <- merge(data, map, by.x=c("y", "cond"), by.y=c("x", "cond"), suffixes=c("x", "y")) X.width <- max(map$i) X <- matrix(0,nrow=nrow(data), ncol=X.width) X[matrix(c(1:length(data$ix),data$ix),ncol=2)] <- -1 X[matrix(c(1:length(data$iy),data$iy),ncol=2)] <- 1 colnames(X) <- map$name[order(map$i)] data <- cbind(data,X) ``` ## Fit Positive and Uniform Choice Subsets from Both Condition ```{r Fit free model} data.Both <- droplevels(subset(data,cond=="Both")) amounts.Positive <- c(10,20,50,100,200,500) amounts.Uniform <- c(100,200,300,400,500) data.Both$Positive.subset <- with(data.Both, ifelse(x%in%amounts.Positive & y%in%amounts.Positive, TRUE, FALSE)) data.Both$Uniform.subset <- with(data.Both, ifelse(x%in%amounts.Uniform & y%in%amounts.Uniform, TRUE, FALSE)) fit.glm.nonpara.to.Both <- function(data, model) { switch(model, Positive={m <- glm(safe.choice ~ log(q/p) + w10.Both + w20.Both + w50.Both + w100.Both + w200.Both, data=data, family=binomial)}, Uniform={m <- glm(safe.choice ~ log(q/p) + w100.Both + w200.Both + w300.Both + w400.Both, data=data, family=binomial)}, Both={m <- glm(safe.choice ~ log(q/p) + w10.Both + w20.Both + w50.Both + w100.Both + w200.Both + w300.Both + w400.Both, data=data, family=binomial)}, stop("Uncaught condition in fit.glm.nonpara.to.Both()") ) beta <- coef(m) bias <- exp(beta["(Intercept)"]) gamma <- beta["log(q/p)"] v <- exp( beta[grep("w", names(beta))] / gamma ) data.frame(sub.id=data$sub.id[1], condition=data$cond[1], population=data$population[1], name=c("bias", "gamma", c(names(v),paste("w500", "Both", sep=".")), "logLik", "converged"), value=c(bias, gamma, v, 1, logLik(m), m$converged)) } data.Both.Positive <- subset(data.Both, Positive.subset) fits.m.nonpara.Both.Positive <- by(data.Both.Positive, INDICES=list(data.Both.Positive$sub.id), FUN=fit.glm.nonpara.to.Both, model="Positive") fits.m.nonpara.Both.Positive <- do.call("rbind", fits.m.nonpara.Both.Positive) fits.m.nonpara.Both.Positive <- merge(fits.m.nonpara.Both.Positive, map, all.x=TRUE) fits.m.nonpara.Both.Positive <- fits.m.nonpara.Both.Positive[order(fits.m.nonpara.Both.Positive$sub.id),] fits.m.nonpara.Both.Positive$subset <- "Positive" data.Both.Uniform <- subset(data.Both, Uniform.subset) fits.m.nonpara.Both.Uniform <- by(data.Both.Uniform, INDICES=list(data.Both.Uniform$sub.id), FUN=fit.glm.nonpara.to.Both, model="Uniform") fits.m.nonpara.Both.Uniform <- do.call("rbind", fits.m.nonpara.Both.Uniform) fits.m.nonpara.Both.Uniform <- merge(fits.m.nonpara.Both.Uniform, map, all.x=TRUE) fits.m.nonpara.Both.Uniform <- fits.m.nonpara.Both.Uniform[order(fits.m.nonpara.Both.Uniform$sub.id),] fits.m.nonpara.Both.Uniform$subset <- "Uniform" fits.m.nonpara.Both <- Reduce(rbind, list(fits.m.nonpara.Both.Positive, fits.m.nonpara.Both.Uniform)) fits.m.nonpara.Both.molten <- melt(fits.m.nonpara.Both, id=c("sub.id", "condition", "population", "name", "subset"), measure.vars=c("value")) fits.m.nonpara.Both.wide <- dcast(data=fits.m.nonpara.Both.molten, formula= ... ~ name + subset) fits.m.nonpara.Both.wide <- fits.m.nonpara.Both.wide[,colSums(is.na(fits.m.nonpara.Both.wide))!=nrow(fits.m.nonpara.Both.wide)] # Drop all entirely NA columns # At this point fits.m.nonpara.Both.wide is one row per participant, with a fit to only their positive choice set and a fit to only their uniform choice set ``` ## Bootstrap medians ```{r Bootstrap medians} boot.wrapper.m.nonpara <- function(data, indices, fun) { d <- data[indices,] apply(d[,grepl("^w", names(d)) & !grepl("^w500", names(d))], c(2), fun, na.rm=TRUE) } make.CI.table <- function(results) { estimate.and.CI <- function(bootci) { c(estimate=bootci$t0, CI95.=bootci$norm[2:3]) } CIs <- vector("list", length(results$t0)) for(i in 1:length(results$t0)) { CIs[[i]] <- boot.ci(results, type="norm", index=i) } tbl <- t(sapply(CIs, estimate.and.CI)) colnames(tbl) <- c("estimate", "lower.CI", "upper.CI") rownames(tbl) <- names(results$t0) tbl } make.values.from.CI.table <- function(CI.table, map) { CI.table$name <- rownames(CI.table) # Drop everything after - CI.table$name <- sapply(row.names(CI.table), function(x) {strsplit(x, "_")[[1]][1]}) CI.table$subset <- sapply(row.names(CI.table), function(x) {strsplit(x, "_")[[1]][2]}) values <- merge(map, CI.table, all.x=TRUE) values[is.na(values)] <- 1 values <- values[order(values$cond, values$x),] values } boot.result.median.nonpara.Both <- boot(data=fits.m.nonpara.Both.wide, statistic=boot.wrapper.m.nonpara, fun=median, R=10001, parallel="multicore", ncpus=23) map.Both <- Reduce(rbind, list(cbind(subset(map, x %in% amounts.Positive & cond=="Both"), subset="Positive"),cbind(subset(map, x %in% amounts.Uniform & cond=="Both"), subset="Uniform"))) values.Both <- make.values.from.CI.table(as.data.frame(make.CI.table(boot.result.median.nonpara.Both)), map.Both) write.csv(droplevels(subset(values.Both, subset!="All")), file="glm_nonpara_individual_bootstrap_both_data_points.csv") ``` ## Figure 5 ```{r Figure 5} glm.nonpara.fit <- fread("glm_nonpara_individual_bootstrap_both_data_points.csv") ggplot(glm.nonpara.fit, aes(x=x, y=estimate, col=subset, shape=subset, ymin=lower.CI, ymax=upper.CI)) + geom_line() + geom_linerange() + geom_point(size=3) + labs(x="Amount / £", y="Utility", col="Choice Subset", shape="Choice Subset") + theme_classic() + scale_color_brewer(palette = "Dark2") # + geom_line(data=power.functions.data, aes(x=x, y=utility, ymin=NULL, ymax=NULL, col=subset)) ggsave("glm_nonpara_individual_bootstrap_both.pdf", width=6, height=4)#, scale=0.5) ``` <file_sep>--- title: 'Futility of Utility Modelling' author: <NAME> date: '`r format(Sys.time(), "%d %B %Y")`' output: html_document: toc: true toc_depth: 3 --- --- ```{r setup, echo=FALSE} library(data.table) library(lattice) library(latticeExtra) library(gtools) ``` ```{r} sessionInfo() ``` This file cleans the trial-level data and removes outliers as described in Appendix A of Stewart, Canic, and Mullett (2020) # Read in data $px$ is the riskier gamble. ```{r} trials.4a <- read.csv("trials_4a.csv", as.is=TRUE) trials.4a$sub.id <- paste("PA", trials.4a$sub.id, sep="") trials.4a$population <- "PA" trials.4b <- read.csv("trials_4b.csv", as.is=TRUE) trials.4b$sub.id <- paste("MTurk", trials.4b$sub.id, sep="") trials.4b$population <- "MTurk" trials <- rbind(trials.4a, trials.4b) rm(trials.4a, trials.4b) trials$population <- as.factor(trials$population) trials$condition <- factor(trials$cond, levels=c("Positive", "Uniform", "Both")) trials$sub.id <- factor(trials$sub.id, levels=mixedsort(unique(trials$sub.id))) demographics.4a <- read.csv("demographics_4a.csv", as.is=TRUE) demographics.4a$sub.id <- paste("PA", demographics.4a$sub.id, sep="") demographics.4a$population <- "PA" demographics.4b <- read.csv("demographics_4b.csv", as.is=TRUE) demographics.4b$sub.id <- paste("MTurk", demographics.4b$sub.id, sep="") demographics.4b$population <- "MTurk" demographics <- rbind(demographics.4a, demographics.4b) rm(demographics.4a, demographics.4b) demographics$population <- as.factor(demographics$population) demographics$condition <- factor(demographics$cond, levels=c("Positive", "Uniform", "Both")) demographics$sub.id <- factor(demographics$sub.id, levels=mixedsort(unique(demographics$sub.id))) demographics$experiment.duration <- demographics$experiment.duration/1000/60 # to get to minutes from ms demographics$time <- as.POSIXct(demographics$time, format="%T %a %d %b %y") # For the MTurk experiment, study was incorrectly run in £ until Wednesday 2 September 2015 when it was switched to $ choices <- read.csv("choices.csv", as.is=TRUE) choices$condition <- factor(choices$cond, levels=c("Positive", "Uniform", "Both")) # px is a risky choice all(choices$p < choices$q) all(choices$x > choices$y) names(choices)[names(choices)=="id"] <- "trial.id" ``` # Duration 75\% of people completed in fewer than 13 minutes. 90\% of people completed in fewer than 17 minutes. ```{r} densityplot(~experiment.duration | population, groups=cond, data=subset(demographics, experiment.duration<30), auto.key=TRUE, layout=c(1,2), as.table=TRUE, scales=list(alternating=FALSE), type="g") quantile(demographics$experiment.duration, na.rm=TRUE, probs=c(.25,.5,.75,.9)) x <- as.data.table(demographics) ( cutoff.durations <- as.data.frame(x[,.(duration.5=quantile(experiment.duration, probs=c(.05)), duration.95=quantile(experiment.duration, probs=c(.95))),by=list(condition,population)]) ) demographics <- merge(cutoff.durations, demographics) demographics$outlier <- demographics$experiment.duration < demographics$duration.5 | demographics$experiment.duration > demographics$duration.95 xyplot(experiment.duration~condition | population, groups=outlier, data=demographics, jitter.x=TRUE, layout=c(2,1), as.table=TRUE, scales=list(alternating=FALSE), type=c("p", "g")) ( duration.outliers <- demographics$sub.id[demographics$outlier] ) ``` # IP Duplicates ```{r} duplicates <- function(x, set) {sum(x == set[!is.na(set)])-1} demographics$duplicate <- sapply(demographics$ip, duplicates, set=demographics$ip) ( ip.duplicates <- demographics$sub.id[demographics$duplicate!=0] ) ``` # Uncounterbalance px qy left right ```{r} # Work out counterbalancing of trials trials$location <- ifelse(trials$p < trials$q, "Risky Left", "Risky Right") trials$choice <- ifelse((trials$location=="Risky Left" & trials$button=="left") | (trials$location=="Risky Right" & trials$button=="right"), "Risky", "Safe") trials$risky.choice <- ifelse(trials$choice=="Risky", 1 ,0) trials$safe.choice <- 1 - trials$risky.choice # Rename p,q,x,y with location based names, and then use p,q,x,y for risky and safe names(trials)[names(trials)=="p"] <- "left.prob" names(trials)[names(trials)=="q"] <- "right.prob" names(trials)[names(trials)=="x"] <- "left.amount" names(trials)[names(trials)=="y"] <- "right.amount" trials$p <- ifelse(trials$location=="Risky Left", trials$left.prob, trials$right.prob) trials$q <- ifelse(trials$location=="Risky Left", trials$right.prob, trials$left.prob) trials$x <- ifelse(trials$location=="Risky Left", trials$left.amount, trials$right.amount) trials$y <- ifelse(trials$location=="Risky Left", trials$right.amount, trials$left.amount) trials <- merge(trials, choices) ``` # Alternation Outliers ```{r} trials <- trials[with(trials, order(sub.id, trial)),] trials$prev.button <- c(NA, trials$button[-nrow(trials)]) trials$prev.button[trials$trial==0] <- NA trials$alternation <- ifelse(trials$button == trials$prev.button, 0, 1) alternations <- aggregate(alternation~sub.id + condition, data=trials, FUN=mean) i <- order(alternations$alternation) alternations <- alternations[order(alternations$alternation),] head(alternations) tail(alternations) alternation.cuts <- quantile(alternations$alternation, probs=c(.05, .95)) densityplot(~alternation, groups=condition, data=alternations, auto.key=TRUE) + layer(panel.abline(v=alternation.cuts)) xyplot(as.factor(button)~trial | sub.id, data=trials, as.table=TRUE, type="l", index.cond=list(i)) alternation.outliers <- alternations$sub.id[alternations$alternation < alternation.cuts[1] | alternations$alternation > alternation.cuts[2]] xyplot(as.factor(button)~trial | sub.id, data=subset(trials, sub.id%in%alternation.outliers), as.table=TRUE, type="l") ``` # Remove Outliers and Duplicates ```{r} ( outliers <- Reduce(union, list(duration.outliers, alternation.outliers, ip.duplicates)) ) length(outliers) trials <- subset(trials, !sub.id%in%outliers) demographics$outlier <- demographics$sub.id %in% outliers xtabs(~condition+outlier, data=demographics) ``` # Save Cleaned Data ```{r} data <- trials save(data, file="cleaned_data.RData") ``` <file_sep>rm(list = ls()) setwd('C:/Users/Tim/Dropbox/skewdist_projects/modelling') require(tidyverse) data = read_csv('cpt_alphas_halves_1a.csv') eudata = read_csv('eu_alphas_halves_1a.csv') # cptranks = apply(data, 1, rank) # euranks = apply(eudata, 1, rank) cptranks = data cptranks[,] = t(apply(cptranks, 1, rank, ties.method = 'random')) euranks = eudata euranks[,] = t(apply(eudata, 1, rank, ties.method = 'random')) startpoints = c(3,15,29,44,57) # startpoints = c(1,15,29,44,59) # startpoints = c(15,29,44) allcombs = matrix(1:nrow(cptranks), 3, byrow = T) cptrankmatch = matrix(NA, nrow(data)/3, length(startpoints)) refit_cptrankmatch = matrix(NA, nrow(data)/3, length(startpoints)) eurankmatch = matrix(NA, nrow(data)/3, length(startpoints)) refit_eurankmatch = matrix(NA, nrow(data)/3, length(startpoints)) cptranks = as.matrix(cptranks) euranks = as.matrix(euranks) for(i in 1:length(allcombs[1,])){ for(k in 1:length(startpoints)){ cptrankmatch[i,k] = mean(as.numeric(cptranks[allcombs[1,i], cptranks[allcombs[2,i],] == startpoints[k]])) refit_cptrankmatch[i,k] = mean(as.numeric(cptranks[allcombs[1,i], cptranks[allcombs[3,i],] == startpoints[k]])) eurankmatch[i,k] = mean(as.numeric(euranks[allcombs[1,i], euranks[allcombs[2,i],] == startpoints[k]])) refit_eurankmatch[i,k] = mean(as.numeric(euranks[allcombs[1,i], euranks[allcombs[3,i],] == startpoints[k]])) } } # cptrankchange = abs(cptrankmatch - rep(startpoints, each = nrow(data)/3)) # cptrankchange = as.data.frame(cptrankchange) # colnames(cptrankchange) <- c('Rank_0', 'Rank_25', 'Rank_50', 'Rank_75', 'Rank_100') # colnames(cptrankchange) <- c('Rank_0', 'Rank_25', 'Rank_50', 'Rank_75', 'Rank_100') # p1 = ggplot(gather(cptrankchange)) + geom_histogram(aes(value/58, fill = key), position = 'dodge') + xlab('Absolute change in rank') cptrankmatch = as.data.frame(cptrankmatch) refit_cptrankmatch = as.data.frame(refit_cptrankmatch) colnames(cptrankmatch) <- c('5 percentile', '25 percentile', '50 percentile', '75 percentile', '95 percentile') colnames(refit_cptrankmatch) <- c('5 percentile', '25 percentile', '50 percentile', '75 percentile', '95 percentile') # colnames(cptrankmatch) <- c('0 percentile', '25 percentile', '50 percentile', '75 percentile', '100 percentile') # colnames(refit_cptrankmatch) <- c('0 percentile', '25 percentile', '50 percentile', '75 percentile', '100 percentile') # colnames(cptrankmatch) <- c('25 percentile', '50 percentile', '75 percentile') # colnames(refit_cptrankmatch) <- c('25 percentile', '50 percentile', '75 percentile') # cpt_plotframe = gather(add_column(gather(cptrankmatch), refit_rank = gather(refit_cptrankmatch)$value)) cpt_plotframe = gather(add_column(gather(cptrankmatch), refit_rank = gather(refit_cptrankmatch)$value), 'rank_source', 'rankpos', c('value', 'refit_rank')) # cpt_plotframe$key = factor(cpt_plotframe$key, levels = c('0 percentile', '25 percentile', '50 percentile', '75 percentile', '100 percentile')) cpt_plotframe$key = factor(cpt_plotframe$key, levels = c('5 percentile', '25 percentile', '50 percentile', '75 percentile', '95 percentile')) # p1 = ggplot(cpt_plotframe) + geom_histogram(aes(rankpos, fill = rank_source), position = 'dodge') + xlab('Distribution of paired rank') + facet_grid(~key) + scale_x_continuous(breaks=c(2,29,58), labels=c("0%", "50%", "100%")) # p1 = p1 + theme(legend.title = element_blank()) + scale_fill_discrete(labels = c("Within Sample", "Out of Sample")) + # theme_classic() + # theme(panel.background = element_rect(fill = NA), panel.border = element_rect(linetype = "solid", fill = NA), legend.title = element_blank()) + # theme(axis.text.x = element_text(angle=45)) p1 = ggplot(cpt_plotframe) + geom_histogram(aes(rankpos, fill = rank_source), position = 'dodge') + xlab('Percentile') + ylab('Count') + facet_grid(~key) + scale_x_continuous(breaks=c(2,29,58), labels=c("0%", "50%", "100%")) + theme(legend.title = element_blank()) + theme_classic() + scale_fill_brewer(palette = "Dark2", labels = c("Within Half", "Second Half")) + # scale_fill_discrete(labels = c("Within Half", "Second Half")) + theme(legend.title = element_blank()) + theme(strip.background = element_blank(), strip.text=element_text(size=8)) + theme(axis.text.x = element_text(angle=45)) p1 ggsave("CPT_plot.pdf", plot = p1, width=6, height=4) # %Neil's # ggplot(booted.parameters, aes(x=choice.set, y=mean, ymin=lower, ymax=upper)) + geom_point() + geom_linerange() + facet_wrap(~parameter.label, scales="free_y", labeller=label_parsed) + theme_classic() + # scale_color_brewer(palette = "Dark2") + labs(x="Choice Subset", y="Parameter Value") + scale_x_discrete(labels=c("All Choices", "Scaled Down", "Scaled Up")) + theme(strip.background = element_blank(), # strip.text=element_text(size=20)) eurankmatch = as.data.frame(eurankmatch) refit_eurankmatch = as.data.frame(refit_eurankmatch) colnames(eurankmatch) <- c('5 percentile', '25 percentile', '50 percentile', '75 percentile', '95 percentile') colnames(refit_eurankmatch) <- c('5 percentile', '25 percentile', '50 percentile', '75 percentile', '95 percentile') # colnames(eurankmatch) <- c('0 percentile', '25 percentile', '50 percentile', '75 percentile', '100 percentile') # colnames(refit_eurankmatch) <- c('0 percentile', '25 percentile', '50 percentile', '75 percentile', '100 percentile') # colnames(eurankmatch) <- c('25 percentile', '50 percentile', '75 percentile') # colnames(refit_eurankmatch) <- c('25 percentile', '50 percentile', '75 percentile') eu_plotframe = gather(add_column(gather(eurankmatch), refit_rank = gather(refit_eurankmatch)$value), 'rank_source', 'rankpos', c('value', 'refit_rank')) # eu_plotframe$key = factor(eu_plotframe$key, levels = c('0 percentile', '25 percentile', '50 percentile', '75 percentile', '100 percentile')) eu_plotframe$key = factor(eu_plotframe$key, levels = c('5 percentile', '25 percentile', '50 percentile', '75 percentile', '95 percentile')) # p2 = ggplot(eu_plotframe) + geom_histogram(aes(rankpos, fill = rank_source), position = 'dodge') + xlab('Distribution of paired rank') + facet_grid(~key) + scale_x_continuous(breaks=c(2,29,58), labels=c("0%", "50%", "100%")) # p2 = p2 + theme(legend.title = element_blank()) + scale_fill_discrete(labels = c("Within Sample", "Out of Sample")) + # theme_classic() + # theme(panel.background = element_rect(fill = NA), panel.border = element_rect(linetype = "solid", fill = NA), legend.title = element_blank()) + # theme(axis.text.x = element_text(angle=45)) # # ggsave("EU_plot.pdf", plot = p2, height = 5 , width = 5 * 1.5) p2 = ggplot(eu_plotframe) + geom_histogram(aes(rankpos, fill = rank_source), position = 'dodge') + xlab('Percentile') + ylab('Count') + facet_grid(~key) + scale_x_continuous(breaks=c(2,29,58), labels=c("0%", "50%", "100%")) + theme(legend.title = element_blank()) + theme_classic() + scale_fill_brewer(palette = "Dark2", labels = c("Within Half", "Second Half")) + # scale_fill_discrete(labels = c("Within Half", "Second Half")) + theme(legend.title = element_blank()) + theme(strip.background = element_blank(), strip.text=element_text(size=8)) + theme(axis.text.x = element_text(angle=45)) p2 ggsave("EU_plot.pdf", plot = p2, width=6, height=4) # gridExtra::grid.arrange(p1, p2, p3, p4) require(ggpubr) # ggarrange( # p1, p2, p3, p4, labels = c("A", "B", "C", "D"), # common.legend = TRUE, legend = "bottom" # ) ggarrange( p1, p2, labels = c("CPT", "EU"), hjust = c(-0.2, -0.9), nrow = 2, common.legend = TRUE, legend = "right" )
72f6e768b6a320c55ba05e4ec3eed81d90e0b1ba
[ "Markdown", "Makefile", "RMarkdown", "R" ]
7
RMarkdown
neil-stewart/futility_of_utility_code_and_data
3ced312cdd553afcd596051b3eb26dc632dfc214
a0f4b89cfccb5eb45068ffcfe9d02f5ea2701fca
refs/heads/master
<repo_name>bradleywhite2014/Dapp<file_sep>/index.ios.js const Firebase = require('firebase'); const styles = require('./styles.js') const StatusBar = require('./Components/StatusBar'); const ActionButton = require('./Components/ActionButton'); const ListItem = require('./Components/ListItem'); var Home = require('./Screens/Home'); var InterestScreen = require('./Screens/InterestScreen'); 'use strict'; import React, { AppRegistry, Component, StyleSheet, Text, View, ListView, AlertIOS, TextInput, Navigator } from 'react-native'; class Dapp extends Component { renderScene(route, nav) { switch (route.id) { case 'authenticate': return <Home navigator={nav} />; case 'interestScreen': return <InterestScreen navigator={nav} />; default: return <View />; } } render(){ return ( <Navigator initialRoute={{ id: 'authenticate', }} renderScene={this.renderScene} configureScene={(route) => { if (route.sceneConfig) { return route.sceneConfig; } return Navigator.SceneConfigs.FloatFromRight; }} /> ); } } AppRegistry.registerComponent('Dapp', () => Dapp); <file_sep>/Screens/InterestScreen.js const Firebase = require('firebase'); const styles = require('../styles.js') const StatusBar = require('../Components/StatusBar'); const ActionButton = require('../Components/ActionButton'); const ListItem = require('../Components/ListItem'); 'use strict'; import React, { AppRegistry, Component, StyleSheet, Text, View, ListView, AlertIOS, TextInput } from 'react-native'; class InterestScreen extends Component { render() { return ( <View style={styles.flexColumnContainer}> <StatusBar title="Dapp" /> <Text style={styles.text}> Welcome! Lets figure out what apps you would like to demo! </Text> <ActionButton title="Next" onPress={this.pickAnApp.bind(this)}/> </View> ); } pickAnApp(){ } } module.exports = InterestScreen; <file_sep>/android/settings.gradle rootProject.name = 'Dapp' include ':app'
d7d4e20751e6d1527518535f24d3872ba3202aa0
[ "JavaScript", "Gradle" ]
3
JavaScript
bradleywhite2014/Dapp
eb7702937ef8dfb68654d7bccb1eb96f72cd8a1b
bef968739a18167fb26408c053395f51a2411372
refs/heads/master
<repo_name>jrotter/hackerrank_build_a_palindrome<file_sep>/build_a_palindrome_old.c #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAXSTRING 10001 void print_array(int array[],int size) { int i; for (i=0;i<size;i++) { printf("%d ",array[i]); } printf("\n\n"); } int palindrome(char *str, int length) { int a = 0; int b = length - 1; while (b > a) { if (str[a++] != str[b--]) { return 0; } } return 1; } void find_palindromes_left(char *s, int length, int results[]) { char hold; int x, y; for (x=0;x<length;x++) { results[x] = 1; } for (x=0;x<length;x++) { for (y=length-1;y>x;y--) { if (s[y] == s[x]) { hold = s[y+1]; s[y+1] = '\0'; /* Temporarily end the string after y */ if (palindrome(&(s[x]),y-x+1)) { s[y+1] = hold; /* Undo the temporary end-of-string */ results[x] = y-x+1; break; } else { s[y+1] = hold; } } } } } void find_palindromes_right(char *s, int length, int results[]) { char hold; int x, y; for (x=0;x<length;x++) { results[x] = 1; } for (y=length-1;y>0;y--) { for (x=0;x<y;x++) { if (s[y] == s[x]) { hold = s[y+1]; s[y+1] = '\0'; /* Temporarily end the string after y */ if (palindrome(&(s[x]),y-x+1)) { s[y+1] = hold; /* Undo the temporary end-of-string */ results[y] = y-x+1; break; } else { s[y+1] = hold; } } } } } void save_if_best( char *candidate, int candidate_length, char *best, int *best_length) { /* Note that we assume here that candidate_length >= (*best_length) */ if ((candidate_length > (*best_length)) || (strcmp(candidate,best) < 0)) { //printf(" A NEW BEST!\n"); strcpy(best,candidate); (*best_length) = candidate_length; } } void reverse_string(char *target, char *source, int length) { int i; /* loop counter */ for(i=0;i<length;i++) { target[length-i-1] = source[i]; } target[length] = '\0'; } int main() { int params; char s1[MAXSTRING]; char s2[MAXSTRING]; int s1_palindromes[MAXSTRING]; int s2_palindromes[MAXSTRING]; int s1_length; int s2_length; char left_bookend[MAXSTRING]; char right_bookend[MAXSTRING]; int bookend_length; int total_bookend_length; int body_length; char best[MAXSTRING+MAXSTRING]; int best_length; char teststring[MAXSTRING+MAXSTRING]; int teststring_length; int i, n, x, y, a, b; /* Loop counters */ /* Read in the number of pairs we'll consider */ i = scanf("%i",&params); for (n=0;n<params;n++) { /* Read in the pair */ i = scanf("%s",s1); i = scanf("%s",s2); s1_length = strlen(s1); s2_length = strlen(s2); //printf("s1 == \"%s\"\n",s1); //printf("s2 == \"%s\"\n",s2); /* Initialize our best result */ best[0] = '\0'; best_length = 0; /* Find all palindromes in s1 (left-indexed) and s2 (right-indexed) */ find_palindromes_left(s1,s1_length,s1_palindromes); //print_array(s1_palindromes,strlen(s1)); find_palindromes_right(s2,s2_length,s2_palindromes); //print_array(s2_palindromes,strlen(s2)); for (x=0;x<s1_length;x++) { if (best_length <= (s1_length - x + s2_length)) { for (y=x;y<s1_length;y++) { /* Set up the bookend data */ bookend_length = y-x+1; total_bookend_length = bookend_length * 2; strncpy(left_bookend,&(s1[x]),bookend_length); left_bookend[bookend_length] = '\0'; //printf("Left bookend (%d,%d) = \"%s\"\n",x,y,left_bookend); reverse_string(right_bookend,left_bookend,bookend_length); /* See if any right bookends are found */ if (strstr(s2,right_bookend)) { //printf(" Right bookend = \"%s\"\n",right_bookend); /* Try the body from s1 */ if (y != (s1_length-1)) { body_length = s1_palindromes[y+1]; /* Ignore this body if the resulting string would be too small */ if ((total_bookend_length + body_length) >= best_length) { /* Build the test string */ teststring_length = total_bookend_length + body_length; strcpy(teststring,left_bookend); strncpy(&(teststring[bookend_length]),&(s1[y+1]),body_length); strncpy(&(teststring[bookend_length+body_length]),right_bookend,bookend_length); teststring[teststring_length] = '\0'; //printf(" Teststring (body from s1): \"%s\"\n",teststring); /* Compare test string with the best we've seen */ save_if_best(teststring,teststring_length,best,&best_length); } } else /* No body available from s1 - try just the bookends */ { /* Ignore this body if the resulting string would be too small */ if (total_bookend_length >= best_length) { /* Build the test string */ teststring_length = total_bookend_length; strcpy(teststring,left_bookend); strncpy(&(teststring[bookend_length]),right_bookend,bookend_length); teststring[teststring_length] = '\0'; //printf(" Teststring (no body): \"%s\"\n",teststring); /* Compare test string with the best we've seen */ save_if_best(teststring,teststring_length,best,&best_length); } } } else /* No right bookend was found */ { /* If a right bookend was not found for x at a given length nothing will be found with a greater length */ break; } } } } /* for */ for (b=s2_length-1;b>=0;b--) { if (best_length <= (s1_length + b + 1)) { for (a=b;a>=0;a--) { /* Set up the bookend data */ bookend_length = b-a+1; total_bookend_length = bookend_length * 2; strncpy(right_bookend,&(s2[a]),bookend_length); right_bookend[bookend_length] = '\0'; //printf("Right bookend (%d,%d) = \"%s\"\n",a,b,right_bookend); reverse_string(left_bookend,right_bookend,bookend_length); /* See if any left bookends are found */ if (strstr(s1,left_bookend)) { //printf(" Left bookend = \"%s\"\n",left_bookend); /* Try the body from s2 */ if (a != 0) { body_length = s2_palindromes[a-1]; /* Ignore this body if the resulting string would be too small */ if ((total_bookend_length + body_length) >= best_length) { /* Build the test string */ teststring_length = total_bookend_length + body_length; strcpy(teststring,left_bookend); strncpy(&(teststring[bookend_length]),&(s2[a-body_length]),body_length); strncpy(&(teststring[bookend_length+body_length]),right_bookend,bookend_length); teststring[teststring_length] = '\0'; //printf(" Teststring (body from s2): \"%s\"\n",teststring); /* Compare test string with the best we've seen */ save_if_best(teststring,teststring_length,best,&best_length); } } else /* No body available from s2 - try just the bookends */ { /* Ignore this body if the resulting string would be too small */ if (total_bookend_length >= best_length) { /* Build the test string */ teststring_length = total_bookend_length; strcpy(teststring,left_bookend); strncpy(&(teststring[bookend_length]),right_bookend,bookend_length); teststring[teststring_length] = '\0'; //printf(" Teststring (no body): \"%s\"\n",teststring); /* Compare test string with the best we've seen */ save_if_best(teststring,teststring_length,best,&best_length); } } } else /* No left bookend was found */ { /* If a left bookend was not found for b at a given length nothing will be found with a greater length */ break; } } } } /* for */ if (best_length) printf("%s\n",best); else printf("-1\n"); } } <file_sep>/Makefile all: cc -pg -o build_a_palindrome build_a_palindrome.c <file_sep>/build_a_palindrome.rb class String # Is the String object a palindrome? def palindrome? self == self.reverse end def palindrome? a = 0 b = length-1 while b > a return false if self[a] != self[b] a += 1 b -= 1 end true end # Return an array of all indexes where the substr was found within the string def indexes(substr) outarray = nil if (i = self.index(substr)) outarray = [] while i outarray << i i = self.index(substr,i+1) end end outarray end end module Best def Best.init @@value = nil @@length = 0 end def Best.check(test_string) if test_string.length > @@length || ((test_string.length == @@length) && (test_string < @@value)) @@value = test_string @@length = test_string.length end end def Best.length @@length end def Best.value @@value end end # Find all trivial palindromic substrings in a string # Returns an array of their leftmost index in the string def find_palindromes_left(s) outarray = [] for x in (0..(s.length-1)) outarray[x] = 1 end for x in (0..(s.length-1)) if matches = s.indexes(s[x]) matches.reverse.each do |y| test_string = s[x..y] #puts "x=#{x}, y=#{y}, substring = \"#{test_string}\"" if test_string.palindrome? #puts "Found palindrome: \"#{test_string}\"" outarray[x] = test_string.length # Note that I will always find a palindrome at s[x..x] so y won't pass x break end end end end outarray end # Find all trivial palindromic substrings in a string # Returns an array of their rightmost index in the string def find_palindromes_right(s) outarray = [] for x in (0..(s.length-1)) outarray[x] = 1 end for y in (s.length-1).downto(0) if matches = s.indexes(s[y]) matches.each do |x| test_string = s[x..y] #puts "x=#{x}, y=#{y}, substring = \"#{test_string}\"" if test_string.palindrome? #puts "Found palindrome: \"#{test_string}\"" outarray[y] = test_string.length # Note that I will always find a palindrome at s[y..y] so x won't pass y break end end end end outarray end # Read in the data count = gets.strip.to_i count.times do |i| s1 = gets.strip s2 = gets.strip Best::init() # Find all palindromes in s1 (left-indexed) and s2 (right-indexed) s1_palindromes = find_palindromes_left(s1) #puts s1_palindromes.inspect s2_palindromes = find_palindromes_right(s2) #puts s2_palindromes.inspect s1_substring = nil s2_substring = nil indexlists = {} # Run through all possible substrings of s1 for x in (0..(s1.length-1)) # On the off chance that our best palindrome is already bigger than # anything else we'll see from here on out, break if (Best::length > ((s1.length-x) + s2.length)) break end for y in (x..(s1.length-1)) # The left bookend is s1[x..y] left_bookend = s1[x..y] #puts "Left bookend: \"#{left_bookend}\" (#{x})" # This substring is the left bookend of the palindrome. # Find all possible right bookends indexlists[left_bookend] ||= s2.indexes(left_bookend.reverse) indexlist = indexlists[left_bookend] # If any right bookends were found... if indexlist total_bookend_length = left_bookend.length * 2 # By definition, the bookends are mirror images right_bookend = left_bookend.reverse # Try the body from s1 unless y == s1.length-1 # Only bother if this could be better than the best if (total_bookend_length + s1_palindromes[y+1]) >= Best::length body = s1[(y+1)..(y+s1_palindromes[y+1])] #puts " Body from s1: \"#{body}\"" teststring = left_bookend + body + right_bookend #puts " Test string: \"#{teststring}\"" Best::check(teststring) end end # Reduce indexlist to only palindrome sizes that may # exceed the best we've seen reducedlist = [] max = Best::length - total_bookend_length if max == 0 && indexlist[0] == 0 reducedlist << 0 start = 1 else start = 0 end for i in start.upto(indexlist.length - 1) if s2_palindromes[indexlist[i]-1] > max reducedlist = [ indexlist[i] ] elsif s2_palindromes[indexlist[i]-1] == max reducedlist << indexlist[i] end end #puts "Reduced list: #{reducedlist.inspect}" # Now loop through the remaining right bookends reducedlist.each do |a| #b = a + left_bookend.length - 1 # The right bookend is s2[a..b] #puts " Right bookend: \"#{right_bookend}\" (#{a})" if a == 0 if y == s1.length-1 # Try the bookends without a body #puts " No body" teststring = left_bookend + right_bookend #puts " Test string: \"#{teststring}\"" Best::check(teststring) end else # Try the body from s2 # Only bother if this could be better than the best if (total_bookend_length + s2_palindromes[a-1]) >= Best::length body = s2[(a-s2_palindromes[a-1])..(a-1)] #puts " Body from s2: \"#{body}\"" teststring = left_bookend + body + right_bookend #puts " Test string: \"#{teststring}\"" Best::check(teststring) else #puts " Not worth trying palindrome from s2" end end end else # If a right bookend was not found for x at a given length # nothing will be found with a greater length break end end end if Best::value puts Best::value else puts "-1" end end <file_sep>/README.md # Submission for HackerRank's Build a Palindrome Problem *Author:* <NAME> *Problem URL:* https://www.hackerrank.com/challenges/challenging-palindromes *Date:* 2017-08-31 *Language:* Ruby *Example:* ``` cat testfile.txt | ruby build_a_palindrome.rb ``` <file_sep>/build_a_palindrome.c #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAXSTRING 100001 void print_array(int array[],int size) { int i; for (i=0;i<size;i++) { printf("%d ",array[i]); } printf("\n\n"); } int max (int a, int b) { if (a > b) return a; else return b; } int palindrome(char *str, int length) { int a = 0; int b = length - 1; while (b > a) { if (str[a++] != str[b--]) { return 0; } } return 1; } /* Find the length of all longest palindromes beginning at s[x] */ void find_palindromes_left(char *s, int length, int results[]) { char hold; int x, y; for (x=0;x<length;x++) { results[x] = 1; } for (x=0;x<length;x++) { for (y=length-1;y>x;y--) { if (s[y] == s[x]) { hold = s[y+1]; s[y+1] = '\0'; /* Temporarily end the string after y */ if (palindrome(&(s[x]),y-x+1)) { s[y+1] = hold; /* Undo the temporary end-of-string */ results[x] = y-x+1; break; } else { s[y+1] = hold; } } } } } /* Find the length of the longest palindrome ending at s[x] */ void find_palindromes_right(char *s, int length, int results[]) { char hold; int x, y; for (x=0;x<length;x++) { results[x] = 1; } for (y=length-1;y>0;y--) { for (x=0;x<y;x++) { if (s[y] == s[x]) { hold = s[y+1]; s[y+1] = '\0'; /* Temporarily end the string after y */ if (palindrome(&(s[x]),y-x+1)) { s[y+1] = hold; /* Undo the temporary end-of-string */ results[y] = y-x+1; break; } else { s[y+1] = hold; } } } } } /* Return the length of the maximal bookend ending at s1[x] that has a match in s2 */ int find_s1_bookend_length(int x, char *s1, char *s2, char *buffer, int startlength) { char *searchstring = buffer; int i = x; int j = 0; while (j < startlength) { searchstring[j++] = s1[i--]; } searchstring[j+1] = '\0'; while (i >= 0) { searchstring[j] = s1[i]; searchstring[j+1] = '\0'; //printf("[S1] x == %d, i == %d, j == %d, last == %d, searchstring == %s\n",x,i,j,startlength,searchstring); if (strstr(s2,searchstring)) { j++; i--; } else { //printf("x == %d: returning %d\n",x,j); return j; } } //printf("x == %d: returning %d\n",x,j); return j; } /* Return the length of the maximal bookend starting at s2[x] that has a match in s1 */ int find_s2_bookend_length(int x, char *s1, char *s2, char *buffer, int startlength) { char *searchstring = buffer; int i = x; int j = MAXSTRING; searchstring[j--] = '\0'; while ((MAXSTRING - 1 - j) < startlength) { searchstring[j--] = s2[i++]; } while (s2[i] != '\0') { searchstring[j] = s2[i]; //printf("[S2] x == %d, i == %d, j == %d, last == %d, searchstring == %s\n",x,i,j,startlength,&(searchstring[j])); if (strstr(s1,&(searchstring[j]))) { j--; i++; } else { //printf("x == %d: returning %d\n",x,i-x); return i-x; } } //printf("x == %d: returning %d\n",x,i-x); return i-x; } // Find all bookend lengths find_bookend_lengths( char s1[], int s1_length, int s1_bookend_length[], char s2[], int s2_length, int s2_bookend_length[], char tempbuffer[]) { int x, last; /* Find the lengths of all left bookends */ last = 1; for (x=s1_length-1;x>=0;x--) { last = find_s1_bookend_length(x,s1,s2,tempbuffer,last-1); s1_bookend_length[x] = last; } //printf("S1 Bookends: "); //print_array(s1_bookend_length,s1_length); /* Find the lengths of all right bookends */ last = 1; for (x=0;x<s2_length;x++) { last = find_s2_bookend_length(x,s1,s2,tempbuffer,last-1); s2_bookend_length[x] = last; } //printf("S2 Bookends: "); //print_array(s2_bookend_length,s2_length); } /* Return the length of the palindrome formed by bookends at the end of s1 and beginning of s2 */ int find_trivial_bookend_palindrome(char *s1, int s1_length, char *s2, int s2_length) { int i = s1_length-1; int j = 0; while ((s1[i] == s2[j]) && (i >= 0) && (j < s2_length)) { i--; j++; } //printf("Trival palindrome length == %d\n",j*2); return j*2; } void save_if_best(char *candidate, char *best) { /* Note that we assume here that candidate_length == best_length */ if ((best[0] == '\0') || (strcmp(candidate,best) < 0)) { //printf("A NEW BEST! \"%s\"\n",candidate); strcpy(best,candidate); } } void reverse_string(char *target, char *source, int length) { int i; /* loop counter */ for(i=0;i<length;i++) { target[length-i-1] = source[i]; } target[length] = '\0'; } // Find the maximum palindrome length int max_palindrome_length( int s1_length, int s1_bookend_length[], int s1_palindromes[], int s2_length, int s2_bookend_length[], int s2_palindromes[]) { int best_length; int x; // Prime it with the best length of the two bookends best_length = max(s1_bookend_length[s1_length-1],s2_bookend_length[0])*2; // Body from S1 for (x=1;x<s1_length;x++) { if (s1_bookend_length[x-1]) { best_length = max(best_length,s1_bookend_length[x-1]*2+s1_palindromes[x]); } } // Body from S2 for (x=0;x<s2_length-1;x++) { if (s2_bookend_length[x+1]) { best_length = max(best_length,s2_bookend_length[x+1]*2+s2_palindromes[x]); } } return(best_length); } void find_best_palindrome( char s1[], int s1_length, char s2[], int s2_length, int best_length, int s1_bookend_length[], int s2_bookend_length[], int s1_palindromes[], int s2_palindromes[], char best[], char teststring[]) { int x; int bookend_length; int total_bookend_length; int body_length; // First deal with the bookends-only scenario if (find_trivial_bookend_palindrome(s1,s1_length,s2,s2_length) == best_length) { bookend_length = s1_bookend_length[s1_length-1]; strncpy(teststring,&(s1[s1_length-bookend_length]),bookend_length); reverse_string(&(teststring[bookend_length]),&(s1[s1_length-bookend_length]),bookend_length); //printf("Considering teststring (bookends only): \"%s\"\n",teststring); save_if_best(teststring,best); } // Next look at strings including a body from s1 for (x=1;x<s1_length;x++) { if (s1_bookend_length[x-1]*2+s1_palindromes[x] == best_length) { bookend_length = s1_bookend_length[x-1]; body_length = s1_palindromes[x]; strncpy(teststring,&(s1[x-bookend_length]),bookend_length+body_length); reverse_string(&(teststring[bookend_length+body_length]),&(s1[x-bookend_length]),bookend_length); //printf("Considering teststring (body from s1, x=%2d): \"%s\"\n",x,teststring); save_if_best(teststring,best); } } // Next look at strings including a body from s2 for (x=0;x<s2_length-1;x++) { if (s2_bookend_length[x+1]*2+s2_palindromes[x] == best_length) { bookend_length = s2_bookend_length[x+1]; body_length = s2_palindromes[x]; reverse_string(teststring,&(s2[x+1]),bookend_length); strncpy(&(teststring[bookend_length]),&(s2[x+1-body_length]),body_length+bookend_length); teststring[best_length] = '\0'; //printf("Considering teststring (body from s2, x=%2d): \"%s\"\n",x,teststring); save_if_best(teststring,best); } } } int main() { int params; char s1[MAXSTRING]; char s2[MAXSTRING]; int s1_palindromes[MAXSTRING]; int s2_palindromes[MAXSTRING]; int s1_length; int s2_length; char tempbuffer[MAXSTRING+MAXSTRING]; int s1_bookend_length[MAXSTRING]; int s2_bookend_length[MAXSTRING]; char best[MAXSTRING+MAXSTRING]; int best_length; char *teststring = tempbuffer; int teststring_length; int i; /* Temporary variable */ int n, x; /* Loop counters */ int last; ///////////////////////////////////////////////////////////////////////////// // Read in the number of pairs we'll consider ///////////////////////////////////////////////////////////////////////////// i = scanf("%i",&params); for (n=0;n<params;n++) { /////////////////////////////////////////////////////////////////////////// // Read in the pair of strings /////////////////////////////////////////////////////////////////////////// i = scanf("%s",s1); i = scanf("%s",s2); s1_length = strlen(s1); s2_length = strlen(s2); //printf("s1 == \"%s\"\n",s1); //printf("s1 length == \"%d\"\n",s1_length); //printf("s2 == \"%s\"\n",s2); //printf("s2 length == \"%d\"\n",s2_length); /* Initialize our best result */ best[0] = '\0'; best_length = 0; /////////////////////////////////////////////////////////////////////////// // Find all palindromes in s1 (left-indexed) and s2 (right-indexed) /////////////////////////////////////////////////////////////////////////// find_palindromes_left(s1,s1_length,s1_palindromes); //printf("S1 Palindromes: "); //print_array(s1_palindromes,strlen(s1)); find_palindromes_right(s2,s2_length,s2_palindromes); //printf("S2 Palindromes: "); //print_array(s2_palindromes,strlen(s2)); /////////////////////////////////////////////////////////////////////////// // Find the lengths of all bookends /////////////////////////////////////////////////////////////////////////// find_bookend_lengths( s1, s1_length, s1_bookend_length, s2, s2_length, s2_bookend_length, tempbuffer); /////////////////////////////////////////////////////////////////////////// // Determine the maximum palindrome length /////////////////////////////////////////////////////////////////////////// best_length = max_palindrome_length( s1_length, s1_bookend_length, s1_palindromes, s2_length, s2_bookend_length, s2_palindromes); //printf("best_length == %d\n",best_length); /////////////////////////////////////////////////////////////////////////// // We know the maximum length: Now find the best palindrome /////////////////////////////////////////////////////////////////////////// if (best_length < 2) { printf("-1\n"); } else { find_best_palindrome( s1, s1_length, s2, s2_length, best_length, s1_bookend_length, s2_bookend_length, s1_palindromes, s2_palindromes, best, teststring); printf("%s\n",best); } } exit(0); }
0e14444c9260ef1000f6e675ab1544cde0e5921b
[ "Markdown", "C", "Makefile", "Ruby" ]
5
C
jrotter/hackerrank_build_a_palindrome
4ea216431ac9ba24891757f59e5b2aeacf98e235
05e373ddcfe9c2cf23255060ba9ea8edbac50512
refs/heads/master
<file_sep>#include <stdio.h> #include <string.h> #include <pthread.h> #include <dirent.h> #include <fcntl.h> #include <unistd.h> #define MAX 150 pthread_t id[10]; char path[100]; char filepathlist[MAX][MAX]; int len = 0; int threadcount = 0; int sortthread(void *arg){ int i = *(int *)arg; int l = i; printf("thread %d is starting\n",i); while(l<len){ char* filepath = filepathlist[l]; char temp[1000]; char old[1000]; int fd,nbyte; if((fd = open(filepath,O_RDWR)) == -1){ printf("thread %d open file %d filed!\n",i,l); return 1; } memset(temp,0,sizeof(temp)); memset(old,0,sizeof(old)); nbyte = read(fd,temp,sizeof(temp)); read(fd,old,sizeof(old)); for(int a = 0;a < nbyte;a++){ for(int b = 0;b < nbyte - i;b++){ if(temp[b] > temp[b + 1]){ int t = temp[b]; temp[b] = temp[b + 1]; temp[b + 1] = t; } } } lseek(fd,0,SEEK_SET); write(fd,temp,nbyte); close(fd); printf("thread %d sort file %d finished!\n",i,l); //printf("thread %d sort file %d finished! old:%s new:%s\n",i,l,old,temp); l += threadcount; } printf("thread %d is over!\n",i); return 0; } int getpathlist(char path[]){ DIR *d; struct dirent *f; char temppath[MAX]; if(!(d = opendir(path))){ printf("Can't open %s\n",path); return 1; } while((f = readdir(d)) != NULL){ if(strncmp(f->d_name,".",1) == 0) continue; if(f->d_type == 8){ char txt[5]; for(int i=0;i<4;i++) txt[i] = f->d_name[strlen(f->d_name)-4+i]; txt[4]='\0'; if(strcmp(txt,".txt") == 0){ char filepath[MAX]; strcpy(filepath,path); strcat(filepath,"/"); strcat(filepath,f->d_name); strcpy(filepathlist[len++],filepath); } } if(f->d_type == 4){ strcpy(temppath,path); strcat(temppath,"/"); strcat(temppath,f->d_name); getpathlist(temppath); } } closedir(d); return 0; } int main(void){ int ret0,ret1; int ret[10]; int index[10] = {0,1,2,3,4,5,6,7,8,9}; char basepath[MAX]; printf("Please enter the path:\n"); ///Users/wangh7/Desktop/多线程/word scanf("%s",basepath); do{ printf("Please enter the number of thread(<=10):\n"); scanf("%d",&threadcount); }while(threadcount>10&&printf("Too large!\n")); if(getpathlist(basepath)) return 1; printf("found %d file(s):\n",len); for(int i = 0; i < len; i++) printf("%s\n", filepathlist[i]); for(int i=0;i<threadcount;i++){ ret[i] = pthread_create(&id[i],NULL,(void *) sortthread,&index[i]); } for(int i=0;i<threadcount;i++){ if(ret[i]!= 0){ printf("Create thread error!\n"); return 1; } } for(int i=0;i<threadcount;i++){ pthread_join(id[i],NULL); } return 0; }
6f8270b6b43e7357c811c3aedb4441d1409f533c
[ "C" ]
1
C
Wangh7/Multithread_sorting
82b49721ba5b329d4716243f38b04a9fd36e602e
6a90ae208c74faa074318eda4d9f6045c6907330
refs/heads/master
<file_sep>"use strict"; (function () { var menu = document.querySelector(".navbar"); var banner = document.querySelector("#introducao"); var footer = document.querySelector("footer"); var btnSairMenu = document.querySelector("#btn-sair-menu"); var btnMenu = document.querySelector("#btn-menu"); btnMenu.addEventListener("click", function(e){ e.preventDefault(); menu.classList.add("navbar--active"); }); btnSairMenu.addEventListener("click",function (e) { e.preventDefault(); menu.classList.remove("navbar--active"); }); document.addEventListener("click", function(e){ if(!e.target.classList.contains('btn-menu')){ menu.classList.remove("navbar--active"); } }); var links = Array.prototype.slice.call(document.querySelectorAll(".menu-itens li a")); links.forEach(function(link){ link.addEventListener("click",function () { desmarcaTodos(menuItens); this.classList.toggle("active"); }); }); var menuItens = links.reduce(function (menuItens, link) { menuItens[link.getAttribute("href").substr(1)] = link; return menuItens; }, {}); var sections = Array.prototype.map.call(document.querySelectorAll("section"), function(section, index){ return { element: section ,top: function(){ return section.getBoundingClientRect().top + window.scrollY - (menu.getBoundingClientRect().height) } ,bottom: function(){ return section.getBoundingClientRect().top + window.scrollY + section.offsetHeight - (menu.getBoundingClientRect().height) } } }); window.onscroll = _throttle(function markCurrentSection(){ var $currentSection = sections.reduce(function($currentSection, section){ if($currentSection){ return $currentSection } if(scrollY >= section.top() && scrollY <= section.bottom()){ return section.element } }, null) desmarcaTodos(menuItens) if($currentSection){ menuItens[$currentSection.getAttribute('id')].classList.add("active"); } }, 300) function desmarcaTodos(itens) { for(var prop in itens) { itens[prop].classList.remove("active"); } } function _debounce(fn, timeinmilis){ var intervaloSyncEdicao; return function(){ clearInterval(intervaloSyncEdicao); intervaloSyncEdicao = setTimeout(function(){ fn.apply(this, arguments); }, timeinmilis); } } function _throttle(fn, timeWindow){ var that; var args; var lastTime = new Date().getTime() - timeWindow; var newTime; var triggger = function(){ lastTime = newTime; fn.apply(that, args); } var shouldTrigger = function(time){ return (lastTime + timeWindow) < time; } var triggerIfLastTime = _debounce(triggger,timeWindow); return function(){ that = this; args = arguments; newTime = new Date().getTime(); triggerIfLastTime(); if(shouldTrigger(newTime)){ lastTime = newTime; fn.apply(this, arguments); } } } })(); <file_sep># Front-End Alura Sites e webapps com HTML, CSS e JavaScript. Boas práticas e últimas versões como ES6. Ferramentas e frameworks importantes como React, Angular, Webpack, jQuery e mais. # Por onde começar com Front-end ? **Front-End** pode ser descrito como a camada de software que faz parte da interface com o usuário. Tudo o que capta informação do cliente, desde botões a movimentos do celular, até as informações disponibilizadas para ele, como caixas de diálogo, páginas web e audio de voz. Quando falamos genericamente de Front-End, estamos falando de tecnologias e bibliotecas em volta de HTML, CSS e JavaScript. **HTML e CSS** - O primeiro passo para trabalhar com Front-End é entender o que realmente é a web, e após isso, aprender HTML e CSS. É importante manter a **semântica de código** e conseguir criar **sites responsivos**, que se adaptam para os mais diversos tipos de tela existentes, e que prezam pela **acessibilidade web**. Em nossos cursos de HTML e CSS, você dá os primeiros passos até avançar na criação de uma página web completa. **JavaScript e bibliotecas** - Para trazer interatividade e dinamismo para suas páginas web, você precisa de **JavaScript**. Além de conhecer as boas práticas que envolvem essa linguagem de programação, é importante aprender sobre as **bibliotecas** que facilitam o desenvolvimento. Em nossos cursos, você aprende a dominar a biblioteca mais importante do mercado, jQuery. **Automação de Front-End** - Deixar sua rotina de trabalho mais prática é possível utilizando ferramentas que automatizam seu código. Elas otimizam a **performance web**, melhoram a **velocidade de carregamento** de suas páginas e evitam retrabalhos. Você pode começar com nosso curso de performance web. **Frameworks** - Com a popularização do smartphone, o mercado de trabalho do Front-End aumentou muito, assim como as soluções para trabalhar com ele. Frameworks e ferramentas surgiram de forma exponencial, como Vue, React e Angular, conteúdo vastamente explorado na Alura. **Front-End** é um universo com milhares de galáxias a serem exploradas. Existem muitas possibilidades quando já se está no caminho, mas sempre há um início: entender o que há por trás do HTTP e começar suas primeiras linhas de código com HTML e CSS. Há também o Front-End nativo mobile, que é tratado nos nossos cursos de mobile.
2a278f4fc78dbb1a6f59270a4b2f46419fc7500f
[ "JavaScript", "Markdown" ]
2
JavaScript
LumusCode/Front-End-Alura
096c6b9f004e36157878a39d672b0dadb8a81709
02de2a55f366265a23bd1b0f2cadda2e25fddd44
refs/heads/main
<file_sep>import { INotebookState } from '../../states/INotebookState'; import ActionTypes from '../actions/ActionTypes'; import { IAction } from '../actions/IAction'; const initialState: INotebookState = { notebooks: [], selectedNotebook: undefined, }; export default function device(state: INotebookState = initialState, action: IAction): INotebookState { switch (action.type) { case ActionTypes.UPDATE_NOTEBOOK_TABLE: if (action.payload.notebooks) { return { ...state, notebooks: action.payload.notebooks, }; } return state; case ActionTypes.UPDATE_SELECTED_NOTEBOOK: if (action.payload.selectedNotebook) { return { ...state, selectedNotebook: action.payload.selectedNotebook, }; } return state; default: return state; } } <file_sep>import { IColumnSettings } from '../../common/IColumnSettings'; import { INotebookInfo } from '../INotebookInfo'; export enum ColumnKeys { NAME = 'NOTEBOOK_NAME', NAMESPACE = 'NOTEBOOK_NAMESPACE', CREATED_ON = 'NOTEBOOK_CREATED_ON', STATUS = 'NOTEBOOK_STATUS', GATEWAY_NAME = 'GATEWAY_NAME', ACTION = 'NOTEBOOK_ACTION', } export const defaultColumnSettings: { [key: string]: IColumnSettings<INotebookInfo> } = { [ColumnKeys.NAME]: { key: ColumnKeys.NAME, title: 'Name', dataIndex: 'name', editable: false, width: 200, }, [ColumnKeys.NAMESPACE]: { key: ColumnKeys.NAMESPACE, title: 'Namespace', dataIndex: 'namespace', editable: false, width: 50, }, [ColumnKeys.STATUS]: { key: ColumnKeys.STATUS, title: 'Status', dataIndex: 'status', editable: false, width: 50, }, [ColumnKeys.GATEWAY_NAME]: { key: ColumnKeys.GATEWAY_NAME, title: 'Gateway name', dataIndex: 'gatewayName', editable: false, width: 200, render: (_value, record): string => (record.gatewayName ? record.gatewayName : '-'), }, [ColumnKeys.CREATED_ON]: { key: ColumnKeys.CREATED_ON, title: 'Create on', dataIndex: 'createdOn', editable: false, width: 150, }, [ColumnKeys.ACTION]: { key: ColumnKeys.ACTION, title: 'Action', dataIndex: 'action', editable: true, width: 50, }, }; <file_sep>import { combineReducers } from 'redux'; import notebook from './notebook'; import showNotebookDetailDrawer from './showNotebookDetailDrawer'; import showNotebookCreationDrawer from './showNotebookCreationDrawer'; const reducer = combineReducers({ notebook, showNotebookDetailDrawer, showNotebookCreationDrawer, }); export default reducer; <file_sep>import ActionTypes from './ActionTypes'; export interface IAction { type: ActionTypes; payload: any; } <file_sep>import { INotebookState } from './INotebookState'; export interface IState { notebook: INotebookState; showNotebookDetailDrawer: boolean; showNotebookCreationDrawer: boolean; } <file_sep>// Same as backend export interface INotebookResponse { name: string; podName: string; namespace: string; status: string; createdOn: string; label: string[]; node: string; gatewayName: string; gatewayNamespace: string; } export interface INotebookResponses { data: INotebookResponse[]; } <file_sep>import { IContainerInfo } from '../common/IContainerInfo'; export interface INotebookInfo { name: string; podName?: string; namespace: string; status?: string; createdOn?: string; label?: string[]; conditions?: string[]; node?: string; containers?: IContainerInfo[]; gatewayName?: string; gatewayNamespace?: string; } <file_sep>import ActionTypes from '../actions/ActionTypes'; import { IAction } from '../actions/IAction'; const initialState = false; export default function showNotebookCreationDrawer(state: boolean = initialState, action: IAction): boolean { switch (action.type) { case ActionTypes.OPEN_NOTEBOOK_CREATION_DRAWER: return true; case ActionTypes.CLOSE_NOTEBOOK_CREATION_DRAWER: return false; default: return state; } } <file_sep>// @copyright Microsoft Corporation. All rights reserved. enum ActionTypes { OPEN_NOTEBOOK_DETAIL_DRAWER = 'OPEN_NOTEBOOK_DETAIL_DRAWER', CLOSE_NOTEBOOK_DETAIL_DRAWER = 'CLOSE_NOTEBOOK_DETAIL_DRAWER', OPEN_NOTEBOOK_CREATION_DRAWER = 'OPEN_NOTEBOOK_CREATION_DRAWER', CLOSE_NOTEBOOK_CREATION_DRAWER = 'CLOSE_NOTEBOOK_CREATION_DRAWER', UPDATE_NOTEBOOK_TABLE = 'UPDATE_NOTEBOOK_TABLE', UPDATE_SELECTED_NOTEBOOK = 'UPDATE_SELECTED_NOTEBOOK', } // tslint:disable-next-line:export-name export { ActionTypes as default }; <file_sep>import { ColumnProps } from 'antd/es/table'; export interface IColumnSettings<T> { key: string; title?: string; dataIndex: string; width: number; editable: boolean; sorter?: ColumnProps<T>['sorter']; onCell?: ColumnProps<T>['onCell']; // tslint:disable-next-line:no-any render?: ColumnProps<T>['render']; } <file_sep>import { INotebookInfo } from '../models/notebookModels/INotebookInfo'; export interface INotebookState { notebooks?: INotebookInfo[]; selectedNotebook?: INotebookInfo; } <file_sep>import format from 'string-format'; import { INotebookResponses } from '../models/notebookModels/INotebookResponses'; import { INotebookInfo } from '../models/notebookModels/INotebookInfo'; export default class DataProvider { private absoluteUrl: string; private static readonly DELETE_NOTEBOOK_END_POINT: string = '/notebooks?name={0}&namespace={1}'; private static readonly GET_NOTEBOOK_END_POINT: string = '/notebooks'; private static readonly CREATE_NOTEBOOK_END_POINT: string = '/notebooks'; public constructor() { this.absoluteUrl = 'http://0.0.0.0:9090'; } public deleteNotebook(name: string, namespace: string): Promise<void> { const url = format(`${this.absoluteUrl}${DataProvider.DELETE_NOTEBOOK_END_POINT}`, name, namespace); return fetch(url, { method: 'DELETE', }) .then((res) => { if (!res.ok) { throw new Error('response not ok'); } else { // eslint-disable-next-line no-useless-return return; } }) .catch((error) => { throw error; }); } public getNotebooks(): Promise<INotebookInfo[]> { return fetch(`${this.absoluteUrl}${DataProvider.GET_NOTEBOOK_END_POINT}`, { method: 'GET', }) .then((res) => res.json()) .then((data: INotebookResponses) => { const notebooks: INotebookInfo[] = DataProvider.parseNotebookResponses(data); return notebooks; }) .catch((error) => { throw error; }); } public createNotebook(settings: INotebookInfo): Promise<void> { const requestOptions: RequestInit = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...settings }), }; return fetch(`${this.absoluteUrl}${DataProvider.CREATE_NOTEBOOK_END_POINT}`, requestOptions) .then((res) => { if (!res.ok) { throw new Error('response not ok'); } else { // eslint-disable-next-line no-useless-return return; } }) .catch((error) => { throw error; }); } private static parseNotebookResponses(notebooks: INotebookResponses): INotebookInfo[] { const res: INotebookInfo[] = []; for (const notebook of notebooks?.data) { res.push({ name: notebook.name, podName: notebook.podName, namespace: notebook.namespace, status: notebook.status, createdOn: notebook.createdOn, label: notebook.label, node: notebook.node, gatewayName: notebook.gatewayName, gatewayNamespace: notebook.gatewayNamespace, }); } return res; } } <file_sep>export interface IContainerInfo { containerName: string; containerStatus?: string; lastStatus?: string; image?: string; environment?: string; mounts?: string; commands?: string[]; ports?: string; volumes?: string; } <file_sep>export interface INotebookSettings { notebookName?: string; notebookNamespace?: string; gatewayName?: string; gatewayNamespace?: string; containerName?: string; image?: string; ports?: string; command?: string[]; volumes?: string; environment?: string; }
74ff8b93e8da0cbb9f90ce8218c83587a1d54c1b
[ "TypeScript" ]
14
TypeScript
Mirrored90/elastic-jupyter-dashboard
06cbe018172aaf3753fbf8d13041179955223ba4
549b091c4824995cc82650954e5a58b994741afb
refs/heads/master
<file_sep>/** * Created by orenga on 7/1/17. */ public class Course { String number; String name; String faculty; String department; public Course(CourseRaw rawCourse, String faculty, String department) { this.number = rawCourse.courseNumber; this.name = rawCourse.courseName; this.faculty = faculty; this.department = department; } public Course() { } @Override public String toString() { return "Course{" + "number='" + number + '\'' + ", name='" + name + '\'' + ", faculty='" + faculty + '\'' + ", department='" + department + '\'' + '}'; } } <file_sep>/** * Created by orenga on 7/1/17. */ public class CourseRaw { String refPage; String courseName; String courseNumber; public CourseRaw(String refPage, String courseName, String courseNumber) { this.refPage = refPage; this.courseName = courseName; this.courseNumber = courseNumber; } }
0655893e473bd01deed99bddf49808aa65ef900f
[ "Java" ]
2
Java
ogadiel/openu-courses-parser
815317edde6990d753729dfa433e0da2a6daa956
76286cba4daa7eac9137319806988d93e58b05f0
refs/heads/master
<file_sep>var tmi = require('tmi.js'); var keys = require('./keys'); var currentChannel = ["TheKingOfPikmin", "walters954"] var options = { options:{ debug: true }, connection:{ cluster: "aws", reconnect: true }, identity:{ username: "YungYungerbot", password: keys.currentApiKey() }, channels: currentChannel }; var client = new tmi.client(options); client.connect(); // client.on('connected', (address, port) => // { // client.action(currentChannel[0], "The Yungerson is here!") // }); client.on('chat', (channel, user, message, self) => { message = message.toLowerCase() if(message.includes('yung')) { client.action(channel, user['display-name'] + " is not as yung as me!") } else if(message.includes('mike')) { client.action(channel,"You got em bois") } else if(message.includes('jeremy')) { client.action(channel,"Pikim banned me once but now we are friends.") }else if(message.includes('lag')) { client.action(channel,"Everyone has gotta lag sometimes!") } })
c3ab3051c34061674f6f2ddff6eedfdd9fff562e
[ "JavaScript" ]
1
JavaScript
walters954/YungBot
019c151b01dbc85e3f4870de5fc9a91ac58ac141
051e952b969f8a3bff277e3fc65f9f4eb657889b
refs/heads/master
<repo_name>xlliu/web_service<file_sep>/edy_web_services.1/edy_web_services.py # -*- coding: utf-8 -*- import md5 import sys import uuid reload(sys) sys.setdefaultencoding('utf8') import time import re import ConfigParser import xlsxwriter as xlsxwriter # import pandas as pd from bson import ObjectId from flask import Flask, jsonify, g, send_from_directory, request from common.mongodb_conn import mongodb_conn from common.utils import ConvertTime, StringMD5 from savReaderWriter.savWriter import SavWriter app = Flask(__name__) import logging # 使用一个名字为fib的logger logger = logging.getLogger('fib') # 设置logger的level为DEBUG logger.setLevel(logging.DEBUG) # 创建一个输出日志到控制台的StreamHandler hdr = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s] %(name)s:%(levelname)s: %(message)s') hdr.setFormatter(formatter) # 给logger添加上handler logger.addHandler(hdr) config = ConfigParser.ConfigParser() # 初始化config实例(建立一个空的数据集实例) config.read("/data/pywww/web_services/edy_web_services.1/db.conf") # 通过load文件filename来初始化config实例 # config.read("C:\Users\Administrator\PycharmProjects\web_service\edy_web_services.1\db.conf") # 通过load文件filename来初始化config实例 db_1 = config.get("edy_web_services.1", "db_name_1") # 获得指定section中的key的value db_2 = config.get("edy_web_services.1", "db_name_2") host = config.get("edy_web_services.1", "host") port = config.getint("edy_web_services.1", "port") logger.info("logging run start========================================>") @app.before_request def before_request(): logger.info("IP: %s" % request.remote_addr) g.mongo_collection = mongodb_conn(host, port, db_1, flag=0).conn() g.mongo_collection_spss = mongodb_conn(host, port, db_2, flag=0).conn() # g.mysql_conn = mysqldb_conn("10.10.0.9", 3306, "esuser").conn() @app.teardown_request def teardown_request(exception): if g.db is not None: g.db.close() # if g.mysql_conn is not None: # g.mysql_conn.close() @app.route('/app/exis_changelog/<string:pid>') def exis_changelog(pid): _pid = "pid_%s" % pid document_project = getattr(g.mongo_collection, _pid) res = document_project.distinct(u"版本") return jsonify({"data": res}) @app.route('/app/generator_spss/<int:version>_<string:pid>') def generator_spss(version, pid): filepath = '/data/pywww/web_services/temp_spss/' # filepath = 'd:\\' filename = '%s.sav' % pid fpn = filepath + filename _pid = "pid_%s" % pid document_project = getattr(g.mongo_collection_spss, _pid) vartitle = document_project.find_one({"版本": version}, {"_id": 0}) vt = vartitle.get("k_pid") vty = vartitle.get("q_type") vo = [dict(zip([vot_ for vot_ in vot], [str(vot_) for vot_ in vot])) if isinstance(vot, list) else vot for vot in [dict(zip(v[0], v[1])) if v else None for v in vartitle.get("options")]] vs = vartitle.get("k_list") records = document_project.find({"版本": version}, {"_id": 0}, no_cursor_timeout=True) vr_t = [] for v in records: user = StringMD5.md5(v.get("用户".decode('utf8'))) starttime = ConvertTime.timestamp_2_time(v.get("开始时间".decode('utf8'))) endtime = ConvertTime.timestamp_2_time(v.get("结束时间".decode('utf8'))) changelog = v.get("版本".decode('utf8')) vr = v.get("v_list") vr = [user, starttime, endtime, changelog] + vr vr_t.append(vr) # resu = pd.DataFrame(vr_t) varNames = vt # varTypes = dict(zip(varNames, [50 if v.name == "object" else 0 for v in resu.dtypes.tolist()])) varTypes = dict(zip(varNames, [200 if v == "string" else 0 for v in vty])) varTypes["ID"] = 200 varTypes["StartTime"] = 200 varTypes["EndTime"] = 200 varTypes["VerNo"] = 0 formats = dict(zip(varNames, ['A200' if v == 'string' else 'F5.0' for v in vty])) formats["ID"] = 'A200' formats["StartTime"] = 'A200' formats["EndTime"] = 'A200' formats["VerNo"] = 'F5.0' varNames = ["ID", "StartTime", "EndTime", "VerNo"] + varNames vs = [u"用户", u"开始时间", u"结束时间", u"版本"] + vs # varTypes = dict(zip(varNames, [50]*len(varNames))) # va_temp = dict(zip(varNames, [{str(index+1): str(vvn) if isinstance(vvn, int) else vvn for index, vvn in enumerate(vn)} for vn in vo])) # # 清洗 # [va_temp.pop(k) for k, v in va_temp.items() if not v.get("1")] # 倒排值 # va_av_temp = {k: {v1: k1 for k1, v1 in v.items()} for k, v in va_temp.items()} varAttributes = {k: v for k, v in zip(vt, vo) if v} valueLabels = {k: v for k, v in zip(vt, vo) if v} varLabels = dict(zip(varNames, vs)) ioUtf8 = True # missingValues = {'v4': "自动补齐"} # varNames = [k for k, v in zip(varNames, xrange(len(varNames)))] with SavWriter(savFileName=fpn, varNames=varNames, varTypes=varTypes, varLabels=varLabels, valueLabels=valueLabels, ioUtf8=ioUtf8, formats=formats) as writer: # try: writer.writerows(vr_t) # except Exception as e: # print e return send_from_directory(filepath, filename, as_attachment=True) @app.route('/app/generator_excel_zkey/<int:version>_<string:pid>_<int:skip>_<int:limit>') def generator_excel_zkey(version, pid, skip, limit): start = time.time() p = re.compile('^\d{10}$') def objectId_to_str(value): if isinstance(value, ObjectId): return str(value) if p.match(str(value)) if isinstance(value, long) else p.match(value): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(value)) return value _pid = "pid_%s" % pid document_project = getattr(g.mongo_collection, _pid) filepath = '/data/pywww/web_services/temp_excel/' # filepath = 'D:\\' filename = '%s.xlsx' % pid dpt_1 = document_project.find_one({"版本": version}, {"_id": 0}) dp = document_project.find({"版本": version}, {"_id": 0}, no_cursor_timeout=True).skip(skip).limit(limit) workbook = xlsxwriter.Workbook(filepath + filename, {'constant_memory': True}) worksheet = workbook.add_worksheet() k_top = ["开始时间", "结束时间", "用户", "序号", "版本"] kl = dpt_1.get("k_list")[4:] if "用户" in dpt_1.get("k_list") else dpt_1.get("k_list") worksheet.write_row(0, 0, k_top + kl) n = 1 try: for v in dp: vt = [] vt.append(v.get(unicode("开始时间"))) vt.append(v.get(unicode("结束时间"))) vt.append(v.get(unicode("用户"))) vt.append(v.get(unicode("序号"))) vt.append(v.get(unicode("版本"))) vt.extend(v.get("v_list")[4:] if "用户" in v.get("k_list") else v.get("v_list")) worksheet.write_row(n, 0, vt) n += 1 workbook.close() except Exception, e: print e end = time.time() print end - start return send_from_directory(filepath, filename, as_attachment=True) @app.route('/app/generator_excel/<int:version>_<string:pid>_<int:skip>_<int:limit>') def generator_excel(version, pid, skip, limit): start = time.time() p = re.compile('^\d{10}$') def objectId_to_str(value): if isinstance(value, ObjectId): return str(value) if p.match(str(value)) if isinstance(value, long) else p.match(value): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(value)) return value _pid = "pid_%s" % pid document_project = getattr(g.mongo_collection, _pid) filepath = '/data/pywww/web_services/temp_excel/' # filepath = 'D:\\' filename = '%s.xlsx' % pid dpt_1 = document_project.find_one({"版本": version}, {"_id": 0}) dp = document_project.find({"版本": version}, {"_id": 0}, no_cursor_timeout=True).skip(skip).limit(limit) workbook = xlsxwriter.Workbook(filepath + filename, {'constant_memory': True}) worksheet = workbook.add_worksheet() k_top = ["开始时间", "结束时间", "用户", "序号", "版本"] kl = dpt_1.get("k_list")[4:] if "用户" in dpt_1.get("k_list") else dpt_1.get("k_list") worksheet.write_row(0, 0, k_top + kl) n = 1 try: for v in dp: vt = [] vt.append(v.get(unicode("开始时间"))) vt.append(v.get(unicode("结束时间"))) vt.append(StringMD5.md5(v.get(unicode("用户")))) vt.append(v.get(unicode("序号"))) vt.append(v.get(unicode("版本"))) vt.extend(v.get("v_list")[4:] if "用户" in v.get("k_list") else v.get("v_list")) worksheet.write_row(n, 0, vt) n += 1 workbook.close() except Exception, e: print e end = time.time() print end - start return send_from_directory(filepath, filename, as_attachment=True) @app.route('/app/show_excel_info/<int:version>_<string:pid>_<int:skip>_<int:limit>') def show_excel_info(version, pid, skip, limit): _pid = "pid_%s" % pid document_project = getattr(g.mongo_collection, _pid) dpt_k = document_project.find_one({"版本": version}, {"_id": 0, "k_list": 1}) dpt_v = document_project.find({"版本": version}, {"_id": 0, "v_list": 1, "k_list": 1}).skip(skip).limit(limit) dpt_value = [] for dv in dpt_v: dpt_value.append(dv.get("v_list")[4:]) if u"用户" in dv.get("k_list") else dpt_value.append(dv.get("v_list")) data_list = [dpt_k.get("k_list")[4:] if u"用户" in dpt_k.get("k_list") else dpt_k.get("k_list")] + dpt_value return jsonify({"data": data_list}) if __name__ == '__main__': app.run(port=5002) <file_sep>/edy_web_services/requirements.txt Flask == 0.10.1 pymongo == 3.2.2 PyMySQL == 0.7.2 tornado == 4.3 <file_sep>/web_services_run.sh #rm -rf edy_web_services/ #svn checkout svn://1172.16.31.10/datapr edy_web_services --username yulong --password <PASSWORD> cd edy_web_services nohup python tornado_server.py & cd .. ps -ef | grep tornado_server | grep -v "grep" | awk '{print $2}' > edy_web_services.pid echo "============================================== edy_web_services.pid was written to Success =========================================================" cd edy_web_services.1 nohup python tornado_server_1.py & cd .. ps -ef | grep tornado_server_1 | grep -v "grep" | awk '{print $2}' > edy_web_services_1.pid echo "============================================== edy_web_services_1.pid was written to Success ========================================================="<file_sep>/edy_web_services/edy_web_services.py # -*- coding: utf-8 -*- import logging import time import pymongo import pytz import re import xlsxwriter as xlsxwriter from bson import ObjectId from collections import OrderedDict from flask import Flask, jsonify, g, send_from_directory from common.mongodb_conn import mongodb_conn from common.mysql_conn import mysqldb_conn app = Flask(__name__) import logging # 使用一个名字为fib的logger logger = logging.getLogger('fib') # 设置logger的level为DEBUG logger.setLevel(logging.DEBUG) # 创建一个输出日志到控制台的StreamHandler hdr = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s] %(name)s:%(levelname)s: %(message)s') hdr.setFormatter(formatter) # 给logger添加上handler logger.addHandler(hdr) logger.info("logging run start========================================>") @app.before_request def before_request(): g.mongo_collection_edy = mongodb_conn("10.10.0.5", 27017, "xyt_survey", flag=0).conn() g.mysql_conn = mysqldb_conn("10.10.0.9", 3306, "esuser").conn() @app.teardown_request def teardown_request(exception): if g.db is not None: g.db.close() if g.mysql_conn is not None: g.mysql_conn.close() @app.route('/app/weixin/five_list/<int:num>_<string:sort>') def five_list(num=5, sort=""): tzchina = pytz.timezone('Asia/Shanghai') utc = pytz.timezone('UTC') document_project = g.mongo_collection_edy.xyt_survey_project cur = g.mysql_conn.cursor() result = document_project.find({"is_sendpacket": 1, "is_show_wx": {'$ne': 1}, "status":1}).sort("publicdate", pymongo.DESCENDING).limit(num) text = {} temp_text = [] for r in result: temp_list = {} temp_list["pid"] = r.get("short_id") temp_list["title"] = r.get("title") # temp_list["title"] = r.get("title") temp_list["is_sendpacket"] = r.get("is_sendpacket") temp_list["publicdate"] = r.get("publicdate").replace(tzinfo=utc).astimezone(tzchina).strftime( "%Y-%m-%d %H:%M:%S") if r.get("publicdate", "") else "" cur.execute('select mobile from ea_user where user_id=%s', r.get("creator_id")) temp_list["phone"] = cur.fetchone()[0] temp_text.append(temp_list) text["result"] = temp_text return jsonify(text) if __name__ == '__main__': app.run(port=5001) <file_sep>/edy_web_services.1/.~c9_invoke_eYaR6H.py # -*- coding: utf-8 -*- import logging import time import pymongo import pytz import re import xlsxwriter as xlsxwriter from bson import ObjectId from collections import OrderedDict from flask import Flask, jsonify, g, send_from_directory, request from common.mongodb_conn import mongodb_conn from common.mysql_conn import mysqldb_conn app = Flask(__name__) import logging # 使用一个名字为fib的logger logger = logging.getLogger('fib') # 设置logger的level为DEBUG logger.setLevel(logging.DEBUG) # 创建一个输出日志到控制台的StreamHandler hdr = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s] %(name)s:%(levelname)s: %(message)s') hdr.setFormatter(formatter) # 给logger添加上handler logger.addHandler(hdr) logger.info("logging run start========================================>") @app.before_request def before_request(): logger.info("IP: %s" %request.remote_addr) g.mongo_collection = mongodb_conn("10.10.0.5", 27017, "xyt_survey_data", flag=0).conn() # g.mysql_conn = mysqldb_conn("10.10.0.9", 3306, "esuser").conn() @app.teardown_request def teardown_request(exception): if g.db is not None: g.db.close() # if g.mysql_conn is not None: # g.mysql_conn.close() @app.route('/app/generator_excel/<int:version>_<string:pid>_<int:skip>_<int:limit>') def generator_excel(version, pid, skip, limit): start = time.time() p = re.compile('^\d{10}$') def objectId_to_str(value): if isinstance(value, ObjectId): return str(value) if p.match(str(value)) if isinstance(value, long) else p.match(value): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(value)) return value _pid = "pid_%s" % pid document_project = getattr(g.mongo_collection, _pid) filepath = '/data/pywww/web_services/temp_excel/' # filepath = 'D:\\' filename = '%s.xlsx' % pid dpt_1 = document_project.find_one({"0d版本": version},{"_id": 0}) dp = document_project.find({"0d版本": version},{"_id": 0}, no_cursor_timeout=True).skip(skip).limit(limit) workbook = xlsxwriter.Workbook(filepath + filename, {'constant_memory': True}) worksheet = workbook.add_worksheet() #dpt = OrderedDict(sorted(dpt_1.items(),key=lambda d: d[0])) kl = dpt_1.keys() # kl.sort() worksheet.write_row(0, 0, kl) n = 1 try: for v in dp: #si = sorted(v.iteritems(), key=lambda b: b[0]) #kv = OrderedDict(si) # worksheet.write_row(n, 0, map(objectId_to_str, kv.values())) worksheet.write_row(n, 0, v.values()) n += 1 workbook.close() except Exception, e: print e end = time.time() print end - start return send_from_directory(filepath, filename, as_attachment=True) @app.route('/app/show_excel_info/<int:version>_<string:pid>_<int:skip>_<int:limit>') def show_excel_info(version, pid, skip, limit): _pid = "pid_%s" % pid document_project = getattr(g.mongo_collection, _pid) dpt_1 = document_project.find({"0d版本": version},{"_id": 0,"0d开始时间":0,"0d结束时间":0,"0d序号":0, ""}).skip(skip).limit(limit) data_list = list(dpt_1) return jsonify({"data": data_list}) if __name__ == '__main__': app.run(port=5002) <file_sep>/edy_web_services/tornado_server.py # -*- coding: utf-8 -*- import logging import logging.config from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from edy_web_services import app # abs_path = os.path.split(os.path.realpath(__file__))[0] # 使用一个名字为fib的logger logger = logging.getLogger('fib') # 设置logger的level为DEBUG logger.setLevel(logging.DEBUG) # 创建一个输出日志到控制台的StreamHandler hdr = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s] %(name)s:%(levelname)s: %(message)s') hdr.setFormatter(formatter) # 给logger添加上handler logger.addHandler(hdr) if __name__ == '__main__': http_server = HTTPServer(WSGIContainer(app),xheaders=True) http_server.listen(5000) IOLoop.instance().start() <file_sep>/web_services_kill.sh kill -9 `cat edy_web_services.pid` echo "pid: `cat edy_web_services.pid` KO Success" kill -9 `cat edy_web_services_1.pid` echo "pid: `cat edy_web_services_1.pid` KO Success" <file_sep>/edy_web_services.1/common/utils.py #!/usr/bin/env python # -*- coding:utf-8 -*- """ @version: 1.0.0 @author: xlliu @contact: <EMAIL> @site: https://github.com/xlliu @software: PyCharm @file: utils.py @time: 2016/8/8 19:05 """ import hashlib import time class ConvertTime(object): """ About time convert """ @staticmethod def time_2_timestamp(time, **kwargs): time_frame = kwargs.get("timeframe", "%Y-%m-%d %H:%M:%S") # a = "2013-10-10 23:40:00" time_array = time.strptime(time, time_frame) # 转换为时间戳: time_stamp = int(time.mktime(time_array)) return time_stamp @staticmethod def timestamp_2_time(timestamp, **kwargs): time_frame = kwargs.get("timeframe", "%Y-%m-%d %H:%M:%S") # a = "2013-10-10 23:40:00" time_array = time.localtime(timestamp) time_str = time.strftime(time_frame, time_array) return time_str class StringMD5(object): def __init__(self): pass @staticmethod def md5(str): m = hashlib.md5() m.update(str) return m.hexdigest()
7c14e0ce91e94677db4a59287c3fb20b7f9b9af8
[ "Python", "Text", "Shell" ]
8
Python
xlliu/web_service
b023b16c892905c4f9b31cf0fe58819206c3880b
9af406ab167f13cf2f1996951f8e4f543b0dcc88
refs/heads/master
<repo_name>ahierro/springdatamongoejemplo<file_sep>/src/main/java/ar/com/mongo/ejemplo/futbol/dao/repository/ClubRepository.java package ar.com.mongo.ejemplo.futbol.dao.repository; import org.bson.types.ObjectId; import org.springframework.data.repository.PagingAndSortingRepository; import ar.com.mongo.ejemplo.futbol.dao.entity.Club; public interface ClubRepository extends PagingAndSortingRepository<Club, ObjectId>{ }
d07a22ada4b33445c97184a8f246d9150fc65ec4
[ "Java" ]
1
Java
ahierro/springdatamongoejemplo
d66e9e510215b9a75399326254e08730d7a65f15
574c52c1be348e1e3f85e44e0caf08fc1c60b362
refs/heads/master
<repo_name>TankMermaid/Drought-Root-Microbiome<file_sep>/temp/demo.py ######################################################################### # File Name: demo.py # Author: <NAME> # mail: <EMAIL> # Created Time: Tue 24 Nov 2020 08:08:30 PM CST ######################################################################### #!/bin/python ## this is a demo programm displaying some feature of vim and zsh function JFIAJIFAIJ FJAIJFIAJIF FAJIJFIAJIFJAIFJIA FKAIOJFIAJIFJAI JFIAJFIAJ FJAIJFIAJIFJAI FJAIFJAIJFIA JIFAJIJFAIF # File Name: demo.py # Author: <NAME> # mail: <EMAIL> # Created Time: Tue 24 Nov 2020 08:08:30 PM CST ######################################################################### #!/bin/python ## this is a demo programm displaying some feature of vim and zsh function
7b52e27ec0279df3500d518a31062eb40a7a2606
[ "Python" ]
1
Python
TankMermaid/Drought-Root-Microbiome
7518e5266bd789223751d4ae5226b6e4fe6bc672
9547f405adbd0384401f743511b76253eb115546
refs/heads/master
<file_sep>#!/usr/bin/env python import boto3 def create_instances(): ec2 = boto3.resource('ec2') # create the instance of the type ami-e689729e temp = ec2.create_instances(ImageId='ami-e689729e', MinCount=1, MaxCount=1,InstanceType='t2.micro') return temp[0].id create_instances() <file_sep>import boto3 s3 = boto3.client('s3') response = s3.create_bucket(ACL='private', Bucket='my-boto-s3-demo',CreateBucketConfiguration={'LocationConstraint':'us-west-2'}) print(response) <file_sep>#!/usr/bin/env python import boto3 import os #import the create instance function and pass the instance_id to terminate_isnatnce function import create_ec2 def terminate_instance(instance_id): # connect to the ec2 resource ec2 = boto3.resource('ec2') print(instance_id) print("stopping instances...") # stop the running instance based on the ID ec2.instances.filter(InstanceIds=instance_id).terminate() res = create_ec2.create_instances() print(res, "this is id") terminate_instance(res)
2c8196b421e64e4b31e0ebf69e91d1b5bbf710f7
[ "Python" ]
3
Python
saraducks/AWS_boto
0894db075bda6aa4f3d9b52d953a47f26d054574
68955c7147b62a87af903da08d3b993cfcda7607
refs/heads/master
<repo_name>TobyRet/web_analyser<file_sep>/spec/reader_spec.rb require_relative('../lib/reader') describe Reader do it 'does something'do reader = Reader.new('./spec/fixtures/webserver_fixture.log') read_lines = reader.run expect(read_lines.first).to eq("/contact 158.577.775.616\n") end end <file_sep>/README.md # Web Analyser A ruby programme that processes a webserver log and calculates: - most popular page views - unique page views In this implementation, the path to the webserver log is hard-coded. Code coverage is 96% (using the SimpleCov gem) ## Run the programme 1. `bundle install` 2. `ruby -r './lib/app.rb' -e 'App.run'` <file_sep>/lib/parser.rb # frozen_string_literal: true require_relative './line' class Parser attr_reader :lines def initialize(lines) @lines = lines end def run @lines.map do |line| split_line = line.split(' ') Line.new(split_line.first, split_line.last) end end end <file_sep>/spec/app_spec.rb require_relative '../lib/app.rb' describe App do it 'processes a web server log' do expected = [ {:page=>"/about", :page_views=>4}, {:page=>"/home", :page_views=>3}, {:page=>"/about/2", :page_views=>3}, {:page=>"/contact", :page_views=>2}, {:page=>"/help_page/1", :page_views=>1} ], [ {:page=>"/home", :unique_views=>3}, {:page=>"/about/2", :unique_views=>3}, {:page=>"/about", :unique_views=>2}, {:page=>"/contact", :unique_views=>2}, {:page=>"/help_page/1", :unique_views=>1} ] expect(Printer).to receive(:print).with(expected) App.process('./spec/fixtures/webserver_fixture.log') end end <file_sep>/spec/analyser_spec.rb require_relative '../lib/analyser' require_relative '../lib/line' describe Analyser do let(:parsed_log) { [ Line.new('/about', '123.456.789'), Line.new('/about', '123.456.789') ] } let(:subject) { Analyser } it 'calculates page views' do expected_result = [ { page: '/about', page_views: 2 } ] expect(subject.page_views(parsed_log)).to eq(expected_result) end it 'calculates unique views' do expected_result = [ { page: '/about', unique_views: 1 } ] expect(subject.unique_views(parsed_log)).to eq(expected_result) end end <file_sep>/lib/app.rb require_relative './reader' require_relative './parser' require_relative './analyser' require_relative './printer' class App def self.run process("./logs/webserver.log") end def self.process(log) read_log = Reader.new(log).run parsed_log = Parser.new(read_log).run log_grouped_by_page_views = Analyser.page_views(parsed_log) log_grouped_by_unique_views = Analyser.unique_views(parsed_log) Printer.print( [ log_grouped_by_page_views, log_grouped_by_unique_views ] ) end end <file_sep>/lib/reader.rb # frozen_string_literal: true class Reader attr_reader :file_path def initialize(file_path) @file_path = file_path end def run lines = [] File.readlines(file_path) do |line| lines.push(line) end end end <file_sep>/lib/analyser.rb # frozen_string_literal: true class Analyser def self.page_views(parsed_log) grouped_log = group_log(parsed_log).map do |page, ip_addresses| { page: page, page_views: ip_addresses.length } end sort_ascending(grouped_log, :page_views) end def self.unique_views(parsed_log) grouped_log = group_log(parsed_log).map do |page, ip_addresses| { page: page, unique_views: ip_addresses.uniq.length } end sort_ascending(grouped_log, :unique_views) end private def self.group_log(parsed_log) parsed_log.group_by(&:page) end def self.sort_ascending(log, key) log.sort_by { |hsh| hsh[key] }.reverse end end <file_sep>/spec/parser_spec.rb require_relative('../lib/parser') describe Parser do it 'parses a server log' do read_lines = [ "/page_a 123.456.789", "/page_b 789.456.789", ] parser = Parser.new(read_lines) parsed_lines = parser.run #expect(parsed_lines.length).to eq(2) #first_line = parsed_lines.first #expect(first_line).to be_kind_of(Line) #expect(first_line.page).to eq('/page_a') #expect(first_line.ip_address).to eq('123.456.789') end end <file_sep>/lib/printer.rb # frozen_string_literal: true class Printer def self.print(logs) logs.each { |log| p log } end end <file_sep>/lib/line.rb # frozen_string_literal: true class Line < Struct.new(:page, :ip_address); end
d68835c5d941e16f639b116fadc685ac0c85218c
[ "Markdown", "Ruby" ]
11
Ruby
TobyRet/web_analyser
7d20771a323d8a4686975da64667b67900334c5e
fbf845857a12b319edeae79c23e0e7e3912cf1d3
refs/heads/main
<file_sep>include ':app' rootProject.name = "PesanPancong"<file_sep>package com.example.pesanpancong; import android.os.Parcel; import android.os.Parcelable; public class Pemesanan implements Parcelable { private String viewName, viewBawa, viewPancong, viewCoklat, viewKeju, viewKacang, viewOreo; public Pemesanan(String viewName, String viewBawa, String viewPancong, String viewCoklat, String viewKeju, String viewKacang, String viewOreo) { this.viewName = viewName; this.viewBawa = viewBawa; this.viewPancong = viewPancong; this.viewCoklat = viewCoklat; this.viewKeju = viewKeju; this.viewKacang = viewKacang; this.viewOreo = viewOreo; } public Pemesanan() { } public String getViewName() { return viewName; } public void setViewName(String viewName) { this.viewName = viewName; } public String getViewBawa() { return viewBawa; } public void setViewBawa(String viewBawa) { this.viewBawa = viewBawa; } public String getViewPancong() { return viewPancong; } public void setViewPancong(String viewPancong) { this.viewPancong = viewPancong; } public String getViewCoklat() { return viewCoklat; } public void setViewCoklat(String viewCoklat) { this.viewCoklat = viewCoklat; } public String getViewKeju() { return viewKeju; } public void setViewKeju(String viewKeju) { this.viewKeju = viewKeju; } public String getViewKacang() { return viewKacang; } public void setViewKacang(String viewKacang) { this.viewKacang = viewKacang; } public String getViewOreo() { return viewOreo; } public void setViewOreo(String viewOreo) { this.viewOreo = viewOreo; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.viewName); dest.writeString(this.viewBawa); dest.writeString(this.viewPancong); dest.writeString(this.viewCoklat); dest.writeString(this.viewKeju); dest.writeString(this.viewKacang); dest.writeString(this.viewOreo); } protected Pemesanan(Parcel in) { this.viewName = in.readString(); this.viewBawa = in.readString(); this.viewPancong = in.readString(); this.viewCoklat = in.readString(); this.viewKeju = in.readString(); this.viewKacang = in.readString(); this.viewOreo = in.readString(); } public static final Creator<Pemesanan> CREATOR = new Creator<Pemesanan>() { @Override public Pemesanan createFromParcel(Parcel source) { return new Pemesanan(source); } @Override public Pemesanan[] newArray(int size) { return new Pemesanan[size]; } }; } <file_sep># ViewModel <NAME> TI/3F 17
cc706906945ed38254b5f1c74e4deed836643f48
[ "Markdown", "Java", "Gradle" ]
3
Gradle
mirzarayhan/ViewModel
b6e03e2903f5e9526ac393da8447596bade09efc
6990dbf0d9644c7906a3f134f5081f312a935248
refs/heads/master
<file_sep><h1 id="toc_0">一个支持渐变色的圆环进度条控件</h1> <pre><code>XML支持 1.circleWidth 圆环的宽度 2.circleAngle 圆环的进度 3.backgroundColor 圆环的默认背景颜色 代码支持 1.setCircleWidth 圆环宽度(DP) 2.setColorArray 圆环的渐变颜色数组 3.例如: int[] colorArray = new int[]{Color.parseColor(&quot;#27B197&quot;), Color.parseColor(&quot;#00A6D5&quot;)}; 4.如果数组长度为1 那么默认颜色为填充全部无渐变效果 5.setProgress 设置圆环进度(添加由快到慢的插值器) </code></pre> ![](https://github.com/732275239/CircleProgress/blob/master/0223_1.jpg?raw=true) <file_sep>package com.CircleProgress.Circle_progress_bar; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private CircleProgressBar circleBar; private Button add; private Button reduce; private int Progress = 10; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); circleBar = (CircleProgressBar) findViewById(R.id.CircleBar); add = (Button) findViewById(R.id.add); reduce = (Button) findViewById(R.id.reduce); int[] ints = {Color.parseColor("#27B197"), Color.parseColor("#00A6D5")}; //设置圆环的进度颜色(渐变) circleBar.setColorArray(ints); //设置圆环周围的阴影颜色 circleBar.setShadowColor(Color.parseColor("#E2E0DE")); //设置默认进度 circleBar.setProgress(Progress); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Progress += 10; if (Progress>=100){ Progress=100; } circleBar.setProgress(Progress, true); } }); reduce.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Progress -= 10; if (Progress<=0){ Progress=0; } circleBar.setProgress(Progress, true); } }); } }
918b8cdf1965511be16d88d0c6e68b05235f3039
[ "Markdown", "Java" ]
2
Markdown
732275239/CircleProgress
61001a3b823cc36a178303e441ee6c77651f1fc0
b67e80409aadfd4ceac0353cb8661d088b8eaeb1
refs/heads/master
<file_sep><?php /* * This file is part of the Dektrium project. * * (c) Dektrium project <http://github.com/dektrium> * * For the full copyright and license information, please view the LICENSE.md * file that was distributed with this source code. */ namespace wartron\yii2account\rbac\components; use yii\db\Query; use yii\rbac\Assignment; use yii\rbac\Item; use yii\rbac\DbManager as BaseDbManager; use wartron\yii2uuid\helpers\Uuid; /** * This Auth manager changes visibility and signature of some methods from \yii\rbac\DbManager. * * @author <NAME> <<EMAIL>> */ class DbManager extends BaseDbManager implements ManagerInterface { /** * @inheritdoc */ public function getRolesByUser($accountId) { $accountId = Uuid::str2uuid($accountId); if (empty($accountId)) { return []; } $query = (new Query)->select('b.*') ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable]) ->where('{{a}}.[[item_name]]={{b}}.[[name]]') ->andWhere(['a.account_id' => $accountId]) ->andWhere(['b.type' => Item::TYPE_ROLE]); $roles = []; foreach ($query->all($this->db) as $row) { $roles[$row['name']] = $this->populateItem($row); } return $roles; } /** * @inheritdoc */ public function getPermissionsByUser($accountId) { $accountId = Uuid::str2uuid($accountId); if (empty($accountId)) { return []; } $query = (new Query)->select('item_name') ->from($this->assignmentTable) ->where(['account_id' => $accountId]); $childrenList = $this->getChildrenList(); $result = []; foreach ($query->column($this->db) as $roleName) { $this->getChildrenRecursive($roleName, $childrenList, $result); } if (empty($result)) { return []; } $query = (new Query)->from($this->itemTable)->where([ 'type' => Item::TYPE_PERMISSION, 'name' => array_keys($result), ]); $permissions = []; foreach ($query->all($this->db) as $row) { $permissions[$row['name']] = $this->populateItem($row); } return $permissions; } /** * @inheritdoc */ public function getAssignment($roleName, $accountId) { $accountId = Uuid::str2uuid($accountId); if (empty($accountId)) { return null; } $row = (new Query)->from($this->assignmentTable) ->where(['account_id' => $accountId, 'item_name' => $roleName]) ->one($this->db); if ($row === false) { return null; } return new Assignment([ 'userId' => $row['account_id'], 'roleName' => $row['item_name'], 'createdAt' => $row['created_at'], ]); } /** * @inheritdoc */ public function getAssignments($accountId) { $accountId = Uuid::str2uuid($accountId); if (empty($accountId)) { return []; } $query = (new Query) ->from($this->assignmentTable) ->where(['account_id' => $accountId]); $assignments = []; foreach ($query->all($this->db) as $row) { $assignments[$row['item_name']] = new Assignment([ 'userId' => $row['account_id'], 'roleName' => $row['item_name'], 'createdAt' => $row['created_at'], ]); } return $assignments; } /** * @inheritdoc */ public function assign($role, $accountId) { $accountId = Uuid::str2uuid($accountId); $assignment = new Assignment([ 'userId' => $accountId, 'roleName' => $role->name, 'createdAt' => time(), ]); $this->db->createCommand() ->insert($this->assignmentTable, [ 'account_id' => $assignment->userId, 'item_name' => $assignment->roleName, 'created_at' => $assignment->createdAt, ])->execute(); return $assignment; } /** * @inheritdoc */ public function revoke($role, $accountId) { $accountId = Uuid::str2uuid($accountId); if (empty($accountId)) { return false; } return $this->db->createCommand() ->delete($this->assignmentTable, ['account_id' => $accountId, 'item_name' => $role->name]) ->execute() > 0; } /** * @inheritdoc */ public function revokeAll($accountId) { $accountId = Uuid::str2uuid($accountId); if (empty($accountId)) { return false; } return $this->db->createCommand() ->delete($this->assignmentTable, ['account_id' => $accountId]) ->execute() > 0; } /** * @param int|null $type If null will return all auth items. * @param array $excludeItems Items that should be excluded from result array. * @return array */ public function getItems($type = null, $excludeItems = []) { $query = (new Query()) ->from($this->itemTable); if ($type !== null) { $query->where(['type' => $type]); } else { $query->orderBy('type'); } foreach ($excludeItems as $name) { $query->andWhere('name != :item', ['item' => $name]); } $items = []; foreach ($query->all($this->db) as $row) { $items[$row['name']] = $this->populateItem($row); } return $items; } /** * Returns both roles and permissions assigned to user. * * @param binary $accountId * @return array */ public function getItemsByUser($accountId) { $accountId = Uuid::str2uuid($accountId); if (empty($accountId)) { return []; } $query = (new Query)->select('b.*') ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable]) ->where('{{a}}.[[item_name]]={{b}}.[[name]]') ->andWhere(['a.account_id' => $accountId]); $roles = []; foreach ($query->all($this->db) as $row) { $roles[$row['name']] = $this->populateItem($row); } return $roles; } /** @inheritdoc */ public function getItem($name) { return parent::getItem($name); } }<file_sep><?php /* * This file is part of the Dektrium project. * * (c) Dektrium project <http://github.com/dektrium/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace wartron\yii2account\rbac; use wartron\yii2account\rbac\components\DbManager; use wartron\yii2account\rbac\components\ManagerInterface; use wartron\yii2account\Module as AccountModule; use yii\base\Application; use yii\base\BootstrapInterface; /** * Bootstrap class registers translations and needed application components. * @author <NAME> <<EMAIL>> */ class Bootstrap implements BootstrapInterface { /** @inheritdoc */ public function bootstrap($app) { // register translations if (!isset($app->get('i18n')->translations['rbac*'])) { $app->get('i18n')->translations['rbac*'] = [ 'class' => 'yii\i18n\PhpMessageSource', 'basePath' => __DIR__ . '/messages', ]; } if ($this->checkRbacModuleInstalled($app)) { // register auth manager if (!$this->checkAuthManagerConfigured($app)) { $app->set('authManager', [ 'class' => DbManager::className(), ]); } // // if wartron\yii2account/user extension is installed, copy admin list from there // if ($this->checkAccountModuleInstalled($app)) { // $app->getModule('rbac')->admins = $app->getModule('account')->admins; // } } } /** * Verifies that dektrium/yii2-rbac is installed and configured. * @param Application $app * @return bool */ protected function checkRbacModuleInstalled(Application $app) { return $app->hasModule('rbac') && $app->getModule('rbac') instanceof Module; } /** * Verifies that dektrium/yii2-user is installed and configured. * @param Application $app * @return bool */ protected function checkAccountModuleInstalled(Application $app) { return $app->hasModule('account') && $app->getModule('account') instanceof AccountModule; } /** * Verifies that authManager component is configured. * @param Application $app * @return bool */ protected function checkAuthManagerConfigured(Application $app) { return $app->authManager instanceof ManagerInterface; } } <file_sep><?php use yii\db\Migration; class m150823_001311_create_default_roles extends Migration { public function up() { $columns = ['name', 'type', 'description']; $this->batchInsert('{{%auth_item}}', $columns, [ [ 'admin', 1, 'Role Admin', ], [ 'backend', 1, 'Role Backend', ], [ 'user', 1, 'Role User', ], [ 'admin-rbac', 2, 'Can Manage RBAC', ], [ 'backend-accounts', 2, 'Can Manage Accounts', ], [ 'backend-accounts-confirm', 2, 'Can Confirm Accounts', ], [ 'backend-accounts-block', 2, 'Can Block Accounts', ], [ 'backend-accounts-delete', 2, 'Can Delete Accounts', ], [ 'backend-accounts-rbac', 2, 'Can Delete Accounts', ], [ 'backend-accounts-billing', 2, 'Can Manage Accounts Billing', ], ]); $columns = ['parent', 'child']; $this->batchInsert('{{%auth_item_child}}', $columns, [ [ 'admin', 'admin-rbac', ], [ 'admin', 'backend', ], [ 'admin', 'backend-accounts-delete', ], [ 'admin', 'backend-accounts-rbac', ], [ 'admin', 'backend-accounts-billing', ], [ 'backend', 'backend-accounts', ], [ 'backend', 'backend-accounts-confirm', ], [ 'backend', 'backend-accounts-block', ], ]); } public function down() { } }
b99ebefdaf182648cac9f20b52bc92db42a9eccf
[ "PHP" ]
3
PHP
wartron/yii2-account-rbac-uuid
3268fa4e96d37092b4e8c73bb5c7fa1196813220
71a78f695100c9735264b7243146eacf7ef413ee
refs/heads/master
<file_sep># money > Display and convert currency amount ## usd This is the default. The amount needs to be in cents (whole integer). ```js import { usd, fromUsd } from "@tridnguyen/money"; usd(2020); // $20.20 usd(145230); // $1,452.30 usd(-43674); // ($436.74) usd(); // $0.00 usd(10032, true); // 100.32 fromUsd(20.19); // 2019 fromUsd('$30.30'); // 3030 fromCents(2021); // 20.21 toCents(335.67); // 33567 ``` <file_sep>const money = require('./'); export const usd = money.usd; export const fromUsd = money.fromUsd;
803bea4b59eb041c01487b48e8194e482bc72e4b
[ "Markdown", "JavaScript" ]
2
Markdown
tnguyen14/money
789700e0a958362d84a9af5d32790e6cd2c4ac47
1bab8c227b31bca256a263f098d105fa5132b582
refs/heads/master
<repo_name>jeffchiucp/valoria<file_sep>/models/thing.js const mongoose = require('mongoose'); const { Schema } = mongoose; const ThingSchema = new Schema({ kind : String, content : {type : String, default : ''}, key : String, creator : {type : String, default : 'James'}, dimension : String }); const Thing = mongoose.model('Thing', ThingSchema); module.exports = Thing; <file_sep>/controllers/idea.js const Idea = require('../models/idea'); const Dimension = require('../models/dimension'); const fs = require('fs'); let defaultValoria; let defaultCode; fs.readFile('./defaults/valoria.txt', 'utf8', (err, content) => { defaultValoria = content; fs.readFile('./defaults/code.txt', 'utf8', (err, content) => { defaultCode = content; }) }) module.exports = (app) => { app.post('/dimension/:key/idea/:kind/save', (req, res, next) => { Dimension.findOne({key : req.params.key}).then((dimension) => { if(!dimension){ res.send({err : "Dimension does not exist!"}); }else{ Idea.findOne({kind : req.params.kind, dimension : req.params.key}).then((idea) => { if(!idea){ res.send({err : "Idea does not exist!"}); }else{ if( (!idea.isPrivate) || (idea.isPrivate && idea.editors.includes(req.user.username)) ){ idea.isPrivate = req.body.isPrivate; idea.content = req.body.content; idea.save().then((idea) => { res.send(idea); }) }else{ res.send({err : "You can't edit this idea"}); } } }) } }) }); app.post('/dimension/:key/idea/new', (req, res) => { Dimension.findOne({key : req.params.key}).then((dimension) => { if(!dimension){ res.send({err : "Dimension does not exist"}); }else{ Idea.findOne({key : req.body.kind, dimension : req.params.key}).then((idea) => { if(idea){ res.send({err : "Idea already exists"}); }else{ let newIdea = new Idea(); newIdea.kind = req.body.kind; newIdea.content = req.body.content; newIdea.dimension = req.params.key; newIdea.creator = req.user.username; newIdea.editors.push(req.user.username); dimension.ideas.push(req.body.kind); newIdea.save().then((newIdea) => { dimension.save().then(() => { res.send(newIdea); }) }) } }) } }) }) app.get('/dimension/:key/idea/:kind', (req, res) => { Idea.findOne({kind : req.params.kind, dimension : req.params.key}).then((idea) => { if(idea){ //Retrieve Default Code if shit hits the fan if(!idea.content){ if(idea.kind == 'valoria'){ idea.content = defaultValoria; }else if(idea.kind == 'code'){ idea.content = defaultCode; } idea.save(); } res.send(idea); }else{ res.send({err : "Idea does not exist in this dimension"}) } }) }) } <file_sep>/models/idea.js const mongoose = require('mongoose'); const { Schema } = mongoose; const IdeaSchema = new Schema({ kind : String, content : {type : String}, key : String, creator : {type : String, default : 'James'}, dimension : String, isPrivate : {type : Boolean, default : false}, editors : Array, }); const Idea = mongoose.model('Idea', IdeaSchema); module.exports = Idea; <file_sep>/models/dimension.js const mongoose = require('mongoose'); const { Schema } = mongoose; const DimensionSchema = new Schema({ key : String, creator : {type : String, default : 'James'}, background : {type : String, default : '../defaults/valoria-bg.gif'}, ideas : Array, things : Array, thingCount : {default : 0, type : Number}, content : {type : String, default : '{}'}, isPrivate : {type : Boolean, default : false}, editors : Array, defaultIdeas : Array, defaultThings : Array }); const Dimension = mongoose.model('Dimension', DimensionSchema); module.exports = Dimension; <file_sep>/controllers/thing.js const Thing = require('../models/thing'); const Idea = require('../models/idea'); const Dimension = require('../models/dimension'); module.exports = (app) => { app.post('/dimension/:key/thing/new', (req, res) => { Dimension.findOne({key : req.params.key}).then((dimension) => { if(!dimension){ res.send({err : "Dimension does not exist"}); }else{ let newThing = new Thing(); newThing.kind = req.body.kind; newThing.content = JSON.stringify(req.body.content); newThing.key = req.body.kind + dimension.thingCount; newThing.creator = req.user.username; newThing.dimension = dimension.key; newThing.save().then((newThing) => { dimension.things.push(newThing.key); dimension.thingCount += 1; dimension.save().then((dimension) => { res.send(newThing); }) }) } }) }) app.get('/dimension/:key/thing/:thingKey', (req, res) => { Dimension.findOne({key : req.params.key}).then((dimension) => { if(!dimension){ res.send({err : "Dimension does not exist"}); }else{ Thing.findOne({dimension : req.params.key, key : req.params.thingKey}).then((thing) => { if(!thing && req.params.thingKey == 'code0'){ let codeThing = new Thing(); codeThing.kind = 'code'; codeThing.key = 'code0'; codeThing.creator = 'james'; codeThing.dimension = 'valoria'; codeThing.save().then((codeThing) => { dimension.things.push(codeThing.key); dimension.save().then(() => { res.send(codeThing) }) }) }else if(!thing){ res.send({err : "Thing does not exist"}) }else{ res.send(thing); } }) } }) }) //Saving content to a thing app.post('/dimension/:key/thing/:thingKey/save', (req, res) => { Dimension.findOne({key : req.params.key}).then((dimension) => { if(!dimension){ res.send({err : "Dimension does not exist!"}); }else{ Thing.findOne({dimension : req.params.key, key : req.params.thingKey}).then((thing) => { if(!thing){ res.send({err : "Thing does not exist!"}); }else{ thing.content = JSON.stringify(req.body.content); thing.save().then((thing) => { res.send(thing); }); } }) } }) }); app.post('/dimension/:key/thing/:thingKey/delete', (req, res) => { Dimension.findOneAndDelete({key : req.params.key}).then((dimension) => { if(!dimension){ res.send({err : "Dimension does not exist!"}) }else{ Thing.findOne({key : req.params.thingKey, dimension : req.params.dimension}).then((thing) => { if(!thing){ res.send({err : "Thing does not exist!"}); }else{ res.send("Deleted the thing"); } }); } }); }); } <file_sep>/client/components/dimension/dimension.js function loadDimension(){ axios.get('/user/current_dimension').then((dimensionRes) => { eval(dimensionRes.data.content); }) } $(document).ready(() => { loadDimension(); }); <file_sep>/controllers/user.js const User = require('../models/user'); const Dimension = require('../models/dimension'); const jwt = require('jsonwebtoken'); const fs = require('fs'); let defaultDimension; fs.readFile('./defaults/dimension.txt', 'utf8', (err, content) => { defaultDimension = content; }); module.exports = (app) => { app.post('/register', (req, res) => { User.findOne({username : req.body.username.toLowerCase()}).then((user) => { if(user){ res.send({err : "User Already Exists"}); }else{ let newUser = new User; newUser.username = req.body.username.toLowerCase(); newUser.password = <PASSWORD>(req.body.password); newUser.save((err, user) => { // generate a JWT for this user from the user's id and the secret key let userData = { id: user._id, username : user.username, currentDimension : user.currentDimension } let token = jwt.sign(userData, process.env.JWT_SECRET, { expiresIn: "60 days"}); res.cookie('userToken', token); res.redirect('/') }); } }) }); app.post('/login', (req, res) => { User.findOne({username : req.body.username.toLowerCase()}).then((user) => { if(!user){ res.send({err : "Username does not exist" }); } else if(!user.validPassword(req.body.password)){ res.send({err : "Incorrect Password" }); }else{ // generate a JWT for this user from the user's id and the secret key let userData = { id: user._id, username : user.username, currentDimension : user.currentDimension } let token = jwt.sign(userData, process.env.JWT_SECRET, { expiresIn: "60 days"}); res.cookie('userToken', token); res.redirect('/') } }) }); app.get('/logout', (req, res) => { res.clearCookie('userToken'); res.send(); }) app.get('/user/current_dimension', (req, res) => { User.findOne({ _id : req.user.id, current_dimension : req.user.current_dimension }).then((user) => { if(!user){ res.send({err : "You can't load this dimension"}); }else{ Dimension.findOne({key : req.user.currentDimension}).then((dimension) => { if(!dimension){ res.send({err : "Dimension not found"}); }else{ if(!dimension.content && dimension.key == 'valoria'){ dimension.content = defaultDimension; dimension.save(); } res.send(dimension); } }) } }) }) }
52afa0842f126dba42dfcb1fa461019938b5a8b2
[ "JavaScript" ]
7
JavaScript
jeffchiucp/valoria
52a363dd04254ba0184da2ad72978e12dd729f48
3716340a605c26852ec8b6475354d93c306539f2
refs/heads/master
<file_sep># DragAndDrop_card карты <file_sep> // Поворот карты по двойному клику $('.card-block').dblclick( function() { if($(this).find('.card').hasClass('flip')) { $(this).find('.card').removeClass('flip') } else { $(this).find('.card').addClass('flip') } }) // Поворот карты по ховеру // $('.card-block').hover( function() { // $(this).find('.card').addClass('flip') // }, // function() { // $(this).find('.card').removeClass('flip') // }) $(function() { $('.draggable').draggable(); });
ac4d8fdc00822d216bcfcf07c124fbc4c8e5458a
[ "Markdown", "JavaScript" ]
2
Markdown
ruslandesign33/DragAndDrop_card
80490d56d572f7ffa0a17f8525c5eba3aa49b2c0
9c56cc8d127b1b68f9826fb42da4cea1f82edc0b
refs/heads/master
<file_sep>import sys import numpy as np import pylab as plt from astropy.table import Table from astropy.io import fits from matplotlib import gridspec import camb from camb import model, initialpower # author M.Lembo (using pythoncamb) # argv1=betaV_squared, argv2=betaE_squared # Values used in the paper # betaV_squared = 3.15e-2 # betaE_squared = 0.140 betaV_squared = float(sys.argv[1]) betaE_squared = float(sys.argv[2]) directory = '/Users/mac/Desktop/CircularPolarisation-project/plots/GFEmodified-spectra'# 'path_of_your_directory' Want_fig = False # if False no fig. are produced. twopi = 2.0 * np.pi fourpi = 4.0 * np.pi # this correspond to lmax=2000, this value can be change. The max value is 3987. lmax_v = 1999 lmax_e_b = 1999 tau = 0.05905 pars = camb.read_ini('/Users/mac/Documents/Work-University/Codes/camb-puliti/CAMB-0.1.7/params.ini') pars.Reion.Reionization = True results = camb.get_results(pars) powers = results.get_cmb_power_spectra(pars, CMB_unit='muK') cl_tilde_R = powers['unlensed_total'] tildedle_R = cl_tilde_R[2:, 1] tildedlb_R = cl_tilde_R[2:, 2] tildedlte_R = cl_tilde_R[2:, 3] pars.Reion.Reionization = False results = camb.get_results(pars) powers = results.get_cmb_power_spectra(pars, CMB_unit='muK') cl_tilde = powers['unlensed_total'] tildedle = cl_tilde[2:, 1] * np.exp(-2.0 * tau) tildedlb = cl_tilde[2:, 2] * np.exp(-2.0 * tau) tildedlte = cl_tilde[2:, 3] * np.exp(-2.0 * tau) lmax = len(tildedle) sR_e = tildedle_R - tildedle sR_b = tildedlb_R - tildedlb sR_te = tildedlte_R - tildedlte prefac = twopi / (np.arange(2, lmax + 1) * np.arange(3, lmax + 2)) prefac_p1 = twopi / (np.arange(3, lmax + 2) * np.arange(4, lmax + 3)) prefac_m1 = twopi / (np.arange(1, lmax) * np.arange(2, lmax + 1)) prefac_p2 = twopi / (np.arange(4, lmax + 3) * np.arange(5, lmax + 4)) prefac_m2 = twopi / (np.arange(2, lmax) * np.arange(1, lmax - 1)) prefac_m2 = np.insert(prefac_m2, 0, 0) tildedle_p1 = tildedle[1:] tildedle_m1 = np.insert(tildedle, 0, 0) tildedlb_p1 = tildedlb[1:] tildedlb_m1 = np.insert(tildedlb, 0, 0) tildedlb_p2 = tildedlb[2:] tildedlb_m2 = np.insert(tildedlb, 0, 0) tildedlb_m2 = np.insert(tildedlb_m2, 0, 0) fw3j_ee_bb = np.loadtxt('%s/fw3j_ee_bb.txt' % directory, unpack=True) K11 = fw3j_ee_bb[0] K22p1 = fw3j_ee_bb[1] K22p1 = K22p1[1:] K22m1 = fw3j_ee_bb[2] fw3j_vv = np.loadtxt('%s/fw3j_vv.txt' % directory, unpack=True) K44 = fw3j_vv[0] K33p1 = fw3j_vv[1] K33p1 = K33p1[1:] K33m1 = fw3j_vv[2] K44p2 = fw3j_vv[3] K44p2 = K44p2[2:] K44m2 = fw3j_vv[4] cle = prefac[:lmax_e_b] * tildedle[:lmax_e_b] - \ 1.0 / fourpi * (betaV_squared + betaE_squared) * prefac[:lmax_e_b] * tildedle[:lmax_e_b] + \ 1.0 / fourpi * betaV_squared * (K11[:lmax_e_b] * prefac[:lmax_e_b] * tildedle[:lmax_e_b] + K22p1[:lmax_e_b] * prefac_p1[:lmax_e_b] * tildedlb_p1[:lmax_e_b] + K22m1[:lmax_e_b] * prefac_m1[:lmax_e_b] * tildedlb_m1[:lmax_e_b]) clb = prefac[:lmax_e_b] * tildedlb[:lmax_e_b] - \ 1.0 / fourpi * (betaV_squared + betaE_squared) * prefac[:lmax_e_b] * tildedlb[:lmax_e_b] + \ 1.0 / fourpi * betaV_squared * (K11[:lmax_e_b] * prefac[:lmax_e_b] * tildedlb[:lmax_e_b] + K22p1[:lmax_e_b] * prefac_p1[:lmax_e_b] * tildedle_p1[:lmax_e_b] + K22m1[:lmax_e_b] * prefac_m1[:lmax_e_b] * tildedle_m1[:lmax_e_b]) clte = prefac[:lmax_e_b] * tildedlte[:lmax_e_b] - \ 0.5 / fourpi * (betaV_squared + betaE_squared) * prefac[:lmax_e_b] * tildedlte[:lmax_e_b] clv = 1 / np.pi * betaE_squared * ( K44[:lmax_v] * prefac[:lmax_v] * tildedlb[:lmax_v] + K44p2[:lmax_v] * prefac_p2[:lmax_v] * tildedlb_p2[:lmax_v] + K44m2[:lmax_v] * prefac_m2[:lmax_v] * tildedlb_m2[:lmax_v] + K33p1[:lmax_v] * prefac_p1[:lmax_v] * tildedle_p1[:lmax_v] + K33m1[:lmax_v] * prefac_m1[:lmax_v] * tildedle_m1[:lmax_v]) dle = cle * (np.arange(2, lmax_e_b + 2) * np.arange(3, lmax_e_b + 3) / twopi) + sR_e[:len(cle)] dlb = clb * (np.arange(2, lmax_e_b + 2) * np.arange(3, lmax_e_b + 3) / twopi) + sR_b[:len(clb)] dlte = clte * (np.arange(2, lmax_e_b + 2) * np.arange(3, lmax_e_b + 3) / twopi) + sR_te[:len(clte)] dlv = clv * (np.arange(2, lmax_v + 2) * np.arange(3, lmax_v + 3) / twopi) ell = np.arange(2, lmax_e_b + 2) # SR_X: We only rotate the polarization at the last scattering. # So we are adding the reionization part of the spectra unchanged "a posteriori". spectra = Table([ell, dle, dlb, dlte, dlv], names=("ell", "EE", "BB", "TE", "VV")) spectra.write("%s/spectra_lmax%s.fits" % (directory, len(ell)+1), format="fits") if Want_fig == True: fig = plt.figure() plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) gs = gridspec.GridSpec(2, 1, height_ratios=[2.15, 0.95]) spectrum = plt.subplot(gs[0]) spectrum.loglog(ell, dlv, c='none', lw='2', label=' ') spectrum.loglog(ell, dlv, c='tab:red', lw='2', label=r'$VV$') spectrum.loglog(ell, abs(dlte), c='tab:green', lw='2', label=r'$TE$') spectrum.loglog(ell, abs(tildedlte_R[:lmax_e_b]), c='tab:green', lw='2', ls='--', label=r'$\widetilde{TE}$') spectrum.loglog(ell, dlb, c='tab:orange', lw='2', label=r'$BB$') spectrum.loglog(ell, tildedlb_R[:lmax_e_b], c='tab:orange', lw='2', ls='--', label=r'$\widetilde{BB}$') spectrum.loglog(ell, dle, c='tab:blue', lw='2', label=r'$EE$') spectrum.loglog(ell, tildedle_R[:lmax_e_b], c='tab:blue', lw='2', ls='--', label=r'$\widetilde{EE}$') residual = plt.subplot(gs[1], sharex=spectrum) residual.loglog(ell, abs(dlte - tildedlte_R[:lmax_e_b]), c='tab:green', lw='2', label=r'$TE$') residual.loglog(ell, abs(dle - tildedle_R[:lmax_e_b]), c='tab:blue', lw='2', label=r'$EE$') plt.setp(spectrum.get_xticklabels(), visible=False) leg1 = spectrum.legend(loc='lower right', ncol=4, fontsize=12) leg2 = residual.legend(loc='lower right', ncol=2, fontsize=12) leg1.get_frame().set_linewidth(0.0) leg2.get_frame().set_linewidth(0.0) spectrum.set_ylabel(r'$\mathcal{D}_\ell\;[\mu K^2]$', fontsize=18, labelpad=10) residual.set_ylabel(r'$\Delta \mathcal{D}_\ell\;[\mu K^2]$', fontsize=18, labelpad=10) residual.set_xlabel(r'Multipole - $\ell$', fontsize=18) spectrum.tick_params('y', labelrotation=90) spectrum.set_ylim(2e-8, 3e2) residual.set_ylim(2e-8, 7e1) residual.tick_params('y', labelrotation=90) plt.subplots_adjust(left=0.12, right=0.98, top=0.98, bottom=0.12, hspace=.0) plt.yticks(va="center") plt.savefig('%s/spettri.pdf' % directory, bbox_inches='tight', quality=100, format='pdf') plt.show()
5149ba86ddb0752bc709c450d04970c5d4f8dfb8
[ "Python" ]
1
Python
mlembo00/circular-polarization
4b2d607cb9606bd6a169b16b0db84c7a04b767a2
2dc343efaa84bfc819499f796492d372c53a3ad9
refs/heads/master
<repo_name>indigos33k3r/Jabba<file_sep>/src/formats/QuickReplies.ts export interface IQuickRepliesButtonJson { title: string; value: string; } export interface IQuickRepliesJson { type: string; content: { title: string; buttons: IQuickRepliesButtonJson[]; }; } export class QuickReplies { private title: string; private buttons: IQuickRepliesButtonJson[]; constructor(title: string) { this.title = title; this.buttons = []; } public setTitle(title: string): QuickReplies { this.title = title; return this; } public addButton(title: string, optValue?: string): QuickReplies { const value = optValue ? optValue : title; this.buttons.push({ title, value, }); return this; } public toJson(): IQuickRepliesJson { return { type: 'quickReplies', content: { title: this.title, buttons: this.buttons, }, }; } } <file_sep>/src/middlewares/index.ts export { answerFloatingFromCsv } from './wordingFromCsv'; export { converseApiCall } from './botBuilder'; export { notUnderstood } from './notUnderstood'; <file_sep>/src/middlewares/wordingFromCsv.ts import * as fs from 'fs'; import { ChatbotMiddleware, ChatbotMiddlewareNext, IChatbotContext } from '../Chatbot'; export const answerFloatingFromCsv = async (path: string): Promise<ChatbotMiddleware> => { const wording: string[][] = await loadCsvFile(path); return async (ctx: IChatbotContext, next: ChatbotMiddlewareNext): Promise<any> => { if (!ctx.conversation) { return next(); } const intent = ctx.conversation.intents[0]; if (!intent) { return next(); } for (const line of wording) { if (line[0] === intent.slug) { await ctx.message.reply([{ type: 'text', content: line[1] }]); return; } } next(); }; }; const loadCsvFile = ( path: string, opts?: { delimiter?: string } ): Promise<string[][]> => { return new Promise((resolve, reject) => { fs.readFile(path, 'utf-8', (err: NodeJS.ErrnoException, data: string) => { if (err) { return reject(err); } const delimiter: string = opts && opts.delimiter ? opts.delimiter[0] : ';'; const nonEscapedDelimiter: RegExp = new RegExp( `(?:"(?:\\.|[^"])*"|\\.|[^${delimiter}])+`, 'g' ); const lines: string[][] = data .toString() .split(/\n|\r/g) .filter((line: string) => line.length > 0) .map( (line: string) => line.replace(/^"|"$/g, '').match(nonEscapedDelimiter) || [] ); resolve(lines); }); }); }; <file_sep>/src/formats/index.ts export { ICarousselleButtonJson, ICarousselleCardJson, ICarousselleJson, CarousselleCard, Carousselle, } from './Carousselle'; export { IQuickRepliesJson, IQuickRepliesButtonJson, QuickReplies } from './QuickReplies'; export { IBotConnectorFormat } from './BotConnectorFormat'; <file_sep>/src/Chatbot.ts import * as bodyParser from 'body-parser'; import * as express from 'express'; import * as mongoose from 'mongoose'; import * as recastai from 'recastai'; import Client from 'recastai'; import { Session } from './Session.model'; export interface IRecastConfig { requestToken: string; connectToken?: string; } export interface IRecastSdk { request: recastai.Request; connect: recastai.Connect; } export interface IMongoConfig { hostname: string; database: string; username?: string; password?: string; ssl?: boolean; replicaSetName?: string; port?: string; enabled?: boolean; } export interface IChatbotConfig extends IRecastConfig { language: 'fr' | 'en'; mongo?: IMongoConfig; } export interface IChatbotContext { recastSdk: IRecastSdk; config: IChatbotConfig; message: recastai.Message; conversation?: recastai.Conversation; session?: Session; } export type ChatbotMiddlewareNext = () => Promise<void>; export type ChatbotMiddleware = ( ctx: IChatbotContext, next?: ChatbotMiddlewareNext ) => Promise<any>; export default class Chatbot { config: IChatbotConfig; recastSdk: IRecastSdk; httpServer: express.Express; middlewarePipeline: ChatbotMiddleware[]; constructor(config: IChatbotConfig) { this.config = config; this.middlewarePipeline = []; if (config.connectToken) { this.recastSdk = { connect: new Client(config.connectToken, config.language).connect, request: new Client(config.requestToken, config.language).request, }; } else { const instance = new Client(config.requestToken, config.language); this.recastSdk = { connect: instance.connect, request: instance.request, }; } this.httpServer = express(); this.httpServer.use(bodyParser.json()); this.httpServer.post('/', (req, res) => this.recastSdk.connect.handleMessage(req, res, this.onMessage.bind(this)) ); // typescripts import are read-only by default (mongoose as any).Promise = global.Promise; if (this.config.mongo) { this.config.mongo.enabled = true; this.connectToMongo(this.config.mongo); } } public listen(port: number): Promise<{}> { return new Promise((resolve, reject) => { this.httpServer.listen(port, (err: any) => { if (err) { return reject(err); } resolve(); }); }); } public use(middleware: ChatbotMiddleware): Chatbot { this.middlewarePipeline.push(middleware); return this; } public connectToMongo(config: IMongoConfig): mongoose.MongooseThenable { this.config.mongo = config; this.config.mongo.enabled = true; let auth: string = ''; if (config.username) { auth = `${config.username}:${config.password}@`; } let connectionString = `mongodb://${auth}${config.hostname}:${config.port}/${config.database}?ssl=${config.ssl}`; if (config.replicaSetName) { connectionString += `&replicaSet=${config.replicaSetName}` } return mongoose.connect( connectionString, { useMongoClient: true } ); } public isMongoEnabled(): boolean { return this.config.mongo && this.config.mongo.enabled ? true : false; } public async botHostingEntrypoint( body: { message: string; text: string }, response: object, callback: (err: any, data?: any) => void ) { try { if (body.message) { this.recastSdk.connect.handleMessage( { body }, response, this.onMessage.bind(this) ); callback(null, { result: 'Bot answered :)' }); } else if (body.text) { const res: recastai.Conversation = await this.recastSdk.request.converseText( body.text, { conversationToken: this.config.requestToken, } ); if (res && res.reply()) { callback(null, { reply: res.reply(), conversationToken: res.conversationToken, }); } else { callback(null, { reply: 'No reply :(', conversationToken: res.conversationToken, }); } } else { callback('No text provided'); } } catch (err) { callback(err); } } private onMessage(message: recastai.Message): Promise<any> { const ctx: IChatbotContext = { message, recastSdk: this.recastSdk, config: this.config, }; let currentMiddlewareIndex: number = 0; const execNextMiddleware = (): Promise<any> => { const m = this.middlewarePipeline[currentMiddlewareIndex]; if (m) { currentMiddlewareIndex++; return m(ctx, execNextMiddleware); } else { return Promise.resolve(); } }; if (this.isMongoEnabled() === true) { return Session.findOrCreateById(message.conversationId).then((session: Session) => { ctx.session = session; ctx.session._previousNotUnderstand = ctx.session.consecutiveNotUnderstand; ctx.session.consecutiveNotUnderstand = 0; session.messageCount++; return session.save().then(() => execNextMiddleware()); }); } return execNextMiddleware(); } } <file_sep>/src/index.ts import Chatbot, { ChatbotMiddleware, ChatbotMiddlewareNext, IChatbotConfig, IChatbotContext, IRecastConfig, IRecastSdk, } from './Chatbot'; import * as formats from './formats'; import * as middlewares from './middlewares'; import { Session } from './Session.model'; import Wording from './Wording'; export { Chatbot, middlewares, formats, Session, Wording }; <file_sep>/README.md **==================================** **This project is under heavy development** **==================================** **Use at you own risks** **==================================** Jabba stands for "Javascript Awesome Bot Building Apparatus" **==================================** WARNING : run `npm run build` to generate the `lib` folder before publishing on npm **==================================** <file_sep>/src/middlewares/notUnderstood.ts import { ChatbotMiddleware, ChatbotMiddlewareNext, IChatbotContext } from '../Chatbot'; export const notUnderstood = (messages: string[3]): ChatbotMiddleware => { return async (ctx: IChatbotContext, next: ChatbotMiddlewareNext): Promise<any> => { if (ctx.config.mongo && ctx.config.mongo.enabled === true && ctx.session) { ctx.session.consecutiveNotUnderstand = ctx.session._previousNotUnderstand + 1; const count: number = Math.min(ctx.session._previousNotUnderstand, 2); await ctx.session.save(); await ctx.message.reply([{ type: 'text', content: messages[count] }]); return next(); } await ctx.message.reply([{ type: 'text', content: messages[0] }]); return next(); }; }; <file_sep>/src/formats/Carousselle.ts export interface ICarousselleButtonJson { title: string; value: string; type: string; } export interface ICarousselleCardJson { title: string; subtitle: string; imageUrl: string; buttons: ICarousselleButtonJson[]; } export interface ICarousselleJson { type: string; content: ICarousselleCardJson[]; } export class CarousselleCard { private title: string; private subtitle: string; private imageUrl: string; private buttons: ICarousselleButtonJson[]; constructor(title: string, subtitle: string, imageUrl: string) { this.title = title; this.subtitle = subtitle; this.imageUrl = imageUrl; this.buttons = []; } public addPostbackButton(title: string, optValue?: string): CarousselleCard { const value = optValue ? optValue : title; this.buttons.push({ title, value, type: 'postback', }); return this; } public toJson(): ICarousselleCardJson { return { title: this.title, subtitle: this.subtitle, imageUrl: this.imageUrl, buttons: this.buttons, }; } } export class Carousselle { private cards: CarousselleCard[]; constructor() { this.cards = []; } public addCard(card: CarousselleCard): Carousselle { this.cards.push(card); return this; } public toJson(): ICarousselleJson { return { type: 'carouselle', content: this.cards.map(c => c.toJson()), }; } } <file_sep>/src/middlewares/botBuilder.ts import { ChatbotMiddleware, ChatbotMiddlewareNext, IChatbotContext } from '../Chatbot'; export const converseApiCall = (): ChatbotMiddleware => { return async (ctx: IChatbotContext, next: ChatbotMiddlewareNext) => { ctx.conversation = await ctx.recastSdk.request.converseText(ctx.message.content, { conversationToken: ctx.message.senderId, language: ctx.config.language, }); return next(); }; }; <file_sep>/src/Session.model.ts import * as mongoose from 'mongoose'; export interface ISessionModel { conversationId: string; consecutiveNotUnderstand: number; createdAt: Date; updatedAt: Date; memory: object; messageCount: number; } export interface ISessionDocument extends ISessionModel, mongoose.Document {} const sessionSchema = new mongoose.Schema({ conversationId: { type: String, required: true, }, createdAt: { type: Date, required: false, }, updatedAt: { type: Date, required: false, }, consecutiveNotUnderstand: { type: Number, default: 0, required: false, }, memory: { type: Object, default: {}, }, messageCount: { type: Number, default: 0, }, }); sessionSchema.index({ conversationId: 1 }); sessionSchema.pre('save', next => { if (this._doc) { const doc = this._doc as ISessionModel; const now = new Date(); if (!doc.createdAt) { doc.createdAt = now; } doc.updatedAt = now; } next(); }); export const SessionModel = mongoose.model('Session', sessionSchema); export class Session { public _previousNotUnderstand: number; public static create(conversationId: string): Promise<Session> { const instance: ISessionModel = { conversationId, consecutiveNotUnderstand: 0, messageCount: 0, createdAt: new Date(), updatedAt: new Date(), memory: {}, }; return SessionModel.create(instance).then( (res: mongoose.Document) => new Session(res as ISessionDocument) ); } public static findById(conversationId: string): Promise<Session> { return SessionModel.findOne({ conversationId }).then((res: mongoose.Document) => { if (!res) { return Promise.reject(`Sersation with id ${conversationId} not found.`); } return Promise.resolve(new Session(res as ISessionDocument)); }); } public static findOrCreateById(conversationId: string): Promise<Session> { return SessionModel.findOne({ conversationId }).then((res: mongoose.Document) => { if (!res) { return this.create(conversationId); } return Promise.resolve(new Session(res as ISessionDocument)); }); } private document: ISessionDocument; constructor(model: ISessionDocument) { this._previousNotUnderstand = 0; this.document = model; } get conversationId(): string { return this.document.conversationId; } get memory(): object { return this.document.memory; } get consecutiveNotUnderstand(): number { return this.document.consecutiveNotUnderstand; } set consecutiveNotUnderstand(n: number) { this.document.consecutiveNotUnderstand = Math.min(n, 2); } get messageCount(): number { return this.document.messageCount; } set messageCount(n: number) { this.document.messageCount = n; } public save(): Promise<Session> { this.document.markModified('memory'); return this.document.save().then(() => this); } public reset(): Promise<Session> { this.document.consecutiveNotUnderstand = 0; this.document.messageCount = 0; this.document.memory = {}; return this.save(); } } <file_sep>/src/Wording.ts /* ** This module helps reading a json wording file and templating it */ import { readFile, readFileSync } from "fs"; import { shuffle } from "lodash"; export type StringMap = { [key: string]: string[] }; export type WordingFile = { [key: string]: StringMap[][] }; function checkWordingFile(file: any): Error | null { for (const key in file) { if (typeof key !== "string") { return new Error(`Invalid wording key: ${key}. Keys must be a string.`); } if (!(file[key] instanceof Array)) { return new Error(`Invalid value for key ${key}: Value must be an array`); } for (const value of file[key]) { if (!(value instanceof Array)) { return new Error( `Invalid entry ${value} for key ${key}: Value must be an array of messages` ); } } } return null; } export default class Wording { public dictionnary: WordingFile; constructor(dictionnary: WordingFile) { this.dictionnary = dictionnary; } // public execTemplate(template: string[]): IMessage[] { // return template.map(line => shuffle(line.split('$$'))[0]).map(elem => { // } public get(key: string): StringMap[] { if (!this.dictionnary[key] || this.dictionnary[key].length === 0) { throw new Error(`Could not find wording for key "${key}"`); } return shuffle(this.dictionnary[key])[0]; } static fromFile(path: string): Promise<Wording> { return new Promise((resolve, reject) => { readFile(path, (err: NodeJS.ErrnoException, content: Buffer) => { if (err) return reject( `Wording#loadFromFile error while reading file: ${err}` ); const json: any = JSON.parse(content.toString()); const invalidFileError: Error | null = checkWordingFile(json); if (!invalidFileError) return resolve(new Wording(json as WordingFile)); return reject(invalidFileError); }); }); } static fromFileSync(path: string): Wording { const content: Buffer = readFileSync(path); const json: any = JSON.parse(content.toString()); const invalidFileError: Error | null = checkWordingFile(json); if (invalidFileError) throw invalidFileError; return new Wording(json as WordingFile); } static fromJson(json: any): Wording { const invalidFileError: Error | null = checkWordingFile(json); if (!invalidFileError) return new Wording(json as WordingFile); throw invalidFileError; } } <file_sep>/src/formats/BotConnectorFormat.ts import { ICarousselleJson } from './Carousselle'; import { IQuickRepliesJson } from './QuickReplies'; export interface IBotConnectorFormat { toJson(): ICarousselleJson | IQuickRepliesJson; }
eb4454ef2e0760d8150acbda74d82b7a2d43406a
[ "Markdown", "TypeScript" ]
13
TypeScript
indigos33k3r/Jabba
7bf13d2869edf0fff9f6e35365cf384baa170e9f
bd3602469e713ffe1b1041747d3c4b0aeed3bc2d
refs/heads/main
<file_sep>import React, { Fragment, useEffect } from 'react' import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { getProjectById } from '../../actions/projeto' import Spinner from '../layouts/Spinner'; import { Link } from 'react-router-dom'; import Moment from 'react-moment'; const Projeto = ({ getProjectById, auth, projeto:{ projeto, loading }, match }) => { useEffect(() => { getProjectById(match.params.id); }, [getProjectById, match.params.id]); return ( <Fragment> { projeto === null || loading === true ? <Spinner/> : <Fragment> <h3 class="text-dark">{projeto.nome}</h3> <p> </p> <p><strong>Protocolo: </strong>{projeto.protocolo}</p> <p><strong>Tipo: </strong>{projeto.tipo.nome}</p> <p><strong>Data: </strong><Moment format='YYYY/MM/DD'>{projeto.created_at}</Moment></p> <br/> <p><strong>Descricao: </strong><br />{projeto.descricao}</p> <br/> <p><strong>Status: </strong>{ projeto.aprovado === null ? 'Pendente' : 'Finalizado' }</p> <p><strong>Aprovado: </strong>{ projeto.aprovado === null ? 'Projeto em votação' : (projeto.aprovado ? 'Sim' : 'Não') }</p> <p><strong>Total de votos: </strong>{projeto.total_votos}</p> <p><strong>Relator: </strong><Link to={`/politico/${projeto.relator.politico_id}`}>{projeto.relator.nome}</Link></p> </Fragment> } </Fragment> ) } Projeto.propTypes = { auth: PropTypes.object.isRequired, projeto: PropTypes.func.isRequired, getProjectById:PropTypes.func.isRequired } const mapStateToProps = state =>({ auth:state.auth, projeto:state.projeto }) export default connect( mapStateToProps, { getProjectById } )(Projeto) <file_sep>import React, { Fragment, useState } from 'react' import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Spinner from '../layouts/Spinner'; import { searchProjetos } from '../../actions/projeto'; import ProjetoItem from './ProjetoItem'; const Projetos = ({ searchProjetos, projeto:{ projetos, loading } }) => { const [formData, setFormData] = useState({ param:'', }) const {param} = formData; const onChange = e => { setFormData({ ...formData, [e.target.name]: e.target.value }) setTimeout(() => { searchProjetos(e.target.value); }, 500) } return ( <Fragment> { loading ? <Spinner/> : <Fragment> <h1 className="large text-primary">Projetos</h1> <p className="lead"> <i className="fas fa-search"></i>{' '}Faça sua pesquisa </p> <form className="form"> <div className="form-group"> <input value={param} onChange={e => onChange(e)} type="text" placeholder="* School or Bootcamp" name="param"/> </div> </form> <div className="profiles"> { projetos.length > 0 ? ( projetos.map(projeto => ( <ProjetoItem key={projeto.id} projeto={projeto}/> )) ) : <h4>Não foram encontrados projetos. Digite acima para pesquisar.</h4>} </div> </Fragment> } </Fragment> ) } Projetos.propTypes = { searchProjetos: PropTypes.func.isRequired, projeto: PropTypes.object.isRequired } const mapStateToProps = state =>({ projeto: state.projeto }) export default connect( mapStateToProps, { searchProjetos } )(Projetos) <file_sep>import React, { Fragment, useEffect } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { getPoliticoById } from '../../actions/politico'; import Spinner from '../layouts/Spinner'; import { Link } from 'react-router-dom'; import PoliticoTop from './PoliticoTop'; import PoliticoAbout from './PoliticoAbout'; import PoliticoMandatoProjeto from './PoliticoMandatoProjeto'; const PoliticoProfile = ({ getPoliticoById, auth, politico:{ politico, loading }, match }) => { useEffect(() => { getPoliticoById(match.params.id); // match.params is a react variable to take the parameter passed by the url with that name }, [getPoliticoById, match.params.id]); return ( <Fragment> { politico === null || loading === true ? <Spinner/> : <Fragment> <Link to="/politicos" className="btn btn-light">Voltar</Link> <div className="profile-grid my-1"> <PoliticoTop politico={politico} /> <PoliticoAbout politico={politico} /> { politico.mandatos.length > 0 ? ( politico.mandatos.map(mandato => ( mandato.projetos !== null && mandato.projetos.length > 0 ? ( <div className="profile-exp bg-white p-2"> <h2 className="text-primary">Projetos</h2> { mandato.projetos.map(projeto => ( <PoliticoMandatoProjeto projeto={projeto}/> )) } </div> ) : (<div className="profile-exp bg-white p-2"> <h4>Nao foram encontrados projetos nesse</h4> </div>) ) ) ) : (<div className="profile-exp bg-white p-2"> <h4>Nao foram encontrados projetos</h4> </div>) } </div> </Fragment> } </Fragment> ) } PoliticoProfile.propTypes = { getPoliticoById:PropTypes.func.isRequired, auth: PropTypes.object.isRequired, politico: PropTypes.object.isRequired } const mapStateToProps = state =>({ auth: state.auth, politico: state.politico }) export default connect( mapStateToProps, { getPoliticoById } )(PoliticoProfile) <file_sep>import Axios from 'axios'; import { SEARCHING_PROJETOS, SEARCH_PROJETOS, PROJETOS_ERROR, GET_PROJETO, PROJETO_ERROR, CLEAR_PROJETOS, GET_POLITICO } from './types'; export const searchProjetos = param => async dispatch => { try{ dispatch({ type:SEARCHING_PROJETOS, payload:null }) const res = await Axios.get(`/api/projeto/search?param=${param}`); dispatch({ type:SEARCH_PROJETOS, payload: res.data }) }catch(err){ dispatch({ type: PROJETOS_ERROR, payload:{ msg: err.response.data.error, status: err.response.status } }); dispatch({ type: CLEAR_PROJETOS, payload:null }); } } export const getProjectById = id => async dispatch => { try{ dispatch({ type:SEARCHING_PROJETOS, payload:null }) const res = await Axios.get(`/api/projeto/${id}/get`); dispatch({ type:GET_PROJETO, payload:res.data }) }catch(err){ dispatch({ type: PROJETOS_ERROR, payload:{ msg: err.response.data.error, status: err.response.status } }); dispatch({ type: CLEAR_PROJETOS, payload:null }); } }<file_sep>import { SEARCHING_POLITICOS, SEARCH_POLITICOS, GET_POLITICO, POLITICOS_ERROR, POLITICO_ERROR, CLEAR_POLITICOS } from '../actions/types'; const initial_state = { politico:null, politicos:[], loading: false, error:{} } export default function(state = initial_state, action){ const { type, payload } = action switch(type){ case SEARCHING_POLITICOS: return{ ...state, loading:true } case SEARCH_POLITICOS: return{ ...state, politicos: payload, loading:false } case GET_POLITICO: return{ ...state, politico: payload, loading: false } case POLITICOS_ERROR: case POLITICO_ERROR: return{ ...state, loading:false, error:payload, } case CLEAR_POLITICOS: return{ ...state, politico:null, politicos:[], loading:false } default: return state; } }<file_sep>import {v4 as uuid} from "uuid"; import { SET_ALERT, REMOVE_ALERT } from './types' export const setAlert = (msg, alert_type, timeout = 5000) => dispatch => { const id = uuid(); // random long string // this the action dispatched dispatch({ type:SET_ALERT, payload: {msg, alert_type, id} }); setTimeout(() => dispatch({ type: REMOVE_ALERT, payload:id }), timeout); };<file_sep>import React from 'react' import PropTypes from 'prop-types' const PoliticoTop = ({ politico:{ id, nome, data_nascimento, descricao, ultimo_mandato, image } }) => { const background = `http://localhost:8888/fichapolitica/public/img/politicos/${image}` return ( <div className="profile-top bg-primary p-2"> <span style={{backgroundImage: "url(" + background + ")"}} className="round-img"></span> <h1 className="large">{nome}</h1> { ultimo_mandato !== null && <p className="lead"> {ultimo_mandato.cargo} {' - '} {ultimo_mandato.partido} <small className="small-break">Mandato: { ultimo_mandato.ano_inicio }{' - '} { ultimo_mandato.ano_fim ? ultimo_mandato.ano_fim : 'Atualmente' }</small> </p> } <p>Data de nascimento: {data_nascimento}</p> <p>{descricao}</p> </div> ) } PoliticoTop.propTypes = { } export default PoliticoTop <file_sep>import React, { Fragment } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; const PoliticoItem = ({ politico:{ id, nome, image, ultimo_mandato } }) => { const background = `http://localhost:8888/fichapolitica/public/img/politicos/${image}` return ( <div className="profile bg-light"> <span style={{backgroundImage: "url(" + background + ")"}} className="round-img"></span> <div> <h2>{nome}</h2> { ultimo_mandato !== null && <Fragment> <p>{ultimo_mandato.cargo}</p> <p>{ultimo_mandato.partido}</p> </Fragment> } <Link to={`/politico/${id}`} className="btn btn-primary">Ver perfil politico</Link> </div> </div> ) } PoliticoItem.propTypes = { politico:PropTypes.object.isRequired } export default PoliticoItem <file_sep>import { SEARCHING_PROJETOS, SEARCH_PROJETOS, PROJETOS_ERROR, GET_PROJETO, PROJETO_ERROR, CLEAR_PROJETOS } from "../actions/types"; const initial_state = { projetos:[], projeto:null, loading: false, error:{} } export default function(state = initial_state, action){ const { type, payload } = action; switch(type){ case SEARCHING_PROJETOS: return{ ...state, loading:true } case SEARCH_PROJETOS: return{ ...state, projetos: payload, loading:false } case GET_PROJETO: return{ ...state, projeto: payload, loading: false } default: return state; } }<file_sep>// Alert export const SET_ALERT = 'SET_ALERT'; export const REMOVE_ALERT = 'REMOVE_ALERT'; // Auth export const USER_LOADED = 'USER_LOADED'; export const AUTH_ERROR = 'AUTH_ERROR'; export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; export const LOGIN_FAIL = 'LOGIN_FAIL'; export const LOGOUT = 'LOGOUT'; // Clean export const CLEAR_PROFILE = 'CLEAR_PROFILE'; // Politicos export const SEARCHING_POLITICOS = 'SEARCHING_POLITICOS'; export const SEARCH_POLITICOS = 'SEARCH_POLITICOS'; export const POLITICOS_ERROR = 'POLITICOS_ERROR'; export const GET_POLITICO = 'GET_POLITICO'; export const POLITICO_ERROR = 'POLITICO_ERROR'; export const CLEAR_POLITICOS = 'CLEAR_POLITICOS'; // Projetos export const SEARCHING_PROJETOS = 'SEARCHING_PROJETOS'; export const SEARCH_PROJETOS = 'SEARCH_PROJETOS'; export const PROJETOS_ERROR = 'PROJETOS_ERROR'; export const GET_PROJETO = 'GET_PROJETO'; export const PROJETO_ERROR = 'PROJETO_ERROR'; export const CLEAR_PROJETOS = 'CLEAR_PROJETOS';<file_sep>import React from 'react'; import PropTypes from 'prop-types'; import Moment from 'react-moment'; const PoliticoMandatoProjeto = ({ projeto:{ aprovado, created_at, nome, protocolo, tipo, total_votos, url, descricao } }) => { console.log(nome) return ( <div> <h3 class="text-dark">{nome}</h3> <p> </p> <p><strong>Protocolo: </strong>{protocolo}</p> <p>Tipo: {tipo.nome}</p> <p><strong>Data: </strong><Moment format='YYYY/MM/DD'>{created_at}</Moment></p> <p>Aprovado: {aprovado}</p> <p>Total de votos: {total_votos}</p> </div> ) } PoliticoMandatoProjeto.propTypes = { projeto:PropTypes.object.isRequired, } export default PoliticoMandatoProjeto <file_sep>import React, { Fragment } from 'react' import PropTypes from 'prop-types' import { Link } from 'react-router-dom' const PoliticoItem = ({ projeto:{ id, nome, protocolo, tipo }}) => { return ( <div className="profile profile-block bg-light"> <div> <h2>{nome}</h2> <Fragment> <p>{tipo.nome}</p> <p>{protocolo}</p> </Fragment> <Link to={`/projeto/${id}`} className="btn btn-primary">Ver projeto</Link> </div> </div> ) } PoliticoItem.propTypes = { } export default PoliticoItem
871cc4be8689a7cf01144bd24b990d33d0f0ed96
[ "JavaScript" ]
12
JavaScript
luwynne/ficha_politica_fe
d54d1fb1da9fcb50430e4efde4744b8523c6cf16
b73be16ad759677c510ad87cd11bfcdc93d33c4e
refs/heads/master
<repo_name>Qerts/vox<file_sep>/Vox/WinRTLogger/Logger.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WinRTLogger { public class Logger { public Logger(Uri path, string filename) { //todo } public Logger(string email, string filename) { throw new NotImplementedException(); } public void AddLog(Importance importance, string sourceTitle, string message, string description) { //todo } } } <file_sep>/Vox/Vox/Vox.Shared/WorkingClasses/FileManager.cs using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Windows.Storage; namespace Vox.WorkingClasses { public class FileManager { public void Load() { throw new NotImplementedException(); } public async Task Save(byte[] buffer) { try { StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(Settings.Path); StorageFile file = await folder.CreateFileAsync($"recorded {DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day} {DateTime.Now.Hour}-{DateTime.Now.Minute}-{DateTime.Now.Second}.{Settings.AudioFormat}", CreationCollisionOption.ReplaceExisting); //StorageFile file = await folder.CreateFileAsync("name123." + Settings.AudioFormat, CreationCollisionOption.ReplaceExisting); using (Stream writeStream = await file.OpenStreamForWriteAsync()) { //writeStream.Read(buffer, 0, buffer.Length); writeStream.Write(buffer, 0, buffer.Length); } } catch (Exception ex) { throw; } } } } <file_sep>/Vox/Vox/Vox.Shared/WorkingClasses/Recorder.cs using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Windows.Media.Capture; using Windows.Media.MediaProperties; using Windows.Storage.Streams; namespace Vox.WorkingClasses { public class Recorder { private MediaCapture _capturer; private FileManager _fileManager; private IRandomAccessStream _audioStream; public Recorder() { _fileManager = new FileManager(); } private void _capturer_RecordLimitationExceeded(MediaCapture sender) { throw new NotImplementedException(); } private void _capturer_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) { throw new NotImplementedException(); } public async Task StartRecording() { MediaEncodingProfile profile = null; switch (Settings.AudioFormat) { case Enums.AudioEncodingFormat.mp3: profile = MediaEncodingProfile.CreateMp3(Settings.AudioQuality); break; case Enums.AudioEncodingFormat.wav: profile = MediaEncodingProfile.CreateMp3(Settings.AudioQuality); break; case Enums.AudioEncodingFormat.avi: profile = MediaEncodingProfile.CreateMp3(Settings.AudioQuality); break; case Enums.AudioEncodingFormat.m4a: profile = MediaEncodingProfile.CreateMp3(Settings.AudioQuality); break; case Enums.AudioEncodingFormat.wma: profile = MediaEncodingProfile.CreateMp3(Settings.AudioQuality); break; case Enums.AudioEncodingFormat.wmv: profile = MediaEncodingProfile.CreateMp3(Settings.AudioQuality); break; default: throw new NotImplementedException(); } _audioStream = new InMemoryRandomAccessStream(); _capturer = new MediaCapture(); _capturer.Failed += _capturer_Failed; _capturer.RecordLimitationExceeded += _capturer_RecordLimitationExceeded; MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings() { StreamingCaptureMode = StreamingCaptureMode.Audio, }; await _capturer.InitializeAsync(settings); await _capturer.StartRecordToStreamAsync(profile, _audioStream); } public async Task PauseRecording() { throw new NotImplementedException(); } public async Task StopRecording() { try { await _capturer.StopRecordAsync(); _capturer.Dispose(); using (DataReader dataReader = new DataReader(_audioStream.GetInputStreamAt(0))) { await dataReader.LoadAsync((uint)_audioStream.Size); byte[] buffer = new byte[(uint)_audioStream.Size]; dataReader.ReadBytes(buffer); await _fileManager.Save(buffer); } } catch (Exception ex) { throw; } } internal void ResumeRecording() { throw new NotImplementedException(); } } } <file_sep>/Vox/WinRTLogger/Importance.cs namespace WinRTLogger { public enum Importance { Trace, Informative, Warning, Error, Fatal, } }<file_sep>/Vox/Vox/Vox.Shared/Enums/View.cs using System; using System.Collections.Generic; using System.Text; namespace Vox.Enums { public enum View { Init = 0, //there is only buttons in the middle of the screen ShowRightBar = 1, //right bar is meant to contain applicable sound effects HideRightBar = 2, ShowLeftBar = 3, //left bar is meant to contain sound files HideLeftBar = 4, ShowBottomBar = 5, //bottom bar is meant to contain player HideBottomBar = 6, ShowTopPanel = 7, //top panel is meant to contain informative content such is progress, adds and such HodeTopPanel = 8, ShowPurchasePanel = 9, //purchase panel is meant to contain shop with purchasable items HidePurchasePanel = 10, ShowRecordButton = 11, //is meant to show record button and hide stop and pause buttons ShowStopButton = 12, //is meant to show stop and pause buttons and hide record button } } <file_sep>/Vox/Vox/Vox.Shared/WorkingClasses/SoundProcessor.cs using System; using System.Collections.Generic; using System.Text; namespace Vox.WorkingClasses { public class SoundProcessor { } } <file_sep>/Vox/Vox/Vox.Shared/Core.cs using System; using System.Collections.Generic; using System.Text; using Vox.WorkingClasses; namespace Vox { public class Core { #region Singleton private static Core _instance = null; public static Core Properties { get { if (_instance == null) { _instance = new Core(); } return _instance; } } #endregion #region Members private WinRTLogger.Logger _logger = null; public WinRTLogger.Logger Logger { get { return _logger; } set { _logger = value; } } private Player _player = null; public Player Player { get { return _player; } set { _player = value; } } private Recorder _recorder = null; public Recorder Recorder { get { return _recorder; } set { _recorder = value; } } private Settings _settings = null; public Settings Settings { get { return _settings; } set { _settings = value; } } private FileManager _fileManager = null; public FileManager FileManager { get { return _fileManager; } set { _fileManager = value; } } private SoundHolder _soundHolder = null; public SoundHolder SoundHolder { get { return _soundHolder; } set { _soundHolder = value; } } private SoundProcessor _soundProcessor = null; public SoundProcessor SoundProcessor { get { return _soundProcessor; } set { _soundProcessor = value; } } private EffectStorage _effectStorage = null; public EffectStorage EffectStorage { get { return _effectStorage; } set { _effectStorage = value; } } #endregion #region Constructor private Core() { _logger = new WinRTLogger.Logger(new Uri("C:\\", UriKind.RelativeOrAbsolute), "TheVox.log"); _player = new Player(); _recorder = new Recorder(); _settings = new Settings(); _fileManager = new FileManager(); _soundHolder = new SoundHolder(); _soundProcessor = new SoundProcessor(); _effectStorage = new EffectStorage(); } #endregion } } <file_sep>/Vox/Vox/Vox.Windows/Pages/Index.xaml.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Vox.Enums; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace Vox.Pages { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Index : Page { public Index() { this.InitializeComponent(); this.Loaded += Index_Loaded; } private void Index_Loaded(object sender, RoutedEventArgs e) { SetView(View.Init); //TODO check if there are any files loaded //TODO check if there are any effects loaded } private void SetView(View view) { switch (view) { case View.Init: //init positions break; case View.ShowRightBar: throw new NotImplementedException(); break; case View.HideRightBar: throw new NotImplementedException(); break; case View.ShowLeftBar: throw new NotImplementedException(); break; case View.HideLeftBar: throw new NotImplementedException(); break; case View.ShowBottomBar: throw new NotImplementedException(); break; case View.HideBottomBar: throw new NotImplementedException(); break; case View.ShowTopPanel: throw new NotImplementedException(); break; case View.HodeTopPanel: throw new NotImplementedException(); break; case View.ShowPurchasePanel: throw new NotImplementedException(); break; case View.HidePurchasePanel: throw new NotImplementedException(); break; case View.ShowRecordButton: buttonRecord.Visibility = Visibility.Visible; buttonStop.Visibility = Visibility.Collapsed; break; case View.ShowStopButton: buttonStop.Visibility = Visibility.Visible; buttonRecord.Visibility = Visibility.Collapsed; break; default: break; } } private async void buttonRecord_Tapped(object sender, TappedRoutedEventArgs e) { SetView(View.ShowStopButton); await Core.Properties.Recorder.StartRecording(); } private async void buttonStop_Tapped(object sender, TappedRoutedEventArgs e) { SetView(View.ShowRecordButton); await Core.Properties.Recorder.StopRecording(); } private async void buttonPause_Tapped(object sender, TappedRoutedEventArgs e) { //TODO modify pause button to checkbutton await Core.Properties.Recorder.PauseRecording(); } } } <file_sep>/Vox/Vox/Vox.Shared/WorkingClasses/Settings.cs using System; using System.Collections.Generic; using System.Text; using Vox.Enums; using Windows.Media.MediaProperties; namespace Vox.WorkingClasses { public class Settings { private static string _path = Windows.Storage.KnownFolders.Playlists.Path; public static string Path { get { return _path; } set { _path = value; } } private static AudioEncodingQuality _audioQuality = AudioEncodingQuality.Auto; public static AudioEncodingQuality AudioQuality { get { return _audioQuality; } set { _audioQuality = value; } } private static AudioEncodingFormat _audioFormat = AudioEncodingFormat.mp3; public static AudioEncodingFormat AudioFormat { get { return _audioFormat; } set { _audioFormat = value; } } } }
ff241e71a33f332d8249d7d78a4de60c38afd7db
[ "C#" ]
9
C#
Qerts/vox
41444b6494d0891928f534646291ad54f0e7bea0
8871182a5c8838e591195f7370f0653cd1970f87
refs/heads/master
<repo_name>darshanramu/LinuxLikeOS<file_sep>/kernel/drivers/memdevs.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "errno.h" #include "globals.h" #include "util/string.h" #include "util/debug.h" #include "mm/mm.h" #include "mm/page.h" #include "mm/mmobj.h" #include "mm/kmalloc.h" #include "mm/pframe.h" #include "drivers/bytedev.h" #include "vm/anon.h" #include "fs/vnode.h" static int null_read(bytedev_t *dev, int offset, void *buf, int count); static int null_write(bytedev_t *dev, int offset, const void *buf, int count); static int zero_read(bytedev_t *dev, int offset, void *buf, int count); static int zero_mmap(vnode_t *file, vmarea_t *vma, mmobj_t **ret); bytedev_ops_t null_dev_ops = { null_read, null_write, NULL, NULL, NULL, NULL }; bytedev_ops_t zero_dev_ops = { zero_read, null_write, zero_mmap, NULL, NULL, NULL }; /* * The byte device code needs to know about these mem devices, so create * bytedev_t's for null and zero, fill them in, and register them. */ void memdevs_init() { NOT_YET_IMPLEMENTED("DRIVERS: memdevs_init"); } /** * Reads a given number of bytes from the null device into a * buffer. Any read performed on the null device should read 0 bytes. * * @param dev the null device * @param offset the offset to read from. Should be ignored * @param buf the buffer to read into * @param count the maximum number of bytes to read * @return the number of bytes read, which should be 0 */ static int null_read(bytedev_t *dev, int offset, void *buf, int count) { NOT_YET_IMPLEMENTED("DRIVERS: null_read"); return -ENOMEM; } /** * Writes a given number of bytes to the null device from a * buffer. Writing to the null device should _ALWAYS_ be successful * and write the maximum number of bytes. * * @param dev the null device * @param offset the offset to write to. Should be ignored * @param buf buffer to read from * @param count the maximum number of bytes to write * @return the number of bytes written, which should be count */ static int null_write(bytedev_t *dev, int offset, const void *buf, int count) { NOT_YET_IMPLEMENTED("DRIVERS: null_write"); return -ENOMEM; } /** * Reads a given number of bytes from the zero device into a * buffer. Any read from the zero device should be a series of zeros. * * @param dev the zero device * @param offset the offset to read from. Should be ignored * @param buf the buffer to write to * @param count the maximum number of bytes to read * @return the number of bytes read. Should always read the maximum * number of bytes */ static int zero_read(bytedev_t *dev, int offset, void *buf, int count) { NOT_YET_IMPLEMENTED("DRIVERS: zero_read"); return 0; } /* Don't worry about these until VM. Once you're there, they shouldn't be hard. */ static int zero_mmap(vnode_t *file, vmarea_t *vma, mmobj_t **ret) { NOT_YET_IMPLEMENTED("DRIVERS: zero_mmap"); return -1; } <file_sep>/kernel/include/main/acpi.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once struct acpi_header { uint32_t ah_sign; uint32_t ah_size; uint8_t ah_rev; uint8_t ah_checksum; uint8_t ah_oemid[6]; uint8_t ah_tableid[8]; uint32_t ah_oemrev; uint32_t ah_creatorid; uint32_t ah_creatorrev; }; void acpi_init(); void *acpi_table(uint32_t signature, int index); <file_sep>/kernel/include/proc/kmutex.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #include "proc/sched.h" typedef struct kmutex { ktqueue_t km_waitq; /* wait queue */ struct kthread *km_holder; /* current holder */ } kmutex_t; /** * Initializes the fields of the specified kmutex_t. * * @param mtx the mutex to initialize */ void kmutex_init(kmutex_t *mtx); /** * Locks the specified mutex. * * Note: This function may block. * * Note: These locks are not re-entrant * * @param mtx the mutex to lock */ void kmutex_lock(kmutex_t *mtx); /** * Locks the specified mutex, but puts the current thread into a * cancellable sleep if the function blocks. * * Note: This function may block. * * Note: These locks are not re-entrant. * * @param mtx the mutex to lock * @return 0 if the current thread now holds the mutex and -EINTR if * the sleep was cancelled and this thread does not hold the mutex */ int kmutex_lock_cancellable(kmutex_t *mtx); /** * Unlocks the specified mutex. * * @mtx the mutex to unlock */ void kmutex_unlock(kmutex_t *mtx); <file_sep>/kernel/drivers/disk/ata.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "types.h" #include "main/interrupt.h" #include "main/io.h" #include "util/string.h" #include "util/debug.h" #include "util/list.h" #include "util/delay.h" #include "drivers/blockdev.h" #include "drivers/dev.h" #include "drivers/pci.h" #include "drivers/disk/dma.h" #include "proc/sched.h" #include "proc/kmutex.h" #include "mm/kmalloc.h" #include "mm/page.h" /* Copied from the bochsrc, make sure it always matches */ #define IRQ_DISK_PRIMARY 14 #define IRQ_DISK_SECONDARY 15 /* * Huge pile of helpful definitions (copied from OSDev). Note that we * do not support busmaster, drive detection, or LBA48 We support * secondary channel and slave drive, but probably won't ever use * them. */ /* Interface type (we will only use ATA) */ #define ATA_TYPE_ATA 0x00 #define ATA_TYPE_ATAPI 0x01 /* Master or slave */ #define ATA_MASTER 0x00 #define ATA_SLAVE 0x01 /* Channels */ #define ATA_PRIMARY 0x00 #define ATA_SECONDARY 0x01 /* Operations */ #define ATA_READ 0x00 #define ATA_WRITE 0x01 /* "Base" port addresses */ /* The addresses to use for actual IO registers are offsets from these */ #define ATA_PRIMARY_CTRL_BASE 0x3f0 #define ATA_PRIMARY_CMD_BASE 0x1f0 #define ATA_SECONDARY_CTRL_BASE 0x370 #define ATA_SECONDARY_CMD_BASE 0x170 /* Note interrupt numbers defined in core/interrupt.h */ typedef void (*atac_intr_handler_t)(regs_t *regs, void *arg); static struct ata_channel { /* Base port for cmd registers */ uint16_t atac_cmd; /* Base port for ctrl registers */ uint16_t atac_ctrl; /* Interrupt number for this channel */ uint8_t atac_intr; /* Interrupt handler for this channel */ atac_intr_handler_t atac_intr_handler; /* Argument for interrupt handler */ void *atac_intr_arg; /* address of busmaster register */ uint16_t atac_busmaster; } ATA_CHANNELS[2] = { { ATA_PRIMARY_CMD_BASE, ATA_PRIMARY_CTRL_BASE, INTR_DISK_PRIMARY, NULL, NULL, NULL }, { ATA_SECONDARY_CMD_BASE, ATA_SECONDARY_CTRL_BASE, INTR_DISK_SECONDARY, NULL, NULL, NULL } }; #define ATA_NUM_CHANNELS 2 #define ATA_SECTOR_SIZE 512 /* Pretty much always true */ /* Drive/head values (for ATA_REG_DRIVEHEAD) */ #define ATA_DRIVEHEAD_MASTER 0xA0 #define ATA_DRIVEHEAD_SLAVE 0xB0 /* Port address offsets for registers */ /* Command registers */ #define ATA_REG_DATA 0x00 /* Data register (read/write address) */ #define ATA_REG_ERROR 0x01 #define ATA_REG_FEATURE 0x01 #define ATA_REG_SECCOUNT0 0x02 /* Number of sectors to read/write */ #define ATA_REG_SECNUM 0x03 /* chs addressing */ #define ATA_REG_CYLLOW 0x04 #define ATA_REG_CYLHIGH 0x05 #define ATA_REG_LBA0 0x03 /* lba addressing */ #define ATA_REG_LBA1 0x04 #define ATA_REG_LBA2 0x05 #define ATA_REG_DRIVEHEAD 0x06 /* Special drive info (used to set master/slave) */ #define ATA_REG_COMMAND 0x07 /* Write only */ #define ATA_REG_STATUS 0x07 /* Read only */ #define ATA_REG_SECCOUNT1 0x08 /* These four are only used in lba48 */ #define ATA_REG_LBA3 0x09 #define ATA_REG_LBA4 0x0A #define ATA_REG_LBA5 0x0B /* --- */ #define ATA_REG_NIEN_CONTROL 0x0C /* Control registers */ #define ATA_REG_CONTROL 0x06 /* Write only */ /* Like status, but does not imply clear of interrupt */ #define ATA_REG_ALTSTATUS 0x06 /* Read only */ #define ATA_REG_DEVADDRESS 0x07 /* Status codes (for ATA_REG_STATUS) */ #define ATA_SR_BSY 0x80 /* Busy */ #define ATA_SR_DRDY 0x40 /* Drive ready */ #define ATA_SR_DF 0x20 /* Drive write fault */ #define ATA_SR_DSC 0x10 /* Drive seek complete */ #define ATA_SR_DRQ 0x08 /* Data request ready */ #define ATA_SR_CORR 0x04 /* Corrected data */ #define ATA_SR_IDX 0x02 /* inlex */ #define ATA_SR_ERR 0x01 /* Error */ /* Error codes (for ATA_REG_ERROR) */ #define ATA_ER_BBK 0x80 /* Bad sector */ #define ATA_ER_UNC 0x40 /* Uncorrectable data */ #define ATA_ER_MC 0x20 /* No media */ #define ATA_ER_IDNF 0x10 /* ID mark not found */ #define ATA_ER_MCR 0x08 /* No media */ #define ATA_ER_ABRT 0x04 /* Command aborted */ #define ATA_ER_TK0NF 0x02 /* Track 0 not found */ #define ATA_ER_AMNF 0x01 /* No address mark */ /* Commands (for ATA_REG_COMMAND) */ #define ATA_CMD_READ_PIO 0x20 #define ATA_CMD_READ_PIO_EXT 0x24 #define ATA_CMD_READ_DMA 0xC8 #define ATA_CMD_READ_DMA_EXT 0x25 #define ATA_CMD_WRITE_PIO 0x30 #define ATA_CMD_WRITE_PIO_EXT 0x34 #define ATA_CMD_WRITE_DMA 0xCA #define ATA_CMD_WRITE_DMA_EXT 0x35 #define ATA_CMD_CACHE_FLUSH 0xE7 #define ATA_CMD_CACHE_FLUSH_EXT 0xEA #define ATA_CMD_PACKET 0xA0 #define ATA_CMD_IDENTIFY_PACKET 0xA1 #define ATA_CMD_IDENTIFY 0xEC /* Drive/head values for CHS / LBA */ #define ATA_DRIVEHEAD_CHS 0x00 #define ATA_DRIVEHEAD_LBA 0x40 #define ATA_IDENT_MAX_LBA 30 /* Reads from the command registers, NOT the control registers */ #define ata_inb_reg(channel, reg) inb(ATA_CHANNELS[channel].atac_cmd + reg) #define ata_inw_reg(channel, reg) inw(ATA_CHANNELS[channel].atac_cmd + reg) #define ata_inl_reg(channel, reg) inl(ATA_CHANNELS[channel].atac_cmd + reg) /* Writes to command registers */ #define ata_outb_reg(channel, reg, data) \ outb(ATA_CHANNELS[(channel)].atac_cmd + (reg), (data)) #define ata_outw_reg(channel, reg, data) \ outw(ATA_CHANNELS[(channel)].atac_cmd + (reg), (data)) #define ata_outl_reg(channel, reg, data) \ outl(ATA_CHANNELS[(channel)].atac_cmd + (reg), (data)) /* Helpful for delaying, etc. */ #define ata_inb_altstatus(channel) \ inb(ATA_CHANNELS[(channel)].atac_ctrl + ATA_REG_ALTSTATUS) /* Delay 1 port read without implying interrupt clear (as reading from * status does) */ static void ata_sync(uint8_t channel) { ata_inb_altstatus(channel); } /* Sync and wait a bit */ static void ata_pause(uint8_t channel) { ata_sync(channel); ndelay(400); } #define ATA_IDENT_BUFSIZE 256 #define bd_to_ata(bd) (CONTAINER_OF((bd), ata_disk_t, ata_bdev)) typedef struct ata_disk { /* 0 (Primary Channel) or 1 (Secondary Channel) */ uint8_t ata_channel; /* 0 (Master Drive) or 1 (Slave Drive) */ uint8_t ata_drive; /* Size of disk in number of sectors */ uint32_t ata_size; uint32_t ata_sectors_per_block; /* Threads making blocking disk operations wait one this * queue, and disk interrupt wakes them up */ ktqueue_t ata_waitq; /* Disk mutex since only one process can be using the disk at * any time */ kmutex_t ata_mutex; /* Underlying block device */ blockdev_t ata_bdev; } ata_disk_t; /* this prototype needs to be after the struct definition */ uint16_t ata_setup_busmaster(ata_disk_t* adisk); #define NDISKS __NDISKS__ static void ata_intr_wrapper(regs_t *regs); static int ata_read(blockdev_t *bdev, char *data, blocknum_t blocknum, unsigned int count); static int ata_write(blockdev_t *bdev, const char *data, blocknum_t blocknum, unsigned int count); static int ata_do_operation(ata_disk_t *adisk, char *data, \ blocknum_t sectornum, int write); static void ata_intr(regs_t *regs, void *arg); static blockdev_ops_t ata_disk_ops = { .read_block = ata_read, .write_block = ata_write }; void ata_init() { int ii; intr_map(IRQ_DISK_PRIMARY, INTR_DISK_PRIMARY); intr_map(IRQ_DISK_SECONDARY, INTR_DISK_SECONDARY); dma_init(); /* IMPORTANT! */ uint8_t oldipl = intr_getipl(); intr_setipl(INTR_DISK_PRIMARY); for (ii = 0; ii < NDISKS; ii++) { int i; int err = 0; uint32_t ident_buf[ATA_IDENT_BUFSIZE]; uint8_t status = 0; int channel = ii; /* No slave drive support */ ata_disk_t *adisk; if (ii >= ATA_NUM_CHANNELS) panic("ATA does not have as many drives" "as you want!\n"); /* Choose drive - In this case always Master */ ata_outb_reg(channel, ATA_REG_DRIVEHEAD, ATA_DRIVEHEAD_MASTER | ATA_DRIVEHEAD_LBA); /* Set the Sector count register to be 0 */ ata_outb_reg(channel, ATA_REG_SECCOUNT0, 0); /* Set the LBA0 LBA1 LBA2 registers to be 0 */ ata_outb_reg(channel, ATA_REG_LBA0, 0); ata_outb_reg(channel, ATA_REG_LBA1, 0); ata_outb_reg(channel, ATA_REG_LBA2, 0); /* disable IRQs for the master (shamelessly stolen from OS Dev */ outb(ATA_PRIMARY_CTRL_BASE + ATA_REG_CONTROL, 0x02); /* Tell drive to get ready to in identification space */ ata_outb_reg(channel, ATA_REG_COMMAND, ATA_CMD_IDENTIFY); /* wait some time for the drive to process */ ata_pause(channel); /* If status register is 0xff, drive does not exist */ if (0x00 == ata_inb_reg(channel, ATA_REG_STATUS)) { dbgq(DBG_DISK, "Drive does not exist\n"); continue; } /* poll until the BSY bit clears */ while(1) { status = ata_inb_reg(channel, ATA_REG_STATUS); if (!(status & ATA_SR_BSY)) break; ata_pause(channel); } /* Now the drive is no longer busy, poll until the error bit is set or drq is set */ while (1) { status = ata_inb_reg(channel, ATA_REG_STATUS); if (status & ATA_SR_ERR) { err = 1; break; } if (status & ATA_SR_DRQ) break; ata_pause(channel); } if (err) { panic("Error setting up ATA drive\n"); } /* Now clear the command register */ outb(ATA_PRIMARY_CTRL_BASE + ATA_REG_CONTROL, 0x00); /* Otherwise, allocate new disk */ if (NULL == (adisk = (ata_disk_t *)kmalloc(sizeof(ata_disk_t)))) panic("Not enough memory for ata disk struct!\n"); adisk->ata_channel = channel; adisk->ata_drive = 0; for (i = 0; i < ATA_IDENT_BUFSIZE; i++) { ident_buf[i] = ata_inl_reg(adisk->ata_channel, ATA_REG_DATA); } /* Determine disk size */ adisk->ata_size = ident_buf[ATA_IDENT_MAX_LBA]; /* In theory we could use this identification buffer * to find out lots of other things but we don't * really need to know any of them */ adisk->ata_sectors_per_block = BLOCK_SIZE / ATA_SECTOR_SIZE; sched_queue_init(&adisk->ata_waitq); kmutex_init(&adisk->ata_mutex); dbg(DBG_DISK, "Initialized ATA device %d, channel %s, drive %s, size %d\n", ii, (adisk->ata_channel ? "SECONDARY" : "PRIMARY"), (adisk->ata_drive ? "SLAVE" : "MASTER"), adisk->ata_size); /* Set up corresponding handler */ intr_register(ATA_CHANNELS[adisk->ata_channel].atac_intr, ata_intr_wrapper); ATA_CHANNELS[adisk->ata_channel].atac_intr_handler = ata_intr; ATA_CHANNELS[adisk->ata_channel].atac_intr_arg = adisk; ATA_CHANNELS[adisk->ata_channel].atac_busmaster = ata_setup_busmaster(adisk); adisk->ata_bdev.bd_id = MKDEVID(DISK_MAJOR, ii); adisk->ata_bdev.bd_ops = &ata_disk_ops; blockdev_register(&adisk->ata_bdev); } intr_setipl(oldipl); } static void ata_intr_wrapper(regs_t *regs) { int i; dbg(DBG_DISK, "ATA interrupt\n"); for (i = 0; i < ATA_NUM_CHANNELS; i++) { /* Check if interrupt is for this channel */ if (ATA_CHANNELS[i].atac_intr == regs->r_intr) { if (NULL == ATA_CHANNELS[i].atac_intr_handler) panic("No handler registered " "for ATA channel %d!\n", i); ATA_CHANNELS[i].atac_intr_handler( regs, ATA_CHANNELS[i].atac_intr_arg); /* Acknowledge interrupt */ ata_inb_reg(i, ATA_REG_STATUS); return; } } panic("Received interrupt on channel we don't know about\n"); } /** * Reads a given number of blocks from a block device starting at a * given block number into a buffer. * * @param bdev the block device to read from * @param data buffer to write to * @param blocknum the block number to start reading at * @param count the number of blocks to read * @return 0 on success and <0 on error */ static int ata_read(blockdev_t *bdev, char *data, blocknum_t blocknum, unsigned int count) { NOT_YET_IMPLEMENTED("DRIVERS: ata_read"); return -1; } /** * Writes a a given number of blocks from a buffer to a block device * starting at a given block. * * @param bdev the block device to write to * @param data buffer to read data from * @param blocknum the block number to start writing at * @param count the number of blocks to write * @return 0 on success and <0 on error */ static int ata_write(blockdev_t *bdev, const char *data, blocknum_t blocknum, unsigned int count) { NOT_YET_IMPLEMENTED("DRIVERS: ata_write"); return -1; } /** * Read/write the given block. * * @param adisk the disk to perform the operation on * @param data the buffer to write from or read into * @param blocknum which block on the disk to read or write * @param write true if writing, false if reading * @return 0 on sucess or <0 on error */ /* * In this function you will perform a disk operation using * direct memory access (DMA). Follow these steps _VERY_ * carefully. The steps are as follows: * * o Lock the mutex and set the IPL. We don't want to * other threads trying to perform an operation while we * are in the middle of this operation. We also don't want * to receive a disk interrupt, which is supposed to wake * up this thread to alert us that the DMA operation has * completed, before the thread goes to sleep and puts * itself on the wait queue. Since the only interrupts we * care about are disk interrupts, we do not have to mask * all interrupts, just disk interrupts (and consequently, * all interrupts with lower priority than disk * interrupts). Try INTR_DISK_SECONDARY. * * o Initialize DMA for this operation (see the dma_load() * function) * * o Write to the disk's registers to tell it the number * of sectors that will be read/writen and the starting * sector. Use the ata_outb_reg() function for writing * to the hardware registers (as these are each one byte * in size). * * We use logical block addressing (LBA) to specify the * starting sector. Our interface supports 24-bit sector * numbers, and up to 256* sectors to be read/written at a * time. Write the number of sectors to ATA_REG_SECCOUNT0. * Write the sector number in little-endian order to * ATA_REG_LBA{0-2} (least-significant eight bits to * ATA_REG_LBA0, middle eight bits to ATA_REG_LBA1, * most-significant eight bits to ATA_REG_LBA2). * * (* Note that the special value 0 when written to this * register will in fact write 256 sectors, though you will * not ever be writing this value) * * o Write to the disk's registers to tell it the type of * operation it will be performing. * * You should write either ATA_CMD_WRITE_DMA or * ATA_CMD_READ_DMA to the ATA_REG_COMMAND register. * * o Pause to make sure the disk is ready to go (see the * ata_pause() function). * * o Start the DMA operation (see the dma_start() function). * * o Now that we have given the disk and the DMA * controller the necessary information, all we have to do * is wait. This is the whole point of DMA: this process * can yield, allowing the CPU to perform other tasks * while we wait for the disk to seek and perform the * requested operation. * * Specifically, we want to sleep on the disk's wait queue * so we can be woken up by the interrupt handler, which * will be called when the DMA operation is completed. * * o Once we have woken up from sleep, we need to read * the status of the DMA operation from the disk's * ATA_REG_STATUS register (see the ata_inb_reg() * function). * * o Next, we check the status to see if the error bit is * set (for status flags, see ATA_SR_* values). If there * is an error, read the error code from the disk's * ATA_REG_ERROR register (propagate it up as -error). * * o Alert the DMA controller that we have received the * interrupt and, if necessary, clear the error bit (see * dma_reset() function). * * o Now we are finished. Restore the IPL, release any * locks we have, and return the status of the DMA * operation. */ static int ata_do_operation(ata_disk_t *adisk, char *data, blocknum_t blocknum, int write) { NOT_YET_IMPLEMENTED("DRIVERS: ata_do_operation"); return -1; } /** * Interrupt handler called by the disk when an operation has * completed. * * @param regs the register state * @param arg the disk the operation was performed on. This should be * a pointer to an ata_disk_t struct. */ static void ata_intr(regs_t *regs, void *arg) { NOT_YET_IMPLEMENTED("DRIVERS: ata_intr"); } /* * This function takes in an ATA Disk struct and * sets it up for busmastering DMA */ uint16_t ata_setup_busmaster(ata_disk_t* adisk) { /* First step is to read the command register and see what's there */ pcidev_t* ide = pci_lookup(0x01, 0x01, 0x80); if (ide == NULL) { panic("Could not find ide device\n"); } uint32_t command = pci_read_config(ide, PCI_COMMAND, 2); /* set the busmaster bit to 1 to enable busmaster */ command |= 0x4; /* clear bit 10 to make sure that interrupts are enabled */ command &= 0xfdff; pci_write_config(ide, PCI_COMMAND, command, 2); /* read BAR4 and return the address of the busmaster register */ uint32_t busmaster_base = ide->pci_bar[4].base_addr + (adisk->ata_channel * 8); if (busmaster_base == 0) { panic("No valid busmastering address\n"); } KASSERT(busmaster_base != 0 && "Disk device should not have 0 for the busmaster register"); return (uint16_t)busmaster_base; } <file_sep>/kernel/drivers/disk/dma.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "main/io.h" #include "util/debug.h" #include "util/string.h" #include "util/delay.h" #include "drivers/disk/dma.h" #include "mm/pagetable.h" #include "mm/page.h" typedef struct { uint32_t prd_addr; uint16_t prd_count; uint16_t prd_last; } prd_t; static prd_t prd_table[2] __attribute__((aligned(32))); static prd_t *DMA_PRDS[2]; void dma_init() { /* Clear the table */ memset(prd_table, 0, sizeof(prd_t) * 2); /* Set pointers to it; note each channel only needs one PRD entry */ DMA_PRDS[0] = prd_table; DMA_PRDS[1] = prd_table + 1; } void dma_load(uint8_t channel, void *start, int count) { KASSERT(PAGE_ALIGNED(start)); prd_t* table = DMA_PRDS[channel]; memset(table, 0, sizeof(prd_t)); /* set up the PRD for this operation */ table->prd_addr = pt_virt_to_phys((uintptr_t) start); table->prd_count = count; table->prd_last = 0x8000; return; } void dma_start(uint8_t channel, uint16_t busmaster_addr, int write) { uint8_t cmd = 0; /* first we need to set the read/write bit */ if (write == 0) { cmd = (1 << 3); } /* then set the address of the prd */ outl(busmaster_addr + DMA_PRD, pt_virt_to_phys((uintptr_t)DMA_PRDS[channel])); /* then allow all channels of DMA on this busmaster by setting that status register */ outb(busmaster_addr + DMA_STATUS, inb(busmaster_addr + DMA_STATUS) | 0x60); /* then we need to set the start/stop bit */ cmd |= 0x01; outb(busmaster_addr + DMA_COMMAND, cmd); } void dma_reset(uint16_t busmaster_addr) { /* to acknowledge the interrupt we need to both * read the status register and write 0x64 to it. * the 0x64 resets the interrupts somehow while * keeping DMA enabled */ inb(busmaster_addr + DMA_STATUS); outb(busmaster_addr + DMA_STATUS, 0x64); /* we also should clear the start bit of the command register */ outb(busmaster_addr + DMA_COMMAND, 0x00); } <file_sep>/kernel/proc/context.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "config.h" #include "proc/context.h" #include "proc/kthread.h" #include "main/apic.h" #include "main/interrupt.h" #include "main/gdt.h" #include "mm/page.h" #include "mm/pagetable.h" #include "util/debug.h" static void __context_initial_func(context_func_t func, int arg1, void *arg2) { apic_setipl(IPL_LOW); intr_enable(); void *result = func(arg1, arg2); kthread_exit(result); panic("\nReturned from kthread_exit.\n"); } void context_setup(context_t *c, context_func_t func, int arg1, void *arg2, void *kstack, size_t kstacksz, pagedir_t *pdptr) { KASSERT(NULL != pdptr); KASSERT(PAGE_ALIGNED(kstack)); c->c_kstack = (uintptr_t)kstack; c->c_kstacksz = kstacksz; c->c_pdptr = pdptr; /* put the arguments for __contect_initial_func onto the * stack, leave room at the bottom of the stack for a phony * return address (we should never return from the lowest * function on the stack */ c->c_esp = (uintptr_t)kstack + kstacksz; c->c_esp -= sizeof(arg2); *(void **)c->c_esp = arg2; c->c_esp -= sizeof(arg1); *(int *)c->c_esp = arg1; c->c_esp -= sizeof(context_func_t); *(context_func_t *)c->c_esp = func; c->c_esp -= sizeof(uintptr_t); c->c_ebp = c->c_esp; c->c_eip = (uintptr_t)__context_initial_func; } void context_make_active(context_t *c) { dbg(DBG_PRINT,"context make active\n"); gdt_set_kernel_stack((void *)((uintptr_t)c->c_kstack + c->c_kstacksz)); pt_set(c->c_pdptr); /* Switch stacks and run the thread */ __asm__ volatile( "movl %0,%%ebp\n\t" /* update ebp */ "movl %1,%%esp\n\t" /* update esp */ "push %2\n\t" /* save eip */ "ret" /* jump to new eip */ :: "m"(c->c_ebp), "m"(c->c_esp), "m"(c->c_eip) ); } void context_switch(context_t *oldc, context_t *newc) { gdt_set_kernel_stack((void *)((uintptr_t)newc->c_kstack + newc->c_kstacksz)); pt_set(newc->c_pdptr); /* * Save the current value of the stack pointer and the frame pointer into * the old context. Set the instruction pointer to the return address * (whoever called us). */ __asm__ __volatile__( "pushfl \n\t" /* save EFLAGS on the stack */ "pushl %%ebp \n\t" "movl %%esp, %0 \n\t" /* save ESP into oldc */ "movl %2, %%esp \n\t" /* restore ESP from newc */ "movl $1f, %1 \n\t" /* save EIP into oldc */ "pushl %3 \n\t" /* restore EIP */ "ret \n\t" "1:\t" /* this is where oldc starts executing later */ "popl %%ebp \n\t" "popfl" /* restore EFLAGS */ :"=m"(oldc->c_esp), "=m"(oldc->c_eip) :"m"(newc->c_esp), "m"(newc->c_eip) ); } <file_sep>/kernel/proc/fork.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "types.h" #include "globals.h" #include "errno.h" #include "util/debug.h" #include "util/string.h" #include "proc/proc.h" #include "proc/kthread.h" #include "mm/mm.h" #include "mm/mman.h" #include "mm/page.h" #include "mm/pframe.h" #include "mm/mmobj.h" #include "mm/pagetable.h" #include "mm/tlb.h" #include "fs/file.h" #include "fs/vnode.h" #include "vm/shadow.h" #include "vm/vmmap.h" #include "api/exec.h" #include "main/interrupt.h" /* Pushes the appropriate things onto the kernel stack of a newly forked thread * so that it can begin execution in userland_entry. * regs: registers the new thread should have on execution * kstack: location of the new thread's kernel stack * Returns the new stack pointer on success. */ static uint32_t fork_setup_stack(const regs_t *regs, void *kstack) { /* Pointer argument and dummy return address, and userland dummy return * address */ uint32_t esp = ((uint32_t) kstack) + DEFAULT_STACK_SIZE - (sizeof(regs_t) + 12); *(void **) (esp + 4) = (void *) (esp + 8); /* Set the argument to point to location of struct on stack */ memcpy((void *) (esp + 8), regs, sizeof(regs_t)); /* Copy over struct */ return esp; } /* * The implementation of shadow_destroy. * This routine cleans up the shadow objects. * We decrement the new ref count and mmobj is reset to old mmobj and its count. */ static void shadow_destroy(list_t *parent_vma, list_t *child_vma) { list_link_t *parent, *child; parent = parent_vma->l_next; child = child_vma->l_next; while (parent != parent_vma) { vmarea_t *pvma, *cvma; pvma = list_item(parent, vmarea_t, vma_plink); cvma = list_item(child, vmarea_t, vma_plink); if (cvma->vma_obj == NULL) { break; } if ((pvma->vma_flags & MAP_TYPE) == MAP_PRIVATE) { mmobj_t *parent_mmo = pvma->vma_obj->mmo_shadowed; parent_mmo->mmo_ops->ref(parent_mmo); pvma->vma_obj->mmo_ops->put(pvma->vma_obj); pvma->vma_obj = parent_mmo; } parent = parent->l_next; child = child->l_next; } } static void init_shadow(vmarea_t *vma, mmobj_t *shadow) { mmobj_t *bottom; bottom = mmobj_bottom_obj(vma->vma_obj); bottom->mmo_ops->ref(bottom); shadow->mmo_un.mmo_bottom_obj = bottom; shadow->mmo_shadowed = vma->vma_obj; if (list_link_is_linked(&vma->vma_olink)) { list_remove(&vma->vma_olink); } list_insert_tail(&bottom->mmo_un.mmo_vmas, &vma->vma_olink); vma->vma_obj = shadow; } /* * The implementation of fork(2). Once this works, * you're practically home free. This is what the * entirety of Weenix has been leading up to. * Go forth and conquer. */ int do_fork(struct regs *regs) { /*NOT_YET_IMPLEMENTED("VM: do_fork");*/ KASSERT(regs != NULL); dbg(DBG_PRINT, "(GRADING3A 7.a)\n"); KASSERT(curproc != NULL); dbg(DBG_PRINT, "(GRADING3A 7.a)\n"); KASSERT(curproc->p_state == PROC_RUNNING); dbg(DBG_PRINT, "(GRADING3A 7.a)\n"); proc_t *child_pcb = proc_create("child process"); /* if (child_pcb == NULL) { dbg(DBG_ERROR, "(GRADING3A 1)\n"); curthr->kt_errno = -ENOMEM; return -1; }*/ KASSERT(child_pcb->p_state == PROC_RUNNING); dbg(DBG_PRINT, "(GRADING3A 7.a)\n"); KASSERT(child_pcb->p_pagedir != NULL); dbg(DBG_PRINT, "(GRADING3A 7.a)\n"); /*Copy address space from parent to child */ /*This just copies single level VMA, so later we do the linked lists copy */ vmmap_t *child_vmap = vmmap_clone(curproc->p_vmmap); int retVal = 0; if (NULL != child_vmap) { dbg(DBG_PRINT, "(GRADING3F)\n"); list_t *parent_vmm, *child_vmm; list_link_t *parent_vma, *child_vma; parent_vmm = &curproc->p_vmmap->vmm_list; child_vmap->vmm_proc = child_pcb; child_vmm = &child_vmap->vmm_list; parent_vma = parent_vmm->l_next; child_vma = child_vmm->l_next; /*Copy VMA linked lists from parent to child */ while (parent_vma != parent_vmm) { dbg(DBG_PRINT, "(GRADING3F)\n"); /*Want new items every time, so declare again */ vmarea_t *pvma, *cvma; pvma = list_item(parent_vma, vmarea_t, vma_plink); cvma = list_item(child_vma, vmarea_t, vma_plink); cvma->vma_obj = pvma->vma_obj; /* TODO : Verify if this is needed? */ cvma->vma_obj->mmo_ops->ref(cvma->vma_obj); int map_type = pvma->vma_flags & MAP_TYPE; if (map_type == MAP_PRIVATE) { dbg(DBG_PRINT, "(GRADING3F)\n"); mmobj_t *p_shadow = shadow_create(); if (p_shadow != NULL) { dbg(DBG_PRINT, "(GRADING3F)\n"); mmobj_t *c_shadow = shadow_create(); if (c_shadow != NULL) { dbg(DBG_PRINT, "(GRADING3F)\n"); p_shadow->mmo_ops->ref(p_shadow); c_shadow->mmo_ops->ref(c_shadow); init_shadow(pvma,p_shadow); init_shadow(cvma,c_shadow); } /*else { dbg(DBG_ERROR, "(GRADING3A 7)\n"); retVal = -ENOSPC; }*/ } /*else { dbg(DBG_ERROR, "(GRADING3A 8)\n"); retVal = -ENOSPC; }*/ /*if (retVal < 0) { dbg(DBG_ERROR, "(GRADING3A 9)\n"); cvma->vma_obj->mmo_ops->put(cvma->vma_obj); cvma->vma_obj = NULL; break; }*/ } parent_vma = parent_vma->l_next; child_vma = child_vma->l_next; } /*if (retVal) { dbg(DBG_ERROR, "(GRADING3A 10)\n"); shadow_destroy(parent_vmm, child_vmm); vmmap_destroy(child_vmap); retVal = -ENOMEM; } else*/ { dbg(DBG_PRINT, "(GRADING3F)\n"); vmmap_destroy(child_pcb->p_vmmap); child_pcb->p_vmmap = child_vmap; /*retVal = 0;*/ } } /*else if (child_vmap == NULL) { dbg(DBG_ERROR, "(GRADING3A 12)\n"); retVal = -ENOMEM; }*/ /* Error during clone, clear up new child mess*/ /*if (retVal) { dbg(DBG_ERROR, "(GRADING3A 13)\n"); list_remove(&child_pcb->p_list_link); list_remove(&child_pcb->p_child_link); pt_destroy_pagedir(child_pcb->p_pagedir); vput(child_pcb->p_cwd); vmmap_destroy(child_pcb->p_vmmap); curthr->kt_errno = -ENOMEM; return -1; }*/ /* Create a new child thread and setup its stack */ kthread_t *childthr = kthread_clone(curthr); /*if (childthr == NULL) { dbg(DBG_ERROR, "(GRADING3A 14)\n"); shadow_destroy(&curproc->p_vmmap->vmm_list, &child_pcb->p_vmmap->vmm_list); list_remove(&child_pcb->p_list_link); list_remove(&child_pcb->p_child_link); pt_destroy_pagedir(child_pcb->p_pagedir); vput(child_pcb->p_cwd); vmmap_destroy(child_pcb->p_vmmap); curthr->kt_errno = -ENOMEM; return -1; }*/ childthr->kt_proc = child_pcb; KASSERT(childthr->kt_kstack != NULL); dbg(DBG_PRINT, "(GRADING3A 7.a)\n"); list_insert_tail(&child_pcb->p_threads, &childthr->kt_plink); /* Child gets 0 return status on fork success */ regs->r_eax = 0; childthr->kt_ctx.c_pdptr = child_pcb->p_pagedir; childthr->kt_ctx.c_eip = (uint32_t) userland_entry; childthr->kt_ctx.c_esp = fork_setup_stack(regs, childthr->kt_kstack); childthr->kt_ctx.c_kstack = (uintptr_t) childthr->kt_kstack; childthr->kt_ctx.c_kstacksz = DEFAULT_STACK_SIZE; /* Copy Parent's FDT */ int i; for (i = 0; i < NFILES; i++) { dbg(DBG_PRINT, "(GRADING3F)\n"); child_pcb->p_files[i] = curproc->p_files[i]; if (child_pcb->p_files[i] != NULL) { dbg(DBG_PRINT, "(GRADING3F)\n"); fref(child_pcb->p_files[i]); } } tlb_flush_all(); pt_unmap_range(curproc->p_pagedir, USER_MEM_LOW, USER_MEM_HIGH); child_pcb->p_brk = curproc->p_brk; child_pcb->p_start_brk = curproc->p_start_brk; sched_make_runnable(childthr); regs->r_eax = child_pcb->p_pid; return child_pcb->p_pid; } <file_sep>/kernel/include/limits.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #define CHAR_BIT 8 #define CHAR_MAX UCHAR_MAX #define UCHAR_MAX ((unsigned char)(~0U)) #define SCHAR_MAX ((signed char)(UCHAR_MAX>>1)) #define SCHAR_MIN (-SCHAR_MAX - 1) #define USHRT_MAX ((unsigned short)(~0U)) #define SHRT_MAX ((signed short)(USHRT_MAX>>1)) #define SHRT_MIN (-SHRT_MAX - 1) #define UINT_MAX ((unsigned int)(~0U)) #define INT_MAX ((signed int)(UINT_MAX>>1)) #define INT_MIN (-INT_MAX - 1) #define ULONG_MAX ((unsigned long)(~0UL)) #define LONG_MAX ((signed long)(ULONG_MAX>>1)) #define LONG_MIN (-LONG_MAX - 1) #define UPTR_MAX UINT_MAX <file_sep>/kernel/include/drivers/tty/screen.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #include "types.h" /** * Initialize the screen subsystem. */ void screen_init(void); /** * Move the cursor to the given (x,y) coords (measured from top left). * * @param x the x coordinate * @param y the y coordinate */ void screen_move_cursor(uint8_t x, uint8_t y); /** * Writes a character to the screen at the given position. * * @param c the character to display on the screen * @param x the x coordinate * @param y the y coordinate */ void screen_putchar(char c, uint8_t x, uint8_t y); /** * Writes a character to the screen at a given position with the given * attributes. * * @param c the character to display on the screen * @param x the x coordinate * @param y the y coordinate * @param the attributes for the character */ void screen_putchar_attrib(char c, uint8_t x, uint8_t y, uint8_t attrib); /** * Write a buffer of characters which is _EXACTLY_ DISPLAY_WIDTH x * DISPLAY_HEIGHT characters. * * @param buf the buffer to write to the screen */ void screen_putbuf(const char *buf); /** * Write a buffer of characters which is _EXACTLY_ DISPLAY_WIDTH x * DISPLAY_HEIGHT characters and attributes. * * @param buf the buffer to write to the screen */ void screen_putbuf_attrib(const uint16_t *buf); /** * Clear the screen. */ void screen_clear(void); <file_sep>/kernel/include/boot/config.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #define KERNEL_PHYS_BASE 0x100000 #define MEMORY_MAP_BASE 0x9000 <file_sep>/kernel/drivers/tty/screen.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "drivers/tty/screen.h" #include "drivers/tty/tty.h" #include "drivers/tty/virtterm.h" #include "main/io.h" #include "mm/pagetable.h" #include "util/debug.h" #include "util/string.h" /* Location of directly mapped video memory (by default) */ /* Note that this is a short * as video memory is addressed in 2-byte chunks - * 1st byte is attributes, 2nd byte is char */ #define PHYS_VIDEORAM 0xb8000 /* Port addresses for the CRT controller */ #define CRT_CONTROL_ADDR 0x3d4 #define CRT_CONTROL_DATA 0x3d5 /* Addresses we can pass to the CRT_CONTROLL_ADDR port */ #define CURSOR_HIGH 0x0e #define CURSOR_LOW 0x0f /* Right now, we shouldn't need cursor high to change from zero */ /* Default attribs */ #define DEFAULT_ATTRIB 0x0F /* This is basically a "logic-free" file - it interfaces directly with the * hardware, but higher-level terminal output logic will be dealt with elsewhere * */ static uint16_t *videoram; /* Needs to get a virtual memory mapping for video memory */ void screen_init() { videoram = (uint16_t *) pt_phys_perm_map(PHYS_VIDEORAM, 1); } /* Copied from OSDev */ void screen_move_cursor(uint8_t x, uint8_t y) { /* Commented out until we have kasserts */ /* KASSERT(cursor_col < DISPLAY_WIDTH && cursor_row < DISPLAY_HEIGHT); */ uint16_t pos = y * DISPLAY_WIDTH + x; outb(CRT_CONTROL_ADDR, CURSOR_HIGH); outb(CRT_CONTROL_DATA, pos >> 8); /* Output address being modified */ outb(CRT_CONTROL_ADDR, CURSOR_LOW); /* New position of cursor */ outb(CRT_CONTROL_DATA, pos & 0xff); } void screen_putchar(char c, uint8_t x, uint8_t y) { /* Update the character at the current cursor position, using the default * attributes */ *(videoram + (y * DISPLAY_WIDTH + x)) = (DEFAULT_ATTRIB << 8) | c; } void screen_putchar_attrib(char c, uint8_t x, uint8_t y, uint8_t attrib) { /* Similarly, but with custom attributes */ *(videoram + (y * DISPLAY_WIDTH + x)) = (attrib << 8) | c; } void screen_putbuf(const char *buf) { uint16_t *pos; for (pos = videoram; pos - videoram < DISPLAY_WIDTH * DISPLAY_HEIGHT; buf++, pos++) *pos = (DEFAULT_ATTRIB << 8) | *buf; } /* In theory, this one should be much faster, but it probably isn't */ void screen_putbuf_attrib(const uint16_t *buf) { memcpy(videoram, buf, DISPLAY_WIDTH * DISPLAY_HEIGHT * 2); } void screen_clear() { /* Attributes: 0x0F (white on black) with character 0x20 (space) */ /* Note that using a null character instead of a space is OK, but we can't * use a memcpy b/c attribute 0x00 is black on black (which messes up the * attribute settings . . . ) */ uint16_t blank = (DEFAULT_ATTRIB << 8) | 0x20; uint16_t *pos; for (pos = videoram; pos - videoram < DISPLAY_WIDTH * DISPLAY_HEIGHT; pos++) *pos = blank; } <file_sep>/kernel/include/api/access.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #include "types.h" struct proc; struct argstr; struct argvec; int copy_from_user(void *kaddr, const void *uaddr, size_t nbytes); int copy_to_user(void *uaddr, const void *kaddr, size_t nbytes); char *user_strdup(struct argstr *ustr); char **user_vecdup(struct argvec *uvec); int range_perm(struct proc *p, const void *vaddr, size_t len, int perm); int addr_perm(struct proc *p, const void *vaddr, int perm); <file_sep>/kernel/include/fs/vfs_syscall.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #include "dirent.h" #include "types.h" #include "fs/open.h" #include "fs/stat.h" int do_close(int fd); int do_read(int fd, void *buf, size_t nbytes); int do_write(int fd, const void *buf, size_t nbytes); int do_dup(int fd); int do_dup2(int ofd, int nfd); int do_mknod(const char *path, int mode, unsigned devid); int do_mkdir(const char *path); int do_rmdir(const char *path); int do_unlink(const char *path); int do_link(const char *from, const char *to); int do_rename(const char *oldname, const char *newname); int do_chdir(const char *path); int do_getdent(int fd, struct dirent *dirp); int do_lseek(int fd, int offset, int whence); int do_stat(const char *path, struct stat *uf); #ifdef __MOUNTING__ /* for mounting implementations only, not required */ int do_mount(const char *source, const char *target, const char *type); int do_umount(const char *target); #endif <file_sep>/kernel/include/proc/sched.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #include "util/list.h" struct kthread; typedef struct ktqueue { list_t tq_list; int tq_size; } ktqueue_t; /** * Switches execution between kernel threads. */ void sched_switch(void); /** * Marks the given thread as runnable, and adds it to the run queue. * * @param thr the thread to make runnable */ void sched_make_runnable(struct kthread *kt); /** * Initializes a queue. * * @param q the queue */ void sched_queue_init(ktqueue_t *q); /** * Returns true if the queue is empty. * * @param q the queue * @return true if the queue is empty */ int sched_queue_empty(ktqueue_t *q); /** * Causes the current thread to enter into an uncancellable sleep on * the given queue. * * @param q the queue to sleep on */ void sched_sleep_on(ktqueue_t *q); /** * Causes the current thread to enter into a cancellable sleep on the * given queue. * * @param q the queue to sleep on * @return -EINTR if the thread was cancelled and 0 otherwise */ int sched_cancellable_sleep_on(ktqueue_t *q); /** * Wakes a single thread from sleep if there are any waiting on the * queue. * * @param q the q to wakeup a thread from * @return NULL if q is empty and a thread waiting on the q otherwise */ struct kthread *sched_wakeup_on(ktqueue_t *q); /** * Wake up all threads running on the queue. * * @param q the queue to wake up threads from */ void sched_broadcast_on(ktqueue_t *q); /** * Cancel the given thread from the queue it sleeps on. * * @param the thread to cancel sleep from */ void sched_cancel(struct kthread *kthr); <file_sep>/kernel/include/fs/dirent.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ /* dirent.h - filesystem-independent directory entry * mcc, kma, jal */ #pragma once /* Kernel and user header (via symlink) */ #ifdef __KERNEL__ #include "config.h" #else #include "weenix/config.h" #endif typedef struct dirent { ino_t d_ino; /* entry inode number */ off_t d_off; /* seek pointer of next entry */ char d_name[NAME_LEN + 1]; /* filename */ } dirent_t; #define d_fileno d_ino <file_sep>/kernel/proc/sunghan_test.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ /* * Author: <NAME> <<EMAIL>> * * BC: You must NOT change this file. If you submit a modified version * of this file, it will be deleted from your submission. */ #include "kernel.h" #include "globals.h" #include "util/debug.h" #include "util/list.h" #include "util/string.h" #include "util/printf.h" #include "proc/kthread.h" #include "proc/proc.h" #include "proc/sched.h" #include "proc/proc.h" #include "proc/kmutex.h" typedef struct my_node { int length; kmutex_t my_mutex; ktqueue_t my_queue; } my_node_t; static my_node_t mynode; static int rand_x = 200, rand_y = 50, rand_z = 3000; static int random_function() { rand_x = ( rand_x * 171 ) % 30269; rand_y = ( rand_y * 172 ) % 30307; rand_z = ( rand_z * 170 ) % 30323; float n = ((((float)rand_x)/30269.0) + (((float)rand_y)/30307.0) + (((float)rand_z)/30323.0)) * 100; return n; } void check_sleep(char *str) { if (random_function() % 10 < 5) { dbg(DBG_TEST, "Thread %s goes to sleep\n", str); sched_broadcast_on(&mynode.my_queue); sched_sleep_on(&mynode.my_queue); dbg(DBG_TEST, "Thread %s awake\n", str); } } static void * add_my_node(int arg1, void *arg2) { int counter = 10; dbg(DBG_TEST, "Invoke add_mynode\n"); int rand_number, i=0; while (counter > 0) { check_sleep("add"); kmutex_lock(&mynode.my_mutex); check_sleep("add"); if (mynode.length < 5) { mynode.length++; counter--; } dbg(DBG_TEST, "Add node: %d\n", mynode.length); kmutex_unlock(&mynode.my_mutex); } return NULL; } static void * remove_my_node(int arg1, void *arg2) { int counter = 10; dbg(DBG_TEST, "Invoke remove_mynode\n"); int rand_number, i=0; while (counter > 0) { check_sleep("remove"); kmutex_lock(&mynode.my_mutex); check_sleep("remove"); if (mynode.length > 0) { mynode.length--; counter--; } dbg(DBG_TEST, "Remove node: %d\n", mynode.length); kmutex_unlock(&mynode.my_mutex); } return NULL; } static void * watch_dog(int arg1, void *arg2) { while(!sched_queue_empty(&mynode.my_queue)) { dbg(DBG_TEST, "Watch_dog wake up all sleeping thread\n"); sched_broadcast_on(&mynode.my_queue); sched_sleep_on(&mynode.my_queue); } return NULL; } void * sunghan_test(int arg1, void *arg2) { int status; int proc_count = 0; pid_t proc_pid[3]; int i; dbg(DBG_TEST, ">>> Start running sunghan_test()...\n"); mynode.length = 0; kmutex_init(&mynode.my_mutex); sched_queue_init(&mynode.my_queue); proc_t *p1 = proc_create("add_node"); KASSERT(NULL != p1); kthread_t *thr1 = kthread_create(p1, add_my_node, 0, NULL); KASSERT(NULL != thr1); sched_make_runnable(thr1); proc_pid[proc_count++] = p1->p_pid; proc_t *p2 = proc_create("remove_node"); KASSERT(NULL != p2); kthread_t *thr2 = kthread_create(p2, remove_my_node, 0, NULL); KASSERT(NULL != thr2); sched_make_runnable(thr2); proc_pid[proc_count++] = p2->p_pid; proc_t *p3 = proc_create("watch_dog"); KASSERT(NULL != p3); kthread_t *thr3 = kthread_create(p3, watch_dog, 0, NULL); KASSERT(NULL != thr3); sched_make_runnable(thr3); proc_pid[proc_count++] = p3->p_pid; for (i=0; i<2; ++i) { do_waitpid(proc_pid[i], 0, &status); } sched_broadcast_on(&mynode.my_queue); do_waitpid(proc_pid[2], 0, &status); while (!do_waitpid(p2->p_pid, 0, &status)); dbg(DBG_TEST, "sunghan_test() terminated\n"); return NULL; } void * sunghan_deadlock_test(int arg1, void *arg2) { int status; int proc_count = 0; pid_t proc_pid[3]; int i; dbg(DBG_TEST, ">>> Start running sunghan_deadlock_test()...\n"); mynode.length = 0; kmutex_init(&mynode.my_mutex); sched_queue_init(&mynode.my_queue); proc_t *p1 = proc_create("add_node"); KASSERT(NULL != p1); kthread_t *thr1 = kthread_create(p1, add_my_node, 0, NULL); KASSERT(NULL != thr1); sched_make_runnable(thr1); proc_pid[proc_count++] = p1->p_pid; proc_t *p2 = proc_create("remove_node"); KASSERT(NULL != p2); kthread_t *thr2 = kthread_create(p2, remove_my_node, 0, NULL); KASSERT(NULL != thr2); sched_make_runnable(thr2); proc_pid[proc_count++] = p2->p_pid; for (i=0; i<2; ++i) { do_waitpid(proc_pid[i], 0, &status); } sched_broadcast_on(&mynode.my_queue); dbg(DBG_TEST, "Shouldn't have gotten here in sunghan_deadlock_test(). Did NOT deadlock.\n"); return NULL; } <file_sep>/kernel/include/fs/fcntl.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ /* fcntl.h - File access bits * mcc, jal */ #pragma once /* Kernel and user header (via symlink) */ /* File access modes for open(). */ #define O_RDONLY 0 #define O_WRONLY 1 #define O_RDWR 2 /* File status flags for open(). */ #define O_CREAT 0x100 /* Create file if non-existent. */ #define O_TRUNC 0x200 /* Truncate to zero length. */ #define O_APPEND 0x400 /* Append to file. */ <file_sep>/kernel/drivers/tty/tty.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "drivers/tty/tty.h" #include "drivers/bytedev.h" #include "drivers/tty/driver.h" #include "drivers/tty/keyboard.h" #include "drivers/tty/ldisc.h" #include "drivers/tty/n_tty.h" #include "drivers/tty/screen.h" #include "drivers/tty/virtterm.h" #include "mm/kmalloc.h" #include "util/debug.h" #define bd_to_tty(bd) \ CONTAINER_OF(bd, tty_device_t, tty_cdev) /** * The callback function called by the virtual terminal subsystem when * a key is pressed. * * @param arg a pointer to the tty attached to the virtual terminal * which received the key press= * @param c the character received */ static void tty_global_driver_callback(void *arg, char c); /** * Reads a specified maximum number of bytes from a tty into a given * buffer. * * @param dev the tty to read from * @param offset this parameter is ignored in this function * @param buf the buffer to read into * @param count the maximum number of bytes to read * @return the number of bytes read into buf */ static int tty_read(bytedev_t *dev, int offset, void *buf, int count); /** * Writes a specified maximum number of bytes from a given buffer into * a tty. * * @param dev the tty to write to * @param offset this parameter is ignored in this function * @param buf the buffer to read from * @param count the maximum number of bytes to write * @return the number of bytes written */ static int tty_write(bytedev_t *dev, int offset, const void *buf, int count); /** * Echoes out to the tty driver. * * @param driver the tty driver to echo to * @param out the string to echo */ static void tty_echo(tty_driver_t *driver, const char *out); static bytedev_ops_t tty_bytedev_ops = { tty_read, tty_write, NULL, NULL, NULL, NULL }; void tty_init() { screen_init(); vt_init(); keyboard_init(); /* * Create NTERMS tty's, all with the default line discipline * and a virtual terminal driver. */ int nterms, i; nterms = vt_num_terminals(); for (i = 0; i < nterms; ++i) { tty_driver_t *ttyd; tty_device_t *tty; tty_ldisc_t *ldisc; ttyd = vt_get_tty_driver(i); KASSERT(NULL != ttyd); KASSERT(NULL != ttyd->ttd_ops); KASSERT(NULL != ttyd->ttd_ops->register_callback_handler); tty = tty_create(ttyd, i); if (NULL == tty) { panic("Not enough memory to allocate tty\n"); } if (NULL != ttyd->ttd_ops->register_callback_handler( ttyd, tty_global_driver_callback, (void *)tty)) { panic("Callback already registered " "to terminal %d\n", i); } ldisc = n_tty_create(); if (NULL == ldisc) { panic("Not enough memory to allocate " "line discipline\n"); } KASSERT(NULL != ldisc); KASSERT(NULL != ldisc->ld_ops); KASSERT(NULL != ldisc->ld_ops->attach); ldisc->ld_ops->attach(ldisc, tty); if (bytedev_register(&tty->tty_cdev) != 0) { panic("Error registering tty as byte device\n"); } } } /* * Initialize a tty device. The driver should not be NULL, but we don't * need a line descriptor yet. To initialize the byte device in the tty * struct, use the MKDEVID macro and the correct byte device function * table for a tty. */ tty_device_t * tty_create(tty_driver_t *driver, int id) { NOT_YET_IMPLEMENTED("DRIVERS: tty_create"); return 0; } /* * This is the function called by the virtual terminal subsystem when * a key is pressed. * * The first thing you should do is to pass the character to the line * discipline. This way, the character will be buffered, so that when * the read system call is made, an entire line will be returned, * rather than just a single character. * * After passing the character off to the line discipline, the result * of receive_char() should be echoed to the screen using the * tty_echo() function. */ void tty_global_driver_callback(void *arg, char c) { NOT_YET_IMPLEMENTED("DRIVERS: tty_global_driver_callback"); } /* * You should use the driver's provide_char function to output * each character of the string 'out'. */ void tty_echo(tty_driver_t *driver, const char *out) { NOT_YET_IMPLEMENTED("DRIVERS: tty_echo"); } /* * In this function, you should block I/O, call the line discipline, * and unblock I/O. We do not want to receive interrupts while * modifying the input buffer. */ int tty_read(bytedev_t *dev, int offset, void *buf, int count) { NOT_YET_IMPLEMENTED("DRIVERS: tty_read"); return 0; } /* * In this function, you should block I/O, process each * character with the line discipline and output the result to * the driver, and then unblock I/O. * * Important: You should return the number of bytes processed, * _NOT_ the number of bytes written out to the driver. */ int tty_write(bytedev_t *dev, int offset, const void *buf, int count) { NOT_YET_IMPLEMENTED("DRIVERS: tty_write"); return 0; } <file_sep>/Makefile .PHONY: all clean all_kernel all_user clean_kernel clean_user nyi all: all_kernel all_user all_kernel: @ cd kernel && $(MAKE) all all_user: @ cd user && $(MAKE) all clean: clean_kernel clean_user clean_kernel: @ cd kernel && $(MAKE) clean clean_user: @ cd user && $(MAKE) clean nyi: @ cd kernel && $(MAKE) nyi procs-submit: tar cvzf procs-submit.tar.gz \ Config.mk \ procs-README.txt \ kernel/main/kmain.c \ kernel/proc/kmutex.c \ kernel/proc/kthread.c \ kernel/proc/proc.c \ kernel/proc/sched.c vfs-submit: tar cvzf vfs-submit.tar.gz \ Config.mk \ vfs-README.txt \ kernel/main/kmain.c \ kernel/proc/kmutex.c \ kernel/proc/kthread.c \ kernel/proc/proc.c \ kernel/proc/sched.c \ kernel/fs/namev.c \ kernel/fs/open.c \ kernel/fs/vfs_syscall.c \ kernel/fs/vnode.c vm-submit: tar cvzf vm-submit.tar.gz \ Config.mk \ vm-README.txt \ kernel/main/kmain.c \ kernel/proc/kmutex.c \ kernel/proc/kthread.c \ kernel/proc/proc.c \ kernel/proc/sched.c \ kernel/fs/namev.c \ kernel/fs/open.c \ kernel/fs/vfs_syscall.c \ kernel/fs/vnode.c \ kernel/mm/pframe.c \ kernel/api/access.c \ kernel/api/syscall.c \ kernel/proc/fork.c \ kernel/vm/anon.c \ kernel/vm/brk.c \ kernel/vm/mmap.c \ kernel/vm/pagefault.c \ kernel/vm/shadow.c \ kernel/vm/vmmap.c <file_sep>/kernel/boot/stdio.h #ifndef __STDIO_H__ #define __STDIO_H__ puts16: pusha /* save registers */ mov $0x00, %bh mov $0x07, %bl 1: lodsb /* load next byte from si into al and increment si */ or %al, %al /* is al 0? (null terminator) */ jz 1f /* null terminated, exit now */ mov $0x0e, %ah /* int 0x10 function 0x0e prints character */ int $0x10 jmp 1b /* repeat until null terminator found */ 1: popa /* restore registers */ ret #endif /* __STDIO_H__ */ <file_sep>/user/usr/bin/fork-and-wait.c /* * Does the basic fork and wait to make sure that the * fork and waitpid system calls are working correctly. */ #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> int Data = 0x017; int main(int argc, char **argv) { pid_t pid; char buf[80]; open("/dev/tty0", O_RDONLY, 0); open("/dev/tty0", O_WRONLY, 0); sprintf(buf, "(Before fork(), Data should be 0x17) Data = 0x%08x\n", Data); write(1, buf, strlen(buf)); write(1, "Ready to fork()...\n", 19); pid = fork(); if (pid == 0) { Data = 0x0129e; sprintf(buf, "(Child, Data should be 0x129e) Data = 0x%08x\n", Data); write(1, buf, strlen(buf)); write(1, "(Child) Hello, world!\n", 22); exit(0); } else if (pid == (pid_t)(-1)) { write(1, "fork() failed.\n", 15); } else { Data = 0x0b38e; sprintf(buf, "(Parent, Data should be 0xb38e) Data = 0x%08x\n", Data); write(1, buf, strlen(buf)); write(1, "(Parent) Calling waitpid()...\n", 30); waitpid(pid, 0, NULL); write(1, "(Parent) waitpid() returned successfully.\n", 42); } return 0; } <file_sep>/kernel/include/mm/tlb.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #include "kernel.h" #include "types.h" #include "mm/page.h" /* Invalidates any entries from the TLB which contain * mappings for the given virtual address. */ static inline void tlb_flush(uintptr_t vaddr) { __asm__ volatile("invlpg (%0)" :: "r"(vaddr)); } /* Invalidates any entries for the count virtual addresses * starting at vaddr from the TLB. If this range is very * large it may be more efficient to call tlb_flush_all * to invalidate the entire TLB. */ static inline void tlb_flush_range(uintptr_t vaddr, uint32_t count) { uint32_t i; for (i = 0; i < count; ++i, vaddr += PAGE_SIZE) { tlb_flush(vaddr); } } /* Invalidates the entire TLB. */ static inline void tlb_flush_all() { uintptr_t pdir; __asm__ volatile("movl %%cr3, %0" : "=r"(pdir)); __asm__ volatile("movl %0, %%cr3" :: "r"(pdir) : "memory"); } <file_sep>/kernel/drivers/tty/keyboard.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "drivers/tty/keyboard.h" #include "drivers/tty/tty.h" #include "drivers/tty/virtterm.h" #include "main/io.h" #include "main/interrupt.h" #include "util/debug.h" #define IRQ_KEYBOARD 1 /* Indicates that one of these is "being held down" */ #define SHIFT_MASK 0x1 #define CTRL_MASK 0x2 /* Indicates that an escape code was the previous key received */ #define ESC_MASK 0x4 static int curmask = 0; /* Where to read from to get scancodes */ #define KEYBOARD_IN_PORT 0x60 #define KEYBOARD_CMD_PORT 0x61 /* Scancodes for special keys */ #define LSHIFT 0x2a #define RSHIFT 0x36 #define CTRL 0x1d /* Right ctrl is escaped */ /* Our keyboard driver totally ignores ALT */ #define ESC0 0xe0 #define ESC1 0xe1 /* Special stuff for scrolling (note that these only work when ctrl is held) */ #define SCROLL_UP 0x0e #define SCROLL_DOWN 0x1c /* Keys for switching virtual terminals - for now F1,F2,...,F10 */ #define VT_KEY_LOW 0x3b #define VT_KEY_HIGH 0x44 /* If the scancode & BREAK_MASK, it's a break code; otherwise, it's a make code */ #define BREAK_MASK 0x80 #define NORMAL_KEY_HIGH 0x39 /* Some sneaky value to indicate we don't actually pass anything to the terminal */ #define NO_CHAR 0xff /* Scancode tables copied from http://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html */ /* The scancode table for "normal" scancodes - from 02 to 39 */ /* Unsupported chars are symbolized by \0 */ static const char *normal_scancodes = "\0" /* Error */ "\e" /* Escape key */ "1234567890-=" /* Top row */ "\b" /* Backspace */ "\tqwertyuiop[]\n" /* Next row - ish */ "\0" /* Left ctrl */ "asdfghjkl;\'`" "\0" /* Lshift */ "\\" "zxcvbnm,./" "\0\0\0" /* Rshift, prtscrn, Lalt */ " "; /* Space bar */ /* As above, but if shift is pressed */ static const char *shift_scancodes = "\0" "\e" "!@#$%^&*()_+" "\b" "\tQWERTYUIOP{}\n" "\0" "ASDFGHJKL:\"~" "\0" "|" "ZXCVBNM<>?" "\0\0\0" " "; static keyboard_char_handler_t keyboard_handler = NULL; /* This is the function we register with the interrupt handler - it reads the * scancode and, if appropriate, call's the tty's receive_char function */ static void keyboard_intr_handler(regs_t *regs) { uint8_t sc; /* The scancode we receive */ int break_code; /* Was it a break code */ /* the resulting character ('\0' -> ignored char) */ uint8_t c = NO_CHAR; /* Get the scancode */ sc = inb(KEYBOARD_IN_PORT); /* Separate out the break code */ break_code = sc & BREAK_MASK; sc &= ~BREAK_MASK; /* dbg(DBG_KB, ("scancode 0x%x, break 0x%x\n", sc, break_code)); */ /* The order of this conditional is very, very tricky - be careful when * editing! */ /* Most break codes are ignored */ if (break_code) { /* Shift/ctrl release */ if (sc == LSHIFT || sc == RSHIFT) curmask &= ~SHIFT_MASK; else if (sc == CTRL) curmask &= ~CTRL_MASK; } /* Check for the special keys */ else if (sc == LSHIFT || sc == RSHIFT) { curmask |= SHIFT_MASK; } else if (sc == CTRL) { curmask |= CTRL_MASK; } /* All escaped keys past this point (anything except right shift and right * ctrl) will be ignored */ else if (curmask & ESC_MASK) { /* Escape mask only lasts for one key */ curmask &= ~ESC_MASK; } /* Now check for escape code */ else if (sc == ESC0 || sc == ESC1) { curmask |= ESC_MASK; } /* Check for Ctrl+Fn key which indicates virt term switch */ else if (sc >= VT_KEY_LOW && sc <= VT_KEY_HIGH) { vt_switch(sc - VT_KEY_LOW); } /* Check for Ctrl+Backspace which indicates scroll down */ else if ((curmask & CTRL_MASK) && sc == SCROLL_DOWN) { vt_scroll(DISPLAY_HEIGHT, 0); } /* Check for Ctrl+Enter which indicates scroll down */ else if ((curmask & CTRL_MASK) && sc == SCROLL_UP) { vt_scroll(DISPLAY_HEIGHT, 1); } /* Check to make sure the key isn't high enough that it won't be found in * tables */ else if (sc > NORMAL_KEY_HIGH) { /* ignore */ } /* Control characters */ else if (curmask & CTRL_MASK) { /* Because of the way ASCII works, the control chars are based on the * values of the shifted chars produced without control */ c = shift_scancodes[sc]; /* Range of chars that have corresponding control chars */ if (c >= 0x40 && c < 0x60) c -= 0x40; else c = NO_CHAR; } /* Capitals */ else if (curmask & SHIFT_MASK) { c = shift_scancodes[sc]; } else { c = normal_scancodes[sc]; } /* Give the key to the vt system, which passes it to the tty */ if (c != NO_CHAR && keyboard_handler) { keyboard_handler(c); } } void keyboard_init() { intr_map(IRQ_KEYBOARD, INTR_KEYBOARD); intr_register(INTR_KEYBOARD, keyboard_intr_handler); } void keyboard_register_handler(keyboard_char_handler_t handler) { keyboard_handler = handler; } <file_sep>/kernel/include/main/io.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #include "kernel.h" #include "types.h" static inline void outb(uint16_t port, uint8_t val) { __asm__ volatile("outb %0,%1" :: "a"(val), "Nd"(port)); } static inline uint8_t inb(uint16_t port) { uint8_t ret; __asm__ volatile("inb %1,%0" : "=a"(ret) : "Nd"(port)); return ret; } static inline void outw(uint16_t port, uint16_t val) { __asm__ volatile("outw %0,%1" :: "a"(val), "Nd"(port)); } static inline uint16_t inw(uint16_t port) { uint16_t ret; __asm__ volatile("inw %1,%0" : "=a"(ret) : "Nd"(port)); return ret; } static inline void outl(uint16_t port, uint32_t val) { __asm__ volatile("outl %0,%1" :: "a"(val), "Nd"(port)); } static inline uint32_t inl(uint16_t port) { uint32_t ret; __asm__ volatile("inl %1,%0" : "=a"(ret) : "Nd"(port)); return ret; } <file_sep>/kernel/proc/faber_test.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ /* * Author: <NAME> <<EMAIL>> * With modifications by: <NAME> <<EMAIL>> * * BC: You must NOT change this file. If you submit a modified version * of this file, it will be deleted from your submission. */ #include "kernel.h" #include "config.h" #include "globals.h" #include "errno.h" #include "util/debug.h" #include "util/list.h" #include "util/string.h" #include "util/printf.h" #include "proc/kthread.h" #include "proc/proc.h" #include "proc/sched.h" #include "proc/proc.h" #include "proc/kmutex.h" #include "mm/slab.h" #include "mm/page.h" #include "mm/mmobj.h" #include "mm/mm.h" #include "mm/mman.h" ktqueue_t wake_me_q; int wake_me_len = 0; int race=0; kmutex_t mutex; typedef struct { struct proc *p; struct kthread *t; } proc_thread_t; /* * Create a process and a thread with the given name and calling teh given * function. Arg1 is passed to the function (arg2 is always NULL). The thread * is immediately placed on the run queue. A proc_thread_t is returned, giving * the caller a pointer to the new process and thread to coordinate tests. NB, * the proc_thread_t is returned by value, so there are no stack problems. */ static void start_proc(proc_thread_t *ppt, char *name, kthread_func_t f, int arg1) { proc_thread_t pt; pt.p = proc_create(name); pt.t = kthread_create(pt.p, f, arg1, NULL); KASSERT(pt.p && pt.t && "Cannot create thread or process"); sched_make_runnable(pt.t); if (ppt != NULL) { memcpy(ppt, &pt, sizeof(proc_thread_t)); } } /** * Call do_waitpid with the process ID of the given process. Print a debug * message with the exiting process's status. */ static void wait_for_proc(proc_t *p) { int rv; pid_t pid; char pname[PROC_NAME_LEN]; strncpy(pname, p->p_comm, PROC_NAME_LEN); pname[PROC_NAME_LEN-1] = '\0'; pid = do_waitpid(p->p_pid, 0, &rv); dbg(DBG_TEST, "%s (%d) exited: %d\n", pname, pid, rv); } /** * Call waitpid with a -1 pid and print a message about any process that exits. * Returns the pid found, including -ECHILD when this process has no children. */ static pid_t wait_for_any() { int rv; pid_t pid; pid = do_waitpid(-1, 0, &rv); if ( pid != -ECHILD) dbg(DBG_TEST, "child (%d) exited: %d\n", pid, rv); return pid; } /* * Repeatedly call wait_for_any() until it returns -ECHILD */ static void wait_for_all() { while (wait_for_any() != -ECHILD) ; } /* * Keep context switching until *count >= tot. Used to count the number of * nodes waiting for the kernel thread queue. */ static void stop_until_queued(int tot, int *count) { while ( *count < tot) { sched_make_runnable(curthr); sched_switch(); } } /* * Keep context switching until *count == 0. Used to count the number of * nodes waiting for the kernel thread queue. */ static void stop_until_zero(int *count) { while ( *count > 0) { sched_make_runnable(curthr); sched_switch(); } } /* * A thread function that simply calls do_exit() with status arg1 */ void *waitpid_test(int arg1, void *arg2) { do_exit(arg1); return NULL; } /* * A thread function that returns NULL, silently invoking kthread_exit() */ void *kthread_exit_test(int arg1, void *arg2) { return NULL; } /* * A thread function that waits on wake_me_q and exist when released. If it is * cancelled, it prints an error message. */ void *wakeme_test(int arg1, void *arg2) { wake_me_len++; if (sched_cancellable_sleep_on(&wake_me_q) == -EINTR ) { dbg(DBG_TEST, "Wakeme cancelled?! pid (%d)\n", curproc->p_pid); wake_me_len--; do_exit(-1); } wake_me_len--; do_exit(arg1); return NULL; } /* * A thread function that uncancellably waits on wake_me_q and exist when * released. */ void *wakeme_uncancellable_test(int arg1, void *arg2) { wake_me_len++; sched_sleep_on(&wake_me_q); wake_me_len--; do_exit(arg1); return NULL; } /* * A thread function that waits on wake_me_q and exist when released. If it is * not cancelled, it prints an error message. */ void *cancelme_test(int arg1, void *arg2) { wake_me_len++; if (sched_cancellable_sleep_on(&wake_me_q) != -EINTR ) { dbg(DBG_TEST, "Wakeme returned?! pid (%d)\n", curproc->p_pid); wake_me_len--; do_exit(-1); } wake_me_len--; do_exit(arg1); return NULL; } /* * A Thread function that exhibits a race condition on the race global. It * loads increments and stores race, context switching between each line of C. */ void *racer_test(int arg1, void *arg2) { int local; sched_make_runnable(curthr); sched_switch(); local = race; sched_make_runnable(curthr); sched_switch(); local++; sched_make_runnable(curthr); sched_switch(); race = local; sched_make_runnable(curthr); sched_switch(); do_exit(race); return NULL; } /* * A Thread function that exhibits a race condition on the race global being * removed by a mutex. It loads increments and stores race, context switching * between each line of C after acquiring mutex. The mutex acquire cannot * be cancelled. */ void *mutex_uncancellable_test(int arg1, void *arg2) { int local; kmutex_lock(&mutex); sched_make_runnable(curthr); sched_switch(); local = race; sched_make_runnable(curthr); sched_switch(); local++; sched_make_runnable(curthr); sched_switch(); race = local; sched_make_runnable(curthr); sched_switch(); kmutex_unlock(&mutex); do_exit(race); return NULL; } /* * A Thread function that exhibits a race condition on the race global being * removed by a mutex. It loads increments and stores race, context switching * between each line of C after acquiring mutex. The mutex acquire can * be cancelled, but will print an error message if this happens. */ void *mutex_test(int arg1, void *arg2) { int local; if ( kmutex_lock_cancellable(&mutex) ) { dbg(DBG_TEST, "Mutex cancelled? %d", curproc->p_pid); do_exit(-1); } sched_make_runnable(curthr); sched_switch(); local = race; sched_make_runnable(curthr); sched_switch(); local++; sched_make_runnable(curthr); sched_switch(); race = local; sched_make_runnable(curthr); sched_switch(); kmutex_unlock(&mutex); do_exit(race); return NULL; } /* * A Thread function that exhibits a race condition on the race global being * removed by a mutex. It loads increments and stores race, context switching * between each line of C after acquiring mutex. The mutex acquire can * be cancelled, but will print an error message if the mutex acquire succeeds * - it expects to be cancelled. */ void *mutex_test_cancelme(int arg1, void *arg2) { int local; if ( kmutex_lock_cancellable(&mutex) ) do_exit(0); dbg(DBG_TEST, "Mutex not cancelled? %d", curproc->p_pid); sched_make_runnable(curthr); sched_switch(); local = race; sched_make_runnable(curthr); sched_switch(); local++; sched_make_runnable(curthr); sched_switch(); race = local; sched_make_runnable(curthr); sched_switch(); kmutex_unlock(&mutex); do_exit(race); return NULL; } /* * A thread function to test reparenting. Start a child wakeme_test process, * and if arg1 is > 1, create a child process that will do the same (with arg1 * decrementd. Calling this with arg1 results in 2 * arg1 processes, half of * them waiting on wake_me_q. None of them wait, so as they exit, they should * all become children of init. */ void *reparent_test(int arg1, void *arg2) { start_proc(NULL, "reparented" , wakeme_test, arg1); if ( arg1 > 1 ) start_proc(NULL, "reparent ", reparent_test, arg1-1); do_exit(0); return NULL; } /* * The core thread test code. * This function is meant to be invoked in a separate kernel process. */ void *faber_thread_test(int arg1, void *arg2) { proc_thread_t pt; pid_t pid = -1; proc_t *p; int rv = 0; int i = 0; dbg(DBG_TEST, ">>> Start running faber_thread_test()...\n"); #if CS402TESTS > 0 dbg(DBG_TEST, "waitpid any test\n"); start_proc(&pt, "waitpid any test", waitpid_test, 23); wait_for_any(); dbg(DBG_TEST, "waitpid test\n"); start_proc(&pt, "waitpid test", waitpid_test, 32); pid = do_waitpid(2323, 0, &rv); if ( pid != -ECHILD ) dbg(DBG_TEST, "Allowed wait on non-existent pid\n"); wait_for_proc(pt.p); dbg(DBG_TEST, "kthread exit test\n"); start_proc(&pt, "kthread exit test", kthread_exit_test, 0); wait_for_proc(pt.p); dbg(DBG_TEST, "many test\n"); for (i = 0; i < 10; i++) start_proc(NULL, "many test", waitpid_test, i); wait_for_all(); dbg(DBG_TEST, "(C.1) done\n"); #endif #if CS402TESTS > 1 dbg(DBG_TEST, "Context switch test\n"); start_proc(&pt, "Context switch", racer_test, 0); wait_for_proc(pt.p); dbg(DBG_TEST, "(C.2) done\n"); #endif #if CS402TESTS > 2 sched_queue_init(&wake_me_q); dbg(DBG_TEST, "wake me test\n"); wake_me_len = 0; start_proc(&pt, "wake me test", wakeme_test, 0); /* Make sure p has blocked */ stop_until_queued(1, &wake_me_len); sched_wakeup_on(&wake_me_q); wait_for_proc(pt.p); KASSERT(wake_me_len == 0 && "Error on wakeme bookkeeping"); dbg(DBG_TEST, "broadcast me test\n"); for (i = 0; i < 10; i++ ) start_proc(NULL, "broadcast me test", wakeme_test, 0); stop_until_queued(10, &wake_me_len); /* Make sure the processes have blocked */ sched_broadcast_on(&wake_me_q); wait_for_all(); KASSERT(wake_me_len == 0 && "Error on wakeme bookkeeping"); dbg(DBG_TEST, "(C.3) done\n"); #endif #if CS402TESTS > 3 dbg(DBG_TEST, "wake me uncancellable test\n"); start_proc(&pt, "wake me uncancellable test", wakeme_uncancellable_test, 0); /* Make sure p has blocked */ stop_until_queued(1, &wake_me_len); sched_wakeup_on(&wake_me_q); wait_for_proc(pt.p); KASSERT(wake_me_len == 0 && "Error on wakeme bookkeeping"); dbg(DBG_TEST, "broadcast me uncancellable test\n"); for (i = 0; i < 10; i++ ) start_proc(NULL, "broadcast me uncancellable test", wakeme_uncancellable_test, 0); /* Make sure the processes have blocked */ stop_until_queued(10, &wake_me_len); sched_broadcast_on(&wake_me_q); wait_for_all(); KASSERT(wake_me_len == 0 && "Error on wakeme bookkeeping"); dbg(DBG_TEST, "(C.4) done\n"); #endif #if CS402TESTS > 4 dbg(DBG_TEST, "cancel me test\n"); start_proc(&pt, "cancel me test", cancelme_test, 0); /* Make sure p has blocked */ stop_until_queued(1, &wake_me_len); sched_cancel(pt.t); wait_for_proc(pt.p); KASSERT(wake_me_len == 0 && "Error on wakeme bookkeeping"); dbg(DBG_TEST, "prior cancel me test\n"); start_proc(&pt, "prior cancel me test", cancelme_test, 0); /* Cancel before sleep */ sched_cancel(pt.t); wait_for_proc(pt.p); KASSERT(wake_me_len == 0 && "Error on wakeme bookkeeping"); dbg(DBG_TEST, "cancel me head test\n"); start_proc(&pt, "cancel me head test", cancelme_test, 0); start_proc(NULL, "cancel me head test", wakeme_test, 0); stop_until_queued(2, &wake_me_len); sched_cancel(pt.t); sched_wakeup_on(&wake_me_q); wait_for_all(); KASSERT(wake_me_len == 0 && "Error on wakeme bookkeeping"); dbg(DBG_TEST, "cancel me tail test\n"); start_proc(NULL, "cancel me tail test", wakeme_test, 0); start_proc(&pt, "cancel me tail test", cancelme_test, 0); stop_until_queued(2, &wake_me_len); sched_cancel(pt.t); sched_wakeup_on(&wake_me_q); wait_for_all(); KASSERT(wake_me_len == 0 && "Error on wakeme bookkeeping"); dbg(DBG_TEST, "(C.5) done\n"); #endif #if CS402TESTS > 5 dbg(DBG_TEST, "Reparenting test\n"); start_proc(NULL, "Reparenting test", reparent_test, 1); stop_until_queued(1, &wake_me_len); sched_wakeup_on(&wake_me_q); wait_for_all(); stop_until_zero(&wake_me_len); dbg(DBG_TEST, "Reparenting stress test\n"); start_proc(NULL, "Reparenting stress test", reparent_test, 10); stop_until_queued(10, &wake_me_len); sched_broadcast_on(&wake_me_q); wait_for_all(); stop_until_zero(&wake_me_len); KASSERT(wake_me_len == 0 && "Error on wakeme bookkeeping"); dbg(DBG_TEST, "(C.6) done\n"); #endif #if CS402TESTS > 6 kmutex_init(&mutex); dbg(DBG_TEST, "show race test\n"); race = 0; for (i = 0; i < 10; i++ ) start_proc(NULL, "show race test", racer_test, 0); wait_for_all(); dbg(DBG_TEST, "fix race test\n"); race = 0; for (i = 0; i < 10; i++ ) start_proc(NULL, "fix race test", mutex_uncancellable_test, 0); wait_for_all(); dbg(DBG_TEST, "fix race test w/cancel\n"); race = 0; for (i = 0; i < 10; i++ ) { if ( i % 2 == 0) { start_proc(NULL, "fix race test w/cancel", mutex_test, 0); } else { start_proc(&pt, "fix race test w/cancel", mutex_test_cancelme, 0); sched_cancel(pt.t); } } wait_for_all(); dbg(DBG_TEST, "(C.7) done\n"); #endif #if CS402TESTS > 7 dbg(DBG_TEST, "kill child procs test\n"); for ( i=0 ; i < 10; i++ ) start_proc(NULL, "kill child procs test", cancelme_test, 0); stop_until_queued(10, &wake_me_len); list_iterate_begin(&curproc->p_children, p, proc_t, p_child_link) { proc_kill(p, -1); } list_iterate_end(); wait_for_all(); KASSERT(wake_me_len == 0 && "Error on wakeme bookkeeping"); dbg(DBG_TEST, "(C.8) done\n"); #endif #if CS402TESTS > 8 dbg(DBG_TEST, "proc kill all test\n"); for ( i=0 ; i < 10; i++ ) start_proc(NULL, "proc kill all test", cancelme_test, 0); stop_until_queued(10, &wake_me_len); /* * If you don't run this test in a separate process, * the kernel should shutdown and you would fail this test. * Therefore, you must run faber_thread_test() in a separate process, * since proc_kill_all() should not kill the init process, * although this function will not return, you should * be able to get your kshell prompt back. */ proc_kill_all(); dbg(DBG_TEST, "proc_kill_all() must not return\n\n"); KASSERT(0 && "Error in proc kill all test"); #endif return NULL; } <file_sep>/kernel/drivers/bytedev.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "kernel.h" #include "types.h" #include "util/debug.h" #include "drivers/bytedev.h" #include "util/list.h" #include "drivers/tty/tty.h" #include "drivers/memdevs.h" static list_t bytedevs; void bytedev_init() { list_init(&bytedevs); /* Initialize all subsystems */ tty_init(); memdevs_init(); } int bytedev_register(bytedev_t *dev) { bytedev_t *cd; /* Make sure dev, dev ops, and dev id not null */ if (!dev || (NULL_DEVID == dev->cd_id) || !(dev->cd_ops)) return -1; /* we should not have already seen dev->cd_id. */ list_iterate_begin(&bytedevs, cd, bytedev_t, cd_link) { if (dev->cd_id == cd->cd_id) return -1; } list_iterate_end(); /* initialize portions of structure ignored by device drivers: */ list_insert_tail(&bytedevs, &dev->cd_link); return 0; } bytedev_t * bytedev_lookup(devid_t id) { bytedev_t *cd; list_iterate_begin(&bytedevs, cd, bytedev_t, cd_link) { KASSERT(NULL_DEVID != cd->cd_id); if (id == cd->cd_id) return cd; } list_iterate_end(); return NULL; } <file_sep>/kernel/drivers/tty/n_tty.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "drivers/tty/n_tty.h" #include "errno.h" #include "drivers/tty/driver.h" #include "drivers/tty/ldisc.h" #include "drivers/tty/tty.h" #include "mm/kmalloc.h" #include "proc/kthread.h" #include "util/debug.h" /* helpful macros */ #define EOFC '\x4' #define TTY_BUF_SIZE 128 #define ldisc_to_ntty(ldisc) \ CONTAINER_OF(ldisc, n_tty_t, ntty_ldisc) static void n_tty_attach(tty_ldisc_t *ldisc, tty_device_t *tty); static void n_tty_detach(tty_ldisc_t *ldisc, tty_device_t *tty); static int n_tty_read(tty_ldisc_t *ldisc, void *buf, int len); static const char *n_tty_receive_char(tty_ldisc_t *ldisc, char c); static const char *n_tty_process_char(tty_ldisc_t *ldisc, char c); static tty_ldisc_ops_t n_tty_ops = { .attach = n_tty_attach, .detach = n_tty_detach, .read = n_tty_read, .receive_char = n_tty_receive_char, .process_char = n_tty_process_char }; struct n_tty { kmutex_t ntty_rlock; ktqueue_t ntty_rwaitq; char *ntty_inbuf; int ntty_rhead; int ntty_rawtail; int ntty_ckdtail; tty_ldisc_t ntty_ldisc; }; tty_ldisc_t * n_tty_create() { n_tty_t *ntty = (n_tty_t *)kmalloc(sizeof(n_tty_t)); if (NULL == ntty) return NULL; ntty->ntty_ldisc.ld_ops = &n_tty_ops; return &ntty->ntty_ldisc; } void n_tty_destroy(tty_ldisc_t *ldisc) { KASSERT(NULL != ldisc); kfree(ldisc_to_ntty(ldisc)); } /* * Initialize the fields of the n_tty_t struct, allocate any memory * you will need later, and set the tty_ldisc field of the tty. */ void n_tty_attach(tty_ldisc_t *ldisc, tty_device_t *tty) { NOT_YET_IMPLEMENTED("DRIVERS: n_tty_attach"); } /* * Free any memory allocated in n_tty_attach and set the tty_ldisc * field of the tty. */ void n_tty_detach(tty_ldisc_t *ldisc, tty_device_t *tty) { NOT_YET_IMPLEMENTED("DRIVERS: n_tty_detach"); } /* * Read a maximum of len bytes from the line discipline into buf. If * the buffer is empty, sleep until some characters appear. This might * be a long wait, so it's best to let the thread be cancellable. * * Then, read from the head of the buffer up to the tail, stopping at * len bytes or a newline character, and leaving the buffer partially * full if necessary. Return the number of bytes you read into the * buf. * In this function, you will be accessing the input buffer, which * could be modified by other threads. Make sure to make the * appropriate calls to ensure that no one else will modify the input * buffer when we are not expecting it. * * Remember to handle newline characters and CTRL-D, or ASCII 0x04, * properly. */ int n_tty_read(tty_ldisc_t *ldisc, void *buf, int len) { NOT_YET_IMPLEMENTED("DRIVERS: n_tty_read"); return 0; } /* * The tty subsystem calls this when the tty driver has received a * character. Now, the line discipline needs to store it in its read * buffer and move the read tail forward. * * Special cases to watch out for: backspaces (both ASCII characters * 0x08 and 0x7F should be treated as backspaces), newlines ('\r' or * '\n'), and full buffers. * * Return a null terminated string containing the characters which * need to be echoed to the screen. For a normal, printable character, * just the character to be echoed. */ const char * n_tty_receive_char(tty_ldisc_t *ldisc, char c) { NOT_YET_IMPLEMENTED("DRIVERS: n_tty_receive_char"); return NULL; } /* * Process a character to be written to the screen. * * The only special case is '\r' and '\n'. */ const char * n_tty_process_char(tty_ldisc_t *ldisc, char c) { NOT_YET_IMPLEMENTED("DRIVERS: n_tty_process_char"); return NULL; } <file_sep>/kernel/main/pit.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "globals.h" #include "main/io.h" #include "main/interrupt.h" #include "util/delay.h" #include "main/apic.h" #include "proc/sched.h" #include "proc/kthread.h" #define APIC_TIMER_IRQ 32 /* Map interrupt 32 */ /* IRQ */ /*#define PIT_IRQ 0*/ /* I/O ports */ /*#define PIT_DATA0 0x40 #define PIT_DATA1 0x41 #define PIT_DATA2 0x42 #define PIT_CMD 0x43 #define CLOCK_TICK_RATE 1193182 #undef HZ #define HZ 1000 #define LATCH (CLOCK_TICK_RATE / HZ)*/ static unsigned int ms = 0; void pit_handler(regs_t* regs) { } void pit_init(uint8_t intr) { } <file_sep>/kernel/util/time.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "globals.h" #include "main/interrupt.h" #include "main/apic.h" #include "main/pit.h" #include "util/debug.h" #include "util/init.h" #include "proc/sched.h" #include "proc/kthread.h" #define APIC_TIMER_IRQ 32 /* Map interrupt 32 */ #ifdef __UPREEMPT__ static unsigned int ms = 0; static void pit_handler(regs_t *regs) { dbg(DBG_CORE, "PIT HANDLER FIRED\n"); } /* Uncomment this to enable the apic timer to * call the pit_handler for userland preemption */ static __attribute__((unused)) void time_init(void) { intr_map(APIC_TIMER_IRQ, APIC_TIMER_IRQ); intr_register(APIC_TIMER_IRQ, pit_handler); /* TODO: figure out how this argument converts to hertz */ apic_enable_periodic_timer(8); } init_func(time_init); #endif <file_sep>/kernel/test/kshell/priv.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #include "test/kshell/kshell.h" #include "util/list.h" #define dprintf(x, args...) dbg(DBG_TEST, x, ## args) #define KSH_BUF_SIZE 1024 /* This really just needs to be as large as * the line discipline buffer */ #define KSH_CMD_NAME_LEN 16 #define KSH_MAX_ARGS 128 #define KSH_DESC_LEN 64 struct bytedev; struct kshell_command; struct kshell { /* If we have a filesystem, we can write to the file * descriptor. Otherwise, we need to write to a byte device */ #ifdef __VFS__ int ksh_fd; /* Used for redirection */ int ksh_out_fd; int ksh_in_fd; #else struct bytedev *ksh_bd; #endif }; list_t kshell_commands_list; /** * Searches for a shell command with a specified name. * * @param name name of the command to search for * @param namelen length of name * @return the command, if it exists, or NULL */ struct kshell_command *kshell_lookup_command(const char *name, size_t namelen); <file_sep>/kernel/vm/mmap.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "globals.h" #include "errno.h" #include "types.h" #include "mm/mm.h" #include "mm/tlb.h" #include "mm/mman.h" #include "mm/page.h" #include "proc/proc.h" #include "util/string.h" #include "util/debug.h" #include "fs/vnode.h" #include "fs/vfs.h" #include "fs/file.h" #include "vm/vmmap.h" #include "vm/mmap.h" /* * This function implements the mmap(2) syscall, but only * supports the MAP_SHARED, MAP_PRIVATE, MAP_FIXED, and * MAP_ANON flags. * * Add a mapping to the current process's address space. * You need to do some error checking; see the ERRORS section * of the manpage for the problems you should anticipate. * After error checking most of the work of this function is * done by vmmap_map(), but remember to clear the TLB. */ int do_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off, void **ret) { /*NOT_YET_IMPLEMENTED("VM: do_mmap");*/ vnode_t *vnode = NULL; vmarea_t *vma; int retVal = 0; uint32_t vlow; dbg(DBG_PRINT, "(GRADING3D 2)\n"); /*Man page: EINVAL We don't like addr, length, or offset */ if (!PAGE_ALIGNED(off)) { dbg(DBG_PRINT, "(GRADING3D 2)\n"); return -EINVAL; } if (addr != NULL && (uint32_t) addr < USER_MEM_LOW) { dbg(DBG_PRINT, "(GRADING3D 2)\n"); return -EINVAL; } if (len > USER_MEM_HIGH) { dbg(DBG_PRINT, "(GRADING3D 2)\n"); return -EINVAL; } /*if (addr != NULL && len + (uint32_t) addr > USER_MEM_HIGH) { dbg(DBG_ERROR, "5\n"); return -EINVAL; }*/ if (len == NULL) { dbg(DBG_PRINT, "(GRADING3D 2)\n"); return -EINVAL; } /* Man page : flags contained neither MAP_PRIVATE or MAP_SHARED, or contained both of these values.*/ if ((!(flags & MAP_PRIVATE) && !(flags & MAP_SHARED)) || ((flags & MAP_PRIVATE) && (flags & MAP_SHARED))) { dbg(DBG_PRINT, "(GRADING3D 2)\n"); return -EINVAL; } /* Errors when flag is FIXED */ /*if (!(flags & MAP_ANON) && (flags & MAP_FIXED) && !PAGE_ALIGNED(addr)) { dbg(DBG_ERROR, "8\n"); return -EINVAL; }*/ if (addr == 0 && (flags & MAP_FIXED)) { dbg(DBG_PRINT, "(GRADING3D 2)\n"); return -EINVAL; } if (!(flags & MAP_ANON)) { dbg(DBG_PRINT, "(GRADING3D 2)\n"); /*MAN Page: EBADF fd is not a valid file descriptor (and MAP_ANONYMOUS was not set).*/ if (fd < 0 || fd > NFILES || curproc->p_files[fd] == NULL) { dbg(DBG_PRINT, "(GRADING3D 2)\n"); return -EBADF; } file_t *f = curproc->p_files[fd]; vnode = f->f_vnode; /*MAN page: MAP_PRIVATE was requested, but fd is not open for reading. */ /*if ((flags & MAP_PRIVATE) && !(f->f_mode & FMODE_READ)) { dbg(DBG_ERROR, "12\n"); return -EACCES; }*/ /*MAN page: MAP_SHARED was requested and PROT_WRITE is set, but fd is not open in read/write (O_RDWR) mode.*/ if ((flags & MAP_SHARED) && (prot & PROT_WRITE) && !((f->f_mode & FMODE_READ) && (f->f_mode & FMODE_WRITE))) { dbg(DBG_PRINT, "(GRADING3D 2)\n"); return -EACCES; } /*MAN page: MAP_SHARED was requested and PROT_WRITE is set, but fd is not open in read/write (O_RDWR) mode.*/ /*if ((prot & PROT_WRITE) && (f->f_mode & FMODE_APPEND)) { dbg(DBG_ERROR, "14\n"); return -EACCES; }*/ } retVal = vmmap_map(curproc->p_vmmap, vnode, ADDR_TO_PN(addr), (uint32_t) PAGE_ALIGN_UP(len) / PAGE_SIZE, prot, flags, off, VMMAP_DIR_HILO, &vma); if (ret != NULL && retVal >= 0) { dbg(DBG_PRINT, "(GRADING3D 2)\n"); *ret = PN_TO_ADDR(vma->vma_start); vlow = (uint32_t) PN_TO_ADDR(vma->vma_start); pt_unmap_range(curproc->p_pagedir, vlow, vlow + (uintptr_t) PAGE_ALIGN_UP(len)); tlb_flush_range(vlow, (uint32_t) PAGE_ALIGN_UP(len) / PAGE_SIZE); } KASSERT(NULL != curproc->p_pagedir); dbg(DBG_PRINT, "(GRADING3A 2.a)\n"); return retVal; } /* * This function implements the munmap(2) syscall. * * As with do_mmap() it should perform the required error checking, * before calling upon vmmap_remove() to do most of the work. * Remember to clear the TLB. */ int do_munmap(void *addr, size_t len) { /*NOT_YET_IMPLEMENTED("VM: do_munmap"); */ int retVal = 0; uint32_t vlow; /*Man page: EINVAL We don't like addr, length, or offset */ if ((uint32_t) addr < USER_MEM_LOW || USER_MEM_HIGH - (uint32_t) addr < len) { dbg(DBG_PRINT, "(GRADING3D 2)\n"); return -EINVAL; } /*if (!PAGE_ALIGNED(addr)) { dbg(DBG_ERROR, "17\n"); return -EINVAL; }*/ if (len == NULL) { dbg(DBG_PRINT, "(GRADING3D 2)\n"); return -EINVAL; } dbg(DBG_PRINT, "(GRADING3D 2)\n"); retVal = vmmap_remove(curproc->p_vmmap, ADDR_TO_PN(addr), (uint32_t) PAGE_ALIGN_UP(len) / PAGE_SIZE); vlow = (uint32_t) PN_TO_ADDR(ADDR_TO_PN(addr)); tlb_flush_range(vlow, (uint32_t) PAGE_ALIGN_UP(len) / PAGE_SIZE); pt_unmap_range(curproc->p_pagedir, vlow, (uint32_t) PN_TO_ADDR( ADDR_TO_PN(addr) + (uint32_t) PAGE_ALIGN_UP(len) / PAGE_SIZE)); KASSERT(NULL != curproc->p_pagedir); dbg(DBG_PRINT, "(GRADING3A 2.b)\n"); return retVal; } <file_sep>/kernel/boot/floppy.h #pragma once segment_inc: .word 0x1000 bytes_per_sector: .word 512 sectors_per_track: .word 0 heads_per_cylinder: .word 0 absolute_sector: .byte 0x00 absolute_head: .byte 0x00 absolute_track: .byte 0x00 dot_string: .string "." newline_string: .string "\n\r" failed_string: .string "failed to read disk" disk_error: mov $failed_string, %si call puts16 hlt /* Read disk geometry into global variables * DL=>drive index * * uses interrupt 0x13 function 0x08 */ .read_disk_geometry: push %ax push %bx push %cx push %dx push %es push %di /* set es:di to 0x0:0x0 to handle buggy BIOS */ mov $0x00, %di mov %di, %es mov $0x08, %ah int $0x13 jc disk_error inc %dh mov %dh, heads_per_cylinder mov %cl, %ah and $0x3f, %ah mov %ah, sectors_per_track pop %di pop %es pop %dx pop %cx pop %bx pop %ax ret /* Convert LBA to CHS * AX=>LBA Address to convert * * absolute sector = (logical sector / sectors per track) + 1 * absolute head = (logical sector / sectors per track) MOD number of heads * absolute track = logical sector / (sectors per track * number of heads) */ .lba_to_chs: push %dx xor %dx, %dx divw sectors_per_track inc %dl mov %dl, absolute_sector xor %dx, %dx divw heads_per_cylinder movb %dl, absolute_head movb %al, absolute_track pop %dx ret /* Reads a series of sectors * DL=>drive number * CX=>Number of sectors to read * AX=>Starting sector * ES:BX=>Buffer to read to */ read_sectors: push %es call .read_disk_geometry 4: mov $0x0005, %di /* five retries in case of error */ 1: /* on error loop back here */ push %ax push %bx push %cx push %dx call .lba_to_chs mov $0x02, %ah /* int 0x13 function 2 is read sectors */ mov $0x01, %al /* number of sectors to read */ movb absolute_track, %ch movb absolute_sector, %cl movb absolute_head, %dh int $0x13 jnc 1f /* test for read error */ /* error occured use int 0x13 function 0 to reset disk */ xor %ax, %ax int $0x13 dec %di /* decrement error count */ pop %dx pop %cx pop %bx pop %ax jnz 1b int $0x18 /* total failure */ 1: mov $dot_string, %si call puts16 pop %dx pop %cx pop %bx pop %ax addw bytes_per_sector, %bx /* move the location where we store data */ jc 2f 3: inc %ax /* prepare to read next sector */ loop 4b pop %es mov $newline_string, %si call puts16 ret 2: clc mov %es, %dx addw segment_inc, %dx mov %dx, %es jmp 3b <file_sep>/kernel/test/kshell/commands.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #include "test/kshell/kshell.h" #define KSHELL_CMD(name) \ int kshell_ ## name(kshell_t *ksh, int argc, char **argv) KSHELL_CMD(help); KSHELL_CMD(exit); KSHELL_CMD(echo); #ifdef __VFS__ KSHELL_CMD(cat); KSHELL_CMD(ls); KSHELL_CMD(cd); KSHELL_CMD(rm); KSHELL_CMD(link); KSHELL_CMD(rmdir); KSHELL_CMD(mkdir); KSHELL_CMD(stat); #endif <file_sep>/kernel/drivers/blockdev.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "kernel.h" #include "types.h" #include "util/debug.h" #include "util/list.h" #include "drivers/blockdev.h" #include "drivers/disk/ata.h" #include "mm/pframe.h" #include "mm/mmobj.h" static void blockdev_ref(mmobj_t *o); static void blockdev_put(mmobj_t *o); static int blockdev_lookuppage(mmobj_t *o, uint32_t pagenum, int forwrite, pframe_t **pf); static int blockdev_fillpage(mmobj_t *o, pframe_t *pf); static int blockdev_dirtypage(mmobj_t *o, pframe_t *pf); static int blockdev_cleanpage(mmobj_t *o, pframe_t *pf); static mmobj_ops_t blockdev_mmobj_ops = { .ref = blockdev_ref, .put = blockdev_put, .lookuppage = blockdev_lookuppage, .fillpage = blockdev_fillpage, .dirtypage = blockdev_dirtypage, .cleanpage = blockdev_cleanpage }; static list_t blockdevs; void blockdev_init() { list_init(&blockdevs); /* Initialize all subsystems */ ata_init(); } int blockdev_register(blockdev_t *dev) { blockdev_t *bd; /* Make sure dev, dev ops, and dev id not null */ if (!dev || (NULL_DEVID == dev->bd_id) || !(dev->bd_ops)) return -1; /* dev id must be unique */ list_iterate_begin(&blockdevs, bd, blockdev_t, bd_link) { if (dev->bd_id == bd->bd_id) return -1; } list_iterate_end(); /* Initialize its object here */ mmobj_init(&dev->bd_mmobj, &blockdev_mmobj_ops); list_insert_tail(&blockdevs, &dev->bd_link); return 0; } blockdev_t * blockdev_lookup(devid_t id) { blockdev_t *bd; list_iterate_begin(&blockdevs, bd, blockdev_t, bd_link) { if (id == bd->bd_id) return bd; } list_iterate_end(); return NULL; } /* * Clean and then free all resident pages belonging to this * particular block device. * As with pframe_clean_all, this is not guaranteed to terminate. */ void blockdev_flush_all(blockdev_t *dev) { pframe_t *pf; /* Clean all pages - see pframe_clean_all for * explanation of this loop */ clean: list_iterate_begin(&dev->bd_mmobj.mmo_respages, pf, pframe_t, pf_olink) { if (pframe_is_dirty(pf)) { pframe_clean(pf); goto clean; } } list_iterate_end(); /* Free all pages */ list_iterate_begin(&dev->bd_mmobj.mmo_respages, pf, pframe_t, pf_olink) { KASSERT(!pframe_is_dirty(pf)); pframe_free(pf); } list_iterate_end(); } /* Implementation of mmobj entry points: */ /* Block device mmobjs don't need to ref or put, as they will * never be destroyed until the driver is shut down. */ static void blockdev_ref(mmobj_t *o) {} static void blockdev_put(mmobj_t *o) {} static int blockdev_lookuppage(mmobj_t *o, uint32_t pagenum, int forwrite, pframe_t **pf) { return pframe_get(o, pagenum, pf); } static int blockdev_fillpage(mmobj_t *o, pframe_t *pf) { KASSERT(pf && pf->pf_obj); /* Find the corresponding blockdev */ blockdev_t *bd = CONTAINER_OF(pf->pf_obj, blockdev_t, bd_mmobj); /* And fill in the page by reading from it */ return bd->bd_ops->read_block(bd, pf->pf_addr, pf->pf_pagenum, 1); } /* block devices don't need to make use of this entry point: */ static int blockdev_dirtypage(mmobj_t *o, pframe_t *pf) { return 0; } static int blockdev_cleanpage(mmobj_t *o, pframe_t *pf) { KASSERT(pf && pf->pf_obj); /* Find the corresponding blockdev */ blockdev_t *bd = CONTAINER_OF(pf->pf_obj, blockdev_t, bd_mmobj); /* Clean the corresponding page by writing it back */ return bd->bd_ops->write_block(bd, pf->pf_addr, pf->pf_pagenum, 1); } <file_sep>/kernel/drivers/tty/virtterm.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "drivers/tty/virtterm.h" #include "drivers/tty/driver.h" #include "drivers/tty/keyboard.h" #include "drivers/tty/screen.h" #include "drivers/tty/tty.h" #include "main/interrupt.h" #include "mm/kmalloc.h" #include "util/string.h" #include "util/debug.h" /* The number of virtual terminals */ #define NTERMS __NTERMS__ /* Total size of the scroll buffer */ #define SCROLL_BUFSIZE (5 * DISPLAY_SIZE) #define driver_to_vt(driver) \ CONTAINER_OF(driver, virtterm_t, vt_driver) static void vt_provide_char(tty_driver_t *ttyd, char c); static tty_driver_callback_t vt_register_callback_handler( tty_driver_t *ttyd, tty_driver_callback_t callback, void *arg); static tty_driver_callback_t vt_unregister_callback_handler( tty_driver_t *driver); static void *vt_block_io(tty_driver_t *ttyd); static void vt_unblock_io(tty_driver_t *ttyd, void *data); static tty_driver_ops_t vt_driver_ops = { .provide_char = vt_provide_char, .register_callback_handler = vt_register_callback_handler, .unregister_callback_handler = vt_unregister_callback_handler, .block_io = vt_block_io, .unblock_io = vt_unblock_io }; typedef struct virtterm { /* * head, tail, and top are row aligned */ /* Current buffer head (circular buffer) */ int vt_head; /* Current buffer tail (circular buffer) */ int vt_tail; /* Top of screen (in current scroll buffer) */ int vt_top; /* Cursor position (in buffer, not on screen) */ int vt_cursor; /* scroll buffer */ char vt_buf[SCROLL_BUFSIZE]; /* "Temporary buffer" */ char vt_tempbuf[DISPLAY_WIDTH *DISPLAY_HEIGHT]; tty_driver_t vt_driver; } virtterm_t; static virtterm_t vt_terms[NTERMS]; static virtterm_t *vt_curterm; /** * Called when a key is pressed. Sends the key press to the current * terminal if there is one. * * @param c the character pressed */ static void vt_keyboard_handler(char c); /** * Puts a given character to a given virtual terminal, moving the * cursor accordingly and correctly handling special characters, such * as newline and backspace. * * Note that vt_handle_char puts the character into the virtual * terminals buffer, _NOT_ onto the screen. * * @return true if we put a new displayable character on the screen */ static int vt_handle_char(virtterm_t *vt, char c); /** * Redraws the entire screen. */ static void vt_redraw(); /** * Redraws only the cursor. */ static void vt_cursor_redraw(); /* to and from are pointers into our circular buffer - this returns the * distance (including wraparound) between them */ #define circ_dist(to, from) \ (((to) - (from) + SCROLL_BUFSIZE) % SCROLL_BUFSIZE) /* Given a position (int) in the buffer, returns an int corresponding * to the first char in the next row of the buffer (using * DISPLAY_WIDTH) */ #define next_row(i) \ ((((i) / DISPLAY_WIDTH + 1) * DISPLAY_WIDTH) % SCROLL_BUFSIZE) /* Moves the given "pointer" into the buffer (really an int) by the * appropriate amount - works both forwards and backwards. Only works * on "moving" distances smaller than a SCROLL_BUFSIZE */ #define buf_add(ptr,amt) \ (ptr = (((ptr) + (amt) + SCROLL_BUFSIZE) % SCROLL_BUFSIZE)) /* Surprisingly helpful */ #define buf_inc(ptr) buf_add(ptr,1) #define buf_dec(ptr) buf_add(ptr,-1) void vt_init() { /* Initialize NTERMS virtual terminals */ int i; for (i = 0; i < NTERMS; i++) { memset(vt_terms[i].vt_buf, 0, SCROLL_BUFSIZE); vt_terms[i].vt_top = 0; vt_terms[i].vt_cursor = 0; vt_terms[i].vt_head = 0; /* * Dealing with a silly memset bug - the problem is * that if tail and head are ever the same, the first * character we add will get overwritten when we * memset after changing the tail. */ vt_terms[i].vt_tail = DISPLAY_WIDTH; vt_terms[i].vt_driver.ttd_ops = &vt_driver_ops; vt_terms[i].vt_driver.ttd_callback = NULL; vt_terms[i].vt_driver.ttd_callback_arg = NULL; } /* Initialize the current virtual terminal */ vt_curterm = vt_terms; /* Wipe the screen to start (Who knows?) */ vt_redraw(); /* Register handler with keyboard */ keyboard_register_handler(vt_keyboard_handler); } int vt_num_terminals() { return NTERMS; } tty_driver_t * vt_get_tty_driver(int id) { if (id >= NTERMS) { return NULL; } else { return &vt_terms[id].vt_driver; } } void vt_scroll(int lines, int scroll_up) { /* We move vt_top and redraw the entire buffer */ if (scroll_up) { /* Check against the head of the buffer */ if (circ_dist(vt_curterm->vt_top, vt_curterm->vt_head) < lines * DISPLAY_WIDTH) { vt_curterm->vt_top = vt_curterm->vt_head; } else { buf_add(vt_curterm->vt_top, -lines * DISPLAY_WIDTH); } } else { /* Check against tail of buffer */ /* Note we add one as tail points AFTER the last * line */ if (circ_dist(vt_curterm->vt_tail, vt_curterm->vt_top) < (lines + 1) * DISPLAY_WIDTH) { vt_curterm->vt_top = vt_curterm->vt_tail; buf_add(vt_curterm->vt_top, -DISPLAY_WIDTH); } else { buf_add(vt_curterm->vt_top, lines * DISPLAY_WIDTH); } } vt_redraw(); } int vt_switch(int term) { if (term < 0 || term >= NTERMS) return -1; vt_curterm = &(vt_terms[term]); vt_redraw(); return 0; } void vt_print_shutdown() { tty_driver_t *ttyd; static const char str[] = " " "It is now safe to turn off your computer"; int i; if (vt_curterm == NULL) return; ttyd = &vt_curterm->vt_driver; KASSERT(NULL != ttyd->ttd_ops); KASSERT(NULL != ttyd->ttd_ops->provide_char); for (i = 0; i < 20; i++) ttyd->ttd_ops->provide_char(ttyd, '\n'); for (i = 0; str[i] != '\0'; i++) ttyd->ttd_ops->provide_char(ttyd, str[i]); for (i = 0; i < 14; i++) ttyd->ttd_ops->provide_char(ttyd, '\n'); } void vt_provide_char(tty_driver_t *ttyd, char c) { KASSERT(NULL != ttyd); virtterm_t *vt = driver_to_vt(ttyd); /* Store for optimizing */ int old_cursor = vt->vt_cursor; int old_top = vt->vt_top; int can_write_char; /* If cursor is not on the screen, we move top */ if (circ_dist(vt->vt_cursor, vt->vt_top) >= DISPLAY_SIZE) { /* Cursor should be on the last row in this case */ vt->vt_top = next_row(vt->vt_cursor); buf_add(vt->vt_top, -DISPLAY_SIZE); } can_write_char = vt_handle_char(vt, c); /* Redraw if it's the current terminal */ if (vt_curterm == vt) { /* * Check if we can optimize (just put 1 char instead * of redrawing screen) */ if (old_top == vt->vt_top) { if (can_write_char) { int rel_cursor = circ_dist(old_cursor, vt->vt_top); screen_putchar(c, rel_cursor % DISPLAY_WIDTH, rel_cursor / DISPLAY_WIDTH); } vt_cursor_redraw(); } else { vt_redraw(); } } } tty_driver_callback_t vt_register_callback_handler(tty_driver_t *ttyd, tty_driver_callback_t callback, void *arg) { tty_driver_callback_t previous_callback; KASSERT(NULL != ttyd); previous_callback = ttyd->ttd_callback; ttyd->ttd_callback = callback; ttyd->ttd_callback_arg = arg; return previous_callback; } tty_driver_callback_t vt_unregister_callback_handler(tty_driver_t *ttyd) { tty_driver_callback_t previous_callback; KASSERT(NULL != ttyd); previous_callback = ttyd->ttd_callback; ttyd->ttd_callback = NULL; return previous_callback; } void * vt_block_io(tty_driver_t *ttyd) { uint8_t oldipl; KASSERT(NULL != ttyd); oldipl = intr_getipl(); intr_setipl(INTR_KEYBOARD); return (void *)(uintptr_t)oldipl; } void vt_unblock_io(tty_driver_t *ttyd, void *data) { uint8_t oldipl = (uint8_t)(uintptr_t)data; KASSERT(NULL != ttyd); KASSERT(intr_getipl() == INTR_KEYBOARD && "Virtual terminal I/O not blocked"); intr_setipl(oldipl); } void vt_keyboard_handler(char c) { if (vt_curterm && vt_curterm->vt_driver.ttd_callback) { vt_curterm->vt_driver.ttd_callback( vt_curterm->vt_driver.ttd_callback_arg, c); } } /* Redraws only the cursor */ void vt_cursor_redraw() { int rel_cursor = circ_dist(vt_curterm->vt_cursor, vt_curterm->vt_top); screen_move_cursor(rel_cursor % DISPLAY_WIDTH, rel_cursor / DISPLAY_WIDTH); } /* Redraws the screen based on the current virtual terminal */ void vt_redraw() { /* akerber: There is, quite tragically, a reason why this * doesn't ever use MIN and MAX - see the appropriate * header */ /* Clear temporary buffer for use */ memset(vt_curterm->vt_tempbuf, 0, DISPLAY_SIZE); /* Write in the entire buffer starting from top */ if (vt_curterm->vt_top <= vt_curterm->vt_tail) { /* No wraparound */ if (vt_curterm->vt_tail - vt_curterm->vt_top <= DISPLAY_SIZE) { memcpy(vt_curterm->vt_tempbuf, vt_curterm->vt_buf + vt_curterm->vt_top, vt_curterm->vt_tail - vt_curterm->vt_top); } else { memcpy(vt_curterm->vt_tempbuf, vt_curterm->vt_buf + vt_curterm->vt_top, DISPLAY_SIZE); } } else { /* Wraparound */ int first_part_size = SCROLL_BUFSIZE - vt_curterm->vt_top; /* First half */ if (first_part_size >= DISPLAY_SIZE) { memcpy(vt_curterm->vt_tempbuf, vt_curterm->vt_buf + vt_curterm->vt_top, DISPLAY_SIZE); } else { memcpy(vt_curterm->vt_tempbuf, vt_curterm->vt_buf + vt_curterm->vt_top, first_part_size); /* Second half (after wrapping) */ if (first_part_size + vt_curterm->vt_tail <= DISPLAY_SIZE) { memcpy(vt_curterm->vt_tempbuf + first_part_size, vt_curterm->vt_buf, vt_curterm->vt_tail); } else { memcpy(vt_curterm->vt_tempbuf + first_part_size, vt_curterm->vt_buf, DISPLAY_SIZE - first_part_size); } } } screen_putbuf(vt_curterm->vt_tempbuf); /* Also want to reposition the cursor */ vt_cursor_redraw(); } /* Puts the given char into the given terminal's buffer, moving the * cursor accordingly for control chars Returns 1 if char can be * echoed (non-control char), 0 otherwise */ static int vt_handle_char(virtterm_t *vt, char c) { KASSERT(NULL != vt); /* Start where the cursor currently is located */ int new_cursor = vt->vt_cursor; int ret = 0; switch (c) { case '\b': /* Move cursor back one space */ /* the user can't backspace past the beginning */ if (new_cursor != vt->vt_head) buf_dec(new_cursor); break; case '\r': new_cursor = (new_cursor / DISPLAY_WIDTH) * DISPLAY_WIDTH; break; /* In the next two cases, the cursor advances, and we * need to compare it with the end of the buffer to * determine whether or not to advance the buffer * tail */ case '\n': /* To beginning of next line */ new_cursor = next_row(new_cursor); goto handle_tail; default: /* Actually put a char into the buffer */ vt->vt_buf[new_cursor] = c; /* And increment */ buf_inc(new_cursor); ret = 1; handle_tail: /* Yuck */ if (circ_dist(new_cursor, vt->vt_cursor) >= circ_dist(vt->vt_tail, vt->vt_cursor)) { /* Current cursor pos past tail of the current * buffer, so advance tail */ int new_tail = next_row(new_cursor); /* Check for head adjusting (if we write * enough that the scroll buffer fills up, we * sacrifice chars near the head) */ if (circ_dist(vt->vt_tail, vt->vt_head) >= circ_dist(vt->vt_tail, new_tail)) { vt->vt_head = next_row(new_tail); } /* Remember to clear space we may have acquired */ if (vt->vt_tail <= new_tail) { memset(vt->vt_buf + vt->vt_tail, 0, new_tail - vt->vt_tail); } else { memset(vt->vt_buf + vt->vt_tail, 0, SCROLL_BUFSIZE - vt->vt_tail); memset(vt->vt_buf, 0, new_tail); } /* Finally, set the new tail */ vt->vt_tail = new_tail; } break; } vt->vt_cursor = new_cursor; return ret; } <file_sep>/kernel/include/test/kshell/io.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #include "test/kshell/kshell.h" /* * When writing a kernel shell command, make sure to use the following * I/O functions. * * Before VFS is not enabled, the kernel shell will use functions from * bytedev.h to get a pointer the the bytedev_t struct for the TTY. * * When VFS is enabled, the kernel shell will use the functions from * vfs_syscall.h to open and close the TTY and perform I/O operations * on the TTY. * * If you use the functions below, this process will be completely * transparent. */ /** * Replacement for do_write. * * @param ksh the kshell to write to * @param buf the buffer to write out to the kshell * @param nbytes the maximum number of bytes to write * @return number of bytes written on sucess and <0 on error */ int kshell_write(kshell_t *ksh, const void *buf, size_t nbytes); /** * Replacement for do_read. * * @param ksh the kshell to read from * @param buf the buffer to store data read from the kshell * @param nbytes the maximum number of bytes to read * @param number of bytes read on success and <0 on error */ int kshell_read(kshell_t *ksh, void *buf, size_t nbytes); /* Unless an error occurs, guarantees that all of buf will be * written */ /** * Writes a specified number of bytes from a buffer to the * kshell. Unlike kshell_write, this function guarantees it will write * out the desired number of bytes. * * @param ksh the kshell to write to * @param buf the buffer to write out to the kshell * @param nbytes the number of bytes to write * @return number of bytes written on success and <0 on error */ int kshell_write_all(kshell_t *ksh, void *buf, size_t nbytes); /* Replacement for printf */ /** * Write output to a kshell according to a format string. * * @param ksh the kshell to write to * @param fmt the format string */ void kprintf(kshell_t *ksh, const char *fmt, ...); <file_sep>/kernel/fs/faber_fs_test.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ /* * BC: You must NOT change this file. If you submit a modified version * of this file, it will be deleted from your submission. */ #include "errno.h" #include "proc/proc.h" #include "proc/kthread.h" #ifdef __VFS__ #include "fs/fcntl.h" #include "fs/vfs_syscall.h" #include "fs/lseek.h" #include "fs/s5fs/s5fs.h" #endif #include "test/kshell/io.h" #include "test/kshell/kshell.h" #include "util/debug.h" #include "util/string.h" #include "util/printf.h" #define FILE_CONTENT "look!\n" #define CONTENT_LEN 6 #define TESTBUFLEN 256 #ifdef __VFS__ #ifdef __VM__ /* Write a sparse file, specifically one that has FILE_CONTENT starting at byte * 50000 and no other data. The size will be 50000+CONTENT_LEN, but only one * block is allocated to the file. */ int faber_sparse_test(kshell_t *ksh, int argc, char **argv) { KASSERT(NULL != ksh); KASSERT(NULL != argv); int f = -1; /* file descriptor */ int rv = 0; /* Return value */ /* Open the file, and create it if not present */ if ( (f = do_open("/sparse", O_WRONLY | O_CREAT)) < 0) { kprintf(ksh, "Couldn't open /sparse\n"); return -1; } /* Seek out 50000 bytes (the seek pointer is in the VFS layer, so the * s5fs layer will just see a write at byte 50000 later) */ if ( (rv = do_lseek(f, 50000, SEEK_END)) != 50000 ) { do_close(f); kprintf(ksh, "seek failed %d\n", rv); return -1; } /* Write the visible bytes. Here's where the first memory/disk block * is allocated. */ if ( do_write(f, FILE_CONTENT, CONTENT_LEN) != CONTENT_LEN) { do_close(f); kprintf(ksh, "File write failed?\n"); return -1; } /* Close up and go home */ do_close(f); kprintf(ksh, "Created sparse file \"/sparse\"\n"); return 0; } #endif /* __VM__ */ static char block[S5_BLOCK_SIZE]; /* Create as large a file as the file system structures will allow. The disk * that comes with weenix will not support a file this size, so it will fail in * the do_write calls. */ int faber_space_test(kshell_t *ksh, int argc, char **argv) { KASSERT(NULL != ksh); int f = -1; /* File descriptor */ int rv = 0; /* Return value */ int i = 0; /* Scratch */ kprintf(ksh, ">>> Running faber_space_test()... "); /* Create the file */ if ( (f = do_open("/space", O_WRONLY | O_CREAT)) < 0) { kprintf(ksh, "Couldn't open /space (%d) %s\n", f, strerror(-f)); return -1; } /* Write data until the either the max size file is written or the * filesystem fills. The filesystem should fill. */ for ( i = 0; i < (int) S5_MAX_FILE_BLOCKS; i++ ) { if ( (rv = do_write(f, block, S5_BLOCK_SIZE)) < 0 ) { /* Close the file or we keep it forever... */ do_close(f); kprintf(ksh, "Error writing block %d of /space (%d) %s\n", i, rv, strerror(-rv)); return rv; } } rv = 0; if (rv == 0) kprintf(ksh, "PASSED.\n"); return 0; } /* * A function executed by a thread that creates a directory called /dir00n * (where n is arg1) and writes 20 files into it called /dir00n/test000 through * /dir00n/test019. If any fail, exit with their return code. Threads running * this are created by both faber_fs_thread_test and faber_directory_test. */ static void *make_dir_thread(int arg1, void *arg2) { char dir[TESTBUFLEN]; /* A buffer for the directory name */ char file[TESTBUFLEN]; /* A buffer for the full file pathname */ int rv = 0; /* return values */ int i = 0; /* Scratch */ /* Make the directory name and the directory. Snprintf is safe - it * always zero-terminates and never overflows the buffer. */ snprintf(dir, TESTBUFLEN, "/dir%03d", arg1); do_mkdir(dir); for (i = 0; i < 20 ; i++ ) { int f= 0; /* File descriptor */ snprintf(file, TESTBUFLEN, "%s/test%03d", dir, i); /* Open a file (creating it if it's not there) */ if ( (f = do_open(file, O_WRONLY | O_CREAT)) < 0 ) { rv = f; goto fail; } /* Write the same content to every file. */ if ( (rv = do_write(f, FILE_CONTENT, CONTENT_LEN)) != CONTENT_LEN) { do_close(f); goto fail; } do_close(f); } rv = 0; fail: do_exit(rv); return NULL; } /* * A function executed by a thread that creates a directory called /dir00n * (where n is arg1) and unlinks 20 files from it called /dir00n/test000 through * /dir00n/test019. Ignore the return codes (files may not be there yet). * Threads running this are created by faber_directory_test. Structurally * similar to make_dir_thread. */ static void *rm_dir_thread(int arg1, void *arg2) { char dir[TESTBUFLEN]; /* Directory pathname */ char file[TESTBUFLEN]; /* Each file's pathname */ int rv = 0; /* Return value */ int i = 0; /* Scratch */ /* Make the directory */ snprintf(dir, TESTBUFLEN, "/dir%03d", arg1); do_mkdir(dir); /* Unlink the files */ for (i = 0; i < 20 ; i++ ) { snprintf(file, TESTBUFLEN, "%s/test%03d", dir, i); do_unlink(file); } do_exit(rv); return NULL; } /* * A function executed by a thread that deletes all files * under a directory called /dir00n (where n is arg1). * Arg2 == 0 means directory should exist. * Arg2 == 1 means if directory does not exist, don't treat it as error. * Threads running this are created by faber_fs_thread_test. */ static void *clean_dir_thread(int arg1, void *arg2) { struct dirent d; /* The current directory entry */ char dir[TESTBUFLEN]; /* Directory pathname */ char file[TESTBUFLEN]; /* Each file's pathname */ int rv = 0; /* Return value */ int i = 0; /* Scratch */ int f = -1; /* File descriptor (dirs must be opened) */ int got_one = 1; /* True if this iteration deleted a file */ snprintf(dir, TESTBUFLEN, "/dir%03d", arg1); while ( got_one ) { got_one = 0; /* Open up the directory */ if ( (f = do_open(dir, O_RDONLY)) < 0 ) { if (arg2) { do_exit(0); } do_exit(f); } while ( ( rv = do_getdent(f, &d)) > 0 ) { /* Keep looking if d contains . or .. */ if ( strncmp(".", d.d_name, NAME_LEN) == 0 || strncmp("..", d.d_name, NAME_LEN) == 0 ) continue; /* Found a name to delete. Construct the path and delete it */ snprintf(file, TESTBUFLEN, "%s/%s", dir, d.d_name); if ( (rv = do_unlink(file)) < 0 ) { /* Something went wrong- d probably points to a directory. * Report the error, close f, and terminate the command. */ dbg(DBG_TEST, "Unlink failed on %s: %d %s\n", file, rv, strerror(-rv)); do_close(f); do_exit(rv); } got_one = 1; /* CLose the directory and restart (because it set got_one) */ break; } do_close(f); if (rv) { do_exit(rv); } } return NULL; } /* * Run multiple threads, each running make_dir_thread with a different * parameter. The calling format (from the kshell) is thread_test <num>, where * num is an integer. The number is parsed into an int and threads with * parameter 0..num are created. This code then waits for them and prints each * exit value. Fewer than 4 copies should exit safely, but more than that will * run out of inodes. */ int faber_fs_thread_test(kshell_t *ksh, int argc, char **argv) { KASSERT(NULL != ksh); proc_t *p = NULL; /* A process to run in */ kthread_t *thr = NULL; /* A thread to run in the process */ char tname[TESTBUFLEN]; /* The thread name */ int pid = 0; /* Process ID returned by do_waitpid */ int lim = 1; /* Number of processes to start */ int rv = 0; /* Return value */ int i = 0; /* Scratch */ int passed = 1; /* Passed all tests */ KASSERT(NULL != ksh); kprintf(ksh, ">>> Running faber_fs_thread_test()... "); if ( argc == 1 ) { kprintf(ksh, "\nError: faber_fs_thread_test() cannot run without a commandline argument."); kprintf(ksh, "\nUsage: %s n\n", argv[0]); return 1; } if ( argc > 1) { /* Oh, barf, sscanf makes me ill.*/ if ( sscanf(argv[1], "%d", &lim) != 1) lim = 1; /* A little bounds checking */ if ( lim < 1 || lim > 255 ) lim = 1; } /* Start the children */ for ( i = 0; i< lim; i++) { snprintf(tname, TESTBUFLEN, "thread%03d", i); p = proc_create(tname); KASSERT(NULL != p); thr = kthread_create(p, make_dir_thread, i, NULL); KASSERT(NULL != thr); sched_make_runnable(thr); } /* Wait for children and report errors in their return values */ while ( ( pid = do_waitpid(-1, 0 , &rv) ) != -ECHILD) { if ( rv < 0 ) { kprintf(ksh, "\nChild (make dir) %d: %d %s", pid, rv, strerror(-rv)); passed = 0; } else { kprintf(ksh, "\nChild (make dir) %d: %d", pid, rv); } } for ( i = 0; i< lim; i++) { snprintf(tname, TESTBUFLEN, "clean_dir_thread%03d", i); p = proc_create(tname); KASSERT(NULL != p); thr = kthread_create(p, clean_dir_thread, i, (passed ? NULL : (void*)1)); KASSERT(NULL != thr); sched_make_runnable(thr); while ( ( pid = do_waitpid(-1, 0, &rv) ) != -ECHILD) if ( rv < 0 ) kprintf(ksh, "\nChild (clean dir) %d: %d %s", pid, rv, strerror(-rv)); else kprintf(ksh, "\nChild (clean dir) %d: %d", pid, rv); } for ( i = 0; i< lim; i++) { int rv2; snprintf(tname, TESTBUFLEN, "/dir%03d", i); if ((rv2 = do_rmdir(tname)) < 0) { rv = rv2; kprintf(ksh, "\nFailed rmdir(%s): %d %s", tname, rv, strerror(-rv)); } } if (passed) { kprintf(ksh, "\nPASSED.\n"); } else { kprintf(ksh, "\n"); } return rv; } /* * Run multiple pairs of threads, each running make_dir_thread or rm_dir_thread * with a different parameter. One will be creating a directory full of files, * and the other will be deleting them. They do not move in lock step, so for * a few threads, say 4 or 5, the system is likely to run out of i-nodes. * * The calling format (from the kshell) is * directory_test <num>, where num is an integer. The number is parsed into an * int and pairs of threads with parameter 0..num are created. This code then * waits for them and prints each exit value. */ int faber_directory_test(kshell_t *ksh, int argc, char **argv) { KASSERT(NULL != ksh); proc_t *p = NULL; /* A process to run in */ kthread_t *thr = NULL; /* A thread to run in it */ char tname[TESTBUFLEN]; /* A thread name */ int pid = 0; /* Process ID from do_waitpid (who exited?) */ int lim = 1; /* Number of processes to run */ int rv = 0; /* Return values */ int i = 0; /* Scratch */ KASSERT(NULL != ksh); kprintf(ksh, ">>> Running faber_directory_test()... "); if ( argc == 1 ) { kprintf(ksh, "\nError: faber_directory_test() cannot run without a commandline argument."); kprintf(ksh, "\nUsage: %s n\n", argv[0]); return 1; } if ( argc > 1) { /* Oh, barf */ if ( sscanf(argv[1], "%d", &lim) != 1) lim = 1; /* A little bounds checking */ if ( lim < 1 || lim > 255 ) lim = 1; } /* Start pairs of processes */ for ( i = 0; i< lim; i++) { /* The maker process */ snprintf(tname, TESTBUFLEN, "thread%03d", i); p = proc_create(tname); KASSERT(NULL != p); thr = kthread_create(p, make_dir_thread, i, NULL); KASSERT(NULL != thr); sched_make_runnable(thr); /* The deleter process */ snprintf(tname, TESTBUFLEN, "rmthread%03d", i); p = proc_create(tname); KASSERT(NULL != p); thr = kthread_create(p, rm_dir_thread, i, NULL); KASSERT(NULL != thr); sched_make_runnable(thr); } /* Wait for children and report their error codes */ while ( ( pid = do_waitpid(-1, 0 , &rv) ) != -ECHILD) { if ( rv < 0 ) { kprintf(ksh, "\nChild %d: %d %s", pid, rv, strerror(-rv)); } else { kprintf(ksh, "\nChild %d: %d", pid, rv); } } for ( i = 0; i< lim; i++) { int rv2; snprintf(tname, TESTBUFLEN, "/dir%03d", i); if ((rv2 = do_rmdir(tname)) < 0) { rv = rv2; kprintf(ksh, "\nFailed rmdir(%s): %d %s", tname, rv, strerror(-rv)); } } if (rv == 0) { kprintf(ksh, "\nPASSED.\n"); } else { kprintf(ksh, "\n"); } return rv; } /* * A little convenience command to clear the files from a directory (though not * the directories). Called from the kshell as cleardir <name>. */ int faber_cleardir(kshell_t *ksh, int argc, char **argv) { KASSERT(NULL != ksh); struct dirent d; /* The current directory entry */ char buf[TESTBUFLEN]; /* A buffer used to assemble the pathname */ int f = -1; /* File descriptor (dirs must be opened) */ int rv = 0; /* Return values */ int got_one = 1; /* True if this iteration deleted a file */ if ( argc < 2 ) { kprintf(ksh, "Usage: cleardir dir\n"); return -1; } /* Because unlinking a file changes the order of the directory entries * - specifically, it moves a directory entry into the spot where the * unlinked file's directory entry was - this loop starts over every * time a file is unlinked. The pseudocode is: * * repeat * open the directory. * find the first directory entry that is neither . nor .. * unlink it * close the directory * until only . and .. are left */ while ( got_one ) { got_one = 0; /* Open up the directory */ if ( (f = do_open(argv[1], O_RDONLY)) < 0 ) { kprintf(ksh, "Open failed on %s: %d %s\n", argv[1], f, strerror(-f)); return -1; } while ( ( rv = do_getdent(f, &d)) > 0 ) { /* Keep looking if d contains . or .. */ if ( strncmp(".", d.d_name, NAME_LEN) == 0 || strncmp("..", d.d_name, NAME_LEN) == 0 ) continue; /* Found a name to delete. Construct the path and delete it */ snprintf(buf, TESTBUFLEN, "%s/%s", argv[1], d.d_name); kprintf(ksh, "unlinking %s\n", buf); if ( (rv = do_unlink(buf)) < 0 ) { /* Something went wrong- d probably points to a directory. * Report the error, close f, and terminate the command. */ kprintf(ksh, "Unlink failed on %s: %d %s\n", buf, rv, strerror(-rv)); do_close(f); return rv; } got_one = 1; /* CLose the directory and restart (because it set got_one) */ break; } do_close(f); /* This branch will be taken if do_getdent fails */ if ( rv < 0 ) { kprintf(ksh, "get_dent failed on %s: %d %s\n", argv[1], rv, strerror(-rv)); return rv; } } /* OK, deleted everything we could. */ return rv; } #endif /* __VFS__ */ <file_sep>/kernel/include/drivers/tty/n_tty.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #include "drivers/tty/ldisc.h" #include "proc/kmutex.h" /* * The default line discipline. */ typedef struct n_tty n_tty_t; /** * Allocate and initialize an n_tty line discipline, which is not yet * attached to a tty. * * @return a newly allocated n_tty line discipline */ tty_ldisc_t *n_tty_create(); /** * Destory an n_tty line discipline. * * @param ntty the n_tty line discipline to destroy */ void n_tty_destroy(tty_ldisc_t *ntty); <file_sep>/kernel/test/kshell/tokenizer.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "tokenizer.h" #include <ctype.h> #include "util/debug.h" #define EOL '\0' const char *ksh_tok_type_str[] = { "text", "<", ">", ">>", "end of line", "" }; int kshell_next_token(kshell_t *ksh, char *line, kshell_token_t *token) { KASSERT(NULL != ksh); KASSERT(NULL != line); KASSERT(NULL != token); int i = 0; while (line[i] != EOL && isspace(line[i])) ++i; token->kt_text = line + i; /* Determine the token type */ switch (line[i]) { case EOL: token->kt_type = KTT_EOL; token->kt_textlen = 0; break; case '<': token->kt_type = KTT_REDIRECT_IN; token->kt_textlen = i = 1; break; case '>': if (line[i + 1] == '>') { token->kt_type = KTT_REDIRECT_OUT_APPEND; token->kt_textlen = i = 2; } else { token->kt_type = KTT_REDIRECT_OUT; token->kt_textlen = i = 1; } break; default: token->kt_type = KTT_WORD; token->kt_textlen = 0; break; } switch (token->kt_type) { case KTT_WORD: while (!isspace(line[i]) && line[i] != '<' && line[i] != '>' && line[i] != EOL) { ++i; ++token->kt_textlen; } break; case KTT_EOL: return 0; default: break; } return i; } const char *kshell_token_type_str(kshell_token_type_t type) { KASSERT(type < KTT_MAX); return ksh_tok_type_str[type]; } <file_sep>/kernel/include/util/bits.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once #include "types.h" #include "kernel.h" #define BIT(n) (1<<(n)) static inline void bit_flip(void *addr, uintptr_t bit) { uint32_t *map = (uint32_t *)addr; map += (bit >> 5); *map ^= (uint32_t)(1 << (bit & 0x1f)); } static inline int bit_check(const void *addr, uintptr_t bit) { const uint32_t *map = (const uint32_t *)addr; map += (bit >> 5); return (*map & (1 << (bit & 0x1f))); } <file_sep>/kernel/include/types.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once /* Kernel and user header (via symlink) */ #define NULL 0 typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed short int16_t; typedef unsigned short uint16_t; typedef signed int int32_t; typedef unsigned int uint32_t; #if defined(__i386__) typedef signed long long int64_t; typedef unsigned long long uint64_t; typedef signed int intptr_t; typedef unsigned int uintptr_t; #elif defined(__x86_64__) || defined(__ia64__) typedef signed long int64_t; typedef unsigned long uint64_t; typedef signed long intptr_t; typedef unsigned long uintptr_t; #endif typedef uint32_t size_t; typedef int32_t ssize_t; typedef int32_t off_t; typedef int64_t off64_t; typedef int32_t pid_t; typedef uint16_t mode_t; typedef uint32_t blocknum_t; typedef uint32_t ino_t; typedef uint32_t devid_t; <file_sep>/kernel/proc/kmutex.c /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #include "globals.h" #include "errno.h" #include "util/debug.h" #include "proc/kthread.h" #include "proc/kmutex.h" /* * IMPORTANT: Mutexes can _NEVER_ be locked or unlocked from an * interrupt context. Mutexes are _ONLY_ lock or unlocked from a * thread context. */ void kmutex_init(kmutex_t *mtx) { /* NOT_YET_IMPLEMENTED("PROCS: kmutex_init"); */ /*dbg(DBG_PRINT, "(GRADING1D 1)\n");*/ dbg(DBG_PRINT, "(GRADING1D)\n"); sched_queue_init(&mtx->km_waitq); mtx->km_holder = NULL; } /* * This should block the current thread (by sleeping on the mutex's * wait queue) if the mutex is already taken. * * No thread should ever try to lock a mutex it already has locked. */ void kmutex_lock(kmutex_t *mtx) { /*dbg(DBG_PRINT, "Lock mutex\n");*/ /* NOT_YET_IMPLEMENTED("PROCS: kmutex_lock");*/ KASSERT(curthr && (curthr != mtx->km_holder)); dbg(DBG_PRINT, "(GRADING1A 5.a)\n"); /*dbg(DBG_PRINT, "(GRADING1D 1)\n");*/ dbg(DBG_PRINT, "(GRADING1D)\n"); if (mtx->km_holder != NULL) { /*dbg(DBG_PRINT, "Enqueue to mutex queue\n");*/ sched_sleep_on(&mtx->km_waitq); } /*dbg(DBG_PRINT, "Current thread holds mutex\n");*/ mtx->km_holder = curthr; /* dbg(DBG_ERROR, "lock mutex holder curr id: %d\n", mtx->km_holder->kt_proc->p_pid);*/ } /* * This should do the same as kmutex_lock, but use a cancellable sleep * instead. */ int kmutex_lock_cancellable(kmutex_t *mtx) { /* NOT_YET_IMPLEMENTED("PROCS: kmutex_lock_cancellable"); */ int retVal = 0; KASSERT(curthr && (curthr != mtx->km_holder)); dbg(DBG_PRINT, "(GRADING1A 5.b)\n"); /*dbg(DBG_PRINT, "(GRADING1C 7)\n");*/ dbg(DBG_PRINT, "(GRADING1C)\n"); if (mtx->km_holder != NULL) { dbg(DBG_PRINT, "(GRADING1C)\n"); retVal = sched_cancellable_sleep_on(&(mtx->km_waitq)); } else { mtx->km_holder = curthr; } /*dbg(DBG_PRINT, "Current thread holds mutex\n");*/ if (retVal >= 0) { mtx->km_holder = curthr; } /*dbg(DBG_ERROR, "cancellable lock mutex holder curr id: %d\n", mtx->km_holder->kt_proc->p_pid);*/ return retVal; } /* * If there are any threads waiting to take a lock on the mutex, one * should be woken up and given the lock. * * Note: This should _NOT_ be a blocking operation! * * Note: Don't forget to add the new owner of the mutex back to the * run queue. * * Note: Make sure that the thread on the head of the mutex's wait * queue becomes the new owner of the mutex. * * @param mtx the mutex to unlock */ void kmutex_unlock(kmutex_t *mtx) { /*NOT_YET_IMPLEMENTED("PROCS: kmutex_unlock");*/ /*dbg(DBG_PRINT, "unlock mutex holder curr id: %d\n", curthr->kt_proc->p_pid);*/ KASSERT(curthr && (curthr == mtx->km_holder)); dbg(DBG_PRINT, "(GRADING1A 5.c)\n"); /*dbg(DBG_PRINT, "(GRADING1D 1)\n");*/ dbg(DBG_PRINT, "(GRADING1D)\n"); /*dbg(DBG_PRINT, "Switching mutex to new thread");*/ mtx->km_holder = sched_wakeup_on(&mtx->km_waitq); KASSERT(curthr != mtx->km_holder); } <file_sep>/kernel/include/mm/slab.h /******************************************************************************/ /* Important Spring 2015 CSCI 402 usage information: */ /* */ /* This fils is part of CSCI 402 kernel programming assignments at USC. */ /* Please understand that you are NOT permitted to distribute or publically */ /* display a copy of this file (or ANY PART of it) for any reason. */ /* If anyone (including your prospective employer) asks you to post the code, */ /* you must inform them that you do NOT have permissions to do so. */ /* You are also NOT permitted to remove or alter this comment block. */ /* If this comment block is removed or altered in a submitted file, 20 points */ /* will be deducted. */ /******************************************************************************/ #pragma once /* Define SLAB_REDZONE to add top and bottom redzones to every object. * Use kmem_check_redzones() liberally throughout your code to test * for memory pissing. */ #define SLAB_REDZONE 0xdeadbeef /* Define SLAB_CHECK_FREE to add extra book keeping to make sure there * are no double frees. */ #define SLAB_CHECK_FREE /* * The slab allocator. A "cache" is a store of objects; you create one by * specifying a constructor, destructor, and the size of an object. The * "alloc" function allocates one object, and the "free" function returns * it to the free list *without calling the destructor*. This lets you save * on destruction/construction calls; the idea is that every free object in * the cache is in a known state. */ typedef struct slab_allocator slab_allocator_t; slab_allocator_t *slab_allocator_create(const char *name, size_t size); int slab_allocators_reclaim(int target); void *slab_obj_alloc(slab_allocator_t *allocator); void slab_obj_free(slab_allocator_t *allocator, void *obj);
a8fe56c633588aa7e0e0299d1af14f7727631ee5
[ "C", "Makefile" ]
43
C
darshanramu/LinuxLikeOS
863c151588a9233d69fbc46794dbcc6e580c312e
5e54605accfc61e04c0b12f8a577ecedf3a964bf
refs/heads/master
<file_sep>import React from 'react'; import "./main.css"; import Divider from '@mui/material/Divider'; import Paper from '@mui/material/Paper'; import MenuList from '@mui/material/MenuList'; import MenuItem from '@mui/material/MenuItem'; import ListItemText from '@mui/material/ListItemText'; const list = ["Featured Auckland deals", "Collections", "Escapes", "Picked for you", "Store", "Automotiv", "Fitness & sports "] const Main = () => { return ( <div className="mai"> <div className="desktopheaderimage"> <img className="mainimg" src="https://mediacdn.grabone.co.nz/asset/E8rOLoskPU" /> <p>Covid 19 Update: We encourage you to shop as normal for all your products but shipping delays may occur. Stay safe NZ!</p> <p>Full Early Bird Christmas terms and conditions here.</p> </div> <div className="mainItem"> <div className="menuMain"> <Paper sx={{ width: 350, maxWidth: '100%' }}> {list.map(item => <MenuList> <MenuItem> <ListItemText>{item}</ListItemText> </MenuItem> <Divider /></MenuList> )} </Paper> </div> <div className="divCl"> <img className="im" src="https://www.scubastore.com/f/13785/137858413/adidas-logo-3-units-face-mask.jpg" /> <hr /> <h1> Face Mask </h1> <p> price : 10 $</p> </div> <div className="divCl"> <img className="im" src="https://m.media-amazon.com/images/I/612oCx1r4hL._AC_UL480_FMwebp_QL65_.jpg" /> <hr /> <h1> Nike T Shirt </h1> <p> price : 50 $</p> </div> </div> </div> ) }; export default Main; <file_sep>import React from 'react'; import "./navigation.css" import { styled, alpha } from '@mui/material/styles'; import InputBase from '@mui/material/InputBase'; import SearchIcon from '@mui/icons-material/Search'; const Search = styled('div')(({ theme }) => ({ position: 'relative', borderRadius: theme.shape.borderRadius, backgroundColor: alpha(theme.palette.common.white, 0.15), '&:hover': { backgroundColor: alpha(theme.palette.common.white, 0.25), }, marginLeft: 0, width: '100%', [theme.breakpoints.up('sm')]: { marginLeft: theme.spacing(1), width: 'auto', }, })); const SearchIconWrapper = styled('div')(({ theme }) => ({ padding: theme.spacing(0, 2), height: '100%', position: 'absolute', pointerEvents: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', })); const StyledInputBase = styled(InputBase)(({ theme }) => ({ color: 'inherit', '& .MuiInputBase-input': { padding: theme.spacing(1, 1, 1, 0), // vertical padding + font size from searchIcon paddingLeft: `calc(1em + ${theme.spacing(4)})`, transition: theme.transitions.create('width'), width: '100%', [theme.breakpoints.up('sm')]: { width: '12ch', '&:focus': { width: '20ch', }, }, }, })); const Navigation = () => { return ( <div className="nav"> <select name="cars" id="cars" className="leftNavList"> <option>Browse categories </option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> <p className="leftNav"> whats new </p> <p className="leftNav">Trendeng</p> <p className="leftNav">For You</p> <p className="leftNav">Shop products</p> <div className="rightNav"> <Search> <SearchIconWrapper> <SearchIcon /> </SearchIconWrapper> <StyledInputBase placeholder="Search…" inputProps={{ 'aria-label': 'search' }} /> </Search> </div> </div>) }; export default Navigation; <file_sep>import React from 'react'; import { Route } from 'react-router-dom'; import Header from "../src/components/header"; import Navigation from "../src/components/navigation"; import Main from "./components/main"; import "./App.css"; const App = () => { return ( <div> <Header/> <Navigation/> <Main/> </div> ) }; export default App;
a042646a21fabf5c9e103620109e31486e1c08b9
[ "JavaScript" ]
3
JavaScript
bridgecrew-perf7/abd-alghani-task-deploy
1a807324afded6d0a181c2e6d66211045b9bdeb8
c15a14934b3485e477de6e75fe1c5d531286ccc0
refs/heads/master
<file_sep><?php /** * @package Fuel\Alias * @version 2.0 * @author Fuel Development Team * @license MIT License * @copyright 2010 - 2014 Fuel Development Team * @link http://fuelphp.com */ namespace Fuel\Alias\Providers; use League\Container\ServiceProvider; /** * Fuel ServiceProvider class for Alias * * @package Fuel\Alias * * @since 2.0 */ class FuelServiceProvider extends ServiceProvider { /** * @var array */ protected $provides = ['alias']; /** * {@inheritdoc} */ public function register() { $this->container->singleton('alias', 'Fuel\Alias\Manager') ->withMethodCall('register'); } } <file_sep><?php namespace Fuel\Alias; class ResolverTest extends \Codeception\TestCase\Test { public function testResolveWithoutRegex() { $resolver = new Resolver('pattern', 'stdClass'); $this->assertEquals('stdClass', $resolver->resolve('pattern')); } public function testResolveWithRegex() { $resolver = new Resolver('Pattern\*', '$1'); $this->assertEquals('stdClass', $resolver->resolve('Pattern\stdClass')); } public function testFailingResolve() { $resolver = new Resolver('pattern', 'translation'); $this->assertFalse($resolver->resolve('other_pattern')); $this->assertFalse($resolver->resolve('pattern')); } public function testMatches() { $resolver = new Resolver('pattern', 'translation'); $this->assertTrue($resolver->matches('pattern')); $this->assertTrue($resolver->matches('pattern', 'translation')); $this->assertFalse($resolver->matches('other_pattern', 'translation')); $this->assertFalse($resolver->matches('pattern', 'other_translation')); $this->assertFalse($resolver->matches('other_pattern', 'other_translation')); $this->assertFalse($resolver->matches('other_pattern')); } } <file_sep><?php /** * Fuel Alias Caching * * This file is used to cache class aliases. */<file_sep># Fuel Alias [![Build Status](https://img.shields.io/travis/fuelphp/alias.svg?style=flat-square)](https://travis-ci.org/fuelphp/alias) [![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/fuelphp/alias.svg?style=flat-square)](https://scrutinizer-ci.com/g/fuelphp/alias) [![Quality Score](https://img.shields.io/scrutinizer/g/fuelphp/alias.svg?style=flat-square)](https://scrutinizer-ci.com/g/fuelphp/alias) [![HHVM Status](https://img.shields.io/hhvm/fuelphp/alias.svg?style=flat-square)](http://hhvm.h4cc.de/package/fuelphp/alias) **Library for lazy class aliasing.** ## Install Via Composer ``` bash $ composer require fuelphp/alias ``` ## Usage Within FuelPHP class aliases are used to provide easy access to namespaced classes and facilitate class inheritance injection. The package exposes an alias manager which lets you create 3 types of aliases: * __Literal__<br/>A one-to-one translation. Class "Namespaced\\Classname" translates to "Another\\Classname". * __Namespace__<br/>Namespace aliases allow you to alias an entire namespace with one call. * __Replacement__<br/>A pattern is matched an through replacements a new class is generated. "Namespace\\*" maps to "Alias\\$1". When registering the alias manager append or prepends itself to the autoload stack to act as a pre-processor or fallback. Depending on the amount of aliases and it could be beneficial to alternate between pre- or appending. By default the manager will prepend itself to the autoloader stack. ### Basic Usage ```php // Create a new alias manager $manager = new Fuel\Alias\Manager; // Register the manager $manager->register(); // Alias one class $manager->alias('Alias\Me', 'To\This'); // Or alias many $manager->alias([ 'Alias\This' => 'To\Me', 'AndAlias\This' => 'To\SomethingElse', ]); // ``` ### Namespace usage ```php // alias to a less deep namespace $manager->aliasNamespace('Less\Deep', 'Some\Super\Deep\Name\Space'); // alias a namespace to global $manager->aliasNamespace('Some\Space', ''); ``` ### Pattern Usage ```php $manager = new Fuel\Alias\Manager; // Alias with wildcards $manager->aliasPattern('Namespaced\*', 'Other\\$1'); $otherThing = new Namespaced\Thing; ``` This can result into class resolving that doesn't exists. Luckily the package is smart enough the check wether the class exists and will continue to look for the correct class if the resolved class does not exist. This is also taken into account when it comes to caching. Only resolved classes that exist will be cached. ## Contributing Thank you for considering contribution to FuelPHP framework. Please see [CONTRIBUTING](https://github.com/fuelphp/fuelphp/blob/master/CONTRIBUTING.md) for details. ## License The MIT License (MIT). Please see [License File](LICENSE) for more information. <file_sep><?php /** * @package Fuel\Alias * @version 2.0 * @author Fuel Development Team * @license MIT License * @copyright 2010 - 2015 Fuel Development Team * @link http://fuelphp.com */ namespace Fuel\Alias; /** * Preserved for BC reasons */ interface CacheInterface extends Cache { } <file_sep><?php namespace Check; class ItOut {} <file_sep><?php /** * Fuel Alias Caching * * This file is used to cache class aliases. */ $manager->alias(array( 'MyObject' => 'Dummy', 'Dummy' => 'Pref\Dummy', 'Pref\Dummy' => 'Prefixed\Dummy\Wooo', 'Prefixed\Dummy\Wooo' => 'Dummy\Wooo\Prefixed', 'Dummy\Wooo\Prefixed' => 'Wooo\Prefixed\Dummy', ));<file_sep><?php /** * @package Fuel\Alias * @version 2.0 * @author Fuel Development Team * @license MIT License * @copyright 2010 - 2015 Fuel Development Team * @link http://fuelphp.com */ namespace Fuel\Alias; trait ObjectTester { /** * Checks various object types for existence */ protected function objectExists($object, $autoload = true) { return class_exists($object, $autoload) or interface_exists($object, $autoload) or trait_exists($object, $autoload); } } <file_sep><?php /** * @package Fuel\Alias * @version 2.0 * @author Fuel Development Team * @license MIT License * @copyright 2010 - 2015 Fuel Development Team * @link http://fuelphp.com */ namespace Fuel\Alias; class Resolver { use ObjectTester; /** * @var string */ protected $regex; /** * @var string $pattern */ protected $pattern; /** * @var string|callable $translation */ protected $translation; /** * @var boolean */ protected $active = false; /** * @param string $pattern * @param string|callable $translation */ public function __construct($pattern, $translation) { $regex = preg_quote($pattern, '#'); $this->regex = '#^'.str_replace('\\*', '(.*)', $regex).'$#uD'; $this->pattern = $pattern; $this->translation = $translation; } /** * Resolves an alias * * @param string $alias * * @return string|boolean */ public function resolve($alias) { // Check wether the alias matches the pattern if ( ! preg_match($this->regex, $alias, $matches)) { return false; } // Get the translation $translation = $this->translation; if (strpos($translation, '$') === false) { $class = $translation; } else { // Make sure namespace seperators are escaped $translation = str_replace('\\', '\\\\', $translation); // Resolve the replacement $class = preg_replace($this->regex, $translation, $alias); } // Check wether the class exists if ($class and $this->objectExists($class, true)) { return $class; } return false; } /** * Checks whether the resolver matches a given pattern and optional translation * * @param string $pattern * @param string|callable $translation * * @return boolean */ public function matches($pattern, $translation = null) { return $this->pattern === $pattern and (!$translation or $translation === $this->translation); } }
32f985e9d2690176fb7835cc64ec78a69f0e3b40
[ "Markdown", "PHP" ]
9
PHP
fuelphp-storage/alias
911cf6caab6b35becd19f30c57768ba977bcec9d
49c722610d4f2003664b5029fdd6f27bd5b5e481
refs/heads/master
<file_sep>from despatchbay.despatchbay_sdk import DespatchBaySDK client = DespatchBaySDK(api_user='<APIUSER>', api_key='<APIKEY>') my_parcel_1 = client.parcel( weight=3, length=14, width=15, height=92, contents='Apples', value=65 ) my_parcel_2 = client.parcel( weight=30, length=100, width=100, height=100, contents='Oranges', value=1 ) recipient_address = client.address( company_name="Acme", country_code="GB", county="Theshire", locality="Placeton", postal_code="ps76de", town_city="Cityville", street="123 Fake Street" ) recipient = client.recipient( name="<NAME>", telephone="01632987654", email="<EMAIL>", recipient_address=recipient_address ) # Sender using address_id sender = client.sender( name="<NAME>", telephone="01632123456", email="<EMAIL>", address_id='123456' ) shipment_request = client.shipment_request( parcels=[my_parcel_1, my_parcel_2], client_reference='puchacz', collection_date='2019-04-01', sender_address=sender, recipient_address=recipient, follow_shipment='true' ) services = client.get_available_services(shipment_request) shipment_request.service_id = services[0].service_id dates = client.get_available_collection_dates(sender, services[0].courier.courier_id) shipment_request.collection_date = dates[0] added_shipment = client.add_shipment(shipment_request) client.book_shipments([added_shipment]) shipment_return = client.get_shipment(added_shipment) label_pdf = client.get_labels(shipment_return.shipment_document_id) label_pdf.download('./new_label.pdf') <file_sep>from despatchbay.despatchbay_sdk import DespatchBaySDK client = DespatchBaySDK(api_user='<APIUSER>', api_key='<APIKEY') tracking = client.get_tracking('DEMO1234567890123456') print(tracking) <file_sep>from despatchbay.despatchbay_sdk import DespatchBaySDK client = DespatchBaySDK(api_user='<APIUSER>', api_key='<APIKEY>') address_1 = client.find_address('DN227AY', '1') print(address_1) address_2 = client.get_address_by_key('DN227AY0001') print(address_2) address_3 = client.get_address_keys_by_postcode('DN22 7AY') print(address_3) <file_sep>""" Client for the Despatchbay v15 api https://github.com/despatchbay/despatchbay-api-v15/wiki """ from suds.client import Client from suds.transport.http import HttpAuthenticated import suds from . import despatchbay_entities, documents_client, exceptions MIN_SOAP_API_VERSION = 15 MIN_DOCUMENTS_API_VERSION = 1 def handle_suds_fault(error): """ Throws despatchbaysdk exceptions in response to suds exceptions """ try: exception_info = error.args[0].decode() except AttributeError: exception_info = error.args[0] if 'Unauthorized' in exception_info: raise exceptions.AuthorizationException('Invalid API credentials') from error if 'Could not connect to host' in exception_info: raise exceptions.ConnectionException('Failed to connect to the Despatch Bay API') from error if 'Your access rate limit for this service has been exceeded' in exception_info: raise exceptions.RateLimitException(exception_info) # Re-raise general suds exceptions as exceptions.ApiException raise exceptions.ApiException(error) from error def handle_suds_generic_fault(error): """ Throws despatchbaysdk exceptions in response to suds generic 'Exception' exceptions """ try: exception_info = error.args[0].decode() except AttributeError: exception_info = error.args[0] if 401 in exception_info: raise exceptions.AuthorizationException('Invalid API credentials') from error if 429 in exception_info: raise exceptions.RateLimitException(exception_info[1]) # Re-raise original error raise error def try_except(function): """ A decorator to catch suds exceptions """ def wrapped(*args, **kwargs): try: return function(*args, **kwargs) except suds.WebFault as detail: handle_suds_fault(detail) except Exception as detail: handle_suds_generic_fault(detail) return wrapped class DespatchBaySDK: """ Client for despatchbay v15 api. https://github.com/despatchbay/despatchbay-api-v15/wiki """ def __init__(self, api_user, api_key, api_domain='api.despatchbay.com', despactchbay_api_version=MIN_SOAP_API_VERSION, documents_api_version=MIN_DOCUMENTS_API_VERSION): if despactchbay_api_version < MIN_SOAP_API_VERSION: raise exceptions.ApiException("DespatchBay API version must be 15 or higher.") if documents_api_version < MIN_DOCUMENTS_API_VERSION: raise exceptions.ApiException("Documents API version must be 1 or higher.") soap_url_template = 'http://{}/soap/v{}/{}?wsdl' documents_url = 'http://{}/documents/v{}'.format(api_domain, documents_api_version) account_url = soap_url_template.format(api_domain, despactchbay_api_version, 'account') shipping_url = soap_url_template.format(api_domain, despactchbay_api_version, 'shipping') addressing_url = soap_url_template.format(api_domain, despactchbay_api_version, 'addressing') tracking_url = soap_url_template.format(api_domain, despactchbay_api_version, 'tracking') self.account_client = Client( account_url, transport=self.create_transport(api_user, api_key)) self.addressing_client = Client( addressing_url, transport=self.create_transport(api_user, api_key)) self.shipping_client = Client( shipping_url, transport=self.create_transport(api_user, api_key)) self.tracking_client = Client( tracking_url, transport=self.create_transport(api_user, api_key)) self.pdf_client = documents_client.DocumentsClient(api_url=documents_url) @staticmethod def create_transport(username, password): """ HTTP transport providing authentication for suds. """ return HttpAuthenticated(username=username, password=<PASSWORD>) # Shipping entities def parcel(self, **kwargs): """ Creates a dbp parcel entity """ return despatchbay_entities.Parcel(self, **kwargs) def address(self, **kwargs): """ Creates a dbp address entity """ return despatchbay_entities.Address(self, **kwargs) def recipient(self, **kwargs): """ Creates a dbp recipient address entity """ return despatchbay_entities.Recipient(self, **kwargs) def sender(self, **kwargs): """ Creates a dbp sender address entity """ return despatchbay_entities.Sender(self, **kwargs) def shipment_request(self, **kwargs): """ Creates a dbp shipment entity """ return despatchbay_entities.ShipmentRequest(self, **kwargs) # Account Services @try_except def get_account(self): """Calls GetAccount from the Despatch Bay Account Service.""" account_dict = self.account_client.dict(self.account_client.service.GetAccount()) return despatchbay_entities.Account.from_dict( self, account_dict ) @try_except def get_account_balance(self): """ Calls GetBalance from the Despatch Bay Account Service. """ balance_dict = self.account_client.dict(self.account_client.service.GetAccountBalance()) return despatchbay_entities.AccountBalance.from_dict( self, balance_dict ) @try_except def get_sender_addresses(self): """ Calls GetSenderAddresses from the Despatch Bay Account Service. """ sender_addresses_dict_list = [] for sender_address in self.account_client.service.GetSenderAddresses(): sender_address_dict = self.account_client.dict(sender_address) sender_addresses_dict_list.append(despatchbay_entities.Sender.from_dict( self, sender_address_dict)) return sender_addresses_dict_list @try_except def get_services(self): """ Calls GetServices from the Despatch Bay Account Service. """ service_list = [] for account_service in self.account_client.service.GetServices(): service_list.append( despatchbay_entities.Service.from_dict( self, self.account_client.dict(account_service) )) return service_list @try_except def get_payment_methods(self): """ Calls GetPaymentMethods from the Despatch Bay Account Service. """ payment_methods = [] for payment_method in self.account_client.service.GetPaymentMethods(): payment_methods.append( despatchbay_entities.PaymentMethod.from_dict( self, self.account_client.dict(payment_method) ) ) return payment_methods @try_except def enable_automatic_topups(self, minimum_balance=None, topup_amount=None, payment_method_id=None, automatic_topup_settings_object=None): """ Calls EnableAutomaticTopups from the Despatch Bay Account Service. Passing an automatic_topup_settings object takes priority over using individual arguments. """ if not automatic_topup_settings_object: automatic_topup_settings_object = despatchbay_entities.AutomaticTopupSettings( self, minimum_balance, topup_amount, payment_method_id) return self.account_client.service.EnableAutomaticTopups( automatic_topup_settings_object.to_soap_object()) @try_except def disable_automatic_topups(self): """ Calls DisableAutomaticTopups from the Despatch Bay Account Service. """ return self.account_client.service.DisableAutomaticTopups() # Addressing Services @try_except def find_address(self, postcode, property_string): """ Calls FindAddress from the Despatch Bay Addressing Service. """ found_address_dict = self.addressing_client.dict( self.addressing_client.service.FindAddress( postcode, property_string )) return despatchbay_entities.Address.from_dict( self, found_address_dict ) @try_except def get_address_by_key(self, key): """ Calls GetAddressByKey from the Despatch Bay Addressing Service. """ found_address_dict = self.addressing_client.dict( self.addressing_client.service.GetAddressByKey(key) ) return despatchbay_entities.Address.from_dict( self, found_address_dict ) @try_except def get_address_keys_by_postcode(self, postcode): """ Calls GetAddressKeysFromPostcode from the Despatch Bay Addressing Service. """ address_keys_dict_list = [] for soap_address_key in self.addressing_client.service.GetAddressKeysByPostcode(postcode): address_key_dict = self.account_client.dict(soap_address_key) address_keys_dict_list.append(despatchbay_entities.AddressKey.from_dict( self, address_key_dict)) return address_keys_dict_list # Shipping services @try_except def get_available_services(self, shipment_request): """ Calls GetAvailableServices from the Despatch Bay Shipping Service. """ available_service_dict_list = [] for available_service in self.shipping_client.service.GetAvailableServices( shipment_request.to_soap_object()): available_service_dict = self.shipping_client.dict(available_service) available_service_dict_list.append(despatchbay_entities.Service.from_dict( self, available_service_dict)) return available_service_dict_list @try_except def get_available_collection_dates(self, sender_address, courier_id): """ Calls GetAvailableCollectionDates from the Despatch Bay Shipping Service. """ available_collection_dates_response = self.shipping_client.service.GetAvailableCollectionDates( sender_address.to_soap_object(), courier_id) available_collection_dates_list = [] for collection_date in available_collection_dates_response: collection_date_dict = self.shipping_client.dict(collection_date) available_collection_dates_list.append( despatchbay_entities.CollectionDate.from_dict(self, collection_date_dict)) return available_collection_dates_list @try_except def get_collection(self, collection_id): """ Calls GetCollection from the Despatch Bay Shipping Service. """ collection_dict = self.shipping_client.dict( self.shipping_client.service.GetCollection(collection_id)) return despatchbay_entities.Collection.from_dict( self, collection_dict ) @try_except def get_collections(self): """ Calls GetCollections from the Despatch Bay Shipping Service. """ collections_dict_list = [] for found_collection in self.shipping_client.service.GetCollections(): collection_dict = self.shipping_client.dict(found_collection) collections_dict_list.append( despatchbay_entities.Collection.from_dict( self, collection_dict ) ) return collections_dict_list @try_except def get_shipment(self, shipment_id): """ Calls GetShipment from the Despatch Bay Shipping Service. """ shipment_dict = self.shipping_client.dict( self.shipping_client.service.GetShipment(shipment_id)) return despatchbay_entities.ShipmentReturn.from_dict( self, shipment_dict ) @try_except def add_shipment(self, shipment_request): """ Calls AddShipment from the Despatch Bay Shipping Service. """ return self.shipping_client.service.AddShipment(shipment_request.to_soap_object()) @try_except def book_shipments(self, shipment_ids): """ Calls BookShipments from the Despatch Bay Shipping Service. """ array_of_shipment_id = self.shipping_client.factory.create('ns1:ArrayOfShipmentID') array_of_shipment_id.item = shipment_ids booked_shipments_list = [] for booked_shipment in self.shipping_client.service.BookShipments(array_of_shipment_id): booked_shipment_dict = self.shipping_client.dict(booked_shipment) booked_shipments_list.append( despatchbay_entities.ShipmentReturn.from_dict( self, booked_shipment_dict ) ) return booked_shipments_list @try_except def cancel_shipment(self, shipment_id): """ Calls CancelShipment from the Despatch Bay Shipping Service. """ return self.shipping_client.service.CancelShipment(shipment_id) # Tracking services @try_except def get_tracking(self, tracking_number): """ Calls GetTracking from the Despatch Bay Tracking Service. """ return self.tracking_client.service.GetTracking(tracking_number) # Documents services def get_labels(self, document_ids, **kwargs): """ Fetches labels from the Despatch Bay documents API. """ return self.pdf_client.get_labels(document_ids, **kwargs) def get_manifest(self, collection_document_id, **kwargs): """ Fetches manifests from the Despatch Bay documents API. """ return self.pdf_client.get_manifest(collection_document_id, **kwargs) <file_sep># Despatch Bay Python SDK <file_sep>""" Entities relating to types in the Despatchbay v15 api https://github.com/despatchbay/despatchbay-api-v15/wiki """ class Entity: """Base class for Despatchbay entities""" def __init__(self, soap_type, soap_client, soap_map): self.soap_type = soap_type self.soap_client = soap_client self.soap_map = soap_map def to_soap_object(self): """ Creates a SOAP client object representation of this entity. """ suds_object = self.soap_client.factory.create(self.soap_type) for soap_property in self.soap_map: if self.soap_map[soap_property]['type'] == 'entity': setattr( suds_object, soap_property, getattr( self, self.soap_map[soap_property]['property']).to_soap_object() ) elif self.soap_map[soap_property]['type'] == 'entityArray': entity_list = [] for entity in getattr(self, self.soap_map[soap_property]['property']): entity_list.append(entity.to_soap_object()) soap_array = self.soap_client.factory.create(self.soap_map[soap_property]['soap_type']) soap_array.item = entity_list soap_array._arrayType = 'urn:ArrayType[]' setattr(suds_object, soap_property, soap_array) else: setattr( suds_object, soap_property, getattr( self, self.soap_map[soap_property]['property'] ) ) return suds_object def __repr__(self): return str(self.to_soap_object()) class Account(Entity): """ Represents a Despactchbay API AccountType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Account-Service#accounttype """ SOAP_MAP = { 'AccountID': { 'property': 'account_id', 'type': 'integer' }, 'AccountName': { 'property': 'name', 'type': 'string' }, 'AccountBalance': { 'property': 'balance', 'type': 'entity', 'soap_type': 'ns1:AccountBalanceType', } } SOAP_TYPE = 'ns1:AccountType' def __init__(self, client, account_id=None, name=None, balance=None): super().__init__(self.SOAP_TYPE, client.account_client, self.SOAP_MAP) self.account_id = account_id self.name = name self.balance = balance @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, account_id=soap_dict.get('AccountID', None), name=soap_dict.get('AccountName', None), balance=AccountBalance.from_dict( client, client.account_client.dict(soap_dict.get('AccountBalance', None)) ) ) class AccountBalance(Entity): """ Represents a Despactchbay API AccountBalanceType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Account-Service#accountbalancetype """ SOAP_MAP = { 'Balance': { 'property': 'balance', 'type': 'float' }, 'AvailableBalance': { 'property': 'available', 'type': 'float' } } SOAP_TYPE = 'ns1:AccountBalanceType' def __init__(self, client, balance=None, available=None): super().__init__(self.SOAP_TYPE, client.account_client, self.SOAP_MAP) self.balance = balance self.available = available @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, balance=soap_dict.get('Balance', None), available=soap_dict.get('AvailableBalance', None) ) class Address(Entity): """ Represents a Despactchbay API AddressType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Account-Service#addresstype """ SOAP_MAP = { 'CompanyName': { 'property': 'company_name', 'type': 'string', }, 'Street': { 'property': 'street', 'type': 'string', }, 'Locality': { 'property': 'locality', 'type': 'string', }, 'TownCity': { 'property': 'town_city', 'type': 'string', }, 'County': { 'property': 'county', 'type': 'string', }, 'PostalCode': { 'property': 'postal_code', 'type': 'string', }, 'CountryCode': { 'property': 'country_code', 'type': 'string', } } SOAP_TYPE = 'ns1:AddressType' def __init__(self, client, company_name=None, street=None, locality=None, town_city=None, county=None, postal_code=None, country_code=None): super().__init__(self.SOAP_TYPE, client.addressing_client, self.SOAP_MAP) self.company_name = company_name self.street = street self.locality = locality self.town_city = town_city self.county = county self.postal_code = postal_code self.country_code = country_code @classmethod def from_dict(cls, client, soap_dict): """ Alternative initialiser, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, company_name=soap_dict.get('CompanyName', None), street=soap_dict.get('Street', None), locality=soap_dict.get('Locality', None), town_city=soap_dict.get('TownCity', None), county=soap_dict.get('County', None), postal_code=soap_dict.get('PostalCode', None), country_code=soap_dict.get('CountryCode', None) ) class AddressKey(Entity): """ Represents a Despactchbay API AddressKeyType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Addressing-Service#addresskeytype """ SOAP_MAP = { 'Key': { 'property': 'key', 'type': 'string', }, 'Address': { 'property': 'address', 'type': 'string', } } SOAP_TYPE = 'ns1:AddressKeyType' def __init__(self, client, key, address): super().__init__(self.SOAP_TYPE, client.addressing_client, self.SOAP_MAP) self.key = key self.address = address @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, key=soap_dict.get('Key', None), address=soap_dict.get('Address', None) ) class AutomaticTopupSettings(Entity): """ Represents a Despactchbay API AutomaticTopupSettings entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Account-Service#automatictopupsettings """ SOAP_MAP = { "MinimumBalance": { "property": "minimum_balance", "type": "float" }, "TopupAmount": { "property": "topup_amount", "type": "float" }, "PaymentMethodID": { "property": "payment_method_id", "type": "string" } } SOAP_TYPE = 'ns1:AutomaticTopupsSettingsRequestType' def __init__(self, client, minimum_balance=None, topup_amount=None, payment_method_id=None): super().__init__(self.SOAP_TYPE, client.account_client, self.SOAP_MAP) self.minimum_balance = minimum_balance self.topup_amount = topup_amount self.payment_method_id = payment_method_id @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, minimum_balance=soap_dict.get('MinimumBalance', None), topup_amount=soap_dict.get('TopupAmount', None), payment_method_id=soap_dict.get('PaymentMethodID', None) ) class Collection(Entity): """ Represents a Despactchbay API CollectionType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Shipping-Service#collectionreturntype """ SOAP_MAP = { "CollectionID": { "property": "collection_id", "type": "string" }, "CollectionDocumentID": { "property": "document_id", "type": "string" }, "CollectionType": { "property": "collection_type", "type": "string" }, "CollectionDate": { "property": "date", "type": "string" }, "SenderAddress": { "property": "sender_address", "type": "string" }, "Courier": { "property": "collection_courier", "type": "string" }, "LabelsURL": { "property": "labels_url", "type": "string" }, "Manifest": { "property": "manifest_url", "type": "string" } } SOAP_TYPE = 'ns1:CollectionReturnType' def __init__(self, client, collection_id=None, document_id=None, collection_type=None, date=None, sender_address=None, collection_courier=None, labels_url=None, manifest_url=None): super().__init__(self.SOAP_TYPE, client.shipping_client, self.SOAP_MAP) self.despatchbay_client = client self.collection_id = collection_id self.document_id = document_id self.collection_type = collection_type self.date = date self.sender_address = sender_address self.collection_courier = collection_courier self.labels_url = labels_url self.manifest_url = manifest_url @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, collection_id=soap_dict.get('CollectionID'), document_id=soap_dict.get('CollectionDocumentID'), collection_type=soap_dict.get('CollectionType'), date=CollectionDate.from_dict( client, client.shipping_client.dict(soap_dict.get('CollectionDate')) ), sender_address=Sender.from_dict( client, client.shipping_client.dict(soap_dict.get('SenderAddress', None)) ), collection_courier=Courier.from_dict( client, client.shipping_client.dict(soap_dict.get('Courier', None)) ), labels_url=soap_dict.get('LabelsURL', None), manifest_url=soap_dict.get('Manifest', None) ) def get_labels(self, **kwargs): """ Fetches label pdf through the Despatch Bay API client. """ return self.despatchbay_client.get_labels(self.document_id, **kwargs) def get_manifest(self, **kwargs): """ Fetches menifest pdf through the Despatch Bay API client. """ return self.despatchbay_client.get_manifest(self.document_id, **kwargs) class CollectionDate(Entity): """ Represents a Despactchbay API CollectionDateType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Shipping-Service#collectiondatetype """ SOAP_MAP = { "CollectionDate": { "property": "date", "type": "string" } } SOAP_TYPE = 'ns1:CollectionDateType' def __init__(self, client, date=None): super().__init__(self.SOAP_TYPE, client.shipping_client, self.SOAP_MAP) self.date = date @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, date=soap_dict.get('CollectionDate', None) ) class Courier(Entity): """ Represents a Despactchbay API CourierType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Shipping-Service#couriertype """ SOAP_MAP = { 'CourierID': { 'property': 'courier_id', 'type': 'integer' }, 'CourierName': { 'property': 'name', 'type': 'string' } } SOAP_TYPE = 'ns1:CourierType' def __init__(self, client, courier_id=None, name=None): super().__init__(self.SOAP_TYPE, client.shipping_client, self.SOAP_MAP) self.courier_id = courier_id self.name = name @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, courier_id=soap_dict.get('CourierID', None), name=soap_dict.get('CourierName', None) ) class Parcel(Entity): """ Represents a Despactchbay API ParcelType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Shipping-Service#parceltype """ SOAP_MAP = { 'Weight': { 'property': 'weight', 'type': 'float' }, 'Length': { 'property': 'length', 'type': 'float' }, 'Width': { 'property': 'width', 'type': 'float' }, 'Height': { 'property': 'height', 'type': 'float' }, 'Contents': { 'property': 'contents', 'type': 'string' }, 'Value': { 'property': 'value', 'type': 'float' }, 'TrackingNumber': { 'property': 'tracking_number', 'type': 'string' } } SOAP_TYPE = 'ns1:ParcelType' def __init__(self, client, weight=None, length=None, width=None, height=None, contents=None, value=None, tracking_number=None): super().__init__(self.SOAP_TYPE, client.shipping_client, self.SOAP_MAP) self.weight = weight self.length = length self.width = width self.height = height self.contents = contents self.value = value self.tracking_number = tracking_number @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, weight=soap_dict.get('Weight', None), length=soap_dict.get('Length', None), width=soap_dict.get('Width', None), height=soap_dict.get('Height', None), contents=soap_dict.get('Contents', None), value=soap_dict.get('Value', None), tracking_number=soap_dict.get('TrackingNumber', None) ) class PaymentMethod(Entity): """ Represents a Despactchbay API PaymentMethodType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Account-Service#paymentmethodtype """ SOAP_MAP = { 'PaymentMethodID': { 'property': 'payment_method_id', 'type': 'integer' }, 'Type': { 'property': 'payment_method_type', 'type': 'string' }, 'Description': { 'property': 'description', 'type': 'string' } } SOAP_TYPE = 'ns1:PaymentMethodType' def __init__(self, client, payment_method_id=None, payment_method_type=None, description=None): super().__init__(self.SOAP_TYPE, client.account_client, self.SOAP_MAP) self.payment_method_id = payment_method_id self.payment_method_type = payment_method_type self.description = description @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, payment_method_id=soap_dict.get('PaymentMethodID', None), payment_method_type=soap_dict.get('Type', None), description=soap_dict.get('Description', None) ) class Recipient(Entity): """ Represents a Despactchbay API RecipientAddressType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Shipping-Service#recipientaddresstype """ SOAP_MAP = { 'RecipientName': { 'property': 'name', 'type': 'string', }, 'RecipientTelephone': { 'property': 'telephone', 'type': 'string', }, 'RecipientEmail': { 'property': 'email', 'type': 'string', }, 'RecipientAddress': { 'property': 'recipient_address', 'type': 'entity', 'soap_type': 'ns1:RecipientAddressType', }, } SOAP_TYPE = 'ns1:RecipientAddressType' def __init__(self, client, name=None, telephone=None, email=None, recipient_address=None): super().__init__(self.SOAP_TYPE, client.shipping_client, self.SOAP_MAP) self.name = name self.telephone = telephone self.email = email self.recipient_address = recipient_address @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, name=soap_dict.get('RecipientName', None), telephone=soap_dict.get('RecipientTelephone', None), email=soap_dict.get('RecipientEmail', None), recipient_address=Address.from_dict( client, client.shipping_client.dict(soap_dict.get('RecipientAddress', None)) ) ) class Sender(Entity): """ Represents a Despactchbay API SenderAddressType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Shipping-Service#senderaddresstype """ SOAP_MAP = { 'SenderName': { 'property': 'name', 'type': 'string', }, 'SenderTelephone': { 'property': 'telephone', 'type': 'string', }, 'SenderEmail': { 'property': 'email', 'type': 'string', }, 'SenderAddress': { 'property': 'sender_address', 'type': 'entity', 'soap_type': 'ns1:SenderAddress', }, 'SenderAddressID': { 'property': 'address_id', 'type': 'integer', }, } SOAP_TYPE = 'ns1:SenderAddressType' def __init__(self, client, name=None, telephone=None, email=None, sender_address=None, address_id=None): super().__init__(self.SOAP_TYPE, client.shipping_client, self.SOAP_MAP) self.name = name self.telephone = telephone self.email = email if sender_address: self.sender_address = sender_address else: self.sender_address = Address(client) self.address_id = address_id @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, name=soap_dict.get('SenderName', None), telephone=soap_dict.get('SenderTelephone', None), email=soap_dict.get('SenderEmail', None), sender_address=Address.from_dict( client, client.shipping_client.dict(soap_dict.get('SenderAddress', None)) ), address_id=soap_dict.get('SenderAddressID') ) def to_soap_object(self): """ Creates a SOAP client object representation of this entity. Removes sender address property if a sender address id is provided. """ soap_object = super().to_soap_object() if soap_object.SenderAddressID: soap_object.SenderAddress = None return soap_object class Service(Entity): """ Represents a Despactchbay API ServiceType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Shipping-Service#servicetype """ SOAP_MAP = { 'ServiceID': { 'property': 'service_id', 'type': 'integer' }, 'Format': { 'property': 'service_format', 'type': 'string' }, 'Name': { 'property': 'name', 'type': 'string' }, 'Cost': { 'property': 'cost', 'type': 'currency', }, 'Courier': { 'property': 'courier', 'type': 'entity', 'soap_type': 'ns1:CourierType', }, } SOAP_TYPE = 'ns1:ServiceType' def __init__(self, client, service_id, service_format, name, cost, courier): super().__init__(self.SOAP_TYPE, client.shipping_client, self.SOAP_MAP) self.service_id = service_id self.format = service_format self.name = name self.cost = cost self.courier = courier @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ return cls( client=client, service_id=soap_dict.get('ServiceID', None), service_format=soap_dict.get('Format', None), name=soap_dict.get('Name', None), cost=soap_dict.get('Cost', None), courier=Courier.from_dict( client, client.shipping_client.dict(soap_dict.get('Courier', None)) ) ) class ShipmentRequest(Entity): """ Represents a Despactchbay API ShipmentRequest entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Shipping-Service#shipmentrequesttype """ SOAP_MAP = { 'ServiceID': { 'property': 'service_id', 'type': 'string', }, 'Parcels': { 'property': 'parcels', 'type': 'entityArray', 'soap_type': 'ns1:ArrayOfParcelType', }, 'ClientReference': { 'property': 'client_reference', 'type': 'string', }, 'CollectionDate': { 'property': 'collection_date', 'type': 'entity', 'soap_type': 'ns1:CollectionDateType', }, 'RecipientAddress': { 'property': 'recipient_address', 'type': 'entity', 'soap_type': 'ns1:RecipientAddressType', }, 'SenderAddress': { 'property': 'sender_address', 'type': 'entity', 'soap_type': 'ns1:SenderAddressType', }, 'FollowShipment': { 'property': 'follow_shipment', 'type': 'boolean', } } SOAP_TYPE = 'ns1:ShipmentRequestType' def __init__(self, client, service_id=None, parcels=None, client_reference=None, collection_date=None, sender_address=None, recipient_address=None, follow_shipment=None): super().__init__(self.SOAP_TYPE, client.shipping_client, self.SOAP_MAP) self.despatchbay_client = client self.service_id = service_id self.parcels = parcels self.client_reference = client_reference self._collection_date = self.validate_collection_date_object(collection_date) self.sender_address = sender_address self.recipient_address = recipient_address self.follow_shipment = follow_shipment def validate_collection_date_object(self, collection_date): """ Converts a string timestamp to a CollectionDate object. """ if isinstance(collection_date, str): return CollectionDate(self.despatchbay_client, date=collection_date) return collection_date @property def collection_date(self): """ Returns the private attribute collection_date """ return self._collection_date @collection_date.setter def collection_date(self, collection_date): """ Allows the collection date to be set from just a timestamp string but limits the type of the _collection_date attribute to a CollectionDate object. """ self._collection_date = self.validate_collection_date_object(collection_date) class ShipmentReturn(Entity): """ Represents a Despactchbay API ShipmentReturnType entity. https://github.com/despatchbay/despatchbay-api-v15/wiki/Shipping-Service#shipmentreturntype """ SOAP_MAP = { 'ShipmentID': { 'property': 'shipment_id', 'type': 'string', }, 'ShipmentDocumentID': { 'property': 'shipment_document_id', 'type': 'string', }, 'CollectionID': { 'property': 'collection_id', 'type': 'string', }, 'CollectionDocumentID': { 'property': 'collection_document_id', 'type': 'string', }, 'ServiceID': { 'property': 'service_id', 'type': 'string', }, 'Parcels': { 'property': 'parcels', 'type': 'entityArray', 'soap_type': 'ns1:ArrayOfParcelType', }, 'ClientReference': { 'property': 'client_reference', 'type': 'string', }, 'RecipientAddress': { 'property': 'recipient_address', 'type': 'entity', 'soap_type': 'ns1:RecipientAddressType', }, 'IsFollowed': { 'property': 'is_followed', 'type': 'boolean', }, 'IsPrinted': { 'property': 'is_printed', 'type': 'boolean', }, 'IsDespatched': { 'property': 'is_despatched', 'type': 'boolean', }, 'IsDelivered': { 'property': 'is_delivered', 'type': 'boolean', }, 'IsCancelled': { 'property': 'is_cancelled', 'type': 'boolean', }, 'LabelsURL': { 'property': 'labels_url', 'type': 'boolean', }, } SOAP_TYPE = 'ns1:ShipmentReturnType' def __init__(self, client, shipment_id=None, shipment_document_id=None, collection_id=None, collection_document_id=None, service_id=None, parcels=None, client_reference=None, recipient_address=None, is_followed=None, is_printed=None, is_despatched=None, is_delivered=None, is_cancelled=None, labels_url=None): super().__init__(self.SOAP_TYPE, client.shipping_client, self.SOAP_MAP) self.despatchbay_client = client self.shipment_id = shipment_id self.shipment_document_id = shipment_document_id self.collection_id = collection_id self.collection_document_id = collection_document_id self.service_id = service_id self.parcels = parcels self.client_reference = client_reference self.recipient_address = recipient_address self.is_followed = is_followed self.is_printed = is_printed self.is_despatched = is_despatched self.is_delivered = is_delivered self.is_cancelled = is_cancelled self.labels_url = labels_url @classmethod def from_dict(cls, client, soap_dict): """ Alternative constructor, builds entity object from a dictionary representation of a SOAP response created by the SOAP client. """ parcel_array = [] for parcel_item in soap_dict.get('Parcels'): parcel_array.append( Parcel.from_dict( client, client.shipping_client.dict(parcel_item) ) ) return cls( client=client, shipment_id=soap_dict.get('ShipmentID'), shipment_document_id=soap_dict.get('ShipmentDocumentID'), collection_id=soap_dict.get('CollectionID'), collection_document_id=soap_dict.get('CollectionDocumentID'), service_id=soap_dict.get('ServiceID'), parcels=parcel_array, client_reference=soap_dict.get('ClientReference'), recipient_address=Recipient.from_dict( client, client.shipping_client.dict(soap_dict.get('RecipientAddress', None)) ), is_followed=soap_dict.get('IsFollowed'), is_printed=soap_dict.get('IsPrinted'), is_despatched=soap_dict.get('IsDespatched'), is_delivered=soap_dict.get('IsDelivered'), is_cancelled=soap_dict.get('IsCancelled'), labels_url=soap_dict.get('LabelsURL', None) ) def book(self): """ Makes a BookShipment request through the Despatch Bay API client. """ book_return = self.despatchbay_client.book_shipments([self.shipment_id]) if book_return: self.shipment_document_id = book_return[0].shipment_document_id self.collection_id = book_return[0].collection_id self.collection_document_id = book_return[0].collection_document_id self.labels_url = book_return[0].labels_url return book_return[0] def cancel(self): """ Makes a CancelShipment request through the Despatch Bay API client. """ cancel_return = self.despatchbay_client.cancel_shipment(self.shipment_id) if cancel_return: self.is_cancelled = True return cancel_return def get_labels(self, **kwargs): """ Fetches label pdf through the Despatch Bay API client. """ return self.despatchbay_client.get_labels(self.shipment_document_id, **kwargs) <file_sep>"""Despatchbay SDK exceptions""" class Error(Exception): """Base class for other exceptions""" class InvalidArgumentException(Error): """Exception to raise when invalid arguments are passed.""" class AuthorizationException(Error): """Exception to raise when a 401 error is returned.""" class PaymentException(Error): """Exception to raise when an operation fails due to insufficient funds.""" class ApiException(Error): """General API exception""" class ConnectionException(Error): """General connection error exception.""" class RateLimitException(Error): """Exception to raise when an operation fails due rate limits.""" <file_sep>from despatchbay.despatchbay_sdk import DespatchBaySDK client = DespatchBaySDK(api_user='<APIUSER>', api_key='<APIKEY>') account_return = client.get_account() print(account_return) services_return = client.get_services() print(services_return) account_balance = client.get_account_balance() print(account_balance) sender_addresses = client.get_sender_addresses() print(sender_addresses) payment_methods = client.get_payment_methods() print(payment_methods) automatic_topup_enabled = client.enable_automatic_topups( '100', payment_methods[0].payment_method_id, payment_methods[0].payment_method_id) print(automatic_topup_enabled) automatic_topup_disabled = client.disable_automatic_topups() print(automatic_topup_disabled) <file_sep>""" Classes for working with the despatchbay documents api https://github.com/despatchbay/despatchbay-api-v15/wiki/Documents-API """ from urllib.parse import urlencode import base64 import requests from . import exceptions class Document: """ A document (label/manifest) in the despatchbay documents api. https://github.com/despatchbay/despatchbay-api-v15/wiki/Documents-API """ def __init__(self, data): self.data = data def get_raw(self): """ Returns the raw data used to create the entity. """ return self.data def get_base64(self): """ Base 64 encodes the document data before returning it. """ return base64.b64encode(self.data) def download(self, path): """ Saves the file to the specified location. """ with open(path, 'wb') as document_file: document_file.write(self.data) class DocumentsClient: """ Client for the despatchbay documents api https://github.com/despatchbay/despatchbay-api-v15/wiki/Documents-API """ def __init__(self, api_url='http://api.despatchbay.com/documents/v1'): self.api_url = api_url @staticmethod def handle_response_code(code, response): """ Returns true if code is 200, otherwise raises an appropriate exception. """ if code == 200: return True if code == 400: raise exceptions.InvalidArgumentException( 'The Documents API was unable to process the request: {}'.format(response)) if code == 401: raise exceptions.AuthorizationException('Unauthorized') if code == 402: raise exceptions.PaymentException('Insufficient Despatch Bay account balance') if code == 404: raise exceptions.ApiException('Unknown shipment ID') raise exceptions.ApiException('An unexpected error occurred (HTTP {})'.format(code)) def get_labels(self, document_ids, label_layout=None, label_format=None, label_dpi=None): """ Returns a document entity of the shipment labels identified by the document_ids arg which can be a comma separated string of shipment IDs or a single collection ID. """ if isinstance(document_ids, list): shipment_string = ','.join(document_ids) else: shipment_string = document_ids query_dict = {} if label_layout: query_dict['layout'] = label_layout if label_format: query_dict['format'] = label_format if label_format == 'png_base64' and label_dpi: query_dict['dpi'] = label_dpi label_request_url = '{}/labels/{}'.format(self.api_url, shipment_string) if query_dict: query_string = urlencode(query_dict) label_request_url = label_request_url + '?' + query_string response = requests.get(label_request_url) self.handle_response_code(response.status_code, response.text) return Document(response.content) def get_manifest(self, collection_document_id, manifest_format=None): """ Returns a document entity of the shipment manifest identified by collection_document_id. """ manifest_request_url = '{}/manifest/{}'.format(self.api_url, collection_document_id) if manifest_format: manifest_request_url = '{}?format={}'.format(manifest_request_url, manifest_format) response = requests.get(manifest_request_url) self.handle_response_code(response.status_code, response.text) return Document(response.content)
5b1c315c45b9415b1596f71b56cb276108059a40
[ "Markdown", "Python" ]
9
Python
despatchbay/despatchbay-python-sdk
c5fa87197260cb344e82d9ab0e6627419303484d
6491f43fb3103253ade591557bf2c85740d1d3fc
refs/heads/main
<repo_name>ReVelaO/evaluacion4<file_sep>/app/src/main/java/com/example/listaprecios/RegistroUsuarios.java package com.example.listaprecios; import android.os.Bundle; import android.view.View; import android.widget.EditText; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; public class RegistroUsuarios extends AppCompatActivity { private static int IndexCounter; private EditText oRegName1; private EditText oRegName2; public static ArrayList<Persona> oUsuarios; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registro_usuarios); IndexCounter = 0; oUsuarios = new ArrayList<>(); oRegName1 = findViewById(R.id.idRegUser); oRegName2 = findViewById(R.id.idRegPass); } public void Crear(View v) { //obtenemos un id para identificarlo IndexCounter++; Persona nueva = new Persona(); nueva.setId(IndexCounter); nueva.setUsuario(oRegName1.getText().toString()); nueva.setContrasena(oRegName2.getText().toString()); oUsuarios.add(nueva); //avisamos que ya existe el usuario MainActivity.IsRegistryCompleted = true; //regresamos el usuario al menu principal onBackPressed(); } } <file_sep>/app/src/main/java/com/example/listaprecios/RegistroPokemons.java package com.example.listaprecios; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; public class RegistroPokemons extends AppCompatActivity { private EditText oVisName; private EditText oVisHP; private EditText oVisATK; private EditText oVisDEF; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registro_pokemons); oVisName = findViewById(R.id.idVisName); oVisHP = findViewById(R.id.idVisHP); oVisATK = findViewById(R.id.idVisATK); oVisDEF = findViewById(R.id.idVisDEF); } public void Añadir(View v) { Pokemon pokemon = new Pokemon(); pokemon.setNombre(oVisName.getText().toString()); pokemon.setVida(Integer.parseInt(oVisHP.getText().toString())); pokemon.setAtaque(Integer.parseInt(oVisATK.getText().toString())); pokemon.setDefensa(Integer.parseInt(oVisDEF.getText().toString())); MainActivity.aPokemons.add(pokemon); Toast.makeText(getApplicationContext(), "Se agregó " + pokemon.getNombre(), Toast.LENGTH_SHORT).show(); onBackPressed(); } }
7215eb16eb306c40b20f410496d07d0fa4242d47
[ "Java" ]
2
Java
ReVelaO/evaluacion4
9478c8506a96688fd578148bb594f2e37e01644f
c05cee1e22827b7b0405abd0d3c41761af668ba9
refs/heads/master
<file_sep>import _ from 'underscore'; var UploadTemplate = _.template(` <h1>Upload</h1> <div class="row" id="formUpload"> <div class="col-md-4"> <div class="form-group" style="margin-bottom:10px"> <label for="txtExtraData1">Data Extra 1</label> <input type="input" class="form-control" id="txtExtraData1" placeholder="Datos Extra 1"> </div> <div class="form-group" style="margin-bottom:10px"> <label for="txtExtraData2">Data Extra 2</label> <input type="input" class="form-control" id="txtExtraData2" placeholder="Datos Extra 2"> </div> <div class="form-group" style="margin-bottom:10px"> <label style="width:100%">Foto</label> <label id="imagen_id" class="oculto">E</label> <input type="file" id="input_file" name="myFile" type="file" class="hidden"/> <button id="buscar_file" class="btn btn-primary btn-file pull-left"><i class="fa fa-file-image-o" aria-hidden="true"></i>Buscar </button> <button id="subir_file" class="btn btn-primary btn-file pull-left" disabled><i class="fa fa-upload" aria-hidden="true"></i>Subir </button> <a target="_blank" id="ver_file" class="btn btn-primary btn-file pull-left" disabled><i class="fa fa-search" aria-hidden="true" style="margin-right: 5px"></i>Ver </a> </div> </div> <div class="col-md-3"> <div class="form-group"> <label id="lblMensaje"></label> </div> </div> <div class="col-md-3"> <div class="form-group" id="formUbicaciones"> <label for="txtDistrito">Ver modelo de selcción en consola</label><br> <button type="button" class="btn btn-primary" id="verModelo"><i class="fa fa-search" aria-hidden="true"></i>Ver Modelo</button> </div> </div> </div> `); export default UploadTemplate; <file_sep>import Backbone from 'backbone'; import $ from 'jquery'; import HomeTemplate from '../templates/home_template'; var HomeView = Backbone.View.extend({ el: '#workspace', initialize: function(){ }, events: { }, render: function() { $(this.el).html( HomeTemplate({ nombre: 'Pepe', base_url: BASE_URL, })) ; }, }); export default HomeView; <file_sep>import Backbone from 'backbone'; import $ from 'jquery'; var TableView = Backbone.View.extend({ //el: "#formUbicaciones", definido en el constructor initialize: function(params){ // inicializar variables this.idTable = params["idTable"]; this.idTableBody = params["idTable"] + "Body"; this.targetMensaje = params["targetMensaje"]; this.mensajes = params["mensajes"]; this.collection = params["collection"]; this.urlListar = params["urlListar"]; this.urlGuardar = params["urlGuardar"]; this.fila = params["fila"]; this.filaBotones = params["filaBotones"]; this.model = params["model"]; this.collection = params["collection"]; this.extraData = null; this.tableKeys = params['tableKeys']; this.file = params['file']; this.fileServerUrl = params['fileServerUrl']; this.observador = { nuevo: [], editado: [], eliminado: [], }; this.pagination = params["pagination"]; this.paginaActual = 1; // asignacion dinamica de eventos this.events = this.events || {}; //this.events["keyup #" + this.idNombre] = "buscarCooincidencias"; //this.events["focusout #" + this.idNombre] = "limpiarSiVacio"; this.listenTo(this.collection, "change", this.onChange, this); this.delegateEvents(); }, events: { // se está usando asignacion dinamica de eventos en el constructor "keyup input.text": "inputTextEscribir", "click i.quitar-fila": "quitarFila", "click button.agregar-fila": "agregarFila", "click button.guardar-tabla": "guardarTabla", "change td > select": "cambiarSelect", "change .input.checkbox": "clickCheckBox", //botones de paginacion "click tfoot > tr > td > span > .fa-fast-backward": "paginacionIrPrimero", "click tfoot > tr > td > span > .fa-backward": "paginacionIrAnteior", "click tfoot > tr > td > span > .fa-forward": "paginacionIrSiguiente", "click tfoot > tr > td > span > .fa-fast-forward": "paginacionIrUltimo", //botones de fileUpload "click i.seleccionar-archivo": "fileSelect", "click i.subir-archivo": "fileUpload", "click i.ver-archivo": "fileView", }, //método que permite la herencia de eventos inheritEvents: function(parent) { var parentEvents = parent.prototype.events; if (_.isFunction(parentEvents)) { parentEvents = parentEvents(); } this.events = _.extend({}, parentEvents, this.events); }, // métodos de la vista limpiarBody: function(){ var tabla = document.getElementById(this.idTable); var childs = tabla.childNodes; for (var i = 0; i < childs.length; i++) { if(childs[i].nodeName == "TBODY"){ tabla.removeChild(childs[i]); } } }, limpiarPagination: function(){ var elementos = document.getElementById(this.pagination.idBotonesPaginacion); $(elementos).empty(); }, listar: function(){ this.collection.reset(); var dataSend= { }; if(this.pagination !== undefined){ dataSend.data = JSON.stringify({ step: this.pagination.pageSize, page: this.paginaActual, }); this.contarPaginas(); this.crearPaginacion(); } var viewInstance = this; $.ajax({ type: "GET", url: viewInstance.urlListar, data: dataSend, headers: { [CSRF_KEY]: CSRF, }, async: false, success: function(data){ var responseData = JSON.parse(data); var tbody = document.createElement("tbody"); for(var i = 0; i < responseData.length; i++){ var tr = document.createElement("tr"); var modelo = new window[viewInstance.model](responseData[i]); if(viewInstance.tableKeys === undefined){ for (var key in responseData[i]) { //console.log(key, responseData[i][key]); var fila = viewInstance.fila[key]; var params = { key: key, modelo: modelo, tdProps: 'XD', fila: fila, }; if(fila !== undefined){ if(viewInstance.helper()[fila.tipo] !== undefined){ var td = viewInstance.helper()[fila.tipo](params, viewInstance); tr.appendChild(td); }else{ console.warn("Componente '" + fila.tipo + "' no se encuentra en helpers para construir el HTML"); } }else{ console.warn("Llave '" + key + "' no se encuentra mapeada en la tabla '" + viewInstance.idTable + "'"); } } }else{ for (var k = 0; k < viewInstance.tableKeys.length; k++) { var key = viewInstance.tableKeys[k]; //console.log(key); var fila = viewInstance.fila[key]; var params = { key: key, modelo: modelo, tdProps: 'XD', fila: fila, }; if(fila !== undefined){ if(viewInstance.helper()[fila.tipo] !== undefined){ var td = viewInstance.helper()[fila.tipo](params, viewInstance); tr.appendChild(td); }else{ console.warn("Componente '" + fila.tipo + "' no se encuentra en helpers para construir el HTML"); } }else{ console.warn("Llave '" + key + "' no se encuentra mapeada en la tabla '" + viewInstance.idTable + "'"); } } } // append de botones de la fila var params = { modelo: modelo, filaBotones: viewInstance.filaBotones, estilos: viewInstance.fila.filaBotones.estilos, }; var tdBotones = viewInstance.helper()["btn_td"](params); tr.appendChild(tdBotones); // agregar modelo a collection viewInstance.collection.add(modelo); tbody.appendChild(tr); } //console.log(viewInstance.collection);console.log(tbody); document.getElementById(viewInstance.idTable).appendChild(tbody); }, error: function(error){ $("#" + viewInstance.targetMensaje).removeClass("color-success"); $("#" + viewInstance.targetMensaje).removeClass("color-warning"); $("#" + viewInstance.targetMensaje).addClass("color-danger"); $("#" + viewInstance.targetMensaje).html(viewInstance.mensajes["errorListarAjax"]); console.log(error); } }); }, contarPaginas: function(){ var viewInstance = this; $.ajax({ type: "GET", url: viewInstance.pagination.urlCount, data: {}, headers: { [CSRF_KEY]: CSRF, }, async: false, success: function(count){ var temp = count/viewInstance.pagination.pageSize; if(temp % 1 > 0){ viewInstance.cantidadPaginas = (count / viewInstance.pagination.pageSize) - (temp % 1) + 1; }else{ viewInstance.cantidadPaginas = temp; } }, error: function(error){ //TODO console.log(error); } }); }, crearPaginacion: function(){ var labelIndice = document.createElement("label"); labelIndice.innerHTML = this.paginaActual + " / " + this.cantidadPaginas; var appendLabel = false; if(this.paginaActual != 1){ var inicioHtmlI = document.createElement("i"); inicioHtmlI.classList.add("fa"); inicioHtmlI.classList.add("fa-fast-backward"); inicioHtmlI.classList.add("btn-pagination"); inicioHtmlI.setAttribute("alt", "Primeros " + this.pagination.pageSize + " registros"); var anteriorHtmlI = document.createElement("i"); anteriorHtmlI.classList.add("fa"); anteriorHtmlI.classList.add("fa-backward"); anteriorHtmlI.classList.add("btn-pagination"); anteriorHtmlI.setAttribute("alt", this.pagination.pageSize + " registros anteriores"); document.getElementById(this.pagination.idBotonesPaginacion).appendChild(inicioHtmlI); document.getElementById(this.pagination.idBotonesPaginacion).appendChild(anteriorHtmlI); document.getElementById(this.pagination.idBotonesPaginacion).appendChild(labelIndice); appendLabel = true; } if(this.paginaActual != this.cantidadPaginas){ var siguienteHtmlI = document.createElement("i"); siguienteHtmlI.classList.add("fa"); siguienteHtmlI.classList.add("fa-forward"); siguienteHtmlI.classList.add("btn-pagination"); siguienteHtmlI.setAttribute("alt", this.pagination.pageSize + " registros posteriores"); var finHtmlI = document.createElement("i"); finHtmlI.classList.add("fa"); finHtmlI.classList.add("fa-fast-forward"); finHtmlI.classList.add("btn-pagination"); finHtmlI.setAttribute("alt", "Últimos " + this.pagination.pageSize + " registros"); if(appendLabel == false){ document.getElementById(this.pagination.idBotonesPaginacion).appendChild(labelIndice); } document.getElementById(this.pagination.idBotonesPaginacion).appendChild(siguienteHtmlI); document.getElementById(this.pagination.idBotonesPaginacion).appendChild(finHtmlI); } }, paginacionIrPrimero: function(){ this.paginaActual = 1; this.limpiarBody(); this.limpiarPagination(); this.listar(); }, paginacionIrAnteior: function(){ this.paginaActual = this.paginaActual - 1; this.limpiarBody(); this.limpiarPagination(); this.listar(); }, paginacionIrSiguiente: function(){ this.paginaActual = this.paginaActual + 1; this.limpiarBody(); this.limpiarPagination(); this.listar(); }, paginacionIrUltimo: function(){ this.paginaActual = this.cantidadPaginas; this.limpiarBody(); this.limpiarPagination(); this.listar(); }, helper: function(params, viewInstance){ return { "td_id": function(params){ //console.log("LABEL_ID"); var td = document.createElement("td"); td.setAttribute("style", params.fila.estilos); td.setAttribute("key", params.key); td.innerHTML = params.modelo.get(params.key); //console.log(td); return td; }, "label": function(params){ //console.log("LABEL"); var td = document.createElement("td"); td.setAttribute("style", params.fila.estilos); td.setAttribute("key", params.key); td.innerHTML = params.modelo.get(params.key); //console.log(td); return td; }, "text": function(params){ //console.log("LABEL_ID"); var td = document.createElement("td"); var inputText = document.createElement("INPUT"); inputText.setAttribute("type", "text"); inputText.setAttribute("style", params.fila.estilos); inputText.setAttribute("key", params.key); inputText.value = params.modelo.get(params.key); inputText.classList.add("text"); td.appendChild(inputText); //console.log(inputText); return td; }, "check": function(params){ var td = document.createElement("td"); //td.setAttribute("style", params.estilos); var inputCheck = document.createElement("INPUT"); inputCheck.type = "checkbox"; inputCheck.setAttribute("style", params.fila.estilos); inputCheck.setAttribute("key", params.key); inputCheck.classList.add("input-check"); if(params.modelo.get(params.key) == 1){ inputCheck.checked = true; } td.appendChild(inputCheck); //console.log(inputCheck); return td; }, "select": function(params){ //console.log("LABEL_ID"); var td = document.createElement("td"); var select = document.createElement("select"); select.setAttribute("style", params.fila.estilos); //console.log(params.modelo.get(params.key)); //console.log(params.fila.collection.models); for (var i = 0; i < params.fila.collection.models.length; i++) { var option = document.createElement("option"); option.value = params.fila.collection.models[i].get("id"); option.text = params.fila.collection.models[i].get("nombre"); select.appendChild(option); } select.setAttribute("key", params.key); select.value = params.modelo.get(params.key); td.appendChild(select); return td; }, "autocomplete": function(params, viewInstance){ var td = document.createElement("td"); td.setAttribute("style", params.estilos); var inputText = document.createElement("INPUT"); inputText.setAttribute("type", "text"); inputText.setAttribute("style", params.fila.estilos); inputText.setAttribute("key", params.key); var idInputAutocomplete = viewInstance.idTable + params.key + "input" + _.random(0, 1000); inputText.setAttribute("id", idInputAutocomplete); inputText.value = params.modelo.get(params.fila.keyModeloInput); inputText.classList.add("autocomplete-text"); td.appendChild(inputText); var ulSugerencias = document.createElement("ul"); ulSugerencias.classList.add("oculto"); ulSugerencias.classList.add("sugerencia-contenedor"); ulSugerencias.style.cssText = params.fila.estilos; var idUlAutocomplete = viewInstance.idTable + params.key + "ul" + _.random(0, 1000); ulSugerencias.setAttribute("id", idUlAutocomplete); td.appendChild(ulSugerencias); //crear instacia de autcompletar new AutocompleteView({ el: td, nombre: idInputAutocomplete, targetMensajeError: viewInstance.targetMensaje, targetSugerencias: idUlAutocomplete, mensajeError: params.fila.mensajeError, url: params.fila.url, collection: params.fila.collection, model: params.fila.model, modeloCelda: params.modelo, keyModeloCelda: params.fila.keyModeloCelda, valueModeloCelda: params.fila.keyModeloInput, }); return td; }, "btn_td": function(params){ //console.log("BTN-TD"); var td = document.createElement("td"); td.setAttribute("style", params.estilos); for(var i = 0; i < params.filaBotones.length; i++){ var boton = null; switch(params.filaBotones[i].tipo) { case "i": // de font-awesome 4 //<i class="fa fa-chevron-left" aria-hidden="true"></i> var htmlI = document.createElement("i"); htmlI.classList.add("fa"); htmlI.classList.add(params.filaBotones[i].clase); htmlI.setAttribute("style", params.filaBotones[i].estilos); // operación a la que se le asignará un evento htmlI.classList.add(params.filaBotones[i].claseOperacion); boton = htmlI; break; case "href": var href = document.createElement("a"); var htmlI = document.createElement("i"); htmlI.classList.add("fa"); htmlI.classList.add(params.filaBotones[i].clase); href.setAttribute("href", params.filaBotones[i].url + params.modelo.id); href.classList.add(params.filaBotones[i].claseOperacion); href.appendChild(htmlI); boton = href; break; default: console.log("tipo de botón no soportado"); } if(boton != null){ //console.log(boton); td.appendChild(boton); } } //console.log(params.modelo); return td; }, }; }, inputTextEscribir: function(event){ var idFila = event.target.parentElement.parentElement.firstChild.innerHTML; var valorInput = event.target.value; var key = event.target.getAttribute("key"); var modelo = this.collection.get(idFila); //console.log("inputTextEscribir"); modelo.set(key, valorInput); //thisDOM.parent().parent().children(0).children(0).html(); }, clickCheckBox: function(event){ var idFila = event.target.parentElement.parentElement.firstChild.innerHTML; var checked = event.target.checked; var valor = 0; if(checked == true){ valor = 1; } var key = event.target.getAttribute("key"); var modelo = this.collection.get(idFila); modelo.set(key, valor); }, clickSugerenenciaAutocomplete: function(event){ //console.log("clickSugerenenciaAutocomplete"); //var idFila = event.target.parentElement.parentElement.firstChild.innerHTML; console.log("XDDDD"); console.log(event.target); }, quitarFila: function(event){ var idFila = event.target.parentElement.parentElement.firstChild.innerHTML; var tbody = event.target.parentElement.parentElement.parentElement; var td = event.target.parentElement.parentElement; tbody.removeChild(td); var modelo = this.collection.get(idFila); //console.log(modelo); // si el modelo a editar ya existe como nuevo o editado, eliminar de observador y agregar como eliminado en observador if(_.contains(this.observador.nuevo, (idFila + ""))){ this.observador.nuevo = _.without(this.observador.nuevo, (idFila + "")); } if(_.contains(this.observador.editado, (idFila + ""))){ this.observador.editado = _.without(this.observador.editado, (idFila + "")); } if(!_.contains(this.observador.eliminado, (idFila + ""))){ this.observador.eliminado.push(idFila + ""); } this.collection.remove(modelo); }, cambiarSelect: function(event){ var idFila = event.target.parentElement.parentElement.firstChild.innerHTML; var valorSelect = event.target.value; var key = event.target.getAttribute("key"); var modelo = this.collection.get(idFila); //console.log("inputTextEscribir"); modelo.set(key, valorSelect); }, agregarFila: function(event){ var modelo = new window[this.model]({id: this.idTable + _.random(0, 1000)}); var tr = document.createElement("tr"); for (var key in this.fila) { if(key != "filaBotones"){ var fila = this.fila[key]; var params = { key: key, modelo: modelo, tdProps: 'XD', fila: fila, }; var td = this.helper()[fila.tipo](params, this); tr.appendChild(td); }else{ var params = { modelo: modelo, filaBotones: this.filaBotones, estilos: this.fila.filaBotones.estilos, }; var tdBotones = this.helper()["btn_td"](params); tr.appendChild(tdBotones); } } // agregar modelo a collection this.collection.add(modelo); //console.log(tr);console.log(tbody); var children = document.querySelectorAll('#' + this.idTable + ' > *'); var tbody = null; for(var i = 0; i < children.length; i++){ if(children[i].nodeName == "TBODY"){ tbody = children[i]; } } if(tbody == null){ tbody = document.createElement("tbody"); tbody.appendChild(tr); document.getElementById(this.idTable).appendChild(tbody); }else{ tbody.appendChild(tr); } }, guardarTabla: function(event){ var data = { nuevos: [], editados: [], eliminados: [], }; if(this.observador.nuevo.length == 0 && this.observador.editado.length == 0 && this.observador.eliminado.length == 0){ $("#" + this.targetMensaje).removeClass("color-danger"); $("#" + this.targetMensaje).removeClass("color-success"); $("#" + this.targetMensaje).addClass("color-warning"); $("#" + this.targetMensaje).html("No se ha ejecutado cambios en la tabla"); $("html, body").animate({ scrollTop: $("#" + this.targetMensaje).offset().top }, 1000); }else{ for (var key in this.observador) { for (var i = 0; i < this.observador[key].length; i++) { var observadorId = this.observador[key][i]; if(key == "nuevo" || key == "editado"){ var modelo = this.collection.get(observadorId); data[key + "s"].push(modelo.toJSON()); }else{ data["eliminados"].push(observadorId); } } } var viewInstance = this; if(this.extraData != null){ data.extra = this.extraData } $.ajax({ type: "POST", url: viewInstance.urlGuardar, data: { data: JSON.stringify(data) }, headers: { [CSRF_KEY]: CSRF, }, async: false, success: function(data){ var responseData = JSON.parse(data); if(responseData.tipo_mensaje == "success"){ $("#" + viewInstance.targetMensaje).removeClass("color-danger"); $("#" + viewInstance.targetMensaje).removeClass("color-warning"); $("#" + viewInstance.targetMensaje).addClass("color-success"); $("#" + viewInstance.targetMensaje).html(responseData.mensaje[0]); $("html, body").animate({ scrollTop: $("#" + viewInstance.targetMensaje).offset().top }, 1000); //reemplezar los ids de los nuevos temporales por los generados en la base de datos var idNuevos = responseData.mensaje[1]; if(idNuevos != null){ for(var p = 0; p < idNuevos.length; p++){ var temp = idNuevos[p]; var idTemportal = temp.temporal; var idNuevo = temp.nuevo_id; //actualizar id en collection var modelo = viewInstance.collection.get(idTemportal); modelo.set({"id": idNuevo}); //actualizar id en DOM de la tabla var trs = document.getElementById(viewInstance.idTable).lastChild.querySelectorAll("tr"); for (var i = 0; i < trs.length; i++) { if(trs[i].firstChild.innerHTML == idTemportal){ trs[i].firstChild.innerHTML = idNuevo; } } } } //resetear el observador viewInstance.observador = { nuevo: [], editado: [], eliminado: [], }; } }, error: function(error){ $("#" + viewInstance.targetMensaje).removeClass("color-success"); $("#" + viewInstance.targetMensaje).removeClass("color-warning"); $("#" + viewInstance.targetMensaje).addClass("color-danger"); $("#" + viewInstance.targetMensaje).html(viewInstance.mensajes["errorGuardarAjax"]); $("html, body").animate({ scrollTop: $("#" + viewInstance.targetMensaje).offset().top }, 1000); console.log(error); } }); } }, onChange: function(modeloCambiado) { if(modeloCambiado != null){ var idFila = modeloCambiado.get("id") + ""; if(idFila.indexOf(this.idTable) >= 0){ if(!_.contains(this.observador.nuevo, idFila)){ this.observador.nuevo.push(idFila); } }else{ if(!_.contains(this.observador.editado, idFila)){ this.observador.editado.push(idFila); } } //console.log(this.observador); } }, fileSelect: function(event){ var viewInstance = this; $("#" +viewInstance.file.input_file_id).trigger("click"); }, fileGetExtension: function(file){ var temp = file.name.split("."); return temp[temp.length - 1]; }, fileUpload: function(event){ var viewInstance = this; var file = $("#" +viewInstance.file.input_file_id)[0].files[0]; if(!_.contains(viewInstance.file.formats, this.fileGetExtension(file))){ $("#" + viewInstance.targetMensaje).removeClass("color-success"); $("#" + viewInstance.targetMensaje).removeClass("color-warning"); $("#" + viewInstance.targetMensaje).addClass("color-danger"); $("#" + viewInstance.targetMensaje).html("Formato de archivo no válido"); $("html, body").animate({ scrollTop: $("#" + viewInstance.targetMensaje).offset().top }, 1000); }else{ var file_size_mb = file.size / Math.pow(10, 6); if(file.size < file_size_mb){ $("#" + viewInstance.targetMensaje).removeClass("color-success"); $("#" + viewInstance.targetMensaje).removeClass("color-warning"); $("#" + viewInstance.targetMensaje).addClass("color-danger"); $("#" + viewInstance.targetMensaje).html("Tamaño de archivo supera el máximo permitido (" + viewInstance.file.max_size + "mb)"); $("html, body").animate({ scrollTop: $("#" + viewInstance.targetMensaje).offset().top }, 1000); }else{ var formData = new FormData(); formData.append(viewInstance.file.form_name, file); // anexar al formData los datos extras a enviar var idFila = event.target.parentElement.parentElement.firstChild.innerHTML; var model = viewInstance.collection.get(idFila).attributes; for(var i = 0; i < viewInstance.file.model_attributes.length; i++){ formData.append(viewInstance.file.model_attributes[i], model[viewInstance.file.model_attributes[i]]); } //for(var pair of formData.entries()) {console.log(pair[0]+ ', ' + pair[1]);} var viewInstance = this; $.ajax({ type: viewInstance.file.method, url: viewInstance.file.url, headers: { [CSRF_KEY]: CSRF, }, data: formData, //use contentType, processData for sure. contentType: false, processData: false, beforeSend: function() { $("#" + viewInstance.targetMensaje).removeClass("color-success"); $("#" + viewInstance.targetMensaje).removeClass("color-error"); $("#" + viewInstance.targetMensaje).addClass("color-warning"); $("#" + viewInstance.targetMensaje).html("Subiendo"); }, success: function(data) { var data = JSON.parse(data); $("#" + viewInstance.targetMensaje).removeClass("color-warning"); $("#" + viewInstance.targetMensaje).removeClass("color-error"); $("#" + viewInstance.targetMensaje).addClass("color-success"); $("#" + viewInstance.targetMensaje).html(data["mensaje"]["mensaje"]); viewInstance.collection.get(idFila).attributes[viewInstance.file.model_key] = data["mensaje"]["file_id"]; //actualizar observador if(idFila.indexOf(viewInstance.idTable) >= 0){ if(!_.contains(viewInstance.observador.nuevo, idFila)){ viewInstance.observador.nuevo.push(idFila); } }else{ if(!_.contains(viewInstance.observador.editado, idFila)){ viewInstance.observador.editado.push(idFila); } } }, error: function(error) { console.log(error); $("#" + viewInstance.targetMensaje).removeClass("color-success"); $("#" + viewInstance.targetMensaje).removeClass("color-warning"); $("#" + viewInstance.targetMensaje).addClass("color-danger"); $("#" + viewInstance.targetMensaje).html("Ocurrió un error en subir el archivo al servidor"); $("html, body").animate({ scrollTop: $("#" + viewInstance.targetMensaje).offset().top }, 1000); } }); } } }, fileView: function(event){ var viewInstance = this; var idFila = event.target.parentElement.parentElement.firstChild.innerHTML; var model = viewInstance.collection.get(idFila).attributes; var fileUrl = viewInstance.collection.get(idFila).attributes[viewInstance.file.model_key]; if (fileUrl != null){ $("#" + viewInstance.targetMensaje).removeClass("color-success"); $("#" + viewInstance.targetMensaje).removeClass("color-error"); $("#" + viewInstance.targetMensaje).addClass("color-warning"); $("#" + viewInstance.targetMensaje).html(""); var win = window.open(viewInstance.fileServerUrl + fileUrl, '_blank'); win.focus(); }else{ $("#" + viewInstance.targetMensaje).removeClass("color-success"); $("#" + viewInstance.targetMensaje).removeClass("color-warning"); $("#" + viewInstance.targetMensaje).addClass("color-danger"); $("#" + viewInstance.targetMensaje).html("No se ha anexado ninguna imagen al registro"); $("html, body").animate({ scrollTop: $("#" + viewInstance.targetMensaje).offset().top }, 1000); } }, }); <file_sep>import Backbone from 'backbone'; import $ from 'jquery'; import _ from 'underscore'; import UploadTemplate from '../templates/upload_template'; import File from '../models/file'; import UploadView from '../libs/upload'; var UploadViewTab = Backbone.View.extend({ el: '#workspace', uploadView: null, initialize: function(){ this.uploadView = new UploadView({ el: "#formUpload", imagenId: "imagen_id", inputFileId: "input_file", buscarBtnId: "buscar_file", subirBtnId: "subir_file", verBtnId: "ver_file", fileName: "myFile", lblMensaje: "lblMensaje", mensajes: { "formatoNoValido": "Archivo formato no válido", "tamanioNoValido": "Tamaño de archivo no válido", "errorAjax": "Error de comunicación con el servidor", "success": "Se cargado el archivo", }, url: BASE_URL + "file/upload", extraData: [ {"llave": "key1", "domId": "txtExtraData1"}, {"llave": "key2", "domId": "txtExtraData2"}, ], maxSize: 3545850, //bytes allowTypes: ["image/png", "image/jpeg"], method: "POST", model: new File(), }); }, events: { "click #buscar_file": "buscarFile", "click #subir_file": "subirFile", }, buscarFile: function(event){ this.uploadView.triggerInputFile(); }, subirFile: function(event){ this.uploadView.subirFile(); }, render: function() { $(this.el).html( UploadTemplate({ nombre: 'Pepe', base_url: BASE_URL, })) ; }, }); export default UploadViewTab; <file_sep>import _ from 'underscore'; var HomeTemplate = _.template(` <h1>hola mundo</h1> base_url : <%= base_url %> <button> <i class="fa fa-envelope-open" aria-hidden="true"></i> hola </button> <a href="#"> <span class="glyphicon glyphicon-asterisk"></span> hola </a> `); export default HomeTemplate; <file_sep># Webpack $ npm install $ npm run webpack --- Fuentes: + https://webpack.js.org/guides/getting-started/ + https://webpack.js.org/concepts/mode/ + https://stackoverflow.com/questions/35903246/how-to-create-multiple-output-paths-in-webpack-config + https://webpack.js.org/plugins/mini-css-extract-plugin/ + https://github.com/webpack-contrib/sass-loader + https://stackoverflow.com/questions/52395155/how-do-i-generate-a-css-file-using-webpack-4-and-mini-css-extract-plugin + https://webpack.js.org/configuration/dev-server/ + https://desarrolloweb.com/articulos/servidor-desarrollo-webpack.html + https://webpack.js.org/guides/production/ + https://webpack.js.org/concepts/entry-points/ + https://medium.com/@chanonroy/webpack-2-and-font-awesome-icon-importing-59df3364f35c <file_sep>require 'sinatra' require 'sequel' require 'sqlite3' # conexión a base de datos Sequel::Model.plugin :json_serializer DB = Sequel.connect('sqlite://db/demo.db') # clases ORM class Departamento < Sequel::Model(DB[:departamentos]) end class Provincia < Sequel::Model(DB[:provincias]) end class Distrito < Sequel::Model(DB[:distritos]) end class DistritoProvinciaDepartamento < Sequel::Model(DB[:vw_distrito_provincia_departamentos]) end class TipoEstacion < Sequel::Model(DB[:tipo_estaciones]) end class Estacion < Sequel::Model(DB[:estaciones]) end # aplicación sinatra before do headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS' headers['Content-type'] = 'text/html; charset=UTF-8' headers['server'] = 'Ruby, Ubuntu' end get '/test/conexion' do 'Ok' end get '/' do 'Error: Url Vacía' end # rutas : departamento get '/departamento/listar' do Departamento.all.to_a.to_json end post '/departamento/guardar' do data = JSON.parse(params[:data]) nuevos = data['nuevos'] editados = data['editados'] eliminados = data['eliminados'] rpta = [] array_nuevos = [] error = false execption = nil DB.transaction do begin if nuevos.length != 0 nuevos.each do |nuevo| n = Departamento.new( :nombre => nuevo['nombre'] ) n.save t = { :temporal => nuevo['id'], :nuevo_id => n.id } array_nuevos.push(t) end end if editados.length != 0 editados.each do |editado| e = Departamento.where( :id => editado['id'] ).first e.nombre = editado['nombre'] e.save end end if eliminados.length != 0 eliminados.each do |eliminado| Departamento.where( :id => eliminado ).delete end end rescue Exception => e Sequel::Rollback error = true execption = e end end if error == false return { :tipo_mensaje => 'success', :mensaje => [ 'Se ha registrado los cambios en los departamentos', array_nuevos ] }.to_json else status 500 return { :tipo_mensaje => 'error', :mensaje => [ 'Se ha producido un error en guardar la tabla de departamentos', execption.message ] }.to_json end end #rutas provincia get '/provincia/listar/:departamento_id' do Provincia.select(:id, :nombre).where(:departamento_id => params['departamento_id']).all().to_a.to_json end post '/provincia/guardar' do data = JSON.parse(params[:data]) nuevos = data['nuevos'] editados = data['editados'] eliminados = data['eliminados'] usuario_id = data['extra'] departamento_id = data['extra']['departamento_id'] rpta = [] array_nuevos = [] error = false execption = nil DB.transaction do begin if nuevos.length != 0 nuevos.each do |nuevo| n = Provincia.new( :nombre => nuevo['nombre'], :departamento_id => departamento_id ) n.save t = { :temporal => nuevo['id'], :nuevo_id => n.id } array_nuevos.push(t) end end if editados.length != 0 editados.each do |editado| e = Provincia.where( :id => editado['id'] ).first e.nombre = editado['nombre'] e.save end end if eliminados.length != 0 eliminados.each do |eliminado| Provincia.where( :id => eliminado ).delete end end rescue Exception => e Sequel::Rollback error = true execption = e end end if error == false return { :tipo_mensaje => 'success', :mensaje => [ 'Se ha registrado los cambios en las provincias', array_nuevos ] }.to_json else status 500 return { :tipo_mensaje => 'error', :mensaje => [ 'Se ha producido un error en guardar la tabla de provincias', execption.message ] }.to_json end end # rutas : distrito get '/distrito/listar/:provincia_id' do Distrito.select(:id, :nombre).where(:provincia_id => params['provincia_id']).all().to_a.to_json end get '/distrito/buscar' do DistritoProvinciaDepartamento.where(Sequel.like(:nombre, params['nombre'] + '%')).limit(10).to_a.to_json end get '/distrito/count' do DistritoProvinciaDepartamento.count.to_s end get '/distrito/buscar_pagina' do data = JSON.parse(params['data']) step = data['step'] page = data['page'] puts data inicio = (page - 1) * step DistritoProvinciaDepartamento.limit(step, inicio).to_a.to_json end post '/distrito/guardar' do data = JSON.parse(params[:data]) nuevos = data['nuevos'] editados = data['editados'] eliminados = data['eliminados'] usuario_id = data['extra'] provincia_id = data['extra']['provincia_id'] rpta = [] array_nuevos = [] error = false execption = nil DB.transaction do begin if nuevos.length != 0 nuevos.each do |nuevo| n = Distrito.new( :nombre => nuevo['nombre'], :provincia_id => provincia_id ) n.save t = { :temporal => nuevo['id'], :nuevo_id => n.id } array_nuevos.push(t) end end if editados.length != 0 editados.each do |editado| e = Distrito.where( :id => editado['id'] ).first e.nombre = editado['nombre'] e.save end end if eliminados.length != 0 eliminados.each do |eliminado| Distrito.where( :id => eliminado ).delete end end rescue Exception => e Sequel::Rollback error = true execption = e end end if error == false return { :tipo_mensaje => 'success', :mensaje => [ 'Se ha registrado los cambios en los distritos', array_nuevos ] }.to_json else status 500 return { :tipo_mensaje => 'error', :mensaje => [ 'Se ha producido un error en guardar la tabla de distritos', execption.message ] }.to_json end end # rutas : tipo_estacion get '/tipo_estacion/listar' do TipoEstacion.select(:id, :nombre).all().to_a.to_json end get '/estacion/listar' do #Estacion.select(:id, :nombre, :descripcion, :latitud, :longitud, :altura, :tipo_estacion_id, :distrito_id).all().to_a.to_json DB.fetch(' SELECT E.id, E.nombre, E.descripcion, E.latitud, E.longitud, E.altura, E.tipo_estacion_id, E.distrito_id, D.nombre AS distrito FROM estaciones E INNER JOIN vw_distrito_provincia_departamentos D ON D.id = E.distrito_id ').to_a.to_json end post '/estacion/guardar' do data = JSON.parse(params[:data]) nuevos = data['nuevos'] editados = data['editados'] eliminados = data['eliminados'] rpta = [] array_nuevos = [] error = false execption = nil DB.transaction do begin if nuevos.length != 0 nuevos.each do |nuevo| n = Estacion.new( :nombre => nuevo['nombre'], :descripcion => nuevo['descripcion'], :latitud => nuevo['latitud'], :longitud => nuevo['longitud'], :altura => nuevo['altura'], :tipo_estacion_id => nuevo['tipo_estacion_id'], :distrito_id => nuevo['distrito_id'], ) n.save t = { :temporal => nuevo['id'], :nuevo_id => n.id } array_nuevos.push(t) end end if editados.length != 0 editados.each do |editado| e = Estacion.where( :id => editado['id'] ).first e.nombre = editado['nombre'] e.descripcion = editado['descripcion'] e.latitud = editado['latitud'] e.longitud = editado['longitud'] e.altura = editado['altura'] e.tipo_estacion_id = editado['tipo_estacion_id'] e.distrito_id = editado['distrito_id'] e.save end end if eliminados.length != 0 eliminados.each do |eliminado| Estacion.where( :id => eliminado ).delete end end rescue Exception => e Sequel::Rollback error = true execption = e end end if error == false return { :tipo_mensaje => 'success', :mensaje => [ 'Se ha registrado los cambios en las estaciones', array_nuevos ] }.to_json else status 500 return { :tipo_mensaje => 'error', :mensaje => [ 'Se ha producido un error en guardar la tabla de estaciones', execption.message ] }.to_json end end options '/file/upload' do tempfile = params[:myFile][:tempfile] filename = params[:myFile][:filename] cp(tempfile.path, "public/uploads/#{filename}") puts '1 ++++++++++++++++++++++++++++++++' end post '/file/upload' do end <file_sep>import Backbone from 'backbone'; import $ from 'jquery'; import HomeView from '../views/home_view'; import UploadViewTab from '../views/upload_view'; import '../scss/demo.scss'; var accessRouter = Backbone.Router.extend({ // attributes homeView: null, calendarView: null, autocompleteView: null, tableView: null, uploadView: null, // methods initialize: function() { }, routes: { '': 'homeRoute', 'system' : 'systemIndex', 'calendar': 'calendarRoute', 'autocomplete': 'autocompleteRoute', 'tables': 'tableRoute', 'upload': 'uploadRoute', 'system/permission/:system_id' : 'systemPermission', 'system/role/:system_id' : 'systemRole', '*actions' : 'default', }, index: function(){ //window.location.href = BASE_URL + "accesos/#/modulo"; }, default: function() { //window.location.href = BASE_URL + "error/access/404"; }, homeRoute: function(){ if(this.homeView == null){ this.homeView = new HomeView(); } this.homeView.render(); }, calendarRoute: function(){ alert('calendarRoute'); }, autocompleteRoute: function(){ alert('autocompleteRoute'); }, tableRoute: function(){ alert('tableRoute'); }, uploadRoute: function(){ if(this.uploadView == null){ this.uploadView = new UploadViewTab(); } this.uploadView.render(); }, }); $(document).ready(function(){ var router = new accessRouter(); Backbone.history.start(); });
f5e6692471e6bf358e32f33f0c7f0d72feb09fcf
[ "JavaScript", "Ruby", "Markdown" ]
8
JavaScript
pepeul1191/webpack-aprendiendo2
ad4c3384c4afeee27c6d1af2c723e88c0b67cadb
d46a2244ebf9fb2c3aa520c915f81bf1a3293ab7
refs/heads/master
<repo_name>siarmehriangel/currencyconverter<file_sep>/addons/default/madebysauce/convertcurrencies-module/src/Convertcurrency/ConvertcurrencySeeder.php <?php namespace Madebysauce\ConvertcurrenciesModule\Convertcurrency; use Anomaly\Streams\Platform\Database\Seeder\Seeder; use Illuminate\Support\Facades\DB; use Madebysauce\ConvertcurrenciesModule\Convertcurrency\Contract\ConvertcurrencyRepositoryInterface; class ConvertcurrencySeeder extends Seeder { private $convertcurrencyRepository; private $currency; public function __construct(ConvertcurrencyRepositoryInterface $convertcurrencyRepository) { $this->convertcurrencyRepository = $convertcurrencyRepository; } public function setCurrency($currency){ $this->currency = $currency; } /** * Run the seeder. */ public function run() { $this->convertcurrencyRepository->truncate(); dump('Here I Will Be Reading The http://www.floatrates.com/daily/'.$this->currency.'.xml file and will seed my table'); $url = 'http://www.floatrates.com/daily/'.$this->currency.'.xml'; $currencyRates = json_decode(json_encode((array) simplexml_load_file($url)), 1); foreach ($currencyRates['item'] as $currencyRate){ $this->convertcurrencyRepository->create(array( 'pubDate' => $currencyRate['pubDate'], 'baseCurrency' => $currencyRate['baseCurrency'], 'baseName' => $currencyRate['baseName'], 'targetCurrency' => $currencyRate['targetCurrency'], 'targetName' => $currencyRate['targetName'], 'exchangeRate' => round($currencyRate['exchangeRate'], 2) )); } } } <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/Convertcurrency/ConvertcurrencyModel.php <?php namespace Madebysauce\ConvertcurrenciesModule\Convertcurrency; use Madebysauce\ConvertcurrenciesModule\Convertcurrency\Contract\ConvertcurrencyInterface; use Anomaly\Streams\Platform\Model\Convertcurrencies\ConvertcurrenciesConvertcurrenciesEntryModel; class ConvertcurrencyModel extends ConvertcurrenciesConvertcurrenciesEntryModel implements ConvertcurrencyInterface { //for mass assignment protected $guarded = ['id']; } <file_sep>/addons/default/madebysauce/convertcurrencies-module/tests/Unit/Convertcurrency/ConvertcurrencyCriteriaTest.php <?php namespace Madebysauce\ConvertcurrenciesModule\Test\Unit\Convertcurrency; class ConvertcurrencyCriteriaTest extends \TestCase { } <file_sep>/addons/default/madebysauce/convertcurrencies-module/migrations/2018_03_25_200502_madebysauce.module.convertcurrencies__create_convertcurrencies_stream.php <?php use Anomaly\Streams\Platform\Database\Migration\Migration; class MadebysauceModuleConvertcurrenciesCreateConvertcurrenciesStream extends Migration { /** * The stream definition. * * @var array */ protected $stream = [ 'slug' => 'convertcurrencies', 'title_column' => 'targetCurrency' ]; /** * The stream assignments. * * @var array */ protected $assignments = [ 'pubDate' => [ 'translatable' => true, 'required' => true, ], 'baseCurrency' => [ 'translatable' => true, 'required' => true, ], 'baseName' => [ 'translatable' => true, 'required' => true, ], 'targetCurrency' => [ 'translatable' => true, 'required' => true, 'unique' => true, ], 'targetName' => [ 'translatable' => true, 'required' => true, ], 'exchangeRate' => [ 'translatable' => true, 'required' => true, ], ]; } <file_sep>/addons/default/madebysauce/convertcurrencies-module/tests/Unit/Convertcurrency/Form/ConvertcurrencyFormBuilderTest.php <?php namespace Madebysauce\ConvertcurrenciesModule\Test\Unit\Convertcurrency; class ConvertcurrencyFormBuilderTest extends \TestCase { } <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/Convertcurrency/ConvertcurrencyCriteria.php <?php namespace Madebysauce\ConvertcurrenciesModule\Convertcurrency; use Anomaly\Streams\Platform\Entry\EntryCriteria; class ConvertcurrencyCriteria extends EntryCriteria { } <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/Convertcurrency/Contract/ConvertcurrencyRepositoryInterface.php <?php namespace Madebysauce\ConvertcurrenciesModule\Convertcurrency\Contract; use Anomaly\Streams\Platform\Entry\Contract\EntryRepositoryInterface; interface ConvertcurrencyRepositoryInterface extends EntryRepositoryInterface { } <file_sep>/addons/default/madebysauce/convertcurrencies-module/migrations/2018_03_25_200412_madebysauce.module.convertcurrencies__create_convertcurrencies_fields.php <?php use Anomaly\Streams\Platform\Database\Migration\Migration; class MadebysauceModuleConvertcurrenciesCreateConvertcurrenciesFields extends Migration { /** * The addon fields. * * @var array */ protected $fields = [ 'pubDate' => 'anomaly.field_type.text', 'baseCurrency' => 'anomaly.field_type.text', 'baseName' => 'anomaly.field_type.text', 'targetCurrency' => 'anomaly.field_type.text', 'targetName' => 'anomaly.field_type.text', 'exchangeRate' => 'anomaly.field_type.decimal' ]; } <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/Convertcurrency/Contract/ConvertcurrencyInterface.php <?php namespace Madebysauce\ConvertcurrenciesModule\Convertcurrency\Contract; use Anomaly\Streams\Platform\Entry\Contract\EntryInterface; interface ConvertcurrencyInterface extends EntryInterface { } <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/ConvertcurrenciesModule.php <?php namespace Madebysauce\ConvertcurrenciesModule; use Anomaly\Streams\Platform\Addon\Module\Module; class ConvertcurrenciesModule extends Module { /** * The navigation display flag. * * @var bool */ protected $navigation = true; /** * The addon icon. * * @var string */ protected $icon = 'fa fa-gbp'; /** * The module sections. * * @var array */ protected $sections = [ 'convertcurrencies' => [ 'buttons' => [ 'new_convertcurrency' => [ 'text' => 'New Currency Rate' ], ], ], ]; } <file_sep>/addons/default/madebysauce/convertcurrencies-module/tests/Unit/Convertcurrency/ConvertcurrencyPresenterTest.php <?php namespace Madebysauce\ConvertcurrenciesModule\Test\Unit\Convertcurrency; class ConvertcurrencyPresenterTest extends \TestCase { } <file_sep>/addons/default/madebysauce/convertcurrencies-module/resources/lang/en/field.php <?php return [ 'pubDate' => [ 'name' => 'Publish Date' ], 'baseCurrency' => [ 'name' => 'Base Currency' ], 'baseName' => [ 'name' =>'Base Name' ], 'targetCurrency'=> [ 'name' => 'Target Currency' ], 'targetName'=> [ 'name' =>'Target Name' ], 'exchangeRate' => [ 'name' => 'Exchange Rate' ] ]; <file_sep>/addons/default/madebysauce/convertcurrencies-module/tests/Unit/Convertcurrency/ConvertcurrencyCollectionTest.php <?php namespace Madebysauce\ConvertcurrenciesModule\Test\Unit\Convertcurrency; class ConvertcurrencyCollectionTest extends \TestCase { } <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/Convertcurrency/ConvertcurrencyRepository.php <?php namespace Madebysauce\ConvertcurrenciesModule\Convertcurrency; use Madebysauce\ConvertcurrenciesModule\Convertcurrency\Contract\ConvertcurrencyRepositoryInterface; use Anomaly\Streams\Platform\Entry\EntryRepository; class ConvertcurrencyRepository extends EntryRepository implements ConvertcurrencyRepositoryInterface { /** * The entry model. * * @var ConvertcurrencyModel */ protected $model; /** * Create a new ConvertcurrencyRepository instance. * * @param ConvertcurrencyModel $model */ public function __construct(ConvertcurrencyModel $model) { $this->model = $model; } } <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/Convertcurrency/ConvertcurrencyCollection.php <?php namespace Madebysauce\ConvertcurrenciesModule\Convertcurrency; use Anomaly\Streams\Platform\Entry\EntryCollection; class ConvertcurrencyCollection extends EntryCollection { } <file_sep>/addons/default/madebysauce/currencyconverter-theme/src/CurrencyconverterTheme.php <?php namespace Madebysauce\CurrencyconverterTheme; use Anomaly\Streams\Platform\Addon\Theme\Theme; class CurrencyconverterTheme extends Theme { } <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/Http/Controller/User/ConvertcurrenciesController.php <?php /** * Created by PhpStorm. * User: siar * Date: 26/03/18 * Time: 01:05 */ namespace Madebysauce\ConvertcurrenciesModule\Http\Controller\User; use Anomaly\Streams\Platform\Http\Controller\PublicController; use Illuminate\Support\Facades\Validator; class ConvertcurrenciesController extends PublicController { private $baseCurrency; protected $floatRate; private $currencyRates; private $selectOptions; private $calculations; private $baseOption; private function setBaseCurrency($currency){ $this->baseCurrency = $currency; $this->calculations = []; } public function index(){ $this->configureVariables('gbp'); if($this->request->getMethod() == 'POST') { $validator = Validator::make($this->request->all(), [ 'basecurrency' => 'required', 'exchangeAmount' => 'required|numeric', 'targetcurrency' => 'required|array|min:1', ],['basecurrency.required' => 'Please select \'From Currency\'.', 'exchangeAmount.required' => 'Exchange Amount is required', 'exchangeAmount.numeric' => 'Exchange Amount should be numeric', 'targetcurrency.required' => 'Please select at least one from the \'To Currency\' list', 'targetcurrency.array' => 'Please select at least one from the \'To Currencies\' list']); if ($validator->fails()) { return $this->view->make('madebysauce.module.convertcurrencies::convertcurrencies/index', ['selectOptions' => $this->selectOptions, 'errors' => $validator->errors()->getMessages()]); } if(isset($this->request->basecurrency)){ $this->configureVariables(strtolower($this->request->basecurrency)); } $this->calculations = $this->calculate($this->request->all()); } return $this->view->make('madebysauce.module.convertcurrencies::convertcurrencies/index', ['selectOptions' => $this->selectOptions, 'calculations' => $this->calculations]); } public function configureVariables($basecurrency){ $this->setBaseCurrency($basecurrency); $this->floatRate = 'http://www.floatrates.com/daily/'.$this->baseCurrency.'.xml'; $currencyRatesXML_TO_ARRAY = json_decode(json_encode((array) simplexml_load_file($this->floatRate)), 1); $this->currencyRates = $currencyRatesXML_TO_ARRAY['item']; $selectOptions = array_column($this->currencyRates, 'targetName', 'targetCurrency'); $this->baseOption = array($this->currencyRates[0]['baseCurrency'] => $this->currencyRates[0]['baseName']); $this->selectOptions = array_merge($this->baseOption,$selectOptions); } public function calculate($requestArray){ $calculations = []; $targetCurrencies = $requestArray['targetcurrency']; $tempPubDate = ''; foreach ($targetCurrencies as $targetCurrency){ $currencyRatesCollection = collect($this->currencyRates)->where('targetCurrency','=', $targetCurrency)->first(); if($currencyRatesCollection and sizeof($currencyRatesCollection)){ $currencyRatesCollection['calculated'] = $currencyRatesCollection['exchangeRate'] * $requestArray['exchangeAmount']; $currencyRatesCollection['exchangeAmount'] = $requestArray['exchangeAmount']; $tempPubDate = $currencyRatesCollection['pubDate']; $calculations[] = $currencyRatesCollection; } elseif($targetCurrency == $requestArray['basecurrency']){ $calculations[] = [ 'title' => '1 '.$requestArray['basecurrency'].' = 1 '. $requestArray['basecurrency'], 'link' => 'http://www.floatrates.com/'.strtolower($targetCurrency).'/'.strtolower($requestArray['basecurrency']).'/', 'description' => '1 '.$requestArray['basecurrency'].' = 1 '. $requestArray['basecurrency'], 'pubDate' => !empty($tempPubDate) ? $tempPubDate : date('D, d M Y H:i:s').' GMT', 'baseCurrency' => $requestArray['basecurrency'], 'baseName' => $requestArray['basecurrency'], 'targetCurrency' => $requestArray['basecurrency'], 'targetName' => $requestArray['basecurrency'], 'exchangeRate' => 1, 'calculated' => $requestArray['exchangeAmount'], 'exchangeAmount' => $requestArray['exchangeAmount'] ]; } } return $calculations; } }<file_sep>/addons/default/madebysauce/convertcurrencies-module/tests/Unit/Convertcurrency/ConvertcurrencyModelTest.php <?php namespace Madebysauce\ConvertcurrenciesModule\Test\Unit\Convertcurrency; class ConvertcurrencyModelTest extends \TestCase { } <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/Convertcurrency/ConvertcurrencyObserver.php <?php namespace Madebysauce\ConvertcurrenciesModule\Convertcurrency; use Anomaly\Streams\Platform\Entry\EntryObserver; class ConvertcurrencyObserver extends EntryObserver { } <file_sep>/README.md # Currency Converter added theme addon: php artisan make:addon madebysauce.theme.currencyconverter # Currency Converter added module addon: php artisan make:addon madebysauce.module.convertcurrencies # Currency Converter installed module addon: php artisan addon:install convertcurrencies # Notes: Everything is pushed into master as it is one person project. if you have any question please email <EMAIL> <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/Http/Controller/Admin/ConvertcurrenciesController.php <?php namespace Madebysauce\ConvertcurrenciesModule\Http\Controller\Admin; use Madebysauce\ConvertcurrenciesModule\Convertcurrency\Form\ConvertcurrencyFormBuilder; use Madebysauce\ConvertcurrenciesModule\Convertcurrency\Table\ConvertcurrencyTableBuilder; use Anomaly\Streams\Platform\Http\Controller\AdminController; class ConvertcurrenciesController extends AdminController { /** * Display an index of existing entries. * * @param ConvertcurrencyTableBuilder $table * @return \Symfony\Component\HttpFoundation\Response */ public function index(ConvertcurrencyTableBuilder $table) { return $table->render(); } /** * Create a new entry. * * @param ConvertcurrencyFormBuilder $form * @return \Symfony\Component\HttpFoundation\Response */ public function create(ConvertcurrencyFormBuilder $form) { return $form->render(); } /** * Edit an existing entry. * * @param ConvertcurrencyFormBuilder $form * @param $id * @return \Symfony\Component\HttpFoundation\Response */ public function edit(ConvertcurrencyFormBuilder $form, $id) { return $form->render($id); } } <file_sep>/addons/default/madebysauce/convertcurrencies-module/tests/Unit/Convertcurrency/Table/ConvertcurrencyTableBuilderTest.php <?php namespace Madebysauce\ConvertcurrenciesModule\Test\Unit\Convertcurrency; class ConvertcurrencyTableBuilderTest extends \TestCase { } <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/Convertcurrency/ConvertcurrencyPresenter.php <?php namespace Madebysauce\ConvertcurrenciesModule\Convertcurrency; use Anomaly\Streams\Platform\Entry\EntryPresenter; class ConvertcurrencyPresenter extends EntryPresenter { } <file_sep>/addons/default/madebysauce/currencyconverter-theme/tests/Feature/CurrencyconverterThemeTest.php <?php namespace Madebysauce\CurrencyconverterTheme\Test\Feature; class CurrencyconverterThemeTest extends \TestCase { public function testFeature() { $this->markTestSkipped('Not implemented.'); } } <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/Convertcurrency/ConvertcurrencyRouter.php <?php namespace Madebysauce\ConvertcurrenciesModule\Convertcurrency; use Anomaly\Streams\Platform\Entry\EntryRouter; class ConvertcurrencyRouter extends EntryRouter { } <file_sep>/addons/default/madebysauce/convertcurrencies-module/resources/lang/en/addon.php <?php return [ 'title' => 'Currency Rates', 'name' => 'Convert Rates Module', 'description' => 'Adding New Currency Rates Here' ]; <file_sep>/addons/default/madebysauce/convertcurrencies-module/src/ConvertcurrenciesModuleSeeder.php <?php /** * Created by PhpStorm. * User: siar * Date: 25/03/18 * Time: 23:14 */ namespace Madebysauce\ConvertcurrenciesModule; use Anomaly\Streams\Platform\Database\Seeder\Seeder; use Madebysauce\ConvertcurrenciesModule\Convertcurrency\Contract\ConvertcurrencyRepositoryInterface; use Madebysauce\ConvertcurrenciesModule\Convertcurrency\ConvertcurrencySeeder; class ConvertcurrenciesModuleSeeder extends Seeder { private $currency; private $convertcurrencyRepository; public function __construct(ConvertcurrencyRepositoryInterface $convertcurrencyRepository, $currency = 'gbp') { $this->convertcurrencyRepository = $convertcurrencyRepository; $this->currency = $currency; } public function run() { $convertcurrencySeeder = new ConvertcurrencySeeder($this->convertcurrencyRepository); $convertcurrencySeeder->setCurrency($this->currency); $convertcurrencySeeder->run(); } }<file_sep>/addons/default/madebysauce/currencyconverter-theme/resources/lang/en/addon.php <?php return [ 'title' => 'Currencyconverter', 'name' => 'Currencyconverter Theme', 'description' => '' ]; <file_sep>/addons/default/madebysauce/convertcurrencies-module/resources/lang/en/button.php <?php return [ 'new_convertcurrency' => 'New Currency Rate', ]; <file_sep>/addons/default/madebysauce/convertcurrencies-module/tests/Unit/Convertcurrency/ConvertcurrencyRepositoryTest.php <?php namespace Madebysauce\ConvertcurrenciesModule\Test\Unit\Convertcurrency; class ConvertcurrencyRepositoryTest extends \TestCase { }
fcafb72d7c51d166c330b5b90054da8388bddb65
[ "Markdown", "PHP" ]
30
PHP
siarmehriangel/currencyconverter
77e5acc7f558cd5d89050c4bf89d12c1a70ef5fa
c690b9545f440e052c5a3f740bc0b87c54ec11c7
refs/heads/main
<file_sep><?php function getScripts() { wp_enqueue_style( 'main_css', get_template_directory_uri() . '/assets/css/main.css', '', 1.00000000003, 'all' ); wp_enqueue_script( 'main_js', get_template_directory_uri() . '/assets/js/main.js', '', 1, true); } add_action( 'wp_enqueue_scripts', 'getScripts'); function smallStafs() { add_theme_support( 'title-tag'); add_theme_support('post-thumbnails'); add_theme_support('custom-logo'); add_theme_support('automatic-feed-links'); add_theme_support('widgets'); register_nav_menus( array( 'primary' => __('Primary Menu', 'sandrose_v'), 'social' => __('Social Menu', 'sandrose_v') )); } add_action( 'after_setup_theme', 'smallStafs' ); function customHeader($wp_customize) { $wp_customize->add_section('header', array( 'title' => __('Header', 'sandrose_v'), 'description' => sprintf(__('Options for theme colors','sandrose_v')), 'priority' => 102 )); $wp_customize->add_setting('header-title', array( 'default' => __('Sandrose', 'sandrose_v'), 'sanitize_callback' => 'sandrose_sanitize_text', 'type' => 'theme_mod' )); $wp_customize->add_control('header-title', array( 'label' => __('Header title', 'sandrose_v'), 'settings' => 'header-title', 'section' => 'header', 'priority' => 2 )); $wp_customize->add_setting('header-subtitle', array( 'default' => __('Enjoy and rest your feets on amazing beaches','sandrose_v'), 'sanitize_callback' => 'sandrose_sanitize_text', 'type' => 'theme_mod' )); $wp_customize->add_control('header-subtitle', array( 'label' => __('Header subtitle', 'sandrose_v'), 'settings' => 'header-subtitle', 'section' => 'header', 'priority' => 2 )); $wp_customize->add_setting('header-btn-text', array( 'default' => __('Explore','sandrose_v'), 'sanitize_callback' => 'sandrose_sanitize_text', 'type' => 'theme_mod' )); $wp_customize->add_control('header-btn-text', array( 'label' => __('Button name', 'sandrose_v'), 'settings' => 'header-btn-text', 'section' => 'header', 'priority' => 2 )); $wp_customize->add_setting('header-btn-url', array( 'default' => __('#latest-posts', 'sandrose_v'), 'sanitize_callback' => 'sandrose_sanitize_url', 'type' => 'theme_mod' )); $wp_customize->add_control('header-btn-url', array( 'label' => __('Button url', 'sandrose_v'), 'settings' => 'header-btn-url', 'section' => 'header', 'priority' => 2 )); $wp_customize->add_setting('header-background', array( 'default' => get_template_directory_uri() . './assets/images/stene.jpeg', 'sanitize_callback' => 'sandrose_sanitize_url', 'type' => 'theme_mod' )); $wp_customize->add_control(new WP_Customize_Image_Control( $wp_customize, 'header-background', array( 'label' => __('Header background image', 'sandrose_v'), 'settings' => 'header-background', 'section' => 'header', 'priority' => 1 )) ); } add_action('customize_register', 'customHeader'); function sandrose_sanitize_text($ar) { return sanitize_text_field( $ar ); } function sandrose_sanitize_url($ar) { return esc_url($ar); } function sandroseWidgets() { register_sidebar( array( 'name' => __('Custom sidebar', 'sandrose_v'), 'id' => 'custom-sidebar-s', 'before_widget' => '<ul class="main-sidebar__lists">', 'after_widget' => '</ul>', 'before_title' => '<h3 class="main-sidebar__header" >', 'after_title' => '</h3>', )); } add_action( 'widgets_init', 'sandroseWidgets' );<file_sep>//Menu Toggler let toggler = document.querySelector('.menu__toggler'); let menu = document.querySelector('.menu__list'); let menu_items = document.querySelectorAll('.menu__item'); toggler.addEventListener('click', () => { menu.classList.toggle('open'); toggler.classList.toggle('open'); }) menu_items.forEach((item) => { item.addEventListener('click', () => { menu.classList.remove('open'); toggler.classList.remove('open'); }) }) // Search form toggler let search_btn = document.querySelector('.search-icon'); let search_form = document.querySelector('.search-form'); search_btn.addEventListener('click', () => { search_form.classList.toggle('open'); }) <file_sep><form action="<?php echo esc_url(home_url('/'))?>" method="GET" class="search-form"> <div class="search-form__group"> <input type="text" class="search-form__input" id="search" placeholder="Search" name="s" value="<?php esc_attr(the_search_query()) ?>" autocomplete="off" > <button type="submit" class="search-form__btn"><?php _e('Search', 'sandrose_v'); ?></button> </div> </form><file_sep><?php get_header(); ?> <section class="all-posts"> <h2 class="heading-primary"><?php the_title(); ?></h2> <div class="all-posts__container"> <div class="article-container"> <div class="page-post"> <?php if(has_post_thumbnail()) : ?> <div class="page-post__thumbnail"> <img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_title(); ?>"> </div> <?php endif; ?> <div class="page-post__content page-layout-2"> <?php the_content(); ?> </div> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'sandrose_v' ), 'after' => '</div>', 'link_before' => '<span class="page-number">', 'link_after' => '</span>', ) ); ?> </div> </div> <aside class="main-sidebar"> <?php get_sidebar(); ?> </aside> </div> </section> <?php get_footer(); ?><file_sep><?php get_header(); ?> <section class="all-posts"> <h2 class="heading-primary"><?php _e('Results for: ', 'sandrose_v'); the_search_query(); ?></h2> <div class="all-posts__container"> <div class="article-container"> <?php if(have_posts()) : while(have_posts()) : the_post(); ?> <?php get_template_part('template-parts/article', 'body'); ?> <?php endwhile; ?> <?php get_template_part('template-parts/article', 'pagination'); ?> <?php else: ?> <div class="text-404"><?php _e('No results found', 'sandrose_v'); ?></div> <?php endif; ?> </div> <aside class="main-sidebar"> <?php get_sidebar(); ?> </aside> </div> </section> <?php get_footer(); ?><file_sep><?php get_header(); ?> <section class="all-posts"> <h2 class="heading-primary"><?php _e('Page not found!', 'sandrose_v'); ?></h2> <div class="all-posts__container"> <div class="article-container"> <div class="page-post"> <div class="page-post__thumbnail-404"> <img src="<?php echo get_template_directory_uri() . './assets/images/404proba.png' ?>" alt="<?php _e('Page not found', 'sandrose_v'); ?>"> </div> </div> </div> <aside class="main-sidebar"> <?php get_sidebar(); ?> </aside> </div> </section> <?php get_footer(); ?><file_sep><div class="pagination"> <?php echo paginate_links(array( 'mid-size' => 2, 'prev_text' => '<i class="fas fa-chevron-left"></i>', 'next_text' => '<i class="fas fa-chevron-right"></i>' )); ?> </div><file_sep><article <?php post_class('article'); ?>> <div class="article__front"> <div class="article__head" <?php if(has_post_thumbnail()) : ?> style="background-image: url(<?php echo get_the_post_thumbnail_url() ?>);" <?php endif; ?> > <p class="article__title"><?php the_title(); ?></p> </div> <div class="article__foot"> <ul class="article__category"> <?php $categories = get_the_category(); ?> <?php foreach( $categories as $category) : ?> <li class="article__category-item"> <a href="<?php echo get_category_link($category->term_id); ?>" class="article__category-link"><?php echo $category->name ?></a> </li> <?php endforeach; ?> </ul> <div class="article__meta"> <div class="article__author"><?php the_author(); ?></div> <div class="article__date"> <?php the_time('Y-m-d H:i:s'); ?> </div> </div> </div> </div> <div class="article__back"> <div class="article__body"> <p class="article__text"><?php echo get_the_excerpt(); ?></p> <a href="<?php the_permalink(); ?>" class="btn--read-more"><?php _e('Read more','sandrose_v'); ?> &rarr;</a> <ul class="article__category"> <?php $categories = get_the_category(); ?> <?php foreach( $categories as $category) : ?> <li class="article__category-item"> <a href="<?php echo get_category_link($category->term_id); ?>" class="article__category-link"><?php echo $category->name ?></a> </li> <?php endforeach; ?> </ul> </div> </div> </article><file_sep><div class="main-sidebar__item"> <h3 class="main-sidebar__header"><?php _e('Categories', 'sandrose_v'); ?></h3> <ul class="main-sidebar__lists"> <?php $allCategories = get_categories(array( 'orderBy' => 'name', 'hide_empty' => 0, 'parent' => 0 )); ?> <?php foreach($allCategories as $allCat) : ?> <li><a href="<?php echo get_category_link($allCat->term_id) ?>"><?php echo $allCat->name; ?></a></li> <?php endforeach; ?> </ul> </div> <div class="main-sidebar__item"> <h3 class="main-sidebar__header"><?php _e('Latest posts', 'sandrose_v'); ?></h3> <ul class="main-sidebar__posts"> <?php $wp_query = new WP_Query(array( 'post_type' => 'post', 'order' => 'DESC', 'posts_per_page' => 3, 'ignore_sticky_posts' => 1, 'date_query' => array( 'after' => '-30 days', 'column' => 'post_date' ) )); ?> <?php if($wp_query->have_posts()) : while($wp_query->have_posts()) : $wp_query->the_post(); ?> <div class="main-sidebar__post"> <?php if(has_post_thumbnail()) : ?> <div class="main-sidebar__post-thumbnail"> <img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_title(); ?>"> </div> <?php endif; ?> <div class="main-sidebar__post-title"> <p><?php the_time('Y-m-d H:i:s'); ?></p> <a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a> </div> </div> <?php endwhile; ?> <?php endif; ?> </ul> </div> <?php if(is_active_sidebar( 'custom-sidebar-s' )) : ?> <?php dynamic_sidebar( 'custom-sidebar-s' ); ?> <?php endif; ?><file_sep><?php get_header(); ?> <section class="latest-posts" id="latest-posts" style="background-image: linear-gradient(to right, rgba(114, 175, 224, 0.8), rgba(32, 99, 155, 0.8), rgba(16, 81, 134, 0.8)), url('<?php echo get_template_directory_uri() . '/assets/images/voda.jpeg'?>');" > <h2 class="heading-primary"><?php _e('Most popular posts', 'sandrose_v'); ?></h2> <div class="article-container"> <?php $wp_query = new WP_Query(array( 'post_type' => 'post', 'posts_per_page' => 2, 'ignore_sticky_posts' => 1, 'comment_count' => array( 'value' => 3, 'compare' => '>=', ) )); ?> <?php if($wp_query->have_posts()) : while($wp_query->have_posts()) : $wp_query->the_post() ?> <?php get_template_part('template-parts/article', 'body'); ?> <?php endwhile; ?> <!-- need to check this --> <?php get_template_part('template-parts/article', 'pagination'); ?> <?php else: ?> <?php _e('Posts no found', 'sandrose_v'); ?> <?php endif; ?> <?php wp_reset_postdata(); ?> </div> </section> <?php get_footer(); ?><file_sep><!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' )?>"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <?php wp_body_open(); ?> <!--Search Icon --> <div class="search-icon">&#128269;</div> <!-- Search Form --> <?php get_search_form(); ?> <!-- Navigation --> <nav class="menu"> <div class="menu__logo"> <a href="#"> <!--<img class="menu__logo-img" src="assets/images/logo.jpg" alt="slika">--> <?php if(function_exists('the_custom_logo')) { the_custom_logo(); } ?> </a> </div> <div class="menu__toggler"><span></span></div> <?php wp_nav_menu(array( 'menu' => '', 'container' => 'ul', 'container_class' => '', 'container_id' => '', 'container_aria_label' => '', 'menu_class' => 'menu__list', 'menu_id' => '', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'item_spacing' => 'preserve', 'depth' => 0, 'walker' => '', 'theme_location' => 'primary', )); ?> </nav> <!-- Header --> <header class="header" style="background-image: linear-gradient(to right, rgba(114, 175, 224, 0.7), rgba(32, 99, 155, 0.7), rgba(16, 81, 134, 0.7)), url('<?php echo esc_url(get_theme_mod('header-background')); ?>')"; > <h1 class="header__title"><?php echo esc_html(get_theme_mod('header-title', 'Sandrose')); ?></h1> <p class="header__subtitle"><?php echo esc_html(get_theme_mod('header-subtitle', 'Enjoy and rest your feets on amazing beaches')); ?></p> <?php if(get_theme_mod('header-btn-text')) : ?> <a href="<?php echo esc_url(get_theme_mod('header-btn-url')); ?>" class="btn btn--primary"><?php echo esc_html(get_theme_mod('header-btn-text', 'Explore')); ?></a> <?php endif; ?> </header> <main class="main"><file_sep> </main> <footer class="footer"> <div class="footer__body"> <div class="footer__logo"> <?php if(function_exists('the_custom_logo')) { the_custom_logo(); } ?> </div> <div class="footer__description">Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo consequatur earum animi quas adipisci atque! Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo consequatur earum animi quas adipisci atque! </div> <div class="footer__tags"> <h3 class="footer__tags-header">Tags</h3> <ul class="footer__tags-list"> <?php $tags = get_tags(); ?> <?php $i = 0; foreach($tags as $tag) : ?> <?php if(++$i > 20) break; ?> <li><a href="<?php echo get_tag_link( $tag->term_id )?>"><?php echo $tag->name ?></a></li> <?php endforeach; ?> </ul> </div> </div> <div class="footer__data"> <div class="footer__copy">&copy; <?php _e('Copyright 2020 Sandrose | All Rights Reserved | <a href="#" class="author-link"><NAME></a>', 'sandrose_v') ?></div> <ul class="footer__social"> <li><a href="#"><i class="fab fa-twitter"></i></a></li> <li><a href="#"><i class="fab fa-facebook-f"></i></a></li> <li><a href="#"><i class="fab fa-instagram"></i></a></li> <li><a href="#"><i class="fab fa-youtube"></i></a></li> </ul> </div> </footer> <?php wp_footer(); ?> </body>
70940b80e976174531260b2bbfbcde51a7071ddc
[ "JavaScript", "PHP" ]
12
PHP
IvanCanic/Sandrose-theme-WP
6415c1e6a9af3dac569f56c91051b2b2fdb6af46
5b271d900ecbeab16215a5f2c1a5f1ae8a301a45
refs/heads/master
<repo_name>wys97/heshifu<file_sep>/.temp/pages/my/apply_detail/apply_detail.js import Nerv from "nervjs"; import './apply_detail.css?v=20190904113'; import Taro, { showLoading as _showLoading, hideLoading as _hideLoading, showToast as _showToast } from "@tarojs/taro-h5"; import { View, Text } from '@tarojs/components'; import Netservice from "../../../netservice"; import Common from "../../../common"; export default class ApplyDetail extends Taro.Component { config = { navigationBarTitleText: '申请详情' }; state = { info: {}, type: 0 }; componentWillMount() { let type = this.$router.params.type || 0; let id = this.$router.params.id || 0; this.getInfo(type, id); this.setState({ type: type }); } componentDidMount() {} componentWillUnmount() {} componentDidShow() {} componentDidHide() {} getInfo(type, rid) { _showLoading({ title: '努力加载中…' }); let that = this; let url = ''; if (type == 0) url = 'heque-backend/collect/queryLoanDetail';else if (type == 1) url = 'heque-backend/work_driver/queryWorkDriverDetail';else if (type == 2) url = 'heque-backend/employ_driver/employDriverDetail';else if (type == 3) url = 'heque-backend/collectCarInfo/findDetail';else if (type == 4) url = 'heque-backend/collectYaDiInfo/findDetail';else if (type == 5) url = 'heque-backend/collectCaoCaoInfo/findDetail';else if (type == 6) url = 'heque-backend/collectShouQiInfo/findDetail';else if (type == 7) url = 'heque-backend/collectPreciseCarInfo/findDetail'; Netservice.request({ url: url + '?id=' + rid, method: 'GET', success: function (res) { _hideLoading(); console.log(res); if (res.code !== Common.NetCode_NoError) { _showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } that.setState({ info: res.data }); }, error: function (err) { _hideLoading(); } }); } render() { let { type, info } = this.state; const moneyDetail = <View className="detail-wrapper"> <View className="detailw-item"> <Text className="dwi-title">周转周期</Text> <Text className="dwi-content">{this.getTimeStr(info.cycle)}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">周转金额(元)</Text> <Text className="dwi-content">{this.getAmountStr(info.money)}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">产品偏好</Text> <Text className="dwi-content">{this.getPreferenceStr(info.special)}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">还款方式偏好</Text> <Text className="dwi-content">{this.getRepaymentStr(info.repayment)}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">您的工作</Text> <Text className="dwi-content">{this.getWorkStr(info.job)}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">您的月收入范围</Text> <Text className="dwi-content">{this.getEarningStr(info.salary)}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">您周转需求的紧急程度</Text> <Text className="dwi-content">{this.getEmergencyStr(info.emergent)}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">称呼</Text> <Text className="dwi-content">{info.userName}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">联系方式</Text> <Text className="dwi-content">{info.phoneNum}</Text> </View> </View>; const rentDetail = <View className="detail-wrapper"> <View className="detailw-item"> <Text className="dwi-title">称呼</Text> <Text className="dwi-content">{info.userName}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">联系方式</Text> <Text className="dwi-content">{info.phoneNum}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">要求的车型方案内容</Text> {info.carType && info.carType.length > 0 && this.getRentArray(info.carType).map((item, index) => { return <View className="rent-detail-view" key={index}> <Text className="rent-detail-text">{item.text}</Text> <Text className="rent-detail-more">{item.more}</Text> </View>; })} </View> </View>; const asCopilotDetail = <View className="detail-wrapper"> <View className="detailw-item"> <Text className="dwi-title">副班代班时间</Text> <Text className="dwi-content">{this.getWorkTimeStr(info.type)}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">接受哪几个区域交车</Text> <Text className="dwi-content dwi_bottom">{info.provinceName + '-' + info.cityName}</Text> <Text className="dwi-content">{(info.areasName || '').replace(/,/g, " ")}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">个人驾龄</Text> <Text className="dwi-content">{this.getDriverTimeStr(info.driverTime)}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">可联系电话</Text> <Text className="dwi-content">{info.phoneNumber}</Text> </View> </View>; const findCopilotDetail = <View className="detail-wrapper"> <View className="detailw-item"> <Text className="dwi-title">副班代班时间</Text> <Text className="dwi-content">{this.getWorkTimeStr(info.type)}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">接受哪几个区域交车</Text> <Text className="dwi-content dwi_bottom">{info.provinceName + '-' + info.cityName}</Text> <Text className="dwi-content">{(info.areasName || '').replace(/,/g, " ")}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">对副班驾龄要求</Text> <Text className="dwi-content">{this.getDriverTimeStr(info.driverTime)}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">补充其他要求</Text> <View className="dwi-wapper"> <Text className="dwi-content">{(info.threeCertificateReady == 1 ? '三证齐全 ' : '') + (info.lessFifty == 1 ? '小于50岁 ' : '') + (info.sameProvince == 1 ? '老乡' : '')}</Text> {info.sameProvince == 1 && <Text className="dwi-content-province">{'(' + info.nativeName + ')'}</Text>} </View> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">可联系电话</Text> <Text className="dwi-content">{info.phoneNumber}</Text> </View> </View>; const rentCar = <View className="detail-wrapper"> <View className="detailw-item"> <Text className="dwi-title">称呼</Text> <Text className="dwi-content">{info.userName}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">联系方式</Text> <Text className="dwi-content">{info.phoneNum}</Text> <View className="dwi-line" /> </View> <View className="detailw-item"> <Text className="dwi-title">品牌偏好</Text> <Text className="dwi-content">{(info.carBrand || '').replace(/,/g, " ")}</Text> <View className="dwi-line" /> </View> <View className="detailw-item detailw_flex"> <Text className="dwi-title">动力类型</Text> <Text className="dwi-content margin_no">{this.getDynamics(info.powerType)}</Text> </View> <View className="detailw-item detailw_flex"> <Text className="dwi-title">变速箱</Text> <Text className="dwi-content margin_no">{this.getGearboxes(info.gearbox)}</Text> </View> <View className="detailw-item detailw_flex"> <Text className="dwi-title">排量</Text> <Text className="dwi-content margin_no">{this.getDisplacements(info.displacement)}</Text> </View> <View className="detailw-item detailw_flex"> <Text className="dwi-title">车龄</Text> <Text className="dwi-content margin_no">{this.getCarAges(info.carAge)}</Text> </View> <View className="detailw-item "> <Text className="dwi-title">车款亮点</Text> <Text className="dwi-content">{(info.preference || '').replace(/,/g, " ")}</Text> <View className="dwi-line" /> </View> <Text className="dwi_title_font">对租赁方案的要求</Text> <View className="detailw-item detailw_flex"> <Text className="dwi-title">租金</Text> <Text className="dwi-content margin_no">{this.getMonies(info.rent)}</Text> </View> <View className="detailw-item detailw_flex margin_bottom"> <Text className="dwi-title">租期</Text> <Text className="dwi-content margin_no">{this.getTimes(info.leaseTerm)}</Text> </View> </View>; return <View className="container-apply-detail"> <View className="apply-detail-content"> <View className="adc-header"> <Text className="adch-state">{this.getStateStr(info.state)}</Text> {info.state == 2 && info.result && info.result.length > 0 && <Text className="adch-result">{info.result}</Text>} <View className="adch-line" /> {(type < 4 || type == 7) && <Text className="adch-text">已提交个人诉求</Text>} {type > 3 && type != 7 && <Text className="adch-text mar-bottom">已提交网约车合作服务申请</Text>} </View> {type == 0 && moneyDetail} {type == 1 && asCopilotDetail} {type == 2 && findCopilotDetail} {type == 3 && rentDetail} {type == 7 && rentCar} </View> </View>; } //状态 0-待处理 1-处理中 2-处理完成 3-已取消 getStateStr(state) { if (state == 0) return '待处理';else if (state == 1) return '处理中';else if (state == 2) return '处理完成';else if (state == 3) return '已取消';else if (state == 4) return '处理失败';else if (state == 5) return '已关闭'; } //周转 ---------------- getTimeStr(value) { const list = [{ value: 1, text: '1~30天' }, { value: 2, text: '30天~1年' }, { value: 3, text: '1年以上' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } getAmountStr(value) { const list = [{ value: 1, text: '1000 ~ 1万' }, { value: 2, text: '1万 ~ 5万' }, { value: 3, text: '5万以上' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } getPreferenceStr(value) { const list = [{ value: 1, text: '纯信用借款产品' }, { value: 2, text: '抵押借款产品(汽车、房产)' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } getRepaymentStr(value) { const list = [{ value: 1, text: '按日计息,随借随还' }, { value: 2, text: '按月等额,长期超划算' }, { value: 3, text: '按月付息,到期还本' }, { value: 4, text: '一次性还本付息' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } getWorkStr(value) { const list = [{ value: 1, text: '出租车司机' }, { value: 2, text: '网约车司机' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } getEarningStr(value) { const list = [{ value: 1, text: '5000~8000元' }, { value: 2, text: '8000~12000元' }, { value: 3, text: '12000~15000元' }, { value: 4, text: '15000元以上' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } getEmergencyStr(value) { const list = [{ value: 1, text: '越快越好,即刻需求' }, { value: 2, text: '近期有可能需要' }, { value: 3, text: '暂时不需要' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } //租车 ---------------- getRentArray(value = '') { const list = [{ value: 1, text: '燃油车', more: '' }, { value: 2, text: '新能源车', more: '' }, { value: 3, text: '短租期', more: '(3个月)' }, { value: 4, text: '租车跑快车', more: '(注重车辆性价比)' }, { value: 5, text: '租车跑专车', more: '(注重车辆品牌性能)' }]; let target = []; const values = value.split(','); for (let i = 0; i < values.length; i++) { const v = values[i]; list.map(function (item) { if (item.value == v) target.push(item); }); } return target; } //当副班 ---------------- getWorkTimeStr(value) { const list = [{ value: 1, text: '白班' }, { value: 2, text: '夜班' }, { value: 3, text: '都可以' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } getDriverTimeStr(value) { const list = [{ value: 0, text: '不限' }, { value: 1, text: '1年' }, { value: 2, text: '2年' }, { value: 3, text: '3年' }, { value: 4, text: '3年以上' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } //type:0-周转 1-当副班 2-招副班 3-租车 4-亚滴租车 5-曹操出行 6-首汽约车 getTypeStr(type) { if (type == 0) return '周转';else if (type == 1) return '当副班';else if (type == 2) return '招副班';else if (type == 3) return '租车';else if (type == 4) return '亚滴租车';else if (type == 5) return '曹操出行';else if (type == 6) return '首汽约车'; } //精准选车----------------------------------------- getDynamics(value) { let list = [{ value: 0, text: '不限' }, { value: 1, text: '汽油' }, { value: 2, text: '纯电动' }, { value: 3, text: '油电混合' }, { value: 4, text: '油气混合' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } getGearboxes(value) { let list = [{ value: 0, text: '不限' }, { value: 1, text: '自动挡' }, { value: 2, text: '手动挡' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } getDisplacements(value) { let list = [{ value: 0, text: '不限' }, { value: 1, text: '1-2L' }, { value: 2, text: '2-3L' }, { value: 3, text: '3L以上' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } getCarAges(value) { let list = [{ value: 0, text: '不限' }, { value: 1, text: '新车' }, { value: 2, text: '6个月以下' }, { value: 3, text: '6-12个月' }, { value: 4, text: '1-2年' }, { value: 5, text: '2-3年' }, { value: 6, text: '3年以上' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } getMonies(value) { let list = [{ value: 0, text: '不限' }, { value: 1, text: '2000~4000元' }, { value: 2, text: '4000~6000元' }, { value: 3, text: '6000元以上' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } getTimes(value) { let list = [{ value: 0, text: '不限' }, { value: 1, text: '3个月以下' }, { value: 2, text: '3~6个月' }, { value: 3, text: '6~12个月' }, { value: 4, text: '12~24个月' }, { value: 5, text: '24个月以上' }]; let target = {}; list.map(function (item) { if (item.value == value) target = item; }); return target.text || ''; } }<file_sep>/src/utils/utils.js import Netservice from '../netservice.js'; // 计算两点距离 export function calculateDistance(p1, p2) { const Rad = ((d) => { return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。 }); let a = Rad(p1.latitude) - Rad(p2.latitude); let b = Rad(p1.longitude) - Rad(p2.longitude); let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(Rad(p1.latitude)) * Math.cos(Rad(p2.latitude)) * Math.pow(Math.sin(b / 2), 2))); s = s * 6378.137; // EARTH_RADIUS; s = (Math.round(s * 10000) / 10000).toFixed(1); if (s >= 1) { s = s + 'km'; } else { s = (Math.round(s * 1000)).toFixed(0) + 'm'; } return s; } // 网址中 解析、查找 对应key的value export function getUrlParam(name) { var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') let url = window.location.href.split('#')[0] let search = url.split('?')[1] if (search) { var r = search.substr(0).match(reg) if (r !== null) return unescape(r[2]) return null } else return null } // 上报用户行为 export function reporteUerBehavior(content, eventType, callBack) { let userId = localStorage.getItem('userId'); if (userId) { const systemInfo = localStorage.getItem('systemInfo') || ''; Netservice.request({ url: 'heque-bi/bp/data/saveBpDataInfo', data: { userId: userId, content: content, eventType: eventType, terminal: systemInfo, channelType: 3 }, success: res => { callBack({ code: 0, msg: '0k' }); }, error: function (err) { callBack({ code: 1, msg: JSON.stringify(err) }); } }) } }<file_sep>/.temp/pages/home_components/point_package/point_package.js import Nerv from "nervjs"; import Taro, { makePhoneCall as _makePhoneCall } from "@tarojs/taro-h5"; import { View, Text, Swiper, SwiperItem, Image } from '@tarojs/components'; import './point_package.css'; import banner1 from '../../../images/home/banner1.png'; import banner2 from '../../../images/home/banner2.png'; import banner3 from '../../../images/home/banner3.png'; import banner4 from '../../../images/home/banner4.png'; import arrowRight1 from '../../../images/common/arrow_right.png'; import inRestImg from '../../../images/home/in_rest.png'; import OrderBtnImg from '../../../images/home/Order_img_btn.png'; import noDishesImg from '../../../images/home/no_dishes.png'; import Netservice from "../../../netservice"; // 下单买单 export default class PointPackage extends Taro.Component { state = { storesDetails: {}, //门店信息 packageList: [], //套餐、菜品列表 inRest: false, //店铺休息状态 true为休息状态 noDishes: false //店铺无菜品 }; componentWillMount() { if (this.props.currentPoint) { let storesDetails = this.props.currentPoint; this.setState({ storesDetails }); //判断是否在休息时间 if (storesDetails.state) this.getPointPackage(storesDetails.id);else this.setState({ inRest: true }); } else { let storesDetails = JSON.parse(this.$router.params.storesDetails); this.setState({ storesDetails }); //判断是否在休息时间 if (storesDetails.state) this.getPointPackage(storesDetails.id);else this.setState({ inRest: true }); } } //实时监听父组件传过来的值的变化 componentWillReceiveProps(nextProps) { if (nextProps.currentPoint && nextProps.currentPoint.id != this.props.currentPoint.id) { let storesDetails = nextProps.currentPoint; this.setState({ storesDetails }); console.log(storesDetails); //判断是否在休息时间 if (storesDetails.state) this.getPointPackage(storesDetails.id);else this.setState({ inRest: true }); } } render() { let { storesDetails, packageList, inRest, noDishes } = this.state; let { foodTime1, foodTime2, foodTime3, foodTime4 } = storesDetails; let timeArray = [foodTime1, foodTime2, foodTime3, foodTime4]; let times = []; for (let time of timeArray) { if (time && time.length > 5) { let aTime = time.slice(0, 5) + '-' + time.slice(11, 16); times.push(aTime); } } storesDetails.times = times; const packages = packageList.map((item, index) => { return <View className="Order_item" key={index} onClick={this.goPackageBuy.bind(this, item)}> <View className="Order_img"> <Image className="Order_image" mode="aspectFill" src={item.dishesUrl} /> </View> <View className="Order_info_wrap"> <Text className="Order_name">{item.dishName}</Text> <Text className="Order_remark">{item.dishesRemake}</Text> <View className="Order_price_wrap"> <View className="Order_tag"> <Text className="Order_sprice"><Text className="Order_sprice_flag">¥</Text>{item.specialOffer > 0 ? item.specialOffer : item.originalPrice}</Text> {item.specialOffer > 0 && <Text className="Order_oprice">¥{item.originalPrice}</Text>} </View> <View className="Order_btn"> <Image src={OrderBtnImg} className="Order_btn_img" style="pointer-events: none" /> </View> </View> </View> </View>; }); {/*没有菜品时 */} const noDishesView = <View className="inRest_img_wrap" onClick={this.goToPoints.bind(this)}> <Image className="inRest_img" mode="aspectFill" src={noDishesImg} /> </View>; return <View className="Order"> <View className="order-point" onClick={this.goSlecPoint}> <View className="order_head"> <View className="order_head_title" onClick={this.goToPoints.bind(this)}> <Text className="order_head_name">{storesDetails.name}</Text> <Image src={arrowRight1} className="order-arrow-right" style="pointer-events: none" /> </View> <View className="order_head_distance">距您 {storesDetails.number >= 1000 ? <Text className="order_head_number"> {(storesDetails.number / 1000).toFixed(1)}<Text className="orderpt_distance_unit"> km</Text> </Text> : <Text className="order_head_number">{storesDetails.number}<Text className="orderpt_distance_unit"> m</Text></Text>} <Text className="order_head_placeholder">|</Text> <Text className="order_head_adds">{storesDetails.adds}</Text> </View> {storesDetails.suppleTime1 !== undefined ? <View className="order_head_time"> <Text>营业时间:</Text> <Text>{storesDetails.suppleTime1}{storesDetails.suppleTime2}{storesDetails.suppleTime3}{storesDetails.suppleTime4}</Text> </View> : <View className="order_head_time"> <Text>营业时间:</Text> {storesDetails.times.length == 1 && <Text>{storesDetails.times[0]}</Text>} {storesDetails.times.length == 2 && <Text>{storesDetails.times[0]} / {storesDetails.times[1]}</Text>} {storesDetails.times.length == 3 && <Text>{storesDetails.times[0]} / {storesDetails.times[1]} / {storesDetails.times[2]}</Text>} {storesDetails.times.length == 4 && <Text>{storesDetails.times[0]} / {storesDetails.times[1]} / {storesDetails.times[2]} / {storesDetails.times[3]}</Text>} </View>} </View> {/*<View className='order-phonePoint-img' onClick={this.contactUs.bind(this)}> <Image src={phonePoint} className='order-phonePoint-img' style='pointer-events: none' /> </View>*/} </View> <Swiper className="order-swiper" circular autoplay interval={3000}> <SwiperItem className="order_SwiperItem"> <Image className="order_swiper_image" src={banner1} onClick={this.goEarn.bind(this)} /> </SwiperItem> <SwiperItem className="order_SwiperItem"> <Image className="order_swiper_image" src={banner2} onClick={this.goLend.bind(this)} /> </SwiperItem> <SwiperItem className="order_SwiperItem"> <Image className="order_swiper_image" src={banner3} onClick={this.goPartTimeMakeMoney.bind(this)} /> </SwiperItem> <SwiperItem className="order_SwiperItem"> <Image className="order_swiper_image" src={banner4} onClick={this.goAssistant.bind(this)} /> </SwiperItem> </Swiper> {/* 休息状态判断 */} {inRest ? <View className="inRest_img_wrap" onClick={this.goToPoints.bind(this)}> <Image className="inRest_img" src={inRestImg} style="pointer-events: none" /> </View> : <View className="Order_dishes_details"> {!noDishes ? packages : noDishesView} </View>} </View>; } //获取门店菜品 getPointPackage(stroeId) { let that = this; Netservice.request({ url: 'heque-eat/eat/storeEatInfo', method: 'POST', data: { stroeId: stroeId }, success: function (res) { if (res.code == '300030') { that.setState({ inRest: true }); } else { let packageList = res.data; let noDishes = false; if (packageList.length <= 0) noDishes = true; const first = packageList[0] || {}; const dishId = first.dishId || 0; const type = first.type || 0; that.setState({ packageList: packageList, noDishes: noDishes, dishId: dishId, pointType: type == 4 ? 2 : 1, inRest: false }); } }, error: function (err) {} }); } //去门店列表 goToPoints(e) { e.stopPropagation(); Taro.navigateTo({ url: "/pages/points/points?v=" + new Date().getTime() }); } //抢购按钮, 去快速支付页 goPackageBuy(item, e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId == null || userId == '') { Taro.navigateTo({ url: '/pages/login/login' }); } else { let price = item.specialOffer || item.originalPrice; let priceType = price === item.specialOffer ? 2 : 1; let storesDetails = this.state.storesDetails; let dishInfo = encodeURIComponent(JSON.stringify({ dishUrl: item.dishesUrl, dishName: item.dishName, dishPricee: price, priceType: priceType, dishId: item.dishId, eatEverydayDishesDishesId: item.eatEverydayDishesDishesId, dishesRemake: item.dishesRemake, storesDetails: storesDetails })); Taro.navigateTo({ url: '/pages/booking/booking?dishInfo=' + dishInfo + '&v=' + new Date().getTime() }); } } //联系商家 contactUs(e) { e.stopPropagation(); _makePhoneCall({ phoneNumber: String(this.state.storesDetails.storePhoneNumber) }); } //外快 goEarn(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/earn/earn?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } //周转 goLend(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/lend/lend?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } //当副班 goPartTimeMakeMoney(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/car/car?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } //招副班 goAssistant(e) { let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/assistant/assistant?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } }<file_sep>/.temp/pages/my/apply/apply.js import Nerv from "nervjs"; import './apply.css?v=20190703108'; import Taro, { showLoading as _showLoading, hideLoading as _hideLoading, showToast as _showToast, showModal as _showModal } from "@tarojs/taro-h5"; import { View, Text, Image } from '@tarojs/components'; import Netservice from "../../../netservice"; import Common from "../../../common"; import no_apply from '../../../images/my/no_apply.png'; import btn_cancel from '../../../images/my/btn_cancel.png'; export default class Apply extends Taro.Component { config = { navigationBarTitleText: '我的申请', enablePullDownRefresh: true }; state = { messages: [], pageIndex: 1, noMoreData: false }; componentWillMount() { this.getMessages(); } componentDidMount() {} componentWillUnmount() {} componentDidShow() { this._offReachBottom = Taro.onReachBottom({ callback: this.onReachBottom, ctx: this, onReachBottomDistance: undefined }); } componentDidHide() { this._offReachBottom && this._offReachBottom(); } onReachBottom() { this.getMessages(); } getMessages() { let userId = localStorage.getItem('userId'); if (!userId) return; let { messages, pageIndex, noMoreData } = this.state; if (noMoreData) return; _showLoading({ title: '努力加载中…' }); let that = this; Netservice.request({ url: 'heque-backend/collect/queryIssueList?userId=' + userId + '&pageSize=10&pageIndex=' + pageIndex, method: 'GET', success: function (res) { _hideLoading(); if (res.code !== Common.NetCode_NoError) { _showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } that.setState({ messages: messages.concat(res.data), pageIndex: pageIndex + 1 }); if (res.data.length < 10) that.setState({ noMoreData: true }); }, error: function (err) { _hideLoading(); } }); } render() { let { messages } = this.state; const messageList = messages.map((item, index) => { return <View className="apply-item" key={index} onClick={this.onTapItem.bind(this, item)}> <View className="ai-content"> <View className="ai-left"> <View className="ail-top"> <Text className="ailt-state">{this.getStateStr(item.state)}</Text> <Text className="ailt-type">{this.getTypeStr(item.type)}</Text> </View> <Text className="ail-time1">{item.updateTime || item.createTime}</Text> </View> {item.state == 0 && <View className="ai-right_wrap" onClick={this.prepareCancel.bind(this, item)}> <Image src={btn_cancel} className="ai-right_img" style="pointer-events: none" /> </View>} </View> <View className="ai-line" /> </View>; }); const noApplyView = <View className="no-apply-view"> <Image src={no_apply} className="nav-img" style="pointer-events: none" /> </View>; return <View className="container-apply"> {messages.length > 0 ? messageList : noApplyView} </View>; } //状态 0-待处理 1-处理中 2-处理完成 3-已取消 getStateStr(state) { if (state == 0) return '待处理';else if (state == 1) return '处理中';else if (state == 2) return '处理完成';else if (state == 3) return '已取消';else if (state == 4) return '处理失败';else if (state == 5) return '已关闭'; } //0-周转 1-当副班 2-招副班 3-租车 4-亚滴租车 5-曹操出行 6-首汽约车 7-精准选车 getTypeStr(type) { if (type == 0) return '周转';else if (type == 1) return '当副班';else if (type == 2) return '招副班';else if (type == 3) return '租车';else if (type == 4) return '亚滴租车';else if (type == 5) return '曹操出行';else if (type == 6) return '首汽约车';else if (type == 7) return '精准选车'; } prepareCancel(item, e) { e.stopPropagation(); let that = this; _showModal({ content: '确定取消申请?', success(res) { if (res.confirm) { that.cancelItem(item); } } }); } cancelItem(item) { if (item.state != 0) return; let userId = localStorage.getItem('userId'); if (!userId) return; _showLoading({ title: '努力加载中…' }); let that = this; let url = ''; if (item.type == 0) url = 'heque-backend/collect/changeLoanInfo';else if (item.type == 1) url = 'heque-backend/work_driver/updateWorkDriverState';else if (item.type == 2) url = 'heque-backend/employ_driver/updateEmployDriverState';else if (item.type == 3) url = 'heque-backend/collectCarInfo/handle';else if (item.type == 4) url = 'heque-backend/collectYaDiInfo/handle';else if (item.type == 5) url = 'heque-backend/collectCaoCaoInfo/handle';else if (item.type == 6) url = 'heque-backend/collectShouQiInfo/handle';else if (item.type == 7) url = 'heque-backend/collectPreciseCarInfo/handle'; Netservice.request({ url: url, method: 'POST', data: { userId: userId, id: item.relateId, state: 3 }, success: function (res) { _hideLoading(); if (res.code !== Common.NetCode_NoError) { _showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } that.setState({ messages: [], pageIndex: 1, noMoreData: false }, () => { that.getMessages(); }); }, error: function (err) { _hideLoading(); } }); } onTapItem(item, e) { Taro.navigateTo({ url: '/pages/my/apply_detail/apply_detail?type=' + item.type + '&id=' + item.relateId + '&v=' + new Date().getTime() }); } }<file_sep>/src/pages/tooltipCoupon/tooltipCoupon.js import Taro, { Component } from '@tarojs/taro' import { View, Text, Image } from '@tarojs/components' import './tooltipCoupon.css?v=20190710108' import CouponImg from '../../images/coupons/more_coupon_bg_img.png' import commonCouponImg from '../../images/coupons/common_coupon_bg_img.png' import confirmBtn from '../../images/coupons/confirm_btn.png' import fork from '../../images/coupons/coupon_fork.png' import Netservice from '../../netservice.js' //优惠券组件 export default class TooltipCoupon extends Component { state = { couponsTitle: [ { id: 1, title: '新人礼券' }, { id: 2, title: '邀请有礼' }, { id: 3, title: '下单有礼' }, ], couponState: false, //优惠券显示状态 false为不显示 receiveType: [],//券的类型 afterClose: 0, //0 不跳转 , 1跳转 faceValueThanZero: [], notScroll: 0, } componentWillMount() { let couponsData = this.props.couponsData; //获取优惠券的信息 let notScroll = this.props.notScroll; //获取优惠券的信息 let afterClose = this.props.afterClose; //用于是否返回首页的判断, 1.返回; 0.关闭当前弹框,不返回;(支付成功的时候) let userId = localStorage.getItem('userId'); if (!userId || couponsData == '' || couponsData.length <= 0) { this.setState({ couponState: false,//不显示券 }) } else { //过滤金额大于0 的券 var okCoupons = couponsData.filter(function (item) { return item.faceValue > 0; }); let showCoupon = okCoupons; //如果数据大于2, 只选前两个 if (okCoupons.length > 2) showCoupon = okCoupons.slice(0, 2); // 如果数据大于0, 显示优惠券 if (showCoupon.length > 0) { this.setState({ couponState: true,//显示券 }) } let receiveTypes = []; //获取优惠券的类型 showCoupon.map((item) => { receiveTypes.push(item.receiveType); }) this.setState({ faceValueThanZero: showCoupon, //券的数据 receiveType: receiveTypes, //券的类型 afterClose: afterClose, //跳转 notScroll: notScroll, }) let couponIds = []; couponsData.map((item) => { couponIds.push(item.id); }) let cardIdsStr = couponIds.join(','); this.amendState(cardIdsStr); } } render() { const { couponState, receiveType, couponsTitle, faceValueThanZero, notScroll } = this.state; //下单有礼,新人礼券,邀请有礼共用组件 let commonListStyle = faceValueThanZero.map((item, index) => { return <View className='coupon_content2' key={index}> <View className='coupon_content_top'> <Text className='coupon_content_money2'>{item.faceValue}元</Text> </View> <View className='coupon_content_bottom'> <View className='coupon_content_name'>禾师傅优惠券</View> <View className='coupon_content_time'>{item.receiveTime.substr(0, 10)}-{item.expireTime.substr(0, 10)}</View> </View> </View> }) //大礼包组件 let giftPacksListStyle = <View className='coupon_list'> {faceValueThanZero.map((item, index) => { return <View className='coupon_content' key={index}> <View className='coupon_content_left'> <Text className='coupon_content_money'>{item.faceValue}</Text> <Text className='coupon_content_unit'>元</Text> </View> <View className='coupon_content_right2'> <View className='coupon_content_name2'>禾师傅优惠券</View> <View className='coupon_content_time2'>{item.receiveTime.substr(0, 10)}-{item.expireTime.substr(0, 10)}</View> </View> </View> }) } </View> return ( <View> {couponState && <View className={notScroll == 1 ? 'TooltipCoupon2' : 'TooltipCoupon'}> <View className={notScroll == 1 ? 'TooltipCoupon_bg2' : 'TooltipCoupon_bg'}> <View className='CouponImg_wrap'> <View className='CouponImg_wrap_content' onClick={this.closeTooltip.bind(this)}> {faceValueThanZero.length >= 2 ? <Image src={CouponImg} className='CouponImg' style='pointer-events: none' /> : <Image src={commonCouponImg} className='CouponImg' style='pointer-events: none' /> } <View className='confirm' onClick={this.closeTooltip.bind(this)}> <Image src={confirmBtn} className='confirmBtn' style='pointer-events: none' /> </View> {couponsTitle.map((item, index) => { return <View className='coupon_title' key={index}> {faceValueThanZero.length >= 2 ? <Text>恭喜获得大礼包</Text> : <Text>{item.id === receiveType[0] ? <Text>{item.title}</Text> : ''}</Text> } </View> }) } {faceValueThanZero.length >= 2 ? giftPacksListStyle : commonListStyle} <View onClick={this.closeTooltip.bind(this)} className='fork_btn'> <Image src={fork} className='coupon_fork_img' style='pointer-events: none' /> </View> </View> </View> </View> </View> } </View> ) } //点击关闭和知道了按钮的事件 closeTooltip(e) { // 阻止默认事件 e.stopPropagation(); this.setState({ couponState: false }) if (this.state.afterClose == 1) Taro.navigateBack(); if (this.props.onCloseCouponView) this.props.onCloseCouponView(); } //修改优惠券为已读 amendState(cardIdsStr) { Netservice.request({ url: 'heque-coupon/discount_coupon/user_has_read', method: 'GET', data: { userCardMedalId: cardIdsStr }, success: (res) => { } }) } } <file_sep>/src/pages/my/apply/apply.js import './apply.css?v=20190703108'; import Taro, { Component } from '@tarojs/taro'; import { View, Text, Image } from '@tarojs/components'; import Netservice from '../../../netservice.js'; import Common from '../../../common.js'; import { setGlobalData, getGlobalData } from '../../../utils/global_data' import no_apply from '../../../images/my/no_apply.png' import btn_cancel from '../../../images/my/btn_cancel.png' export default class Apply extends Component { config = { navigationBarTitleText: '我的申请', enablePullDownRefresh: true, } state = { messages: [], pageIndex: 1, noMoreData: false, } componentWillMount() { this.getMessages(); } componentDidMount() { } componentWillUnmount() { } componentDidShow() { } componentDidHide() { } onReachBottom() { this.getMessages(); } getMessages() { let userId = localStorage.getItem('userId'); if (!userId) return; let { messages, pageIndex, noMoreData } = this.state; if (noMoreData) return; Taro.showLoading({ title: '努力加载中…' }); let that = this; Netservice.request({ url: 'heque-backend/collect/queryIssueList', method: 'GET', data:{ userId, pageSize:10, pageIndex }, success: function (res) { Taro.hideLoading(); if (res.code !== Common.NetCode_NoError) { Taro.showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } that.setState({ messages: messages.concat(res.data), pageIndex: pageIndex + 1 }); if (res.data.length < 10) that.setState({ noMoreData: true }); }, error: function (err) { Taro.hideLoading(); } }) } render() { let { messages } = this.state; const messageList = messages.map((item, index) => { return <View className='apply-item' key={index} onClick={this.onTapItem.bind(this, item)}> <View className='ai-content'> <View className='ai-left'> <View className='ail-top'> <Text className='ailt-state'>{this.getStateStr(item.state)}</Text> <Text className='ailt-type'>{this.getTypeStr(item.type)}</Text> </View> <Text className='ail-time1'>{item.updateTime || item.createTime}</Text> </View> {item.state == 0 && <View className='ai-right_wrap' onClick={this.prepareCancel.bind(this, item)}> <Image src={btn_cancel} className='ai-right_img' style='pointer-events: none' /> </View> } </View> <View className='ai-line' /> </View> }) const noApplyView = <View className='no-apply-view'> <Image src={no_apply} className='nav-img' style='pointer-events: none' /> </View> return ( <View className='container-apply'> {messages.length > 0 ? messageList : noApplyView} </View> ) } //状态 0-待处理 1-处理中 2-处理完成 3-已取消 getStateStr(state) { if (state == 0) return '待处理'; else if (state == 1) return '处理中'; else if (state == 2) return '处理完成'; else if (state == 3) return '已取消'; else if (state == 4) return '处理失败'; else if (state == 5) return '已关闭'; } //0-周转 1-当副班 2-招副班 3-租车 4-亚滴租车 5-曹操出行 6-首汽约车 7-精准选车 getTypeStr(type) { if (type == 0) return '周转'; else if (type == 1) return '当副班'; else if (type == 2) return '招副班'; else if (type == 3) return '租车'; else if (type == 4) return '亚滴租车'; else if (type == 5) return '曹操出行'; else if (type == 6) return '首汽约车'; else if (type == 7) return '精准选车'; } prepareCancel(item, e) { e.stopPropagation(); let that = this; Taro.showModal({ content: '确定取消申请?', success(res) { if (res.confirm) { that.cancelItem(item) } } }) } cancelItem(item) { if (item.state != 0) return; let userId = localStorage.getItem('userId'); if (!userId) return; Taro.showLoading({ title: '努力加载中…' }); let that = this; let url = ''; if (item.type == 0) url = 'heque-backend/collect/changeLoanInfo'; else if (item.type == 1) url = 'heque-backend/work_driver/updateWorkDriverState'; else if (item.type == 2) url = 'heque-backend/employ_driver/updateEmployDriverState'; else if (item.type == 3) url = 'heque-backend/collectCarInfo/handle'; else if (item.type == 4) url = 'heque-backend/collectYaDiInfo/handle'; else if (item.type == 5) url = 'heque-backend/collectCaoCaoInfo/handle'; else if (item.type == 6) url = 'heque-backend/collectShouQiInfo/handle'; else if (item.type == 7) url = 'heque-backend/collectPreciseCarInfo/handle'; Netservice.request({ url: url, method: 'POST', data: { userId: userId, id: item.relateId, state: 3 }, success: function (res) { Taro.hideLoading(); if (res.code !== Common.NetCode_NoError) { Taro.showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } that.setState({ messages: [], pageIndex: 1, noMoreData: false, }, () => { that.getMessages() }); }, error: function (err) { Taro.hideLoading(); } }) } onTapItem(item, e) { Taro.navigateTo({ url: '/pages/my/apply_detail/apply_detail?type=' + item.type + '&id=' + item.relateId + '&v=' + new Date().getTime() }) } }<file_sep>/src/utils/payment.js import Taro from '@tarojs/taro'; import Netservice from '../netservice.js'; import { setGlobalData, } from '../utils/global_data.js' import JSWX from '../libs/jweixin-1.4.0.js' import Common from '../common.js' //微信支付 export function payment(userCardMedalId, orderId, price, openId, successCallBack, cancelBack, failCallBack) { // export function payment( userCardMedalId, orderId, price, openId ) { let that = this; Netservice.request({ url: 'heque-eat/wechat_pay/hsf_user_payment', method: 'POST', data: { ...userCardMedalId, id: orderId, paymentPrice: price, channel: 'h5', openId: openId, }, success: function (res) { Taro.hideLoading(); setGlobalData('currentCoupon', {}); if (res.code !== Common.NetCode_NoError) { Taro.showToast({ title: res.message, icon: 'none', duration: 2000 }); Taro.navigateTo({ url: '/pages/my/order_history/the_order_details/the_order_details?orderId=' + orderId + '&v=' + new Date().getTime() }) return; }; let params = res.data; JSWX.chooseWXPay({ timestamp: params.timeStamp, nonceStr: params.nonceStr, package: params.package, signType: params.signType, paySign: params.sign, // // 支付成功后的回调函数 success(res1) { //支付成功 if (successCallBack) successCallBack(); }, cancel(res2) { //取消支付 if (cancelBack) cancelBack(); }, fail(res3) { //支付失败 if (failCallBack) failCallBack(); } }); }, error:(err)=> { Taro.hideLoading(); //支付失败 if (failCallBack) failCallBack(); } }) } //0元支付 export function zeroPayment(userCardMedalId, price, orderId) { let that = this; Netservice.request({ url: 'heque-eat/wechat_pay/zero_element_pay', method: 'POST', data: { ...userCardMedalId, id: orderId, paymentPrice: price, channel: 'h5', }, success: function (res) { Taro.hideLoading(); if (res.code !== Common.NetCode_NoError) { Taro.showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } setGlobalData('currentCoupon', {}); Taro.navigateTo({ url: '/pages/my/order_history/the_order_details/the_order_details?orderId=' + orderId + '&v=' + new Date().getTime() }) }, fail: function (err) { Taro.hideLoading(); setGlobalData('currentCoupon', {}); Taro.showToast({ title: '支付失败', icon: 'none', duration: 2000 }); Taro.navigateTo({ url: '/pages/my/order_history/the_order_details/the_order_details?orderId=' + orderId + '&v=' + new Date().getTime() }) } }) } <file_sep>/.temp/pages/wish/wish.js import Nerv from "nervjs"; import './wish.css?v=20190717110'; import Taro, { getSystemInfo as _getSystemInfo } from "@tarojs/taro-h5"; import { View, Text, Swiper, SwiperItem, Image } from '@tarojs/components'; import Netservice from "../../netservice"; import Common from "../../common"; import banner1 from '../../images/wish/banner_index01.png'; import banner2 from '../../images/wish/banner_index02.png'; import banner3 from '../../images/wish/banner_index03.png'; import banner4 from '../../images/wish/banner_index04.png'; import icon_wish1 from '../../images/wish/icon_wish1.png'; import icon_wish2 from '../../images/wish/icon_wish2.png'; import icon_wish3 from '../../images/wish/icon_wish3.png'; import icon_wish4 from '../../images/wish/icon_wish4.png'; import icon_message from '../../images/wish/icon_message.png'; export default class Wish extends Taro.Component { config = { navigationBarTitleText: '赚钱' }; state = { messages: [], //消息 system: 'ios' }; componentWillMount() { _getSystemInfo({ success: res => { this.setState({ system: res.system }); } }); } componentDidMount() {} componentDidShow() { this.getMessages(); } componentDidHide() {} getMessages() { let userId = localStorage.getItem('userId'); if (!userId) return; let that = this; Netservice.request({ url: 'heque-backend/collect/queryRecentlyMessage?userId=' + userId, method: 'GET', success: res => { if (res.code == Common.NetCode_NoError) that.setState({ messages: res.data }); } }); } render() { let { messages, system } = this.state; return <View className="container-wish"> <Swiper className="wish-swiper" autoplay interval={3000} circular> <SwiperItem> <Image className="ws_image" src={banner1} onClick={this.goAssistant.bind(this)} /> </SwiperItem> <SwiperItem> <Image className="ws_image" src={banner2} onClick={this.goPartTimeMakeMoney.bind(this)} /> </SwiperItem> <SwiperItem> <Image className="ws_image" src={banner3} onClick={this.goLend.bind(this)} /> </SwiperItem> <SwiperItem> <Image className="ws_image" src={banner4} onClick={this.goEarn.bind(this)} /> </SwiperItem> </Swiper> <Text className="wish-title">快捷服务</Text> <View className="wish_content"> <Image className="wc_image" src={icon_wish1} onClick={this.toAssistantPage.bind(this)} /> <Image className="wc_image" src={icon_wish2} onClick={this.toCarPage.bind(this)} /> </View> <View className="wish_content"> <Image className="wc_image" src={icon_wish3} onClick={this.goToGetMoney.bind(this)} /> <Image className="wc_image" src={icon_wish4} onClick={this.goToEarnMoney.bind(this)} /> </View> <View className="wish_msg_content"> <Image className="wmc_icon" src={icon_message} /> <Text className="wmc_text">{(messages[0] || {}).showText || '暂无消息'}</Text> <Text className="wmc_line" /> <Text className="wmc_more" onClick={this.goToMessageCenter.bind(this)}>查看</Text> </View> <View className="wish_msg_gap" /> {/* {(system.startsWith('iOS') || system.startsWith('ios')) && <View className='wish_msg_gap' />} */} </View>; } //到找车当副班页 toCarPage(e) { let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/car/car?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } //到找副班页 toAssistantPage(e) { let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/assistant/assistant?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } goToMessageCenter(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) Taro.navigateTo({ url: "/pages/wish/messages/messages?v=" + new Date().getTime() });else Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } goToGetMoney(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) Taro.navigateTo({ url: "/pages/wish/lend/lend?v=" + new Date().getTime() });else Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } goToEarnMoney(e) { e.stopPropagation(); const userId = localStorage.getItem('userId'); if (userId) Taro.navigateTo({ url: "/pages/wish/earn/earn?v=" + new Date().getTime() });else Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } //外快 goEarn(e) { e.stopPropagation(); const userId = localStorage.getItem('userId'); if (userId) Taro.navigateTo({ url: "/pages/wish/earn/earn?v=" + new Date().getTime() });else Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } //周转 goLend(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/lend/lend?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } //当副班 goPartTimeMakeMoney(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/car/car?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } //招副班 goAssistant(e) { let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/assistant/assistant?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } }<file_sep>/src/pages/wish/assistant/assistant.js import Taro, { Component } from '@tarojs/taro' import { View, Text, Image, Picker, Swiper, SwiperItem, Input } from '@tarojs/components' import { AtCheckbox } from 'taro-ui' import './assistant.css' import Netservice from '../../../netservice.js' import { setGlobalData, getGlobalData } from '../../../utils/global_data' import arrow_right from '../../../images/common/arrow_right.png' import icon_select from '../../../images/wish/radio_select.png' import icon_notselect from '../../../images/take/icon_notselect.png' import assistant_title1 from '../../../images/wish/assistant/assistant_title1.png' import tick_sheet from '../../../images/wish/car/tick_sheet.png' import btn_next from '../../../images/wish/car/btn_next.png' import checkbox_normal from '../../../images/wish/checkbox_normal.png' import checkbox_select from '../../../images/wish/checkbox_select.png' import banner_rent from '../../../images/wish/car/banner_rent.png' import default_btn_next from '../../../images/wish/car/default_btn_next.png' export default class Assistant extends Component { config = { 'navigationBarTitleText': '招副班' } state = { workTimeType: 0, //副班的时间段类型 默认为0:不选, 1: 白班 2:夜班 3.都可以 provinceAndCity: '请选择省市', //省市默认值 multiSelector: [], //显示的省市数据 checkboxOption: [], //区县 数据 checkedList: ['请选择区域'], showDistrictList: false, // true显示区县 checkAll: false, //显示区县时的全选功能 driveAge: '请选择驾龄', //驾龄 driveAgeValue: ['不限', '1年', '2年', '3年', '3年以上'], supplementaryTerms: [], //补充条件 showDIYSupplementaryTerms: false, //显示补充条件的输入框 checked1: 0, checked2: 0, checked3: 0, provinceData: [], //请求的省市列表 cityId: '', //城市id updateList: false, //是否切换了城市 districtData: [], //选中的区县的列表 checkedDistrictId: [], //选中的区域id checkedListWrap: [], //缓存的区域的数据 //确定时。显示的数据 driveAgeType: 0, //对驾龄要求 0-不限 1-1年 2-2年 3-3年 4-三年以上 provinceData2: [], //老乡籍贯 provinceAndCity2: '请选择籍贯', //老乡籍贯 provinceDataId: 1, //省的id cityName: '', //城市的名字 determinedName: '',//省的名字 initializeDate: [], //省市的初始化数据 showHighLight: false //按钮高亮 } componentWillMount() { } componentDidMount() { let provinceName = []; let cityName = []; let that = this; Netservice.request({ url: 'heque-backend/work_driver/getProvinceAndCityList', method: 'GET', data:{}, success: res => { let data = res.data; data.map(item => { provinceName.push(item.privinceName) }) cityName.push(data[0].cityList[0].cityName) that.setState({ provinceData: data, multiSelector: [provinceName, cityName], initializeDate: [provinceName, cityName], provinceData2: provinceName }) } }) } render() { const { workTimeType, provinceAndCity, showDistrictList, checkboxOption, checkedList, checkAll, driveAge, showDIYSupplementaryTerms, checked1, checked2, checked3, provinceData2, provinceAndCity2, showHighLight } = this.state; //选择区域的组件 let districtComponent = <View className='checkboxOption_wrap'> <View className='checkboxOption_content'> <View className='checkboxOption_Operating_box'> <Text onClick={this.deselectDistrict.bind(this)}>取消</Text> <Text>请选择区域</Text> <Text onClick={this.confirmDistrict.bind(this)}>确认</Text> </View> <View className='checkboxOption_check_all_wrap' onClick={this.checkAllBtn.bind(this)}> {checkAll ? <View className='check_all_img'> <Image src={checkbox_select} className='check_all_img_tick_sheet' style='pointer-events: none' /> </View> : <View className='check_all_img2'> </View>} <Text>全选</Text> </View> <AtCheckbox options={checkboxOption} selectedList={this.state.checkedList} onChange={this.handleChange.bind(this)} /> </View> </View> return ( <View className='Assistant'> <Swiper className='Assistant_swiper' circular autoplay={false} interval={3000} style='width:84%'> <SwiperItem className='Assistant_SwiperItem' style='width:100%'> <Image className='Assistant_swiper_image' src={banner_rent} style='pointer-events: none; width:100%' /> </SwiperItem> {/* <SwiperItem className='pt2_SwiperItem' onClick={this.inviteFriends.bind(this)} > <Image className='pt2_swiper_image' src={banner2} onClick={this.inviteFriends.bind(this)} /> </SwiperItem> <SwiperItem className='pt2_SwiperItem' onClick={this.summerTopic.bind(this)}> <Image className='pt2_swiper_image' src={banner3} onClick={this.summerTopic.bind(this)} /> </SwiperItem>*/} </Swiper> <Image src={assistant_title1} className='Assistant_need_img' style='pointer-events: none' /> <View className='Assistant_need_wrap'> <View> <View className='Assistant_type_title'>副班代班时间</View> <View className='Assistant_time_type_wrap'> <View className='Assistant_time_type' onClick={() => this.switchoverTime(1)}> <Image src={workTimeType == 1 ? icon_select : icon_notselect} className='Assistant_icon_notselect_img' style='pointer-events: none' /> <Text>白班</Text> </View> <View className='Assistant_time_type' onClick={() => this.switchoverTime(2)} > <Image src={workTimeType == 2 ? icon_select : icon_notselect} className='Assistant_icon_notselect_img' style='pointer-events: none' /> <Text>晚班</Text> </View> <View className='Assistant_time_type' onClick={() => this.switchoverTime(3)} > <Image src={workTimeType == 3 ? icon_select : icon_notselect} className='Assistant_icon_notselect_img' style='pointer-events: none' /> <Text>都可以</Text> </View> </View> </View> <View> <View className='Assistant_type_title padding_30'>接受哪几个区域交车</View> <Picker mode='multiSelector' range={this.state.multiSelector} onChange={this.onChange} onColumnChange={this.onColumnChange.bind(this)} onCancel={this.onCancel.bind(this)}> <View className={provinceAndCity.indexOf('请选择省市') == 0 ? 'Assistant_time_type3' : 'Assistant_time_type2'}> <Text>{provinceAndCity}</Text> <Image src={arrow_right} className='Assistant_arrow_right_img' style='pointer-events: none' /> </View> </Picker> </View> <View className={checkedList.indexOf('请选择区域') == 0 ? 'Assistant_time_type3' : 'Assistant_time_type2'} onClick={this.selectRegion.bind(this)}> <View className='Assistant_District'> {checkedList.map((item, index) => { return <Text key={index} className={item.indexOf('请选择区域') == 0 ? 'Assistant_District_details2' : 'Assistant_District_details'}>{item}</Text> }) } </View> <Image src={arrow_right} className='Assistant_arrow_right_img' style='pointer-events: none' /> </View> <View> <View className='Assistant_type_title padding_30' >副班驾龄要求</View> <Picker mode='driveAgeValue' range={this.state.driveAgeValue} onChange={this.setChange} className='Assistant_driveAge_wrap'> <View className={driveAge.indexOf('请选择驾龄') == 0 ? 'Assistant_driveAge2' : 'Assistant_driveAge'}> <Text>{driveAge}</Text> <Image src={arrow_right} className='Assistant_arrow_right_img' style='pointer-events: none' /> </View> </Picker> </View> <View className='Assistant_supplement_title'>补充其他要求(可不选)</View> <View className='Assistant_supplement_type_wrap'> <View className='Assistant_supplement_type' onClick={() => this.setSupplementaryTerms(1)}> <Image src={checked1 ? checkbox_select : checkbox_normal} className='Assistant_supplement_type_icon' style='pointer-events: none' /> <Text className='Assistant_supplement_type_name'>三证齐全</Text> </View> <View className='Assistant_supplement_type' onClick={() => this.setSupplementaryTerms(2)}> <Image src={checked2 ? checkbox_select : checkbox_normal} className='Assistant_supplement_type_icon' style='pointer-events: none' /> <Text className='Assistant_supplement_type_name' >低于50岁</Text> </View> <View className='Assistant_supplement_type' onClick={() => this.setSupplementaryTerms(3)}> <Image src={checked3 ? checkbox_select : checkbox_normal} className='Assistant_supplement_type_icon' style='pointer-events: none' /> <Text className='Assistant_supplement_type_name'>老乡</Text> </View> </View> {showDIYSupplementaryTerms && <Picker mode='provinceData2' range={provinceData2} onChange={this.onChange2}> <View className={provinceAndCity2 == '请选择籍贯' ? 'Assistant_time_type3' : 'Assistant_time_type2'}> <Text>{provinceAndCity2}</Text> </View> </Picker>} </View> <View className='default_btn_next' onClick={this.nextStepBtn.bind(this)}> <Image src={showHighLight ? btn_next : default_btn_next} className='default_btn_next_img' style='pointer-events: none' /> </View> {showDistrictList && districtComponent} </View> ) } //切换副班代班时间类型 switchoverTime(type) { this.setState({ workTimeType: type, }) setTimeout(() => { this.showHighLight(); }, 20) } //取消选择省市时 onCancel(e) { let multiSelector1 = this.state.multiSelector[0]; this.setState({ multiSelector: [multiSelector1, this.state.initializeDate[1]] }) } //修改省市值 onChange = e => { let provinceData = this.state.provinceData; let multiSelector1 = this.state.multiSelector[0]; let determinedValue1 = multiSelector1[e.detail.value[0]]; let multiSelector2 = this.state.multiSelector[1]; let determinedValue2 = multiSelector2[e.detail.value[1]]; let city = {}; provinceData.map((item) => { item.cityList.map(item2 => { if (item2.cityName == determinedValue2) { city = item2 } }) }) this.setState({ provinceAndCity: determinedValue1 + ' - ' + city.cityName, cityId: city.id, updateList: true, checkedList: ['请选择区域'], cityName: city.cityName, checkAll: false, determinedName: determinedValue1, multiSelector: [multiSelector1, this.state.initializeDate[1]] }) this.state.checkedDistrictId.length = 0; this.state.checkedListWrap.length = 0; setTimeout(() => { this.showHighLight(); }, 20) } //修改老乡籍贯 onChange2 = e => { let { provinceData2 } = this.state; if (typeof e.detail.value == 'number') { this.setState({ provinceAndCity2: provinceData2[e.detail.value], }) } if (typeof e.detail.value == 'object') { this.setState({ provinceAndCity2: provinceData2[e.detail.value[0]], }) } } //选择省市是触发的函数 onColumnChange(e) { let i = e.detail.value; let provinceData = this.state.provinceData; let multiSelector = this.state.multiSelector; let cityList = provinceData[i].cityList.map(item => { return item.cityName }) if (e.detail.column == 1) { } else { this.setState({ provinceDataId: provinceData[i].id }) multiSelector.splice(1, 1, cityList) } } //显示选择区域组件 selectRegion(e) { e.stopPropagation(); //未选择省市提示 if (this.state.provinceAndCity.indexOf('请选择省市') == 0) { Taro.showToast({ title: '请先选择省市', icon: 'none', duration: 2000, }) return } let cityId = this.state.cityId; let checkboxOption = this.state.checkboxOption; //当显示区域为默认值时,清空默认值 if (this.state.checkedList[0].indexOf('请选择区域') == 0) { this.setState({ checkedList: [] }) } //更改城市时,请求数据 if (this.state.updateList) { //清空上一个请求的数据 checkboxOption.length = 0; Netservice.request({ url: 'heque-backend/work_driver/getAreaList', method: 'GET', data: { id: cityId, }, success: res => { let district = res.data; district.map(item => { checkboxOption.push({ value: item.areaName, label: item.areaName }) }) if (checkboxOption) { this.setState({ showDistrictList: true, updateList: false, districtData: district, }) } } }) } if (checkboxOption) { this.setState({ showDistrictList: true, updateList: false }) } } //选择的地区 handleChange(value) { let { checkboxOption, checkedDistrictId } = this.state; //全选按钮样式 if (value.length !== checkboxOption.length) { this.setState({ checkAll: false, }) } else { this.setState({ checkAll: true, }) } this.setState({ checkedList: value }) } //选择区县的确定按钮 confirmDistrict(e) { e.stopPropagation(); let { checkedList, districtData, checkedDistrictId } = this.state; checkedDistrictId.length = 0; checkedList.map(item => { districtData.map(item2 => { if (item2.areaName.indexOf(item) == 0) { checkedDistrictId.push(item2.id); checkedDistrictId.join(',') } }) }) if (checkedList.length == 0) { this.setState({ checkedList: ['请选择区域'], showDistrictList: false, checkedListWrap: [], }) } else { this.setState({ checkedListWrap: checkedList, showDistrictList: false }) } setTimeout(() => { this.showHighLight(); }, 20) } //选择区县的取消按钮 deselectDistrict(e) { e.stopPropagation(); let { checkedListWrap, checkedList, checkboxOption } = this.state; if (checkedList.length == 0 && checkedListWrap.length == 0) { this.setState({ showDistrictList: false, checkedList: ['请选择区域'] }) } if (checkedList.length !== 0 && checkedListWrap.length == 0) { this.setState({ showDistrictList: false, checkedList: ['请选择区域'], checkAll: false, }) } if (checkedList.length == 0 && checkedListWrap.length > 0) { this.setState({ showDistrictList: false, checkedList: checkedListWrap }) } if (checkedList.length > 0 && checkedListWrap.length > 0) { this.setState({ showDistrictList: false, checkedList: checkedListWrap }) } if (checkedListWrap.length == checkboxOption.length) { this.setState({ checkAll: true }) } else { this.setState({ checkAll: false }) } } //是否全选功能 checkAllBtn(e) { e.stopPropagation(); let { checkAll, checkboxOption } = this.state; if (checkAll) { this.setState({ checkAll: false, checkedList: [], }) } else { let label = checkboxOption.map((item) => { return item.label }) this.setState({ checkAll: true, checkedList: label, }) } } //修改驾龄 setChange = e => { let driveAgeValue = this.state.driveAgeValue; if (typeof e.detail.value == 'number') { this.setState({ driveAge: driveAgeValue[e.detail.value], driveAgeType: e.detail.value }) } if (typeof e.detail.value == 'object') { this.setState({ driveAge: driveAgeValue[e.detail.value[0]], driveAgeType: e.detail.value[0] }) } setTimeout(() => { this.showHighLight(); }, 20) } //选择补充条件 setSupplementaryTerms(type) { let { supplementaryTerms } = this.state; //查找数组里有没有相同的值 if (supplementaryTerms.includes(type) == true) { //获取相同值的下标 let num = supplementaryTerms.indexOf(type); //删除相同值 supplementaryTerms.splice(num, 1); //是否选了老乡 let aa = supplementaryTerms.indexOf(3); //没选老乡,不显示自定义的补充内容 if (aa == -1) { this.setState({ showDIYSupplementaryTerms: false, }) } else { this.setState({ showDIYSupplementaryTerms: true, }) } if (type == 1) this.setState({ checked1: 0 }) if (type == 2) this.setState({ checked2: 0 }) if (type == 3) this.setState({ checked3: 0, provinceAndCity2: '请选择籍贯', }) } else { supplementaryTerms.push(type); if (supplementaryTerms.includes(3) == true) { this.setState({ showDIYSupplementaryTerms: true, }) } else { this.setState({ showDIYSupplementaryTerms: false, }) } if (type == 1) this.setState({ checked1: 1 }) if (type == 2) this.setState({ checked2: 1 }) if (type == 3) this.setState({ checked3: 1 }) } } //必填项已选择,下一步按钮显示高亮 showHighLight() { let { workTimeType, checkedDistrictId, determinedName, driveAge } = this.state; if (workTimeType == 0 || checkedDistrictId.length == 0 || determinedName == '' || driveAge == '请选择驾龄') { this.setState({ showHighLight: false }) } else { this.setState({ showHighLight: true }) } } //下一步按钮 nextStepBtn(e) { e.stopPropagation(); let { workTimeType, provinceAndCity, checkedList, driveAge, provinceDataId, determinedName, showHighLight, checkedDistrictId, cityName, driveAgeType, provinceAndCity2, checked1, checked2, checked3, cityId } = this.state; if (workTimeType == 0) { Taro.showToast({ title: '请选择副班代班时间', icon: 'none', duration: 1500, }) return } if (provinceAndCity == '请选择省市') { Taro.showToast({ title: '请选择省市', icon: 'none', duration: 1500, }) return } if (checkedList[0].indexOf('请选择区域') == 0) { Taro.showToast({ title: '请选择区域', icon: 'none', duration: 1500, }) return } if (driveAge == '请选择驾龄') { Taro.showToast({ title: '请选择驾龄', icon: 'none', duration: 1500, }) return } if (checked3 == 1 && provinceAndCity2 == '请选择籍贯') { Taro.showToast({ title: '请选择籍贯', icon: 'none', duration: 1500, }) return } //按扭置灰时 if (!showHighLight) { return } //驾龄 let nativePlace = provinceAndCity2 == '请选择籍贯' ? '' : provinceAndCity2; setGlobalData('type', workTimeType) setGlobalData('pId', provinceDataId) setGlobalData('cId', cityId) setGlobalData('provinceName', determinedName) setGlobalData('cityName', cityName) setGlobalData('driverTime', driveAgeType) setGlobalData('threeCertificateReady', checked1) setGlobalData('lessFifty', checked2) setGlobalData('sameProvince', checked3) setGlobalData('nativeName', nativePlace) setGlobalData('areaIds', checkedDistrictId) setGlobalData('areasName', checkedList) Taro.navigateTo({ url: '/pages/wish/assistant/assistantDetails/assistantDetails' }) } }<file_sep>/src/pages/login/login.js import './login.css?v=20190712108'; import Taro, { Component } from '@tarojs/taro'; import { View, Text, Input, Image } from '@tarojs/components'; import defaultLoginBtn from '../../images/common/login_btn2.png'; import loginBtn from '../../images/common/login_btn1.png'; import Netservice from '../../netservice.js?v=20190624108'; import Common from '../../common.js' import TooltipCoupon from '../tooltipCoupon/tooltipCoupon.js?v=201906191108' export default class Login extends Component { config = { navigationBarTitleText: '登录', } constructor() { super(); this.isCodeClickable = true; //验证码防止连续点击 this.isLoginClickable = true; //登录按钮防止连续点击 } state = { hintStyle: true, //提示样式 hintText: '', //提示词 securityCodeStyle: 2, //验证码样式,1 第一次输入达11位 2 倒计时中 3 重发验证码 phoneValue: '', //手机号码 loginStyle: false, //登录按钮样式, 是否可点击 importSecurityCode: '', //输入的验证码 number: 60, //倒计时 btnText: '发送验证码', //验证码按钮文本 disablCodeBtn: false, //禁用验证码按钮 disablLoginBtn: true, //禁用登录按钮 couponStateStyle: false, //为true时显示优惠券弹框 couponsData: [], //传到优惠券组件的数据 } componentWillMount() { } componentDidMount() { } componentWillUpdate() { } componentDidUpdate() { } componentWillUnmount() { } componentDidShow() { } componentDidHide() { } render() { const { phoneValue, securityCodeStyle, importSecurityCode, loginStyle, hintStyle, hintText, btnText, disablCodeBtn, disablLoginBtn, couponStateStyle, couponsData } = this.state; return ( <View className='login'> <View className='contentTitle'> <View>欢迎来到禾师傅</View> <View className='login_font_26'>绑定手机会让您的账户更加安全</View> </View> <View className='input_wrap'> <Input value={phoneValue} placeholder='请输入手机号码' className='phoneInput' onInput={this.onPhoneChange.bind(this)} maxLength='11' type='number' /> <View className='securityCode'> <Input value={importSecurityCode} type='number' maxLength='6' placeholder='请输入验证码' className='input_securityCode' onInput={this.onCodeChange.bind(this)} /> <View className={securityCodeStyle == 1 ? 'login_placeholder' : 'login_placeholder2'}></View> {securityCodeStyle === 1 && <View className='securityCode_btn1' onClick={disablCodeBtn && this.getRegular.bind(this)} >{btnText}</View>} {securityCodeStyle === 2 && <View className='securityCode_btn2' >{btnText}</View>} {securityCodeStyle === 3 && <View className='securityCode_btn3' onClick={disablCodeBtn && this.getRegular.bind(this)} >{btnText}</View>} </View> {hintStyle === false ? <Text className='hint'>{hintText}</Text> : <Text className='hint2'></Text>} </View> <View className="login_btn1" onClick={!disablLoginBtn && this.goLogin.bind(this)}> <Image src={!loginStyle ? defaultLoginBtn : loginBtn} className='login_btn_img' style='pointer-events: none' /> </View> {couponStateStyle && <TooltipCoupon couponsData={couponsData} afterClose={1} notScroll={0} />} </View> ) } //手机号 onPhoneChange(phoneValue) { let value = phoneValue.detail.value; let number = value.replace(/\s/g, " "); this.setState({ phoneValue: number }) // let numRegular =/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]|19[0-9]|16[0-9])[0-9]{8}$/; // if(number.length >= 11 && numRegular.test(number)){ if (number.length >= 11) { this.setState({ securityCodeStyle: 1, disablCodeBtn: true, hintStyle: true, disablLoginBtn: false, }) } else { this.setState({ securityCodeStyle: 2, disablCodeBtn: false, hintStyle: false, disablLoginBtn: true, hintText: '请输入正确的手机号码' }) } } //获取验证码 getRegular(e) { let that = this; if (!this.isCodeClickable) return; this.isCodeClickable = false; setTimeout(() => { this.isCodeClickable = true; }, 2000) if (this.state.securityCodeStyle === 2) { return } else { Netservice.request({ url: 'heque-user/userSms/getUserSmsCode', method: 'GET', data: { phoneNo: this.state.phoneValue, //手机号 smsType: 4, //代表用户登录验证码 }, success: (res) => { if (res.code !== Common.NetCode_NoError) { Taro.showToast({ title: res.message, icon: 'none', duration: 3000 }) } else { that.setState({ btnText: '重发验证码(60s)', disablCodeBtn: false, securityCodeStyle: 2, }) that.setReciprocal(that); } } }) } } //倒计时 setReciprocal(that) { let number = that.state.number; let time = setInterval(() => { number--; this.setState({ btnText: '重发验证码(' + number + 's)', disablCodeBtn: false, securityCodeStyle: 2, }) if (this.state.phoneValue === '' || this.state.phoneValue === null) { this.setState({ number: 60, btnText: '发送验证码', disablCodeBtn: false, securityCodeStyle: 2 }) clearInterval(time); } else if (number === 0) { this.setState({ number: 60, btnText: '重发验证码', disablCodeBtn: true, securityCodeStyle: 3 }) clearInterval(time); } else { this.setState({ btnText: '重发验证码(' + number + 's)', disablCodeBtn: false, securityCodeStyle: 2 }) } }, 1000) } //输入验证码 onCodeChange(importSecurityCode) { let Code = importSecurityCode.detail.value; this.setState({ importSecurityCode: Code, }) if (Code.length >= 6 && this.state.phoneValue.length !== 0) { this.setState({ loginStyle: true, disablLoginBtn: false, }) } else { this.setState({ loginStyle: false, disablLoginBtn: true, }) } } //登录 goLogin(e) { let that = this; let phoneValue = that.state.phoneValue; let Code = that.state.importSecurityCode; let openId = localStorage.getItem('openId') || ''; if (!this.isLoginClickable) return; this.isLoginClickable = false; setTimeout(() => { this.isLoginClickable = true }, 3000); if (phoneValue !== '' && Code !== '') { Netservice.request({ url: 'heque-user/user/reg_or_login', method: 'POST', data: { phoneNo: phoneValue, userType: 1, smsCode: Code, loginType: 1, weChatPublicNumberOpenId: openId, }, success: (res) => { if (res.code === Common.NetCode_NoError) { let userId = res.data.iid; let token = res.data.token; let businessType = res.data.businessType; localStorage.setItem('userId', userId); localStorage.setItem('token', token); localStorage.setItem('phone', phoneValue); if (res.data && res.data.weChatPublicNumberOpenId && res.data.weChatPublicNumberOpenId.length > 10) { localStorage.setItem('openId', res.data.weChatPublicNumberOpenId); } //如果没选司机类型,就去选择司机类型 if (businessType === '' || businessType === undefined) { Taro.redirectTo({ url: '/pages/my/choice_motorman_type/choice_motorman_type?v=' + new Date().getTime(), }) } else { //调用查优惠券的函数 that.getCouponsMessage(userId); } } else { Taro.showToast({ title: res.message, icon: 'none', duration: 3000 }) } }, }) } } //查优惠券 getCouponsMessage(userId) { let that = this; if (userId === null || userId === undefined) { return } else { Netservice.request({ 'url': 'heque-coupon/discount_coupon/get_not_read', method: 'GET', data: { userId: userId, }, success: (res) => { let results = res.data; let coupons = results.filter(function (ele) { return ele.faceValue > 0 }); if (coupons.length === 0 || coupons === '') { that.setState({ couponStateStyle: false, }) //返回 Taro.navigateBack(); } else { that.setState({ couponStateStyle: true, couponsData: coupons, }) } } }) } } }<file_sep>/src/netservice.js import Taro from '@tarojs/taro' export default class NetService { // static pre_url = 'http://192.168.10.200:8763/'; static pre_url = 'http://192.168.3.11:8763/'; // static pre_url = 'http://47.112.107.116:8763/'; // static pre_url = 'https://api.hequecheguanjia.com/'; /* 发起网络请求,调用后端接口 调用样例 request({ url: 'api/xxx/xxx', method: 'POST', // GET data: {}, success: function (res) { }, error: function (err) { } }) */ static request(option) { let token = window.localStorage.getItem('token') || ''; //clientType: 1 app 2 公众号 3小程序 if (option.data == undefined) return; let newData = Object.assign(option.data, { 'clientType': 2 }); Taro.request({ url: this.pre_url + option.url, method: option.method ? option.method.toUpperCase() : 'POST', data: newData || {}, header: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Authorization': token, 'cache': 'no-cache' }, success: function (res) { console.log('-->api: ' + option.url.slice(-40) + ', success:' + JSON.stringify(res.data)); if (option.success && typeof option.success === 'function') option.success(res.data); }, fail: function (err) { console.log('-->api: ' + option.url.slice(-40) + ', fail:' + JSON.stringify(err)); if (option.error && typeof option.error === 'function') option.error(err); } }); } }<file_sep>/src/app.js import Taro, { Component } from '@tarojs/taro' import Index from './pages/index?v=20190617112' import './app.css?v=20190629112' //引用字体适配问题文件 import './utils/init.js?v=20190629112' import Netservice from './netservice'; import Common from './common'; import { getUrlParam } from './utils/utils'; import 'taro-ui/dist/style/index.scss' // 全局引入一次即可 // 如果需要在 h5 环境中开启 React Devtools // 取消以下注释: // if (process.env.NODE_ENV !== 'production' && process.env.TARO_ENV === 'h5') { // require('nerv-devtools') // } class App extends Component { config = { pages: [ 'pages/index/index', 'pages/home_components/package_or_buy/package_or_buy', 'pages/index/summer_topic/summer_topic', 'pages/points/points', 'pages/points/citys/citys', 'pages/booking/booking', 'pages/wish/wish', 'pages/wish/messages/messages', 'pages/wish/car/car', 'pages/wish/car/partTimeMakeMoney/partTimeMakeMoney', 'pages/wish/car/myMessage/myMessage', 'pages/wish/car/caocao/caocao', 'pages/wish/car/caocao/caocao_apply', 'pages/wish/car/shouqi/shouqi', 'pages/wish/car/yadi/yadi', 'pages/wish/lend/lend', 'pages/wish/rent/rent', 'pages/wish/rent2/rent2', 'pages/wish/earn/earn', 'pages/wish/apply_success/apply_success', 'pages/wish/assistant/assistant', 'pages/wish/assistant/assistantDetails/assistantDetails', // 'pages/take_meals/take_meals', 'pages/take_meals/select_coupon/select_coupon', 'pages/my/my', 'pages/my/order_history/order_history', 'pages/my/order_history/the_order_details/the_order_details', 'pages/my/couponList/couponList', 'pages/my/choice_motorman_type/choice_motorman_type', 'pages/my/service/service', 'pages/my/service/apply_for_after_sales/apply_for_after_sales', 'pages/my/apply/apply', 'pages/my/apply_detail/apply_detail', 'pages/my/invite_friends/invite_friends', 'pages/my/invite_friends/activityRules/activityRules', 'pages/my/invite_friends/hasActivationList/hasActivationList', 'pages/login/login', ], permission: { 'scope.userLocation': { desc: '您的位置将用于匹配附近的取餐点' }, 'scope.snsapi_base': { desc: '获取进入页面的用户的openId' } }, "tabBar": { 'color': '#2F2F30', //D6BC98 'selectedColor': '#2F2F30', //FF7A5A 'backgroundColor': '#2F2F30', //2F2F30 'borderStyle': 'black', //white "list": [{ "pagePath": "pages/index/index", // "text": "首页", 'iconPath': './images/tab/tab1_normal.png', 'selectedIconPath': './images/tab/tab1_select.png', 'selectedColor': '#222224' }, { "pagePath": "pages/wish/wish", // "text": "取餐", 'iconPath': './images/tab/tab2_normal.png', 'selectedIconPath': './images/tab/tab2_select.png', 'selectedColor': '#222224' }, { "pagePath": "pages/my/my", // "text": "我的", 'iconPath': './images/tab/tab3_normal.png', 'selectedIconPath': './images/tab/tab3_select.png', 'selectedColor': '#222224' } ] }, window: { backgroundTextStyle: 'light', navigationBarBackgroundColor: '#2F2F30', navigationBarTitleText: '禾师傅', navigationBarTextStyle: 'black', } } componentWillMount() { this.getWxgzhCode(); } componentDidMount() { } componentDidShow() { } componentDidHide() { } componentDidCatchError() { } // 微信公众号获取code getWxgzhCode() { const code = getUrlParam('code') // 截取路径中的code if (code == null || code === '') { // window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed1d300ad50d204f&redirect_uri=' + encodeURIComponent('http://wxgzh.hequecheguanjia.com') + '&response_type=code&scope=snsapi_base&state=1#wechat_redirect'; window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?&appid=wxed1d300ad50d204f&redirect_uri=' + encodeURIComponent('http://wxgzhtest.hequecheguanjia.com') + '&response_type=code&scope=snsapi_base&state=1#wechat_redirect'; // window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed1d300ad50d204f&redirect_uri=' + encodeURIComponent('http://wxgzhtest.hequecheguanjia.com?pid=36') + '&response_type=code&scope=snsapi_base&state=1#wechat_redirect'; } else { this.getOpenId(code) //把code传给后台获取用户信息 } } //获取openId getOpenId(code) { let that = this; Netservice.request({ url: 'heque-eat/we_chat_public_number/get_wechat_user_openid', method: 'GET', data: { code: code }, success: (res) => { if (res && res.code == Common.NetCode_NoError && res.data && res.data.openId && res.data.openId.length > 10) { window.localStorage.setItem('openId', res.data.openId); that.getUserId(res.data.openId); } } }) } //获取userId getUserId(openId) { Netservice.request({ url: 'heque-user/user/open_id_get_user_info', method: 'GET', data: { weChatPublicNumberOpenId: openId, type: 1 }, success: (res) => { if (res && (res.code == Common.NetCode_NoError) && res.data) { const user = res.data; window.localStorage.setItem('token', user.token); window.localStorage.setItem('userId', user.userId); window.localStorage.setItem('phone', user.phoneNo); } } }) } // 在 App 类中的 render() 函数没有实际作用 // 请勿修改此函数 render() { return ( <Index /> ) } } Taro.render(<App />, document.getElementById('app'))<file_sep>/.temp/pages/wish/lend/lend.js import Nerv from "nervjs"; import './lend.css?v=20190703108'; import Taro, { getSystemInfo as _getSystemInfo, showToast as _showToast, showLoading as _showLoading, hideLoading as _hideLoading } from "@tarojs/taro-h5"; import { View, Text, Image, Swiper, SwiperItem } from '@tarojs/components'; import Netservice from "../../../netservice"; import Common from "../../../common"; import { AtInput } from 'taro-ui'; import banner1 from '../../../images/wish/lend/banner1.png'; import icon_normal from '../../../images/wish/radio_normal.png'; import icon_select from '../../../images/wish/radio_select.png'; export default class Lend extends Taro.Component { config = { navigationBarTitleText: '周转' }; constructor() { super(); this.canSubmitClick = true; //支付按钮防止连续点击 } state = { times: [{ value: 1, text: '1~30天' }, { value: 2, text: '30天~1年' }, { value: 3, text: '1年以上' }], timesIndex: -1, amounts: [{ value: 1, text: '1000 ~ 1万' }, { value: 2, text: '1万 ~ 5万' }, { value: 3, text: '5万以上' }], amountsIndex: -1, preferences: [{ value: 1, text: '纯信用借款产品' }, { value: 2, text: '抵押借款产品(汽车、房产)' }], preferencesIndex: -1, repayments: [{ value: 1, text: '按日计息,随借随还' }, { value: 2, text: '按月等额,长期超划算' }, { value: 3, text: '按月付息,到期还本' }, { value: 4, text: '一次性还本付息' }], repaymentsIndex: -1, works: [{ value: 1, text: '出租车司机' }, { value: 2, text: '网约车司机' }], worksIndex: -1, earnings: [{ value: 1, text: '5000~8000元' }, { value: 2, text: '8000~12000元' }, { value: 3, text: '12000~15000元' }, { value: 4, text: '15000元以上' }], earningsIndex: -1, emergencys: [{ value: 1, text: '越快越好,即刻需求' }, { value: 2, text: '近期有可能需要' }, { value: 3, text: '暂时不需要' }], emergencysIndex: -1, name: '', phoneNumber: '', system: 'android' }; componentWillMount() { let phone = localStorage.getItem('phone') || ''; this.setState({ phoneNumber: phone }); _getSystemInfo({ success: res => { this.setState({ system: res.system }); } }); } componentDidMount() { var h = document.body.scrollHeight; window.onresize = function () { if (document.body.scrollHeight < h) document.getElementsByClassName("money-submit")[0].style.display = "none";else document.getElementsByClassName("money-submit")[0].style.display = "block"; }; } componentWillUnmount() {} componentDidShow() {} componentDidHide() {} render() { let { times, timesIndex, amounts, amountsIndex, preferences, preferencesIndex, repayments, repaymentsIndex, works, worksIndex, earnings, earningsIndex, emergencys, emergencysIndex, name, phoneNumber, system } = this.state; console.log(system == 'iOS'); return <View className="container-money bottom-gap"> <Swiper className="money-swiper"> <SwiperItem> <Image className="ms_image" src={banner1} style="pointer-events: none" /> </SwiperItem> </Swiper> <View className="time-view"> <Text className="tv-title">周转周期</Text> <View className="tv-content"> {times.map((item, index) => { return <View className="tvc-view" key={index} onClick={this.onTimeChange.bind(this, index)}> <Image className="tvcv_image" src={timesIndex == index ? icon_select : icon_normal} style="pointer-events: none" /> <Text className="tvcv-text">{item.text}</Text> </View>; })} </View> <View className="tv-line" /> </View> <View className="time-view"> <Text className="tv-title">周转金额(元)</Text> <View className="tv-content"> {amounts.map((item, index) => { return <View className="tvc-view" key={index} onClick={this.onAmountChange.bind(this, index)}> <Image className="tvcv_image" src={amountsIndex == index ? icon_select : icon_normal} style="pointer-events: none" /> <Text className="tvcv-text">{item.text}</Text> </View>; })} </View> <View className="tv-line" /> </View> <View className="time-view"> <Text className="tv-title">产品偏好</Text> <View className="tv-content"> {preferences.map((item, index) => { return <View className="tvc-view" key={index} onClick={this.onPreferenceChange.bind(this, index)}> <Image className="tvcv_image" src={preferencesIndex == index ? icon_select : icon_normal} style="pointer-events: none" /> <Text className="tvcv-text">{item.text}</Text> </View>; })} </View> <View className="tv-line" /> </View> <View className="time-view"> <Text className="tv-title">还款方式偏好</Text> <View className="tv-content"> {repayments.map((item, index) => { return <View className="tvc-view" key={index} onClick={this.onRepaymentChange.bind(this, index)}> <Image className="tvcv_image" src={repaymentsIndex == index ? icon_select : icon_normal} style="pointer-events: none" /> <Text className="tvcv-text">{item.text}</Text> </View>; })} </View> <View className="tv-line" /> </View> <View className="time-view"> <Text className="tv-title">您的工作</Text> <View className="tv-content"> {works.map((item, index) => { return <View className="tvc-view" key={index} onClick={this.onWorkChange.bind(this, index)}> <Image className="tvcv_image" src={worksIndex == index ? icon_select : icon_normal} style="pointer-events: none" /> <Text className="tvcv-text">{item.text}</Text> </View>; })} </View> <View className="tv-line" /> </View> <View className="time-view"> <Text className="tv-title">您的月收入范围</Text> <View className="tv-content"> {earnings.map((item, index) => { return <View className="tvc-view" key={index} onClick={this.onEarningChange.bind(this, index)}> <Image className="tvcv_image" src={earningsIndex == index ? icon_select : icon_normal} style="pointer-events: none" /> <Text className="tvcv-text">{item.text}</Text> </View>; })} </View> <View className="tv-line" /> </View> <View className="time-view"> <Text className="tv-title">您周转需求的紧急程度</Text> <View className="tv-content"> {emergencys.map((item, index) => { return <View className="tvc-view" key={index} onClick={this.onEmergencyChange.bind(this, index)}> <Image className="tvcv_image" src={emergencysIndex == index ? icon_select : icon_normal} style="pointer-events: none" /> <Text className="tvcv-text">{item.text}</Text> </View>; })} </View> <View className="tv-line" /> </View> <View className="lend-name-view"> <Text className="nv-title">您的称呼方式</Text> <AtInput className="nv-name-input" type="text" placeholder="请输入真实姓名" border={false} maxLength={10} adjustPosition={false} onBlur={this.onInputBlur.bind(this)} value={name} onChange={this.onNameChange.bind(this)} /> <View className="tv-line" /> </View> <View className="lend-name-view"> <Text className="nv-title finally_title">请确认您的联系方式。人工客服会在60分钟内联系您,提供优选服务!</Text> <AtInput className="nv-name-input " type="phone" placeholder="请输入联系方式" placeholderStyle="color:#F2D3AB" border={false} maxLength={11} adjustPosition={false} onBlur={this.onInputBlur.bind(this)} value={phoneNumber} onChange={this.onPhoneNumberChange.bind(this)} /> <View className="tv-line" /> </View> {system == 'iOS' && <View className="tv-gap"></View>} <View className="money-submit" onClick={this.onSubmit.bind(this)}>提交</View> </View>; } onInputBlur() { let { system } = this.state; if (system.startsWith('iOS') || system.startsWith('ios')) window.scroll(0, 0); } onTimeChange(index) { this.setState({ timesIndex: index }); } onAmountChange(index) { this.setState({ amountsIndex: index }); } onPreferenceChange(index) { this.setState({ preferencesIndex: index }); } onRepaymentChange(index) { this.setState({ repaymentsIndex: index }); } onWorkChange(index) { this.setState({ worksIndex: index }); } onEarningChange(index) { this.setState({ earningsIndex: index }); } onEmergencyChange(index) { this.setState({ emergencysIndex: index }); } onNameChange(value) { this.setState({ name: value.replace(/ /g, '') }); return value; } onPhoneNumberChange(value) { this.setState({ phoneNumber: value }); return value; } onSubmit(value) { let { times, timesIndex, amounts, amountsIndex, preferences, preferencesIndex, repayments, repaymentsIndex, works, worksIndex, earnings, earningsIndex, emergencys, emergencysIndex, name, phoneNumber } = this.state; if (timesIndex < 0) { _showToast({ title: '请选择周转周期', icon: 'none', duration: 2000 }); return; } if (amountsIndex < 0) { _showToast({ title: '请选择周转金额', icon: 'none', duration: 2000 }); return; } if (preferencesIndex < 0) { _showToast({ title: '请选择产品偏好', icon: 'none', duration: 2000 }); return; } if (repaymentsIndex < 0) { _showToast({ title: '请选择还款方式偏好', icon: 'none', duration: 2000 }); return; } if (worksIndex < 0) { _showToast({ title: '请选择您的工作', icon: 'none', duration: 2000 }); return; } if (earningsIndex < 0) { _showToast({ title: '请选择您的月收入范围', icon: 'none', duration: 2000 }); return; } if (emergencysIndex < 0) { _showToast({ title: '请选择您周转需求的紧急程度', icon: 'none', duration: 2000 }); return; } if (name.length < 1) { _showToast({ title: '请输入称呼', icon: 'none', duration: 2000 }); return; } if (phoneNumber.length < 1) { _showToast({ title: '请输入您的联系方式', icon: 'none', duration: 2000 }); return; } let userId = localStorage.getItem('userId'); if (userId) { if (!this.canSubmitClick) return; this.canSubmitClick = false; setTimeout(() => { this.canSubmitClick = true; }, 1500); _showLoading({ title: '正在提交中…' }); Netservice.request({ url: 'heque-backend/collect/saveLoanInfo', data: { userId: userId, phoneNum: phoneNumber, userName: name, money: amounts[amountsIndex].value, cycle: times[timesIndex].value, special: preferences[preferencesIndex].value, repayment: repayments[repaymentsIndex].value, job: works[worksIndex].value, salary: earnings[earningsIndex].value, emergent: emergencys[emergencysIndex].value }, success: res => { _hideLoading(); if (res.code !== Common.NetCode_NoError) { _showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } _showToast({ title: '提交成功', icon: 'success', duration: 2000 }); Taro.navigateTo({ url: '/pages/wish/apply_success/apply_success?type=' + res.data.type + '&id=' + res.data.id + '&v=' + new Date().getTime() }); }, error: function (err) { _hideLoading(); _showToast({ title: '提交失败', icon: 'none', duration: 2000 }); } }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } }<file_sep>/.temp/pages/my/invite_friends/hasActivationList/hasActivationList.js import Nerv from "nervjs"; import Taro from "@tarojs/taro-h5"; import { View, Text, Image } from '@tarojs/components'; import './hasActivationList.css?v=201906107'; import Netservice from "../../../../netservice"; import defaultInvite from '../../../../images/coupons/defaultInvite.png'; export default class HasActivationList extends Taro.Component { config = { navigationBarTitleText: '已邀请列表' }; state = { hasActivationListData: [] }; componentDidMount() { let that = this; let userId = localStorage.getItem('userId'); Netservice.request({ url: 'heque-user/invite/invite_people', method: 'GET', data: { inviteUserId: userId }, success: res => { console.log(res.data); that.setState({ hasActivationListData: res.data.hasActivation }); } }); } render() { const { hasActivationListData } = this.state; return <View className="HasActivationList"> {hasActivationListData.length === 0 ? <View className="noListData_style"> <Image className="noListData_style_img" src={defaultInvite} /> <View className="noListData_text">暂没成功邀请好友</View> </View> : <View> {hasActivationListData.map((item, index) => { return <View className="HasActivationList_content" key={index}> <View className="HasActivationList_content_left"> <Text className="HasActivationList_content_phone">{item.phoneNo}</Text> <Text className="HasActivationList_content_name">{item.petName}</Text> </View> <View className="HasActivationList_content_right">{item.status === 2 && '已激活'}</View> </View>; })} </View>} </View>; } componentDidShow() { super.componentDidShow && super.componentDidShow(); } componentDidHide() { super.componentDidHide && super.componentDidHide(); } }<file_sep>/src/pages/wish/earn/earn.js import './earn.css?v=20190703108'; import Taro, { Component } from '@tarojs/taro'; import { View, Text, Image, Swiper, SwiperItem } from '@tarojs/components'; import Netservice from '../../../netservice.js'; import Common from '../../../common.js'; import { reporteUerBehavior } from '../../../utils/utils' import banner1 from '../../../images/wish/earn/banner1.png'; import partner1 from '../../../images/wish/earn/partner1.png'; import partner2 from '../../../images/wish/earn/partner2.png'; import partner3 from '../../../images/wish/earn/partner3.png'; import partner4 from '../../../images/wish/earn/partner4.png'; import partner5 from '../../../images/wish/earn/partner5.png'; export default class Earn extends Component { config = { navigationBarTitleText: '外快', } state = { phoneNumber: '', } componentWillMount() { } componentDidMount() { } componentWillUnmount() { } componentDidShow() { } componentDidHide() { } render() { return ( <View className='container-earn'> <Swiper className='earn-swiper'> <SwiperItem> <Image className='es_image' src={banner1} style='pointer-events: none' /> </SwiperItem> </Swiper> <View className='earn-amount-view'> <Text className='eav-title'>派单收入</Text> <View className='eav-content'> <View className='eavc-item'> <Text className='eavci-title'>订单收入(元)</Text> <Text className='eavci-detail'>0.0</Text> </View> <View className='eavc-line' /> <View className='eavc-item'> <Text className='eavci-title'>接单数</Text> <Text className='eavci-detail'>0</Text> </View> </View> </View> <View className='earn-partner-view'> <Text className='epv-title'>聚合接单</Text> <View className='epv-content'> <View className='epvc-partner_wrap' onClick={this.goCaocao.bind(this)}> <Image className='epvc-partner' src={partner1} style='pointer-events: none' /> </View> <View className='epvc-partner_wrap' onClick={this.goShouqi.bind(this)}> <Image className='epvc-partner' src={partner2} style='pointer-events: none' /> </View> <View className='epvc-partner_wrap' onClick={this.goShuangchuang.bind(this)}> <Image className='epvc-partner' src={partner3} style='pointer-events: none' /> </View> <View className='epvc-partner_wrap' onClick={this.goQuanmin.bind(this)}> <Image className='epvc-partner' src={partner4} style='pointer-events: none' /> </View> <View className='epvc-partner_wrap' onClick={this.goShansong.bind(this)}> <Image className='epvc-partner' src={partner5} style='pointer-events: none' /> </View> </View> </View> </View> ) } //曹操下载 goCaocao(e) { e.stopPropagation(); reporteUerBehavior('赚钱|外快|曹操出行', 1, res => { Taro.navigateTo({ url: 'https://mobile.caocaokeji.cn/driver-outside/download/app', }) }); } //首汽下载 goShouqi(e) { e.stopPropagation(); reporteUerBehavior('赚钱|外快|首汽约车', 1, res => { Taro.navigateTo({ url: 'https://monline.01zhuanche.com/appDownload/driverAppDownload.html', }) }); } //双创下载 goShuangchuang(e) { e.stopPropagation(); reporteUerBehavior('赚钱|外快|双创便民', 1, res => { Taro.navigateTo({ url: 'http://appurl.me/79814328146', }) }); } //全民 goQuanmin(e) { e.stopPropagation(); reporteUerBehavior('赚钱|外快|全民用车', 1, res => { Taro.navigateTo({ url: 'https://a.app.qq.com/o/simple.jsp?pkgname=com.zingfon.taxi', }) }); } //闪送 goShansong(e) { e.stopPropagation(); reporteUerBehavior('赚钱|外快|闪送', 1, res => { Taro.navigateTo({ url: 'http://m.ishansong.com/activity/down-ssy.html', }) }); Taro.navigateTo({ url: 'http://m.ishansong.com/activity/down-ssy.html', }) } }<file_sep>/.temp/pages/home_components/point_buy/point_buy.js import Nerv from "nervjs"; import Taro, { getSystemInfo as _getSystemInfo, makePhoneCall as _makePhoneCall, showLoading as _showLoading, hideLoading as _hideLoading, showToast as _showToast } from "@tarojs/taro-h5"; import { View, Text, Swiper, SwiperItem, Image } from '@tarojs/components'; import { AtInput } from 'taro-ui'; import './point_buy.css'; import banner1 from '../../../images/home/banner1.png'; import banner2 from '../../../images/home/banner2.png'; import banner3 from '../../../images/home/banner3.png'; import banner4 from '../../../images/home/banner4.png'; import arrowRight1 from '../../../images/common/arrow_right.png'; import paymentBtn2 from '../../../images/common/payment_btn2.png'; import closeBtn from '../../../images/common/close_btn.png'; import inRestImg from '../../../images/home/in_rest.png'; import Netservice from "../../../netservice"; import Common from "../../../common"; import { payment, zeroPayment } from "../../../utils/payment"; // 引入微信js-sdk import { setGlobalData } from "../../../utils/global_data"; // 输入金额买单 export default class PointBuy extends Taro.Component { constructor(props) { super(props); this.canPayClick = true; //支付按钮防止连续点击 } state = { storesDetails: {}, //门店信息 packageList: [], //套餐、菜品列表 paymentState: false, //支付状态 input聚焦时为true 显示支付时的样式 amount: '', //输入金额 paymentBtnStyle: false, //确定付款按钮样式 false未输入金额前 true输入金额后 currentCoupon: {}, //优惠券 dishId: 0, //默认菜品id alterStyle: false, //过渡效果 inRest: false, //店铺休息状态 true为休息状态 system: 'iOS', //获取手机系统 closePaymentState: false //点击关闭按钮 }; componentWillMount() { if (this.props.currentPoint) { //获取门店信息 let storesDetails = this.props.currentPoint; this.setState({ storesDetails }); //判断是否在休息时间 if (storesDetails.state) { //获取门店菜品 this.getPointPackage(storesDetails.id); } else { this.setState({ inRest: true }); } } _getSystemInfo({ success: res => { this.setState({ system: res.system }); } }); } //实时监听父组件传过来的值的变化 componentWillReceiveProps(nextProps) { if (nextProps.currentPoint && nextProps.currentPoint.id != this.props.currentPoint.id) { let storesDetails = nextProps.currentPoint; this.setState({ storesDetails }); //判断是否在休息时间 if (storesDetails.state) this.getPointPackage(storesDetails.id);else this.setState({ inRest: true }); } if (nextProps.currentCoupon) { let currentCoupon = nextProps.currentCoupon; this.setState({ currentCoupon }); } } componentDidShow() { this.getTheCoupon(); } //查找最大可用优惠券 getTheCoupon() { let userId = localStorage.getItem('userId'); if (!userId) return; let { amount, storesDetails, dishId } = this.state; let that = this; Netservice.request({ url: 'heque-coupon/discount_coupon/orderInfoGetCoupon', method: 'GET', data: { userId: userId, totalPrice: amount, dishId: dishId, storeId: storesDetails.id }, success: function (res) { let coupons = res.data; var okCoupons = coupons.filter(function (item) { return item.type == '2'; }); if (okCoupons.length > 0) { okCoupons.sort(function (item1, item2) { return item2.faceValue - item1.faceValue; }); const targetCoupon = okCoupons[0]; if (targetCoupon.type == '2') { setGlobalData('currentCoupon', targetCoupon); that.setState({ currentCoupon: targetCoupon }); } } else { setGlobalData('currentCoupon', {}); that.setState({ currentCoupon: {} }); } }, error: function (err) {} }); } // 查询门店菜品 getPointPackage(stroeId) { let that = this; Netservice.request({ url: 'heque-eat/eat/storeEatInfo', method: 'POST', data: { stroeId: stroeId }, success: function (res) { if (res.code == '300030') { that.setState({ inRest: true }); } else { let packageList = res.data; const first = packageList[0] || {}; const dishId = first.dishId || 0; that.setState({ packageList: packageList, dishId: dishId, inRest: false }); } }, error: function (err) {} }); } render() { const { storesDetails, paymentState, amount, paymentBtnStyle, currentCoupon, inRest, alterStyle, closePaymentState } = this.state; let { foodTime1, foodTime2, foodTime3, foodTime4 } = storesDetails; let timeArray = [foodTime1, foodTime2, foodTime3, foodTime4]; let times = []; for (let time of timeArray) { if (time && time.length > 5) { let aTime = time.slice(0, 5) + '-' + time.slice(11, 16); times.push(aTime); } } storesDetails.times = times; let cValue = currentCoupon.faceValue ? currentCoupon.faceValue : 0; let couponStr = cValue > 0 ? '-¥' + cValue : '请选择优惠券'; {/* 支付状态*/} const affirmPaymentState = <View className={!alterStyle ? 'pt2-order2' : 'pt2-order2_true'}> <View className="pt2-order2-closeBtn-wrap"> <View className="pt2ol-title2">请输入金额</View> {closePaymentState && <Image src={closeBtn} className="pt2_closeBtn" onClick={this.shutPaymentState.bind(this)} />} </View> <View className="pt2o-line2"> <View className="pt2o-line_rmb2">¥</View> <AtInput className="pt2ol-amount2" type="digit" placeholder="请输入金额" border={false} maxLength={6} onFocus={this.onAmountFocus.bind(this)} onBlur={this.onAmountBlur.bind(this)} value={amount} onChange={this.onAmountChange.bind(this)} /> </View> {paymentState && <View className="pt2ol_coupon2" onClick={this.selectCoupon.bind(this)}> <Text className="pt2ol_coupon_title2">优惠券</Text> <View className="pt2ol_coupon_right_wrap"> <Text className={cValue > 0 ? 'pt2ol_coupon_price2' : 'pt2ol_coupon_price3'}>{couponStr}</Text> <Image src={arrowRight1} className="pt2ol-arrow-right2" style="pointer-events: none" /> </View> </View>} {paymentState && <View className="pt2ol_price_amount2"> <Text className="pt2ol_amount_title2">实付 :</Text> <Text className="pt2ol_amount_price2">¥{this.formatAmount1(amount - cValue)}</Text> </View>} {!paymentBtnStyle ? <View className="po2ol_payment_btn">确认付款</View> : <View onClick={this.bookingMeal.bind(this)} className="po2ol_payment_btn2"> <Image className="po2ol_payment_btn2_img" src={paymentBtn2} style="pointer-events: none" /> </View>} </View>; return <View className="Dierct"> <View className="pt2-point" onClick={this.goSlecPoint}> <View className="pt2pt_head"> <View className="pt2pt_head_title" onClick={this.goToPoints.bind(this)}> <Text>{storesDetails.name}</Text> <Image src={arrowRight1} className="pt2ol-arrow-right" style="pointer-events: none" /> </View> <View className="pt2pt_head_distance">距您 {storesDetails.number >= 1000 ? <Text className="pt2pt_head_number"> {(storesDetails.number / 1000).toFixed(1)}<Text className="pt2pt_distance_unit"> km</Text> </Text> : <Text className="pt2pt_head_number">{storesDetails.number}<Text className="pt2pt_distance_unit"> m</Text></Text>} <Text className="pt2pt_head_placeholder">|</Text> <Text className="pt2pt_head_adds">{storesDetails.adds}</Text> </View> {storesDetails.suppleTime1 !== undefined ? <View className="pt2pt_head_time"> <Text>营业时间:</Text> <Text>{storesDetails.suppleTime1}{storesDetails.suppleTime2}{storesDetails.suppleTime3}{storesDetails.suppleTime4}</Text> </View> : <View className="pt2pt_head_time"> <Text>营业时间:</Text> {storesDetails.times.length == 1 && <Text>{storesDetails.times[0]}</Text>} {storesDetails.times.length == 2 && <Text>{storesDetails.times[0]} / {storesDetails.times[1]}</Text>} {storesDetails.times.length == 3 && <Text>{storesDetails.times[0]} / {storesDetails.times[1]} / {storesDetails.times[2]}</Text>} {storesDetails.times.length == 4 && <Text>{storesDetails.times[0]} / {storesDetails.times[1]} / {storesDetails.times[2]} / {storesDetails.times[3]}</Text>} </View>} </View> {/*<View className='pt2ol-phonePoint' onClick={this.contactUs.bind(this)}> <Image src={phonePoint} className='pt2ol-phonePoint-img' style='pointer-events: none' /> </View>*/} </View> <Swiper className="pt2-swiper" circular autoplay interval={3000}> <SwiperItem className="pt2_SwiperItem"> <Image className="pt2_swiper_image" src={banner1} onClick={this.goEarn.bind(this)} /> </SwiperItem> <SwiperItem className="pt2_SwiperItem"> <Image className="pt2_swiper_image" src={banner2} onClick={this.goLend.bind(this)} /> </SwiperItem> <SwiperItem className="pt2_SwiperItem"> <Image className="pt2_swiper_image" src={banner3} onClick={this.goPartTimeMakeMoney.bind(this)} /> </SwiperItem> <SwiperItem className="pt2_SwiperItem"> <Image className="pt2_swiper_image" src={banner4} onClick={this.goAssistant.bind(this)} /> </SwiperItem> </Swiper> {!inRest ? <View> {/* <View className='Dierct_tabbar'> <View className='Dierct_tabbar_payment'>买单</View> <View className='Dierct_tabbar_evaluate'>评价</View> </View>*/} {/*支付模块*/} {affirmPaymentState} </View> : <View className="inRest_img_wrap2" onClick={this.goToPoints.bind(this)}> <Image className="inRest_img2" src={inRestImg} style="pointer-events: none" /> </View>} </View>; } //去门店列表 goToPoints(e) { e.stopPropagation(); Taro.navigateTo({ url: "/pages/points/points?v=" + new Date().getTime() }); } //联系商家 contactUs(e) { e.stopPropagation(); _makePhoneCall({ phoneNumber: String(this.state.storesDetails.storePhoneNumber) }); } //金额输入框 onAmountChange(value) { this.setState({ amount: this.formatAmount(value) }, () => { if (parseFloat(value) > 0) this.getTheCoupon(); }); if (value !== '' && value !== null) { this.setState({ paymentBtnStyle: true, paymentState: true }); } else { this.setState({ paymentState: false, paymentBtnStyle: false, currentCoupon: {} }); } return this.formatAmount(value); } //计算金额 formatAmount(value) { if (parseFloat(value) < 0) value = 0;else if (parseFloat(value) > 1000) value = 1000; let xiao = value.toString().split(".")[1]; let xiaoLength = xiao ? xiao.length : 0; if (xiaoLength > 2) return parseFloat(parseInt(value * 100) / 100).toFixed(2);else return value; } //计算总金额 formatAmount1(value) { if (parseFloat(value) < 0) value = 0;else if (parseFloat(value) > 1000) value = 1000; let xiao = value.toString().split(".")[1]; let first = xiao ? xiao.charAt(0) : ''; let second = xiao ? xiao.charAt(1) : ''; if (first == '0' && second == '') return parseFloat(value).toFixed(1); let xiaoLength = xiao ? xiao.length : 0; if (xiaoLength <= 0) return parseFloat(value);else if (xiaoLength == 1) return (Math.round(value * Math.pow(10, 1)) / Math.pow(10, 1)).toFixed(2);else return (Math.round(value * Math.pow(10, 2)) / Math.pow(10, 2)).toFixed(2); } //键盘兼容样式 onAmountFocus() { this.setState({ alterStyle: true, closePaymentState: true }); let { system } = this.state; if (system.startsWith('iOS') || system.startsWith('ios')) { setTimeout(() => { window.scrollTo({ top: 0, behavior: "smooth" }); }, 200); } } //键盘兼容样式 onAmountBlur() {} //点击关闭按钮 shutPaymentState(e) { e.stopPropagation(); this.setState({ alterStyle: false, // paymentState: false, closePaymentState: false }); } //选择优惠券 selectCoupon() { let userId = localStorage.getItem('userId'); if (userId) { let { amount, storesDetails, dishId } = this.state; Taro.navigateTo({ url: '/pages/take_meals/select_coupon/select_coupon?userId=' + userId + '&storeId=' + storesDetails.id + '&dishId=' + dishId + '&totalPrice=' + amount + '&v=' + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } //确定支付 bookingMeal() { let userId = localStorage.getItem('userId'); if (userId) { let that = this; let { amount, dishId } = this.state; if (!parseFloat(amount) || parseFloat(amount) <= 0) return; if (!this.canPayClick) return; this.canPayClick = false; setTimeout(() => { this.canPayClick = true; }, 2000); _showLoading({ title: '努力加载中…' }); const currentPoint = this.state.storesDetails; const cityCode = localStorage.getItem('cityCode'); const latitude = localStorage.getItem('latitude'); const longitude = localStorage.getItem('longitude'); Netservice.request({ url: 'heque-eat/order_info/input_amount_order_info', data: { appType: 'h5', codeC: cityCode, longitude: longitude, latitude: latitude, dishId: dishId, storeId: currentPoint.id, totalPrice: amount, userId: userId }, success: res => { _hideLoading(); if (res.code !== Common.NetCode_NoError) { _showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } _showToast({ title: '下单成功', icon: 'success', duration: 2000 }); that.checkPay(res.data.orderId); } }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } checkPay(orderId) { _showLoading({ title: '努力加载中…' }); let { currentCoupon } = this.state; let userCardMedalId = {}; const couponId = currentCoupon.id; if (couponId) { userCardMedalId = { userCardMedalId: couponId }; } let that = this; //查订单支付金额 Netservice.request({ url: 'heque-coupon/discount_coupon/queryRealPayMoney', method: 'GET', data: { ...userCardMedalId, orderId: orderId }, success: function (res) { _hideLoading(); if (res.code !== Common.NetCode_NoError) { _showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } let totalPrice = res.data.totalPrice; if (parseInt(parseFloat(totalPrice) * 100) > parseInt(0)) that.goWechatPay(totalPrice, orderId);else that.zeroPay(totalPrice, orderId); }, error: function (err) { _hideLoading(); _showToast({ title: '查询支付金额失败', icon: 'none', duration: 2000 }); } }); } //微信支付 goWechatPay(totalPrice, orderId) { _showLoading({ title: '努力加载中…' }); let { currentCoupon } = this.state; const openId = localStorage.getItem('openId'); let userCardMedalId = {}; const couponId = currentCoupon.id; if (couponId) { userCardMedalId = { userCardMedalId: couponId }; } payment(userCardMedalId, orderId, totalPrice, openId, () => { //支付成功 setGlobalData('currentCoupon', {}); this.setState({ currentCoupon: {}, amount: '', paymentState: false, alterStyle: false }); Taro.navigateTo({ url: '/pages/my/order_history/the_order_details/the_order_details?orderId=' + orderId }); }, () => { //支付取消 setGlobalData('currentCoupon', {}); this.setState({ currentCoupon: {}, amount: '', paymentState: false, alterStyle: false }); _showToast({ title: '支付取消', icon: 'none', duration: 2000 }); Taro.navigateTo({ url: '/pages/my/order_history/the_order_details/the_order_details?orderId=' + orderId }); }, () => { //支付失败 setGlobalData('currentCoupon', {}); this.setState({ currentCoupon: {}, amount: '', paymentState: false, alterStyle: false }); _showToast({ title: '支付失败', icon: 'none', duration: 2000 }); Taro.navigateTo({ url: '/pages/my/order_history/the_order_details/the_order_details?orderId=' + orderId }); }); } //零元支付 zeroPay(price, orderId) { _showLoading({ title: '努力加载中…' }); let that = this; let { currentCoupon } = this.state; let userCardMedalId = {}; const couponId = currentCoupon.id; if (couponId) { userCardMedalId = { userCardMedalId: couponId }; } that.setState({ currentCoupon: {}, amount: '', paymentState: false, alterStyle: false }); zeroPayment(userCardMedalId, price, orderId); } //外快 goEarn(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/earn/earn?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } //周转 goLend(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/lend/lend?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } //当副班 goPartTimeMakeMoney(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/car/car?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } //招副班 goAssistant(e) { let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: "/pages/wish/assistant/assistant?v=" + new Date().getTime() }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } }<file_sep>/.temp/pages/noprize/noprize.js import Nerv from "nervjs"; import Taro from "@tarojs/taro-h5"; import { View, Image } from '@tarojs/components'; import './noprize.css?v=201906202109'; import noPrizeImg from '../../images/prize/img_no_prize.png'; import iconClose from '../../images/prize/icon_close.png'; //抽奖/开奖 组件 export default class NoPrize extends Taro.Component { componentDidMount() {} render() { return <View className="no-prize-bg"> <View className="no-prize-content"> <Image className="no-prize-img" src={noPrizeImg} onClick={this.tapNoPrize.bind(this)} /> <Image className="no-prize-close" src={iconClose} onClick={this.tapClose.bind(this)} /> </View> </View>; } tapNoPrize(e) { e.stopPropagation(); if (this.props.onTapNoPrize) this.props.onTapNoPrize(); } tapClose(e) { e.stopPropagation(); if (this.props.onTapClose) this.props.onTapClose(); } }<file_sep>/src/pages/my/choice_motorman_type/choice_motorman_type.js import Taro, { Component } from '@tarojs/taro' import { View, Text, Image } from '@tarojs/components' import './choice_motorman_type.css?v=201906261107' import a_default from '../../../images/motormanType/a_default.png' import b_default from '../../../images/motormanType/b_default.png' import c_default from '../../../images/motormanType/c_default.png' import a_slct from '../../../images/motormanType/a_slct.png' import b_slct from '../../../images/motormanType/b_slct.png' import c_slct from '../../../images/motormanType/c_slct.png' import a_unslct from '../../../images/motormanType/a_unslct.png' import b_unslct from '../../../images/motormanType/b_unslct.png' import c_unslct from '../../../images/motormanType/c_unslct.png' import btn_next from '../../../images/motormanType/btn_next.png' import btn_unavailable from '../../../images/motormanType/btn_unavailable.png' import Netservice from '../../../netservice.js' import TooltipCoupon from '../../tooltipCoupon/tooltipCoupon.js' export default class ChoiceMotormanType extends Component { config = { navigationBarTitleText: '选择司机类型', } state = { whetherDefaultState: 0, //司机类型参数 出租车司机1、网约车司机2、普通司机3 couponsData: [], //传到优惠券组件的数据 showBounced: false, //优惠券弹框 defaultState: true, //默认的图 } render() { const { whetherDefaultState, showBounced, couponsData, defaultState } = this.state; return ( <View className='ChoiceMotormanType'> <View className='Motorman_title'>请选择司机类型</View> <View className='MotormanType_wrap' onClick={() => { this.ChangeState(1) }}> {!defaultState ? <Image src={whetherDefaultState === 1 ? a_slct : a_unslct} className='MotormanType_defaultBgImg' /> : <Image src={a_default} className='MotormanType_defaultBgImg' /> } </View> <View className='MotormanType_wrap' onClick={() => { this.ChangeState(2) }}> {!defaultState ? <Image src={whetherDefaultState === 2 ? b_slct : b_unslct} className='MotormanType_defaultBgImg' /> : <Image src={b_default} className='MotormanType_defaultBgImg' /> } </View> <View className='MotormanType_wrap' onClick={() => { this.ChangeState(3) }}> {!defaultState ? <Image src={whetherDefaultState === 3 ? c_slct : c_unslct} className='MotormanType_defaultBgImg' /> : <Image src={c_default} className='MotormanType_defaultBgImg' /> } </View> <View className='Motorman_btn' onClick={this.completeChoice.bind(this)}> { !whetherDefaultState == 0 ? <Image src={btn_next} className='Motorman_btn_img' /> : <Image src={btn_unavailable} className='Motorman_btn_img' /> } </View> {showBounced && <TooltipCoupon couponsData={couponsData} afterClose={1} notScroll={0}></TooltipCoupon>} </View> ) } //选择类型时,修改样式的函数 ChangeState(type) { this.setState({ whetherDefaultState: type, defaultState: false }) } //选择完成,进行跳转 completeChoice() { let that = this; if (that.state.whetherDefaultState === '' || that.state.whetherDefaultState === undefined) { return } else { let businessType = that.state.whetherDefaultState; let userId = localStorage.getItem('userId'); Netservice.request({ url: 'heque-user/user/addBusinessType', method: 'POST', data: { id: userId, businessType: businessType }, success: (res) => { that.getCouponsMessage(userId) } }) } } //查优惠券 getCouponsMessage(userId) { let that = this; Netservice.request({ 'url': 'heque-coupon/discount_coupon/getNotRead', method: 'GET', data: { userId: userId, }, success: (res) => { console.log(res) let results = res.data; let coupons = results.filter(function (ele) { return ele.faceValue > 0 }); if (coupons.length === 0 || coupons === '') { that.setState({ showBounced: false, }) Taro.navigateBack(); } else { that.setState({ showBounced: true, couponsData: coupons, }) } } }) } } <file_sep>/README.md #Project setup npm install #H5 预览: npm run dev:h5 打包: npm run build:h5 #微信小程序 npm run dev:weapp npm run build:weapp #上线检查 接口地址及log:netservice 重定向地址:app 公共配置(邀请地址):common 路径配置(publicPath):config/index <file_sep>/src/pages/home_components/home_points/home_points.js import './home_points.css?v=201907051107'; import Taro, { Component } from '@tarojs/taro'; import { View, Text, Image, Swiper, SwiperItem } from '@tarojs/components'; import Netservice from '../../../netservice.js'; import Common from '../../../common.js'; import { setGlobalData, getGlobalData } from '../../../utils/global_data' import arrowRight from '../../../images/common/arrow_right.png'; import banner1 from '../../../images/home/banner1.png' import banner2 from '../../../images/home/banner2.png' import banner3 from '../../../images/home/banner3.png' import banner4 from '../../../images/home/banner4.png' import resting from '../../../images/home/Resting.png' import default_store_img from '../../../images/home/default_store_img.png' import noServiceImg from '../../../images/home/no_service_img.png' export default class HomePoints extends Component { config = { navigationBarTitleText: '点餐', } state = { cityCode: '', //城市编号 city: '', //城市名 pointList: [], //取餐点列表 noShop: false, //没有取餐点 } componentWillMount() { let cityCode = this.props.cityCode; let city = this.props.city; this.setState({ cityCode, city }); const latitude = getGlobalData('latitude'); const longitude = getGlobalData('longitude'); //请求城市门店 this.getCityPoints(cityCode, latitude, longitude); } componentDidMount() { } //实时监听父组件传过来的值的变化 componentWillReceiveProps(nextProps) { if (nextProps.cityCode && nextProps.cityCode != this.props.cityCode) { this.setState({ cityCode: nextProps.cityCode, city: nextProps.city, }); const latitude = getGlobalData('latitude'); const longitude = getGlobalData('longitude'); //请求城市门店 this.getCityPoints(nextProps.cityCode, latitude, longitude); } } componentWillUnmount() { } componentDidHide() { } //请求城市门店 getCityPoints(cityCode, latitude, longitude) { Taro.showLoading({ title: '努力加载中…' }); let that = this; Netservice.request({ url: 'heque-eat/eat/storeList', method: 'POST', data: { cityCode: cityCode, longitude: longitude, latitude: latitude }, success: function (res) { Taro.hideLoading(); let pointList = res.data; if (pointList.length <= 0) { that.setState({ noShop: true, }) } else { that.setState({ noShop: false, }) } pointList.sort(function (point1, point2) { return point1.number - point2.number }); // 修改时间 for (let point of pointList) { let { foodTime1, foodTime2, foodTime3, foodTime4 } = point; point.suppleTime1 = foodTime1 ? (foodTime1.slice(0, 5) + '-' + foodTime1.slice(11, 16)) : ''; point.suppleTime2 = foodTime2 ? '/ ' + (foodTime2.slice(0, 5) + '-' + foodTime2.slice(11, 16)) : ''; point.suppleTime3 = foodTime3 ? '/ ' + (foodTime3.slice(0, 5) + '-' + foodTime3.slice(11, 16)) : ''; point.suppleTime4 = foodTime4 ? '/ ' + (foodTime4.slice(0, 5) + '-' + foodTime4.slice(11, 16)) : ''; } that.setState({ pointList: pointList }) }, error: function (err) { Taro.hideLoading(); } }) } render() { let { pointList, city, noShop } = this.state; const points = pointList.map((value, index) => { return <View className='pl-item' key={value.id} onClick={this.toOrder.bind(this, value)}> <View className='plih-img_wrap'> {value.state?<Image src={ value.storeUrl!==null && value.storeUrl!=='' ? value.storeUrl : default_store_img } className='plih-img' />: <Image src={resting} className='plih-img' />} </View> <View className='pli_item_content'> <View className='pliht-view'> <Text className='pliht-view_name'>{value.name}</Text> </View> <View className='pli-address_wrap'> <View className='pli-address'>{value.adds}</View> <View className='pliht-distance'> {value.number >= 1000 ? <Text> {(value.number / 1000).toFixed(1)}<Text className='points_distance_unit'> km</Text> </Text> : <Text >{value.number}<Text className='points_distance_unit'> m</Text></Text> } </View> </View> <View className='pli-point-time'> <Text className='pli-time-title'>营业时间 :</Text> <Text>{value.suppleTime1} {value.suppleTime2} {value.suppleTime3} {value.suppleTime4}</Text> </View> </View> </View> }) return ( <View className='container-points'> {/*固定头部*/} <View className='points-header'> <View className='ph-city' onClick={this.goCitys}> <Text>{city}</Text> <Image className='ph-arrow-right' src={arrowRight} /> </View> </View> <Swiper className='points-swiper' circular autoplay interval={3000}> <SwiperItem className='points-swiper_Item'> <Image className='points_swiper_image' src={banner1} onClick={this.goEarn.bind(this)} /> </SwiperItem> <SwiperItem > <Image className='points_swiper_image' src={banner2} onClick={this.goLend.bind(this)} /> </SwiperItem> <SwiperItem > <Image className='points_swiper_image' src={banner3} onClick={this.goPartTimeMakeMoney.bind(this)} /> </SwiperItem> <SwiperItem > <Image className='points_swiper_image' src={banner4} onClick={this.goAssistant.bind(this)} /> </SwiperItem> </Swiper> {/*取餐地点列表*/} {!noShop ? <View className='points-list'> <View className='nearbyShop'>附近商家</View> {points} </View> : <Image src={noServiceImg} className='points_noServiceImg' style='pointer-events: none' /> } </View> ) } toOrder(point, e) { let storesDetails = JSON.stringify(point); Taro.navigateTo({ url: '/pages/home_components/package_or_buy/package_or_buy?storesDetails=' + storesDetails }); } goCitys(e) { Taro.navigateTo({ url: '/pages/points/citys/citys' + '?v=' + new Date().getTime() }) } //外快 goEarn(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: '/pages/wish/earn/earn' + '?v=' + new Date().getTime() }) } else { Taro.navigateTo({ url: '/pages/login/login' + '?v=' + new Date().getTime() }) } } //周转 goLend(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: '/pages/wish/lend/lend' + '?v=' + new Date().getTime() }) } else { Taro.navigateTo({ url: '/pages/login/login' + '?v=' + new Date().getTime() }) } } //当副班 goPartTimeMakeMoney(e) { e.stopPropagation(); let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: '/pages/wish/car/car' + '?v=' + new Date().getTime() }) } else { Taro.navigateTo({ url: '/pages/login/login' + '?v=' + new Date().getTime() }) } } //招副班 goAssistant(e) { let userId = localStorage.getItem('userId'); if (userId) { Taro.navigateTo({ url: '/pages/wish/assistant/assistant' + '?v=' + new Date().getTime() }) } else { Taro.navigateTo({ url: '/pages/login/login' + '?v=' + new Date().getTime() }) } } }<file_sep>/src/pages/my/order_history/the_order_details/the_order_details.js import Taro, { Component } from '@tarojs/taro'; import { View, Text, Image } from '@tarojs/components'; import './the_order_details.css?v=20190627107' import iconNavgation from '../../../../images/common/navigat_img.png' import iconPhone from '../../../../images/common/icon_phone_point.png' import spacing from '../../../../images/take/divider_line.png' import refundDispose from '../../../../images/my/refundDispose.png' import revocationBtn from '../../../../images/my/revocation_btn.png' import serviceBotton from '../../../../images/my/service_botton.png' import payment_btn from '../../../../images/my/payment_btn.png' import { calculateDistance } from '../../../../utils/utils' import Netservice from '../../../../netservice.js'; import Common from '../../../../common.js' import { payment } from '../../../../utils/payment.js' //优惠券组件 import Prize from '../../../prize/prize.js?v=20190717110' import NoPrize from '../../../noprize/noprize.js?v=20190717110' import TooltipCoupon from '../../../tooltipCoupon/tooltipCoupon.js?v=20190626110' import { getGlobalData, setGlobalData } from '../../../../utils/global_data' // 引入微信js-sdk import JSWX from '../../../../libs/jweixin-1.4.0'; export default class TheOrderDetails extends Component { config = { navigationBarTitleText: '订单详情', navigationBarTextStyle: 'white', navigationBarBackgroundColor: '#FF7400', } state = { listData: {}, //订单详情信息 orderState: [ { id: 1, state: '待支付' }, { id: 2, state: '支付失败' }, { id: 3, state: '已支付' }, { id: 4, state: '已取消' }, { id: 5, state: '退款处理中' }, { id: 6, state: '退款申请失败' }, { id: 7, state: '退款成功' }, { id: 8, state: '拒绝退款' }, { id: 9, state: '取消退款' }, ], orderStatelist: '', orderId: '', //订单Id dishesList: [],//菜品列表 paymentPrice: '', //支付的金额 discountPrice: '', //优惠券金额 foodTime1: '', foodTime2: '', //供餐时间 foodTime3: '', foodTime4: '', distance: '', //距离 //支付后 红包/优惠券 couponList: [], zeroCouponIds: [], //零元优惠券,用来置为已读 showPrize: false, //是否显示抽奖/开奖弹框 showCoupon: false, //是否显示优惠券弹框 showNoPrize: false, //是否显示没奖弹框 tapThePrize: false, //是否点击抽奖/开奖弹框 } componentWillMount() { this.getWeChatJSApiParam(); Taro.showLoading({ title: '努力加载中…' }); let orderId = this.$router.params.orderId; this.setState({ orderId: orderId }) } componentDidShow() { Taro.hideLoading(); this.getOrderDetails(); } render() { let { listData, orderState, dishesList, foodTime1, foodTime2, foodTime3, foodTime4, distance, couponList, showPrize, showCoupon, showNoPrize, tapThePrize } = this.state; let takeMealsState = <View className='top_message'> {/*5为申请退款处理中*/} {listData.state !== 5 ? <View className='padding_18'> {/*订单状态*/} {orderState.map((item, index) => { return <View className='details_state_of_payment' key={index}> {listData.state === item.id ? item.state : ''} </View> }) } <View className='thank'>感谢您使用禾师傅</View> </View> : <View className='padding_18'> <View className='refundDispose_titl'> {listData.state == 5 && '退款处理中'} </View> <Image src={refundDispose} className='refundDispose_img' style='pointer-events: none' /> <View className='revocation_btn' onClick={this.refundDispose.bind(this)}> <Image src={revocationBtn} className='revocation_btn_img' /> </View> </View> } </View> let TakeFoodCode = <View className='top_message'> {listData.state == 4 && <View className='padding_18'> <View className='details_state_of_payment'>已取消</View> <View className='thank'>感谢您使用禾师傅</View> </View> } {listData.state === 3 && <View> {/*是否完成取餐 0未完成 1完成 */} {listData.istakemeal == 0 ? <View className='padding_18'> <View className='TakeFoodCode'>取餐码</View> <View className='details_state_of_payment'>{listData.takeMealCode}</View> <View className='thank'>感谢您使用禾师傅</View> </View> : <View className='padding_18'> <View className='details_state_of_payment'>已取餐</View> <View className='thank'>取餐码:{listData.takeMealCode}</View> <View className='thank'>感谢您使用禾师傅</View> </View> } </View> } {listData.state == 2 && <View className='padding_18'> <View className='details_state_of_payment'>支付失败</View> <View className='thank'>感谢您使用禾师傅</View> </View> } {listData.state == 1 && <View className='padding_18'> <View className='details_state_unpaid_title'>待支付</View> <View className='details_state_unpaid_hint'> <Text>30分钟内未支付成功,订单将自动</Text> <Text className='details_state_unpaid_cancel_btn' onClick={this.toCancle.bind(this)}>取消</Text> </View> <View className='details_state_unpaid_payment_btn' onClick={this.goWechatPay2.bind(this)}> <Image src={payment_btn} className='details_state_unpaid_payment_btn_img' /> </View> </View> } </View> //菜品数据 let dishes = dishesList.map((item, index) => { return <View className='classify' key={index}> <View className='dish_name'> <View className='title_name'>{item.dishesName}</View> </View> <View className='classify_number'>X{item.number}</View> <View className='classify_price'>¥ {item.paymentPrice}</View> </View> }) return ( <View className='TheOrderDetails_hTML'> <View className='TheOrderDetails'> {listData.state <= 4 ? TakeFoodCode : takeMealsState} <Image src={spacing} className='spacing_img' style='pointer-events: none' /> <View className='location'> <View className='rade_name_wrap'> <View className='rede_name'>{listData.storeName}</View> <View className='location_right'> {/*<View className='location_img_wrap margin-l_18' onClick={this.contactUs.bind(this)}> <Image className='location_img' src={iconPhone} style='pointer-events: none' /> </View>*/} <View className='location_img_wrap' onClick={this.navigate.bind(this)}> <Image className='location_img' src={iconNavgation} style='pointer-events: none' /> </View> </View> </View> <View className='site'> <Text className='rade_distance'>距您{distance}</Text> {listData.storeAddress}</View> <View className='rade_time'> <View>供餐时间:</View> <View className='rade_time_content'>{foodTime1} {foodTime2} {foodTime3} {foodTime4}</View> </View> </View> <Image src={spacing} className='spacing_img' style='pointer-events: none' /> <View className='commodityList'> {dishes} <View className='discount_coupon'> <View className='discount_coupon_title'>优惠券</View> <View className='subtract'>- ¥{listData.discountPrice}</View> </View> <View className='total'> <View className='total_title'>合计</View> <View className='total_price'><Text className='total_symbol'>¥ </Text>{listData.paymentPrice}</View> </View> </View> <Image src={spacing} className='spacing_img' style='pointer-events: none' /> <View className='createTime_orderNo'> <View className='createTime'>下单时间:{listData.createTime}</View> <View className='orderNo'>订单编号:{listData.orderNo}</View> {listData.channelType == 1 && <View className='orderNo'>下单方式:APP </View>} {listData.channelType == 2 && <View className='orderNo'>下单方式:公众号 </View>} {listData.channelType == 3 && <View className='orderNo'>下单方式:web </View>} {listData.channelType == 4 && <View className='orderNo'>下单方式:小程序 </View>} {listData.state >= 3 && listData.state !== 4 ? <View className='orderNo'>支付方式:微信支付</View> : ''} </View> </View> <View className='service_botton' onClick={this.myService.bind(this)}> <Image src={serviceBotton} className='service_botton_img' /> </View> <View className='service_hint'>客服工作时间 09:00-18:00</View> {showPrize && <Prize onTapThePrize={this.tapThePrize.bind(this)} />} {showCoupon && tapThePrize && <TooltipCoupon couponsData={couponList} notScroll={0} afterClose={0} />} {showNoPrize && tapThePrize && <NoPrize onTapNoPrize={this.closeNoPrize.bind(this)} onTapClose={this.closeNoPrize.bind(this)} />} </View> ) } //当为退款状态是调用的 撤销退款申请 refundDispose(e) { let orderId = this.state.orderId; let that = this; Taro.showModal({ title: '确定撤销?', content: '撤销后无法再次申请', success: function (res) { if (res.confirm) { // 发起取消撤销退款申请 Netservice.request({ url: 'heque-eat/wechat_pay/wechat_pay_revoke_refund', method: 'GET', data: { id: orderId, }, success: res => { if (res.code === Common.NetCode_NoError) { that.getOrderDetails(); } } }) } } }) } //获取微信JS接口参数 getWeChatJSApiParam() { Netservice.request({ url: 'heque-eat/we_chat_public_number/get_signature' , method: 'GET', data:{ url:encodeURIComponent(location.href.split('#')[0]) }, success: res => { JSWX.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: 'wxed1d300ad50d204f', // 必填,企业号的唯一标识,此处填写企业号corpid timestamp: res.data.timestamp, // 必填,生成签名的时间戳(10位) nonceStr: res.data.nonceStr, // 必填,生成签名的随机串,注意大小写 signature: res.data.signature,// 必填,签名, jsApiList: ['chooseWXPay', 'openLocation', 'getLocation'] // 必填,需要使用的JS接口列表, }); JSWX.ready(function () { JSWX.error(function (err) { console.log("config信息验证失败,err=" + JSON.stringify(err)); }); }); } }) } //微信支付 goWechatPay2(e) { e.stopPropagation(); // Taro.showLoading({ title: '努力加载中…' }); let that = this; let orderData = this.state.listData; let dishesList = this.state.dishesList[0]; const openId = localStorage.getItem('openId'); //支付接口 payment({}, orderData.id, dishesList.paymentPrice, openId, () => { //支付成功时,刷新页面 that.getOrderDetails(); }, () => { //支付取消 Taro.showToast({ title: '支付取消', icon: 'none', duration: 2000 }); that.getOrderDetails(); }, () => { //支付失败 Taro.showToast({ title: '支付失败', icon: 'none', duration: 2000 }); that.getOrderDetails(); } ); } // 取消订单弹窗 toCancle(e) { e.stopPropagation(); let that = this; Taro.showModal({ content: '确定取消订餐?', success(res) { if (res.confirm) { that.cancleOrder() } } }) } // 取消订单 cancleOrder() { let that = this; Taro.showLoading({ title: '努力加载中…' }); let orderData = this.state.listData; Netservice.request({ url: 'heque-eat/eat/delete_order', method: 'GET', data:{ id: orderData.id }, success: res => { Taro.hideLoading(); if (res.code == Common.NetCode_NoError) that.getOrderDetails(); else Taro.showToast({ title: res.message, icon: 'none', duration: 2000 }); }, fail: function (error) { Taro.hideLoading(); Taro.showToast({ title: '取消订单失败', icon: 'none', duration: 2000 }); } }) } //导航 navigate(e) { const currentPoint = this.state.listData; JSWX.openLocation({ latitude: currentPoint.latitude, longitude: currentPoint.longitude, name: currentPoint.name, address: currentPoint.adds, }) } //联系商家 contactUs(e) { e.stopPropagation(); Taro.makePhoneCall({ phoneNumber: String(this.state.listData.storePhoneNumber) }) } //去客服 myService(e) { let listDataState = this.state.listData.state; let paymentPrice = this.state.paymentPrice; let discountPrice = this.state.discountPrice; let dishesList = JSON.stringify(this.state.dishesList); let orderId = this.state.orderId; localStorage.setItem('listDataState', listDataState); localStorage.setItem('dishesList', dishesList); Taro.navigateTo({ url: '/pages/my/service/service?dishesList=' + dishesList + '&listDataState=' + listDataState + '&orderId=' + orderId + '&paymentPrice=' + paymentPrice + '&discountPrice=' + discountPrice + '&v=' + new Date().getTime() }) } //获取订单详情 getOrderDetails() { let that = this; Netservice.request({ url: 'heque-eat/eat/user_order_details_info', method: 'GET', data: { id: that.state.orderId, }, success: function (res) { let listData = res.data; //截取时间 let foodTime1 = listData.foodTime1 ? (listData.foodTime1.slice(0, 5) + '-' + listData.foodTime1.slice(11, 16)) : ''; let foodTime2 = listData.foodTime2 ? '/ ' + (listData.foodTime2.slice(0, 5) + '-' + listData.foodTime2.slice(11, 16)) : ''; let foodTime3 = listData.foodTime3 ? '/ ' + (listData.foodTime3.slice(0, 5) + '-' + listData.foodTime3.slice(11, 16)) : ''; let foodTime4 = listData.foodTime4 ? '/ ' + (listData.foodTime4.slice(0, 5) + '-' + listData.foodTime4.slice(11, 16)) : ''; //订单状态 let orderState = localStorage.getItem('orderState'); const latitude = localStorage.getItem('latitude'); const longitude = localStorage.getItem('longitude'); listData.number = calculateDistance({ latitude: res.data.latitude, longitude: res.data.longitude }, { latitude: latitude, longitude: longitude }); that.setState({ listData: listData, dishesList: res.data.list, paymentPrice: listData.paymentPrice, discountPrice: listData.discountPrice, foodTime1, foodTime2, foodTime3, foodTime4, distance: listData.number, }) //判断订单列表是否刷新 true刷新 false不刷新 if (Number(orderState) !== Number(listData.state)) { setGlobalData('orderStateChanged', true); } if (listData.state == 3) { //查优惠券 that.getCoupons(); } } }) } //查询未领取的优惠券 getCoupons() { let userId = localStorage.getItem('userId'); if (!userId) return; let that = this; Netservice.request({ url: 'heque-coupon/discount_coupon/get_not_read', method: 'GET', data:{ userId }, success: res => { if (res.code == Common.NetCode_NoError) { let coupons = res.data; let prizes = coupons.filter(function (ele) { return ele.receiveType == 3 }); let prizeValue = 0; if (prizes.length > 0) { let prize = prizes[0]; prizeValue = prize.faceValue; } let zeroCouponIds = []; prizes.map((item, index) => { // if (item.faceValue <= 0) //零元券 zeroCouponIds.push(item.id) //自动领取 }) if (zeroCouponIds.length > 0) that.readCoupons(zeroCouponIds); that.setState({ couponList: prizes, zeroCouponIds: zeroCouponIds, showPrize: prizes.length > 0, // showPrize: true, showCoupon: ((prizes.length > 0) && (prizeValue > 0)), //是否显示优惠券弹框 showNoPrize: ((prizes.length > 0) && (prizeValue <= 0)), }); } } }) } //点击开红包 tapThePrize(e) { this.setState({ tapThePrize: true }); setTimeout(() => { this.setState({ showPrize: false }); }, 2200); // const { couponList } = this.state; // let couponIds = []; // couponList.map((item, index) => { // couponIds.push(item.id) // }) // //自动领取 // if (couponIds.length > 0) // this.readCoupons(couponIds); } //没中奖 closeNoPrize(e) { this.setState({ showNoPrize: false, }); } //修改已读优惠券 readCoupons(ids) { let cardIds = ids.join(','); Netservice.request({ url: 'heque-coupon/discount_coupon/user_has_read', method: 'GET', data: { userCardMedalId: cardIds }, success: (res) => { } }) } } <file_sep>/src/pages/index/summer_topic/summer_topic.js import './summer_topic.css'; import Taro, { Component } from '@tarojs/taro'; import { View, Text, Image } from '@tarojs/components'; import summer_top_img from '../../../images/home/summer_top.png' import summer_bottom_img from '../../../images/home/summer_bottom.png' export default class SummerTopic extends Component { config = { navigationBarTitleText: '入夏上新 禾家丰盛', } state = { showCoupon: false, //是否显示优惠券弹框 couponList: [], }; componentWillMount() { } componentDidMount() { } componentWillUnmount() { } componentDidShow() { } componentDidHide() { } render() { return (<View className='container-summer'> <Image className='summer-top-img' src={summer_top_img} mode='widthFix' style='pointer-events: none'/> <View className='summer-middle-view'> <Text className='smmv-text'>&nbsp;&nbsp;&nbsp;&nbsp;清脆的蝉鸣,此起彼伏的蛙声,田间绿色的麦田,满天星光萤火虫......这是自然给予我们夏天独有的馈赠。万物生长是夏天的篇章,也是禾师傅发展的主旋律。</Text> <Text className='smmv-text'>&nbsp;&nbsp;&nbsp;&nbsp;今夏,禾师傅带着“司机工作餐”在广州、深圳、杭州、无锡四大城市相继亮相。本着“更快捷、更实惠、更健康”的发展宗旨,禾师傅打开了司机餐饮发展新方向,通过大数据智能餐饮系统,科学合理的健康饮食搭配,有效缓解司机就餐停车难、就餐环境差、饮食不规律、营养不均衡等问题。“让每一位司机拥有健康轻松车生活”是禾师傅发展愿景。未来,禾师傅在提供司机工作餐服务基础上,将不断扩大自身服务范围,丰富自身业务版块,为司机群体建立一站式综合服务智能生态圈。</Text> <Text className='smmv-text'>&nbsp;&nbsp;&nbsp;&nbsp;以夏立新,以餐饮立足司机服务,禾师傅将如花繁叶茂的夏天般欣欣向荣。</Text> </View> <Image className='summer-bottom-img' src={summer_bottom_img} mode='widthFix' style='pointer-events: none'/> </View>) } goBack() { Taro.navigateBack() } }<file_sep>/.temp/pages/index/index.js import Nerv from "nervjs"; import './index.css?v=201907017111'; import Taro, { getSystemInfo as _getSystemInfo, showLoading as _showLoading, hideLoading as _hideLoading, showModal as _showModal, switchTab as _switchTab } from "@tarojs/taro-h5"; import { View, Text, Image } from '@tarojs/components'; import Netservice from "../../netservice"; import Common from "../../common"; import { setGlobalData, getGlobalData } from '../../utils/global_data'; import { getUrlParam } from '../../utils/utils'; import iconNopay from '../../images/home/icon_nopay.png'; import iconClose from '../../images/home/icon_close.png'; import close_btn from '../../images/home/newEdition/close_btn.png'; import goEarn_btn from '../../images/home/newEdition/goEarn_btn.png'; import new_edition_bg from '../../images/home/newEdition/new_edition_bg.png'; //城市门店列表 import HomePoints from '../home_components/home_points/home_points.js?v=2019072411'; //门店菜品列表 import PointPackage from '../home_components/point_package/point_package.js?v=2019072411'; //输入金额下单 import PointBuy from '../home_components/point_buy/point_buy.js?v=2019072411'; //优惠券弹框 import TooltipCoupon from '../tooltipCoupon/tooltipCoupon.js?v=2019072411'; // 引入微信js-sdk import JSWX from '../../libs/jweixin-1.4.0'; export default class Index extends Taro.Component { config = { navigationBarTitleText: '点餐' }; state = { enterType: 0, //进店方式: 1 公众号进入 2 扫描店铺二维码进入 pointType: 0, //店铺类型,1:选菜下单,2:输入金额下单 currentPoint: {}, //当前所选取餐点 nearestId: 0, //最近的门店id hasNoPaidOrder: false, //有尚未支付的订单 showCoupon: false, //是否显示未领取的优惠券弹框 couponList: [], cityCode: '', city: '', ordersId: '', //订单id showNewEdition: false //新版本弹框 }; componentWillMount() { const enterType = getGlobalData('enterType') || 0; if (enterType != 0) this.setState({ enterType: enterType }); const cityCode = getGlobalData('cityCode') || ''; const city = getGlobalData('city') || ''; if (cityCode.length < 2) { //默认用深圳 setGlobalData('cityCode', '440300'); setGlobalData('city', '深圳'); setGlobalData('latitude', 22.53332); setGlobalData('longitude', 113.93041); localStorage.setItem('cityCode', '440300'); localStorage.setItem('city', '深圳'); localStorage.setItem('latitude', 22.53332); localStorage.setItem('longitude', 113.93041); } //使用历史选择 if (enterType == 1 && cityCode.length > 0) { this.setState({ cityCode: cityCode, city: city }); } else if (enterType == 2) { const currentPoint = getGlobalData('currentPoint') || {}; if (currentPoint.name) { this.setState({ currentPoint: currentPoint, pointType: currentPoint.feeType, enterType: 2 }); } else { //扫码直接到店 const pointId = getUrlParam('pid'); if (pointId) { this.getThePoint(pointId); } else { this.setState({ enterType: 1 }); setGlobalData('enterType', 1); } } } else if (enterType == 0) { //扫码直接到店 const pointId = getUrlParam('pid'); if (pointId) { this.getThePoint(pointId); } else { this.setState({ enterType: 1 }); setGlobalData('enterType', 1); } } // https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed1d300ad50d204f&redirect_uri=http%3A%2F%2Fwxgzhtest.hequecheguanjia.com%3Fpid%3D36&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect // let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed1d300ad50d204f&redirect_uri=' + encodeURIComponent('http://wxgzhtest.hequecheguanjia.com?pid=36') + '&response_type=code&scope=snsapi_base&state=1#wechat_redirect'; //手动初始化 setGlobalData('currentCoupon', {}); setGlobalData('notUseCoupon', false); //授权定位 this.getWeChatJSApiParam(); //查询进行中的订单和优惠券 let userId = localStorage.getItem('userId'); if (userId) { this.getGoingOrders(); this.getCoupons(); } _getSystemInfo({ success: res => { localStorage.setItem('systemInfo', JSON.stringify(res)); } }); } componentDidMount() {} componentWillUnmount() {} componentDidShow() { //查询进行中的订单和优惠券 let userId = localStorage.getItem('userId'); if (userId) { this.getGoingOrders(); this.getCoupons(); } let showNewEdition = localStorage.getItem('showNewEdition'); let that = this; if (userId !== null) { //新版本弹框 Netservice.request({ url: 'heque-backend/collect/queryIsPop', method: 'GET', data: { userId: userId }, success: res => { if (res.data == 0 && showNewEdition == null) { that.setState({ showNewEdition: true }); } else { that.setState({ showNewEdition: false }); } } }); } else { if (userId == null && showNewEdition == 1) { that.setState({ showNewEdition: false }); } else { that.setState({ showNewEdition: true }); } } //切换城市 const cityChanged = getGlobalData('cityChanged') || false; if (cityChanged) { setGlobalData('cityChanged', false); const cityCode = getGlobalData('cityCode1'); const city = getGlobalData('city1'); this.setState({ enterType: 1, cityCode, city }); setGlobalData('enterType', 1); setGlobalData('cityCode', cityCode); setGlobalData('city', city); } //切换门店 const pointChanged = getGlobalData('pointChanged') || false; if (pointChanged) { setGlobalData('pointChanged', false); const currentPoint = getGlobalData('currentPoint'); this.setState({ enterType: 2, currentPoint: currentPoint, pointType: currentPoint.feeType }); setGlobalData('enterType', 2); } //切换优惠券 const couponChanged = getGlobalData('couponChanged') || false; if (couponChanged) { setGlobalData('couponChanged', false); const currentCoupon = getGlobalData('currentCoupon') || {}; this.setState({ currentCoupon: currentCoupon }); } } componentDidHide() {} //用ID直接获取门店信息 getThePoint(pId) { _showLoading({ title: '努力加载中…' }); let that = this; const latitude = getGlobalData('latitude') || 0; const longitude = getGlobalData('longitude') || 0; Netservice.request({ url: 'heque-eat/eat/queryDetailByStoreId', method: 'GET', data: { storeId: pId, longitude: longitude, latitude: latitude }, success: function (res) { _hideLoading(); if (res.code == Common.NetCode_NoError) { let point = res.data; setGlobalData('currentPoint', point); that.setState({ nearestId: point.id, enterType: 2, currentPoint: point, pointType: point.feeType }); setGlobalData('enterType', 2); } else { that.setState({ enterType: 1 }); setGlobalData('enterType', 1); //授权定位 that.getWeChatJSApiParam(); } }, error: function (err) { _hideLoading(); that.setState({ enterType: 1 }); setGlobalData('enterType', 1); //授权定位 that.getWeChatJSApiParam(); } }); } //获取未取餐订单列表 getGoingOrders() { let userId = localStorage.getItem('userId'); Netservice.request({ url: 'heque-eat/eat/no_meal_order_info?userId=' + userId, method: 'GET', success: res => { let orders = res.data; let hasNoPaidOrder = false; orders.map(item => { //hasNoPaidOrder == true, 有未支付的订单 if (item.state === 1 || item.state === 2) hasNoPaidOrder = true; this.setState({ ordersId: item.id }); }); this.setState({ hasNoPaidOrder }); } }); } //获取未领取的优惠券 getCoupons() { let userId = localStorage.getItem('userId'); Netservice.request({ url: 'heque-coupon/discount_coupon/get_not_read?userId=' + userId, method: 'GET', success: res => { let results = res.data; let coupons = results.filter(function (ele) { return ele.faceValue > 0; }); this.setState({ showCoupon: coupons.length > 0, couponList: coupons }); } }); } //获取微信JS接口参数 getWeChatJSApiParam() { let that = this; Netservice.request({ url: 'heque-eat/we_chat_public_number/get_signature?url=' + encodeURIComponent(location.href.split('#')[0]), method: 'GET', success: res => { JSWX.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: Common.AppId, // 必填,企业号的唯一标识,此处填写企业号corpid timestamp: res.data.timestamp, // 必填,生成签名的时间戳(10位) nonceStr: res.data.nonceStr, // 必填,生成签名的随机串,注意大小写 signature: res.data.signature, // 必填,签名, jsApiList: ['getLocation', 'updateAppMessageShareData', 'updateTimelineShareData', 'chooseWXPay'] // 必填,需要使用的JS接口列表, }); JSWX.ready(function () { JSWX.error(function (err) { console.log("config信息验证失败,err=" + JSON.stringify(err)); that.locationFailed(); }); JSWX.getLocation({ type: 'gcj02', //火星坐标:中国国内使用的被强制加密后的坐标体系,高德坐标就属于该种坐标体系。 success: function (res1) { localStorage.setItem('latitude', res1.latitude); localStorage.setItem('longitude', res1.longitude); setGlobalData('latitude', res1.latitude); setGlobalData('longitude', res1.longitude); Netservice.request({ url: 'heque-eat/eat/get_city_code_and_city?latitude=' + res1.latitude + '&longitude=' + res1.longitude, method: 'GET', success: res2 => { let cityCode1 = res2.data.cityCode || '440300'; let city1 = res2.data.city || '深圳市'; setGlobalData('cityCode', cityCode1); setGlobalData('city', city1); setGlobalData('locationCity', city1); let { enterType, cityCode } = that.state; if (enterType == 1 && cityCode.length < 2 || enterType == 0) that.setState({ cityCode: cityCode1, city: city1 }); }, error: function (err) { console.log('获取城市失败'); that.locationFailed(); } }); }, cancel: function (res3) { console.log('用户拒绝授权获取位置'); that.locationFailed(); }, error: function (res4) { console.log('定位出错了'); that.locationFailed(); }, fail: function (res5) { console.log('定位失败了'); that.locationFailed(); } }); //分享给好友 JSWX.updateAppMessageShareData({ title: Common.ShareTitle, // 分享标题 desc: Common.ShareDesc, // 分享描述 link: Common.ShareWebsite, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: Common.ShareImgUrl, // 分享图标 success: function () {} }); //分享到朋友圈 JSWX.updateTimelineShareData({ title: Common.ShareTitle, // 分享标题 link: Common.ShareWebsite, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: Common.ShareImgUrl, // 分享图标 success: function () {} }); }); } }); } locationFailed() { let that = this; const enterType = getGlobalData('enterType') || 0; const cityCode = getGlobalData('cityCode') || ''; const currentPoint = getGlobalData('currentPoint') || {}; if (enterType == 0 || enterType == 1 && cityCode.length < 2 || enterType == 2 && !currentPoint.name) { _showModal({ title: '请选择城市', content: '获取定位失败,请手动选择城市', confirmText: '去选择', showCancel: false, success(res) { if (res.confirm) that.goSelectCity(); } }); } } goSelectCity() { Taro.navigateTo({ url: "/pages/points/citys/citys?v=" + new Date().getTime() }); } render() { let { enterType, pointType, currentPoint, hasNoPaidOrder, showCoupon, couponList, currentCoupon, cityCode, city, showNewEdition } = this.state; //有没支付订单 const noPayView = <View className="nopay-view"> <View className="npv-content"> <Image className="npvc_img" mode="aspectFill" src={iconNopay} style="pointer-events: none" /> <Text className="npvc_info">当前存在未支付订单</Text> <Text className="npvc_todo">请先完成支付</Text> <Text className="npvc_gopay" onClick={this.goToPay.bind(this)}>去支付</Text> </View> <Image className="npvc_close" mode="aspectFill" src={iconClose} onClick={this.closeNoPayView.bind(this)} /> </View>; //新版本弹框 const newEdition = <View className="newEdition"> <View className="newEdition_content"> <Image src={new_edition_bg} className="newEdition_conetent_bg" style="pointer-events: none" /> <View className="newEdition_goEarn_btn_wrap" onClick={this.goEarnBtn.bind(this)}> <Image src={goEarn_btn} className="newEdition_goEarn_btn_img" style="pointer-events: none" /> </View> <View className="newEdition_close_btn_wrap" onClick={this.closeBtn.bind(this)}> <Image src={close_btn} className="newEdition_close_btn_img" style="pointer-events: none" /> </View> </View> </View>; { showNewEdition && newEdition; } return <View className="container-index"> {enterType == 1 && cityCode.length > 0 && <HomePoints cityCode={cityCode} city={city} />} {enterType == 2 && <View className="index_component_wrap"> {pointType == 1 && currentPoint.name && <PointPackage className="PointPackage" currentPoint={currentPoint} />} {pointType == 2 && currentPoint.name && <PointBuy className="PointBuy" currentPoint={currentPoint} currentCoupon={currentCoupon} />} </View>} {hasNoPaidOrder && !showNewEdition && noPayView} {showCoupon && !showNewEdition && <TooltipCoupon couponsData={couponList} afterClose={0} onCloseCouponView={this.closeCouponView.bind(this)} />} </View>; } closeNoPayView(e) { e.stopPropagation(); this.setState({ hasNoPaidOrder: false }); } closeCouponView(e) { this.setState({ showCoupon: false }); } goPackageBuy(item, e) { e.stopPropagation(); let price = item.specialOffer || item.originalPrice; let priceType = price === item.specialOffer ? 2 : 1; let dishInfo = encodeURIComponent(JSON.stringify({ dishUrl: item.dishesUrl, dishName: item.dishName, dishPricee: price, priceType: priceType, dishId: item.dishId, eatEverydayDishesDishesId: item.eatEverydayDishesDishesId })); Taro.navigateTo({ url: '/pages/booking/booking?dishInfo=' + dishInfo + '&v=' + new Date().getTime() }); } goToPay(e) { e.stopPropagation(); let orderId = this.state.ordersId; Taro.navigateTo({ url: '/pages/my/order_history/the_order_details/the_order_details?orderId=' + orderId + '&v=' + new Date().getTime() }); } goToPoints(e) { e.stopPropagation(); // Taro.navigateTo({ url: '/pages/points/points' + '?v=' + new Date().getTime() }) } //新版本弹框 去赚钱页 goEarnBtn(e) { e.stopPropagation(); this.setState({ showNewEdition: false }); localStorage.setItem('showNewEdition', 1); _switchTab({ url: '/pages/wish/wish' }); } //新版本弹框 关闭按钮 closeBtn(e) { e.stopPropagation(); this.setState({ showNewEdition: false }); localStorage.setItem('showNewEdition', 1); } }<file_sep>/src/pages/my/service/apply_for_after_sales/apply_for_after_sales.js import Taro, { Component } from '@tarojs/taro' import { View, Text, Image, Textarea } from '@tarojs/components' import './apply_for_after_sales.css?v=201906141107' import Netservice from '../../../../netservice.js' import Common from '../../../../common.js' import checked from '../../../../images/service/checked.png' import checkedNo from '../../../../images/service/checkedNo.png' import success from '../../../../images/service/success.png' import return_btn from '../../../../images/service/return_btn.png' import submit_btn from '../../../../images/service/submit_btn.png' import arrow from '../../../../images/my/arrow.png' export default class ApplyForAfterSales extends Component { config = { navigationBarTitleText: '申请售后', navigationBarTextStyle: 'white', navigationBarBackgroundColor: '#31B1B0', } state = { dishesList: [], //菜品数据 paymentPrice: '', //退款总金额 discountPrice: '', //优惠券金额 value: '', //输入框的值 showOption: false, // 显示退款原因 reasonList: [], //原因列表 checkedId: '', //选中的原因 checkedContent: '', submitSuccessState: false, //提交后的显示页面,true显示 orderId: '', //订单ID system: 'android', //系统 } componentWillMount() { Netservice.request({ url: 'heque-eat/complaint_details/complaint_or_refund_options', method: 'GET', data: { type: 2, }, success: res => { let reasonList = res.data; //显示弹出层数据 this.setState({ reasonList: reasonList, }) } }) let dishesList = JSON.parse(localStorage.getItem('dishesList')); let paymentPrice = this.$router.params.paymentPrice; let orderId = this.$router.params.orderId; let discountPrice = this.$router.params.discountPrice; this.setState({ dishesList: dishesList, orderId: orderId, paymentPrice: paymentPrice, discountPrice: discountPrice, }) Taro.getSystemInfo({ success: res => { this.setState({ system: res.system }); } }); } componentDidMount(){ } render() { let that = this; const { dishesList, paymentPrice, showOption, reasonList, submitSuccessState, checkedId, checkedContent, discountPrice } = this.state; //退款原因组件 let reasonOption = <View className='reasonOption'> <View className='reasonOption_wrap'> <View className='reasonOption_title_hint'>为了便于客服处理,请填写真实原因</View> <View className='reasonOption_contnet_list'> {reasonList.map((item, index) => { return <View className='reasonOption_list_message' key={index} onClick={this.reasonOptionContent.bind(that, item)}> <Text className='reasonOption_list_title'>{item.content}</Text> {checkedId === item.id ? <Image className='reasonOption_icon' src={checked} style='pointer-events: none' /> : <Image className='reasonOption_icon' src={checkedNo} style='pointer-events: none' />} </View> }) } </View> <View className='reasonOption_button' onClick={this.offRefundReason.bind(this)}>取消</View> </View> </View> //提交成功的显示页面 let submitSuccess = <View className='submitSuccess'> <View className='submitSuccess_wrap'> <Image src={success} className='submitSuccess_img' style='pointer-events: none' /> <View className='submitSuccess_content'>退款申请提交成功</View> <View className='submitSuccess_botton' onClick={this.goTheOrderDetails.bind(this)}> <Image src={return_btn} className='submitSuccess_botton_img' style='pointer-events: none' /> </View> </View> </View> return ( <View className='ApplyForAfterSales'> <View className='ApplyForAfterSales_content'> <View className='checked_number'> <Image src={checked} className='checked_img' style='pointer-events: none' /> <Text className='checked_title_text'>退全部商品</Text> </View> {dishesList.map((item, index) => { return <View key={index}> <View className='checked_dishesList' > <Text className='checked_dishesList_name'>{item.dishesName}</Text> <Text className='checked_dishesList_number'>x {item.number}</Text> <Text className='checked_dishesList_price'>¥ {item.paymentPrice}</Text> </View> <View className='checked_dishesList2'> <Text className='checked_dishesList_name'>优惠券金额</Text> <Text className='checked_dishesList_price'>¥{discountPrice}</Text> </View> </View> }) } <View className='refund_reason_wrap'> <View className='refund_reason' onClick={this.refundReason.bind(this)}> <View className='refund_reason_text'>退款原因</View> <View className='refund_reason_type'> <Text className='refund_reason_checked'>{checkedContent === null || checkedContent === '' ? '请选择(必选)' : <Text>{checkedContent}</Text>}</Text> <Image src={arrow} className='refund_reason_arrow' style='pointer-events: none' /> </View> </View> <View className='refund_reason_replenish'> <Textarea type='text' placeholder='补充详细信息以便客服更快帮您处理( 选填 ),最多140字' maxLength='140' className='refund_reason_input' onBlur={this.getInputValue.bind(that)} /> </View> </View> </View> <View className='refund_reason_confirm_button'> <View className='confirm_button_left'> <View className='refund_price'>¥ <Text className='refund_price_size'>{paymentPrice}</Text></View> <View className='refund_reminder'> <View className='refund_reminder_all_costs'>已包含快送费</View> <View className='refund_path'>退款将按原路返回</View> </View> </View> <View className='confirm_button_right' onClick={this.submitBotton.bind(this)}> <Image src={submit_btn} className='submit_btn_img'/> </View> </View> {showOption && reasonOption} {submitSuccessState && submitSuccess} </View> ) } //显示退款原因弹框 refundReason(e) { //显示弹出层 this.setState({ showOption: true, }) } //选择退款原因 reasonOptionContent(item, e) { e.stopPropagation(); let reasonList = this.state.reasonList; //选中的原因 for (let i = 0; i < reasonList.length; i++) { //相等就选中 if (item.id === reasonList[i].id) { this.setState({ checkedId: reasonList[i].id, checkedContent: reasonList[i].content, showOption: false, }) } } } //关闭退款原因弹窗 offRefundReason(e) { e.stopPropagation(); this.setState({ showOption: false }) } //输入框失焦时获取输入补充的内容 getInputValue(e) { let value = e.detail.value; this.setState({ value: value, }) let { system } = this.state; if (system.startsWith('iOS') || system.startsWith('ios')) window.scroll(0, 0); } //提交按钮 submitBotton(e) { e.stopPropagation(); let orderId = this.state.orderId; let checkedId = this.state.checkedId; let value = this.state.value; if (checkedId === null || checkedId === '') { Taro.showToast({ title: '请选择退款原因', icon: 'none', duration: 2000, }) } else { Netservice.request({ url: 'heque-eat/wechat_pay/wechat_pay_refund', data: { id: orderId, complaintsTypeId: checkedId, remark: value, fileInfoUrl: '', }, success: res => { if (res.code === Common.NetCode_NoError) { this.setState({ submitSuccessState: true, }) } } }) } } //返回订单详情 goTheOrderDetails(e) { e.stopPropagation(); Taro.navigateBack({ delta: 2 }) } }<file_sep>/.temp/pages/wish/car/myMessage/myMessage.js import Nerv from "nervjs"; import Taro, { getSystemInfo as _getSystemInfo, showToast as _showToast } from "@tarojs/taro-h5"; import { View, Input, Image, Picker, Swiper, SwiperItem } from '@tarojs/components'; import './myMessage.css'; import { AtInput } from 'taro-ui'; import Netservice from "../../../../netservice"; import { getGlobalData } from '../../../../utils/global_data'; import Common from "../../../../common"; import my_information from '../../../../images/wish/car/my_information.png'; import btn_submit from '../../../../images/wish/car/btn_submit.png'; import arrow_right from '../../../../images/common/arrow_right.png'; import banner_rent from '../../../../images/wish/car/banner_rent.png'; import default_btn_next from '../../../../images/wish/car/default_btn_next.png'; export default class MyMessage extends Taro.Component { constructor(props) { super(props); //防重复点击 this.preventRepeat = true; } config = { 'navigationBarTitleText': '当副班赚钱' }; state = { nameValue: '', //名字 numberValue: '', //手机号 ageValue: '', //年龄 nativePlaceValue: [], //籍贯省份 nativePlace: '请选择您的籍贯', //默认的籍贯提示 showNativePlaceStyle: true, //籍贯的样式 provinceData: [], //省份列表 nativePlaceValueId: 1, //籍贯id showHighLight: false, //按钮高亮 system: 'android' //系统 }; componentWillMount() { let numberValue = localStorage.getItem('phone'); if (numberValue !== '' && numberValue !== null) this.setState({ numberValue, showHighLight: true }); _getSystemInfo({ success: res => { this.setState({ system: res.system }); } }); } componentDidMount() { let provinceName = []; let that = this; Netservice.request({ url: 'heque-backend/work_driver/getProvinceAndCityList', method: 'GET', success: res => { let data = res.data; data.map(item => { provinceName.push(item.privinceName); }); that.setState({ provinceData: data, nativePlaceValue: provinceName }); } }); var h = document.body.scrollHeight; window.onresize = function () { if (document.body.scrollHeight < h) { document.getElementsByClassName("btn_submit_wrap")[0].style.display = "none"; setTimeout(() => { window.scrollTo({ top: 500, behavior: "smooth" }); // window.scroll(0, 500); // document.body && (document.body.scrollTop = 500); }, 300); } else { document.getElementsByClassName("btn_submit_wrap")[0].style.display = "block"; } }; } render() { let { nameValue, numberValue, ageValue, nativePlaceValue, nativePlace, showNativePlaceStyle, showHighLight } = this.state; return <View className="MyMessage"> <Swiper className="MyMessage_swiper" circular autoplay={false} interval={3000} style="width:84%"> <SwiperItem className="MyMessage_SwiperItem" style="width:100%"> <Image className="MyMessage_swiper_image" src={banner_rent} style="pointer-events: none; width:100%" /> </SwiperItem> {/* <SwiperItem className='pt2_SwiperItem' onClick={this.inviteFriends.bind(this)} > <Image className='pt2_swiper_image' src={banner2} onClick={this.inviteFriends.bind(this)} /> </SwiperItem> <SwiperItem className='pt2_SwiperItem' onClick={this.summerTopic.bind(this)}> <Image className='pt2_swiper_image' src={banner3} onClick={this.summerTopic.bind(this)} /> </SwiperItem>*/} </Swiper> <Image src={my_information} className="MyMessage_head_img" style="pointer-events: none" /> <View className="MyMessage_body_content"> <View className="MyMessage_content_type_wrap"> <View className="MyMessage_type_title">姓名</View> <AtInput type="text" value={nameValue} className="MyMessage_content_input" placeholder="请输入您的姓名" maxLength="7" onChange={value => this.getNameValue(value)} onBlur={this.onInputBlur.bind(this)} /> </View> <View className="MyMessage_content_type_wrap"> <View className="MyMessage_type_title">手机(必填)</View> <Input type="number" value={numberValue} className="MyMessage_content_input" maxLength="11" placeholder="请输入您的联系号码" onChange={value => this.getNumberValue(value)} onBlur={this.onInputBlur.bind(this)} /> </View> <View className="MyMessage_content_type_wrap"> <View className="MyMessage_type_title">年龄</View> <Input type="number" value={ageValue} className="MyMessage_content_input" maxLength="2" placeholder="请输入你的年龄" onChange={value => this.getAgeValue(value)} onBlur={this.onInputBlur.bind(this)} /> </View> <View className="MyMessage_content_type_wrap"> <View className="MyMessage_type_title">籍贯</View> <Picker mode="nativePlaceValue" range={nativePlaceValue} onChange={this.Change.bind(this)} className="MyMessage_type_nativePlace_wrap"> <View className={showNativePlaceStyle ? 'MyMessage_nativePlace_title' : 'MyMessage_nativePlace_title2'}> {nativePlace} <Image src={arrow_right} className="MyMessage_arrow_right" style="pointer-events: none" /> </View> </Picker> </View> </View> <View className="btn_submit_wrap" onClick={this.submitBtn.bind(this)}> <Image src={showHighLight ? btn_submit : default_btn_next} className="btn_submit_img" style="pointer-events: none" /> </View> </View>; } //输入框失去焦点时 onInputBlur() { let { system } = this.state; if (system.startsWith('iOS') || system.startsWith('ios')) window.scroll(0, 0); } //获取姓名 getNameValue(value) { this.setState({ nameValue: value.replace(/\s+/g, "") }); } //获取手机 getNumberValue(e) { this.setState({ numberValue: e.detail.value }); this.showHighLight(e.detail.value); } //获取年龄 getAgeValue(e) { this.setState({ ageValue: e.detail.value }); } //选择籍贯 Change(e) { let nativePlaceValue = this.state.nativePlaceValue; let provinceData = this.state.provinceData; if (this.state.nativePlace == '请选择您的籍贯') { this.setState({ showNativePlaceStyle: true }); } else { this.setState({ showNativePlaceStyle: false }); } if (typeof e.detail.value == 'number') { this.setState({ nativePlace: nativePlaceValue[e.detail.value], showNativePlaceStyle: false }); } if (typeof e.detail.value == 'object') { this.setState({ nativePlace: nativePlaceValue[e.detail.value[0]], nativePlaceValueId: provinceData[e.detail.value[0]].id, showNativePlaceStyle: false }); } } //必填项已选择,下一步按钮显示高亮 showHighLight(phoneNumber) { if (phoneNumber == '' || phoneNumber.length !== 11) { this.setState({ showHighLight: false }); } else { this.setState({ showHighLight: true }); } } //提交按钮 submitBtn(e) { e.stopPropagation(); let { nameValue, numberValue, ageValue, nativePlace, showHighLight } = this.state; //防重复点击 if (!this.preventRepeat) return; this.preventRepeat = false; setTimeout(() => { this.preventRepeat = true; }, 3000); if (numberValue == '' || numberValue == null) { _showToast({ title: '请输入您的联系方式', icon: 'none', duration: 1500 }); return; } if (numberValue.length < 11) { _showToast({ title: '请输入正确的联系方式', icon: 'none', duration: 1500 }); return; } if (!showHighLight) return; let nameValue2 = nameValue == '' ? '' : nameValue; //名字 let ageValue2 = ageValue == '' ? '' : ageValue; //年龄 let nativePlace2 = nativePlace == '请选择您的籍贯' ? '' : nativePlace; //籍贯 let userId = localStorage.getItem('userId'); let type = getGlobalData('type2'); let pId = getGlobalData('pId2'); let cId = getGlobalData('cId2'); let provinceName = getGlobalData('provinceName2'); let cityName = getGlobalData('cityName2'); let driverTime = getGlobalData('driverTime2'); let areaIds1 = getGlobalData('areaIds2'); let areasName1 = getGlobalData('areasName2'); //数组转字符串 let areasName = areasName1.join(','); let areaIds = areaIds1.join(','); Netservice.request({ url: 'heque-backend/work_driver/addDriver', method: 'POST', data: { userId: userId, type: type, pId: pId, cId: cId, areaIds: areaIds, provinceName: provinceName, cityName: cityName, areasName: areasName, driverTime: driverTime, userName: nameValue2, phoneNumber: numberValue, nativeName: nativePlace2, age: ageValue2 }, success: res => { if (res.code !== Common.NetCode_NoError) { _showToast({ title: res.message, icon: 'none', duration: 1500 }); } else { Taro.redirectTo({ url: '/pages/wish/apply_success/apply_success?type=' + res.data.collectType + '&id=' + res.data.id + '&v=' + new Date().getTime() }); } } }); } componentDidShow() { super.componentDidShow && super.componentDidShow(); } componentDidHide() { super.componentDidHide && super.componentDidHide(); } }<file_sep>/.temp/pages/my/service/service.js import Nerv from "nervjs"; import Taro, { makePhoneCall as _makePhoneCall } from "@tarojs/taro-h5"; import { View, Image } from '@tarojs/components'; import './service.css?v=201906107'; import applyFor from '../../../images/service/apply_for.png'; // import orderComplaints from '../../../images/service/order_complaints.png' import servicePortrait from '../../../images/service/service_portrait.png'; import service_botton from '../../../images/my/service_botton.png'; export default class AfterService extends Taro.Component { config = { navigationBarTitleText: '我的客服', navigationBarTextStyle: 'white', navigationBarBackgroundColor: '#31B1B0' }; state = { orderId: '', //订单ID orderListData: '', //订单信息 dishesList: '' //菜品信息 }; componentDidShow() { //获取路由传过来的数据 let orderId = this.$router.params.orderId; let dishesList = localStorage.getItem('dishesList'); let listDataState = localStorage.getItem('listDataState'); this.setState({ orderListData: listDataState, dishesList: dishesList, orderId: orderId }); } render() { const { orderListData } = this.state; return <View className="AfterService_content"> <View className="service_card"> <View className="top_remind"> <Image src={servicePortrait} className="Imgsize" style="pointer-events: none" /> <View> <View className="f-34">您好,请自助选择服务</View> <View className="f-24">若自助不能满足您的需求,请电话客服</View> </View> </View> <View className="self-help">自助客服</View> {orderListData !== '3' ? <View></View> : <View className="self_help_list"> <View className="service_option" onClick={this.applyForAfterSales.bind(this)}> <Image src={applyFor} className="Imgsize2" style="pointer-events: none" /> <View className="f-28">申请售后</View> </View> <View className=""> {/*<Image src={orderComplaints} className='Imgsize2' /> <View className='f-28'>订单投诉</View>*/} </View> <View className=""> </View> <View className=""> </View> <View className=""> </View> </View>} </View> <View onClick={this.servicePhone.bind(this)} className="phoneService"> <Image src={service_botton} className="phoneService_img" style="pointer-events: none" /> </View> </View>; } applyForAfterSales(e) { let dishesList = JSON.stringify(this.state.dishesList); let paymentPrice = this.$router.params.paymentPrice; let discountPrice = this.$router.params.discountPrice; let orderId = this.state.orderId; Taro.navigateTo({ url: '/pages/my/service/apply_for_after_sales/apply_for_after_sales?dishesList=' + dishesList + '&orderId=' + orderId + '&paymentPrice=' + paymentPrice + '&discountPrice=' + discountPrice + '&v=' + new Date().getTime() }); } servicePhone(e) { _makePhoneCall({ phoneNumber: '4001686655' }); } componentDidMount() { super.componentDidMount && super.componentDidMount(); } componentDidHide() { super.componentDidHide && super.componentDidHide(); } }<file_sep>/.temp/pages/home_components/package_or_buy/package_or_buy.js import Nerv from "nervjs"; import './package_or_buy.css?v=201907051107'; import Taro from "@tarojs/taro-h5"; import { View } from '@tarojs/components'; import PointPackage from "../point_package/point_package"; import PointBuy from "../point_buy/point_buy"; import { setGlobalData, getGlobalData } from "../../../utils/global_data"; export default class PackageOrBuy extends Taro.Component { config = { navigationBarTitleText: '取餐点' }; state = { currentPoint: {}, currentCoupon: {} }; componentWillMount() { if (this.$router.params.storesDetails !== undefined && this.$router.params.storesDetails !== null) { let storesDetails = this.$router.params.storesDetails; let currentPoint = JSON.parse(decodeURIComponent(storesDetails)); this.setState({ currentPoint }); } } componentDidShow() { //切换优惠券 const couponChanged = getGlobalData('couponChanged') || false; if (couponChanged) { setGlobalData('couponChanged', false); const currentCoupon = getGlobalData('currentCoupon') || {}; this.setState({ currentCoupon: currentCoupon }); } } render() { const { currentPoint, currentCoupon } = this.state; return <View className="PackageOrBuy"> {currentPoint.feeType == 1 ? <PointPackage currentPoint={currentPoint} /> : <PointBuy currentPoint={currentPoint} currentCoupon={currentCoupon} />} </View>; } componentDidMount() { super.componentDidMount && super.componentDidMount(); } componentDidHide() { super.componentDidHide && super.componentDidHide(); } }<file_sep>/.temp/pages/wish/rent/rent.js import Nerv from "nervjs"; import './rent.css?v=20190703108'; import Taro, { getSystemInfo as _getSystemInfo, showToast as _showToast, showLoading as _showLoading, hideLoading as _hideLoading } from "@tarojs/taro-h5"; import { View, Text, Image, Swiper, SwiperItem } from '@tarojs/components'; import Netservice from "../../../netservice"; import Common from "../../../common"; import { AtInput } from 'taro-ui'; import banner1 from '../../../images/wish/rent/banner1.png'; import icon_normal from '../../../images/wish/checkbox_normal.png'; import icon_select from '../../../images/wish/checkbox_select.png'; import rent_more from '../../../images/wish/rent/rent_more.png'; export default class Rent extends Taro.Component { config = { navigationBarTitleText: '定制租车' }; constructor() { super(); this.canSubmitClick = true; //按钮防止连续点击 } state = { preferences: [{ value: 1, text: '燃油车', checked: false, more: '' }, { value: 2, text: '新能源车', checked: false, more: '' }, { value: 3, text: '短租期', checked: false, more: '(3个月)' }, { value: 4, text: '租车跑快车', checked: false, more: '(注重车辆性价比)' }, { value: 5, text: '租车跑专车', checked: false, more: '(注重车辆品牌性能)' }], name: '', phoneNumber: '', system: 'android' }; componentWillMount() { let phone = localStorage.getItem('phone') || ''; this.setState({ phoneNumber: phone }); _getSystemInfo({ success: res => { this.setState({ system: res.system }); } }); } componentDidMount() { var h = document.body.scrollHeight; window.onresize = function () { if (document.body.scrollHeight < h) { document.getElementsByClassName("rent-submit")[0].style.display = "none"; // setTimeout(() => { // // document.body.scrollHeight = 1500; // // window.scrollTo({ top: 1500, behavior: "smooth" }); // // window.scroll(0, 800); // // document.body && (document.body.scrollTop = 500); // }, 500); } else document.getElementsByClassName("rent-submit")[0].style.display = "block"; }; } componentWillUnmount() {} componentDidShow() {} componentDidHide() {} render() { let { preferences, name, phoneNumber } = this.state; return <View className="container-rent"> <Swiper className="rent-swiper"> <SwiperItem> <Image className="rs_image" src={banner1} style="pointer-events: none" /> </SwiperItem> </Swiper> <View className="rent-time-view"> <Text className="rent-tv-title">请勾选符合您要求的出行方案内容</Text> <View className="rent-tv-content"> {preferences.map((item, index) => { return <View className="rent-tvc-view" key={index} onClick={this.onPreferenceChange.bind(this, index)}> <Image className="rent-tvcv_image" src={item.checked ? icon_select : icon_normal} style="pointer-events: none" /> <Text className="rent-tvcv-text">{item.text}</Text> <Text className="rent-tvcv-more">{item.more}</Text> </View>; })} </View> <View className="rent-tv-line" /> </View> <View className="rent-name-view"> <Text className="rnv-title">您的称呼方式</Text> <AtInput className="rent-name-input" type="text" placeholder="请输入真实姓名" border={false} maxLength={10} onFocus={this.onInputFocus.bind(this)} onBlur={this.onInputBlur.bind(this)} value={name} onChange={this.onNameChange.bind(this)} /> <View className="rent-tv-line" /> </View> <View className="rent-name-view"> <Text className="rnv-title">请确认您的联系方式</Text> <AtInput className="rent-name-input" type="phone" placeholder="请输入联系方式" border={false} maxLength={11} onFocus={this.onInputFocus.bind(this)} onBlur={this.onInputBlur.bind(this)} value={phoneNumber} onChange={this.onPhoneNumberChange.bind(this)} /> <View className="rent-tv-line" /> </View> <View className="rent-more-view"> <Image className="rent-more-image" src={rent_more} onClick={this.goToRent2.bind(this)} /> </View> <View className="rent-submit" onClick={this.onSubmit.bind(this)}>提交</View> </View>; } onPreferenceChange(index) { let { preferences } = this.state; let item = preferences[index]; item.checked = !item.checked; preferences.splice(index, 1, item); this.setState({ preferences: preferences }); } onInputFocus() { let { system } = this.state; if (system.startsWith('android') || system.startsWith('Android')) { setTimeout(() => { window.scrollTo({ top: 500, behavior: "smooth" }); window.scroll(0, 500); }, 500); } } onInputBlur() { let { system } = this.state; if (system.startsWith('android') || system.startsWith('Android')) { // setTimeout(() => { // this.setState({ showSubmit: true }); // }, 1000); } if (system.startsWith('iOS') || system.startsWith('ios')) window.scroll(0, 0); } onNameChange(value) { this.setState({ name: value.replace(/ /g, '') }); return value; } onPhoneNumberChange(value) { this.setState({ phoneNumber: value }); return value; } onSubmit(value) { let { preferences, name, phoneNumber } = this.state; let list = preferences.filter(function (item) { return item.checked; }); let valueArray = []; list.map(function (item) { valueArray.push(item.value); }); if (valueArray.length <= 0) { _showToast({ title: '请勾选出行方案内容', icon: 'none', duration: 2000 }); return; } if (name.length < 1) { _showToast({ title: '请输入您的称呼方式', icon: 'none', duration: 2000 }); return; } if (phoneNumber.length < 1) { _showToast({ title: '请输入您的联系方式', icon: 'none', duration: 2000 }); return; } let userId = localStorage.getItem('userId'); if (userId) { if (!this.canSubmitClick) return; this.canSubmitClick = false; setTimeout(() => { this.canSubmitClick = true; }, 1500); _showLoading({ title: '正在提交中…' }); Netservice.request({ url: 'heque-backend/collectCarInfo/add', data: { userId: userId, phoneNum: phoneNumber, userName: name, carType: valueArray.join(',') }, success: res => { _hideLoading(); if (res.code !== Common.NetCode_NoError) { _showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } _showToast({ title: '提交成功', icon: 'success', duration: 2000 }); Taro.navigateTo({ url: '/pages/wish/apply_success/apply_success?type=' + res.data.type + '&id=' + res.data.id + '&v=' + new Date().getTime() }); }, error: function (err) { _hideLoading(); _showToast({ title: '提交失败', icon: 'none', duration: 2000 }); } }); } else { Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } } goToRent2(e) { e.stopPropagation(); Taro.navigateTo({ url: '/pages/wish/rent2/rent2' }); } }<file_sep>/src/pages/wish/messages/messages.js import './messages.css?v=20190703108'; import Taro, { Component } from '@tarojs/taro'; import { View, Text, Image } from '@tarojs/components'; import Netservice from '../../../netservice.js'; import Common from '../../../common.js'; import { setGlobalData, getGlobalData } from '../../../utils/global_data' import no_message from '../../../images/wish/no_message.png' export default class Messages extends Component { config = { navigationBarTitleText: '消息列表', enablePullDownRefresh: true, } state = { messages: [], pageIndex: 1, noMoreData: false, } componentWillMount() { this.getMessages(); } componentDidMount() { } componentWillUnmount() { } componentDidShow() { } componentDidHide() { } onReachBottom() { this.getMessages(); } getMessages() { let userId = localStorage.getItem('userId'); if (!userId) return; let { messages, pageIndex, noMoreData } = this.state; if (noMoreData) return; Taro.showLoading({ title: '努力加载中…' }); let that = this; Netservice.request({ url: 'heque-backend/collect/queryMessageList', method: 'GET', data:{ userId, pageSize:10, pageIndex }, success: function (res) { Taro.hideLoading(); if (res.code !== Common.NetCode_NoError) { Taro.showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } that.setState({ messages: messages.concat(res.data), pageIndex: pageIndex + 1 }); if (res.data.length < 10) that.setState({ noMoreData: true }); }, error: function (err) { Taro.hideLoading(); } }) } render() { let { messages } = this.state; const messageList = messages.map((item, index) => { return <View className='message-item' key={index} onClick={this.onTapItem.bind(this, item)}> <View className='mi-top'> <Text className='mit-title'>状态更新通知</Text> <Text className='mit-time'>{item.createTime}</Text> </View> <Text className='mi-content'>{item.showText}</Text> <View className='mi-line' /> </View> }) const noMessageView = <View className='no-message-view'> <Image src={no_message} className='nmv-img' style='pointer-events: none' /> </View> return ( <View className='container-messages'> {messages.length > 0 ? messageList : noMessageView} </View> ) } onTapItem(item, e) { //状态 0-待处理 1-处理中 2-处理完成 3-已取消 if (item.state == 2) Taro.navigateTo({ url: '/pages/my/apply_detail/apply_detail?type=' + item.type + '&id=' + item.relateId + '&v=' + new Date().getTime() }) } }<file_sep>/.temp/pages/points/points.js import Nerv from "nervjs"; import './points.css?v=201907051107'; import Taro, { showToast as _showToast } from "@tarojs/taro-h5"; import { View, Text, Image } from '@tarojs/components'; import Netservice from "../../netservice"; import { setGlobalData, getGlobalData } from '../../utils/global_data'; import arrowRight from '../../images/common/arrow_right.png'; import breathingSpace from '../../images/home/breathing_space.png'; import iconNearest1 from '../../images/home/icon_nearest1.png'; import OrderImgBtn from '../../images/home/go_details.png'; export default class Points extends Taro.Component { config = { navigationBarTitleText: '选择取餐点' }; state = { cityCode: 0, city: '', pointList: [] }; componentWillMount() { const cityCode = localStorage.getItem('cityCode'); const city = localStorage.getItem('city'); this.setState({ cityCode, city }); const latitude = localStorage.getItem('latitude'); const longitude = localStorage.getItem('longitude'); this.getCityPoints(cityCode, latitude, longitude); } componentDidMount() {} componentWillUnmount() {} componentDidShow() { const cityCode = localStorage.getItem('cityCode'); const city = localStorage.getItem('city'); this.setState({ cityCode, city }); const latitude = localStorage.getItem('latitude'); const longitude = localStorage.getItem('longitude'); this.getCityPoints(cityCode, latitude, longitude); } componentDidHide() {} getCityPoints(cityCode, latitude, longitude) { let that = this; Netservice.request({ url: 'heque-eat/eat/storeList', method: 'POST', data: { cityCode: cityCode, longitude: longitude, latitude: latitude }, success: function (res) { let pointList = res.data; if (pointList.length <= 0) _showToast({ title: '暂无符合条件的取餐点', icon: 'none', duration: 2000 }); pointList.sort(function (point1, point2) { return point1.number - point2.number; }); // 修改时间 for (let point of pointList) { let { foodTime1, foodTime2, foodTime3, foodTime4 } = point; point.suppleTime1 = foodTime1 ? foodTime1.slice(0, 5) + '-' + foodTime1.slice(11, 16) : ''; point.suppleTime2 = foodTime2 ? '/ ' + (foodTime2.slice(0, 5) + '-' + foodTime2.slice(11, 16)) : ''; point.suppleTime3 = foodTime3 ? '/ ' + (foodTime3.slice(0, 5) + '-' + foodTime3.slice(11, 16)) : ''; point.suppleTime4 = foodTime4 ? '/ ' + (foodTime4.slice(0, 5) + '-' + foodTime4.slice(11, 16)) : ''; } that.setState({ pointList: pointList }); }, error: function (err) {} }); } render() { let { pointList, city } = this.state; const points = pointList.map((value, index) => { return <View className="Points_item" key={value.id}> <View className="Points-conent_wrap"> <View className="Points-conent_left"> <View className="Points-view_name"> <Text>{value.name}</Text> {index === 0 && <Image src={iconNearest1} className="Points-nearest" />} </View> <View className="Points-distance"> {value.number >= 1000 ? <Text><Text className="Points-distance_number">{(value.number / 1000).toFixed(1)}</Text>km</Text> : <Text><Text className="Points-distance_number">{value.number}</Text>m</Text>} </View> <View className="Points-address">{value.adds}</View> <View className="Points-point-time"> <Text className="Points-time-title">供餐时间 :</Text> <Text className="Points-time">{value.suppleTime1} {value.suppleTime2} {value.suppleTime3} {value.suppleTime4}</Text> </View> </View> <View className="Points-conent_right"> {value.state && <View className="Points-order-btn" onClick={this.toOrder.bind(this, value)}> <Image src={OrderImgBtn} className="Points-OrderImgBtn-btn" /> </View>} {!value.state && <View className="Points-breathingSpace-btn"> <Image src={breathingSpace} className="Points-breathingSpace-btn" /> </View>} </View> </View> </View>; }); return <View className="default_points"> {/*固定头部*/} <View className="Points_points-header"> <View className="Points_ph-city" onClick={this.goCitys}> <Text>{city}</Text> <Image className="Points-arrow-right" src={arrowRight} /> </View> </View> {/*取餐地点列表*/} <View className="points-list"> {points} </View> </View>; } goBack() { Taro.navigateBack(); } //去门店页 toOrder(point, e) { const currentPoint = getGlobalData('currentPoint'); if (!currentPoint || currentPoint.id != point.id) { setGlobalData('currentPoint', point); setGlobalData('pointChanged', true); let { cityCode, city } = this.state; setGlobalData('cityCode', cityCode); setGlobalData('city', city); } let storesDetails = JSON.stringify(point); let pid = this.getUrlParam('pid'); if (pid !== null) { setGlobalData('currentPoint', point); setGlobalData('pointChanged', true); Taro.redirectTo({ url: '/pages/index/index?storesDetails=' + storesDetails + '&v=' + new Date().getTime() }); } else { Taro.redirectTo({ url: '/pages/home_components/package_or_buy/package_or_buy?storesDetails=' + storesDetails + '&v=' + new Date().getTime() }); } } //去城市列表 goCitys(e) { Taro.navigateTo({ url: "/pages/points/citys/citys?v=" + new Date().getTime() }); } // 网址中 解析、查找 getUrlParam(name) { var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'); let url = window.location.href.split('#')[0]; let search = url.split('?')[1]; if (search) { var r = search.substr(0).match(reg); if (r !== null) return unescape(r[2]); return null; } else return null; } }<file_sep>/src/pages/my/invite_friends/activityRules/activityRules.js import Taro, { Component } from '@tarojs/taro' import { View } from '@tarojs/components' import './activityRules.css?v=201906107' export default class ActivityRules extends Component { config = { navigationBarTitleText: '活动规则', } render() { return ( <View className='activityRules'> <View className='activityRules_content'> <p class="activityRules_content_title">Q:如何参加邀请好友活动?</p> <p class="activityRules_title_answer">A:活动时间内,点击分享按钮将链接发给好友即可参与。</p> <p class="activityRules_content_title margin_top">Q:怎样算是邀请成功?</p> <p class="activityRules_answer">A:好友作为新用户通过您分享的链接下载App,注册成功后算邀请成功。</p> <p class="fontSize30 strong">新用户的定义:</p> <p class="strfontSize28 ">之前从未注册过禾师傅,在活动期间注册禾师傅且使用手机号码绑定账号的。不能被认定为“新用户”的情形,包括但不限于如下情形:</p> <p class="strfontSize28 strong">*使用曾经安装过禾师傅客户端的终端设备登录的用户</p> <p class="strfontSize28 strong">*使用禾师傅已有账号登录新终端设备的用户</p> <p class="strfontSize28 strong">*通过其他禾师傅用户邀请再次下载禾师傅客户端的用户</p> <p class="strfontSize28 strong">*使用同一个手机号码、第三方账号等注册过禾师傅账号的用户</p> <p class="strfontSize28 strong">*存在采用各种不当手段下载、安装、注册、登录客户端,或存在涉嫌违法违规行为(包括不限于作弊、造假、其他交易风险等)的用户</p> <p class="fontSize30 answer">凡是符合以上任一一种情形的,均不能被认定为新用户,禾师傅有权收回因此给与邀请者的奖励。</p> <p class="activityRules_content_title margin_top">Q:获得的奖励如何发放?</p> <p class="answer"> A:邀请成功后获得的优惠券奖励,将会在被邀请人登录成功后发放至您的个人账户中,您可以在禾师傅公众号-我的-我的优惠券里查看。</p> <p class="activityRules_content_title margin_top">Q:优惠券如何使用?</p> <p class="answer">A:支付前可选择使用优惠券,单个用户每日最多使用两张优惠券。</p> </View> </View> ) } }<file_sep>/.temp/pages/take_meals/select_coupon/select_coupon.js import Nerv from "nervjs"; import './select_coupon.css?v=20190703108'; import Taro, { showLoading as _showLoading, hideLoading as _hideLoading, showToast as _showToast } from "@tarojs/taro-h5"; import { View, Text, Image } from '@tarojs/components'; import Netservice from "../../../netservice"; import Common from "../../../common"; import { setGlobalData, getGlobalData } from '../../../utils/global_data'; import selected from '../../../images/take/icon_select.png'; import notselected from '../../../images/take/icon_notselect.png'; import gapLine from '../../../images/take/divider_line.png'; import warning from '../../../images/take/icon_warning.png'; import noneCoupon from '../../../images/take/no_coupon.png'; export default class SelectCoupon extends Taro.Component { config = { navigationBarTitleText: '选择优惠券' }; state = { coupons: [], couponId: 0 }; componentWillMount() { const { orderId, storeId, dishId, totalPrice } = this.$router.params; if (orderId) this.getCoupons('heque-coupon/discount_coupon/queryIsUseCoupon', { orderId: orderId });else { let userId = localStorage.getItem('userId'); this.getCoupons('heque-coupon/discount_coupon/order_info_get_coupon', { userId: userId, totalPrice: totalPrice, dishId: dishId, storeId: storeId }); } const currentCoupon = getGlobalData('currentCoupon') || {}; const couponId = currentCoupon.id; this.setState({ couponId }); } componentDidMount() {} componentWillUnmount() {} componentDidShow() {} componentDidHide() {} getCoupons(url, params) { _showLoading({ title: '努力加载中…' }); let that = this; Netservice.request({ url: url, method: 'GET', data: params, success: function (res) { _hideLoading(); if (res.code !== Common.NetCode_NoError) { _showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } let coupons = res.data; var okCoupons = coupons.filter(function (item) { return item.type == 2; }); var notCoupons = coupons.filter(function (item) { return item.type == 1; }); // coupons.sort(function (item1, item2) { // return item2.faceValue - item1.faceValue // }); that.setState({ coupons: okCoupons.concat(notCoupons) }); }, error: function (err) { _hideLoading(); } }); } render() { let { coupons, couponId } = this.state; const coupon = coupons.map((item, index) => { const reasons = item.reason.slice(1, -1).split(','); const reasonsView = reasons.map((reasonItem, index) => { return <Text className="ibc-text">{reasonItem}</Text>; }); return <View className="coupon-item" key={index} onClick={this.onTapItem.bind(this, item)}> <View className="item-top"> <View className="it-left"> <View className="itl-top"> <Text className="itlt-flag">¥</Text> <Text className="itlt-amount">{item.faceValue}</Text> </View> {item.useType == 2 && <Text className="itlt-limit">满<Text className="itlt-orange">{item.consumptionMoney}</Text>元可用</Text>} </View> <View className="it-middle"> <View className="im-title">{item.name}</View> {item.applyType == 2 && <Text className="im-type">仅限菜品</Text>} {item.applyType == 3 && <Text className="im-type">仅限商品</Text>} <Text className="im-type">{item.receiveTime.slice(0, 10).replace(/-/g, '.')}-{item.expireTime.slice(0, 10).replace(/-/g, '.')}</Text> </View> {item.type == 2 && <Image class="it-right" src={couponId == item.id ? selected : notselected} style="pointer-events: none"></Image>} </View> <Image class="item-middle" src={gapLine} mode="widthFix" style="pointer-events: none"></Image> <View className="item-bottom"> {item.type == 2 ? <View className="ib-content"> {item.storeId !== '0' ? <Text className="ibc-text">限{item.storeName}使用</Text> : <Text className="ibc-text">不限门店</Text>} </View> : <View className="ib-content"> <View className="ibc-title"> <Image class="ibct-img" src={warning} mode="widthFix" style="pointer-events: none" /> <Text className="ibct-text">不可用原因</Text> </View> {reasonsView} {/* <Text className='ibc-text'>{item.reason.slice(1, -1)}</Text> */} </View>} </View> {item.type == 1 && <View className="item-cover" />} </View>; }); const noCoupon = <View className="no-coupon"> <Image className="nc-img" src={noneCoupon} style="pointer-events: none" /> </View>; const couponList = <View className="coupon-list"> <View className="not-use" onClick={this.notUseCoupon}> <Text className="nu-text">不使用优惠券</Text> <Image class="nu-img" src={couponId == 0 ? selected : notselected} style="pointer-events: none"></Image> </View> <View className="coupon-list"> {coupon} </View> </View>; return <View className="container-coupons"> {coupons.length > 0 ? couponList : noCoupon} </View>; } notUseCoupon(e) { setGlobalData('currentCoupon', {}); setGlobalData('notUseCoupon', true); setGlobalData('couponChanged', true); Taro.navigateBack(); } onTapItem(coupon, e) { // 1不可使用 2可使用 if (coupon.type == 2) { setGlobalData('currentCoupon', coupon); setGlobalData('notUseCoupon', false); setGlobalData('couponChanged', true); Taro.navigateBack(); } } }<file_sep>/.temp/pages/wish/apply_success/apply_success.js import Nerv from "nervjs"; import './apply_success.css?v=20190626110'; import Taro from "@tarojs/taro-h5"; import { View, Text, Image } from '@tarojs/components'; import successImg from '../../../images/wish/submit_success.png'; export default class ApplySuccess extends Taro.Component { config = { navigationBarTitleText: '提交成功' }; state = { type: 0, id: 0 }; componentWillMount() { let type = this.$router.params.type || 0; let id = this.$router.params.id || 0; this.setState({ type, id }); } componentDidMount() {} componentWillUnmount() {} componentDidShow() {} componentDidHide() {} render() { return <View className="container-apply-success"> <View className="apply-content-view"> <Image className="apply-image" src={successImg} mode="widthFix" /> <Text className="apply-content-title">申请提交成功</Text> <Text className="apply-content-info" onClick={this.goBackHome.bind(this)}>返回赚钱首页</Text> <Text className="apply-content-detail" onClick={this.goToDetail.bind(this)}>查看申请详情</Text> </View> </View>; } goBackHome() { Taro.redirectTo({ url: "/pages/wish/wish?v=" + new Date().getTime() }); } goToDetail() { const { type, id } = this.state; Taro.navigateTo({ url: '/pages/my/apply_detail/apply_detail?type=' + type + '&id=' + id + '&v=' + new Date().getTime() }); } }<file_sep>/src/pages/home_components/package_or_buy/package_or_buy.js import './package_or_buy.css?v=201907051107'; import Taro, { Component } from '@tarojs/taro'; import { View, Text, Image, Swiper, SwiperItem } from '@tarojs/components'; import PointPackage from '../point_package/point_package.js'; import PointBuy from '../point_buy/point_buy.js'; import { setGlobalData, getGlobalData } from '../../../utils/global_data.js' export default class PackageOrBuy extends Component { config = { navigationBarTitleText: '取餐点', } state = { currentPoint:{}, currentCoupon:{}, } componentWillMount(){ if(this.$router.params.storesDetails!==undefined && this.$router.params.storesDetails!== null){ let storesDetails = this.$router.params.storesDetails; let currentPoint = JSON.parse(decodeURIComponent(storesDetails)); this.setState({ currentPoint, }) } } componentDidShow(){ //切换优惠券 const couponChanged = getGlobalData('couponChanged') || false; if (couponChanged) { setGlobalData('couponChanged', false); const currentCoupon = getGlobalData('currentCoupon') || {}; this.setState({ currentCoupon: currentCoupon }); } } render() { const { currentPoint, currentCoupon } = this.state; return ( <View className='PackageOrBuy'> {currentPoint.feeType==1? <PointPackage currentPoint={currentPoint}/> : <PointBuy currentPoint={currentPoint} currentCoupon={currentCoupon}/> } </View> ) } }<file_sep>/.temp/pages/wish/car/car.js import Nerv from "nervjs"; import Taro from "@tarojs/taro-h5"; import { View, Image, Swiper, SwiperItem } from '@tarojs/components'; import './car.css?v=20190809110'; import { reporteUerBehavior } from '../../../utils/utils'; import car_home_banner from '../../../images/wish/car/car_home_banner_rent.png'; import area_fuban from '../../../images/wish/car/area_fuban.png'; import area_zuche from '../../../images/wish/car/area_zuche.png'; import area_caocao from '../../../images/wish/car/area_caocao.png'; import area_shouqi from '../../../images/wish/car/area_shouqi.png'; import area_yadi from '../../../images/wish/car/area_yadi.png'; import area_huolala from '../../../images/wish/car/area_huolala.png'; import area_kuaigou from '../../../images/wish/car/area_kuaigou.png'; import area_shenzhou from '../../../images/wish/car/area_shenzhou.png'; export default class Car extends Taro.Component { config = { 'navigationBarTitleText': '找车' }; render() { return <View className="content_car"> <Swiper className="content_car_swiper" circular autoplay={false} interval={3000} style="width:100%"> <SwiperItem className="content_car_SwiperItem" style="width:100%"> <Image className="content_car_swiper_image" src={car_home_banner} style="pointer-events: none; width:100%" /> </SwiperItem> {/* <SwiperItem className='pt2_SwiperItem' onClick={this.inviteFriends.bind(this)} > <Image className='pt2_swiper_image' src={banner2} onClick={this.inviteFriends.bind(this)} /> </SwiperItem> <SwiperItem className='pt2_SwiperItem' onClick={this.summerTopic.bind(this)}> <Image className='pt2_swiper_image' src={banner3} onClick={this.summerTopic.bind(this)} /> </SwiperItem>*/} </Swiper> <View className="car_title">禾师傅金牌服务</View> <View className="car_service_delivery"> <View className="area_fuban_wrap" onClick={this.PartTimeMakeMoney.bind(this)}> <Image src={area_fuban} className="area_fuban_img" style="pointer-events: none" /> </View> <View className="car_service_delivery_placeholder"></View> <View className="area_zuche_wrap" onClick={this.toCarRental.bind(this)}> <Image src={area_zuche} className="area_zuche_img" style="pointer-events: none" /> </View> </View> <View className="car_title">网约车合作专区</View> <View className="car_cooperation_wrap"> <View className="car_cooperation_content" onClick={this.goCaocao.bind(this)}> <Image src={area_caocao} className="car_cooperation_content_img" style="pointer-events: none" /> </View> <View className="car_cooperation_content" onClick={this.goShouqi.bind(this)}> <Image src={area_shouqi} className="car_cooperation_content_img" style="pointer-events: none" /> </View> <View className="car_cooperation_content" onClick={this.goYadi.bind(this)}> <Image src={area_yadi} className="car_cooperation_content_img" style="pointer-events: none" /> </View> <View className="car_cooperation_content" onClick={this.goShenzhou.bind(this)}> <Image src={area_shenzhou} className="car_cooperation_content_img" style="pointer-events: none" /> </View> <View className="car_cooperation_content" onClick={this.goHuolala.bind(this)}> <Image src={area_huolala} className="car_cooperation_content_img" style="pointer-events: none" /> </View> <View className="car_cooperation_content" onClick={this.goKuaigou.bind(this)}> <Image src={area_kuaigou} className="car_cooperation_content_img" style="pointer-events: none" /> </View> </View> </View>; } //到副班赚钱页 PartTimeMakeMoney(e) { e.stopPropagation(); Taro.navigateTo({ url: '/pages/wish/car/partTimeMakeMoney/partTimeMakeMoney?v=' + new Date().getTime() }); } //到租车页 toCarRental(e) { e.stopPropagation(); Taro.navigateTo({ url: '/pages/wish/rent/rent' }); } //曹操出行页 goCaocao(e) { e.stopPropagation(); Taro.navigateTo({ url: '/pages/wish/car/caocao/caocao' }); } //首汽出行 goShouqi(e) { e.stopPropagation(); Taro.navigateTo({ url: '/pages/wish/car/shouqi/shouqi' }); } //亚嘀出租 goYadi(e) { e.stopPropagation(); Taro.navigateTo({ url: '/pages/wish/car/yadi/yadi' }); } //到神州 goShenzhou(e) { e.stopPropagation(); reporteUerBehavior('赚钱|找车|神州专车', 1, res => { Taro.navigateTo({ url: 'https://recruit.10101111.com/#/?ucarfrom=guanwangQRcode' }); }); } //到货拉拉 goHuolala(e) { e.stopPropagation(); reporteUerBehavior('赚钱|找车|货拉拉', 1, res => { Taro.navigateTo({ url: 'https://www.huolala.cn/m/driver.html' }); }); } //跳转到快狗 goKuaigou(e) { e.stopPropagation(); reporteUerBehavior('赚钱|找车|快狗打车', 1, res => { Taro.navigateTo({ url: 'https://huoyun.daojia.com/driver-register/index.html#/newindex?hmsr=web_kuaigoudache_join_qr_code' }); }); } componentDidMount() { super.componentDidMount && super.componentDidMount(); } componentDidShow() { super.componentDidShow && super.componentDidShow(); } componentDidHide() { super.componentDidHide && super.componentDidHide(); } }<file_sep>/.temp/common.js export default { AppId: 'wxed1d300ad50d204f', //禾师傅餐饮 NetCode_NoError: '000000', //接口返回无误 NetCode_TokenInvalid: '1<PASSWORD>', //token失效 // 分享公众号 公共文本 ShareTitle: '一起来禾师傅吃饭吧', // 分享标题 ShareDesc: '禾师傅——司机工作餐', // 分享描述 ShareImgUrl: 'https://heque-base-dev.oss-cn-shenzhen.aliyuncs.com/group2/f815ad2668214593a58b5ec1295950c8.png', // 分享图标 // 邀请好友 公共文本 InviteTitle: '送你1张代金券,一起来禾师傅吃饭吧', // 分享标题 InviteDesc: '禾师傅——司机工作餐', // 分享描述 InviteImgUrl: 'https://heque-base-dev.oss-cn-shenzhen.aliyuncs.com/group2/0a8256fc023d43409bbef735a29324f1.png', // 分享图标 //外网测试环境 InvitationFriend: 'http://wxgzhtest.hequecheguanjia.com/share?userId=', // 邀请好友 ShareWebsite: 'http://wxgzhtest.hequecheguanjia.com' // 分享公众号 //生产环境 // InvitationFriend: 'http://wxgzh.hequecheguanjia.com/share?userId=', // 邀请好友 // ShareWebsite: 'http://wxgzh.hequecheguanjia.com', // 分享公众号 };<file_sep>/src/pages/booking/booking.js import './booking.css?v=201906107'; import Taro, { Component } from '@tarojs/taro'; import { View, Text, Image } from '@tarojs/components'; import Netservice from '../../netservice.js'; import Common from '../../common.js' import { payment, zeroPayment } from '../../utils/payment.js' import { getGlobalData, setGlobalData } from '../../utils/global_data' import subBtn from '../../images/common/sub_btn.png' import addBtn from '../../images/common/add_btn.png' import navigatImg from '../../images/common/navigat_img.png' import arrowRight from "../../images/common/arrow_right.png"; import paymentBtn from "../../images/common/payment_btn.png"; // 引入微信js-sdk import JSWX from '../../libs/jweixin-1.4.0'; export default class Booking extends Component { config = { navigationBarTitleText: '确认点餐', } constructor() { super(); this.canPayClick = true; //支付按钮防止连续点击 } state = { currentPoint: {}, //当前取餐点信息 orderInfo: null, //订单信息 priceTotal: 0, //总金额 count: 1, //菜品数量 couponStr: '', //优惠券的金额 cValue: '', // 用于计算的优惠券的金额 couponStyle: false, // 优惠券的样式 currentCoupon: {}, //优惠券信息 businessHours1: '', //营业时间 businessHours2: '', //营业时间 businessHours3: '', //营业时间 businessHours4: '', //营业时间 }; componentWillMount() { //手动初始化 setGlobalData('currentCoupon', {}); setGlobalData('notUseCoupon', false); let { dishInfo } = this.$router.params; let orderInfo = JSON.parse(decodeURIComponent(dishInfo)); const currentPoint = orderInfo.storesDetails; let priceTotal = parseFloat(orderInfo.dishPricee); this.setState({ currentPoint, orderInfo, priceTotal, businessHours1: orderInfo.storesDetails.suppleTime1, businessHours2: orderInfo.storesDetails.suppleTime2, businessHours3: orderInfo.storesDetails.suppleTime3, businessHours4: orderInfo.storesDetails.suppleTime4, }); //查优惠券 this.getCouponList(orderInfo, priceTotal); this.getWeChatJSApiParam(); } componentDidMount() { } componentWillUnmount() { } componentDidShow() { let { dishInfo } = this.$router.params; let orderInfo1 = JSON.parse(decodeURIComponent(dishInfo)); let priceTotal = parseFloat(orderInfo1.dishPricee); const couponChanged = getGlobalData('couponChanged') || false; if (couponChanged) { setGlobalData('couponChanged', false); //获取选择的优惠券 const currentCoupon = getGlobalData('currentCoupon') || {}; this.setState({ currentCoupon }) let cValue = currentCoupon.faceValue ? currentCoupon.faceValue : 0; let couponStr = cValue > 0 && currentCoupon.type == '2' ? '- ¥' + cValue : '请选择优惠券'; let orderInfo = this.state.orderInfo; if (cValue > 0) { this.setState({ couponStyle: true, }) } else { this.setState({ couponStyle: false }) } //数量>=1时,显示 if (this.state.count >= 1 && cValue == 0) { //总价 = 数量 * 菜品金额 let totalValue = Number(this.state.count * orderInfo.dishPricee); this.setState({ priceTotal: totalValue, couponStr, cValue: cValue, }) } else { //总价 = 数量 * 菜品金额 - 优惠券 let totalValue = Number((this.state.count * orderInfo.dishPricee) - cValue); if (totalValue > 0) { this.setState({ priceTotal: totalValue, couponStr }) } else { this.setState({ priceTotal: 0, couponStr }) } } } else { let notUseCoupon = getGlobalData('notUseCoupon'); if (!notUseCoupon) { //查优惠券 this.getCouponList(orderInfo1, priceTotal); } } } componentDidHide() { } //计算金额的函数 calculate(cValue) { //菜品的价格 let dishPricee = this.state.orderInfo.dishPricee; //总价格 = 菜品的价格 - 优惠券的金额 let Pricee = dishPricee - cValue; //总价格 < 0 时 if (Pricee < 0) { this.setState({ priceTotal: 0 }) } else { this.setState({ priceTotal: Pricee }) } } render() { let { currentPoint, orderInfo, count, priceTotal, couponStr, couponStyle, businessHours1, businessHours2, businessHours3, businessHours4 } = this.state; return (<View className='container-book'> {/*取餐点信息*/} <View className='book-point'> <View className='bp-info'> <View className='bpi_name'> <Text className='bpin-name'>{currentPoint.name}</Text> </View> <View className='bpi-address'>距您 {currentPoint.number >= 1000 ? <Text className='bpi-address-distance'> {(currentPoint.number / 1000).toFixed(1)} <Text className='booking_unit'>km</Text> </Text> : <Text className='bpi-address-distance'>{currentPoint.number}<Text className='booking_unit'>m</Text> </Text> } <Text className='margin_10'>|</Text> {currentPoint.adds} </View> {businessHours1 !== undefined ? <View className='bpi_businessHours'> <Text className='margin-r-18'>营业时间 : </Text> <Text>{businessHours1} {businessHours2} {businessHours3} {businessHours4}</Text> </View> : <View className='bpi_businessHours'> <Text>营业时间:</Text> {currentPoint.times.length == 1 && <Text>{currentPoint.times[0]}</Text>} {currentPoint.times.length == 2 && <Text>{currentPoint.times[0]} / {currentPoint.times[1]}</Text>} {currentPoint.times.length == 3 && <Text>{currentPoint.times[0]} / {currentPoint.times[1]} / {currentPoint.times[2]}</Text>} {currentPoint.times.length == 4 && <Text>{currentPoint.times[0]} / {currentPoint.times[1]} / {currentPoint.times[2]} / {currentPoint.times[3]}</Text>} </View>} </View> <View className='bp-navigator' onClick={this.goLocation.bind(this)}> <Image className='bpn-img' src={navigatImg} style='pointer-events: none'></Image> </View> </View> {/*餐品信息*/} <View className='order-detail'> <View className='order-meal'> <Image className='order-icon' src={orderInfo.dishUrl} mode='aspectFill' /> <View className='order-info'> <View className='order-title'>{orderInfo.dishName}</View> <View className='order-subheading'>{orderInfo.dishesRemake}</View> <View className='price-count'> <Text className='order-price'>¥{orderInfo.dishPricee}</Text> <View className='order-count'> <View onClick={this.subNum.bind(this)}> <Image src={subBtn} className='count-btn' style='pointer-events: none' /> </View> <Text className='count'>{count}</Text> <View onClick={this.addNum.bind(this)}> <Image src={addBtn} className='count-addBtn' style='pointer-events: none' /> </View> </View> </View> </View> </View> <View className='meal-line'></View> <View className='order_meal_coupons' onClick={this.toCouponsList.bind(this)}> <View className='order_meal_coupons_title'>优惠券</View> <View className='order_meal_coupons_right'> <Text className={couponStyle ? 'order_meal_coupons_price2' : 'order_meal_coupons_price'}>{couponStr}</Text> <Image className='order_meal_coupons_img' src={arrowRight} style='pointer-events: none' /> </View> </View> <View className='meal-line'></View> <View className='fee-view'> <View className='fee-content'> <Text className='fc-total'>合计</Text> <View className='fc-flag'>¥<Text className='fc-num'>{priceTotal.toFixed(2)}</Text></View> </View> </View> </View> {/*底部按钮*/} <View className='btn-view' onClick={this.bookingMeals.bind(this)}> <Image src={paymentBtn} className='booking-btn' style='pointer-events: none' /> </View> </View>) } goBack() { Taro.navigateBack() } // 减少数量 subNum() { let { count, orderInfo } = this.state; if (count > 1) { count--; //总价 = 金额 * 数量 let priceTotal = Number((parseFloat(orderInfo.dishPricee) * count)); this.setState({ count, priceTotal }); //请求的优惠券数据 this.getUsableCoupons(priceTotal, orderInfo, count); } } // 添加数量 addNum() { let { count, orderInfo } = this.state; count++; //总价 = 金额 * 数量 let priceTotal = Number((parseFloat(orderInfo.dishPricee) * count)); this.setState({ count, priceTotal }) //请求的优惠券数据 this.getUsableCoupons(priceTotal, orderInfo, count); } //增加,减少 数量时请求的优惠券数据 getUsableCoupons(priceTotal, orderInfo, count) { let that = this; let userId = localStorage.getItem('userId'); //查可用的优惠券 Netservice.request({ url: 'heque-coupon/discount_coupon/order_info_get_coupon', method: 'GET', data: { userId: userId, totalPrice: priceTotal, dishId: orderInfo.dishId, storeId: orderInfo.storesDetails.id, }, success: res => { //有优惠券 if (res.data.length > 0) { //过滤 可使用的优惠券 2=可使用 var okCoupons = res.data.filter(function (item) { return item.type == 2; }); //可使用的优惠券> 0 if (okCoupons.length > 0) { //排序 可使用的优惠券 okCoupons.sort(function (item1, item2) { return item2.faceValue - item1.faceValue }); //设置第一个值 const targetCoupon = okCoupons[0]; setGlobalData('currentCoupon', targetCoupon); that.setState({ currentCoupon: targetCoupon }) //优惠券设置值 let cValue = targetCoupon.faceValue ? targetCoupon.faceValue : 0; //优惠券大于0时 let couponStr = cValue > 0 && targetCoupon.type == '2' ? '- ¥' + cValue : '请选择优惠券'; //是否选择优惠券 let notUseCoupon = getGlobalData('notUseCoupon') || false; //优惠券大于0时 && 选择了优惠券 if (cValue > 0 && !notUseCoupon) { //总价 = 金额 * 数量 let priceTotal = Number((parseFloat(orderInfo.dishPricee) * count) - cValue); //小于0 显示0 let priceTotal2 = priceTotal > 0 ? priceTotal : 0; that.setState({ priceTotal: priceTotal2, couponStr, cValue: cValue, couponStyle: true, }) // 没有选择优惠券 } else { //清空优惠券 setGlobalData('currentCoupon', {}); that.setState({ couponStr: '请选择优惠券', couponStyle: false, currentCoupon: {} }) } //没有优惠券 } else { that.setState({ couponStr: '请选择优惠券', couponStyle: false, }) } } } }) } //获取微信JS接口参数 getWeChatJSApiParam() { Netservice.request({ url: 'heque-eat/we_chat_public_number/get_signature', method: 'GET', data:{ url: encodeURIComponent(location.href.split('#')[0]) }, success: res => { JSWX.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: 'wxed1d300ad50d204f', // 必填,企业号的唯一标识,此处填写企业号corpid timestamp: res.data.timestamp, // 必填,生成签名的时间戳(10位) nonceStr: res.data.nonceStr, // 必填,生成签名的随机串,注意大小写 signature: res.data.signature,// 必填,签名, jsApiList: ['openLocation', 'getLocation', 'chooseWXPay'] // 必填,需要使用的JS接口列表, }); JSWX.ready(function () { JSWX.error(function (err) { console.log("config信息验证失败,err=" + JSON.stringify(err)); }); }); } }) } // 去导航 goLocation() { const currentPoint = this.state.currentPoint; JSWX.openLocation({ latitude: currentPoint.latitude, longitude: currentPoint.longitude, name: currentPoint.name, address: currentPoint.adds, }) } // 查可用的优惠券 getCouponList(orderInfo, dishPricee) { let that = this; let userId = localStorage.getItem('userId'); let currentPoint = orderInfo.storesDetails; // let orderInfo = this.state.orderInfo; if (userId) { //查可用的优惠券 Netservice.request({ url: 'heque-coupon/discount_coupon/order_info_get_coupon', method: 'GET', data: { userId: userId, totalPrice: dishPricee, dishId: orderInfo.dishId, storeId: currentPoint.id, }, success: res => { if (res.data.length > 0) { //过滤 可使用的优惠券 2=可使用 var okCoupons = res.data.filter(function (item) { return item.type == 2; }); //可使用的优惠券> 0 if (okCoupons.length > 0) { //排序 可使用的优惠券 okCoupons.sort(function (item1, item2) { return item2.faceValue - item1.faceValue }); const targetCoupon = okCoupons[0]; setGlobalData('currentCoupon', targetCoupon); that.setState({ currentCoupon: targetCoupon }) let cValue = targetCoupon.faceValue ? targetCoupon.faceValue : 0; let couponStr = cValue > 0 && targetCoupon.type == '2' ? '- ¥' + cValue : '请选择优惠券'; that.setState({ couponStr, cValue: cValue, couponStyle: true, }) //计算金额 that.calculate(targetCoupon.faceValue); } else { that.setState({ couponStr: '请选择优惠券', couponStyle: false, }) } } else { that.setState({ couponStr: '请选择优惠券', couponStyle: false, }) } } }) } } //去支付按钮 bookingMeals() { //防重复点击 if (!this.canPayClick) return; this.canPayClick = false; setTimeout(() => { this.canPayClick = true }, 3000); let userId = localStorage.getItem('userId'); if (userId) { let that = this; Taro.showLoading({ title: '努力加载中…' }); let { orderInfo, count, priceTotal } = this.state; const currentPoint = this.state.currentPoint; //计算总价 let totalPrice = Number(count * orderInfo.dishPricee); //保存订单 Netservice.request({ url: 'heque-eat/eat/save_order', method: 'POST', data: { dishId: orderInfo.dishId, storeId: currentPoint.id, num: count, userId: userId, priceType: orderInfo.priceType, longitude: currentPoint.longitude, latitude: currentPoint.latitude, codeC: currentPoint.cityCode, totalPrice: totalPrice, appType: 'h5', }, success: res => { let orderId = res.data; Taro.hideLoading(); if (res.code !== Common.NetCode_NoError) { Taro.showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } //调起支付 that.checkPay(orderId) // Taro.showToast({ title: '点餐成功', icon: 'success', duration: 2000 }); // Taro.switchTab({ url: '/pages/take_meals/take_meals' }) } }) } else { Taro.navigateTo({ url: '/pages/login/login' + '?v=' + new Date().getTime() }) } } //去选择优惠券 toCouponsList(e) { let userId = localStorage.getItem('userId'); let currentPoint = this.state.currentPoint; let orderInfo = this.state.orderInfo; let count = this.state.count; //计算总价 let totalPrice = Number(count * orderInfo.dishPricee); if (userId) { Taro.navigateTo({ url: '/pages/take_meals/select_coupon/select_coupon?userId=' + userId + '&storeId=' + currentPoint.id + '&dishId=' + orderInfo.dishId + '&totalPrice=' + totalPrice + '&v=' + new Date().getTime(), }) } else { Taro.navigateTo({ url: '/pages/login/login' }) } } //查要支付的实际金额 checkPay(orderId) { let userCardMedalId = {}; const currentCoupon = this.state.currentCoupon || {}; const couponId = currentCoupon.id; if (couponId) { userCardMedalId = { userCardMedalId: couponId }; } let that = this; Netservice.request({ url: 'heque-coupon/discount_coupon/query_real_pay_price', method: 'GET', data: { ...userCardMedalId, orderId: orderId, }, success: function (res) { let totalPrice = res.data.totalPrice; if (parseInt(parseFloat(totalPrice) * 100) > parseInt(0)) that.goWechatPay(totalPrice, orderId); //调起微信支付 else that.zeroPay(totalPrice, orderId); // ;零元支付 }, error: function (err) { Taro.hideLoading(); Taro.showToast({ title: '支付失败', icon: 'none', duration: 2000 }); Taro.navigateTo({ url: '/pages/my/order_history/the_order_details/the_order_details?orderId=' + orderId + '&=' + new Date().getTime() }) } }) } //调起支付 goWechatPay(totalPrice, orderId) { const currentCoupon = this.state.currentCoupon || {}; let openId = localStorage.getItem('openId'); let userCardMedalId = {}; const couponId = currentCoupon.id; if (couponId) { userCardMedalId = { userCardMedalId: couponId }; } let that = this; // //支付接口 payment(userCardMedalId, orderId, totalPrice, openId, () => { //支付成功 that.setState({ count: 1 }); Taro.navigateTo({ url: '/pages/my/order_history/the_order_details/the_order_details?orderId=' + orderId + '&v=' + new Date().getTime() }) }, () => { //支付取消 that.setState({ count: 1 }); Taro.showToast({ title: '支付取消', icon: 'none', duration: 2000 }); Taro.navigateTo({ url: '/pages/my/order_history/the_order_details/the_order_details?orderId=' + orderId + '&v=' + new Date().getTime() }) }, () => { //支付失败 that.setState({ count: 1 }); Taro.showToast({ title: '支付失败', icon: 'none', duration: 2000 }); Taro.navigateTo({ url: '/pages/my/order_history/the_order_details/the_order_details?orderId=' + orderId + '&v=' + new Date().getTime() }) } ); } //零元支付 zeroPay(price, orderId) { Taro.showLoading({ title: '努力加载中…' }); let userCardMedalId = {}; const currentCoupon = this.state.currentCoupon || {}; const couponId = currentCoupon.id; if (couponId) { userCardMedalId = { userCardMedalId: couponId }; } this.setState({ count: 1 }); //支付 zeroPayment(userCardMedalId, price, orderId); } }<file_sep>/.temp/pages/index/summer_topic/summer_topic.js import Nerv from "nervjs"; import './summer_topic.css'; import Taro from "@tarojs/taro-h5"; import { View, Text, Image } from '@tarojs/components'; import summer_top_img from '../../../images/home/summer_top.png'; import summer_bottom_img from '../../../images/home/summer_bottom.png'; export default class SummerTopic extends Taro.Component { config = { navigationBarTitleText: '入夏上新 禾家丰盛' }; state = { showCoupon: false, //是否显示优惠券弹框 couponList: [] }; componentWillMount() {} componentDidMount() {} componentWillUnmount() {} componentDidShow() {} componentDidHide() {} render() { return <View className="container-summer"> <Image className="summer-top-img" src={summer_top_img} mode="widthFix" style="pointer-events: none" /> <View className="summer-middle-view"> <Text className="smmv-text">    清脆的蝉鸣,此起彼伏的蛙声,田间绿色的麦田,满天星光萤火虫......这是自然给予我们夏天独有的馈赠。万物生长是夏天的篇章,也是禾师傅发展的主旋律。</Text> <Text className="smmv-text">    今夏,禾师傅带着“司机工作餐”在广州、深圳、杭州、无锡四大城市相继亮相。本着“更快捷、更实惠、更健康”的发展宗旨,禾师傅打开了司机餐饮发展新方向,通过大数据智能餐饮系统,科学合理的健康饮食搭配,有效缓解司机就餐停车难、就餐环境差、饮食不规律、营养不均衡等问题。“让每一位司机拥有健康轻松车生活”是禾师傅发展愿景。未来,禾师傅在提供司机工作餐服务基础上,将不断扩大自身服务范围,丰富自身业务版块,为司机群体建立一站式综合服务智能生态圈。</Text> <Text className="smmv-text">    以夏立新,以餐饮立足司机服务,禾师傅将如花繁叶茂的夏天般欣欣向荣。</Text> </View> <Image className="summer-bottom-img" src={summer_bottom_img} mode="widthFix" style="pointer-events: none" /> </View>; } goBack() { Taro.navigateBack(); } }<file_sep>/.temp/pages/take_meals/take_meals.js import Nerv from "nervjs"; import './take_meals.css?v=20190717110'; import Taro, { showLoading as _showLoading, hideLoading as _hideLoading, switchTab as _switchTab, makePhoneCall as _makePhoneCall, showToast as _showToast, showModal as _showModal } from "@tarojs/taro-h5"; import { View, Text, Swiper, SwiperItem, Image, ScrollView } from '@tarojs/components'; import Netservice from "../../netservice"; import Common from "../../common"; import { getGlobalData, setGlobalData } from '../../utils/global_data'; import { calculateDistance } from '../../utils/utils'; import iconPhone from '../../images/common/icon_phone_point.png'; import navigatImg from "../../images/common/navigat_img.png"; import arrowRight from "../../images/common/arrow_right.png"; import wepayIcon from "../../images/common/wepay_icon.png"; import noMeal from "../../images/take/no_meal.png"; import spacing from "../../images/take/divider_line.png"; import btnLeft from "../../images/take/btn_left.png"; import btnRight from "../../images/take/btn_right.png"; import iconSelect from "../../images/take/icon_select.png"; import Prize from '../prize/prize.js?v=20190717110'; import NoPrize from '../noprize/noprize.js?v=20190717110'; import TooltipCoupon from '../tooltipCoupon/tooltipCoupon.js?v=20190626110'; // 引入微信js-sdk import JSWX from '../../libs/jweixin-1.4.0'; export default class TakeMeals extends Taro.Component { config = { navigationBarTitleText: '取餐' }; constructor() { super(); this.canPayClick = true; //支付按钮防止连续点击 } state = { meals: [], //待取餐订单列表 orderIndex: 0, //当前所在订单index couponIndex: 0, //当前使用优惠券的index //支付后 红包/优惠券 couponList: [], zeroCouponIds: [], //零元优惠券,用来置为已读 showPrize: false, //是否显示抽奖/开奖弹框 showCoupon: false, //是否显示优惠券弹框 showNoPrize: false, //是否显示没奖弹框 tapThePrize: false //是否点击抽奖/开奖弹框 }; componentWillMount() { this.getWeChatJSApiParam(); //手动初始化 setGlobalData('currentCoupon', {}); setGlobalData('notUseCoupon', false); this.setState({ meals: [], orderIndex: 0, couponIndex: 0 }); } componentDidMount() {} componentDidShow() { this.getMeals(); const couponChanged = getGlobalData('couponChanged') || false; if (couponChanged) { setGlobalData('couponChanged', false); let { orderIndex } = this.state; this.setState({ couponIndex: orderIndex }); } } componentDidHide() {} //获取未取餐订单列表 getMeals() { let userId = localStorage.getItem('userId'); if (!userId) return; let that = this; _showLoading({ title: '努力加载中…' }); Netservice.request({ url: 'heque-eat/eat/no_meal_order_info?userId=' + userId, method: 'GET', success: res => { _hideLoading(); if (res.code !== Common.NetCode_NoError) { that.setState({ meals: [] }); return; } let meals = res.data; const latitude = getGlobalData('latitude') || 0; const longitude = getGlobalData('longitude') || 0; // 修改时间格式 for (let meal of meals) { let { foodTime1, foodTime2, foodTime3, foodTime4 } = meal; let timeArray = [foodTime1, foodTime2, foodTime3, foodTime4]; let times = []; for (let time of timeArray) { if (time && time.length > 5) { let aTime = time.slice(0, 5) + '-' + time.slice(11, 16); times.push(aTime); } } meal.times = times; meal.distance = calculateDistance({ latitude: meal.latitude, longitude: meal.longitude }, { latitude: latitude, longitude: longitude }); } let { orderIndex } = that.state, length; meals.length ? length = meals.length - 1 : length = 0; if (orderIndex > length) { that.setState({ meals, orderIndex: length, couponIndex: length }); } else { that.setState({ meals }); } // 没选优惠券的自动选一个 const notUseCoupon = getGlobalData('notUseCoupon') || false; if (!notUseCoupon) { const currentCoupon = getGlobalData('currentCoupon') || {}; if (!currentCoupon.faceValue) { for (var i = 0; i < meals.length; i++) { const meal = meals[i]; // 未支付订单 if (meal.state === 1 || meal.state === 2) { that.getTheCoupon(meal.id, i); break; } } } } setTimeout(that.getCoupons(), 2000); }, fail: function (error) { _hideLoading(); this.setState({ meals: [] }); setTimeout(that.getCoupons(), 2000); } }); } //查找最大可用优惠券 getTheCoupon(orderId, orderIndex) { let that = this; Netservice.request({ url: 'heque-coupon/discount_coupon/queryIsUseCoupon', method: 'GET', data: { orderId: orderId }, success: function (res) { let coupons = res.data; var okCoupons = coupons.filter(function (item) { return item.type == 2; }); if (okCoupons.length > 0) { okCoupons.sort(function (item1, item2) { return item2.faceValue - item1.faceValue; }); const targetCoupon = okCoupons[0]; setGlobalData('currentCoupon', targetCoupon); that.setState({ couponIndex: orderIndex }); } }, error: function (err) {} }); } render() { let that = this; let { meals, orderIndex, couponIndex, couponList, showPrize, showCoupon, showNoPrize, tapThePrize } = this.state; const currentCoupon = getGlobalData('currentCoupon') || {}; let cValue = currentCoupon.faceValue ? currentCoupon.faceValue : 0; let couponStr = cValue > 0 ? '-¥' + cValue : '请选择优惠券'; let mealList = meals.map(function (item, index) { let totalStr = couponIndex == index ? new Number(item.paymentPrice - cValue >= 0 ? item.paymentPrice - cValue : 0).toFixed(2) : new Number(item.paymentPrice).toFixed(2); let mealsInfo = item.list.map(function (meal) { return <View className="meal-info" taroKey={meal.id}> <Text className="meal-name">{meal.dishesName}</Text> <Text className="meal-num">x {meal.number}</Text> <Text className="meal-num">¥ {meal.paymentPrice}</Text> </View>; }); return <SwiperItem taroKey={item.id}> <ScrollView className="meals-item" scrollY> {/*待支付*/} {(item.state === 1 || item.state === 2) && <View className="status-view"> <Text className="status-title">待支付</Text> <View className="status-content"> <Text>30分钟内未支付成功,订单将自动</Text> <Text className="svc-btn" onClick={that.toCancle.bind(that)}>取消</Text> </View>} </View>} {/*取餐码*/} {(item.state === 3 || item.state === 6 || item.state === 8 || item.state === 9) && <View className="status-view"> <Text className="code-title">取餐码</Text> <Text className="code-code">{item.takeMealCode}</Text> </View>} <Image src={spacing} className="space-img" style="pointer-events: none" /> {/*取餐点*/} <View className="point-take"> <View className="pt-first"> <Text className="pt-name">{item.storeName}</Text> <View className="pt-navigator"> <View onClick={that.goLocation.bind(that)}> <Image className="ptn-navigat" src={navigatImg} style="pointer-events: none" /> </View> <View onClick={that.contactPoint.bind(that)}> <Image className="ptn_phone" src={iconPhone} style="pointer-events: none" /> </View> </View> </View> <View className="pti-supply"> {item.times.length == 1 && <Text className="supply-time">供餐时间 {item.times[0]}</Text>} {item.times.length == 2 && <Text className="supply-time">供餐时间 {item.times[0]} / {item.times[1]}</Text>} {item.times.length >= 3 && <View className="ptis-ver"> <Text className="supply-time">供餐时间</Text> {item.times.length == 3 && <Text className="supply-time"> {item.times[0]} / {item.times[1]} / {item.times[2]} </Text>} {item.times.length == 4 && <Text className="supply-time"> {item.times[0]} / {item.times[1]} / {item.times[2]} / {item.times[3]}</Text>} </View>} <Text className="supply-addr" space>距您{item.distance} | {item.storeAddress}</Text> </View> </View> <Image src={spacing} className="space-img" style="pointer-events: none" /> {/*餐品信息(列表)*/} {mealsInfo} {/*优惠券信息 */} {(item.state === 1 || item.state === 2) && <View className="take-coupon"> <Text className="take-coupon-title">优惠券</Text> <View className="slec-coupon" onClick={that.selectCoupon.bind(that)}> <Text className="coupon-name">{couponIndex == index ? couponStr : '请选择优惠券'}</Text> <Image src={arrowRight} className="arrow-right" style="pointer-events: none" /> </View> </View>} {item.state === 3 && item.discountPrice > 0 && <View className="take-coupon"> <Text className="take-coupon-title">优惠券</Text> <Text className="coupon-name">-¥{item.discountPrice}</Text> </View>} <View className="total-view"> <Text>合计</Text> <View className="price-icon">¥<Text className="price-total">{totalStr}</Text></View> </View> <Image src={spacing} className="space-img" style="pointer-events: none" /> {/*支付*/} {(item.state === 1 || item.state === 2) && <View className="pay"> <View className="pay-channel"> <View className="channel"> <Image src={wepayIcon} className="channel-icon" style="pointer-events: none" /> <View className="channel-info"> <Text className="channel-name">微信支付</Text> <Text className="channel-desc">亿万用户的选择,更快更安全</Text> </View> </View> <Image src={iconSelect} className="sleced-btn" style="pointer-events: none" /> </View> <Image src={spacing} className="space-img" style="pointer-events: none" /> </View>} {/*订单信息(判断) */} <View className="order-info-list" style={item.state === 1 || item.state === 2 ? 'margin-bottom: 60px;' : 'margin-bottom: 10px;'}> <Text className="oil-text">下单时间:{item.createTime} </Text> <Text className="oil-text">订单编号:{item.orderNo} </Text> </View> </ScrollView> {/*底部固定的按钮 订单未支付 */} {(item.state === 1 || item.state === 2) && <View className="bottom-btn"> <View className="pay-btn" onClick={that.checkPay.bind(that)}>去支付</View> </View>} </SwiperItem>; }); {/* 左右滑动按钮 */} let leftBtn = <View className="pages-left-btn" onClick={that.goPrevious.bind(that)}> <Image src={btnLeft} className="pb-left" style="pointer-events: none" /> </View>; let rightBtn = <View className="pages-right-btn" onClick={this.goNext.bind(this)}> <Image src={btnRight} className="pb-left" style="pointer-events: none" /> </View>; let mealSwiper = <Swiper className="meals-swiper" indicatorDots indicatorColor={'rgb(114,114,114)'} indicatorActiveColor={'#727272'} onChange={this.swiperChange.bind(this)} current={orderIndex}> {mealList} </Swiper>; {/* 默认页(无订单) */} const defaultPage = <View className="default-page"> <Image src={noMeal} className="no-meal" style="pointer-events: none" /> <Text className="order-btn" onClick={this.goIndex}>去点餐</Text> <View className="go-history-order" onClick={this.goHistoryOrder}> <Text className="history-order-text">历史订单</Text> <Image src={arrowRight} className="arrow-right" style="pointer-events: none" /> </View> </View>; return <View className="container-take"> {meals[0] ? mealSwiper : defaultPage} {orderIndex > 0 && leftBtn} {orderIndex < meals.length - 1 && rightBtn} {showPrize && <Prize onTapThePrize={this.tapThePrize.bind(this)} />} {showCoupon && tapThePrize && <TooltipCoupon couponsData={couponList} notScroll={0} afterClose={0} />} {showNoPrize && tapThePrize && <NoPrize onTapNoPrize={this.closeNoPrize.bind(this)} onTapClose={this.closeNoPrize.bind(this)} />} </View>; } // 滑块改变 swiperChange(e) { let orderIndex = e.detail.current; this.setState({ orderIndex }); } // 返回首页点餐 goIndex() { _switchTab({ url: "/pages/index/index?v=" + new Date().getTime() }); } //历史订单 goHistoryOrder() { let userId = localStorage.getItem('userId'); if (userId) Taro.navigateTo({ url: "/pages/my/order_history/order_history?v=" + new Date().getTime() });else Taro.navigateTo({ url: "/pages/login/login?v=" + new Date().getTime() }); } //导航去门店 goLocation() { let { meals, orderIndex } = this.state; let order = meals[orderIndex]; JSWX.openLocation({ latitude: order.latitude, longitude: order.longitude, name: order.storeName, address: order.storeAddress }); } //电话联系门店 contactPoint(e) { e.stopPropagation(); let { meals, orderIndex } = this.state; let order = meals[orderIndex]; _makePhoneCall({ phoneNumber: order.storePhoneNumber + '' }); } selectCoupon() { let { meals, orderIndex } = this.state; let order = meals[orderIndex]; Taro.navigateTo({ url: '/pages/take_meals/select_coupon/select_coupon?orderId=' + order.id + '&v=' + new Date().getTime() }); } //左右滑动按钮 goPrevious(e) { e.stopPropagation(); let { orderIndex } = this.state; if (orderIndex > 0) orderIndex--; this.setState({ orderIndex }); } goNext(e) { e.stopPropagation(); let { meals, orderIndex } = this.state; if (orderIndex < meals.length - 1) orderIndex++; this.setState({ orderIndex }); } //获取微信JS接口参数 getWeChatJSApiParam() { Netservice.request({ url: 'heque-eat/we_chat_public_number/get_signature?url=' + encodeURIComponent(location.href.split('#')[0]), method: 'GET', success: res => { JSWX.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: Common.AppId, // 必填,企业号的唯一标识,此处填写企业号corpid timestamp: res.data.timestamp, // 必填,生成签名的时间戳(10位) nonceStr: res.data.nonceStr, // 必填,生成签名的随机串,注意大小写 signature: res.data.signature, // 必填,签名, jsApiList: ['chooseWXPay', 'openLocation', 'updateAppMessageShareData', 'updateTimelineShareData'] // 必填,需要使用的JS接口列表, }); JSWX.ready(function () { JSWX.error(function (err) { console.log("config信息验证失败,err=" + JSON.stringify(err)); }); //分享给好友 JSWX.updateAppMessageShareData({ title: Common.ShareTitle, // 分享标题 desc: Common.ShareDesc, // 分享描述 link: Common.ShareWebsite, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: Common.ShareImgUrl, // 分享图标 success: function () {} }); //分享到朋友圈 JSWX.updateTimelineShareData({ title: Common.ShareTitle, // 分享标题 link: Common.ShareWebsite, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: Common.ShareImgUrl, // 分享图标 success: function () {} }); }); } }); } //查订单支付金额 checkPay() { if (!this.canPayClick) return; this.canPayClick = false; setTimeout(() => { this.canPayClick = true; }, 1500); _showLoading({ title: '努力加载中…' }); let { meals, orderIndex } = this.state; let order = meals[orderIndex]; let userCardMedalId = {}; const currentCoupon = getGlobalData('currentCoupon') || {}; const couponId = currentCoupon.id; if (couponId) { userCardMedalId = { userCardMedalId: couponId }; } let that = this; //查订单支付金额 Netservice.request({ url: 'heque-coupon/discount_coupon/query_real_pay_price', method: 'GET', data: { ...userCardMedalId, orderId: order.id }, success: function (res) { _hideLoading(); if (res.code !== Common.NetCode_NoError) { _showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } let totalPrice = res.data.totalPrice; if (parseInt(parseFloat(totalPrice) * 100) > parseInt(0)) that.goWechatPay(totalPrice);else that.zeroPay(totalPrice); }, error: function (err) { _hideLoading(); _showToast({ title: '查询支付金额失败', icon: 'none', duration: 2000 }); } }); } //微信支付 goWechatPay(price) { _showLoading({ title: '努力加载中…' }); let { meals, orderIndex } = this.state; let order = meals[orderIndex]; const openId = localStorage.getItem('openId'); let userCardMedalId = {}; const currentCoupon = getGlobalData('currentCoupon') || {}; const couponId = currentCoupon.id; if (couponId) { userCardMedalId = { userCardMedalId: couponId }; } let that = this; Netservice.request({ url: 'heque-eat/wechat_pay/hsf_user_payment', method: 'POST', data: { ...userCardMedalId, id: order.id, paymentPrice: price, channel: 'h5', openId: openId }, success: function (res) { _hideLoading(); if (res.code !== Common.NetCode_NoError) { _showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } let params = res.data; JSWX.chooseWXPay({ timestamp: params.timeStamp, nonceStr: params.nonceStr, package: params.package, signType: params.signType, paySign: params.sign, success: function (res1) { // 支付成功后的回调函数 setGlobalData('currentCoupon', {}); that.getMeals(); }, cancel: function (res2) { _showToast({ title: '支付取消', icon: 'none', duration: 2000 }); }, fail: function (res3) { console.log('-->chooseWXPay, fail:' + JSON.stringify(res3)); _showToast({ title: '支付失败', icon: 'none', duration: 2000 }); } }); }, error: function (err) { _hideLoading(); _showToast({ title: '支付失败', icon: 'none', duration: 2000 }); } }); } //零元支付 zeroPay(price) { _showLoading({ title: '努力加载中…' }); let { meals, orderIndex } = this.state; let order = meals[orderIndex]; let userCardMedalId = {}; const currentCoupon = getGlobalData('currentCoupon') || {}; const couponId = currentCoupon.id; if (couponId) { userCardMedalId = { userCardMedalId: couponId }; } let that = this; Netservice.request({ url: 'heque-eat/wechat_pay/zero_element_pay', method: 'POST', data: { ...userCardMedalId, id: order.id, paymentPrice: price, channel: 'h5' }, success: function (res) { _hideLoading(); if (res.code !== Common.NetCode_NoError) { _showToast({ title: res.message, icon: 'none', duration: 2000 }); return; } setGlobalData('currentCoupon', {}); that.getMeals(); }, error: function (err) { _hideLoading(); _showToast({ title: '支付失败', icon: 'none', duration: 2000 }); } }); } //查询未领取的优惠券 getCoupons() { let userId = localStorage.getItem('userId'); if (!userId) return; let that = this; Netservice.request({ url: 'heque-coupon/discount_coupon/get_not_read?userId=' + userId, method: 'GET', success: res => { if (res.code == Common.NetCode_NoError) { let coupons = res.data; let prizes = coupons.filter(function (ele) { return ele.receiveType == 3; }); let prizeValue = 0; if (prizes.length > 0) { let prize = prizes[0]; prizeValue = prize.faceValue; } let zeroCouponIds = []; prizes.map((item, index) => { // if (item.faceValue <= 0) //零元券 zeroCouponIds.push(item.id); //自动领取 }); if (zeroCouponIds.length > 0) that.readCoupons(zeroCouponIds); that.setState({ couponList: prizes, zeroCouponIds: zeroCouponIds, showPrize: prizes.length > 0, // showPrize: true, showCoupon: prizes.length > 0 && prizeValue > 0, //是否显示优惠券弹框 showNoPrize: prizes.length > 0 && prizeValue <= 0 }); } } }); } //修改已读优惠券 readCoupons(ids) { let cardIds = ids.join(','); Netservice.request({ url: 'heque-coupon/discount_coupon/user_has_read', method: 'GET', data: { userCardMedalId: cardIds }, success: res => {} }); } tapThePrize(e) { this.setState({ tapThePrize: true }); setTimeout(() => { this.setState({ showPrize: false }); }, 2200); // const { couponList } = this.state; // let couponIds = []; // couponList.map((item, index) => { // couponIds.push(item.id) // }) // //自动领取 // if (couponIds.length > 0) // this.readCoupons(couponIds); } closeNoPrize(e) { this.setState({ showNoPrize: false }); } // 取消订单弹窗 toCancle(e) { e.stopPropagation(); let that = this; _showModal({ content: '确定取消订餐?', success(res) { if (res.confirm) { that.cancleOrder(); } } }); } // 取消订单 cancleOrder() { _showLoading({ title: '努力加载中…' }); const { orderIndex, meals } = this.state; const id = meals[orderIndex].id; Netservice.request({ url: 'heque-eat/eat/delete_order?id=' + id, method: 'GET', success: res => { _hideLoading(); if (res.code == Common.NetCode_NoError) this.getMeals();else _showToast({ title: res.message, icon: 'none', duration: 2000 }); }, fail: function (error) { _hideLoading(); _showToast({ title: '取消订单失败', icon: 'none', duration: 2000 }); } }); } }
dd5ce6443c7a18309c87b79b52fad9b16fb94026
[ "JavaScript", "Markdown" ]
39
JavaScript
wys97/heshifu
d86f5ae9998fbb51fc1e25fcb2ab86cddd569824
4610a8dd82ea274875c2949518fe9c75c260bd5a
refs/heads/master
<file_sep>/* * Descripition: burn ID * * Copyright : SDMC Inc. Jul 13, 2013 * * Created by Ronny <<EMAIL>> */ #ifndef __IDBURNER_H__ #define __IDBURNER_H__ #define MAC_ADDR_START 0x04 #define MAC_ADDR_LENGTH 0x06 #define MAC2_ADDR_START 0x40 #ifdef NEW_SN_LENGTH #define USER_DEVICE_ID_ADDR_START 0x0F #define USER_DEVICE_ID_ADDR_LENGTH 0x19 #elif NEW_SN_LENGTH32 #define USER_DEVICE_ID_ADDR_START 0x0F #define USER_DEVICE_ID_ADDR_LENGTH 0x20 #else #define USER_DEVICE_ID_ADDR_START 0x10 #define USER_DEVICE_ID_ADDR_LENGTH 0x25 #endif #define USER_PRIVATE_ID_ADDR_START 0x28 #define USER_PRIVATE_ID_ADDR_LENGTH 0x08 #define USER_HARDWARE_VERSION_ID_START 0x30 #define USER_HARDWARE_VERSION_ID_LENGTH 0x08 #define USER_TUNER_TYPE_ADDR_TYPE 0x39 //用于判断tuner的类型 #define USER_TUNER_TYPE_ADDR_LENGTH 1 #define ACTIVE_CODE_ADDR_START 0x50 #define ACTIVE_CODE_ADDR_LENGTH 0x10 #define DM2016_DEV_ADDR 0xa0 #define EEPROM_MAX_SIZE 0x98 #define EEPROM_DEVICE_ADDR 0xa0 #define EEPROM_WRITE_DELAY_MS 20 #define MAX_I2C_MSG 2 #define D_SUCCESS 0x0 #define WRITE_DATA_DELAY 20000 //~ #define __PLATFORM_MESSAGE__ #ifdef __PLATFORM_MESSAGE__ #define LOG_TAG "IDBURNER" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) #define DPrintf LOGE #define DError LOGE #define DInfo LOGI #else #define DPrintf printf #define DError printf #define DInfo printf #endif #ifdef __cplusplus extern "C" { #endif /*********************************************** *** activeCode 16 byte ************************************************/ int readActivecode(char* activeCode); int writeActivecode(char* activeCode); /*********************************************** *** sn 8 byte ************************************************/ int readSN(char* sn); int writeSN(char* sn); /*********************************************** *** chipId 8 byte ************************************************/ int readChipID(char* chipId); int writeChipID(char* chipId); /*********************************************** ***Function: write mac to hardware dm2016 ***input: *** data: in data buffer, 6Bytes, be sure it's clean ***return: *** =0: on success *** <0: on error ************************************************/ int writeMacAddr(const char *data); /*********************************************** ***Function: read mac from hardware dm2016 ***input: *** data: out data buffer,at least 6Bytes, be sure it's clean ***return: *** =0: on success *** <0: on error ************************************************/ int readMacAddr(char *data); /*********************************************** ***Function: write mac to hardware dm2016 ***input: *** data: in data buffer, 6Bytes, be sure it's clean ***return: *** =0: on success *** <0: on error ************************************************/ int writeMac2Addr(const char *data); /*********************************************** ***Function: read mac from hardware dm2016 ***input: *** data: out data buffer,at least 6Bytes, be sure it's clean ***return: *** =0: on success *** <0: on error ************************************************/ int readMac2Addr(char *data); /*********************************************** ***Function: read device id from hardware ***input: *** data: out data buffer, at least 24Bytes, be sure it's clean ***return: *** =0: on success *** <0: on error ************************************************/ int readUserDeviceID(char *data); /*********************************************** ***Function: write device id to hardware ***input: *** data: in data buffer, 24Bytes ***return: *** =0: on success *** <0: on error ************************************************/ int writeUserDeviceID(const char *data); /*********************************************** ***Function: read user private id to hardware ***input: *** data: out data buffer, at least 8 Bytes ***return: *** =0: on success *** <0: on error ************************************************/ int readUserPrivateID(char *data); /*********************************************** ***Function: write user private id to hardware ***input: *** data: in data buffer, 8 Bytes ***return: *** =0: on success *** <0: on error ************************************************/ int writeUserPrivateID(const char *data); /*********************************************** ***Function: read user hardware version id from hardware ***input: *** data: out data buffer, at least 8 Bytes ***return: *** =0: on success *** <0: on error ************************************************/ int readUserHardwareVersionID(char *data); /*********************************************** ***Function: write user hardware version id to eeprom ***input: *** data: in data buffer, 8 Bytes ***return: *** =0: on success *** <0: on error ************************************************/ int writeUserHardwareVersionID(const char *data); /*********************************************** ***Function: write RSA private key to hardware ***input: *** keyPath: in ,key file full path, limit max 256 Bytes *** macAddr: in ,mac addr string, fixed 6 Bytes ***return: *** =0: on success *** <0: on error ***notes: ************************************************/ int edsv_keyBurn(const char *keyPath, const char *macAddr); /*********************************************** ***Function: checking writed RSA private key on hardware ***input: *** keyPath: in ,key file full path, limit max 256 Bytes *** macAddr: in ,mac addr string, fixed 6 Bytes ***return: *** =0: on success *** <0: on error ***notes: ************************************************/ int edsv_keyCheck(const char *keyPath, const char *macAddr); /*********************************************** ***Function: test ddr and hardware on board ***input: *** nCount: in ,test times ***return: *** =0: on success *** <0: on error *** -1: test error *** -2: no memery error ***notes: ************************************************/ int ddrTest(int nCount); #ifdef __cplusplus } #endif #endif <file_sep>/**@defgroup TYPEDEF TYPEDEF 定义SDI乃至整个EastWin系列软件中的基本数据类型 @brief Typedef模块对应头文件sdi2_typedef.h,主要定义SDI乃至整个Eastwin系列软件中 的基本数据类型,如SDI_BOOL、SDI_HANDLE等,没有接口需要实现。现对定义的32位整 数型变量和64位整数型变量的定义做如下说明: - 本模块虽然有定义SDI_INT32、SDI_UINT32等32位整数型变量,但除非需要精确控制 变量的长度,如位运行,否则Eastwin会尽量使用C语言原生的数据结构而不是这里的定义。\n - 如果平台不支持原生64位整数(这样的平台已经越来越少了),或者对64位整数的运算不 符合C99规范,则不需要定义MMCP_SUPPORT_LL宏,这种情况下SDI会通过一个Struct模 拟64位整数,并在Eastwin内部提供该模拟的64位数学运算方法。需要特别注意的是,部分 SDI接口中已包含了SDI_UINT64类型的参数,在实现这些接口时,若需要涉及64位整数的 运算,需移植层自行实现。\n @note 本模块仅定义结构,没有接口需要实现。 @note 除非特别说明,整个SDI接口必须保证线程安全。 @version 2.0.3 2009/08/24 去掉64位运算宏,由平台去实现。 @version 2.0.2 2009/08/20 增加64位运算宏,移除公共返回错误代码 @version 2.0.1 2009/07/27 初稿 @{ */ //这里描述整个SDI的总体描述及版本信息,所有涉及SDI的改动,请在这里记录 /**@mainpage Unified Driver Interface(SDI2.0) 文档 @version <B>SDI_V2.1.1</B> 2009/09/26 - 增加更详细的模块总体说明及要点说明 - 调整大量接口语言描述使之更清晰更容易理解 - 去掉枚举最后一个成员的逗号,以解决部分平台无法编译通过的问题 - 添加Tuner,Demux连接状态查询功能;添加Tuner和Demux不可连接的错误代码说明 - 修改获取Tuner信息接口,使得现在可以单独获取部分信息以提高效率 - 修正一些文档语言描述性的错误 @version <B>SDI_V2.1.0</B> 2009/09/09 - 增加可移动设备的支持,包括Tuner,存储设备;统一了可移动存储设备的接口 @version <B>SDI_V2.0.3</B> 2009/08/28 - 增加了图片硬解码接口;增加了demux连接tuner的接口 @version <B>SDI_V2.0.2</B> 2009/08/25 - 经过第一次综合评审 @version <B>SDI_V2.0.1</B> 2009/08/16 - 初始版本 */ #ifndef _SDI2_TYPEDEF_H_ #define _SDI2_TYPEDEF_H_ #ifdef __cplusplus extern "C" { #endif /***********以下内容在绝大多数平台上,不需要改动*********************/ typedef int SDI_BOOL; ///< 布尔类型 typedef void * SDI_HANDLE; ///< 句柄类型,其长度等于指针长度。note Eastwin会将SDI_NULL当做一个非法的句柄,请是现实特别注意所有Handle的取值范围 //除非需要精确控制长度,否则不建议使用以下定义 typedef signed char SDI_INT8; ///< 8位有符号数 typedef unsigned char SDI_UINT8; ///< 8位无符号数 typedef signed short SDI_INT16; ///< 16位有符号数 typedef unsigned short SDI_UINT16; ///< 16位无符号数 typedef signed long SDI_INT32; ///< 32位有符号数 typedef unsigned long SDI_UINT32; ///< 32位无符号数,注意禁止使用SDI_UINT32存储指针 //gcc,VC提供的头文件均按此方式定义 #ifdef __cplusplus #define SDI_NULL 0 #else #define SDI_NULL ((void *)0) #endif #ifndef NULL #define NULL (void *)0 #endif #define SDI_FALSE (0 == 1) #define SDI_TRUE (!(SDI_FALSE)) /***********以下内容可能会根据平台的不同,经常改变,定义以下结构仅为兼容部分第三方代码而设,请尽量不要使用*********************/ /**@brief 若平台支持64位数,则必须定义以下类型,否则可不关注 @note 该宏定义必须由平台决定是否支持,并进行定义 */ #ifdef MMCP_SUPPORT_LL typedef long long SDI_INT64; ///< 64位有符号数,当定义MMCP_SUPPORT_LL时有效 typedef unsigned long long SDI_UINT64; ///< 64位无符号数,当定义MMCP_SUPPORT_LL时有效 #else /**@brief 64位有符号数结构体*/ typedef struct { SDI_UINT32 low; ///< 低32位 SDI_INT32 high;///< 高32位 }SDI_INT64; /**@brief 64位无符号数结构体*/ typedef struct { SDI_UINT32 low;///< 低32位 SDI_UINT32 high;///< 高32位 }SDI_UINT64; #endif #ifdef __cplusplus } #endif /** @} */ #endif //_SDI2_TYPEDEF_H_ <file_sep>package com.sdmc.jni; import com.sdmc.jni.FactoryBurn.BurnPermissionException; public class FactoryUtil { public static long CMD_EXCUTE_TIME_OUT = 5000; private static final String KEY_VERIFIER = "sdmccoress1234"; private static final String INVALID_MAC_SECOND_POSITION = "13579BDF"; private static final String MAC_VALID_ZERO = "000000000000"; private static final String MAC_VALID_FF = "ffffffffffff"; public static final String SN_FLAG = "NEW"; public static final int SN_FLAGED_LENGTH_MAX = 25; //the max length of sn , which can set flag public static final int SN_FLAG_LENGTH = 5; private static final int MAC_VALID_LEN = 12; public static final String DEVICE_SN_EPPROM_DEFAULT_VALUED = "ffffffffffffffffffffffffffffffffffffffffffffffff"; private static final String TAG = "FactoryUtil"; private static String mVerifyKey; private static int mS2SNLen = 10; private static int nS2ACLen = 10; public static void setPermissionKey(String key){ mVerifyKey = key; } /*public static String getVerifyKey(){ return KEY_VERIFIER; }*/ public static void permissionVerify() throws BurnPermissionException { if(!isVerifyKey(mVerifyKey)){ throw new BurnPermissionException(mVerifyKey); } } public static boolean checkMACIDValid(String macid) { if(macid.length() == 32){ return true; } return false; } public final static boolean checkValid(final String str, final int length, final int... multiOpts) { if (str == null) { return false; } else { int len = str.length(); boolean valid = false; valid = len == length; for (int l : multiOpts) { if (l == len) { valid = true; break; } } return valid; } } public final static String wrapMe(final String oriStr, final int maxLen) { if (oriStr == null) { return null; } int num = maxLen - oriStr.length(); StringBuffer sb = new StringBuffer(oriStr); for (int i = 0; i < num; i++) { sb.append('0'); } return sb.toString(); } public synchronized static void setSNLen(int len) { mS2SNLen = len; } public static int getSNLen() { return mS2SNLen; } public synchronized static void setACLen(int len) { nS2ACLen = len; } public static int getACLen() { return nS2ACLen; } public static boolean isMACValid(String mac) { if(mac.equals("")){ return false; } String macstr = mac.replaceAll(":", ""); if(macstr.length()!= MAC_VALID_LEN){ return false; } String secondInvalid = INVALID_MAC_SECOND_POSITION; // "13579bdf"; String secondStr = macstr.substring(1, 2); String secondStrLow = secondStr.toLowerCase(); String secondStrHigh = secondStr.toUpperCase(); if (secondInvalid.contains(secondStrLow) || secondInvalid.contains(secondStrHigh)) { return false; } if (macstr.equalsIgnoreCase(MAC_VALID_ZERO) || macstr.equalsIgnoreCase(MAC_VALID_FF)) { return false; } for(int i = 0; i < macstr.length(); i ++){ try { String signleStr = macstr.substring(i, i + 1); int value = -1; int singlehex = Integer.valueOf(bin2hex(signleStr.toUpperCase())); if(singlehex <= Integer.valueOf(bin2hex("9"))){ value = singlehex - Integer.valueOf(bin2hex("0")); } if(singlehex >= Integer.valueOf(bin2hex("A"))){ value = singlehex - Integer.valueOf(bin2hex("A")) + 10; } CoreSSLog.d("isMACValid ", "value = " + value); if((value < 0) || (value > 0xf)){ return false; } } catch (NumberFormatException e) { CoreSSLog.d("NumberFormatException ", macstr); return false; } } return true; } public static String bin2hex(String bin) { bin = bin.toUpperCase(); char[] digital = "0123456789ABCDEF".toCharArray(); StringBuffer sb = new StringBuffer(""); byte[] bs = bin.getBytes(); int bit; for (int i = 0; i < bs.length; i++) { bit = (bs[i] & 0x0f0) >> 4; sb.append(digital[bit]); bit = bs[i] & 0x0f; sb.append(digital[bit]); } return sb.toString(); } public static String hex2bin(String hex) { if(hex.equalsIgnoreCase(DEVICE_SN_EPPROM_DEFAULT_VALUED)){ return ""; } hex = hex.toUpperCase(); String digital = "0123456789ABCDEF"; char[] hex2char = hex.toCharArray(); byte[] bytes = new byte[hex.length() / 2]; int temp; for (int i = 0; i < bytes.length; i++) { temp = digital.indexOf(hex2char[2 * i]) * 16; temp += digital.indexOf(hex2char[2 * i + 1]); bytes[i] = (byte) (temp & 0xff); } return new String(bytes); } public static boolean isDeviceSNValid(String deviceStr, int defaultLen) { return (deviceStr != null && deviceStr.length() == defaultLen); } public static String getValidStrWrite(String deviceStr, int standardSnLen, int defaultLen) { String deviceValid = null; // add "0" at the end; if(standardSnLen > 0){ int len = standardSnLen; if(standardSnLen <= SN_FLAGED_LENGTH_MAX){ deviceStr = SN_FLAG + getValidStrLengthWrite(standardSnLen) + deviceStr; len = defaultLen - standardSnLen - SN_FLAG_LENGTH; } if(len >= 0 ){ deviceValid = addZeroForNum(deviceStr, len); } } CoreSSLog.d("deviceValid", "deviceValid = " + deviceValid + " Length " + deviceValid.length()); return deviceValid; } public static String getValidStrLengthWrite(int snLen){ String length = String.valueOf(snLen); if(snLen < 10){ length = "0" + length; } return length; } public static String addZeroForNum(String str, int strLength) { for (int i = 0 ; i < strLength; i ++ ) { StringBuffer sb = new StringBuffer(); sb.append(str).append("0");//�Ҳ�0 str = sb.toString(); } return str; } private static boolean isVerifyKey(String key) { return KEY_VERIFIER.equals(key); } } <file_sep>package com.sdmc.jni; import com.sdmc.jni.FactoryBurn.BurnPermissionException; /** * @author lx * for a20 and amlogic from idburner jni; */ public class FactoryBurnUtilImp extends FactoryBurnUtil{ private static final String TAG = "FactoryBurnUtilImp"; private static final String RECOVERY_DEVICE_NODE_ADDRESS = "/sys/class/saradc/ch0"; private static final int MAX_CHIP_ID_LENGTH = 16; private static int defaultSNLength = 30; //sn with flag "NEW"(3bytes) ,after with sn length(2bytes), end with sn(sn length bytes) private static int SN_LENGTH_INDEX_START = 3; private static int SN_LENGTH_INDEX_END = 5; @Override public int writeEthMAC(String ethMac) throws BurnPermissionException { FactoryUtil.permissionVerify(); byte[] ethMacBytes = BytesUtil.hexStringToBytes(ethMac); for(int i = 0; i < ethMacBytes.length; i++) { CoreSSLog.d(TAG, "ethMacBytes[" + i + "]= " + ethMacBytes[i]); } if (FactoryUtil.isMACValid(ethMac)) { return (IDburner.writeMacAddr(ethMacBytes) == FactoryBurn.REC_BURNER_SUCCESS) ? FactoryBurn.REC_BURNER_SUCCESS : FactoryBurn.ERROR_BURNER_FAILE; } else { return FactoryBurn.ERROR_IPUT_ID_INVALID; } } @Override public String readEthMAC() { byte[] macBytes = new byte[6]; int result = IDburner.readMacAddr(macBytes); CoreSSLog.d(TAG, "mac:" + macBytes[0]+ ":"+ macBytes[1] + ":"+ macBytes[2]+ ":"+ macBytes[3]+ ":"+ macBytes[4] + ":"+ macBytes[5]); if(result == 0) { StringBuilder stringBuilder = new StringBuilder(""); for (int i = 0; i < macBytes.length; i++) { int v = macBytes[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); if(i == macBytes.length - 1) { } else { stringBuilder.append(":"); } } return stringBuilder.toString(); } else { return ""; } } @Override public int writeDeviceSN(String sn, int standardSnLen) throws BurnPermissionException { FactoryUtil.permissionVerify(); String deviceStr = FactoryUtil.getValidStrWrite(sn ,standardSnLen, defaultSNLength); if ((FactoryUtil.isDeviceSNValid(deviceStr, defaultSNLength))) { deviceStr = FactoryUtil.bin2hex(deviceStr); return (IDburner.writeUserDeviceID(BytesUtil.hexStringToBytes(deviceStr)) == FactoryBurn.REC_BURNER_SUCCESS)? FactoryBurn.REC_BURNER_SUCCESS : FactoryBurn.ERROR_BURNER_FAILE; } else{ return FactoryBurn.ERROR_IPUT_ID_INVALID; } } @Override public String readDeviceSN(int snLen) { byte SNBytes[] = new byte[24]; int result = IDburner.readUserDeviceID(SNBytes); String burnerId = BytesUtil.bytes2HexString(SNBytes); burnerId = FactoryUtil.hex2bin(burnerId); if (burnerId.startsWith(FactoryUtil.SN_FLAG)) { int length = Integer.valueOf(burnerId.substring(SN_LENGTH_INDEX_START, SN_LENGTH_INDEX_END)); burnerId = burnerId.substring(SN_LENGTH_INDEX_END, length + SN_LENGTH_INDEX_END); }else if (snLen > 0 && (snLen <= burnerId.length())) { burnerId = burnerId.substring(0, snLen); } return burnerId; } @Override public int writeDeviceSN(String sn) throws BurnPermissionException { return writeDeviceSN(sn, sn.length()); } @Override public String readDeviceSN() { return readDeviceSN(defaultSNLength); } @Override public boolean checkHDCPFileValid(String keyFilePath) throws BurnPermissionException { FactoryUtil.permissionVerify(); return false; } @Override public int getHDCPKeyUsedNum(String keyFilePath) { return -1; } @Override public int getHDCPKeyUnusedNum(String keyFilePath) { return -1; } @Override public int writeHDCPKey(String keyFilePath) throws BurnPermissionException { FactoryUtil.permissionVerify(); return -1; } @Override public boolean isHDCPBurned() { return false; } @Override public boolean writeDongleSecureKey(String secureKey)throws BurnPermissionException { return false; } @Override public String readDongleSecureKey(int len) throws BurnPermissionException { return ""; } @Override public int writeS2AC(String acStr) throws BurnPermissionException { FactoryUtil.permissionVerify(); boolean valid = FactoryUtil.checkValid(acStr, 20, 10); if (valid) { FactoryUtil. setACLen(acStr.length()); int result = IDburner.writeS2Activecode(BytesUtil.hexStringToBytes(FactoryUtil.wrapMe(acStr, 20))); CoreSSLog.d(TAG,"writeS2AC result : " + result); if (result != 0) { return FactoryBurn.ERROR_BURNER_FAILE; } else { return FactoryBurn.REC_BURNER_SUCCESS; } } else { return FactoryBurn.ERROR_IPUT_ID_INVALID; } } @Override public int writeS2SN(String snStr) throws BurnPermissionException { return writeDeviceSN(snStr, snStr.length()); } @Override public int writeS2ChipID(String cid) throws BurnPermissionException { FactoryUtil.permissionVerify(); boolean valid = FactoryUtil.checkValid(cid, 16, 10); if (valid) { String chipidString = FactoryUtil.wrapMe(cid, 16); CoreSSLog.d(TAG, "chipidString: " + chipidString); byte[] chipidByte = BytesUtil.hexStringToBytes(chipidString); CoreSSLog.d(TAG, "chipidByte: " + chipidByte.length); for(int i = 0; i < chipidByte.length; i++) { CoreSSLog.d(TAG, "chipidByte[" + i +"] :" + chipidByte[i]) ; } int result = IDburner.writeChipID(chipidByte); CoreSSLog.d(TAG, "result : " + result); if (result != 0) { return FactoryBurn.ERROR_BURNER_FAILE; } else { return FactoryBurn.REC_BURNER_SUCCESS; } } else { return FactoryBurn.ERROR_IPUT_ID_INVALID; } } @Override public String readS2AC() { byte[] acBytes = new byte[16]; int result = IDburner.readS2Activecode(acBytes); if(result == 0) { return BytesUtil.bytes2HexString(acBytes).substring(0, FactoryUtil.getACLen()); } return ""; } @Override public String readS2SN() { return readDeviceSN(defaultSNLength); } @Override public String readS2ChipID() { String chipID = ""; byte[] chipIdBytes = new byte[MAX_CHIP_ID_LENGTH/2]; int result = IDburner.readChipID(chipIdBytes,MAX_CHIP_ID_LENGTH/2); if(result == 0) { chipID = BytesUtil.bytes2HexString(chipIdBytes); } return chipID; } @Override public int DDRTest(int testCount) { return IDburner.ddrTest(testCount); } @Override public String readDeviceID() { return ""; } @Override public int writeDeviceID(String deviceID) { return -1; } @Override public int writeMACID(String MACID) throws BurnPermissionException { return -1; } @Override public String readMACID() { return ""; } @Override public int writeWiFiMAC(String wifiMAC) throws BurnPermissionException { return -1; } @Override public String readWiFiMAC(String wifiModelType) { return ""; } @Override public boolean writeChipID(String chipID) throws BurnPermissionException { FactoryUtil.permissionVerify(); CoreSSLog.d(TAG, "chip id length: " + chipID.length()); if(chipID.length() > MAX_CHIP_ID_LENGTH ) { CoreSSLog.d(TAG, "chip id length invaild"); return false; } boolean valid = FactoryUtil.checkValid(chipID, chipID.length()); if (valid) { String chipidString = FactoryUtil.wrapMe(chipID, 16); CoreSSLog.d(TAG, "wrapMe chipidString: " + chipidString); byte[] chipidByte = BytesUtil.hexStringToBytes(chipidString); CoreSSLog.d(TAG, "chipidByte: " + chipidByte.length); for(int i = 0; i < chipidByte.length; i++) { CoreSSLog.d(TAG, "chipidByte[" + i +"] :" + chipidByte[i]) ; } int result = IDburner.writeChipID(chipidByte); CoreSSLog.d(TAG, "write ChipID result : " + result); if (result != 0) { return false; } else { return true; } } else { return false; } } @Override public String readChipID(int len) { String chipID = ""; byte[] chipIdBytes = new byte[len/2]; int result = IDburner.readChipID(chipIdBytes, len/2); for(int i= 0 ; i < len/2; i++) { CoreSSLog.d(TAG, "chipIdBytes[" + i + "] : " + chipIdBytes[i]); } if(result == 0) { chipID = BytesUtil.bytes2HexString(chipIdBytes); } return chipID; } @Override public boolean checkRecoveryButton() { String checkResult = FileAccessUtil.readStringFromFile(RECOVERY_DEVICE_NODE_ADDRESS); CoreSSLog.d(TAG, "checkResult: " + checkResult); return Integer.parseInt(checkResult, 10) >= 0 && Integer.parseInt(checkResult, 10) <= 512; } @Override public String readChipID() { return readChipID(MAX_CHIP_ID_LENGTH); } } <file_sep> #ifndef _SDI2_I2C_H #define _SDI2_I2C_H #include "sdi2_typedef.h" #include "sdi2_error.h" #ifdef __cplusplus extern "C" { #endif /**@brief I2C设备组 */ typedef enum { I2C_BLOCK0 = 0, I2C_BLOCK1, I2C_BLOCK2, I2C_BLOCK3, I2C_BLOCK4, I2C_BLOCK_MAX }I2CBlockIndex_E; /**@brief I2C总线的通信速率类型定义 */ typedef enum { I2C_SPEED_50K = 1, I2C_SPEED_100K, I2C_SPEED_200K, I2C_SPEED_300K, I2C_SPEED_400K, I2C_SPEED_MAX }I2CSpeed_E; typedef struct { I2CBlockIndex_E BlockIndex; I2CSpeed_E I2CSpeed; SDI_INT32 TimeOut; /* Unit is ms */ SDI_INT8 BoadID; }I2COpenParam_S; /** @brief 打开一个I2C设备; @param[in] param 描述I2C设备打开属性的结构体指针; @param[out] handle 打开I2C设备后生成的I2C句柄; @return 成功返回0;失败返回-1; */ SDI_Error_Code SDII2COpen(I2COpenParam_S *param, SDI_HANDLE *handle); /** @brief 关闭一个I2C设备; @param[in] handle 打开的I2C设备句柄; @return 成功返回0;失败返回-1; */ SDI_Error_Code SDII2CClose(SDI_HANDLE handle); /** @brief 通过I2C总线从设备读取数据; @param[in] handle I2C设备句柄; @param[in] devAddr I2C的设备地址; @param[in] buf 接收读取的数据的BUF的首地址指针; @param[in] len 读取数据的长度; @note 需要读取的数据长度必须小于等于BUF的长度; @return 成功返回0;失败返回-1; */ SDI_Error_Code SDII2CRead(SDI_HANDLE handle, SDI_UINT8 devAddr, SDI_UINT8 *buf, SDI_INT32 len); /** @brief 通过I2C总线向设备写入数据; @param[in] handle I2C设备句柄; @param[in] devAddr I2C的设备地址; @param[in] buf 待写入的数据BUF指针; @param[in] len 待写入的数据长度; @note 参数len必须小于等于BUF的长度; @return 成功返回0;失败返回-1; */ SDI_Error_Code SDII2CWrite(SDI_HANDLE handle, SDI_UINT8 devAddr, SDI_UINT8 *buf, SDI_INT32 len); /** @brief 通过I2C总线从设备的某个特定位置读取数据; @param[in] handle I2C设备句柄; @param[in] devAddr I2C的设备地址; @param[in] regAddr 存放要读取的数据的设备内偏移地址指针; @param[in] alen 存放偏移地址的BUF长度; @param[in] buf 接收读取的数据的BUF的首地址指针; @param[in] len 读取数据的长度; @note 需要读取的数据长度必须小于等于BUF的长度, 使用此接口在第一次传输完成后不带STOP信号。; @return 成功返回0;失败返回-1; */ SDI_Error_Code SDII2CReadWithRegAddr(SDI_HANDLE handle, SDI_UINT8 devAddr, SDI_UINT8 *regAddr, SDI_INT32 alen, SDI_UINT8 *buf, SDI_INT32 len); /** @brief 通过I2C总线从设备的某个特定位置开始写入数据; @param[in] handle I2C设备句柄; @param[in] devAddr I2C的设备地址; @param[in] regAddr 存放要写入的数据的设备内偏移地址指针; @param[in] alen 存放偏移地址的BUF长度; @param[in] buf 存放待写入的数据的BUF指针; @param[in] len 待写入数据的长度; @note 参数len必须小于等于BUF的长度,使用此接口在第一次传输完成后不带STOP信号。; @return 成功返回0;失败返回-1; */ SDI_Error_Code SDII2CWriteWithRegAddr(SDI_HANDLE handle, SDI_UINT8 devAddr, SDI_UINT8 *regAddr, SDI_INT32 alen, SDI_UINT8 *buf, SDI_INT32 len); #ifdef __cplusplus } #endif #endif //_SDI2_I2C_H<file_sep>LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_SRC_FILES := burner.cpp LOCAL_SHARED_LIBRARIES := libIDburn_d liblog LOCAL_C_INCLUDES := $(LOCAL_PATH)/../libIDburn LOCAL_MODULE := libidburnerjni ifeq ($(shell test $(PLATFORM_SDK_VERSION) -ge 26 && echo OK),OK) LOCAL_PROPRIETARY_MODULE := true endif LOCAL_CFLAGS += -Wno-unused-parameter \ -Wno-format LOCAL_C_INCLUDES += \ libnativehelper/include_jni/ include $(BUILD_SHARED_LIBRARY) <file_sep>package com.sdmc.jni; public class BytesUtil { public static void int2bytes(int n, byte[] bytes, int start){ for(int i = 0; i < 4; i ++){ bytes[i + start] = (byte)(n >> (24 - i * 8)); } } public static void float2bytes(float x, byte[] bytes, int start) { int l = Float.floatToIntBits(x); for (int i = 0; i < 4; i++) { bytes[start + i] = Integer.valueOf(l).byteValue(); l = l >> 8; } } public static void short2bytes(short s, byte[] bytes, int start){ for(int i = 0; i < 2; i ++){ bytes[i + start] = (byte)(s >> (8 - i * 8)); } } public static int byte2int(byte b){ return (int) (b & 0xff); } public static int bytes2int(byte[] b, int start){ return (int)(((b[start] & 0xff) << 24) | ((b[start + 1] & 0xff) << 16) | ((b[start + 2] & 0xff) << 8) | ((b[start + 3] & 0xff) << 0)); } public static void copyBytes(byte[] from, byte[] to, int start, int offset, int length) { for (int i = 0; i < length; i ++) { to[start + i] = from[i + offset]; } } public static String byte2HexString(byte b) { int v = b & 0xFF; String s = String.format("%02x", v); return s; } public static String bytes2HexString(byte[] bt) { StringBuilder stringBuilder = new StringBuilder(""); if (bt == null || bt.length <= 0) { return null; } for (int i = 0; i < bt.length; i++) { int v = bt[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString(); } /** * Convert hex string to byte[] * @param hexString the hex string * @return byte[] */ public static byte[] hexStringToBytes(String hexString) { if (hexString == null || hexString.equals("")) { return null; } hexString = hexString.toUpperCase(); int length = hexString.length() / 2; char[] hexChars = hexString.toCharArray(); byte[] d = new byte[length]; for (int i = 0; i < length; i++) { int pos = i * 2; d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); } return d; } /** * Convert char to byte * @param c char * @return byte */ private static byte charToByte(char c) { return (byte) "0123456789ABCDEF".indexOf(c); } } <file_sep>#include "IDburner.h" #include <malloc.h> #include <string.h> #include <jni.h> #include <android/log.h> #include <stdio.h> #undef JNIEXPORT #define JNIEXPORT extern "C" #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) JNIEXPORT jint JNICALL Java_com_sdmc_jni_IDburner_readMacAddr (JNIEnv *env, jclass thiz, jbyteArray jmacAddr) { const unsigned int MAC_LENGTH = 6; char macAddr[MAC_LENGTH+1] = {0}; int result = readMacAddr(macAddr); LOGE("read macAddr is %02x:%02x:%02x:%02x:%02x:%02x" \ ,macAddr[0], macAddr[1], macAddr[2], \ macAddr[3], macAddr[4], macAddr[5]); if(result == 0) { env->SetByteArrayRegion(jmacAddr, 0, MAC_LENGTH, (const jbyte *) macAddr); } else { LOGE("read macAddr fail!"); } return result; } JNIEXPORT jint JNICALL Java_com_sdmc_jni_IDburner_writeMacAddr (JNIEnv *env, jclass thiz, jbyteArray jmacAddr) { const unsigned int MAC_LENGTH = 6; char macAddr[MAC_LENGTH] = {0}; jbyte *tmpMacAddr = env->GetByteArrayElements(jmacAddr, 0); memcpy(macAddr, tmpMacAddr, MAC_LENGTH); LOGE("write macAddr %02x:%02x:%02x:%02x:%02x:%02x", \ macAddr[0], macAddr[1], macAddr[2], macAddr[3], macAddr[4], macAddr[5]); int result = writeMacAddr(macAddr); env->ReleaseByteArrayElements(jmacAddr,tmpMacAddr,0); return result; } JNIEXPORT jint JNICALL Java_com_sdmc_jni_IDburner_readUserDeviceID (JNIEnv *env, jclass thiz, jbyteArray juserDeviceID) { char userDeviceID[37] = {0}; int arryLen = env->GetArrayLength(juserDeviceID); int result = readUserDeviceID(userDeviceID); LOGE("read sn len is %d" , arryLen); LOGE("read device id %s" , userDeviceID); if(result == 0) { env->SetByteArrayRegion(juserDeviceID, 0, arryLen, (const jbyte *) userDeviceID); LOGE("read sn success"); } else { LOGE("read sn fail"); } return result; } JNIEXPORT jint JNICALL Java_com_sdmc_jni_IDburner_writeUserDeviceID (JNIEnv *env, jclass thiz, jbyteArray juserDeviceID) { int arryLen = env->GetArrayLength(juserDeviceID); const unsigned int SN_LENGTH = 37; char userDeviceID[SN_LENGTH] = {0}; LOGE("write sn len is %d" , arryLen); jbyte *tmpUserDeviceID = env->GetByteArrayElements(juserDeviceID, 0); memcpy(userDeviceID, tmpUserDeviceID, arryLen); LOGE("write user device id %s", userDeviceID); int result = writeUserDeviceID(userDeviceID); env->ReleaseByteArrayElements(juserDeviceID, tmpUserDeviceID, 0); return result; } JNIEXPORT jint JNICALL Java_com_sdmc_jni_IDburner_readS2Activecode (JNIEnv *env, jclass thiz, jbyteArray jactiveCode) { const unsigned int AC_LEN = 16; char activeCode[AC_LEN] = {0}; int result = readActivecode(activeCode); LOGE("read active code is %02x:%02x", activeCode[0], activeCode[1]); if(result == 0) { env->SetByteArrayRegion(jactiveCode, 0, AC_LEN, (const jbyte *) activeCode); LOGE("read active code success"); } else { LOGE("read active code fail"); } return result; } JNIEXPORT jint JNICALL Java_com_sdmc_jni_IDburner_writeS2Activecode (JNIEnv *env, jclass thiz, jbyteArray jactiveCode) { const unsigned int AC_LEN = 16; char activeCode[16] = {0}; jbyte * tmpActiveConde = env->GetByteArrayElements(jactiveCode, NULL); memcpy(activeCode, tmpActiveConde, AC_LEN); int result = writeActivecode(activeCode); env->ReleaseByteArrayElements(jactiveCode, tmpActiveConde, 0); return result; } JNIEXPORT jint JNICALL Java_com_sdmc_jni_IDburner_readChipID (JNIEnv *env, jclass thiz, jbyteArray jchipID, jint len) { char chipID[8] = {0}; int result = readChipID(chipID); int valueLength = LOGE("read chipid: %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x", \ chipID[0], chipID[1], chipID[2], chipID[3], chipID[4], chipID[5],\ chipID[6] ,chipID[7]); if(result == 0) { env->SetByteArrayRegion(jchipID, 0, len, (jbyte *) chipID); LOGE("readChipID success"); } else { LOGE("readChipID fail"); } return result; } JNIEXPORT jint JNICALL Java_com_sdmc_jni_IDburner_writeChipID (JNIEnv *env, jclass thiz, jbyteArray jchipID) { const unsigned int CHIPID_LENGTH = 8; char chipID[CHIPID_LENGTH] = {0}; jbyte *tmpChipID = env->GetByteArrayElements(jchipID, 0); memcpy(chipID, tmpChipID, CHIPID_LENGTH); LOGE("wired chipid: %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x", \ chipID[0], chipID[1], chipID[2], chipID[3], chipID[4], chipID[5],\ chipID[6] ,chipID[7]); int result = writeChipID(chipID); env->ReleaseByteArrayElements(jchipID, tmpChipID, 0); return result; } JNIEXPORT jint JNICALL Java_com_sdmc_jni_IDburner_ddrTest (JNIEnv *env, jclass thiz, jint jdata) { int count = jdata; int result = ddrTest(count); LOGE("Java_com_sdmc_jni_IDburner_ddrTest %02x", count); return result; } <file_sep>package com.sdmc.jni; public class IDburner { /*********************************************** ***Function: read device id from hardware ***input: *** data: out data buffer, at least 24Bytes, be sure it's clean ***return: *** 0: on success *** <0: on error ************************************************/ public static native int readUserDeviceID(byte[] userDeviceID); /*********************************************** ***Function: write device id to hardware ***input: *** data: in data buffer, 24Bytes ***return: *** 0: on success *** <0: on error ************************************************/ public static native int writeUserDeviceID(byte[] data); public static native int readMacAddr(byte[] macAddr); public static native int writeMacAddr(byte[] data); /*********************************************** ***31-37 burn AC SN ChipID for S2 . ************************************************/ public static native int readS2Activecode(byte[] ac); public static native int writeS2Activecode(byte[] ac); public static native int readChipID(byte[] chipID, int len); public static native int writeChipID(byte[] chipID); public static native int ddrTest(int count); static { System.loadLibrary("idburnerjni"); } } <file_sep>#include <stdio.h> #include <errno.h> #include <unistd.h> #include <malloc.h> #include <string.h> #include <fcntl.h> #include <time.h> //#include <linux/genhd.h> #include <android/log.h> #include <mtd/mtd-abi.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <netinet/in.h> #include <linux/if.h> #include <linux/if_arp.h> #include <sys/socket.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <android/log.h> #include <stdio.h> #include <string.h> #include "cutils/properties.h" #include "IDburner.h" #include "i2c-dev.h" //#include "efuse.h" //#include "EDSV_Key.h" //#include "blkinand.h" #include "sdi2/sdi2_i2c.h" #define MAC_SN_ATTAVH "/sys/class/unifykeys/attach" #define MAC_SN_NAME "/sys/class/unifykeys/name" #define MAC_SN_WRITE "/sys/class/unifykeys/write" #define MAC_SN_READ "/sys/class/unifykeys/read" #define MAX_STR_LEN 4096 #define MODE_AUTO 0 #define MODE_QUICK 1 #define MODE_READ 2 #define MODE_FUNC 3 void OSThreadSleep(unsigned int uMilliSeconds) { struct timespec delay; struct timespec rem; int rc; if (uMilliSeconds == 0) { return; } delay.tv_sec = (int) uMilliSeconds / 1000; delay.tv_nsec = 1000 * 1000 * (uMilliSeconds % 1000); for (;;) { rc = nanosleep(&delay, &rem); /* [u]sleep can't be used because it uses SIGALRM */ if (rc != 0) { if (errno == EINTR) { delay = rem; /* sleep again */ continue; } return; } break; /* done */ } return; } int I2cRead(unsigned long dwStartAddress, unsigned char * pucData, unsigned int uDataLength , unsigned int devAddr) { SDI_INT32 ret = 0; SDI_Error_Code err = SDI_SUCCESS; I2COpenParam_S sI2Cparam = {0}; SDI_HANDLE hI2C = SDI_NULL; SDI_UINT8 tmpAddr = 0; if (!pucData) { DError("pucData is NULL!"); return ret; } tmpAddr = dwStartAddress; sI2Cparam.BlockIndex = I2C_BLOCK2; sI2Cparam.I2CSpeed = I2C_SPEED_100K; sI2Cparam.TimeOut = 20; err = SDII2COpen(&sI2Cparam, &hI2C); if ((err != SDI_SUCCESS) || (hI2C == SDI_NULL)) { DError("%s_%d: SDII2COpen error, err:%d, hI2C:%d\n",__FUNCTION__,__LINE__,err,hI2C); return ret; } else { DError("open SDII2COpen success!\n"); } ret = SDII2CReadWithRegAddr(hI2C, devAddr, &tmpAddr, 1, pucData, uDataLength); if (ret != D_SUCCESS) { DError("read dm2016 dongle failed!\n"); } else { DError("read dongle 2016 success!\n"); } SDII2CClose(hI2C); return ret; } int I2cWrite(unsigned long dwStartAddress, const unsigned char * pucData, unsigned int uDataLength, unsigned int devAddr) { SDI_INT32 i = 0; SDI_INT32 ret = 0; SDI_Error_Code err = SDI_SUCCESS; I2COpenParam_S sI2Cparam = {0}; SDI_HANDLE hI2C = SDI_NULL; SDI_UINT8 tmpAddr = 0; if (!pucData) { DError("pucData is NULL!"); return ret; } tmpAddr = dwStartAddress; sI2Cparam.BlockIndex = I2C_BLOCK2; sI2Cparam.I2CSpeed = I2C_SPEED_100K; sI2Cparam.TimeOut = 20; err = SDII2COpen(&sI2Cparam, &hI2C); if ((err != SDI_SUCCESS) || (hI2C == SDI_NULL)) { DError("%s_%d: SDII2COpen error, err:%d, hI2C:%d\n",__FUNCTION__,__LINE__,err,hI2C); return ret; } else { DError("open SDII2COpen success!\n"); } while (i < uDataLength) { ret = SDII2CWriteWithRegAddr(hI2C, devAddr, &tmpAddr, 1, &pucData[i], 1); if (ret != D_SUCCESS) { DError("write dm2016 tmpAddr = %d failed!\n", tmpAddr); goto write_error; } else { DError("write dongle 2016 success!\n"); } //write buff deley usleep(WRITE_DATA_DELAY); i++; tmpAddr++; } write_error: SDII2CClose(hI2C); return ret; } int EPRRead(unsigned long dwStartAddress, unsigned char * pucData, unsigned int uDataLength ) { SDI_INT32 ret = 0; SDI_Error_Code err = SDI_SUCCESS; I2COpenParam_S sI2Cparam = {0}; SDI_HANDLE hI2C = SDI_NULL; SDI_UINT8 tmpAddr = 0; if (!pucData) { DError("pucData is NULL!"); return ret; } tmpAddr = dwStartAddress; sI2Cparam.BlockIndex = I2C_BLOCK2; sI2Cparam.I2CSpeed = I2C_SPEED_100K; sI2Cparam.TimeOut = 20; err = SDII2COpen(&sI2Cparam, &hI2C); if ((err != SDI_SUCCESS) || (hI2C == SDI_NULL)) { DError("%s_%d: SDII2COpen error, err:%d, hI2C:%d\n",__FUNCTION__,__LINE__,err,hI2C); return ret; } else { DError("open SDII2COpen success!\n"); } ret = SDII2CReadWithRegAddr(hI2C, DM2016_DEV_ADDR, &tmpAddr, 1, pucData, uDataLength); if (ret != D_SUCCESS) { DError("read dm2016 dongle failed!\n"); } else { DError("read dongle 2016 success!\n"); } SDII2CClose(hI2C); return ret; } int EPRWrite(unsigned long dwStartAddress, const unsigned char * pucData, unsigned int uDataLength) { SDI_INT32 i = 0; SDI_INT32 ret = 0; SDI_Error_Code err = SDI_SUCCESS; I2COpenParam_S sI2Cparam = {0}; SDI_HANDLE hI2C = SDI_NULL; SDI_UINT8 tmpAddr = 0; if (!pucData) { DError("pucData is NULL!"); return ret; } tmpAddr = dwStartAddress; sI2Cparam.BlockIndex = I2C_BLOCK2; sI2Cparam.I2CSpeed = I2C_SPEED_100K; sI2Cparam.TimeOut = 20; err = SDII2COpen(&sI2Cparam, &hI2C); if ((err != SDI_SUCCESS) || (hI2C == SDI_NULL)) { DError("%s_%d: SDII2COpen error, err:%d, hI2C:%d\n",__FUNCTION__,__LINE__,err,hI2C); return ret; } else { DError("open SDII2COpen success!\n"); } while (i < uDataLength) { ret = SDII2CWriteWithRegAddr(hI2C, DM2016_DEV_ADDR, &tmpAddr, 1, &pucData[i], 1); if (ret != D_SUCCESS) { DError("write dm2016 tmpAddr = %d failed!\n", tmpAddr); goto write_error; } else { DError("write dongle 2016 success!\n"); } //write buff deley usleep(WRITE_DATA_DELAY); i++; tmpAddr++; } write_error: SDII2CClose(hI2C); return ret; } #if 0 int EPRRead(unsigned long dwStartAddress, unsigned char * pucData, unsigned int uDataLength ) { int nRet = -1; signed long nI2C_Handle = -1; signed long i; unsigned char ucRegAddr=0; struct i2c_rdwr_ioctl_data work_queue; if(dwStartAddress > EEPROM_MAX_SIZE) { DError("EPRRead: dwStartAddress invalid\n"); return -1; } if(!pucData || (dwStartAddress+uDataLength) > EEPROM_MAX_SIZE) { DError("EPRRead: invalid params\n"); return -2; } nI2C_Handle=open(I2C_EEP_FILE, O_RDWR); if(nI2C_Handle < 0) { DError("open %s fail, %d\n" , I2C_EEP_FILE , nI2C_Handle); return -1; } else { //DError("open %s, %d\n" , I2C_EEP_FILE , nI2C_Handle); } nRet = ioctl(nI2C_Handle, I2C_TIMEOUT, 20/ 10); if(nRet != 0) { DError("set timeout error, %ld\n", nRet); } memset(&work_queue, 0, sizeof(struct i2c_rdwr_ioctl_data)); work_queue.nmsgs = 2; /* 消息数量 */ work_queue.msgs = (struct i2c_msg*)malloc(work_queue.nmsgs *sizeof(struct i2c_msg)); if (!work_queue.msgs) { DError("Memory alloc error\n"); if(close(nI2C_Handle)<0) { DError("close %s fail\n" , I2C_EEP_FILE); } return -1; } memset(work_queue.msgs, 0, work_queue.nmsgs *sizeof(struct i2c_msg)); ucRegAddr = dwStartAddress&0xff; work_queue.nmsgs = MAX_I2C_MSG; memset(work_queue.msgs, 0, work_queue.nmsgs *sizeof(struct i2c_msg)); work_queue.msgs[0].flags = I2C_M_TEN; work_queue.msgs[0].addr = (EEPROM_DEVICE_ADDR >> 1); work_queue.msgs[0].buf = &ucRegAddr; work_queue.msgs[0].len = 1; work_queue.msgs[1].flags = I2C_M_RD; work_queue.msgs[1].addr = (EEPROM_DEVICE_ADDR >> 1); work_queue.msgs[1].buf = pucData; work_queue.msgs[1].len = uDataLength; nRet = ioctl(nI2C_Handle, I2C_RDWR, (unsigned long) &work_queue); if(nRet < 0) { if(close(nI2C_Handle)<0) { DError("close %s fail\n" , I2C_EEP_FILE); } DError("EPRRead: ioctl failed\n"); nRet = -3; } if(close(nI2C_Handle)<0) { DError("close %s fail\n" , I2C_EEP_FILE); } free(work_queue.msgs); #if 0 for(i=0;i<uDataLength;i++){ DError("EPRRead success: 0x%x \n",pucData[i]); } #endif return 0; } int EPRWrite(unsigned long dwStartAddress, const unsigned char * pucData, unsigned int uDataLength) { int nRet = -1; signed long nI2C_Handle = -1; unsigned char pWriteBuf[16]={0}; unsigned int i = 0; struct i2c_rdwr_ioctl_data work_queue; if(dwStartAddress > EEPROM_MAX_SIZE) { DError("EPRWrite: dwStartAddress invalid\n"); return -2; } if(!pucData || (dwStartAddress+uDataLength) > EEPROM_MAX_SIZE) { DError("EPRWrite: invalid params\n"); return -1; } #if 0 for(i=0;i<uDataLength;i++){ DInfo("EPRWrite success: 0x%x \n",pucData[i]); } #endif nI2C_Handle=open(I2C_EEP_FILE, O_RDWR); if(nI2C_Handle < 0) { DError("open %s fail, %d\n" , I2C_EEP_FILE , nI2C_Handle); return -3; } else { //DError("open %s, %d\n" , I2C_EEP_FILE , nI2C_Handle); } nRet = ioctl(nI2C_Handle, I2C_TIMEOUT, 20/ 10); if(nRet != 0) { DError("set timeout error, %ld\n", nRet); } memset(&work_queue, 0, sizeof(struct i2c_rdwr_ioctl_data)); work_queue.nmsgs = 2; /* 消息数量 */ work_queue.msgs = (struct i2c_msg*)malloc(work_queue.nmsgs *sizeof(struct i2c_msg)); if (!work_queue.msgs) { DError("Memory alloc error\n"); if(close(nI2C_Handle)<0) { DError("close %s fail\n" , I2C_EEP_FILE); } return -1; } memset(work_queue.msgs, 0, work_queue.nmsgs *sizeof(struct i2c_msg)); for(i=0;i<uDataLength;i++) { //DError("uDataLength = %d\n",uDataLength); pWriteBuf[0] = (dwStartAddress+i)&0xff; pWriteBuf[1] = pucData[i]; work_queue.nmsgs = MAX_I2C_MSG; memset(work_queue.msgs, 0, work_queue.nmsgs *sizeof(struct i2c_msg)); work_queue.msgs[0].flags=I2C_M_TEN; work_queue.msgs[0].buf=pWriteBuf; work_queue.msgs[0].len=2; work_queue.msgs[0].addr = (EEPROM_DEVICE_ADDR >> 1); nRet = ioctl(nI2C_Handle , I2C_RDWR, (unsigned long) &work_queue); if(nRet < 0) { if(close(nI2C_Handle)<0) { DError("Error: close %s fail\n" , I2C_EEP_FILE); } DError("Error: ioctl I2C_RDWR failed, i = %d,%d(%s)\n" , i,errno,strerror(errno)); //add by Ronny free(work_queue.msgs); close(nI2C_Handle); return -3; } OSThreadSleep(EEPROM_WRITE_DELAY_MS); } if(close(nI2C_Handle)<0) { DError("close %s fail\n" , I2C_EEP_FILE); } free(work_queue.msgs); //add by Ronny return 0; } #endif int open_i2c_dev(int i2cbus, char *filename, size_t size, int quiet) { int file; snprintf(filename, size, "/dev/i2c/%d", i2cbus); filename[size - 1] = '\0'; file = open(filename, O_RDWR); if (file < 0 && (errno == ENOENT || errno == ENOTDIR)) { sprintf(filename, "/dev/i2c-%d", i2cbus); file = open(filename, O_RDWR); } if (file < 0 && !quiet) { if (errno == ENOENT) { fprintf(stderr, "Error: Could not open file " "`/dev/i2c-%d' or `/dev/i2c/%d': %s\n", i2cbus, i2cbus, strerror(ENOENT)); } else { fprintf(stderr, "Error: Could not open file " "`%s': %s\n", filename, strerror(errno)); if (errno == EACCES) fprintf(stderr, "Run as root?\n"); } } return file; } static int scan_i2c_bus(int file, int mode, int first, int last) { int i, j; int res; printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\n"); for (i = 0; i < 128; i += 16) { printf("%02x: ", i); for(j = 0; j < 16; j++) { fflush(stdout); /* Skip unwanted addresses */ if (i+j < first || i+j > last) { printf(" "); continue; } /* Set slave address */ if (ioctl(file, I2C_SLAVE, i+j) < 0) { if (errno == EBUSY) { printf("UU "); continue; } else { fprintf(stderr, "Error: Could not set " "address to 0x%02x: %s\n", i+j, strerror(errno)); return -1; } } /* Probe this address */ switch (mode) { case MODE_QUICK: /* This is known to corrupt the Atmel AT24RF08 EEPROM */ res = i2c_smbus_write_quick(file, I2C_SMBUS_WRITE); break; case MODE_READ: /* This is known to lock SMBus on various write-only chips (mainly clock chips) */ res = i2c_smbus_read_byte(file); break; default: if ((i+j >= 0x30 && i+j <= 0x37) || (i+j >= 0x50 && i+j <= 0x5F)) res = i2c_smbus_read_byte(file); else res = i2c_smbus_write_quick(file, I2C_SMBUS_WRITE); } if (res < 0) printf("-- "); else printf("%02x ", i+j); } printf("\n"); } return 0; } static int isZeroEtherAddr(const char *addr) { return !(addr[0] | addr[1] | addr[2] | addr[3] | addr[4] | addr[5]); } static int isMulticastEtherAddr(const char *addr) { return ((addr[0] != 0xff) && (0x01 & addr[0])); } static int isMacValid(const char *pcMac) { return !isZeroEtherAddr(pcMac) && !isMulticastEtherAddr(pcMac); } static int sdmc_get_sysfs_str(const char *path, char *value) { int fd; int val = 0; char bcmd[MAX_STR_LEN + 1] = { 0 }; int len = 0; fd = open(path, O_RDONLY); if (fd >= 0) { len = read(fd, bcmd, sizeof(bcmd)); DError("sdmc_get_sysfs_str:%d", len); close(fd); } else { DError("unable to open file %s,err: %s", path, strerror(errno)); } // strcpy(value, bcmd); memcpy(value,bcmd,len); return val; } static int sdmc_fileecho(const char *name, const char *cmd, unsigned int uDataLength) { int fd, len, ret; if(NULL == name || NULL == cmd) { return -1; } fd = open(name, O_WRONLY); if(fd==-1) { printf("cannot open file \"%s\"\n", name); return -1; } //printf("open file \"%s\" ok\n", name); //len = strlen(cmd); len = uDataLength; ret = write(fd, cmd, len); if(ret!=len) { printf("write failed file:\"%s\" cmd:\"%s\" error:\"%s\"\n", name, cmd, strerror(errno)); close(fd); return -1; } //printf("write file \"%s\" ok\n", name); close(fd); return 0; } int writeMacAddrToFlash(char *data, unsigned int uDataLength) { int nRet = -1; DError("==========writeMacAddrToFlash==========len:%d=uDataLength:%d=",strlen(data), uDataLength); nRet = sdmc_fileecho(MAC_SN_ATTAVH, "1", 1); nRet |= sdmc_fileecho(MAC_SN_NAME, "mac", 3); nRet |= sdmc_fileecho(MAC_SN_WRITE, data, uDataLength); nRet |= sdmc_fileecho(MAC_SN_ATTAVH, "0", 1); return nRet; } int readMacAddrFromFlash(const char *data) { int nRet = -1; DError("==========readMacAddrFromFlash==========len:%d==",strlen(data)); nRet = sdmc_fileecho(MAC_SN_ATTAVH, "1", 1); nRet |= sdmc_fileecho(MAC_SN_NAME, "mac", 3); nRet |= sdmc_get_sysfs_str(MAC_SN_READ, data); nRet |= sdmc_fileecho(MAC_SN_ATTAVH, "0", 1); return nRet; } int writeMacAddr(const char *data) { char value[PROPERTY_VALUE_MAX] = {0}; if(!data) { return -1; } if(isMacValid(data)) { int i = 0; for(i=0;i<6;i++) { DError("0x%x ",data[i]); } DError("\n"); property_get("ro.sdmc.thirdpart", value, "0"); if (!strncmp(value, "true", 4)) { return writeMacAddrToFlash(data, MAC_ADDR_LENGTH); } DError("==========writeMacAddrTodm2016============"); return EPRWrite(MAC_ADDR_START , data, MAC_ADDR_LENGTH); } else return -1; } int readMacAddr(char *data) { char value[PROPERTY_VALUE_MAX] = {0}; int nRet = -1; if(!data) { return -1; } property_get("ro.sdmc.thirdpart", value, "0"); if (!strncmp(value, "true", 4)) { nRet = readMacAddrFromFlash(data); } else{ DError("==========readMacAddrFromdm2016============"); nRet = EPRRead(MAC_ADDR_START , data, MAC_ADDR_LENGTH); } if(isMacValid(data)) { int i = 0; for(i=0;i<6;i++) { DError("0x%x ",data[i]); } DError("\n"); return 0; } else { int i = 0; for(i=0;i<6;i++) { DError("0x%x ",data[i]); } DError("\n"); return -1; } } int readUserDeviceIDFromFlash(char *data) { int nRet = -1; DError("==========readUserDeviceIDFromFlash============"); nRet = sdmc_fileecho(MAC_SN_ATTAVH, "1", 1); nRet |= sdmc_fileecho(MAC_SN_NAME, "usid", 4); nRet |= sdmc_get_sysfs_str(MAC_SN_READ, data); nRet |= sdmc_fileecho(MAC_SN_ATTAVH, "0", 1); return nRet; } int writeUserDeviceIDToFlash(const char *data, unsigned int uDataLength) { int nRet = -1; DError("==========writeUserDeviceIDToFlash============"); nRet = sdmc_fileecho(MAC_SN_ATTAVH, "1", 1); nRet |= sdmc_fileecho(MAC_SN_NAME, "usid", 4); nRet |= sdmc_fileecho(MAC_SN_WRITE, data, USER_DEVICE_ID_ADDR_LENGTH); nRet |= sdmc_fileecho(MAC_SN_ATTAVH, "0", 1); return nRet; } int readUserDeviceID(char *data) { char value[PROPERTY_VALUE_MAX] = {0}; if(!data) { return -1; } property_get("ro.sdmc.thirdpart", value, "0"); if (!strncmp(value, "true", 4)) { return readUserDeviceIDFromFlash(data); } DError("==========readUserDeviceIDFromDM2016============"); return EPRRead(USER_DEVICE_ID_ADDR_START , data, USER_DEVICE_ID_ADDR_LENGTH); } int writeUserDeviceID(const char *data) { char value[PROPERTY_VALUE_MAX] = {0}; if(!data) { return -1; } property_get("ro.sdmc.thirdpart", value, "0"); if (!strncmp(value, "true", 4)) { return writeUserDeviceIDToFlash(data, USER_DEVICE_ID_ADDR_LENGTH); } DError("==========writeUserDeviceIDDM2016============"); return EPRWrite(USER_DEVICE_ID_ADDR_START , data, USER_DEVICE_ID_ADDR_LENGTH); } int readUserPrivateID(char *data) { if(!data) { return -1; } return EPRRead(USER_PRIVATE_ID_ADDR_START , data, USER_PRIVATE_ID_ADDR_LENGTH); } int writeUserPrivateID(const char *data) { if(!data) { return -1; } return EPRWrite(USER_PRIVATE_ID_ADDR_START , data, USER_PRIVATE_ID_ADDR_LENGTH); } int readUserHardwareVersionID(char *data) { if(!data) { return -1; } return EPRRead(USER_HARDWARE_VERSION_ID_START , data, USER_HARDWARE_VERSION_ID_LENGTH); } int writeUserHardwareVersionID(const char *data) { if(!data) { return -1; } return EPRWrite(USER_HARDWARE_VERSION_ID_START , data, USER_HARDWARE_VERSION_ID_LENGTH); } int edsv_keyBurn(const char *keyPath, const char *macAddr) { return 0; } int edsv_keyCheck(const char *keyPath, const char *macAddr) { return 0; } int hdcp_is_written(int *is_written) { return 0; } int hdcp_write_key(const char *path) { return 0; } int hdcp_get_used_keynum(const char *path, int *used_num) { return 0; } int hdcp_get_unused_keynum(const char *path, int *unused_num) { return 0; } int hdcp_file_is_valid(const char *path, int *is_valid) { return 0; } int writeMac2Addr(const char *data) { if(!data) { return -1; } if(isMacValid(data)) { return EPRWrite(MAC2_ADDR_START , data, MAC_ADDR_LENGTH); } else return -1; } int readMac2Addr(char *data) { if(!data) { return -1; } int nRet = EPRRead(MAC2_ADDR_START , data, MAC_ADDR_LENGTH); if(isMacValid(data)) { return 0; } else { int i = 0; for(i=0;i<6;i++) { DError("0x%x ",data[i]); } DError("\n"); return -1; } } #include "stdio.h" #include "string.h" #include "stdlib.h" #include <fcntl.h> #include <time.h> #define TDATA32F 0xffffffff #define TDATA32A 0xaaaaaaaa #define TDATA325 0x55555555 #define DEFAULT_SIZE 0x2000000 #define BUFFER_LENGTH 32*1024*1024 static void ddr_write(void *buff, unsigned m_length) { unsigned *p; unsigned i, j, n; unsigned m_len = m_length; p = (unsigned *)buff; while(m_len) { for(j=0;j<32;j++) { if(m_len >= 128) n = 32; else n = m_len>>2; for(i = 0; i < n; i++) { switch(i) { case 0: case 9: case 14: case 25: case 30: *(p+i) = TDATA32F; break; case 1: case 6: case 8: case 17: case 22: *(p+i) = 0; break; case 16: case 23: case 31: *(p+i) = TDATA32A; break; case 7: case 15: case 24: *(p+i) = TDATA325; break; case 2: case 4: case 10: case 12: case 19: case 21: case 27: case 29: *(p+i) = 1<<j; break; case 3: case 5: case 11: case 13: case 18: case 20: case 26: case 28: *(p+i) = ~(1<<j); break; } } if(m_len > 128) { m_len -= 128; p += 32; } else { p += (m_len>>2); m_len = 0; break; } } } } static int ddr_read(void *buff, unsigned m_length) { unsigned *p; unsigned i, j, n; unsigned m_len = m_length; int err_flag = 0; p = (unsigned *)buff; while(m_len) { for(j=0;j<32;j++) { if(m_len >= 128) n = 32; else n = m_len>>2; for(i = 0; i < n; i++) { switch(i) { case 0: case 9: case 14: case 25: case 30: if(*(p+i) != TDATA32F){ err_flag = 1; } break; case 1: case 6: case 8: case 17: case 22: if(*(p+i) != 0){ err_flag = 1; } break; case 16: case 23: case 31: if(*(p+i) != TDATA32A){ err_flag = 1; } break; case 7: case 15: case 24: if(*(p+i) != TDATA325){ err_flag = 1; } break; case 2: case 4: case 10: case 12: case 19: case 21: case 27: case 29: if(*(p+i) != 1<<j){ err_flag = 1; } break; case 3: case 5: case 11: case 13: case 18: case 20: case 26: case 28: if(*(p+i) != ~(1<<j)){ err_flag = 1; } break; } err_flag = 0; } if(m_len > 128) { m_len -= 128; p += 32; } else { p += (m_len>>2); m_len = 0; break; } } } return err_flag; } int ddrTest(int nCount) { int nRet = 0; char *pBuff = NULL; while(nCount) { char *pBuff = (char *)malloc(BUFFER_LENGTH); if(pBuff) { ddr_write(pBuff, BUFFER_LENGTH); nRet = ddr_read(pBuff, BUFFER_LENGTH); nRet = ddr_read(pBuff, BUFFER_LENGTH); nRet = ddr_read(pBuff, BUFFER_LENGTH); if(nRet != 0) { free(pBuff); return -1; } free(pBuff); }else{ return -2; } nCount--; } return 0; } int readActivecode(char* activeCode) { return EPRRead(ACTIVE_CODE_ADDR_START , activeCode, ACTIVE_CODE_ADDR_LENGTH); } int writeActivecode(char* activeCode) { return EPRWrite(ACTIVE_CODE_ADDR_START , activeCode, ACTIVE_CODE_ADDR_LENGTH); } int getTunerType(char* tunerType) { return EPRRead(USER_TUNER_TYPE_ADDR_TYPE , tunerType, USER_TUNER_TYPE_ADDR_LENGTH); } int setTunerType(char* tunerType) { return EPRWrite(USER_TUNER_TYPE_ADDR_TYPE , tunerType, USER_TUNER_TYPE_ADDR_LENGTH); } int readSN(char* sn) { char tmp[USER_DEVICE_ID_ADDR_LENGTH]={0}; if(readUserDeviceID(tmp)<0) { return -1; } else { memcpy(sn, tmp, 8); return 0; } } int writeSN(char* sn) { char tmp[USER_DEVICE_ID_ADDR_LENGTH]={0}; if(sn == NULL) { return -1; } memcpy(tmp, sn, 8); if(writeUserDeviceID(tmp)<0) { return -1; } else { return 0; } } int readChipID(char* chipId) { return readUserPrivateID(chipId); } int writeChipID(char* chipId) { return writeUserPrivateID(chipId); } <file_sep>LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := libi2c_s LOCAL_MODULE_TAGS := optional LOCAL_SRC_FILES := sdi2_i2c.c LOCAL_C_INCLUDES += \ $(LOCAL_PATH)/../include \ prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6/sysroot/usr/include/ LOCAL_STATIC_LIBRARIES := liblog libcutils LOCAL_CERTIFICATE := platform LOCAL_CFLAGS += -Wno-pointer-sign \ -Wno-pointer-sign include $(BUILD_STATIC_LIBRARY) include $(CLEAR_VARS) LOCAL_MODULE := libi2c_d LOCAL_MODULE_TAGS := optional LOCAL_SRC_FILES := sdi2_i2c.c LOCAL_C_INCLUDES += \ $(LOCAL_PATH)/../include \ prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6/sysroot/usr/include/ LOCAL_SHARED_LIBRARIES := liblog libcutils LOCAL_CERTIFICATE := platform ifeq ($(shell test $(PLATFORM_SDK_VERSION) -ge 26 && echo OK),OK) LOCAL_PROPRIETARY_MODULE := true endif LOCAL_CFLAGS += -Wno-pointer-sign \ -Wno-pointer-sign include $(BUILD_SHARED_LIBRARY) <file_sep># Copyright (C) 2009 The Android Open Source Project # # 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. # # the purpose of this sample is to demonstrate how one can # generate two distinct shared libraries and have them both # uploaded in # LOCAL_PATH:= $(call my-dir) # shared lib, which will be built shared include $(CLEAR_VARS) LOCAL_MODULE := libIDburn_d LOCAL_SRC_FILES := IDburner.c LOCAL_C_INCLUDES := \ $(LOCAL_PATH)/../include \ libnativehelper/include_jni/ LOCAL_SHARED_LIBRARIES += \ libcutils \ libutils \ liblog \ libi2c_d LOCAL_CFLAGS += -Wno-unused-parameter \ -Wno-pointer-sign \ -Wno-missing-field-initializers \ -Wno-format \ -Wno-uninitialized \ -Wno-parentheses \ -Wno-incompatible-pointer-types-discards-qualifiers \ -Wno-sign-compare ifeq ($(shell test $(PLATFORM_SDK_VERSION) -ge 26 && echo OK),OK) LOCAL_PROPRIETARY_MODULE := true endif include $(BUILD_SHARED_LIBRARY) include $(CLEAR_VARS) LOCAL_MODULE := libIDburn_s LOCAL_SRC_FILES := IDburner.c LOCAL_C_INCLUDES := \ $(LOCAL_PATH)/../include \ libnativehelper/include_jni/ LOCAL_STATIC_LIBRARIES += \ libcutils \ libutils \ liblog \ libi2c_s LOCAL_CFLAGS += -Wno-unused-parameter \ -Wno-pointer-sign \ -Wno-missing-field-initializers \ -Wno-format \ -Wno-uninitialized \ -Wno-parentheses \ -Wno-incompatible-pointer-types-discards-qualifiers \ -Wno-sign-compare ifeq ($(shell test $(PLATFORM_SDK_VERSION) -ge 26 && echo OK),OK) LOCAL_PROPRIETARY_MODULE := true endif include $(BUILD_STATIC_LIBRARY) <file_sep>package com.sdmc.jni; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileAccessUtil { public static boolean writeStringToFile(final String fileName, final String msg) { if (msg == null) { return false; } File file = new File(fileName); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return false; } } FileWriter fw = null; BufferedWriter writer = null; try { fw = new FileWriter(file); writer = new BufferedWriter(fw); writer.write(msg); writer.flush(); } catch (Exception e) { } finally { try { writer.close(); } catch (Exception e) { } try { fw.close(); } catch (Exception e) { } } return true; } public static String readStringFromFile(String fileName){ File file = new File(fileName); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } FileReader freader; try { freader = new FileReader(file); BufferedReader reader = new BufferedReader(freader); String line = reader.readLine(); reader.close(); return line; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } <file_sep>/**@defgroup ERROR ERROR 定义各个模块的错误代码基本值及通用出错代码 @brief Error模块对应头文件sdi2_error.h,定义了各个模块的错误代码基本值、通用 成功代码SDI_SUCCESS及通用出错代码SDI_FAILURE,没有接口需要实现。 一般情况下,SDI所有的函数均返回本模块定义的SDI_Error_Code类型的错误代码值, 该类错误代码值由两部分组成,其高16位为模块代码,在本模块中定义(即错误代码基本 值);低16位为具体错误代码,在具体模块中定义。 @note 除非在模块及接口中对错误代码值如FEATURE_NOT_SUPPORTED、NO_MEMORY等进行了 特别说明,否则错误代码值仅用于调试,Eastwin仅会判断其结果是否成功,而不会根据错 误代码值做出不同的后续操作。 @version 2.0.1 2009/07/27 初稿 @{ */ #ifndef _SDI2_ERROR_H_ #define _SDI2_ERROR_H_ #include "sdi2_typedef.h" #ifdef __cplusplus extern "C" { #endif #define SDI_SUCCESS (0) ///< 通用成功代码,所有一般成功均用该值表示 #define WATCHDOG_DIS_INIT 0x10101010 #define SDI_FAILURE (0xFFFFFFFF) ///< 一般失败代码,未定义的出错代码可使用该值,但建议返回实际的错误代码值,而不应该使用该值 typedef SDI_UINT32 SDI_Error_Code; ///< 平台公共返回值类型 /**@brief 各个模块错误代码基本值枚举定义 @note 每个模块的错误代码值都会包含四个基本的错误代码类型:BAD_PARAMETER,NO_MEMORY,FEATURE_NOT_SUPPORTED,UNKNOWN_ERROR */ enum { SDI_AOUT_ERROR_BASE = 1 << 16, ///< AOUT模块的错误代码基本值 SDI_AUDIO_ERROR_BASE = 2 << 16, ///< AUDIO模块的错误代码基本值 SDI_VIDEO_ERROR_BASE = 3 << 16, ///< VIDEO模块的错误代码基本值 SDI_SCREEN_ERROR_BASE = 4 << 16, ///< SCREEN模块的错误代码基本值 SDI_DESCRAMBLE_ERROR_BASE = 5 << 16, ///< DESCRAMBLE模块的错误代码基本值 SDI_INJECT_ERROR_BASE = 6 << 16, ///< INJECTER模块的错误代码基本值 SDI_RECORD_ERROR_BASE = 7 << 16, ///< RECORD模块的错误代码基本值 SDI_OSG_ERROR_BASE = 8 << 16, ///< OSG模块的错误代码基本值 SDI_SECTION_ERROR_BASE = 9 << 16, ///< SECTION模块的错误代码基本值 SDI_SMC_ERROR_BASE = 10 << 16, ///< SMC模块的错误代码基本值 SDI_OS_ERROR_BASE = 11 << 16, ///< OS模块的错误代码基本值 SDI_FS_ERROR_BASE = 12 << 16, ///< FS模块的错误代码基本值 SDI_PLAYER_ERROR_BASE = 13 << 16, ///< PLAYER模块的错误代码基本值 SDI_TUNER_ERROR_BASE = 14 << 16, ///< TUNER模块的错误代码基本值 SDI_FLASH_ERROR_BASE = 15 << 16, ///< FLASH模块的错误代码基本值 SDI_DEMUX_ERROR_BASE = 16 << 16, ///< DEMUX模块的错误代码基本值 SDI_EEPROM_ERROR_BASE = 17 << 16, ///< EEPROM模块的错误代码基本值 SDI_TOOLSET_ERROR_BASE = 18 << 16, ///< TOOLSET模块的错误代码基本值 SDI_PANEL_ERROR_BASE = 19 << 16, ///< PANEL模块的错误代码基本值 SDI_INPUT_ERROR_BASE = 20 << 16, ///< INPUT模块的错误代码基本值 SDI_IPCFG_ERROR_BASE = 21 << 16, ///< IPCFG模块的错误代码基本值 SDI_OTA_ERROR_BASE = 22 << 16, ///< OTA模块的错误代码基本值 SDI_EW200S_ERROR_BASE = 23 << 16, ///< Eastwin200服务层错误代码基本值 SDI_MAX_ERROR_BASE ///< 边界值 }; #ifdef __cplusplus } #endif /** @} */ #endif //_SDI2_ERROR_H_ <file_sep>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <linux/i2c-dev.h> #include <linux/i2c.h> #include "sdi2/sdi2_i2c.h" #include <android/log.h> #ifndef LOG_TAG #define LOG_TAG "i2c_lib" #endif #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) #define RW_BUF_MAXSIZE 256 /**@brief I2C设备句柄 */ typedef struct { int32_t dev; /* 打开的I2C设备文件描述符 */ I2CBlockIndex_E index; /* I2C设备组索引 */ I2COpenParam_S param; /* 打开的I2C设备属性 */ }I2CHandle_S; SDI_Error_Code SDII2COpen(I2COpenParam_S *param, SDI_HANDLE *handle) { SDI_INT32 ret = 0; SDI_UINT8 temp[16]={0}; I2CHandle_S *i2c_handle = NULL; if(param == NULL) { LOGE("%s::%d:: Invalid param\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } i2c_handle = (I2CHandle_S *)malloc(sizeof(I2CHandle_S)); if(i2c_handle == NULL) { LOGE("%s::%d::Malloc error.\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } memset(i2c_handle, 0, sizeof(I2CHandle_S)); memcpy(&i2c_handle->param, param, sizeof(I2COpenParam_S)); if(i2c_handle->param.BlockIndex >= I2C_BLOCK_MAX) { LOGE("%s::%d:: Invalid param\n", __FUNCTION__, __LINE__); goto err; } if((i2c_handle->param.I2CSpeed != I2C_SPEED_100K)&&(i2c_handle->param.I2CSpeed != I2C_SPEED_400K)) { LOGE("Only 100kbps and 400kbps are supported in currentplatform.\n"); LOGE("Select 100kbps as default speed.\n"); i2c_handle->param.I2CSpeed = I2C_SPEED_100K; } #if 0 // modified by Ronny if(i2c_handle->param.I2CSpeed == I2C_SPEED_400K) { i2c_handle->param.BlockIndex = I2C_BLOCK0; } if(i2c_handle->param.I2CSpeed == I2C_SPEED_100K) { i2c_handle->param.BlockIndex = I2C_BLOCK1; } #endif sprintf(temp, "/dev/i2c-%u", i2c_handle->param.BlockIndex); LOGE("open i2c device: %s\n", temp); i2c_handle->dev = -1; i2c_handle->dev = open((const char*)temp, O_RDWR); if(i2c_handle->dev < 0) { perror("I2C dev open"); goto err; } if(i2c_handle->param.TimeOut > 0) { if(i2c_handle->param.TimeOut < 10) i2c_handle->param.TimeOut = 10; ret = ioctl(i2c_handle->dev, I2C_TIMEOUT, i2c_handle->param.TimeOut / 10); if(ret != 0) { LOGE("set timeout error, %ld\n", ret); } } *handle = (SDI_HANDLE *)i2c_handle; return SDI_SUCCESS; err: if(i2c_handle->dev > 0) close(i2c_handle->dev); if(i2c_handle != NULL) free(i2c_handle); *handle = NULL; return SDI_FAILURE; } SDI_Error_Code SDII2CClose(SDI_HANDLE handle) { I2CHandle_S *i2c_handle = (I2CHandle_S *)handle; if((i2c_handle == NULL)||(i2c_handle->dev <= 0)) { LOGE("%s::%d:: Invalid Handle\n", __FUNCTION__, __LINE__); return -1; } close(i2c_handle->dev); free(i2c_handle); return SDI_SUCCESS; } SDI_Error_Code SDII2CRead(SDI_HANDLE handle, SDI_UINT8 devAddr, SDI_UINT8 *buf, SDI_INT32 len) { SDI_INT32 ret = 0; I2CHandle_S *i2c_handle = (I2CHandle_S *)handle; struct i2c_rdwr_ioctl_data data; if((i2c_handle == NULL)||(i2c_handle->dev <= 0)) { LOGE("%s::%d:: Invalid Handle\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } if(buf == NULL) { LOGE("%s::%d:: Invalid param\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } memset(&data, 0, sizeof(struct i2c_rdwr_ioctl_data)); data.nmsgs = 1; data.msgs = (struct i2c_msg*)malloc(data.nmsgs * sizeof(struct i2c_msg)); if(data.msgs == NULL) { LOGE("%s::%d:: Malloc error\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } memset(data.msgs, 0, (data.nmsgs * sizeof(struct i2c_msg))); data.msgs[0].flags = I2C_M_RD; data.msgs[0].addr = devAddr >> 1; data.msgs[0].buf = buf; data.msgs[0].len = len; ret = ioctl(i2c_handle->dev, I2C_RDWR, (unsigned long)&data); if(ret < 0) { perror("ioctl"); if(data.msgs) free(data.msgs); return SDI_FAILURE; } else { if(data.msgs) free(data.msgs); return SDI_SUCCESS; } } SDI_Error_Code SDII2CWrite(SDI_HANDLE handle, SDI_UINT8 devAddr, SDI_UINT8 *buf, SDI_INT32 len) { SDI_INT32 ret = 0; I2CHandle_S *i2c_handle = (I2CHandle_S *)handle; struct i2c_rdwr_ioctl_data data; if((i2c_handle == NULL)||(i2c_handle->dev <= 0)) { LOGE("%s::%d:: Invalid Handle\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } if(buf == NULL) { LOGE("%s::%d:: Invalid param\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } memset(&data, 0, sizeof(struct i2c_rdwr_ioctl_data)); data.nmsgs = 1; data.msgs = (struct i2c_msg*)malloc(data.nmsgs * sizeof(struct i2c_msg)); if(data.msgs == NULL) { LOGE("%s::%d:: Malloc error\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } memset(data.msgs, 0, (data.nmsgs * sizeof(struct i2c_msg))); data.msgs[0].flags = 0;//I2C_M_NOSTART; data.msgs[0].addr = devAddr >> 1; data.msgs[0].buf = buf; data.msgs[0].len = len; //LOGE("data.msgs[0].addr: 0x%02x\n", data.msgs[0].addr); //LOGE("data.msgs[0].buf[0]: 0x%02x(regaddr)\n", data.msgs[0].buf[0]); //LOGE("data.msgs[0].len: 0x%02x(length)\n", data.msgs[0].len); ret = ioctl(i2c_handle->dev, I2C_RDWR, (unsigned long)&data); if(ret < 0) { perror("ioctl"); if(data.msgs) free(data.msgs); return SDI_FAILURE; } if(data.msgs) free(data.msgs); return SDI_SUCCESS; } SDI_Error_Code SDII2CReadWithRegAddr(SDI_HANDLE handle, SDI_UINT8 devAddr, SDI_UINT8 *regAddr, SDI_INT32 alen, SDI_UINT8 *buf, SDI_INT32 len) { SDI_INT32 ret = 0; I2CHandle_S *i2c_handle = (I2CHandle_S *)handle; struct i2c_rdwr_ioctl_data data; if((i2c_handle == NULL)||(i2c_handle->dev <= 0)) { LOGE("%s::%d:: Invalid Handle\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } if((regAddr == NULL)||(buf == NULL)||(alen < 0)) { LOGE("%s::%d:: Invalid param\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } memset(&data, 0, sizeof(struct i2c_rdwr_ioctl_data)); data.nmsgs = 2; data.msgs = (struct i2c_msg*)malloc(data.nmsgs * sizeof(struct i2c_msg)); if(data.msgs == NULL) { LOGE("%s::%d:: Malloc error\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } memset(data.msgs, 0, (data.nmsgs * sizeof(struct i2c_msg))); data.msgs[0].flags = 0; data.msgs[0].addr = devAddr >> 1; data.msgs[0].buf = regAddr; data.msgs[0].len = alen; data.msgs[1].flags = I2C_M_RD; data.msgs[1].addr = devAddr >> 1; data.msgs[1].buf = buf; data.msgs[1].len = len; //LOGE("data.msgs[1].buf[0] = 0x%02x, addr 0x%x\n", data.msgs[1].buf[0], data.msgs[1].buf); ret = ioctl(i2c_handle->dev, I2C_RDWR, (unsigned long)&data); //LOGE("data.msgs[1].buf[0] = 0x%02x, addr 0x%x\n", data.msgs[1].buf[0], data.msgs[1].buf); if(ret < 0) { perror("ioctl"); if(data.msgs) free(data.msgs); return SDI_FAILURE; } else { if(data.msgs) free(data.msgs); return SDI_SUCCESS; } } SDI_Error_Code SDII2CWriteWithRegAddr(SDI_HANDLE handle, SDI_UINT8 devAddr, SDI_UINT8 *regAddr, SDI_INT32 alen, SDI_UINT8 *buf, SDI_INT32 len) { SDI_INT32 ret = 0; I2CHandle_S *i2c_handle = (I2CHandle_S *)handle; struct i2c_rdwr_ioctl_data data; SDI_UINT8 wrbuf[RW_BUF_MAXSIZE] = {0}; if((i2c_handle == NULL)||(i2c_handle->dev <= 0)) { LOGE("%s::%d:: Invalid Handle\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } if((regAddr == NULL)||(buf == NULL)||(alen <= 0)) { LOGE("%s::%d:: Invalid param\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } memset(&data, 0, sizeof(struct i2c_rdwr_ioctl_data)); data.nmsgs = 1; data.msgs = (struct i2c_msg*)malloc(data.nmsgs * sizeof(struct i2c_msg)); if(data.msgs == NULL) { LOGE("%s::%d:: Malloc error\n", __FUNCTION__, __LINE__); return SDI_FAILURE; } memset(data.msgs, 0, (data.nmsgs * sizeof(struct i2c_msg))); memcpy(wrbuf, regAddr, alen); memcpy(wrbuf+alen, buf, len); data.msgs[0].flags = 0;//I2C_M_NOSTART; data.msgs[0].addr = devAddr >> 1; data.msgs[0].buf = wrbuf; data.msgs[0].len = alen+len; //LOGE("data.msgs[0].addr: 0x%02x\n", data.msgs[0].addr); //LOGE("data.msgs[0].buf[0]: 0x%02x(regaddr)\n", data.msgs[0].buf[0]); //LOGE("data.msgs[0].len: 0x%02x(length)\n", data.msgs[0].len); ret = ioctl(i2c_handle->dev, I2C_RDWR, (unsigned long)&data); if(ret < 0) { LOGE("%s::%d:: Malloc error\n", __FUNCTION__, __LINE__); perror("ioctl"); if(data.msgs) { free(data.msgs); } return SDI_FAILURE; } if(data.msgs) { free(data.msgs); } return SDI_SUCCESS; } <file_sep># #add sdmc libs auto compile # PRODUCT_PACKAGES += \ libdm2016_d \ libi2c_d \ libIDburn_s #libidburnerjni \
649efa5e10325065107720ede8f5323cf0535674
[ "Java", "C", "Makefile", "C++" ]
16
C
Huylehp912/lib_codeName_1
bf5b9e9fec7830fbf97e7dbd27e413a1e95c6efd
577df7e8a8c99cf5eb34ceaeb378addea3fa8e66
refs/heads/main
<file_sep><?php class groupe{ use hydrate; private $id; private $userList; public function getId(){ return $this->id; } public function setId($id){ $this->id = $id; } public function setUserList($datas){ for } public function getUserList(){ return $this->userList; } public function getGroupeById($id){ $db = new Database(); $datas = $db->query('SELECT * FROM groupe WHERE id = ?', array($id)); $tmp = new Groupe(); $tmp->setId($id); return $tmp; } }<file_sep>import React from 'react' // import { useHistory } from 'react-router-dom' import './Footer.css' export default function Footer() { return ( <footer className="footer"> <div className="containerNousContacter"> <h1>Nous Contacter</h1> <h2>CarbLife</h2> <p> 10, Route de l'hermite <br/> 10000<br/> KONOHA </p> <p> <i className="fas fa-phone-alt"></i> (+33) 01 02 03 04 05<br/> <i className="fas fa-envelope-open"></i> <EMAIL> </p> </div> </footer> ) }<file_sep>import React from 'react' import { useHistory } from 'react-router-dom' import './Nav.css' import logo from './../img/logo.png'; export default function Nav({ page }) { const history = useHistory(); function handleClickLogout() { history.push("/") window.location.reload(false); } function handleClickHelp() { history.push("/help") window.location.reload(false); } function handleClickHome() { history.push("/user") window.location.reload(false); } return ( <div> {page === 'user' ? <nav className="navbar"> <img src={logo} alt="logo" onClick={handleClickLogout} /> <h1>CarbLife</h1> <div className="wrapperIcon"> <i className="fas fa-2x fa-flag button__help" onClick={handleClickHelp} ></i> <i className="fas fa-3x fa-power-off button__logout" onClick={handleClickLogout} ></i> </div> </nav> : page === 'home' ? <nav className="navbar"> <img src={logo} alt="logo"/> <h1>CarbLife</h1> <div className="wrapperLink"> <span> <div className="testButton">Inscris-toi</div> </span> </div> </nav> : page === 'help' ? <nav className="navbar"> <img src={logo} alt="logo" onClick={handleClickLogout} /> <h1>CarbLife</h1> <div className="wrapperIcon"> <i className="fas fa-2x fa-home button__help" onClick={handleClickHome} ></i> <i className="fas fa-3x fa-power-off button__logout" onClick={handleClickLogout} ></i> </div> </nav> : page === 'tracking' ? <nav className="navbar"> <img src={logo} alt="logo" onClick={handleClickLogout} /> <h1>CarbLife</h1> <div className="wrapperIcon"> <i className="fas fa-2x fa-home button__help" onClick={handleClickHome} ></i> <i className="fas fa-3x fa-power-off button__logout" onClick={handleClickLogout} ></i> </div> </nav> : null } </div> ) }<file_sep><?php class User { use Hydrate; private $nom; private $prenom; private $email; private $password; private $actual_trajet_id; private $groupe; public function getId(){ return $this->id; } public function setId($id){ $this->id = $id; } public function getActual_trajet_id(){ return $this->actual_trajet_id; } public function setActual_trajet_id($actual_trajet_id){ $this->actual_trajet_id = $actual_trajet_id; } public function getNom(){ return $this->nom; } public function setNom($nom){ $this->nom = $nom; } public function getPrenom(){ return $this->prenom; } public function setPrenom($prenom){ $this->prenom = $prenom; } public function getEmail(){ return $this->email; } public function setEmail($email){ $this->email = $email; } public function getPassword(){ return $this->password; } public function setPassword($password){ $this->password = $password; } public function getGroupe(){ return $this->groupe; } public function setGroupe($uti_id){ $this->groupe = Groupe::getAllGroupeByUtiId($uti_id); } static function getUserById($id){ $db = new Database(); $data = $db->queryOne('SELECT * FROM utilisateurs WHERE id = ?', array($id)); $tmp = new User(); $tmp->hydrate($data); $tmp->setGroupe($tmp->id); return $tmp; } static function getAllUser() { $db = new Database(); $data = $db->queryOne('SELECT * FROM utilisateurs '); $res = array(); foreach ($datas as $data) { $tmp = new User(); $tmp->hydrate($data); $res[] = $tmp; } return $res; } static function hasActualTrajet($id) { $db = new Database(); $data = $db->queryOne('SELECT * FROM utilisateurs WHERE id = ?', array($id)); if ($data['actual_trajet_id'] == null) { return False; } return True; } static function resetTrajetByUtiId($uti_id) { $db = new Database(); $user = User::getUserById($uti_id); Trajet::deleteTrajetById($user->getActual_trajet_id()); User::updateActualTrajet($uti_id, null); } static function updateActualTrajet($uti_id, $trajet_id) { $db = new Database(); $data = $db->executeSql('UPDATE utilisateurs SET `actual_trajet_id`=? WHERE id = ?', array($trajet_id, $uti_id)); } static function getUserByEmail($email){ $db = new Database(); $data = $db->queryOne('SELECT * FROM utilisateurs WHERE email = ?', array($email)); $tmp = new User(); $tmp->hydrate($data); $tmp->setGroupe($tmp->id); return $tmp; } } <file_sep>import React from 'react' // import { useHistory } from 'react-router-dom' import './Help.css' import pic1 from './../img/1re_connexion/ios1.webp'; import pic2 from './../img/1re_connexion/ios2.webp'; import pic3 from './../img/1re_connexion/ios3.webp'; import pic4 from './../img/1re_connexion/ios4.webp'; import pic_android1 from './../img/1re_connexion/accès_chrome.webp'; import pic_android2 from './../img/1re_connexion/raw1.webp'; import pic_android3 from './../img/1re_connexion/raw2.webp'; import pic_android4 from './../img/1re_connexion/raw3.webp'; import pic_android5 from './../img/1re_connexion/raw4.webp'; export default function Help() { return ( <section className="wrapperHelp"> <div className="title"> <h1>Facilitez vous la vie !</h1> <div className="chevron"> <i className="fas fa-3x fa-chevron-down"></i> </div> </div> <div className="wrapperContent"> <div className="line"> <div className="content__line1"> <h2>Sur IOS</h2> <p> Pour les versions IOS, il vous suffit d'ouvir le navigateur Safari sur votre iPhone ou iPad. Tapez dans la barre d'adresse, l'URL de notre site puis cliquez sur l'icône Partager (carré avec une flèche pointant vers le haut), une suite d'onglets s'affichent. </p> <p> <img src={pic1} alt="ios 1" className="center"/> </p> <p> Appuyez sur l'onglet "Sur l'écran d'accueil" puis donnez un nom à votre raccourci </p> <p> <img src={pic2} alt="ios 2"/> </p> <p> Appuyez sur le bouton "Ajouter" placé dans le coin supérieur droit de l’écran pour enregistrer vos modifications </p> <p> <img src={pic3} alt="ios 3"/> </p> <p> L’icône se placera automatiquement sur l’écran d’accueil de votre téléphone ou de votre tablette. </p> <p> <img src={pic4} alt="ios 4"/> </p> </div> </div> <div className="line"> <div className="content__line2"> <h2>Sur Android</h2> <p> Concernant les versions Android, le processus est similaire et tout aussi simple. </p> <p> Ouvrez l'application Google Chrome, puis rendez-vous sur notre site afin de créer un raccourci. </p> <img alt="Tutoriel" src={pic_android1}/> <p> Appuyez sur les trois petits points du menu en haut à droite et sélectionnez "Ajouter à l'écran d'accueil". Enfin, nommez la page et appuyez sur "Ajouter". </p> <p> <img alt="Tutoriel" src={pic_android2}/> </p> <p> <img alt="Tutoriel" src={pic_android3}/> </p> <p> <img alt="Tutoriel" src={pic_android4}/> </p> <p> Un raccourci vers la page web est apparu sur l'écran d'accueil de votre smartphone, une simple pression sur l'icône vous y renvoie directement. </p> <img alt="Tutoriel" src={pic_android5}/> </div> </div> </div> </section> ) }<file_sep><?php include 'class/class.php'; class Locomotion { use Hydrate; private $id; private $carburant_id; private $locomotion_id; private $type_trajets_id; private $consommation; private $carburant; private $locomotion; private $type_trajets; public function getId(){ return $this->id; } public function setId($id){ $this->id = $id; } public function getCarburant_id(){ return $this->carburant_id; } public function setCarburant_id($carburant_id){ $this->carburant_id = $carburant_id; } public function getLocomotion_id(){ return $this->locomotion_id; } public function setLocomotion_id($locomotion_id){ $this->locomotion_id = $locomotion_id; } public function getType_trajets_id(){ return $this->type_trajets_id; } public function setType_trajets_id($type_trajets_id){ $this->type_trajets_id = $type_trajets_id; } public function getConsommation(){ return $this->consommation; } public function setConsommation($consommation){ $this->consommation = $consommation; } public function getCarburant(){ return $this->carburant; } public function setCarburant($carburant){ $this->carburant = $carburant; } public function getLocomotion(){ return $this->locomotion; } public function setLocomotion($locomotion){ $this->locomotion = $locomotion; } public function getType_trajets(){ return $this->type_trajets; } public function setType_trajets($type_trajets){ $this->type_trajets = $type_trajets; } static function getLocomotionJoin($carburant_id, $locomotion_id, $type_trajets_id) { $db = new Database(); $data = $db->queryOne('SELECT carburants.nom AS carburant, type_trajets.type AS type_trajets, moyen_locomotion.type AS locomotion, locomotion_carburant.id, carburant_id, locomotion_id, type_trajets_id FROM locomotion_carburant INNER JOIN carburants ON locomotion_carburant.carburant_id = carburants.id INNER JOIN moyen_locomotion ON locomotion_carburant.locomotion_id = moyen_locomotion.id INNER JOIN type_trajets ON locomotion_carburant.type_trajets_id = type_trajets.id WHERE carburant_id = ? AND locomotion_id = ? AND type_trajets_id = ?', array($carburant_id, $locomotion_id, $type_trajets_id)); $tmp = new Locomotion(); $tmp->hydrate($data); return $tmp; } }<file_sep>import React, { useEffect } from 'react' import axios from 'axios' // import { useHistory } from 'react-router-dom' import './Tracking.css' export default function Tracking() { return ( <div > <h3 class="text-success"> Session Tracking</h3> <div class="wrapperForm"> <h4>Moyen de Locomotion</h4> <div class="card" id="locomotion"> <button type="button" class="btn btn-warning">Bus</button> <button type="button" class="btn btn-warning">Voiture</button> <button type="button" class="btn btn-warning">Moto</button> <button type="button" class="btn btn-warning">Scooter</button> </div> <div class="blackBar"></div> <h4>Type de Carburant</h4> <div class="card" id= "carburant"> <div class="card-body"> <button type="button" class="btn btn-warning">diesel</button> <button type="button" class="btn btn-warning">essence</button> <button type="button" class="btn btn-warning">lpg</button> <button type="button" class="btn btn-warning">ethanol</button> </div> </div> <div class="blackBar"></div> <h4>Type de Trajets</h4> <div class="card" id= "type_trajet"> <button type="button" class="btn btn-warning">ville</button> <button type="button" class="btn btn-warning">campagne</button> <button type="button" class="btn btn-warning">autoroute</button> </div> </div> <div class="blackBar"></div> <div class="card" id="action"> <button type="button" class="btn" id="start">Start</button> <button type="button" class="btn" id="pause">Pause</button> <button type="button" class="btn" id="reset">Reset</button> <div class="wrapperOptionTimer"> <button type="button" class="btn" id="returnToSettings">Revenir aux options</button> <button type="button" class="btn" id="returnToHome">Arrêter la course</button> </div> </div> <div class="wrapperMap"> <div class="container"> <div id="map-e"> </div> </div> <br/> <p class="p" id="p">Distance: 0km</p> <div class="tim"> <p>Durée: </p> <span >0 h</span> : <span >0 min</span> : <span >0 s</span> : <span >0 ms</span> </div> <br/> <p class="p">Empreinte carbone : </p> </div> </div> ) }<file_sep><?php class Groupe{ use hydrate; public $id; public $userList; public function getId(){ return $this->id; } public function setId($id){ $this->id = $id; } public function setUserList($userList){ $this->userList = $userList; } public function getUserList(){ return $this->userList; } static function getAllGroupeByUtiId($uti_id){ $db = new Database(); $res = array(); $groupes = $db->query('SELECT * FROM groupe_field WHERE uti_id = ?', array($uti_id)); foreach($groupes as $groupe) { $datas = $db->query('SELECT * FROM groupe_field WHERE groupe_id = ?', array($groupe['groupe_id'])); $grp = new Groupe(); $grp->setId($groupe['groupe_id']); $tmp = array(); foreach($datas as $data) { $tmp[] = $data['uti_id']; } $grp->setUserList($tmp); $res[] = $grp; } return ($res); } static function getGroupeById($id) { $db = new Database(); $datas = $db->query('SELECT * FROM groupe WHERE groupe_id = ?', array($id)); $grp = Groupe(); $grp->setId($id); $tmp = array(); foreach($datas as $data) { $tmp[] = $data['uti_id']; } $grp->setUserList($tmp); return $grp; } static function addGroupe($nom, $uti_id){ $db = new Database(); $groupe_id= $db->executeSql("INSERT INTO groupe (nom) values (?)", array($nom)); $db->executeSql("INSERT INTO groupe_field (groupe_id, uti_id) values (?, ?)", array($groupe_id,$uti_id)); } static function addNewUserToGroupe($groupe_id, $uti_id) { $db = new Database(); $data = $db->query('SELECT * FROM groupe_field WHERE groupe_id = ? AND uti_id = ?', array($groupe_id, $uti_id)); if ($data == false) { $data = $db->executeSql("INSERT INTO groupe_field (groupe_id, uti_id) values (?, ?)", array($groupe_id, $uti_id)); } } }<file_sep><?php include "class/class.php"; session_start(); if (isset($_POST['nom']) && isset($_POST['prenom']) && isset($_POST['email']) && isset($_POST['password'])) { $db = new Database(); $data = $db->queryOne('SELECT id FROM utilisateurs WHERE email = ?', array($_POST['email'])); if ($data == false) { $options = ['cost' => 12]; $password = password_hash($_POST['password'], PASSWORD_BCRYPT, $options); $db->executeSql('INSERT INTO utilisateurs (nom, prenom, password, email) VALUES (?, ?, ? , ?)', array($_POST['nom'], $_POST['prenom'], $password, $_POST['email'])); echo "OK"; } else { echo "email already used"; } }<file_sep><?php include 'class/class.php'; class Carburant { use Hydrate; public $id; public $nom; public function getId(){ return $this->id; } public function setId($id){ $this->id = $id; } public function getNom(){ return $this->nom; } public function setNom($nom){ $this->nom = $nom; } static function getAllCarburants() { $db = new Database(); $datas = $db->query("SELECT * FROM carburants"); $res = array(); foreach ($datas as $data) { $tmp = new Carburant(); $tmp->hydrate($data); $res[] = $tmp; } return $res; } static function getCarburantById($id) { $db = new Database(); $data = $db->queryOne("SELECT * FROM carburants WHERE id = ?", array($id)); $tmp = new Carburant(); $tmp->hydrate($data); return $tmp; } }<file_sep><?php include 'class/class.php'; session_start(); if (isset($_SESSION['id'])) { if (isset($_POST['action'])) { if ($_POST['action'] == "newUser") { if (isset($_POST['uti_id']) && isset($_POST['groupe_id'])) { $groupe = Groupe::addNewUserToGroupe($_POST['groupe_id'], $_POST['uti_id']); http_response_code(200); return ; } } elseif ($_POST['action'] == "newGroupe") { if (isset($_POST['nom'])) { $nom = htmlspecialchars($_POST['nom']); $groupe = Groupe::addGroupe($nom, $_SESSION['id']); http_response_code(200); return ; } } } http_response_code(404); } http_response_code(403);<file_sep><?php include 'class/class.php'; session_start(); include 'index.html';<file_sep><?php include 'class/class.php'; class MoyenLocomotion { use Hydrate; public $id; public $type; public function getId(){ return $this->id; } public function setId($id){ $this->id = $id; } public function getType(){ return $this->type; } public function setType($type){ $this->type = $type; } static function getAllMoyenLocomotions() { $db = new Database(); $datas = $db->query("SELECT * FROM moyen_locomotion"); $res = array(); foreach ($datas as $data) { $tmp = new MoyenLocomotion(); $tmp->hydrate($data); $res[] = $tmp; } return $res; } static function getMoyenLocomotionById($id) { $db = new Database(); $data = $db->queryOne("SELECT * FROM moyen_locomotion WHERE id = ?", array($id)); $tmp = new MoyenLocomotion(); $tmp->hydrate($data); return $tmp; } }<file_sep><?php include 'class/class.php'; session_start(); if (isset($_SESSION['id'])) { if (isset($_POST['action'])) { if ($_POST['action'] == "allData") { $allCarburant = Carburant::getAllCarburants(); $allTypeTrajet = TypeTrajet::getAllTypeTrajets(); $allMoyenLocomotion = MoyenLocomotion::getAllMoyenLocomotions(); $resLocomotion = array(); $resCarburant = array(); $resTypeProjet = array(); foreach ($allMoyenLocomotion as $aml) { $resLocomotion[] = get_object_vars($aml); } foreach ($allCarburant as $ac) { $resCarburant[] = get_object_vars($ac); } foreach ($allTypeTrajet as $atp) { $resTypeProjet[] = get_object_vars($atp); } $res = json_encode(array("carburant" => $resCarburant, "moyen_locomotion" => $resLocomotion, "type_trajets" => $resTypeProjet)); echo $res; return ; } elseif ($_POST['action'] == "allGroupe") { $datas = Groupe::getAllGroupeByUtiId($_SESSION['id']); $resData = array(); foreach($datas as $data) { $resData[] = get_object_vars($data); } echo json_encode($resData); return ; } elseif($_POST['action'] == "getUser") { if (isset($_POST['id'])) { $user = User::getUserById($_SESSION['id']); $resData = array( "id" => $user->getId(), "nom" => $user->getNom(), "prenom" => $user->getPrenom(), "email" => $user->getEmail(), "actual_trajet_id" => $user->getActual_trajet_id() ); echo json_encode($resData); return ; } } elseif ($_POST['action'] == "allUser") { $users = User::getAllUser($_SESSION['id']); $res = []; foreach($users as $user) { $tmpData = array( "id" => $user->getId(), "nom" => $user->getNom(), "prenom" => $user->getPrenom(), "email" => $user->getEmail(), "actual_trajet_id" => $user->getActual_trajet_id() ); $res[] = $tmpData; } echo json_encode($res); return; } } } http_response_code(403);<file_sep><?php spl_autoload_register(function ($className) { $className = lcfirst($className); // je passe la première lettre en minuscules = Article devient article if(is_file('class/'.$className.'.class.php')) { // si j'ai un fichier class/article.class.php alors il est inclus require_once('class/'.$className.'.class.php'); } else if(is_file('class/'.$className.'.trait.php')) { // si j'ai un fichier class/article.class.php alors il est inclus require_once('class/'.$className.'.trait.php'); } }); <file_sep><?php session_start(); include 'class/class.php'; if (isset($_POST['email']) && isset($_POST['password'])) { $user = User::getUserByEmail($_POST['email']); if (password_verify($_POST['password'], $user->getPassword())) { $_SESSION['id'] = $user->getId(); $_SESSION['nom'] = $user->getNom(); $_SESSION['prenom'] = $user->getPrenom(); $_SESSION['email'] = $user->getEmail(); echo 'OK'; } else { echo 'bad password'; } } <file_sep><?php include 'class/class.php'; class Trajet { use Hydrate; private $id; private $uti_id; private $carburant_id; private $locomotion_id; private $type_trajet_id; private $total_co2; private $total_km; private $origine; private $destination; private $time_creation; private $time_end; public function getId(){ return $this->id; } public function setId($id){ $this->id = $id; } public function getUti_id(){ return $this->uti_id; } public function setUti_id($uti_id){ $this->uti_id = $uti_id; } public function getCarburant_id(){ return $this->carburant_id; } public function setCarburant_id($carburant_id){ $this->carburant_id = $carburant_id; } public function getLocomotion_id(){ return $this->locomotion_id; } public function setLocomotion_id($locomotion_id){ $this->locomotion_id = $locomotion_id; } public function getType_trajet_id(){ return $this->type_trajet_id; } public function setType_trajet_id($type_trajet_id){ $this->type_trajet_id = $type_trajet_id; } public function getTotal_co2(){ return $this->total_co2; } public function setTotal_co2($total_co2){ $this->total_co2 = $total_co2; } public function getTotal_km(){ return $this->total_km; } public function setTotal_km($total_km){ $this->total_km = $total_km; } public function getOrigine(){ return $this->origine; } public function setOrigine($origine){ $this->origine = $origine; } public function getDestination(){ return $this->destination; } public function setDestination($destination){ $this->destination = $destination; } public function getTime_creation(){ return $this->time_creation; } public function setTime_creation($time_creation){ $this->time_creation = $time_creation; } public function getTime_end(){ return $this->time_end; } public function setTime_end($time_end){ $this->time_end = $time_end; } static function startNewTrajet($uti_id, $carburant_id, $locomotion_id, $type_trajet_id, $origine) { $db = new Database(); $data = $db->executeSql('INSERT INTO trajets (uti_id, carburant_id, locomotion_id, type_trajet_id, origine, time_creation) VALUES (?, ?, ?, ?, ?, NOW())', array($uti_id, $carburant_id, $locomotion_id, $type_trajet_id, $origine)); User::updateActualTrajet($data, $uti_id); return $data; } static function deleteTrajetById($trajet_id) { $db = new Database(); $db->executeSql('DELETE FROM trajets WHERE id = ?', array($trajet_id)); } static function endTrajet($trajet_id, $destination, $total_co2, $total_km) { $db = new Database(); $data = $db->executeSql('UPDATE trajets set `total_co2` = ?, `total_km` = ?, `destination` = ?, `time_end` = NOW() WHERE id = ?', array($total_co2, $total_km, $destination, $trajet_id)); $trajet = Trajet::getTrajetById($trajet_id); User::updateActualTrajet($trajet->getUti_id(), null); } static function getTrajetById($trajets_id) { $db = new Database(); $data = $db->queryOne("SELECT * FROM trajets WHERE id = ?", array($trajets_id)); $trajet = new Trajet(); $trajet->hydrate($data); return $trajet; } static function getAllTrajetsByUtiId($uti_id) { $db = new Database(); $datas = $db->query("SELECT * FROM trajets WHERE uti_id = ?", array($uti_id)); $res = array(); foreach ($datas as $data) { $tmpTrajet = new Trajet(); $tmpTrajet->hydrate($data); $res[] = $data; } return $res; } }<file_sep><?php trait Hydrate{ public function hydrate($data) { foreach($data as $propriete => $valeur) { $methodName = 'set'.ucfirst($propriete); if (method_exists($this, $methodName)) $this->$methodName($valeur); } } }<file_sep>/*la fonction getElementByTagName renvoie une liste des éléments portant le nom de balise donné ici "span".*/ var sp = document.querySelectorAll(".tim span"); var btn_start=document.getElementById("start"); var btn_stop=document.getElementById("stop"); var travelBtns = document.querySelectorAll("#locomotion .btn"); var t; var ms=0,s=0,mn=0,h=0; window.lat = 45.7596625; window.lng = 4.8250668; var travelmode = "a_pied"; for (var i = 0; i < travelBtns.length; i++) { travelBtns[i].onclick = function(element){ travelmode = element.target.textContent; }; } // VALEUR DE DEPART POUR TEST CAR PAS SUR TEL //window.latStart et window.lngStart = origine //window.lat et window.lng = actuel et fin //SI user->actual_trajet_id != NULL: // origine = trajet.origine.split(','); // window.latStart = origine[0]; // window.lngStart = origine[1]; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition ( (position) =>{ window.latStart = 45.7696625; window.lngStart = 4.8250668; window.lat = position.coords.latitude; window.lng = position.coords.longitude; } ); } setInterval (function () {updatePosition (getLocation ())}, 1000); let map; let mark; initialize = function() { map = new google.maps.Map(document.getElementById('map-e'), {center:{lat:lat,lng:lng},zoom:12}); mark = new google.maps.Marker({position:{lat:lat, lng:lng}, map:map}); }; window.initialize = initialize; let redraw = function(payload) { lat = payload.message.lat; lng = payload.message.lng; map.setCenter({lat:lat, lng:lng, alt:0}); mark.setPosition({lat:lat, lng:lng, alt:0}); }; var pnChannel = "map-channel"; var pubnub = new PubNub({ publishKey: '<KEY>', subscribeKey: 'sub-c-e6d3ec84-1d10-11eb-9f1e-baa67f46029c' }); pubnub.subscribe({channels: [pnChannel]}); pubnub.addListener({message:redraw}); setInterval(function() { pubnub.publish({channel:pnChannel, message:{lat:window.lat, lng:window.lng}}); }, 1000); /*La fonction "start" démarre un appel répétitive de la fonction update_chrono par une cadence de 100 milliseconde en utilisant setInterval et désactive le bouton "start" */ function start(){ t =setInterval(update_chrono,100); btn_start.disabled=true; getLocation (); //AJOUTER REQUETE TRAJET START } /*La fonction update_chrono incrémente le nombre de millisecondes par 1 <==> 1*cadence = 100 */ function update_chrono(){ ms+=1; /*si ms=10 <==> ms*cadence = 1000ms <==> 1s alors on incrémente le nombre de secondes*/ if(ms==10){ ms=1; s+=1; } /*on teste si s=60 pour incrémenter le nombre de minute*/ if(s==60){ s=0; mn+=1; } if(mn==60){ mn=0; h+=1; } /*afficher les nouvelle valeurs*/ sp[0].innerHTML=h+" h"; sp[1].innerHTML=mn+" min"; sp[2].innerHTML=s+" s"; sp[3].innerHTML=ms+" ms"; } /*on arrête le "timer" par clearInterval ,on réactive le bouton start */ function stop(){ clearInterval(t); btn_start.disabled=false; var distanceService = new google.maps.DistanceMatrixService(); if (travelmode == "Bus" || travelmode == "Voiture" || travelmode == "Moto" || travelmode == "Scooter") { var tmpTravelMode = 'DRIVING'; } else if (travelmode == "a_pied") { var tmpTravelMode = 'WALKING'; } else if (travelmode == "velo") { var tmpTravelMode = 'BICYCLING'; } distanceService.getDistanceMatrix({ origins:[window.latStart + ","+ window.lngStart], destinations: [window.lat + ","+ window.lng], travelMode: tmpTravelMode,//DRIVING, BICYCLING, TRANSIT, WALKING unitSystem: google.maps.UnitSystem.METRIC, durationInTraffic: true, avoidHighways: false, avoidTolls: false }, function (response, status){ if (status !== google.maps.DistanceMatrixStatus.OK) { console.log('Error:', status); } else { console.log(response); document.getElementById("p").innerHTML = "Distance: " + response.rows[0].elements[0].distance.text; //AJOUTER REQUETE TRAJET END } }); } /*dans cette fonction on arrête le "timer" ,on réactive le bouton "start" et on initialise les variables à zéro */ function reset(){ clearInterval(t); btn_start.disabled=false; ms=0,s=0,mn=0,h=0; /*on accède aux différents span par leurs indice*/ sp[0].innerHTML=h+" h"; sp[1].innerHTML=mn+" min"; sp[2].innerHTML=s+" s"; sp[3].innerHTML=ms+" ms"; // AJOUTER LA REQUETE TRAJET RESET } //Source : www.exelib.net function updatePosition (position) { if (position) { window.lat = position.coords.latitude; window.lng = position.coords.longitude; } } function updateStart(position){ if (position) { window.latStart = position.coords.latitude; window.lngStart = position.coords.longitude; } } function getLocation () { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition (updatePosition); } return null; }; function currentLocation () { return {lat: window.lat, lng: window.lng}; }; <file_sep><?php include 'class/class.php'; session_start(); if (isset($_POST['email']) && isset($_POST['password'])) { $user = User::getUserByEmail($_POST['email']); if (password_verify($_POST['password'], $user->getPassword())) { $_SESSION['id'] = $user->getId(); $_SESSION['nom'] = $user->getNom(); $_SESSION['prenom'] = $user->getPrenom(); $_SESSION['email'] = $user->getEmail(); http_response_code(200); } else { http_response_code(403); } } <file_sep><?php include 'class/class.php'; session_start(); if (isset($_SESSION['id'])) { if (isset($_POST['action'])) { if ($_POST['action'] == "new") { if (isset($_POST['carburant_id']) && isset($_POST['locomotion_id']) && isset($_POST['type_trajets_id'])&& isset($_POST['origine'])) { $id_trajet = Trajet::startNewTrajet($_SESSION['id'], $_POST['carburant_id'], $_POST['locomotion_id'], $_POST['type_trajets_id'], $_POST['origine']); $user = User::getUserById($_SESSION['id']); User::updateActualTrajet($_SESSION['id'], $id_trajet); http_response_code(200); return ; } } elseif ($_POST['action'] == "end" && User::hasActualTrajet($_SESSION['id'])) { if (isset($_POST['destination']) && isset($_POST['total_km'])) { $user = User::getUserById($_SESSION['id']); $total_co2 = 150; // a calculer $trajet = Trajet::endTrajet($user->getActual_trajet_id(), $_POST['destination'], $total_co2, $_POST['total_km']); http_response_code(200); return ; } } elseif ($_POST['action'] == "reset" && User::hasActualTrajet($_SESSION['id'])) { User::resetTrajetByUtiId($_SESSION['id']); http_response_code(200); return ; } } http_response_code(404); } http_response_code(403);<file_sep><?php include 'class/class.php'; session_start(); include 'index.html';<file_sep><?php class User { use Hydrate; private $nom; private $prenom; private $email; private $password; private $groupe; public function getId(){ return $this->id; } public function setId($id){ $this->id = $id; } public function getNom(){ return $this->nom; } public function setNom($nom){ $this->nom = $nom; } public function getPrenom(){ return $this->prenom; } public function setPrenom($prenom){ $this->prenom = $prenom; } public function getEmail(){ return $this->email; } public function setEmail($email){ $this->email = $email; } public function getPassword(){ return $this->password; } public function setPassword($password){ $this->password = $password; } public function getGroupe(){ return $this->groupe; } public function setGroupe($groupe){ $this->groupe = $groupe; } static function getUserById($id){ $db = new Database(); $data = $db->queryOne('SELECT * FROM utilisateurs WHERE id = ?', array($id)); $tmp = new User(); $tmp->hydrate($data); return $tmp; } static function getUserByEmail($email){ $db = new Database(); $data = $db->queryOne('SELECT * FROM utilisateurs WHERE email = ?', array($email)); $tmp = new User(); $tmp->hydrate($data); return $tmp; } } <file_sep>import React from 'react' // import { useHistory } from 'react-router-dom' import './HeaderHome.css' export default function HeaderHome() { return ( <header> <h1>Plus besoin de chercher, vous êtes au bon endroit :</h1> <div>Carblife est fait pour vous aider à gérer votre Empreinte Carbone !</div> <div>Développé, hébergé et maintenu dans le web français, c'est l'outil écologique de choix pour la sensibilisation, et accessible pour tous les âges.</div> <div>Tout en mettant au centre de l'écologie, les liens humains dans un monde qui se digitalise à outrance. </div> </header> ) }<file_sep>import React, { useState } from 'react' // import { useHistory } from 'react-router-dom' import './Popup.css' export default function Popup() { const [userMail, setUserMail] = useState("") const [pwd, setPwd] = useState("") // const [warningFeedback, setWarning] = useState() return ( <div> <div id="connexion" className="containerPopup"> <i className="fas fa-times"></i> <div className="wrapperPopup"> <div className="disclaimer">Connexion !</div> <form className="wrapperInput" > {/* <span className="warningMessage">{warningFeedback}</span> */} <div className="wrapperLabelContent"> <input type="text" name="loginMail" id="loginMail" value={userMail} onChange={event => setUserMail(event.target.value)} /> <label htmlFor="loginMail"> <span> E-mail </span> </label> </div> <div className="wrapperLabelContent"> <input type="<PASSWORD>" name="loginPassword" id="loginPassword" value={pwd} onChange={event => setPwd(event.target.value)} /> <label htmlFor="loginPassword"> <span> Password </span> </label> </div> </form> <div className= "wrapperButton"> <div id="inscriptionButton" className="submitButton" >Inscription</div> <div id="loginSubmit" className="submitButton" >Connexion</div> </div> </div> </div> <div id="inscription" className="containerPopup"> <i className="fas fa-times"></i> <div className="wrapperPopup"> <div className="disclaimer">Inscription !</div> <form className="wrapperInput"> <div className="wrapperLabelContent"> <input type="text" name="prenom" id="prenom"/> <label htmlFor="prenom"> <span> Prénom </span> </label> </div> <div className="wrapperLabelContent"> <input type="text" name="nom" id="nom"/> <label htmlFor="nom"> <span> Nom </span> </label> </div> <div className="wrapperLabelContent"> <input type="text" name="mail" id="mail"/> <label htmlFor="mail"> <span> E-mail </span> </label> </div> <div className="wrapperLabelContent"> <input type="<PASSWORD>" name="password" id="password"/> <label htmlFor="password"> <span> Password </span> </label> </div> <div className="wrapperLabelContent"> <input type="<PASSWORD>" name="confirmPassword" id="confirmPassword"/> <label htmlFor="confirmPassword"> <span> Confirm password </span> </label> </div> </form> <div className="wrapperButton"> <div id="inscriptionSubmit" className="submitButton">Inscription</div> </div> </div> </div> </div> ) }<file_sep><?php include "class/class.php"; session_start(); if (isset($_SESSION['id'])) { $test = Locomotion::getLocomotionJoin(1, 4, 1); $user = User::getUserById($_SESSION['id']); $trajets = Trajet::getAllTrajetsByUtiId($_SESSION['id']); $moyenLoc = MoyenLocomotion::getMoyenLocomotionById(1); $typeTrajet = TypeTrajet::getTypeTrajetById(1); $carburant = Carburant::getCarburantById(1); $allCarburant = Carburant::getAllCarburants(); echo "user has actual_trajet: ".User::hasActualTrajet($_SESSION['id']); var_dump($allCarburant); $allTypeTrajet = TypeTrajet::getAllTypeTrajets(); var_dump($allTypeTrajet); $allMoyenLocomotion = MoyenLocomotion::getAllMoyenLocomotions(); var_dump($allMoyenLocomotion); include "test.phtml"; } <file_sep>import React from 'react' // import { useHistory } from 'react-router-dom' import './BannerHome.css' export default function BannerHome() { return ( <section className="banner"> <div className="wrapperTestLink"> <div className="testLogiciel"> <p> Essayer gratuitement notre logiciel </p> </div> <div className="testLogiciel__button"> <div className="testButton">Faire le test</div> </div> </div> </section> ) }
0a4e734ac41fbb6b41f1d821862de911846136e8
[ "JavaScript", "PHP" ]
27
PHP
Vaalgtir/Workshop-2020
87bfd56381481c731c8a5b014a22f06bb37409f5
2f5b3cfdce5c89af491bd5c063abb73b67dd7f8d
refs/heads/master
<repo_name>ioio-creative/School-VR<file_sep>/src/utils/aframeEditor/old/extractBase64StrFromHtmlFileReader.js function extractBase64StrFromHtmlFileReader(resultStrFromFileReader) { const strToFind = "base64,"; const idxOfStrToFind = resultStrFromFileReader.indexOf(strToFind); return resultStrFromFileReader.substr(idxOfStrToFind + strToFind.length); } export default extractBase64StrFromHtmlFileReader; <file_sep>/src/containers/aframeEditor/homePage/aFramePanel.js import React, {Component} from 'react'; import AFRAME from 'aframe'; import 'aframe-gif-shader'; import {withSceneContext} from 'globals/contexts/sceneContext'; // import dcjaiobj from '../../3Dmodels/20190215_dave_pose(3d glasses).obj'; // import dcjaitex from '../../3Dmodels/GF_Dave_smile.jpg'; // fonts import TTFLoader from 'vendor/threejs/TTFLoader'; //import fontSchoolbellRegular from 'fonts/Schoolbell/SchoolbellRegular.png'; // import fontNotoSansRegular from 'fonts/Noto_Sans_TC/NotoSansTC-Regular.otf'; import fontYenHeavy from 'fonts/Yen_Heavy/wt009.ttf'; import iconNavigation from "media/icons/navigation3D.svg"; import './aFramePanel.css'; import { TweenMax } from 'gsap'; // console.log(AFRAME.THREE.Font); //const Events = require('vendor/Events.js'); const ttfFonts = { }; const three = AFRAME.THREE; const loader = new TTFLoader(); // const targetFont = this.el.getAttribute('text')['fontPath']; loader.load(fontYenHeavy, (json) => { ttfFonts['fontYenHeavy'] = new three.Font(json); }) // loadFonts(); // loader.load(fontNotoSansRegular, (json) => { // ttfFonts['fontNotoSansRegular'] = new three.Font(json); // // oldMesh.geometry = newGeometry; // }) AFRAME.registerComponent('cursor-listener', { init: function () { var lastIndex = -1; const hoverColor = '#AAAAAA'; const clickColor = '#28a8ff'; const activeColor = '#AAAAAA'; const defaultColor = '#FFFFFF';// this.el.getAttribute('material')['color']; this.el.setAttribute('geometry', 'primitive', 'cylinder'); this.el.setAttribute('scale', '1 0.1 1'); this.el.setAttribute('rotation', '90 0 0'); // this.el.setAttribute('material', 'color', '#F00'); this.el.setAttribute('material', 'src', '#iconNavigation'); this.el.setAttribute('material', 'transparent', true); const aniComponent = document.createElement('a-entity'); aniComponent.setAttribute('geometry', 'primitive', 'cylinder'); aniComponent.setAttribute('scale', '1 0.1 1'); // aniComponent.setAttribute('rotation', '0 90 90'); aniComponent.setAttribute('material', 'color', defaultColor); aniComponent.setAttribute('material', 'opacity', 0); this.el.appendChild(aniComponent); aniComponent.addEventListener('loaded', () => { // aniComponent.getObject3D('mesh').geometry.translate(0, 0.5, 0); }) let childrenEls = []; // if (this.el.children) { // childrenEls = Array.prototype.slice.call(this.el.children); // } // this.el.addEventListener('click', function (evt) { // // lastIndex = (lastIndex + 1) % COLORS.length; // const isVisible = this.getAttribute('material')['opacity']; // // console.log(isVisible); // // const originalRotation = this.getAttribute('rotation'); // // const cameraRotation = this.sceneEl.camera.el.getAttribute('rotation'); // if (isVisible) { // // aniComponent.setAttribute('material', 'color', activeColor); // // this.setAttribute('rotation', { // // x: -cameraRotation.x, // // y: -cameraRotation.y, // // z: -cameraRotation.z // // }); // // childrenEls.forEach(childEl => { // // childEl.setAttribute('material', 'color', clickColor); // // }) // const sceneEl = this.sceneEl; // const nextSlideId = sceneEl.data.sceneContext.getCurrentEntity(this.id)['navigateToSlideId']; // // console.log(nextSlideId); // setTimeout(_=> { // aniComponent.setAttribute('material', 'color', clickColor); // console.log('clicked') // // this.setAttribute('rotation', originalRotation); // // childrenEls.forEach(childEl => { // // childEl.setAttribute('material', 'color', defaultColor); // // }) // if (nextSlideId) { // if (!sceneEl.getAttribute('vr-mode-ui')['enabled']) { // if (sceneEl.data.socket) { // sceneEl.data.socket.emit('updateSceneStatus', { // action: 'selectSlide', // details: { // slideId: nextSlideId, // autoPlay: true // } // }) // } // sceneEl.data.sceneContext.selectSlide(nextSlideId); // sceneEl.data.sceneContext.playSlide(); // } // } // }, 250); // } // }); // let currentOpacity = this.el.getAttribute('material')['opacity']; let currentRotation = this.el.getAttribute('rotation'); let fillTimer = null; let hovering = false; this.el.addEventListener('mouseenter', function (evt) { // lastIndex = (lastIndex + 1) % COLORS.length; // if (hovering) { return; } currentRotation = this.getAttribute('rotation'); const currentOpacity = this.getAttribute('material')['opacity']; const currentColor = this.getAttribute('material')['color']; const cameraRotation = this.sceneEl.camera.el.getAttribute('rotation'); // console.log(cameraRotation); if (currentOpacity > 0) { // this.setAttribute('material', 'color', hoverColor); // hovering = true; this.setAttribute('rotation', { x: cameraRotation.x + 90, y: cameraRotation.y, // + 90, z: cameraRotation.z, // + 90 }); const obj3D = aniComponent.getObject3D('mesh'); const aniVar = { y: 0.001, color: '#FFFFFF' }; if (fillTimer) fillTimer.kill(); fillTimer = TweenMax.to(aniVar, 1, { y: 1, color: clickColor, onStart: _=> { aniComponent.setAttribute('material', 'opacity', 1); obj3D.scale.x = 0.001; obj3D.scale.z = 0.001; }, onUpdate: _=> { // obj3D.material.map.repeat.y = aniVar.y; obj3D.scale.x = aniVar.y; obj3D.scale.z = aniVar.y; aniComponent.setAttribute('material', 'color', aniVar.color); }, onComplete: _=> { // assume clicked this.setAttribute('material', 'color', clickColor); aniComponent.setAttribute('material', 'color', activeColor); const sceneEl = this.sceneEl; const nextSlideId = sceneEl.data.sceneContext.getCurrentEntity(this.id)['navigateToSlideId']; // console.log(nextSlideId); setTimeout(_=> { this.setAttribute('material', 'color', currentColor); this.setAttribute('rotation', currentRotation); aniComponent.setAttribute('material', 'opacity', 0); aniComponent.setAttribute('material', 'color', clickColor); if (nextSlideId) { if (sceneEl.getAttribute('user-mode') !== 'viewer') { if (sceneEl.data.socket) { sceneEl.data.socket.emit('updateSceneStatus', { action: 'selectSlide', details: { slideId: nextSlideId, autoPlay: true } }) } sceneEl.data.sceneContext.selectSlide(nextSlideId); sceneEl.data.sceneContext.playSlide(); } } }, 250); } }) // old // // childrenEls.forEach(childEl => { // childEl.setAttribute('material', 'color', hoverColor); // }) } }); this.el.addEventListener('mouseleave', function () { // lastIndex = (lastIndex + 1) % COLORS.length; // this.setAttribute('material', 'opacity', currentOpacity); // hovering = false; if (fillTimer) fillTimer.kill(); this.setAttribute('rotation', currentRotation); // aniComponent.getObject3D('mesh').scale.y = 0.001; aniComponent.setAttribute('material', 'opacity', 0); // childrenEls.forEach(childEl => { // childEl.setAttribute('material', 'color', defaultColor); // }) }); } }); // for chinese font AFRAME.registerComponent('ttfFont', { schema: { fontSize: {type: 'number', default: 1}, opacity: {type: 'number', default: 1}, value: {type: 'string', default: ''}, fontFamily: {type: 'string', default: 'fontYenHeavy'}, color: {type: 'color', default: '#FFF'} }, isFontLoaded: async () => { const loaded = await new Promise((resolve, reject) => { const checkFontLoaded = setInterval(() => { if (ttfFonts['fontYenHeavy']) { resolve(true); clearInterval(checkFontLoaded); } }, 100); }); return loaded; }, init: async function () { const el = this.el; const data = this.data; // Create geometry. //const checkFontLoaded = await this.isFontLoaded(); const textGeometry = new three.TextGeometry( data.value, { font: ttfFonts[data.fontFamily], size: data.fontSize, height: 0.001, curveSegments: 5, // below values are testing, maybe just disable is ok bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.05, bevelOffset: 0, bevelSegments: 5 }); // console.log(textGeometry); // .index textGeometry.center(); // Create material. const textMaterial = new three.MeshStandardMaterial({ color: data.color, opacity: data.opacity, visible: (data.opacity !== 0), transparent: true, needsUpdate: true }); textMaterial.opacity = data.opacity; // ??? textMaterial.transparent = true; // ??? textMaterial.visible = (data.opacity !== 0); // ??? // Create mesh. this.mesh = new three.Mesh(textGeometry, textMaterial); this.mesh.material.transparent = true; // Set mesh on entity. el.setObject3D('mesh', this.mesh); // console.log('init'); // call update to get the correct rendering this.update(data); }, // tick: function(){ // console.log('tick', this.font); // }, update: async function (oldData) { // console.log('update', oldData); const data = this.data; const el = this.el; // console.log(data, oldData); // add this line to prevent update before init const checkFontLoaded = await this.isFontLoaded(); // If `oldData` is empty, then this means we're in the initialization process. // No need to update. if (Object.keys(oldData).length === 0) { return; } // do update logic here if (oldData.fontSize !== data.fontSize || oldData.value !== data.value || oldData.fontFamily !== data.fontFamily) { this.mesh.geometry = new three.TextGeometry( data.value, { font: ttfFonts[data.fontFamily], size: data.fontSize, height: 0.001, curveSegments: 5, // below values are testing, maybe just disable is ok bevelEnabled: false, bevelThickness: 0.01, bevelSize: 0.1, bevelOffset: 0, bevelSegments: 5 }); this.mesh.geometry.center(); } // skip check since the call from init always the same value // and need an assigment to make it render correctly // if (oldData.color !== data.color) { this.mesh.material.color = new three.Color(data.color); // } // if (oldData.opacity !== data.opacity) { this.mesh.material.opacity = data.opacity; this.mesh.material.visible = (data.opacity !== 0); this.mesh.material.transparent = true; // } // this.mesh.material.needsUpdate = true; } }); AFRAME.registerComponent('disable-inspector', { dependencies: ['inspector'], init: function () { this.el.components.inspector.remove(); } }); class AFramePanel extends Component { constructor(props) { super(props); // this.Editor = this.props.editor; this.editor = null; this.sceneEl = null; this.setSceneEl = element => this.sceneEl = element; this.cameraEl = null; this.setCameraEl = element => this.cameraEl = element; this.cameraPreviewEl = null; //this.setCameraPreviewEl = element => this.cameraPreviewEl = element; this.cameraPreviewScreenEl = null; //this.setCameraPreviewScreenEl = element => this.cameraPreviewScreenEl = element; [ 'updateCameraView' ].forEach(methodName => { this[methodName] = this[methodName].bind(this); }); } componentDidMount() { // real-time view on the camera // Events.on('editor-load', obj => { // this.editor = obj; // }); // Events.on('refreshsidebarobject3d', _=> { // this.updateCameraView(); // }) // window.addEventListener('resize', this.updateCameraView); const props = this.props; const sceneContext = props.sceneContext; this.sceneEl.data = { socket: props.socket, sceneContext: sceneContext }; } componentWillUnmount() { } componentDidUpdate(prevProps, prevState) { if (this.props.socket !== prevProps.socket) { this.sceneEl.data.socket = this.props.socket; } } updateCameraView() { const editor = this.editor; const renderer = editor.sceneEl.renderer; const scene = editor.sceneEl.object3D; const camera = editor.currentCameraEl.getObject3D('camera'); const width = renderer.domElement.width; const height = renderer.domElement.height; const newHeight = 270 / width * height; const canvas = this.cameraPreviewEl; const ctx = canvas.getContext('2d'); const helper_status = []; for (let i = 0; i < editor.sceneHelpers.children.length; i++){ helper_status[i] = editor.sceneHelpers.children[i].visible; editor.sceneHelpers.children[i].visible = false; } camera.aspect = width / height; camera.updateProjectionMatrix(); renderer.render(scene, camera); for (let i = 0; i < editor.sceneHelpers.children.length; i++){ editor.sceneHelpers.children[i].visible = helper_status[i]; } canvas.width = 270; canvas.height = newHeight; if (camera.aspect > 1) { this.cameraPreviewScreenEl.setAttribute( 'width', canvas.width / 270 * 0.6 ); this.cameraPreviewScreenEl.setAttribute( 'height', canvas.height / 270 * 0.6 ); } else { this.cameraPreviewScreenEl.setAttribute( 'width', canvas.width / newHeight * 0.6 ); this.cameraPreviewScreenEl.setAttribute( 'height', canvas.height / newHeight * 0.6 ); } ctx.drawImage(renderer.domElement, 0, 0, canvas.width, canvas.height); } render() { const props = this.props; const sceneContext = props.sceneContext; const entitiesList = sceneContext.getEntitiesList(); return ( <div id="aframe-panel"> <a-scene embedded background="color:#6EBAA7" el-name="Background" ref={this.setSceneEl} vr-mode-ui={`enabled: ${props.disableVR? 'false': 'true'}`} user-mode={props['user-mode']} disable-inspector > <a-assets> {/* try load some fonts */} <img src={iconNavigation} id="iconNavigation" /> {/* <canvas ref={this.setCameraPreviewEl} id="camera-preview"/> */} {/* <a-asset-item id="dcjaiModelObj" src={dcjaiobj}></a-asset-item> <img id="dcjaiModelTex" src={dcjaitex} /> */} {/* <a-asset-item id="fontSchoolbellRegular" src={fontSchoolbellRegular} /> */} {/* <img src={fontSchoolbellRegular} id="fontSchoolbellRegularImg" /> */} {/* <a-asset-item id="fontNotoSerifTC" src={fontNotoSerifTC} /> */} </a-assets> {/* <a-sky el-name="sky" el-isSystem={true} color="#FF0000"></a-sky> */} <a-entity position="0 0 0" rotation="0 0 0"> {/* test */} <a-camera el-isSystem={false} position="0 0 0" el-defaultCamera="true" look-controls ref={this.setCameraEl}> {/* camera model */} <a-cone position="0 0 0.5" rotation="90 0 0" geometry="radius-top: 0.15;radius-bottom: 0.5" material="color:#333"></a-cone> <a-box position="0 0 1" scale="0.8 0.8 1.2" material="color:#222"></a-box> <a-cylinder position="0 0.6 0.7" scale="0.3 0.3 0.3" rotation="0 0 90" material="color:#272727"></a-cylinder> <a-cylinder position="0 0.6 1.3" scale="0.3 0.3 0.3" rotation="0 0 90" material="color:#272727"></a-cylinder> {/* camera "monitor" */} {/* <a-plane position="0 0 1.61" material="src: #camera-preview" ref={this.setCameraPreviewScreenEl} scale="0.8 0.8 0.8" rotation="0 0 0"></a-plane> */} {/* camera model end */} {/* click pointer */} <a-entity cursor="fuse: true; fuseTimeout: 1000" position="0 0 -1" geometry="primitive: ring; radiusInner: 0.02; radiusOuter: 0.03" material="color: black; shader: flat"> </a-entity> {/* click pointer end */} </a-camera> </a-entity> <a-light type="ambient" intensity="0.8" el-name="environment light" el-isSystem={true} color="#EEEEEE"></a-light> <a-light position="600 300 900" color="#FFFFFF" intensity="0.9" type="directional" el-name="directional light" el-isSystem={true}></a-light> {/** * method to load an obj model to a-entity */} {/* <a-entity obj-model="obj:#dcjaiModelObj" material="src:#dcjaiModelTex" scale="0.03 0.03 0.03"></a-entity> */} </a-scene> </div> ); } } export default withSceneContext(AFramePanel);<file_sep>/src/vendor/editor.js // import * as THREE from 'three'; import AFRAME from 'aframe'; import { CameraHelper } from './threejs/CameraHelper'; const AFrameExtras = require('aframe-extras'); // use the THREE in aframe const THREE = AFRAME.THREE; const tween = AFRAME.TWEEN; const Events = require('./Events'); const Viewport = require('./viewport').default; function Editor () { this.modules = {}; this.sceneEl = {}; this.on = Events.on; this.opened = false; // Detect if the scene is already loaded if (document.readyState === 'complete' || document.readyState === 'loaded') { this.onDomLoaded(); } else { document.addEventListener('DOMContentLoaded', this.onDomLoaded.bind(this)); } // DEBUG USE, can be removed later AFRAME.EDITOR = this; } Editor.prototype = { /** * Callback once the DOM is completely loaded so we could query the scene */ onDomLoaded: function () { this.sceneEl = AFRAME.scenes[0]; if (!this.sceneEl) { setTimeout(this.onDomLoaded.bind(this), 100); return; } if (this.sceneEl.hasLoaded) { this.onSceneLoaded(); } else { this.sceneEl.addEventListener('loaded', this.onSceneLoaded.bind(this)); } }, /** * Callback when the a-scene is loaded */ onSceneLoaded: function () { this.container = document.querySelector('.a-canvas'); const self = this; // Wait for camera if necessary. if (!AFRAME.scenes[0].camera) { AFRAME.scenes[0].addEventListener('camera-set-active', function waitForCamera () { AFRAME.scenes[0].removeEventListener('camera-set-active', waitForCamera); self.onSceneLoaded(); }); return; } this.currentCameraEl = AFRAME.scenes[0].camera.el; this.currentCameraEl.setAttribute('data-aframe-editor-original-camera', ''); // If the current camera is the default, we should prevent AFRAME from // remove it once when we inject the editor's camera if (this.currentCameraEl.hasAttribute('data-aframe-default-camera')) { this.currentCameraEl.removeAttribute('data-aframe-default-camera'); this.currentCameraEl.setAttribute('data-aframe-editor', 'default-camera'); } this.editorCameraEl = document.createElement('a-entity'); // keep this to hide the camera form real editor this.editorCameraEl.isInspector = true; this.editorCameraEl.addEventListener('componentinitialized', evt => { if (evt.detail.name !== 'camera') { return; } this.EDITOR_CAMERA = this.editorCameraEl.getObject3D('camera'); this.initUI(); this.initModules(); Events.emit('editor-load', this); }); this.editorCameraEl.setAttribute('camera', {far: 10000, fov: 50, near: 0.05, active: true}); this.editorCameraEl.setAttribute('data-aframe-editor', 'camera'); this.editorCameraEl.setAttribute('wasd-controls', true); AFRAME.scenes[0].appendChild(this.editorCameraEl); }, initModules: function () { for (var moduleName in this.modules) { var module = this.modules[moduleName]; console.log('Initializing module <%s>', moduleName); module.init(this.sceneEl); } }, initUI: function () { this.EDITOR_CAMERA.position.set(20, 10, 20); this.EDITOR_CAMERA.lookAt(new THREE.Vector3()); this.EDITOR_CAMERA.updateMatrixWorld(); this.camera = this.EDITOR_CAMERA; this.initEvents(); this.selected = null; window.dispatchEvent(new Event('editor-loaded')); this.scene = this.sceneEl.object3D; this.helpers = {}; this.sceneHelpers = new THREE.Scene(); this.sceneHelpers.userData.source = 'EDITOR'; this.sceneHelpers.visible = true; // false; this.editorActive = false; this.viewport = new Viewport(this); Events.emit('windowresize'); var scope = this; function addObjects (object) { for (var i = 0; i < object.children.length; i++) { var obj = object.children[i]; for (var j = 0; j < obj.children.length; j++) { scope.addObject(obj.children[j]); } } } addObjects(this.sceneEl.object3D); document.addEventListener('model-loaded', event => { this.addObject(event.target.object3D); }); // Events.on('selectedentitycomponentchanged', event => { // this.addObject(event.target.object3D); // }); // Events.on('selectedentitycomponentcreated', event => { // this.addObject(event.target.object3D); // }); this.scene.add(this.sceneHelpers); this.open(); // this.close(); }, removeObject: function (object) { const el = object.el; Events.emit('objectbeforeremoved', el); if (el) { el.pause(); this.deselect(); // Remove just the helper as the object will be deleted by Aframe this.removeHelpers(el.object3D); // need to do delete if the object still exist if (el.parentNode) { el.parentNode.removeChild(el); } // el.destroy(); Events.emit('objectremoved', el.object3D); } }, addHelper: (function () { var geometry = new THREE.SphereBufferGeometry(2, 4, 2); var material = new THREE.MeshBasicMaterial({ color: 0xff0000, visible: false }); return function (object) { var helper; if (object instanceof THREE.Camera) { // no camera helper // return; this.cameraHelper = helper = new CameraHelper(object, 0.1); } else if (object instanceof THREE.PointLight) { // hide all lights controls return; // helper = new THREE.PointLightHelper(object, 1); } else if (object instanceof THREE.DirectionalLight) { // hide all lights controls return; // helper = new THREE.DirectionalLightHelper(object, 1); } else if (object instanceof THREE.SpotLight) { // hide all lights controls return; // helper = new THREE.SpotLightHelper(object, 1); } else if (object instanceof THREE.HemisphereLight) { // hide all lights controls return; // helper = new THREE.HemisphereLightHelper(object, 1); } else if (object instanceof THREE.SkinnedMesh) { helper = new THREE.SkeletonHelper(object); } else { // no helper for this object type return; } var parentId = object.parent.id; // Helpers for object already created, remove every helper if (this.helpers[parentId]) { for (var objectId in this.helpers[parentId]) { this.sceneHelpers.remove(this.helpers[parentId][objectId]); } } else { this.helpers[parentId] = {}; } var picker = new THREE.Mesh(geometry, material); picker.name = 'picker'; picker.userData.object = object; picker.userData.source = 'EDITOR'; helper.add(picker); helper.fromObject = object; helper.userData.source = 'EDITOR'; this.sceneHelpers.add(helper); this.helpers[parentId][object.id] = helper; Events.emit('helperadded', helper); }; })(), removeHelpers: function (object) { var parentId = object.id; if (this.helpers[parentId]) { for (var objectId in this.helpers[parentId]) { var helper = this.helpers[parentId][objectId]; Events.emit('helperremoved', helper); this.sceneHelpers.remove(helper); } delete this.helpers[parentId]; } }, selectEntity: function (entity) { // console.log(entity); if (entity && !entity.components['camera'] && entity.parentEl !== AFRAME.scenes[0]) { entity = entity.parentEl; } this.selectedEntity = entity; if (entity) { this.select(entity.object3D); } else { this.select(null); } Events.emit('enablecontrols', false); // edited: 07052019 // forgot the reason to add these two lines // comment out since it will trigger select twice times // if (emit === undefined) { // Events.emit('entityselected', entity); // } }, enableControls: function(isEnable) { Events.emit('enablecontrols', !!isEnable); }, initEvents: function () { window.addEventListener('keydown', evt => { // Alt + Ctrl + i: Shorcut to toggle the editor // var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey; // j: Shorcut to toggle the editor var shortcutPressed = ((evt.keyCode === 32) && evt.ctrlKey); if (shortcutPressed) { this.toggle(); } }); Events.on('entityselected', entity => { this.selectEntity(entity, false); }); Events.on('objectselectedfromtimeline', (obj, enableControls) => { this.selectFromTimeline(obj, enableControls); }); Events.on('editormodechanged', active => { const sceneEl = this.sceneEl; this.editorActive = active; this.sceneHelpers.visible = this.editorActive; setTimeout(()=>{ sceneEl.resize(); }, 100); }); Events.on('createnewentity', definition => { this.createNewEntity(definition); }); Events.on('selectedentitycomponentchanged', event => { this.addObject(event.target.object3D); }); Events.on('removeObject', obj => { this.removeObject(obj); }) Events.on('takeSnapshot', callback => { callback(this.takeSnapshot()); }); const editorinstance = this; Events.on('getEditorInstance', callback => { callback(editorinstance); }); document.addEventListener('child-detached', event => { var entity = event.detail.el; editorinstance.removeObject(entity.object3D); }); // 20181111: add to handle add entity from other sources... document.addEventListener('child-attached', event => { const entity = event.detail.el; editorinstance.addObject(entity.object3D); }); // key events document.addEventListener('keyup', event => { // esc btn if (event.which === 27 && editorinstance.selected) { editorinstance.deselect(); } // print screen if (event.which === 44) { editorinstance.takeSnapshot(); } // delete btn // always deleted when editing values // if (event.which === 46 && editorinstance.opened && editorinstance.selected) { // // check if camera // if (editorinstance.selected.el.components['camera']) { // return; // } // let el = editorinstance.selected.el; // Events.emit('objectbeforeremoved', el); // el.pause(); // editorinstance.deselect(); // // editorinstance.removeObject(el.object3D); // el.parentNode.removeChild(el); // } }); Events.on('dommodified', mutations => { if (!mutations) { return; } mutations.forEach(mutation => { if (mutation.type !== 'childList') { return; } Array.prototype.slice.call(mutation.removedNodes).forEach(removedNode => { if (this.selectedEntity === removedNode) { this.selectEntity(null); } }); }); }); }, selectById: function (id) { if (id === this.camera.id) { this.select(this.camera); return; } this.select(this.scene.getObjectById(id, true)); }, selectFromTimeline: function (object, enableControls) { // if (this.selected === object) { // return; // } this.selected = object; Events.emit('objectselected', object, enableControls); }, // Change to select object select: function (object) { if (this.selected === object) { return; } this.selected = object; Events.emit('objectselected', object); }, deselect: function () { this.select(null); }, /** * Reset the current scene, removing its content. */ clear: function () { this.camera.copy(this.EDITOR_CAMERA); this.deselect(); AFRAME.scenes[0].innerHTML = ''; Events.emit('editorcleared'); }, /** * Helper function to add a new entity with a list of components * @param {object} definition Entity definition to add: * {element: 'a-entity', components: {geometry: 'primitive:box'}} * @return {Element} Entity created */ createNewEntity: function (definition, parentEl) { var entity = document.createElement(definition.element); var parentEl = parentEl || this.sceneEl; // load default attributes for (var attr in definition.components) { entity.setAttribute(attr, definition.components[attr]); } // Ensure the components are loaded before update the UI entity.addEventListener('loaded', () => { this.addEntity(entity); entity.object3D.el = entity; }); // this.sceneEl.appendChild(entity); parentEl.appendChild(entity); return entity; }, takeSnapshot: function() { var renderer = this.sceneEl.renderer; var scene = this.sceneEl.object3D; var camera = this.currentCameraEl.getObject3D('camera'); // save current selected object var selected = this.selected; var helper_status = []; for (let i = 0; i < this.sceneHelpers.children.length; i++){ helper_status[i] = this.sceneHelpers.children[i].visible; this.sceneHelpers.children[i].visible = false; } this.deselect(); renderer.render(scene, camera); // if (selected) { this.select(selected); // } for (let i = 0; i < this.sceneHelpers.children.length; i++){ this.sceneHelpers.children[i].visible = helper_status[i]; } var result = { 'camera': { 'position': camera.getWorldPosition(), 'rotation' : camera.getWorldRotation() }, 'image': renderer.domElement.toDataURL() }; Events.emit('snapshotcreated', result); return result; }, moveCamera: function(camera) { // move the camera to the position and rotation provided // console.log('moveCamera',camera); let editorinstance = this; let viewCamera = this.currentCameraEl; let current_position = viewCamera.getAttribute('position'); let current_rotation = viewCamera.getAttribute('rotation'); let new_position = camera.position; let new_rotation = camera.rotation; var coords = { pos_x: current_position.x, pos_y: current_position.y, pos_z: current_position.z, rot_x: THREE.Math.degToRad(current_rotation.x), rot_y: THREE.Math.degToRad(current_rotation.y), rot_z: THREE.Math.degToRad(current_rotation.z) }; var newcoords = { pos_x: new_position.x, pos_y: new_position.y, pos_z: new_position.z, rot_x: new_rotation.x, rot_y: new_rotation.y, rot_z: new_rotation.z }; // var tween = AFRAME.TWEEN var c = coords; var z = new tween.Tween(c) .to(newcoords,1000) .onUpdate(function(){ viewCamera.setAttribute('position',{x:c.pos_x,y:c.pos_y,z:c.pos_z}); viewCamera.setAttribute('rotation',{x:THREE.Math.radToDeg(c.rot_x),y:THREE.Math.radToDeg(c.rot_y),z:THREE.Math.radToDeg(c.rot_z)}); viewCamera.components['look-controls'].yawObject.rotation.x = c.rot_x; viewCamera.components['look-controls'].yawObject.rotation.y = c.rot_y; viewCamera.components['look-controls'].yawObject.rotation.z = c.rot_z; viewCamera.components['look-controls'].pitchObject.rotation.x = c.rot_x; viewCamera.components['look-controls'].pitchObject.rotation.y = c.rot_y; viewCamera.components['look-controls'].pitchObject.rotation.z = c.rot_z; }).onComplete(function(){ // console.log('animate complete'); Events.emit('objectchanged',viewCamera); // update the info box if camera is selected if (editorinstance.selected && editorinstance.selected.el === viewCamera) { Events.emit('refreshsidebarobject3d',viewCamera.object3D); } }) z.start(); // viewCamera.setAttribute('position',camera.position); // // this is need for correct display the line, setAttribute('rotation', ...) // viewCamera.setAttribute('rotation',{x: THREE.Math.radToDeg(camera.rotation.x),y: THREE.Math.radToDeg(camera.rotation.y),z: THREE.Math.radToDeg(camera.rotation.z)}); // viewCamera.components['look-controls'].yawObject.rotation.copy(camera.rotation); // viewCamera.components['look-controls'].pitchObject.rotation.copy(camera.rotation); // // update the controls position // Events.emit('objectchanged',viewCamera); // // update the info box if camera is selected // if (this.selected && this.selected.el === viewCamera) { // Events.emit('refreshsidebarobject3d',viewCamera.object3D); // } }, addEntity: function (entity) { this.addObject(entity.object3D); this.selectEntity(entity); }, /** * Toggle the editor */ toggle: function () { if (this.opened) { this.close(); } else { this.open(); } }, /** * Open the editor UI */ open: function () { this.sceneEl = AFRAME.scenes[0]; this.opened = true; if (!this.sceneEl.hasAttribute('aframe-editor-motion-capture-replaying')) { this.sceneEl.pause(); this.sceneEl.exitVR(); } if (this.sceneEl.hasAttribute('embedded')) { // Remove embedded styles, but keep track of it. // this.sceneEl.removeAttribute('embedded'); this.sceneEl.setAttribute('aframe-editor-removed-embedded'); } document.body.classList.add('aframe-editor-opened'); Events.emit('editormodechanged', true); }, /** * Closes the editor and gives the control back to the scene * @return {[type]} [description] */ close: function () { this.opened = false; Events.emit('editormodechanged', false); this.sceneEl.play(); if (this.sceneEl.hasAttribute('aframe-editor-removed-embedded')) { // this.sceneEl.setAttribute('embedded', ''); this.sceneEl.removeAttribute('aframe-editor-removed-embedded'); } document.body.classList.remove('aframe-editor-opened'); this.sceneEl.resize(); }, addObject: function (object) { var scope = this; object.traverse(child => { if (!child.el || !child.el.isInspector) { scope.addHelper(child, object); } }); Events.emit('objectadded', object); Events.emit('scenegraphchanged'); } }; // v1 // const editor = new Editor(); // DEBUG USE, can be removed later // AFRAME.EDITOR = editor; // export default editor; // v1 end // v2 test // initial the editor in the react rather then auto initial here export default Editor; // v2 <file_sep>/src/containers/aframeEditor/homePage/infoPanel/infoTypeCone.js /* info generation of right panel */ import React, {Component} from 'react'; import {roundTo, addToAsset} from 'globals/helperfunctions'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome' import './infoTypeCone.css'; var Events = require('vendor/Events.js'); let editor = null; Events.on('editor-load', obj => { editor = obj; }); function rgb2hex(rgb){ if (!rgb) return '#FFFFFF'; const parsedrgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i); return (parsedrgb && parsedrgb.length === 4) ? "#" + ("0" + parseInt(parsedrgb[1],10).toString(16)).slice(-2) + ("0" + parseInt(parsedrgb[2],10).toString(16)).slice(-2) + ("0" + parseInt(parsedrgb[3],10).toString(16)).slice(-2) : rgb; } class InfoTypeCone extends Component { constructor(props) { super(props); props.timeline[props.timelinePosition]['material']['color'] = rgb2hex(props.timeline[props.timelinePosition]['material']['color']); this.state = { el: props.el, data: props.timeline[props.timelinePosition] }; this.eventListener = Array(); // this.changeObjectTexture = this.changeObjectTexture.bind(this); this.changeObjectField = this.changeObjectField.bind(this); this.deleteObject = this.deleteObject.bind(this); this.selectTimelinePosition = this.selectTimelinePosition.bind(this); } componentDidMount() { // let self = this; // const props = this.props; // // // later need to add event emit when change value // // this.setState({ // // }); // // console.log('componentDidMount'); // props.timeline[props.timelinePosition]['material']['color'] = rgb2hex(props.timeline[props.timelinePosition]['material']['color']); // this.state = { // el: props.el, // data: props.timeline[props.timelinePosition] // }; } componentDidUpdate() { const props = this.props; props.timeline[props.timelinePosition]['material']['color'] = rgb2hex(props.timeline[props.timelinePosition]['material']['color']); this.state = { el: props.el, data: props.timeline[props.timelinePosition] }; } /* componentWillReceiveProps(newProps) { console.log('componentWillReceiveProps'); let self = this; // later need to add event emit when change value this.setState({ el: newProps.el, data: fetchDataFromEl(newProps.el) }); } */ componentWillUnmount() { for (var emitter in this.eventListener) { Events.removeListener(emitter,this.eventListener[emitter]); } } deleteObject() { // editor.deselect(); // this.state.el.parentNode.removeChild(this.state.el); } selectTimelinePosition(transformMode) { const props = this.props; Events.emit('timelinepositionselected', props.el.object3D, props.timeline.uuid, props.timelinePosition); if (transformMode) { Events.emit('transformmodechanged', transformMode); } } changeObjectField(event) { const props = this.props; let field = event.target.getAttribute('data-value').split('.'); // props.timeline // props.timelinePosition const tmp = this.state.data[field[0]]; tmp[field[1]] = event.target.value; // this.setState({ // data: tmp // }); props.timeline[props.timelinePosition][field[0]][field[1]] = event.target.value; Events.emit('timelinepositionselected', props.el.object3D, props.timeline.uuid, props.timelinePosition); // Events.emit('timelineselected', props.el.object3D, props.timeline.uuid); } render() { let data = this.state.data; if (!data) return null; return ( <div> <div className="vec3D-col" onFocus={()=>{this.selectTimelinePosition('translate')}}> <button><FontAwesomeIcon icon="arrows-alt" /></button> <div className="vec3D-fields"> <input className="textInput" value={data.position.x} data-value="position.x" onChange={this.changeObjectField} /> <input className="textInput" value={data.position.y} data-value="position.y" onChange={this.changeObjectField} /> <input className="textInput" value={data.position.z} data-value="position.z" onChange={this.changeObjectField} /> </div> </div> <div> <div className="vec3D-col" onFocus={()=>{this.selectTimelinePosition('rotate')}}> <button><FontAwesomeIcon icon="sync-alt" /></button> <div className="vec3D-fields"> <input className="textInput" value={data.rotation.x} data-value="rotation.x" onChange={this.changeObjectField} /> <input className="textInput" value={data.rotation.y} data-value="rotation.y" onChange={this.changeObjectField} /> <input className="textInput" value={data.rotation.z} data-value="rotation.z" onChange={this.changeObjectField} /> </div> </div> </div> <div> <div className="vec3D-col" onFocus={()=>{this.selectTimelinePosition('scale')}}> <button><FontAwesomeIcon icon="expand-arrows-alt" /></button> <div className="vec3D-fields"> <input className="textInput" value={data.scale.x} data-value="scale.x" onChange={this.changeObjectField} /> <input className="textInput" value={data.scale.y} data-value="scale.y" onChange={this.changeObjectField} /> <input className="textInput" value={data.scale.z} data-value="scale.z" onChange={this.changeObjectField} /> </div> </div> </div> <div> <div className="vec3D-col" onFocus={()=>{this.selectTimelinePosition()}}> <button>radius top/ bottom</button> <div className="vec3D-fields"> <input className="textInput" value={data.geometry.radiusTop} data-value="geometry.radiusTop" onChange={this.changeObjectField} /> <input className="textInput" value={data.geometry.radiusBottom} data-value="geometry.radiusBottom" onChange={this.changeObjectField} /> </div> </div> </div> {/* <div> texture: <span><img className={data.textureClass} src={data.texture} /></span><input onChange={this.changeObjectTexture} type="file" /> </div> */} <div className="vec3D-col" onFocus={()=>{this.selectTimelinePosition()}}> <span>color: </span><input className="colorInput" onChange={this.changeObjectField} type="color" data-value="material.color" value={data.material.color} /> </div> <div className="vec3D-col" onFocus={()=>{this.selectTimelinePosition()}}> opacity: <input className="textInput" value={data.material.opacity} data-value="material.opacity" onChange={this.changeObjectField} /> </div> </div> ); } } export default InfoTypeCone;<file_sep>/src/utils/number/isStrAnInt.js import stricterParseInt from './stricterParseInt'; const isStrAnInt = (str) => { const parseResult = stricterParseInt(str); //return parseResult !== NaN; // note this always return true return !Number.isNaN(parseResult); } export default isStrAnInt;<file_sep>/src/containers/aframeEditor/homePage/timelinePanel.js /* Timeline Panel should be something that show the all entity's name and events happen in the time interval ( = ) ▫▫▫▫▫▫▫▫▫▫▫ ┌────────┐ │ AFRAME ◲ └────────┘ ========== */ import React, {Component} from 'react'; import {withSceneContext} from 'globals/contexts/sceneContext'; import {LanguageContextConsumer, LanguageContextMessagesConsumer} from 'globals/contexts/locale/languageContext'; import Draggable from 'react-draggable'; // import {Resizable} from 'react-resizable'; import {Rnd as ResizableAndDraggable} from 'react-rnd'; // import EntitiesList from 'containers/panelItem/entitiesList'; import {jsonCopy} from 'globals/helperfunctions'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; import './timelinePanel.css'; //const Events = require('vendor/Events.js'); //const uuid = require('uuid/v1'); function getScaleIndicatorText(totaltime, scale, elWidth) { const listEl = []; const textScale = (scale >= 50 ? 1 : 5); const scalePx = textScale * scale; for (let i = 0; (i < (totaltime + textScale) || elWidth > i ) ; i+=textScale) { listEl.push(<div key={i} className="indicator" style={{marginRight: scalePx}}> <span> {i} </span> </div>); } return listEl; } class TimelinePanel extends Component { constructor(props) { super(props); this.scaleLimit = { min: 10, max: 70 }; this.state = { timeScale: 25, editingName: null, timelineListElWidth: 0, entitiesList: [], fetchedEntitiesList: {}, showContextMenu: false }; this.entitiesList = { scrollLeft: 0, scrollTop: 0 }; this.timelineEntity = {}; this.timePointer = React.createRef(); this.resizableAndDraggable = {}; this.dragging = false; this.handleScroll = this.handleScroll.bind(this); this.handleWheel = this.handleWheel.bind(this); this.handleResize = this.handleResize.bind(this); this.changeCurrentTime = this.changeCurrentTime.bind(this); this.selectEntity = this.selectEntity.bind(this); this.deleteEntity = this.deleteEntity.bind(this); this.showContextMenu = this.showContextMenu.bind(this); this.hideContextMenu = this.hideContextMenu.bind(this); this.copyEntity = this.copyEntity.bind(this); // this.selectEntityTimelinePosition = this.selectEntityTimelinePosition.bind(this) } componentDidMount() { window.addEventListener('resize', this.handleResize); this.timelineListEl.addEventListener('wheel', this.handleWheel, {passive: false}); this.handleResize(); } componentDidUpdate() { // console.log('componentDidUpdate'); // this.forceUpdate(); } static getDerivedStateFromProps(nextProps, prevState) { // fetch the sceneContext const currentEntitiesList = nextProps.sceneContext.getEntitiesList(); const fetchedList = {}; currentEntitiesList.forEach(entity => { const entityId = entity['id']; fetchedList[entityId] = jsonCopy(entity); fetchedList[entityId]['timelines'] = {}; entity.timelines.forEach(timeline => { fetchedList[entityId]['timelines'][timeline['id']] = timeline; }) }) return { entitiesList: currentEntitiesList, fetchedEntitiesList: fetchedList }; } componentWillUnmount() { window.removeEventListener('resize', this.handleResize); this.timelineListEl.removeEventListener('wheel', this.handleWheel); } handleResize(event) { this.setState({ timelineListElWidth: this.timelineListEl.getBoundingClientRect().width }); } handleScroll(event) { this.entitiesList = { scrollLeft: event.currentTarget.scrollLeft, scrollTop: event.currentTarget.scrollTop } // console.log('handleScroll', this.entitiesList); if (this.needUpdate) { window.cancelAnimationFrame(this.needUpdate); } const self = this; this.needUpdate = window.requestAnimationFrame(function() { self.recalculateFreezeElPosition(); }); } handleWheel(event) { // seems need handle the horizontal scroll too... event.preventDefault(); // edge no scrollBy ... if (event.shiftKey) { this.timelineListEl.scrollLeft += Math.sign(event.deltaY) * 32; } else { this.timelineListEl.scrollTop += Math.sign(event.deltaY) * 32; } } changeCurrentTime(event, data) { // this.setState({ // 'currentTime': data.x / this.state.timeScale // }) this.currentTime= data.x / this.state.timeScale; this.props.sceneContext.updateCurrentTime(this.currentTime); // Events.emit('setTimelineTime', data.x / this.state.timeScale); // console.log(this.timePointer); } startChangeTimelineTime(event, entityId, timelineId) { const allTimeline = this.state.fetchedEntitiesList[entityId]['timelines']; const selectedTimeline = allTimeline[timelineId]; this.lastValidStart = selectedTimeline['start']; this.initialWidth = selectedTimeline['duration']; this.lastValidWidth = 0; } changeTimelineTime(event, entityId, timelineId, xPos, width = this.lastValidWidth) { const allTimeline = this.state.fetchedEntitiesList[entityId]['timelines']; const newStartTime = Math.round(xPos / this.state.timeScale); // const thisTimeline = allTimeline[timelineId]; const newEndTime = Math.round(newStartTime + this.initialWidth + width / this.state.timeScale); // thisTimeline.start = newStartTime; // save the time data if not overlapping others let isValid = newStartTime < newEndTime; Object.keys(allTimeline).filter(tl => tl !== timelineId).forEach(searchTimelineId => { const searchTimeline = allTimeline[searchTimelineId]; const tlStart = searchTimeline.start; const tlEnd = tlStart + searchTimeline.duration; if (newEndTime > tlStart && newStartTime < tlEnd) { isValid = false; } }) if (newStartTime < 0) { isValid = false; } if (isValid) { this.lastValidStart = newStartTime; this.lastValidWidth = width; } } changedTimelineTime(event, entityId, timelineId, xPos, width = this.lastValidWidth) { this.changeTimelineTime(event, entityId, timelineId, xPos, width); // hack the draggable position ... this.resizableAndDraggable[entityId][timelineId]['draggable']['state']['x'] = this.lastValidStart * this.state.timeScale; // Events.emit('updateTimeline', entityId, this.props.selectedSlide, timelineId, this.lastValidStart, this.initialWidth + this.lastValidWidth / this.state.timeScale); this.props.sceneContext.updateTimeline({ start: this.lastValidStart, duration: this.initialWidth + this.lastValidWidth / this.state.timeScale }, timelineId); } addTimeline(event, entityId, slideId) { if (event.target === event.currentTarget) { const newStartTime = Math.floor((event.clientX - event.currentTarget.getBoundingClientRect().left) / this.state.timeScale); this.props.sceneContext.addTimeline(entityId, newStartTime); // Events.emit('addTimeline', entityId, slideId, newStartTime); } } changeEntityName(event, entityId) { // Events.emit('updateEntityName', entityId, event.currentTarget.value); // this.props.sceneContext.selectEntity(entityId); // selectEntity // this.props.sceneContext.updateEntity(); // selectEntity this.props.sceneContext.updateEntity({ name: event.target.value }, entityId); // selectEntity } selectEntity(event, entityId) { this.props.sceneContext.selectEntity(entityId); // selectEntity } deleteEntity(entityId) { this.props.sceneContext.deleteEntity(entityId); // selectEntity } // selectEntityTimeline(event, entityId, timelineId) { // // event.stopPropagation(); // Events.emit('setTimelinePositionSelected', entityId, this.props.selectedSlide, timelineId); // // Events.emit('objectselected', this.props.entities[entityId]['el']['object3D']); // event.stopPropagation(); // } selectEntityTimelinePosition(event, entityId, timelineId, dir) { // console.log(entityId, this.props.selectedSlide); // Events.emit('setTimelinePositionSelected', entityId, this.props.selectedSlide, timelineId, position); // this.props.sceneContext.selectEntity(entityId); // this.props.sceneContext.selectTimeline(timelineId); const position = ( dir === "left"? "startAttribute" : dir === "right"? "endAttribute" : "" ); this.props.sceneContext.selectTimelinePosition(position, timelineId, entityId); event.preventDefault(); event.stopPropagation(); } changeTimeScale(scale) { const state = this.state; const entitiesList = state.fetchedEntitiesList; const projectedScale = (this.state.timeScale >= 50? 5 * scale: scale); const newTimeScale = Math.min(Math.max(this.state.timeScale + projectedScale, this.scaleLimit.min), this.scaleLimit.max); this.setState({ timeScale: newTimeScale }) this.timePointer.current.state.x = newTimeScale * this.props.currentTime; for (let entityId in this.resizableAndDraggable) { const entity = entitiesList[entityId]; const timelines = this.resizableAndDraggable[entityId]; for (let timelineId in timelines) { if (timelines[timelineId]) { const draggable = timelines[timelineId]["draggable"]; const timeline = entity['timelines'][timelineId]; draggable.state.x = newTimeScale * timeline.start; } } } } recalculateFreezeElPosition() { const entitiesList = this.entitiesList; const timeIndicatorWrap = this.timeIndicatorWrap; const entitiesListWrap = this.entitiesListWrap; entitiesListWrap.style.marginTop = -entitiesList.scrollTop + 'px'; timeIndicatorWrap.style.marginLeft = -entitiesList.scrollLeft + 'px'; } showContextMenu(e) { e.preventDefault(); // if (this.props.isEditing === false) return; this.setState({ showContextMenu: true, menuPosition: { x: e.clientX, y: e.clientY, } }) } hideContextMenu(e) { e.preventDefault(); this.setState({ showContextMenu: false }) } copyEntity() { this.props.sceneContext.copyEntity(); } render() { const props = this.props; const state = this.state; const sceneContext = props.sceneContext; const entitiesList = state.entitiesList; const selectedEntityId = sceneContext.getCurrentEntityId(); const selectedTimelineId = sceneContext.getCurrentTimelineId(); const selectedTimelinePosition = sceneContext.getCurrentTimelinePosition(); const totalTime = sceneContext.getSlideTotalTime(); const currentTime = sceneContext.getCurrentTime(); // console.log(currentTime); return ( <div id="timeline-panel" className="panel opened" onClick={(event)=>{ {/* this.contextMenu.style.display = 'none'; */} {/* this.selectEntityTimelinePosition(event); */} }} ref={(ref) =>this.timelinePanel = ref} > <div className="panel-header"> <div className="header-text"> <LanguageContextMessagesConsumer messageId="TimelinePanel.HeaderLabel" /> </div> <div className="timer"> <span className="current-time"> { Math.floor(currentTime / 60).toString().padStart(2,'0') + ':' + Math.floor(Math.round((currentTime * 100) % 6000) / 100).toString().padStart(2,'0') + '.' + (Math.round(currentTime % 60 * 100) % 100).toString().padStart(2,'0') } </span> <span>&nbsp;/&nbsp;</span> <span className="total-time"> {Math.floor(totalTime / 60).toString().padStart(2,'0') + ':' + Math.floor(totalTime % 60).toString().padStart(2,'0')} </span> </div> <div className="preview-timeline" onClick={() => { /* todo */ // Events.emit('previewTimeline'); if (sceneContext.slideIsPlaying) { sceneContext.stopSlide(); } else { sceneContext.playSlide(); } }} > {sceneContext.slideIsPlaying ? <FontAwesomeIcon icon="pause" />: <FontAwesomeIcon icon="play" /> } </div> <div className="toggle-panel" onClick={() => { this.timelinePanel.classList.toggle('opened'); let newY= 0; if (selectedEntityId !== undefined) { const selectedEntityIdx = entitiesList.findIndex(el => el.id === selectedEntityId); newY = (entitiesList.length - selectedEntityIdx - 1) * 32; } this.timelineListEl.scrollTo(this.timelineListEl.scrollLeft, newY); }} /> <div className="time-scale-controls"> <button disabled={(this.scaleLimit.min === state.timeScale)} onClick={() => { this.changeTimeScale(-1); }}>-</button> <button disabled={(this.scaleLimit.max === state.timeScale)} onClick={() => { this.changeTimeScale(1); }}>+</button> </div> </div> <div className="panel-body"> {/* <div className="totaltime-data" onClick={()=> Events.emit('previewTimeline')}> &nbsp; </div> */} <div className="time-scaler"> <div className="scroll-wrap" ref={ref => this.timeIndicatorWrap = ref}> <Draggable ref={this.timePointer} axis="x" grid={[state.timeScale, 0]} bounds={{left: 0, right: totalTime * state.timeScale}} position={{x: currentTime * state.timeScale, y: 0}} onStart={()=>this.timelinePanel.classList.add('timepointer-dragging')} onDrag={this.changeCurrentTime} onStop={()=>this.timelinePanel.classList.remove('timepointer-dragging')} > <div className="time-pointer" /> </Draggable> {getScaleIndicatorText(totalTime, state.timeScale, state.timelineListElWidth)} </div> </div> <div className="entities-list"> <div className="scroll-wrap" ref={ref => this.entitiesListWrap = ref}> {entitiesList.slice(0).reverse().map((entity) => { const entityId = entity['id']; return ( <div key={entityId} className={"entity-row" + (selectedEntityId === entityId? ' selected': '')}> {!entity.isSystem && entity['type'] !== 'a-camera' && selectedEntityId === entityId && <div className="delete-btn" onClick={() => { {/* Events.emit('deleteEntity', props.selectedEntityId); */} this.deleteEntity(entityId); }}> <FontAwesomeIcon icon="trash-alt" /> </div> } <div className="entity-name" onClick={(event) => { {/* console.log('Ctrl pressed: ', event.ctrlKey); */} //console.log('entityId: ', [entityId, selectedEntityId]); this.selectEntity(event, entityId); }} onContextMenu={(event) => { this.selectEntity(event, entityId); if (entity['type'] !== 'a-camera') { this.showContextMenu(event); } }} onDoubleClick={(event) => this.setState({editingName: entityId})} > {entityId !== null && state.editingName == entityId ? <input type="text" onChange={(event) => this.changeEntityName(event, entityId)} onBlur={(event) => this.setState({editingName: null})} maxLength={10} onKeyPress={(event) => { if (event.which === 13) { this.setState({editingName: null}) } }} value={entity.name} autoFocus={true} /> : <div>{entity.name}</div> } </div> </div> ) })} </div> </div> <LanguageContextConsumer render={ ({ messages }) => ( <div className="timeline-list" onScroll={this.handleScroll} ref={ref=> this.timelineListEl = ref}> {/* slice(0) to shallow copy */} {entitiesList.slice(0).reverse().map((entity) => { const entityId = entity['id']; {/* const selectedSlide = props.selectedSlide; */} const entityTimelines = sceneContext.getTimelinesList(entityId); // if (entity['slide'][selectedSlide]) { // entityTimelines = entity['slide'][selectedSlide]['timeline']; // } {/* console.log(state.timelineListElWidth, totalTime * state.timeScale); */} this.resizableAndDraggable[entityId] = {}; return ( <div key={entityId} className={"entity-row" + (selectedEntityId === entityId? ' selected': '') + (" item-count-" + entityTimelines.length) } style={{ width: Math.max(state.timelineListElWidth, (Math.ceil(totalTime / 5) * 5 + 1) * state.timeScale) - 10 }} > <div className="entity-timeline" onClick={(event) => { if (!this.dragging) { event.preventDefault(); this.addTimeline(event, entityId); } }} empty-text={messages['TimelinePanel.AddAnimationLabel']} style={{width: Math.max(state.timelineListElWidth, (Math.ceil(totalTime / 5) * 5 + 1) * state.timeScale) - 10}} > {entityTimelines.map((timelineData) => { const self = this; // const timelineData = selectedTimeline[timelineId]; const timelineId = timelineData['id']; // this.timelineEntity[timelineId] = entityId; return ( <ResizableAndDraggable ref={(ref)=>this.resizableAndDraggable[entityId][timelineId] = ref} key={timelineId + '_' + timelineData.start + '_' + timelineData.duration} className={`time-span${((selectedEntityId === entityId && selectedTimelineId === timelineId)? " selected": "")}`} default={{ x: timelineData.start * state.timeScale, y: 5, height: 24, width: timelineData.duration * state.timeScale }} size={{ height: 24, width: timelineData.duration * state.timeScale }} resizeGrid={[state.timeScale, 0]} dragGrid={[state.timeScale, 0]} dragAxis='x' enableResizing={{ top: false, right: true, bottom: false, left: true, topRight: false, bottomRight: false, bottomLeft: false, topLeft: false }} // remove the style assigned by the js, let css handle it resizeHandleStyles={{ left: {top: '',left: '',width: '',height: '',cursor: ''}, right: {top: '',right: '',width: '',height: '',cursor: ''} }} resizeHandleClasses={{ left: `position-select start-attribute resize-handle${(selectedEntityId === entityId && selectedTimelineId === timelineId && selectedTimelinePosition === "startAttribute")? ' selected': ''}`, right: `position-select end-attribute resize-handle${(selectedEntityId === entityId && selectedTimelineId === timelineId && selectedTimelinePosition === "endAttribute")? ' selected': ''}` }} onClick={(event) =>{ if (!self.dragging) { this.selectEntityTimelinePosition(event, entityId, timelineId); } }} onDragStart={(event, data)=>{ event.preventDefault(); this.selectEntityTimelinePosition(event, entityId, timelineId); self.dragging = true; self.startChangeTimelineTime(event, entityId, timelineId); }} onDrag={(event, data) => { this.changeTimelineTime(event, entityId, timelineId, data.lastX); }} onDragStop={(event, data) => { this.changedTimelineTime(event, entityId, timelineId, data.lastX); setTimeout(function(){ self.dragging = false; }, 0); }} onResizeStart={(event, dir, ref, delta, pos)=>{ event.preventDefault(); this.selectEntityTimelinePosition(event, entityId, timelineId, dir); this.dragging = true; {/* console.log('onResizeStart: ', event, dir, ref, delta,pos); */} this.startChangeTimelineTime(event, entityId, timelineId); ref.classList.add('resizing'); }} onResize={(event, dir, ref, delta, pos)=>{ {/* console.log('onResize: ', event, dir, ref, delta, pos); */} this.changeTimelineTime(event, entityId, timelineId, pos.x, delta.width); {/* !ref.classList.contains('resizing') && ref.classList.add('resizing'); */} {/* ref.style.cursor = "col-resize"; */} {/* ref.classList.add('resizing'); */} }} onResizeStop={(event, dir, ref, delta, pos)=>{ {/* console.log('onResizeStop: ', event, dir, ref, delta, pos); */} event.preventDefault(); ref.classList.remove('resizing'); {/* ref.style.cursor = ""; */} this.changedTimelineTime(event, entityId, timelineId, pos.x, delta.width); setTimeout(function(){ self.dragging = false; }, 0); }} dragHandleClassName="drag-handle" title={timelineData.start + ' - ' + (timelineData.start + timelineData.duration)} > <div className="drag-handle"></div> {/* <div className={"position-select start-attribute" + (props.selectedTimeline === timelineId && props.selectedTimelinePosition === "startAttribute"? " selected": "")} onClick={(event) => this.selectEntityTimelinePosition(event, entityId, timelineId, "startAttribute") } /> <div className={"position-select end-attribute" + (props.selectedTimeline === timelineId && props.selectedTimelinePosition === "endAttribute"? " selected": "")} onClick={(event) => this.selectEntityTimelinePosition(event, entityId, timelineId, "endAttribute") } /> */} </ResizableAndDraggable> ); })} </div> </div> ) })} </div> ) } /> {state.showContextMenu && <div className="context-menu-container" onClick={this.hideContextMenu} onContextMenu={this.hideContextMenu}> <div className="content-menu-overlay" /> <div className="context-menu" style={{ top: state.menuPosition.y, left: state.menuPosition.x, }}> <div className="menu-item-wrapper"> <div className="menu-item" onClick={this.copyEntity}> <LanguageContextMessagesConsumer messageId='TimelinePanel.Entity.ContextMenu.CopyLabel' /> </div> </div> </div> </div> } </div> </div> ); } } export default withSceneContext(TimelinePanel);<file_sep>/src/utils/errorHandling/handleErrorWithUiDefault.js export default function handleErrorWithUiDefault(err) { const stringifiedErr = JSON.stringify(err); console.error(stringifiedErr); window.alert(stringifiedErr); };<file_sep>/src/containers/aframeEditor/homePage/systemPanel.js /* System Panel File | Edit | XXX | YYY x */ import React, {Component} from 'react'; import {Link} from 'react-router-dom'; import routes from 'globals/routes'; import ipcHelper from 'utils/ipc/ipcHelper'; import isNonEmptyArray from 'utils/variableType/isNonEmptyArray'; import appIcon from 'app_icon.png'; import './systemPanel.css'; // import consts from 'globals/consts'; const appName = require('globals/consts').default.appName; const Events = require('vendor/Events.js'); class SystemPanel extends Component { constructor(props) { super(props); this.state = { menuOpen: false, hoverItem: null, snapshot: [] }; } componentDidMount() { } componentWillUnmount() { } render() { return ( <div id="system-panel"> <div id="app-icon"> <img src={appIcon} /> </div> {/* <div id="app-name">School VR</div> */} <div id="app-buttons"> <div className="menu-group"> <button onMouseEnter={()=> { this.setState({ 'hoverItem': 'file' }); }} onClick={() => this.setState((currentState) => { return {menuOpen: !currentState.menuOpen} })} > File </button> {this.state.hoverItem === 'file' && this.state.menuOpen && <div className="menu-list list-file"> <div className="menu-item" onClick={() => { Events.emit('newProject'); this.setState({ menuOpen: false }); }}>New Project</div> <div className="seperator"></div> <div className="menu-item" onClick={() => { Events.emit('saveProject'); this.setState({ menuOpen: false }); }}>Save</div> <div className="menu-item" onClick={() => { navigator.clipboard.readText().then(text => { Events.emit('loadProject', text); this.setState({ menuOpen: false }); }) }}>Load</div> <div className="seperator"></div> <div className="menu-item" onClick={() => { alert('Bye'); }}>Exit</div> </div> } </div> <div className="menu-group"> <button onMouseEnter={()=> { this.setState({ 'hoverItem': 'edit' }) }} onClick={() => this.setState((currentState) => { return {menuOpen: !currentState.menuOpen} })} > Edit </button> {this.state.hoverItem === 'edit' && this.state.menuOpen && <div className="menu-list list-edit"> <div className="menu-item" onClick={() => { alert('developing') }}>Undo</div> <div className="menu-item" onClick={() => { alert('developing') }}>Redo</div> </div> } </div> <div className="menu-group"> <button onMouseEnter={()=> { this.setState({ 'hoverItem': 'debug' }) }} onClick={() => this.setState((currentState) => { return {menuOpen: !currentState.menuOpen} })} > Debug </button> {this.state.hoverItem === 'debug' && this.state.menuOpen && <div className="menu-list list-debug"> <div className="menu-item" onClick={() => { Events.emit('toggleDebug'); this.setState({ menuOpen: false }); }}>Toggle Debug</div> </div> } </div> </div> <div id="app-name" title={this.props.projectName + ' - ' + appName}> <div className="project-name" onClick={()=>{ let newProjectName = prompt('Enter New Project Name'); if (newProjectName) { Events.emit('setProjectName', newProjectName, 'testing'); } }}>{this.props.projectName}</div> <div className="hyphen">-</div> <div className="app-name">{appName}</div> </div> <div id="system-buttons"> <button id="btn-min-app"></button> <button id="btn-max-app" onClick={()=>{ Events.emit('toggleMaximize'); }}></button> <button id="btn-close-app"></button> </div> </div> ); } } export default SystemPanel;<file_sep>/src/pages/aframeEditor/editorPage.js import React, { Component } from 'react'; // import SystemPanel from 'containers/aframeEditor/homePage/systemPanel'; import { withRouter, Prompt } from 'react-router-dom'; import saveAs from 'utils/fileSaver/saveAs'; import { formatDateTimeForFileName } from 'utils/dateTime/formatDateTime'; import { withSceneContext, capture360OutputResolutionTypes } from 'globals/contexts/sceneContext'; import { LanguageContextConsumer, getLocalizedMessage } from 'globals/contexts/locale/languageContext'; import config from 'globals/config'; import MenuComponent from 'components/menuComponent'; import DefaultLoading from 'components/loading/defaultLoading'; import ButtonsPanel from 'containers/aframeEditor/homePage/buttonsPanel'; import AFramePanel from 'containers/aframeEditor/homePage/aFramePanel'; import InfoPanel from 'containers/aframeEditor/homePage/infoPanel'; import SlidesPanel from 'containers/aframeEditor/homePage/slidesPanel'; import TimelinePanel from 'containers/aframeEditor/homePage/timelinePanel'; // import AssetsPanel from 'containers/aframeEditor/homePage/assetsPanel'; import Editor from 'vendor/editor.js'; // import {addEntityAutoType} from 'utils/aFrameEntities'; // import {roundTo, jsonCopy} from 'globals/helperfunctions'; // import {TweenMax, TimelineMax, Linear} from 'gsap'; // import {addEntityAutoType} from 'utils/aframeEditor/aFrameEntities'; // import {roundTo, jsonCopy} from 'utils/aframeEditor/helperfunctions'; // import {TweenMax, TimelineMax, Linear} from 'gsap'; import isNonEmptyArray from 'utils/variableType/isNonEmptyArray'; import dataUrlToBlob from 'utils/blobs/dataUrlToBlob'; import handleErrorWithUiDefault from 'utils/errorHandling/handleErrorWithUiDefault'; import ipcHelper from 'utils/ipc/ipcHelper'; import { getSearchObjectFromHistory } from 'utils/queryString/getSearchObject'; import getProjectFilePathFromSearchObject from 'utils/queryString/getProjectFilePathFromSearchObject'; import './editorPage.css'; import fileHelper from 'utils/fileHelper/fileHelper'; import PreviewPanel from 'containers/aframeEditor/homePage/previewPanel'; const Events = require('vendor/Events.js'); const uuid = require('uuid/v1'); // const jsonSchemaValidator = require('jsonschema').Validator; // const validator = new jsonSchemaValidator(); // const schema = require('schema/aframe_schema_20181108.json'); function EditorPageMenu(props) { const { sceneContext, handleNewProjectButtonClick, handleOpenProjectButtonClick, handleSaveProjectButtonClick, handleSaveAsProjectButtonClick, handleUndoButtonClick, handleRedoButtonClick, handleCaptureNormalImageClick, handleCapture360_2kImageClick, handleCapture360_4kImageClick, handleCapture360_2kVideoClick, handleCapture360_4kVideoClick } = props; const isEditorOpened = sceneContext.getIsEditorOpened(); const menuButtons = [ { labelId: 'Menu.FileLabel', // onClick: _=> { console.log('file') }, children: [ { labelId: 'Menu.File.HomeLabel', disabled: false, methodNameToInvoke: 'goToHomePage' }, { labelId: '-' }, { labelId: 'Menu.File.NewLabel', disabled: false, onClick: handleNewProjectButtonClick }, { labelId: '-' }, { labelId: 'Menu.File.OpenLabel', disabled: false, onClick: handleOpenProjectButtonClick }, { labelId: 'Menu.File.SaveLabel', disabled: false, onClick: handleSaveProjectButtonClick }, { labelId: 'Menu.File.SaveAsLabel', disabled: false, onClick: handleSaveAsProjectButtonClick }, { labelId: '-' }, { labelId: 'Menu.File.ExitLabel', disabled: false, methodNameToInvoke: 'closeApp' } ] } ]; if (isEditorOpened) { menuButtons.push({ labelId: 'Menu.EditLabel', children: [ { labelId: 'Menu.Edit.UndoLabel', disabled: !sceneContext.getUndoQueueLength(), onClick: handleUndoButtonClick }, { labelId: 'Menu.Edit.RedoLabel', disabled: !sceneContext.getRedoQueueLength(), onClick: handleRedoButtonClick } ] }); } if (isEditorOpened) { menuButtons.push({ labelId: 'Menu.CaptureImageLabel', children: [ { labelId: 'Menu.CaptureImage.Normal', onClick: handleCaptureNormalImageClick }, { labelId: 'Menu.CaptureImage.360_2k', onClick: handleCapture360_2kImageClick }, { labelId: 'Menu.CaptureImage.360_4k', onClick: handleCapture360_4kImageClick } ] }); menuButtons.push({ labelId: 'Menu.CaptureVideoLabel', children: [ { labelId: 'Menu.CaptureVideo.360_2k', onClick: handleCapture360_2kVideoClick } // { // labelId: "Menu.CaptureVideo.360_4k", // onClick: handleCapture360_4kVideoClick // } ] }); } return ( <MenuComponent // projectName="Untitled_1" menuButtons={menuButtons} /> ); } class EditorPage extends Component { constructor(props) { super(props); // variables this.inited = false; // state this.state = { entitiesList: [], loadedProjectFilePath: '', isLoading: false }; // bind methods [ 'setLoading', 'unsetLoading', 'confirmLeaveProject', 'onEditorLoad', 'newProject', 'loadProject', 'saveProject', 'saveProjectAs', 'capture360Image', 'capture360Video', 'handleNewProjectButtonClick', 'handleOpenProjectButtonClick', 'handleSaveProjectButtonClick', 'handleSaveAsProjectButtonClick', 'handleUndoButtonClick', 'handleRedoButtonClick', 'handleCaptureNormalImageClick', 'handleCapture360_2kImageClick', 'handleCapture360_4kImageClick', 'handleCapture360_2kVideoClick', 'handleCapture360_4kVideoClick' ].forEach(methodName => { this[methodName] = this[methodName].bind(this); }); } /* react lifecycles */ componentDidMount() { Events.on('editor-load', this.onEditorLoad); this.editor = new Editor(); this.inited = true; // // window.onbeforeunload = function() { // return 'hello?'; // }; } componentWillUnmount() { const sceneContext = this.props.sceneContext; sceneContext.setProjectName(''); Events.removeListener('editor-load', this.onEditorLoad); this.editor = null; } /* end of react lifecycles */ /* methods */ setLoading() { this.setState({ isLoading: true }); } unsetLoading() { this.setState({ isLoading: false }); } confirmLeaveProject() { const { sceneContext } = this.props; return ( sceneContext.isProjectSaved || window.confirm(getLocalizedMessage('Prompt.UnsavedWorkMessage')) ); } onEditorLoad(editor) { // load project const searchObj = getSearchObjectFromHistory(this.props.history); const projectFilePathToLoad = getProjectFilePathFromSearchObject(searchObj); console.log('project path to load:', projectFilePathToLoad); if (!projectFilePathToLoad) { this.newProject(); } else { this.loadProject(projectFilePathToLoad); } } newProject() { // test open file with user defined extension // const fileDialog = document.createElement('input'); // fileDialog.type = 'file'; // fileDialog.multiple = true; // fileDialog.accept = ['image/x-png','image/gif']; // fileDialog.click(); const { sceneContext } = this.props; this.setState({ loadedProjectFilePath: '' }); sceneContext.newProject(); } loadProject(projectFilePath) { ipcHelper.loadProjectByProjectFilePath(projectFilePath, (err, data) => { if (err) { handleErrorWithUiDefault(err); return; } this.setState({ loadedProjectFilePath: projectFilePath }); const projectJsonData = data.projectJson; //console.log(projectJsonData); this.props.sceneContext.loadProject(projectJsonData); }); } saveProject(projectFilePath) { if (!projectFilePath) { return; } const sceneContext = this.props.sceneContext; let { entitiesList, assetsList } = sceneContext.saveProject(); //const projectName = fileHelper.getFileNameWithoutExtension(projectFilePath); //console.log(projectName, entitiesList, assetsList); // TODO: //entitiesList.projectName = projectName; ipcHelper.saveProject(projectFilePath, entitiesList, assetsList, err => { if (err) { handleErrorWithUiDefault(err); return; } const { loadedProjectFilePath } = this.state; if (loadedProjectFilePath !== projectFilePath) { // save as case // TODO: is the following good enough? /** * !!!Important!!!: * we run setState({loadedProjectFilePath}) and sceneContext.setProjectName() * instead of loadProject() because loadProject takes time * * also using loadProject() would produce errors in sceneContext's addAsset() method, * which would not update assetsList items (src, etc.) if asset has same id */ //this.loadProject(projectFilePath); this.setState({ loadedProjectFilePath: projectFilePath }); const projectName = fileHelper.getFileNameWithoutExtension( projectFilePath ); sceneContext.setProjectName(projectName); } const projectName = fileHelper.getFileNameWithoutExtension( projectFilePath ); alert( `${getLocalizedMessage('Alert.ProjectSavedMessage')}\n${projectName}` ); }); } saveProjectAs() { ipcHelper.saveSchoolVrFileDialog((err, data) => { if (err) { handleErrorWithUiDefault(err); return; } const filePath = data.filePath; this.saveProject(filePath); }); } capture360Image(resolutionType) { this.setLoading(); const imgBase64Str = this.props.sceneContext.captureEquirectangularImage( resolutionType ); ipcHelper.saveRaw360Capture(imgBase64Str, (err, data) => { this.unsetLoading(); if (err) { handleErrorWithUiDefault(err); return; } if (data && data.filePath) { alert( `${getLocalizedMessage('Alert.CaptureSavedMessage')}\n${ data.filePath }` ); } }); } capture360Video(resolutionType, fps) { const vidoeUuid = uuid(); this.props.sceneContext.captureEquirectangularVideo( resolutionType, fps, (currentFrame, totalFrame, imgBase64Str) => { ipcHelper.saveRaw360CaptureForVideo( vidoeUuid, fps, currentFrame, totalFrame, imgBase64Str, (err, data) => { if (err) { handleErrorWithUiDefault(err); return; } if (data && data.filePath) { // last frame if (currentFrame === totalFrame) { alert( `${getLocalizedMessage('Alert.CaptureSavedMessage')}\n${ data.filePath }` ); } } } ); }, config.capture360VideoRenderFrameIntervalInMillis ); } /* end of methods */ /* event handlers */ handleNewProjectButtonClick(event) { if (this.confirmLeaveProject()) { this.newProject(); } } handleOpenProjectButtonClick(event) { if (this.confirmLeaveProject()) { ipcHelper.openSchoolVrFileDialog((err, data) => { if (err) { handleErrorWithUiDefault(err); return; } const filePaths = data.filePaths; if (!isNonEmptyArray(filePaths)) { return; } this.loadProject(filePaths[0]); }); } } handleSaveProjectButtonClick(event) { ipcHelper.isCurrentLoadedProject( this.state.loadedProjectFilePath, (err, data) => { if (err) { handleErrorWithUiDefault(err); return; } const isCurrentLoadedProject = data.isCurrentLoadedProject; if (isCurrentLoadedProject) { this.saveProject(this.state.loadedProjectFilePath); } else { this.saveProjectAs(); } } ); } handleSaveAsProjectButtonClick(event) { this.saveProjectAs(); } handleUndoButtonClick(event) { this.props.sceneContext.undo(); } handleRedoButtonClick(event) { this.props.sceneContext.redo(); } handleCaptureNormalImageClick(event) { const snapshotDataUrl = this.props.sceneContext.takeSnapshot(); const snapshotBlob = dataUrlToBlob(snapshotDataUrl); saveAs( snapshotBlob, `snapShot_${formatDateTimeForFileName(Date.now())}${ config.captured360ImageExtension }` ); } handleCapture360_2kImageClick(event) { this.capture360Image(capture360OutputResolutionTypes['2k']); } handleCapture360_4kImageClick(event) { this.capture360Image(capture360OutputResolutionTypes['4k']); } handleCapture360_2kVideoClick(event) { this.capture360Video( capture360OutputResolutionTypes['2k'], config.captured360VideoFps ); } handleCapture360_4kVideoClick(event) { this.capture360Video( capture360OutputResolutionTypes['4k'], config.captured360VideoFps ); } /* end of event handlers */ render() { const { sceneContext } = this.props; const { loadedProjectFilePath, isLoading } = this.state; //console.log('sceneContext.isProjectSaved:', sceneContext.isProjectSaved); return ( // <SceneContextProvider> <div id='editor' className={ sceneContext.editor && sceneContext.editor.opened ? 'editing' : 'viewing' } > <div className={`${isLoading ? 'show' : 'hide'} editor-loading-container`} > <DefaultLoading /> </div> <div className={`${isLoading ? 'hide' : 'show'}`}> <LanguageContextConsumer render={({ messages }) => ( <Prompt when={!sceneContext.isProjectSaved} message={messages['Prompt.UnsavedWorkMessage']} /> )} /> {/* <SystemPanel projectName={this.projectName} /> */} <EditorPageMenu sceneContext={sceneContext} handleNewProjectButtonClick={this.handleNewProjectButtonClick} handleOpenProjectButtonClick={this.handleOpenProjectButtonClick} handleSaveProjectButtonClick={this.handleSaveProjectButtonClick} handleSaveAsProjectButtonClick={this.handleSaveAsProjectButtonClick} handleUndoButtonClick={this.handleUndoButtonClick} handleRedoButtonClick={this.handleRedoButtonClick} handleCaptureNormalImageClick={this.handleCaptureNormalImageClick} handleCapture360_2kImageClick={this.handleCapture360_2kImageClick} handleCapture360_4kImageClick={this.handleCapture360_4kImageClick} handleCapture360_2kVideoClick={this.handleCapture360_2kVideoClick} handleCapture360_4kVideoClick={this.handleCapture360_4kVideoClick} /> <ButtonsPanel currentLoadedProjectPath={loadedProjectFilePath} /> <AFramePanel user-mode='editor' /> <SlidesPanel isEditing={sceneContext.editor && sceneContext.editor.opened} /> <TimelinePanel /> <InfoPanel /> <PreviewPanel /> </div> </div> // </SceneContextProvider> ); } } export default withSceneContext(withRouter(EditorPage)); <file_sep>/src/globals/customizedAppData/customizedAppData.js import ipcHelper from 'utils/ipc/ipcHelper'; import promisify from 'utils/js/myPromisify'; const getCustomizedAppDataAsync = callBack => { ipcHelper.getCustomizedAppData((err, appDataObj) => { if (err) { // silence error callBack(null, null); return; } callBack(null, appDataObj || {}); }); }; const getCustomizedAppDataPromise = promisify(getCustomizedAppDataAsync); const setCustomizedAppDataAsync = (dataObj, callBack) => { ipcHelper.setCustomizedAppData(dataObj, (err) => { if (err) { callBack(err); return; } callBack(null); }); }; const setCustomizedAppDataPromise = promisify(setCustomizedAppDataAsync); const setCustomizedAppDataLangCodeAsync = (langCode, callBack) => { setCustomizedAppDataAsync({ langCode }, callBack); }; const setCustomizedAppDataLangCodePromise = promisify(setCustomizedAppDataLangCodeAsync); export { getCustomizedAppDataAsync, getCustomizedAppDataPromise, setCustomizedAppDataAsync, setCustomizedAppDataPromise, setCustomizedAppDataLangCodeAsync, setCustomizedAppDataLangCodePromise }<file_sep>/src/utils/videos/injectMetaData.js /** * https://www.npmjs.com/package/ts-ebml * https://github.com/legokichi/ts-ebml */ import {Decoder, tools, Reader} from 'ts-ebml'; function readAsArrayBufferPromise(blob) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsArrayBuffer(blob); reader.onloadend = () => { resolve(reader.result); }; reader.onerror = (ev) => { reject(ev.error); }; }); } // https://github.com/collab-project/videojs-record/issues/317 async function makeVideoSeekableByInjectingMetadataPromise(blob) { const decoder = new Decoder(); const reader = new Reader(); reader.logging = false; reader.drop_default_duration = false; // load webm blob and inject metadata const buffer = await readAsArrayBufferPromise(blob); const elms = decoder.decode(buffer); elms.forEach((elm) => { reader.read(elm); }); reader.stop(); const refinedMetadataBuf = tools.makeMetadataSeekable( reader.metadatas, reader.duration, reader.cues); console.log('makeVideoSeekableByInjectingMetadataPromise reader.metadatas:', reader.metadatas); const body = buffer.slice(reader.metadataSize); const resultedBlob = new Blob([refinedMetadataBuf, body], {type: blob.type}); // the blob object contains the recorded data that // can be downloaded by the user, stored on server etc. console.log('makeVideoSeekableByInjectingMetadataPromise resultedBlob:', resultedBlob); return resultedBlob; } export { makeVideoSeekableByInjectingMetadataPromise };<file_sep>/public/utils/js/shallowMergeObjects.js function shallowMergeObjects(obj) { if (arguments.length === 0) { return null; } if (arguments.length === 1) { return obj; } const argumentsArray = Array.prototype.slice.call(arguments); return Object.assign(...argumentsArray); } module.exports = shallowMergeObjects;<file_sep>/src/containers/aframeEditor/homePage/infoPanel/transformMode.js import React, {Component} from 'react'; //import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; import tranformModeId from 'globals/constants/transformModeId'; import {LanguageContextConsumer} from 'globals/contexts/locale/languageContext'; import {withSceneContext} from 'globals/contexts/sceneContext'; import isNonEmptyArray from 'utils/variableType/isNonEmptyArray'; import './transformMode.css'; const Events = require('vendor/Events.js'); class TransformMode extends Component { constructor(props) { super(props); const { //modes, onUpdate } = props; // state this.state = { editorMode: null, // modes[0] } this.callback = onUpdate || function() {}; // method binding [ 'handleResetCurrentEntityRotationClick', 'updateEntity', 'changeTransformModeFuncFactory', ].forEach(methodName => { this[methodName] = this[methodName].bind(this); }); // constants this.transformMode = { [tranformModeId.translate]: { id: tranformModeId.translate, lableMsgId: 'EditThingPanel.TransformModes.TranslateLabel', tooltipMsgId: 'EditThingPanel.TransformModes.TranslateTooltip', changeTranformFunc: this.changeTransformModeFuncFactory(tranformModeId.translate), iconElement: ( <svg viewBox="0 0 34.09 34.09" xmlSpace="preserve" > <g> <polyline className="st145" points="19.8,3.94 17,1 14.39,4.12 "/> <polyline className="st145" points="14.29,30.09 17.09,33.03 19.7,29.91 "/> <line className="st145" x1="17.05" y1="1.09" x2="17.05" y2="33.09"/> <polyline className="st145" points="30.15,19.8 33.09,17 29.97,14.39 "/> <polyline className="st145" points="4,14.29 1.06,17.09 4.18,19.7 "/> <line className="st145" x1="33" y1="17.05" x2="1" y2="17.05"/> </g> </svg> ), }, [tranformModeId.rotate]: { id: tranformModeId.rotate, lableMsgId: 'EditThingPanel.TransformModes.RotateLabel', tooltipMsgId: 'EditThingPanel.TransformModes.RotateTooltip', changeTranformFunc: this.changeTransformModeFuncFactory(tranformModeId.rotate), iconElement: ( <svg viewBox="0 0 31.63 31.06" xmlSpace="preserve" > <g> <path className="st144" d="M11.77,1.67c5.08-1.59,10.85-0.32,14.8,3.78c5.55,5.77,5.38,14.95-0.39,20.5"/> <path className="st144" d="M19.85,29.4c-4.95,1.55-10.58,0.39-14.53-3.52c-5.7-5.63-5.76-14.81-0.13-20.51"/> <polyline className="st145" points="5.64,8.5 6.39,4.5 2.34,4.2 "/> <polyline className="st145" points="25.86,22.19 25.18,26.19 29.24,26.42 "/> </g> </svg> ), }, [tranformModeId.scale]: { id: tranformModeId.scale, lableMsgId: 'EditThingPanel.TransformModes.ScaleLabel', tooltipMsgId: 'EditThingPanel.TransformModes.ScaleTooltip', changeTranformFunc: this.changeTransformModeFuncFactory(tranformModeId.scale), iconElement: ( <svg viewBox="0 0 24.73 24.73" xmlSpace="preserve"> <g> <polyline className="st145" points="23.57,5.06 23.66,1 19.61,1.36 "/> <polyline className="st145" points="1.17,19.65 1.08,23.71 5.13,23.36 "/> <line className="st145" x1="23.63" y1="1.1" x2="1" y2="23.73"/> <polyline className="st145" points="19.66,23.6 23.73,23.69 23.37,19.64 "/> <polyline className="st145" points="5.07,1.21 1.01,1.11 1.37,5.16 "/> <line className="st145" x1="23.63" y1="23.66" x2="1" y2="1.03"/> </g> </svg> ), } }; } /* react lifecycles */ componentDidMount() { //const { modes } = this.props; // Events.emit('transformmodechanged', modes[0]); Events.on('objectchanged', this.updateEntity) // this.changeTransformMode(modes[0]); } componentWillUnmount() { Events.removeListener('objectchanged', this.updateEntity); } /* end of react lifecycles */ /* event handlers */ handleResetCurrentEntityRotationClick() { const { sceneContext, isInTimeline } = this.props; const isUpdateUndoQueue = true; sceneContext.resetCurrentEntityRotation(isUpdateUndoQueue, isInTimeline); } /* end of event handlers */ /* methods */ updateEntity(object) { this.callback( object.el.getAttribute('position'), object.el.getAttribute('rotation'), object.el.getAttribute('scale') ); } changeTransformModeFuncFactory(newMode) { const setStateCallBack = _ => { if (newMode) { Events.emit('transformmodechanged', newMode); Events.emit('enablecontrols'); } else { Events.emit('disablecontrols'); } }; return _ => { this.setState({ editorMode: newMode }, setStateCallBack); }; } /* end of methods */ render() { const { modes } = this.props; if (!isNonEmptyArray(modes)) { return null; } const { editorMode } = this.state; return ( <LanguageContextConsumer render={ ({ messages }) => ( <> { modes.map((mode) => { const isModeSelected = editorMode === mode; const modeData = this.transformMode[mode]; return ( <button key={mode} className={isModeSelected ? 'selected' : ''} onClick={modeData.changeTranformFunc} title={messages[modeData.tooltipMsgId]} > {modeData.iconElement} <div>{messages[modeData.lableMsgId]}</div> </button> ); }) } { modes.includes(tranformModeId.rotate) && <button className='btn-reset-rotation' onClick={this.handleResetCurrentEntityRotationClick} title={messages['EditThingPanel.TransformModes.RotateResetTooltip']} > {/* <FontAwesomeIcon icon="undo" /> */} <div>{messages['EditThingPanel.TransformModes.RotateResetLabel']}</div> </button> } </> ) } /> ) } } export default withSceneContext(TransformMode);<file_sep>/public/utils/fileSystem/myPath.js const path = require('path'); const mimeTypes = require('mime-types'); /* path api */ const sep = path.sep; const getFileExtensionWithLeadingDot = filePath => { return path.extname(filePath); }; const getFileExtensionWithoutLeadingDot = filePath => { return path.extname(filePath).substr(1); }; const getFileNameWithExtension = filePath => { return path.basename(filePath); }; const getFileNameWithoutExtension = filePath => { // https://stackoverflow.com/questions/4250364/how-to-trim-a-file-extension-from-a-string-in-javascript return path.basename(filePath).split('.').slice(0, -1).join('.'); }; const getFileNameWithDirectoryAndExtension = filePath => { return join(dirname(filePath), getFileNameWithExtension(filePath)); }; const getFileNameWithDirectoryWithoutExtension = filePath => { return join(dirname(filePath), getFileNameWithoutExtension(filePath)); }; const join = (...paths) => { return path.join(...paths); }; const resolve = (...paths) => { return path.resolve(...paths); }; const normalize = filePath => { return path.normalize(filePath); }; const dirname = filePath => { return path.dirname(filePath); }; /* end of path api */ /* mime-types api */ const getMimeType = filePath => { const ext = getFileExtensionWithoutLeadingDot(filePath); const mime = mimeTypes.lookup(ext); return mime; }; /* end of mime-types api */ module.exports = { path, // path api sep, getFileExtensionWithLeadingDot, getFileExtensionWithoutLeadingDot, getFileNameWithExtension, getFileNameWithoutExtension, getFileNameWithDirectoryAndExtension, getFileNameWithDirectoryWithoutExtension, join, resolve, normalize, dirname, // mime-types api getMimeType }; <file_sep>/src/pages/TestSaveLoad.js // https://ourcodeworld.com/articles/read/106/how-to-choose-read-save-delete-or-create-a-file-with-electron-framework import React, { Component } from 'react'; import handleErrorWithUiDefault from 'utils/errorHandling/handleErrorWithUiDefault'; import ipcHelper from 'utils/ipc/ipcHelper'; import isNonEmptyArray from 'utils/variableType/isNonEmptyArray'; class TestSaveLoad extends Component { constructor(props) { super(props); this.actualFileTxt = React.createRef(); this.contentEditorTxt = React.createRef(); this.handleSelectFileClick = this.handleSelectFileClick.bind(this); this.handleSaveChangesClick = this.handleSaveChangesClick.bind(this); this.handleDeleteFileClick = this.handleDeleteFileClick.bind(this); this.handleCreateNewFileClick = this.handleCreateNewFileClick.bind(this); } /* event handlers */ handleSelectFileClick() { ipcHelper.showOpenDialog(null, (err, data) => { if (err) { handleErrorWithUiDefault(err); return; } const filePaths = data.filePaths; if (!isNonEmptyArray(filePaths)) { console.log("No file selected"); } else { this.actualFileTxt.current.value = filePaths[0]; const self = this; const callBack = function(err, data) { if (err) { handleErrorWithUiDefault(err); return; } self.contentEditorTxt.current.value = data.content; }; ipcHelper.readFile(filePaths[0], callBack); } }); } handleSaveChangesClick() { const actualFilePath = this.actualFileTxt.current.value; if (actualFilePath) { const callBack = (err) => { if (err) { handleErrorWithUiDefault(err); return; } alert("The file has been succesfully saved"); } ipcHelper.writeFile(actualFilePath, this.contentEditorTxt.current.value, callBack); } else { alert("Please select a file first"); } } handleDeleteFileClick() { const actualFilePath = this.actualFileTxt.current.value; if (actualFilePath) { const callBack = (err) => { if (err) { handleErrorWithUiDefault(err); return; } }; ipcHelper.deleteFile(actualFilePath, callBack); this.actualFileTxt.current.value = ""; this.contentEditorTxt.current.value = ""; } else { alert("Please select a file first"); } } handleCreateNewFileClick() { const content = this.contentEditorTxt.current.value; ipcHelper.showSaveDialog((filePath) => { if (filePath === undefined) { console.log("You didn't save the file"); return; } console.log(filePath); const callBack = (err) => { if (err) { handleErrorWithUiDefault(err); } alert("The file has been succesfully saved"); }; ipcHelper.writeFile(filePath, content, callBack); }); } /* end of event handlers */ render() { return ( <div> <div> <div style={{textAlign: 'center'}}> <input type="text" placeholder="Please select a file" id="actual-file" disabled="disabled" ref={this.actualFileTxt} /> <input type="button" value="Choose a file" id="select-file" onClick={this.handleSelectFileClick} /> </div> <br /><br /> <textarea id="content-editor" rows="5" ref={this.contentEditorTxt} /> <br /><br /> <input type="button" id="save-changes" value="Save changes" onClick={this.handleSaveChangesClick} /> <input type="button" id="delete-file" value="Delete file" onClick={this.handleDeleteFileClick} /> </div> <hr /> <div style={{textAlign: 'center'}}> <p> The file content will be the same as the editor. </p> <input type="button" value="Save new file" id="create-new-file" onClick={this.handleCreateNewFileClick} /> </div> </div> ); } } export default TestSaveLoad; <file_sep>/src/utils/queryString/getProjectFilePathFromSearchObject.js export default function getProjectFilePathFromSearchObject(searchObj) { return searchObj.projectFilePath ? decodeURIComponent(searchObj.projectFilePath) : null; };<file_sep>/public/utils/fileSystem/CustomedFileStats.js const myPath = require('./myPath'); class CustomedFileStats { /** * * @param {fs.Stats} fsStats * @param {String} filePath */ constructor(fsStats, filePath) { for (let key in fsStats) { this[key] = fsStats[key]; } this.path = filePath; } get fileNameWithExtension() { return myPath.getFileNameWithExtension(this.path); } get fileNameWithoutExtension() { return myPath.getFileNameWithoutExtension(this.path); } get fileExtensionWithLeadingDot() { return myPath.getFileExtensionWithLeadingDot(this.path); } get fileExtensionWithoutLeadingDot() { return getFileExtensionWithLeadingDot.getFileExtensionWithoutLeadingDot(this.path); } } module.exports = CustomedFileStats;<file_sep>/public/utils/fileSystem/mkdir-recursive.js 'use strict'; /** * @file mkdir-recursive main * @module mkdir-recursive * @version 0.3.0 * @author hex7c0 <<EMAIL>> * @copyright hex7c0 2015 * @license GPLv3 */ /* * initialize module */ // var fs = require('fs'); // var path = require('path'); var fs; var path; /* * exports */ /** * make main. Check README.md * * @exports mkdir * @function mkdir * @param {String} root - pathname * @param {Number} mode - directories mode, see Node documentation * @param {Function} callback - next callback */ function mkdir(myFs, myPath, root, mode, callback) { fs = myFs; path = myPath; if (typeof mode === 'function') { var callback = mode; var mode = null; } if (typeof root !== 'string') { throw new Error('missing root'); } else if (typeof callback !== 'function') { throw new Error('missing callback'); } var chunks = root.split(path.sep); // split in chunks var chunk; if (path.isAbsolute(root) === true) { // build from absolute path chunk = chunks.shift(); // remove "/" or C:/ if (!chunk) { // add "/" chunk = path.sep; } } else { chunk = path.resolve(); // build with relative path } return mkdirRecursive(chunk, chunks, mode, callback); } module.exports.mkdir = mkdir; /** * makeSync main. Check README.md * * @exports mkdirSync * @function mkdirSync * @param {String} root - pathname * @param {Number} mode - directories mode, see Node documentation * @return [{Object}] */ function mkdirSync(myFs, myPath, root, mode) { fs = myFs; path = myPath; if (typeof root !== 'string') { throw new Error('missing root'); } var chunks = root.split(path.sep); // split in chunks var chunk; if (path.isAbsolute(root) === true) { // build from absolute path chunk = chunks.shift(); // remove "/" or C:/ if (!chunk) { // add "/" chunk = path.sep; } } else { chunk = path.resolve(); // build with relative path } return mkdirSyncRecursive(chunk, chunks, mode); } module.exports.mkdirSync = mkdirSync; /** * remove main. Check README.md * * @exports rmdir * @function rmdir * @param {String} root - pathname * @param {Function} callback - next callback */ function rmdir(root, callback) { if (typeof root !== 'string') { throw new Error('missing root'); } else if (typeof callback !== 'function') { throw new Error('missing callback'); } var chunks = root.split(path.sep); // split in chunks var chunk = path.resolve(root); // build absolute path // remove "/" from head and tail if (chunks[0] === '') { chunks.shift(); } if (chunks[chunks.length - 1] === '') { chunks.pop(); } return rmdirRecursive(chunk, chunks, callback); } module.exports.rmdir = rmdir; /** * removeSync main. Check README.md * * @exports rmdirSync * @function rmdirSync * @param {String} root - pathname * @return [{Object}] */ function rmdirSync(root) { if (typeof root !== 'string') { throw new Error('missing root'); } var chunks = root.split(path.sep); // split in chunks var chunk = path.resolve(root); // build absolute path // remove "/" from head and tail if (chunks[0] === '') { chunks.shift(); } if (chunks[chunks.length - 1] === '') { chunks.pop(); } return rmdirSyncRecursive(chunk, chunks); } module.exports.rmdirSync = rmdirSync; /* * functions */ /** * make directory recursively * * @function mkdirRecursive * @param {String} root - absolute root where append chunks * @param {Array} chunks - directories chunks * @param {Number} mode - directories mode, see Node documentation * @param {Function} callback - next callback */ function mkdirRecursive(root, chunks, mode, callback) { var chunk = chunks.shift(); if (!chunk) { return callback(null); } var root = path.join(root, chunk); /** * Important (added by Chris): * A possible race condition may happen using the following * fs.exists() check logic. * https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback * Hence, needed to check err.code === 'EEXIST' */ return fs.exists(root, function(exists) { if (exists === true) { // already done return mkdirRecursive(root, chunks, mode, callback); } return fs.mkdir(root, mode, function(err) { if (err) { // added by chris if (err.code !== 'EEXIST') { return callback(err); } } return mkdirRecursive(root, chunks, mode, callback); // let's magic }); }); } /** * make directory recursively. Sync version * * @function mkdirSyncRecursive * @param {String} root - absolute root where append chunks * @param {Array} chunks - directories chunks * @param {Number} mode - directories mode, see Node documentation * @return [{Object}] */ function mkdirSyncRecursive(root, chunks, mode) { var chunk = chunks.shift(); if (!chunk) { return; } var root = path.join(root, chunk); if (fs.existsSync(root) === true) { // already done return mkdirSyncRecursive(root, chunks, mode); } var err = fs.mkdirSync(root, mode); return err ? err : mkdirSyncRecursive(root, chunks, mode); // let's magic } /** * remove directory recursively * * @function rmdirRecursive * @param {String} root - absolute root where take chunks * @param {Array} chunks - directories chunks * @param {Function} callback - next callback */ function rmdirRecursive(root, chunks, callback) { var chunk = chunks.pop(); if (!chunk) { return callback(null); } var pathname = path.join(root, '..'); // backtrack return fs.exists(root, function(exists) { if (exists === false) { // already done return rmdirRecursive(root, chunks, callback); } return fs.rmdir(root, function(err) { if (err) { return callback(err); } return rmdirRecursive(pathname, chunks, callback); // let's magic }); }); } /** * remove directory recursively. Sync version * * @function rmdirRecursive * @param {String} root - absolute root where take chunks * @param {Array} chunks - directories chunks * @return [{Object}] */ function rmdirSyncRecursive(root, chunks) { var chunk = chunks.pop(); if (!chunk) { return; } var pathname = path.join(root, '..'); // backtrack if (fs.existsSync(root) === false) { // already done return rmdirSyncRecursive(root, chunks); } var err = fs.rmdirSync(root); return err ? err : rmdirSyncRecursive(pathname, chunks); // let's magic } <file_sep>/src/utils/aframeEditor/aPlane.js import AEntity from "./aEntity"; class APlane extends AEntity { constructor(el) { super(el); this._messageId = 'SceneObjects.Plane.DefaultName'; this._type = 'a-plane'; this._animatableAttributes = { position: ['x', 'y', 'z'], scale: ['x', 'y', 'z'], rotation: ['x', 'y', 'z'], material: [ 'color', 'opacity' ] } this._staticAttributes = [ { type: 'image', name: 'Texture', attributeKey: 'material', attributeField: 'src' }, // { // type: 'text', // name: 'Text', // attributeKey: 'text', // attributeField: 'value' // } ] this._fixedAttributes = { geometry: { primitive: 'plane' }, material: { transparent: true } } this._animatableAttributesValues = { position: { x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 }, rotation: { x: 0, y: 0, z: 0 }, material: { color: '#FFFFFF', opacity: 1 } } } } export default APlane;<file_sep>/public/utils/ffmpeg/ffmpegCommand.js // https://cliffordhall.com/2016/10/creating-video-server-node-js/ const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path; const ffmpeg = require('fluent-ffmpeg'); ffmpeg.setFfmpegPath(ffmpegPath); //const command = ffmpeg(); function FfmpegCommand() { this.command = ffmpeg(); } /* example: // Use FFMpeg to create a video. // 8 consecutive frames, held for 5 seconds each, 30fps output, no audio command .input('assets/demo1/Sinewave3-1920x1080_%03d.png') .inputFPS(1/5) .output('assets/demo1/Sinewave3-1920x1080.mp4') .outputFPS(30) .noAudio() .run(); */ FfmpegCommand.prototype.imageSequenceToVideo = function ( inputImgFileSelector, inputFps, outputVideoPath, outputFps, onEnd, onProgress, onError ) { console('ffmpegPath:', ffmpegPath); // Use FFMpeg to create a video. // 8 consecutive frames, held for 5 seconds each, 30fps output, no audio return this.command .on('end', onEnd || handleEnd) .on('progress', onProgress || handleProgress) .on('error', onError || handleError) .input(inputImgFileSelector) .inputFPS(inputFps) .output(outputVideoPath) .outputFPS(outputFps) .noAudio() .run(); }; let timemark; function handleProgress(progress) { if (progress.timemark != timemark) { timemark = progress.timemark; console.log('Time mark: ' + timemark + '...'); } } function handleError(err, stdout, stderr) { console.log('Cannot process video: ' + err.message); } function handleEnd() { console.log('Finished processing'); } module.exports = FfmpegCommand; <file_sep>/src/utils/js/setNumberValueWithDefault.js import isNumber from 'utils/number/isNumber'; export default function setNumberValueWithDefault(value, defaultValue) { return isNumber(value) ? value : defaultValue; };<file_sep>/public/utils/network/getIpAddress.js 'use strict'; // https://stackoverflow.com/questions/3653065/get-local-ip-address-in-node-js /* import libraries */ const os = require('os'); const ifaces = os.networkInterfaces(); /* end of import libraries */ /* global variables */ let ifnameAddressMap = null; /* end of global variables */ /* private functions */ const initializeIfnameAddressMap = _ => { ifnameAddressMap = {}; Object.keys(ifaces).forEach(function (ifname) { let alias = 0; ifaces[ifname].forEach(function (iface) { if ('IPv4' !== iface.family || iface.internal !== false) { // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses return; } if (alias >= 1) { // this single interface has multiple ipv4 addresses console.log(ifname + ':' + alias, iface.address); } else { // this interface has only one ipv4 adress console.log(ifname, iface.address); } ++alias; // added by chris ifnameAddressMap[ifname] = iface.address; }); }); }; /* end of private functions */ /* public functions */ const getIpByInterfaceName = (interfaceName) => { if (!ifnameAddressMap) { initializeIfnameAddressMap(); } return ifnameAddressMap[interfaceName]; }; const getAllIps = () => { if (!ifnameAddressMap) { initializeIfnameAddressMap(); } return ifnameAddressMap; }; const getIp = () => { if (!ifnameAddressMap) { initializeIfnameAddressMap(); } const ethernetIp = getIpByInterfaceName('Ethernet'); const wifiIp = getIpByInterfaceName('Wi-Fi'); return ethernetIp? ethernetIp: wifiIp; }; /* end of public functions */ /* exports */ module.exports = { getIp: getIp, getAllIps: getAllIps, getIpByInterfaceName: getIpByInterfaceName }; /* end of exports */<file_sep>/src/containers/aframeEditor/homePage/infoPanel/infoTypeText.js /* info generation of right panel */ import React, {Component} from 'react'; import {roundTo, addToAsset, rgba2hex} from 'utils/aframeEditor/helperfunctions'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome' import {Rnd as ResizableAndDraggable} from 'react-rnd'; import './infoTypeText.css'; var Events = require('vendor/Events.js'); class InfoTypeText extends Component { constructor(props) { super(props); const self = this; this.state = { editorMode: null }; this.changeObjectField = this.changeObjectField.bind(this); this.changeTransformMode = this.changeTransformMode.bind(this); this.events = { transformmodechanged: (mode) => { self.setState({ editorMode: mode }); } }; } componentDidMount() { for (let eventName in this.events) { Events.on(eventName, this.events[eventName]); } Events.emit('gettransformmode', mode => { if (this.state.editorMode !== mode) { this.changeTransformMode(mode); } }) } componentDidUpdate(prevProps, prevState) { const props = this.props; const self = this; if ( props.selectedEntity !== prevProps.selectedEntity || props.selectedSlide !== prevProps.selectedSlide || props.selectedTimeline !== prevProps.selectedTimeline || props.timelinePosition !== prevProps.timelinePosition ) { this.changeTransformMode(null); } else { Events.emit('gettransformmode', mode => { if (self.state.editorMode !== mode) { self.changeTransformMode(mode); } }) } } componentWillUnmount() { for (let eventName in this.events) { Events.removeListener(eventName, this.events[eventName]); } } changeTransformMode(transformMode) { this.setState({ editorMode: transformMode }); if (transformMode) { Events.emit('enablecontrols'); Events.emit('transformmodechanged', transformMode); } else { Events.emit('disablecontrols'); } } changeObjectField(field, value) { const tmp = {}; tmp[field] = value; Events.emit('updateSelectedEntityAttribute', tmp); } render() { const props = this.props; const data = props.timelineObj[props.timelinePosition]; const backgroundColor = rgba2hex(data.material.color); const textColor = rgba2hex(data.text.color); return ( <div className="animatable-params"> <div className="vec3D-btn-col"> <button className={(this.state.editorMode === "translate"? "selected": "")} onClick={()=>{this.changeTransformMode('translate')}} title="Translate" > <FontAwesomeIcon icon="arrows-alt" /> </button> <button className={(this.state.editorMode === "rotate"? "selected": "")} onClick={()=>{this.changeTransformMode('rotate')}} title="Rotate" > <FontAwesomeIcon icon="sync-alt" /> </button> <button className={(this.state.editorMode === "scale"? "selected": "")} onClick={()=>{this.changeTransformMode('scale')}} title="Scale" > <FontAwesomeIcon icon="expand-arrows-alt" /> </button> </div> <div className="attribute-col color-col" onClick={() => this.changeTransformMode(null)}> <label title={textColor}> <div className="field-label">Text Color:</div><div className="color-preview" style={{backgroundColor: textColor}}/> <input type="color" value={textColor} onChange={(event) => this.changeObjectField('text.color', event.target.value)} hidden/> </label> </div> <div className="attribute-col opacity-col" onClick={() => this.changeTransformMode(null)}> <div className="field-label">Text Opacity:</div> <div className="opacity-control"> <div className="hide-button" onClick={() => { // ~~! int value of the opposite opacity, 0 -> 1, 0.x -> 0 this.changeObjectField('text.opacity', ~~!data.text.opacity); }}> {data.text.opacity? <FontAwesomeIcon icon="eye-slash" />: <FontAwesomeIcon icon="eye" /> } </div> <div className="opacity-drag-control" title={data.text.opacity * 100 + '%'} ref={ref=> this.textOpacityControl = ref} onClick={(event) => { const clickPercent = (event.clientX - event.currentTarget.getBoundingClientRect().left) / event.currentTarget.getBoundingClientRect().width; this.changeObjectField('text.opacity', roundTo(clickPercent, 2)); }} > <ResizableAndDraggable className="current-opacity" disableDragging={true} bounds="parent" minWidth="0%" maxWidth="100%" default={{ x: 0, y: 0 }} size={{ height: 24, width: data.text.opacity * 100 + '%' }} dragAxis='x' enableResizing={{ top: false, right: true, bottom: false, left: false, topRight: false, bottomRight: false, bottomLeft: false, topLeft: false }} onResizeStart={(event, dir, ref, delta,pos)=>{ }} onResize={(event, dir, ref, delta, pos)=>{ }} onResizeStop={(event, dir, ref, delta, pos)=>{ console.log(delta.width, this.textOpacityControl.getBoundingClientRect().width); this.changeObjectField('text.opacity', roundTo(data.text.opacity + delta.width / this.textOpacityControl.getBoundingClientRect().width, 2)); }} > <div className="current-opacity" /> </ResizableAndDraggable> </div> <input type="text" value={data.text.opacity} ref={(ref) => this.textOpacityInput = ref} onChange={(event) => this.changeObjectField('text.opacity', event.target.value)} hidden/> </div> </div> {/* <div className="attribute-col color-col" onClick={() => this.changeTransformMode(null)}> <label title={backgroundColor}> <div className="field-label">Background Color:</div><div className="color-preview" style={{backgroundColor: backgroundColor}}/> <input type="color" value={backgroundColor} onChange={(event) => this.changeObjectField('material.color', event.target.value)} hidden/> </label> </div> <div className="attribute-col opacity-col" onClick={() => this.changeTransformMode(null)}> <div className="field-label">Background Opacity:</div> <div className="opacity-control"> <div className="hide-button" onClick={() => { // ~~! int value of the opposite opacity, 0 -> 1, 0.x -> 0 this.changeObjectField('material.opacity', ~~!data.material.opacity); }}> {data.material.opacity? <FontAwesomeIcon icon="eye-slash" />: <FontAwesomeIcon icon="eye" /> } </div> <div className="opacity-drag-control" title={data.material.opacity * 100 + '%'} ref={ref=> this.backgroundOpacityControl = ref} onClick={(event) => { const clickPercent = (event.clientX - event.currentTarget.getBoundingClientRect().left) / event.currentTarget.getBoundingClientRect().width; this.changeObjectField('material.opacity', roundTo(clickPercent, 2)); }} > <ResizableAndDraggable className="current-opacity" disableDragging={true} bounds="parent" minWidth="0%" maxWidth="100%" default={{ x: 0, y: 0 }} size={{ height: 24, width: data.material.opacity * 100 + '%' }} dragAxis='x' enableResizing={{ top: false, right: true, bottom: false, left: false, topRight: false, bottomRight: false, bottomLeft: false, topLeft: false }} onResizeStart={(event, dir, ref, delta,pos)=>{ }} onResize={(event, dir, ref, delta, pos)=>{ }} onResizeStop={(event, dir, ref, delta, pos)=>{ console.log(delta.width, this.backgroundOpacityControl.getBoundingClientRect().width); this.changeObjectField('material.opacity', roundTo(data.material.opacity + delta.width / this.backgroundOpacityControl.getBoundingClientRect().width, 2)); }} > <div className="current-opacity" /> </ResizableAndDraggable> </div> <input type="text" value={data.material.opacity} ref={(ref) => this.backgroundOpacityInput = ref} onChange={(event) => this.changeObjectField('material.opacity', event.target.value)} hidden/> </div> </div> */} </div> ); } } export default InfoTypeText;<file_sep>/public/utils/network/getMacAddress.js // https://www.npmjs.com/package/macaddress const macaddress = require('macaddress'); const {promisify} = require('util'); const getMacAddressHelper = { one: macaddress.one, all: macaddress.all, networkInterfaces: macaddress.networkInterfaces }; const getMacAddressPromiseHelper = {}; Object.keys(getMacAddressHelper).forEach((key) => { getMacAddressPromiseHelper[key] = promisify(getMacAddressHelper[key]); }); module.exports = { getMacAddressHelper, getMacAddressPromiseHelper };<file_sep>/src/utils/aframeEditor/aText.js import AEntity from "./aEntity"; // import APlane from "./aPlane"; // import fontSchoolbellRegular from 'fonts/Schoolbell/SchoolbellRegular.fnt'; // import fontSchoolbellRegularImg from 'fonts/Schoolbell/SchoolbellRegular.png'; // import TypeFace from 'fonts/typeface-0.10.js'; // if (TypeFace) { // console.log(TypeFace); // const ns = require('fonts/Noto_Serif_TC/Noto_Serif_TC_Regular.json'); // TypeFace.loadFace(ns); // } // const opentype = require('opentype.js'); // const typefaceNotoSansTc = require('typeface-noto-sans-tc'); class AText extends AEntity { constructor(el) { super(el); this._messageId = 'SceneObjects.Text.DefaultName'; this._animatableAttributes = { position: ['x', 'y', 'z'], scale: ['x', 'y', 'z'], rotation: ['x', 'y', 'z'], // text: [ ttfFont: [ 'color', 'opacity', // 'fontSize' ] }; this._staticAttributes = [ { type: 'text', name: 'Text', attributeKey: 'ttfFont', attributeField: 'value' }, { type: 'number', name: 'Font Size', attributeKey: 'ttfFont', attributeField: 'fontSize' }, // { // type: 'text', // name: 'Width', // attributeKey: 'text', // attributeField: 'value' // }, // text: [ // // 'align', // // 'anchor', // // 'baseline', // 'color', // 'font', // // 'fontImage', // 'height', // 'letterSpacing', // // 'lineHeight', // 'opacity', // // 'shader', // 'side', // // 'tabSize', // // 'transparent', // 'value', // // 'whiteSpace', // 'width', // 'wrapCount', // // 'wrapPixels', // // 'zOffset' // ] ] // console.log(fontSchoolbellRegular); this._fixedAttributes = { // ...this.fixedAttributes, // text: { // align: 'center', // side: 'double', // // font: 'Noto Sans TC' // // font: fontSchoolbellRegular, // // fontImage: fontSchoolbellRegularImg // }, // 'ttf-font': '' } this._animatableAttributesValues = { position: { x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 }, rotation: { x: 0, y: 0, z: 0 }, ttfFont: { // text: { color: '#000000', opacity: 1, // fontSize: 1 } } } } export default AText;<file_sep>/src/containers/aframeEditor/homePage/infoPanel/infoTypePlane.js /* info generation of right panel */ import React, {Component} from 'react'; import {roundTo, addToAsset} from 'globals/helperfunctions'; var Events = require('vendor/Events.js'); let editor = null; Events.on('editor-load', obj => { editor = obj; }); function fetchDataFromEl(el) { let result = {}; let geo = el.getAttribute('geometry'); result['geometry'] = {width:geo.width,height:geo.height}; let position = el.getAttribute('position'); result['position'] = {x:roundTo(position.x,1),y:roundTo(position.y,1),z:roundTo(position.z,1)}; let rotation = el.getAttribute('rotation'); result['rotation'] = {x:roundTo(rotation.x,1),y:roundTo(rotation.y,1),z:roundTo(rotation.z,1)}; let scale = el.getAttribute('scale'); result['scale'] = {x:roundTo(scale.x,1),y:roundTo(scale.y,1),z:roundTo(scale.z,1)}; result['material'] = {}; let color = el.getAttribute('material').color; result['material']['color'] = color; let texture = el.getAttribute('material').src; result['texture'] = (typeof(texture) == "object"? texture.src: texture); result['textureClass'] = (result['texture']? 'texturePreview': 'texturePreview noTexture'); result['el'] = el; return result; } class InfoTypePlane extends Component { constructor(props) { super(props); this.state = { el: props.el }; this.eventListener = Array(); this.changeObjectTexture = this.changeObjectTexture.bind(this); this.changeObjectField = this.changeObjectField.bind(this); this.deleteObject = this.deleteObject.bind(this); } componentDidMount() { let self = this; // later need to add event emit when change value this.setState({ data: fetchDataFromEl(this.state.el) }); let evt = { 'refreshsidebarobject3d': function(obj) { // console.log('refreshsidebarobject3d',obj); self.setState({ data: fetchDataFromEl(self.state.el) }); } }; for (var emitter in evt) { Events.on(emitter, evt[emitter]); } // evt.forEach() = Events.on('refreshsidebarobject3d', ) this.eventListener = evt; } componentWillReceiveProps(newProps) { let self = this; // later need to add event emit when change value this.setState({ el: newProps.el }); this.setState({ data: fetchDataFromEl(newProps.el) }); } componentWillUnmount() { for (var emitter in this.eventListener) { Events.removeListener(emitter,this.eventListener[emitter]); } } deleteObject() { editor.deselect(); this.state.el.parentNode.removeChild(this.state.el); } changeObjectField(event) { let field = event.target.getAttribute('data-value').split('.'); let tmp = this.state.data[field[0]]; tmp[field[1]] = event.target.value; this.state.el.setAttribute(field[0], tmp); this.state.data[field[0]][field[1]] = event.target.value; this.setState({ data: this.state.data }) Events.emit('objectchanged',this.state.el.object3D); } changeObjectTexture(event) { let evt = event.target; let self = this; if (evt.files && evt.files[0]) { var reader = new FileReader(); reader.onload = function (e) { let img = new Image(); img.onload = function(){ let w = this.width; let h = this.height; if (w>h) { w = w/h; h = 1; } else { h = h/w; w = 1; } let newid = addToAsset(img); self.state.el.setAttribute('material',{ src: '#'+ newid }); self.state.data.texture = e.target.result; self.setState({ data: self.state.data }) } img.src = e.target.result; }; reader.readAsDataURL(evt.files[0]); } } render() { let data = this.state.data; if (!data) return null; return ( <div> <div> <div>Plane <span onClick={this.deleteObject} className="el-remove-btn">Delete</span></div> <div> position: <input className="textInput" value={data.position.x} data-value="position.x" onChange={this.changeObjectField} /> <input className="textInput" value={data.position.y} data-value="position.y" onChange={this.changeObjectField} /> <input className="textInput" value={data.position.z} data-value="position.z" onChange={this.changeObjectField} /> </div> <div> size: <input className="textInput" value={data.geometry.width} data-value="geometry.width" onChange={this.changeObjectField} /> <input className="textInput" value={data.geometry.height} data-value="geometry.height" onChange={this.changeObjectField} /> </div> <div> rotation: <input className="textInput" value={data.rotation.x} data-value="rotation.x" onChange={this.changeObjectField} /> <input className="textInput" value={data.rotation.y} data-value="rotation.y" onChange={this.changeObjectField} /> <input className="textInput" value={data.rotation.z} data-value="rotation.z" onChange={this.changeObjectField} /> </div> <div> scale: <input className="textInput" value={data.scale.x} data-value="scale.x" onChange={this.changeObjectField} /> <input className="textInput" value={data.scale.y} data-value="scale.y" onChange={this.changeObjectField} /> <input className="textInput" value={data.scale.z} data-value="scale.z" onChange={this.changeObjectField} /> </div> <div> texture: <span><img className={data.textureClass} src={data.texture} /></span><input onChange={this.changeObjectTexture} type="file" /> </div> <div> color: <input className="colorInput" onChange={this.changeObjectField} type="color" data-value="material.color" value={data.material.color} /> </div> </div> </div> ); } } export default InfoTypePlane;<file_sep>/src/globals/config.js import fileHelper from 'utils/fileHelper/fileHelper'; import { invokeIfIsFunction } from 'utils/variableType/isFunction'; /* language specifics */ // have to map language names to the [react-intl locale, api query param options] pairs const languages = { english: { code: 'en', locale: 'en', isUsed: true, isFontLoaded: true, fontFamily: '' }, traditionalChinese: { code: 'tc', locale: 'zh-Hant', isUsed: true, isFontLoaded: false, fontFamily: 'Noto Sans TC' }, simplifiedChinese: { code: 'zh', locale: 'zh', isUsed: false, isFontLoaded: false, fontFamily: 'Noto Sans SC' }, japanese: { code: 'ja', locale: 'ja', isUsed: false, isFontLoaded: false, fontFamily: '' } }; const languageCodeToLanguageMap = {}; Object.keys(languages).forEach(key => { languageCodeToLanguageMap[languages[key].code] = languages[key]; }); const usedLanguagesArray = []; for (let language in languages) { if (languages[language].isUsed) { usedLanguagesArray.push(languages[language]); } } function getLanguageFromLanguageCode(languageCode) { return languageCodeToLanguageMap[languageCode]; } /* end of language specifics */ const schoolVrProjectArchiveExtensionWithLeadingDot = '.ivr'; let config = { isElectronApp: Boolean(window.require), webServerStaticFilesPathPrefix: 'files', schoolVrProjectArchiveExtensionWithLeadingDot: schoolVrProjectArchiveExtensionWithLeadingDot, jsonFileExtensionWithLeadingDot: '.json', // TODO: //defaultLanguage: languages.traditionalChinese, defaultLanguage: languages.english, captured360ImageExtension: '.png', captured360VideoExtension: '.mp4', captured360VideoFps: 30, capture360VideoRenderFrameIntervalInMillis: 1000, presentationRecordingVideoExtension: '.webm', presentationRecordingVideoFps: 60 }; let appDirectory = {}; const setAppData = (appData, callBack = null) => { const { appName, homePath, appDataPath, documentsPath } = appData; // https://github.com/electron/electron/blob/master/docs/api/app.md#appgetpathname appDirectory.homeDirectory = homePath; appDirectory.appProjectsDirectory = fileHelper.join( documentsPath, `${appName}-Projects` ); appDirectory.appDataDirectory = fileHelper.join( appDataPath, `${appName}-Data` ); appDirectory.appTempDirectory = fileHelper.join( appDataPath, `${appName}-Temp` ); appDirectory.appTempProjectsDirectory = fileHelper.join( appDirectory.appTempDirectory, `${appName}-Projects` ); appDirectory.appTempAppWorkingDirectory = fileHelper.join( appDirectory.appTempDirectory, `${appName}-App-Working` ); appDirectory.appTempWebContainerDirectory = fileHelper.join( appDirectory.appTempAppWorkingDirectory, 'web' ); appDirectory.webServerFilesDirectory = fileHelper.join( appDirectory.appTempWebContainerDirectory, 'files' ); // make first letter of each word upper-case config.appName = appName .split('-') .map(str => { return str.charAt(0).toUpperCase() + str.substr(1); }) .join(' '); config.appDirectory = appDirectory; invokeIfIsFunction(callBack); }; // https://electronjs.org/docs/api/dialog const Media = { image: { typeName: 'image', directoryUnderProjectDirectory: 'Images', openFileDialogFilter: { name: 'Images', extensions: ['jpeg', 'jpg', 'png', 'gif', 'svg'] } }, gif: { typeName: 'gif', directoryUnderProjectDirectory: 'Gifs', openFileDialogFilter: { name: 'Gifs', extensions: ['gif'] } }, video: { typeName: 'video', directoryUnderProjectDirectory: 'Videos', openFileDialogFilter: { name: 'Videos', extensions: ['mp4'] } } }; /* derivatives from Media */ let mediaType = {}, projectDirectoryStructure = {}, openFileDialogFilter = {}; for (let key of Object.keys(Media)) { const MediumTypeObj = Media[key]; mediaType[key] = MediumTypeObj.typeName; projectDirectoryStructure[key] = MediumTypeObj.directoryUnderProjectDirectory; // https://electronjs.org/docs/api/dialog openFileDialogFilter[key] = MediumTypeObj.openFileDialogFilter; } openFileDialogFilter.schoolVrFile = { name: 'School VR Files', extensions: [schoolVrProjectArchiveExtensionWithLeadingDot.substr(1)] }; openFileDialogFilter.allFiles = { name: 'All Files', extensions: ['*'] }; /* end of derivatives from Media */ let paramsReadFromExternalConfig = { something: 1 }; let setParamsReadFromExternalConfig = configObj => { paramsReadFromExternalConfig = { ...paramsReadFromExternalConfig, ...configObj }; }; /* to prove that export is "pass-by-reference"*/ // let something = 1; // let changeSomething = (val) => { // something = val; // }; export default config; export { setAppData, mediaType, appDirectory, projectDirectoryStructure, openFileDialogFilter, // something, // changeSomething, paramsReadFromExternalConfig, setParamsReadFromExternalConfig, // language specifics languages, usedLanguagesArray, getLanguageFromLanguageCode }; // something = 2; <file_sep>/public/utils/saveLoadProject/ProjectFile.js const {forEach, filter} = require('p-iteration'); const {config, mediaType, appDirectory, projectDirectoryStructure} = require('../../globals/config'); const fileSystem = require('../fileSystem/fileSystem'); const myPath = require('../fileSystem/myPath'); const CustomedFileStats = require('../fileSystem/CustomedFileStats'); const isNonEmptyArray = require('../variableType/isNonEmptyArray'); const parseDataToSaveFormat = require('./parseDataToSaveFormat'); const {hashForUniqueId} = require('../crypto'); //const jsonStringifyFormatted = ('../json/jsonStringifyFormatted'); /* current loaded project (singleton) */ /* somehow static properties seem not yet supported in Node */ currentLoadedProjectFilePath = null; /* end of current loaded project (singleton) */ class ProjectFile { /** * * @param {String} projectName * @param {String} projectFilePath * @param {CustomedFileStats} customedProjectFileStats */ // just need to enter either 1 of the 3 arguments, others can be null // if 1st argument is not null, 2nd and 3rd arguments will be ignored // so on and so forth constructor(projectName, projectFilePath, customedProjectFileStats) { this.name = ""; // saved project this.savedProjectFilePath = ""; this.projectFileStats = null; // the following are set in loadProjectByFilePathAsync this.projectJson = null; this.base64ThumbnailStr = null; if (projectName) { this.name = projectName; this.savedProjectFilePath = myPath.join(appDirectory.appProjectsDirectory, this.name) + config.schoolVrProjectArchiveExtensionWithLeadingDot; } if (projectFilePath) { if (!this.name) { this.name = myPath.getFileNameWithoutExtension(projectFilePath); } if (!this.savedProjectFilePath) { this.savedProjectFilePath = projectFilePath; } } if (customedProjectFileStats) { this.customedProjectFileStats = customedProjectFileStats; if (!this.name) { this.name = customedProjectFileStats.fileNameWithoutExtension; } if (!this.savedProjectFilePath) { this.savedProjectFilePath = customedProjectFileStats.path; } if (!this.projectFileStats) { this.projectFileStats = customedProjectFileStats; } } // set derived properties this.hashedSavedProjectFilePath = `${this.name}_${hashForUniqueId(this.savedProjectFilePath)}`; // temp project directories this.tempProjectDirectoryPath = myPath.join(appDirectory.appTempProjectsDirectory, this.hashedSavedProjectFilePath); this.tempProjectImageDirectoryPath = myPath.join(this.tempProjectDirectoryPath, projectDirectoryStructure.image); this.tempProjectGifDirectoryPath = myPath.join(this.tempProjectDirectoryPath, projectDirectoryStructure.gif); this.tempProjectVideoDirectoryPath = myPath.join(this.tempProjectDirectoryPath, projectDirectoryStructure.video); this.tempProjectAllAssetsDirectoryPaths = [ this.tempProjectImageDirectoryPath, this.tempProjectGifDirectoryPath, this.tempProjectVideoDirectoryPath ]; // temp project files this.tempProjectJsonFilePath = myPath.join(this.tempProjectDirectoryPath, "project" + config.jsonFileExtensionWithLeadingDot); // web server project directories this.webServerProjectDirectoryPath = ''; // fileStats properties if (this.projectFileStats) { // https://nodejs.org/api/fs.html#fs_stats_ctime this.atime = this.projectFileStats.atime; this.atimeMs = this.projectFileStats.atimeMs; this.mtime = this.projectFileStats.mtime; this.mtimeMs = this.projectFileStats.mtimeMs; this.path = this.projectFileStats.path; } // bind methods [ 'getTempImageFilePath', 'getTempGifFilePath', 'getTempVideoFilePath', 'getTempProjectAssetAbsolutePathFromProvidedPathIfIsRelative', 'saveImageToTempAsync', 'saveGifToTempAsync', 'saveVideoToTempAsync', 'convertAssetSrcToProperAbsolutePath', 'getAllExistingAssetFileAbsolutePathsInTempAsync', 'createAssetTempDirectoriesAsync', 'deleteAssetTempDirectoriesAsync', 'deleteNonUsedAssetsFromTempAsync', 'saveAssetsToTempAsync', 'saveToLocalDetailAsync', 'saveToLocalAsync', 'loadProjectAsync', 'setProjectJson', 'readAndSetProjectJsonAsync', ].forEach(methodName => { this[methodName] = this[methodName].bind(this); }); } /* getters or setters */ /** * !!!Important!!! * Note properties of objects retrieved via getters / setters cannot be sent via IPC */ /* end of getters or setters */ /* methods */ /* getProjectPath */ // temp project files getTempImageFilePath(assetId, fileExtensionWithDot) { return myPath.join(this.tempProjectImageDirectoryPath, assetId) + fileExtensionWithDot; } getTempGifFilePath(assetId, fileExtensionWithDot) { return myPath.join(this.tempProjectGifDirectoryPath, assetId) + fileExtensionWithDot; } getTempVideoFilePath(assetId, fileExtensionWithDot) { return myPath.join(this.tempProjectVideoDirectoryPath, assetId) + fileExtensionWithDot; } getTempProjectAssetAbsolutePathFromProvidedPathIfIsRelative(assetPath) { return ProjectFile.isAssetPathRelative(assetPath) ? myPath.join(this.tempProjectDirectoryPath, assetPath) : assetPath; } // saved project static getImageFilePathRelativeToProjectDirectory(assetId, fileExtensionWithDot) { return myPath.join(projectDirectoryStructure.image, assetId) + fileExtensionWithDot; } static getGifFilePathRelativeToProjectDirectory(assetId, fileExtensionWithDot) { return myPath.join(projectDirectoryStructure.gif, assetId) + fileExtensionWithDot; } static getVideoFilePathRelativeToProjectDirectory(assetId, fileExtensionWithDot) { return myPath.join(projectDirectoryStructure.video, assetId) + fileExtensionWithDot; } static isAssetPathRelative(assetPath) { let isAssetPathRelative = false; for (let assetDirectory in projectDirectoryStructure) { if (assetPath.indexOf(projectDirectoryStructure[assetDirectory]) === 0) { isAssetPathRelative = true; break; } } return isAssetPathRelative; } /* end of getProjectPath */ /* saveFilesToTemp */ static async copyFileAsync(srcFilePath, destFilePath, isAssumeDestDirExists) { if (isAssumeDestDirExists) { await fileSystem.copyFileAssumingDestDirExistsPromise(srcFilePath, destFilePath); } else { await fileSystem.copyFileAsync(srcFilePath, destFilePath); } } async saveImageToTempAsync(srcFilePath, assetId, isAssumeDestDirExists) { const destFilePath = this.getTempImageFilePath(assetId, myPath.getFileExtensionWithLeadingDot(srcFilePath)); await ProjectFile.copyFileAsync(srcFilePath, destFilePath, isAssumeDestDirExists); return destFilePath; } async saveGifToTempAsync(srcFilePath, assetId, isAssumeDestDirExists) { const destFilePath = this.getTempGifFilePath(assetId, myPath.getFileExtensionWithLeadingDot(srcFilePath)); await ProjectFile.copyFileAsync(srcFilePath, destFilePath, isAssumeDestDirExists); return destFilePath; } async saveVideoToTempAsync(srcFilePath, assetId, isAssumeDestDirExists) { const destFilePath = this.getTempVideoFilePath(assetId, myPath.getFileExtensionWithLeadingDot(srcFilePath)); await ProjectFile.copyFileAsync(srcFilePath, destFilePath, isAssumeDestDirExists); return destFilePath; } /* end of saveFilesToTemp */ /* listProjects */ static funcFactoryForCompareFileStatsByProperty(fileStatPropSelectFunc, isOrderByDesc = false) { return (fileStat1, fileStat2) => { let valueToReturn = 0; const [fileStat1Prop, fileStat2Prop] = [fileStat1, fileStat2].map(fileStat => fileStatPropSelectFunc(fileStat)); if (fileStat1Prop < fileStat2Prop) { valueToReturn = -1; } else if (fileStat1Prop > fileStat2Prop) { valueToReturn = 1; } else { valueToReturn = 0; } return isOrderByDesc ? -1 * valueToReturn : valueToReturn; }; } // TODO: this function may need to be optimized static async listProjectsAsync(isLoadProjectJson = false) { const appProjectsDirectory = appDirectory.appProjectsDirectory; const fileCustomedStatsObjs = await fileSystem.readdirWithStatPromise(appProjectsDirectory); if (!fileCustomedStatsObjs || fileCustomedStatsObjs.length === 0) { return []; } const filteredFileStatObjs = await filter(fileCustomedStatsObjs, async (fileCustomedStatsObj) => { return fileCustomedStatsObj.fileExtensionWithLeadingDot === config.schoolVrProjectArchiveExtensionWithLeadingDot; }); //const compareFileStatsByAccessTimeAsc = funcFactoryForCompareFileStatsByProperty(fileStatObj => fileStatObj.atimeMs, false); const compareFileStatsByAccessTimeDesc = ProjectFile.funcFactoryForCompareFileStatsByProperty(fileStatObj => fileStatObj.atimeMs, true); //const compareFileStatsByModifiedTimeDesc = funcFactoryForCompareFileStatsByProperty(fileStatObj => fileStatObj.mtimeMs, true); const sortedFileStatObjs = filteredFileStatObjs.sort(compareFileStatsByAccessTimeDesc); const sortedProjectFileObjs = sortedFileStatObjs.map(fileStatObj => new ProjectFile(null, null, fileStatObj)); // call loadProjectAsync() so that this.projectJson is set. if (isLoadProjectJson) { await forEach(sortedProjectFileObjs, async (projectFile) => { await projectFile.loadProjectAsync(); }); } return sortedProjectFileObjs; } /* end of listProjects */ static async deleteAllTempProjectDirectoriesAsync() { await fileSystem.myDeletePromise(appDirectory.appTempProjectsDirectory); } convertAssetSrcToProperAbsolutePath(assetSrc) { // strip file:/// from asset.src const strToStrip = "file:///"; if (assetSrc.includes(strToStrip)) { assetSrc = assetSrc.substr(strToStrip.length); } // TODO: this check of relative path is not well thought through!!! const absoluteAssetFilePath = this.getTempProjectAssetAbsolutePathFromProvidedPathIfIsRelative(assetSrc); // TODO: check if using decodeURIComponent() here is appropriate // https://stackoverflow.com/questions/747641/what-is-the-difference-between-decodeuricomponent-and-decodeuri return decodeURIComponent(absoluteAssetFilePath); }; async getAllExistingAssetFileAbsolutePathsInTempAsync() { const projectAssetTempDirectories = this.tempProjectAllAssetsDirectoryPaths; const existingAssetFileAbsolutePathsInTemp = []; await forEach(projectAssetTempDirectories, async (assetTempDir) => { const isAssetTempDirExists = await fileSystem.existsPromise(assetTempDir); if (!isAssetTempDirExists) { return; } const assetFileStatObjs = await fileSystem.readdirWithStatPromise(assetTempDir); for (let assetFileStatObj of assetFileStatObjs) { existingAssetFileAbsolutePathsInTemp.push(assetFileStatObj.path); } }); return existingAssetFileAbsolutePathsInTemp; } async createAssetTempDirectoriesAsync() { const projectAssetTempDirectories = this.tempProjectAllAssetsDirectoryPaths; await forEach(projectAssetTempDirectories, async (dir) => { await fileSystem.createDirectoryIfNotExistsPromise(dir); }); }; async deleteAssetTempDirectoriesAsync() { const projectAssetTempDirectories = this.tempProjectAllAssetsDirectoryPaths; await forEach(projectAssetTempDirectories, async (dir) => { await fileSystem.myDeletePromise(dir); }); }; /* saveProject */ // check assetsList and project asset temp directories, // delete any assets not in assetsList async deleteNonUsedAssetsFromTempAsync(assetsList) { const projectName = this.name; if (!isNonEmptyArray(assetsList)) { await this.deleteAssetTempDirectoriesAsync(projectName); return; } // check assetsList const normedAssetSrcAbsolutePaths = assetsList.map((asset) => { return myPath.normalize(this.convertAssetSrcToProperAbsolutePath(asset.src)); }); const normedAssetSrcAbsolutePathsSet = new Set(normedAssetSrcAbsolutePaths); // check project asset temp directories const existingProjectAssetFileAbsolutePaths = await this.getAllExistingAssetFileAbsolutePathsInTempAsync(); const normedExistingProjectAssetFileAbsolutePaths = existingProjectAssetFileAbsolutePaths.map((path) => { return myPath.normalize(path); }); const normedExistingProjectAssetFileAbsolutePathsSet = new Set(normedExistingProjectAssetFileAbsolutePaths); // compare assetsList and project asset temp directories // set difference // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set const existingProjectAssetFilesNotInAssetsListSet = new Set([...normedExistingProjectAssetFileAbsolutePathsSet].filter( x => !normedAssetSrcAbsolutePathsSet.has(x) )); // for debug only // console.log(assetsList); // console.log(normedExistingProjectAssetFileAbsolutePathsSet); // console.log(normedAssetSrcAbsolutePathsSet); // console.log(existingProjectAssetFilesNotInAssetsListSet); // delete these no longer used files await forEach([...existingProjectAssetFilesNotInAssetsListSet], async (filePath) => { await fileSystem.myDeletePromise(filePath); }); }; // saveAssetsToTempAsync() will do nothing and pass control to callBack // if assetsList.length === 0 async saveAssetsToTempAsync(assetsList) { if (!isNonEmptyArray(assetsList)) { return; } await this.createAssetTempDirectoriesAsync(); const isAssumeProjectAssetTempDirectoriesExists = true; await forEach(assetsList, async (asset) => { const assetSrcAbsolutePath = this.convertAssetSrcToProperAbsolutePath(asset.src); let saveFileToTempAsyncFunc = null; switch (asset.type) { case mediaType.image: saveFileToTempAsyncFunc = this.saveImageToTempAsync; break; case mediaType.gif: saveFileToTempAsyncFunc = this.saveGifToTempAsync; break; case mediaType.video: default: saveFileToTempAsyncFunc = this.saveVideoToTempAsync; break; } await saveFileToTempAsyncFunc(assetSrcAbsolutePath, asset.id, isAssumeProjectAssetTempDirectoriesExists); }); }; async saveToLocalDetailAsync(entitiesList, assetsList) { // when using constructor new ProjectFile(null, projectFilePath, null), // this.name depends on projectFilePath => correct behaviour const projectName = this.name; const jsonForSave = parseDataToSaveFormat(projectName, entitiesList, assetsList); // deal with assetsList await this.deleteNonUsedAssetsFromTempAsync(assetsList); console.log("saveProjectToLocal - deleteNonUsedAssetsFromTempAsync: Done"); await this.saveAssetsToTempAsync(assetsList); console.log(`saveProjectToLocal - saveProjectToLocalDetail: Assets saved in ${this.tempProjectDirectoryPath}`); // TODO: The following modify the objects in the input assetsList directly. Is this alright? // modify assetsList node in jsonForSave to reflect the relative paths of the project folder structure to be zipped jsonForSave.assetsList.forEach((asset) => { let getAssetFilePathRelativeToProjectDirectoryFunc = null; switch (asset.type) { case mediaType.image: getAssetFilePathRelativeToProjectDirectoryFunc = ProjectFile.getImageFilePathRelativeToProjectDirectory; break; case mediaType.gif: getAssetFilePathRelativeToProjectDirectoryFunc = ProjectFile.getGifFilePathRelativeToProjectDirectory; break; case mediaType.video: default: getAssetFilePathRelativeToProjectDirectoryFunc = ProjectFile.getVideoFilePathRelativeToProjectDirectory; break; } const assetFilePathRelativeToProjectDirectory = getAssetFilePathRelativeToProjectDirectoryFunc(asset.id, myPath.getFileExtensionWithLeadingDot(asset.src)); asset.src = assetFilePathRelativeToProjectDirectory; }); // write project json file //const jsonForSaveStr = jsonStringifyFormatted(jsonForSave); const jsonForSaveStr = JSON.stringify(jsonForSave); const tempJsonPath = this.tempProjectJsonFilePath; await fileSystem.writeFilePromise(tempJsonPath, jsonForSaveStr); console.log(`saveProjectToLocal - saveProjectToLocalDetail: JSON file saved in ${tempJsonPath}`); // zip and move temp folder to appProjectsDirectory const destProjectPackagePath = this.savedProjectFilePath; await fileSystem.createPackagePromise(this.tempProjectDirectoryPath, destProjectPackagePath); console.log(`saveProjectToLocal - saveProjectToLocalDetail: Project file saved in ${destProjectPackagePath}`); ProjectFile.setCurrentLoadedProjectFilePath(destProjectPackagePath); return { //tempProjectDirectoryPath: this.tempProjectDirectoryPath, //tempJsonPath: tempJsonPath, jsonForSave: jsonForSave, destProjectPackagePath: destProjectPackagePath }; } async saveToLocalAsync(entitiesList, assetsList) { let savedProjectObj; // save in temp folder before zip (in appTempProjectsDirectory) // check if tempProjectDir already exists, if exists, delete it if (!ProjectFile.isCurrentLoadedProject(this.savedProjectFilePath)) { //console.log("is not current loaded project"); await fileSystem.myDeletePromise(this.tempProjectDirectoryPath); savedProjectObj = await this.saveToLocalDetailAsync(entitiesList, assetsList); } else { //console.log("is current loaded project"); savedProjectObj = await this.saveToLocalDetailAsync(entitiesList, assetsList); } return savedProjectObj; } /* end of saveProject */ /* loadProject */ async loadProjectAsync() { const savedProjectFilePath = this.savedProjectFilePath; if (!savedProjectFilePath) { return null; } const tempProjectDirectoryPath = this.tempProjectDirectoryPath; ProjectFile.setCurrentLoadedProjectFilePath(savedProjectFilePath); await fileSystem.myDeletePromise(tempProjectDirectoryPath); fileSystem.extractAll(savedProjectFilePath, tempProjectDirectoryPath); console.log(`loadProject - loadProjectByProjectNameAsync: Project extracted to ${tempProjectDirectoryPath}`); const [projectJsonStr, projectJson] = await this.readAndSetProjectJsonAsync(this.tempProjectJsonFilePath); //console.log(projectJsonStr); console.log(`loadProject - loadProjectByProjectNameAsync: Project ${savedProjectFilePath} json loaded.`); // change any relative file path in assets to absolute path const assetsList = projectJson.assetsList; assetsList.forEach((asset) => { const assetSrc = asset.src; asset.src = this.getTempProjectAssetAbsolutePathFromProvidedPathIfIsRelative(assetSrc); // keep reference to any relative path for web server presentation asset.relativeSrc = assetSrc; }); return projectJson; } static async loadProjectByFilePathAsync(filePath) { const projectFile = new ProjectFile(null, filePath, null); return await projectFile.loadProjectAsync(); } setProjectJson(projectJson) { this.projectJson = projectJson; this.base64ThumbnailStr = this.projectJson.entitiesList.slides[0].image; } async readAndSetProjectJsonAsync(projectJsonPath) { const projectJsonStr = await fileSystem.readFilePromise(projectJsonPath); const projectJson = JSON.parse(projectJsonStr); this.setProjectJson(projectJson); return [projectJsonStr, projectJson]; } /* end of loadProject */ /* current loaded project (singleton) */ // Note: may not be good idea to expose this method static setCurrentLoadedProjectFilePath(projectFilePath) { currentLoadedProjectFilePath = projectFilePath; }; static isCurrentLoadedProject(aFilePath) { return currentLoadedProjectFilePath === aFilePath; }; static async loadCurrentLoadedProjectAsync() { return await ProjectFile.loadProjectByFilePathAsync(currentLoadedProjectFilePath); }; /* end of current loaded project (singleton) */ /* end of methods */ } module.exports = ProjectFile;<file_sep>/src/utils/number/setNumberValueWithDefault.js import isNumber from './isNumber'; export default function setNumberValueWithDefault(value, defaultValue) { return isNumber(value) ? value : defaultValue; };<file_sep>/public/utils/fileSystem/fileSystem.js // https://ourcodeworld.com/articles/read/106/how-to-choose-read-save-delete-or-create-a-file-with-electron-framework const rimraf = require('rimraf'); const fx = require('./mkdir-recursive'); const ncp = require('ncp').ncp; const { map } = require('p-iteration'); const myPath = require('./myPath'); const CustomedFileStats = require('./CustomedFileStats'); const toBase64Str = require('../base64/toBase64Str'); const fromBase64Str = require('../base64/fromBase64Str'); const { isFunction, invokeIfIsFunction } = require('../variableType/isFunction'); // https://github.com/electron/asar // http://www.tc4shell.com/en/7zip/asar/ // Somehow using the "import" syntax would result in the following error: // "Module not found: Can't resolve 'original-fs' in 'E:\Documents\Projects\Electron\School-VR\node_modules\asar\lib'" //import asar from 'asar'; const asar = require('asar'); const fs = require('fs'); const { promisify } = require('util'); /* from node.js fs implementation */ // https://github.com/nodejs/node/blob/6e56771f2a9707ddf769358a4338224296a6b5fe/lib/fs.js#L1694 const maybeCallBack = cb => { if (isFunction(cb)) { return cb; } //throw new ERR_INVALID_CALLBACK(); throw new Error(`Callback: '${cb}' is not a function.`); }; const assertEncoding = encoding => { if (encoding && !Buffer.isEncoding(encoding)) { //throw new ERR_INVALID_OPT_VALUE_ENCODING(encoding); throw new Error(`Invalid opt value encoding: ${encoding}`); } }; const getOptions = (options, defaultOptions) => { if (options === null || options === undefined || isFunction(options)) { return defaultOptions; } if (typeof options === 'string') { defaultOptions = { ...defaultOptions }; defaultOptions.encoding = options; options = defaultOptions; } else if (typeof options !== 'object') { //throw new ERR_INVALID_ARG_TYPE('options', ['string', 'Object'], options); throw new Error( `Invalid argument type: 'options: ${options}' should be of one of the types: 'string', 'Object'.` ); } if (options.encoding !== 'buffer') { assertEncoding(options.encoding); } return options; }; /* end of from node.js fs implementation */ /* error handling */ const passbackControlToCallBack = (callBack, data) => { handleGeneralErrAndData(callBack, null, data); }; const handleGeneralErr = (callBack, err) => { handleGeneralErrAndData(callBack, err); }; const handleGeneralErrAndData = (callBack, err, data) => { //console.log("fileSystem - handleGeneralErrAndData"); const callBackCall = (newErr, theData) => { invokeIfIsFunction(callBack, newErr, theData); }; if (err) { console.error(err.stack); callBackCall(err, null); } else { callBackCall(null, data); } }; /* end of error handling */ /* file api */ //const useFileHandle = (filePath, ) /** * !!! Important !!! * This exists() is different from fs.exists(). * It returns callBack(err, data). * err is always null, so that promisifying exists() would not have the reject case. * data is included such that promisified exists() will always be resolved. * data is a Boolean indicating if the file exists. */ // https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback const exists = (filePath, callBack) => { fs.access(filePath, fs.constants.F_OK, err => { callBack(null, !Boolean(err)); // would throw error if callBack is undefined }); }; const existsSync = filePath => { return fs.existsSync(filePath); }; const existsPromise = promisify(exists); // for performance reasons const writeFileAssumingDestDirExists = (filePath, content, callBack) => { fs.writeFile(filePath, content, err => { handleGeneralErr(callBack, err); }); }; // for performance reasons const writeFileAssumingDestDirExistsSync = (filePath, content) => { fs.writeFileSync(filePath, content); }; const writeFileAssumingDestDirExistsPromise = promisify( writeFileAssumingDestDirExists ); /** * writeFile would create any parent directories in filePath if not exist. * writeFile would replace the file if already exists. (same behaviour as fs.writeFile) * https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback * https://stackoverflow.com/questions/16316330/how-to-write-file-if-parent-folder-doesnt-exist */ const writeFile = (filePath, content, callBack) => { const directoriesStr = myPath.dirname(filePath); const writeFileCallBack = () => { fs.writeFile(filePath, content, err => { handleGeneralErr(callBack, err); }); }; exists(directoriesStr, (_, isExists) => { if (!isExists) { // directory does not exist createDirectoryIfNotExists(directoriesStr, err => { if (err) { handleGeneralErr(callBack, err); return; } writeFileCallBack(); }); } else { // directory exists writeFileCallBack(); } }); }; const writeFileSync = (filePath, content) => { const directoriesStr = myPath.dirname(filePath); if (!existsSync(directoriesStr)) { createDirectoryIfNotExistsSync(directoriesStr); } fs.writeFileSync(filePath, content); }; const writeFilePromise = promisify(writeFile); const createWriteStream = outputPath => { return fs.createWriteStream(outputPath); }; const appendFile = (filePath, content, callBack) => { const directoriesStr = myPath.dirname(filePath); const appendFileCallBack = () => { fs.appendFile(filePath, content, err => { handleGeneralErr(callBack, err); }); }; exists(directoriesStr, (_, isExists) => { if (!isExists) { // directory does not exist createDirectoryIfNotExists(directoriesStr, err => { if (err) { handleGeneralErr(callBack, err); return; } appendFileCallBack(); }); } else { // directory exists appendFileCallBack(); } }); }; const appendFileSync = (filePath, content) => { const directoriesStr = myPath.dirname(filePath); if (!existsSync(directoriesStr)) { createDirectoryIfNotExistsSync(directoriesStr); } fs.appendFileSync(filePath, content); }; const appendFilePromise = promisify(appendFile); const rename = (oldPath, newPath, callBack) => { fs.rename(oldPath, newPath, renameErr => { if (renameErr && renameErr.code === 'EXDEV') { // https://stackoverflow.com/questions/43206198/what-does-the-exdev-cross-device-link-not-permitted-error-mean copyFile(oldPath, newPath, copyFileErr => { if (copyFileErr) { handleGeneralErr(callBack, copyFileErr); return; } myDelete(oldPath, myDeleteErr => { handleGeneralErr(callBack, myDeleteErr); }); }); } else { handleGeneralErr(callBack, renameErr); } }); }; const renameSync = (oldPath, newPath) => { fs.renameSync(oldPath, newPath); }; const renamePromise = promisify(rename); // default text file const defaultReadFileOptions = { encoding: 'utf8', flag: 'r' }; const readFile = (filePath, options, callBack) => { callBack = maybeCallBack(callBack || options); options = getOptions(options, defaultReadFileOptions); fs.readFile(filePath, options, (err, data) => { handleGeneralErrAndData(callBack, err, data); }); }; const readFileSync = (filePath, options) => { options = getOptions(options, defaultReadFileOptions); return fs.readFileSync(filePath, defaultReadFileOptions); }; const readFilePromise = promisify(readFile); const createReadStream = filePath => { return fs.createReadStream(filePath); }; // for performance reasons const copyFileAssumingDestDirExists = (src, dest, callBack) => { if (src === dest) { passbackControlToCallBack(callBack, null); return; } fs.copyFile(src, dest, err => { handleGeneralErr(callBack, err); }); }; // for performance reasons const copyFileAssumingDestDirExistsSync = (src, dest) => { if (src === dest) { return; } fs.copyFileSync(src, dest); }; const copyFileAssumingDestDirExistsPromise = promisify( copyFileAssumingDestDirExists ); /** * copyFile and copyFileSync is structurally similar to writeFile and writeFileSync * copyFile would create any parent directories in filePath if not exist. * copyFile would replace the file if already exists. (at least that what I think) */ const copyFile = (src, dest, callBack) => { if (src === dest) { passbackControlToCallBack(callBack, null); return; } const destDirectoriesStr = myPath.dirname(dest); const copyFileCallBack = () => { fs.copyFile(src, dest, err => { handleGeneralErr(callBack, err); }); }; exists(destDirectoriesStr, (_, isExists) => { if (!isExists) { // directory does not exist createDirectoryIfNotExists(destDirectoriesStr, err => { if (err) { handleGeneralErr(callBack, err); return; } copyFileCallBack(); }); } else { // directory exists copyFileCallBack(); } }); }; const copyFileSync = (src, dest) => { if (src === dest) { return; } const destDirectoriesStr = myPath.dirname(dest); if (!existsSync(destDirectoriesStr)) { createDirectoryIfNotExistsSync(destDirectoriesStr); } fs.copyFileSync(src, dest); }; const copyFilePromise = promisify(copyFile); // most powerful const copy = (src, dest, callBack) => { ncp(src, dest, err => { handleGeneralErr(callBack, err); }); }; const copyPromise = promisify(copy); /** * Note: * the return CustomedFileStats object has an additional 'path' property * compared to the default fs.Stats object * https://stackoverflow.com/questions/11659054/how-to-access-name-of-file-within-fs-callback-methods * https://nodejs.org/dist/latest-v10.x/docs/api/fs.html#fs_class_fs_stats */ const stat = (filePath, callBack) => { fs.stat(filePath, (err, stats) => { const customedStatsObj = new CustomedFileStats(stats, filePath); handleGeneralErrAndData(callBack, err, customedStatsObj); }); }; const statSync = filePath => { const statObj = fs.statSync(filePath); return new CustomedFileStats(statObj, filePath); }; const statPromise = promisify(stat); const isDirectory = (filePath, callBack) => { fs.stat(filePath, (err, stats) => { if (err) { handleGeneralErr(err); return; } handleGeneralErrAndData(callBack, null, stats.isDirectory()); }); }; const isDirectorySync = filePath => { return fs.statSync(filePath).isDirectory(); }; const isDirectoryPromise = promisify(isDirectory); const base64Encode = (filePath, callBack) => { readFile(filePath, (err, data) => { handleGeneralErrAndData(callBack, err, toBase64Str(data)); }); }; // https://stackoverflow.com/questions/24523532/how-do-i-convert-an-image-to-a-base64-encoded-data-url-in-sails-js-or-generally const base64EncodeSync = filePath => { // read binary data const data = readFileSync(filePath); // convert binary data to base64 encoded string return toBase64Str(data); }; const base64EncodePromise = promisify(base64Encode); const base64Decode = (locationToSaveFile, encodedStr, callBack) => { writeFile(locationToSaveFile, fromBase64Str(encodedStr), err => { handleGeneralErr(callBack, err); }); }; const base64DecodeSync = (locationToSaveFile, encodedStr) => { writeFileSync(locationToSaveFile, fromBase64Str(encodedStr)); }; const base64DecodePromise = promisify(base64Decode); /* end of file api */ /* asar - Electron Archive https://github.com/electron/asar/blob/master/lib/asar.js */ const createPackage = (src, dest, callBack) => { // https://github.com/electron/asar#transform // passing null as 3rd argument won't work // should pass {} (empty value) or _ => null (a function which returns nothing) or anything other than null or undefined createPackageWithOptions(src, dest, {}, callBack); }; const createPackagePromise = promisify(createPackage); const createPackageWithTransformOption = ( src, dest, transformFunc, callBack ) => { createPackageWithOptions(src, dest, { transform: transformFunc }, callBack); }; const createPackageWithTransformOptionPromise = promisify( createPackageWithTransformOption ); // overwrite existing dest const createPackageWithOptions = (src, dest, options, callBack) => { //console.log(asar); asar.createPackageWithOptions(src, dest, options, err => { const isSuccess = !err; if (isSuccess) { console.log( `fileSystem - createPackageWithOptions: ${src} packaged to ${dest}` ); } handleGeneralErr(callBack, err); }); }; const createPackageWithOptionsPromise = promisify(createPackageWithOptions); const extractFile = (archive, fileName) => { try { asar.uncache(archive); asar.extractFile(archive, fileName); } catch (err) { console.error(err); } }; const extractAll = (archive, dest) => { try { // asar would cache previous result! asar.uncache(archive); //asar.uncacheAll(); // overwrite existing dest! asar.extractAll(archive, dest); } catch (err) { console.log(err); } }; /* end of asar - Electron Archive */ /* directory api */ // somehow this is not working // const defaultMkDirOptions = { // recursive: true // }; // const mkdir = (dirPath, callBack) => { // fs.mkdir(dirPath, defaultMkDirOptions, (err) => { // handleGeneralErr(callBack, err); // }); // }; // const mkdirSync = (dirPath) => { // fs.mkdirSync(dirPath, defaultMkDirOptions); // } // use fx instead of fs const mkdir = (dirPath, callBack) => { fx.mkdir(fs, myPath.path, dirPath, err => { handleGeneralErr(callBack, err); }); }; const mkdirSync = dirPath => { fx.mkdirSync(fs, myPath.path, dirPath); }; const createDirectoryIfNotExists = (dirPath, callBack) => { exists(dirPath, (_, isExists) => { if (!isExists) { // directory does not exist mkdir(dirPath, mkDirErr => { handleGeneralErr(callBack, mkDirErr); }); } else { // directory exists passbackControlToCallBack(callBack); } }); }; // https://stackoverflow.com/questions/21194934/node-how-to-create-a-directory-if-doesnt-exist const createDirectoryIfNotExistsSync = dirPath => { if (!existsSync(dirPath)) { mkdirSync(dirPath); } }; const createDirectoryIfNotExistsPromise = promisify(createDirectoryIfNotExists); // https://askubuntu.com/questions/517329/overwrite-an-existing-directory const createAndOverwriteDirectoryIfExists = (dirPath, callBack) => { myDelete(dirPath, err => { if (err) { handleGeneralErr(callBack, err); } else { mkdir(dirPath, err => { handleGeneralErr(callBack, err); }); } }); }; const createAndOverwriteDirectoryIfExistsSync = dirPath => { myDeleteSync(dirPath); mkdirSync(dirPath); }; const createAndOverwriteDirectoryIfExistsPromise = promisify( createAndOverwriteDirectoryIfExists ); /** * Note: * files returned by fs.readdir is an array of file name strings */ const readdir = (dirPath, callBack) => { fs.readdir(dirPath, (err, fileNames) => { if (err) { handleGeneralErr(callBack, err); return; } const absolutePaths = fileNames.map(fileName => myPath.join(dirPath, fileName) ); handleGeneralErrAndData(callBack, null, absolutePaths); }); }; const readdirSync = dirPath => { return fs .readdirSync(dirPath) .map(fileName => myPath.join(dirPath, fileName)); }; const readdirPromise = promisify(readdir); /** * Note: * the returned files is an array of CustomedStats objects * instead of the default array of file name strings * https://stackoverflow.com/questions/11659054/how-to-access-name-of-file-within-fs-callback-methods * https://nodejs.org/dist/latest-v10.x/docs/api/fs.html#fs_class_fs_stats */ const readdirWithStatPromise = async dirPath => { const fileNames = await readdirPromise(dirPath); if (!Array.isArray(fileNames) || fileNames.length === 0) { return []; } const absolutePaths = await readdirPromise(dirPath); const fileStatObjs = await map(absolutePaths, async fileAbsolutePath => { return await statPromise(fileAbsolutePath); }); return fileStatObjs; }; // https://stackoverflow.com/questions/44199883/how-do-i-get-a-list-of-files-with-specific-file-extension-using-node-js const readdirWithExtensionFilter = (dirPath, extensionWithDot, callBack) => { fs.readdir(dirPath, (err, fileNames) => { if (err) { handleGeneralErr(callBack, err); return; } const extensionWithDotLowerCase = extensionWithDot.toLowerCase(); const absolutePathsFiltered = fileNames.map( fileName => myPath.getFileExtensionWithLeadingDot(fileName).toLowerCase() === extensionWithDotLowerCase ); handleGeneralErrAndData(callBack, null, absolutePathsFiltered); }); }; const readdirWithExtensionFilterPromise = promisify(readdirWithExtensionFilter); /* end of directory api */ /** * rimraf api * work for both file and directory * https://github.com/isaacs/rimraf */ const defaultMyDeleteOptions = Object.assign( { maxBusyTries: 15 }, fs ); const myDelete = (filePath, callBack) => { rimraf(filePath, defaultMyDeleteOptions, err => { //console.log('file to delete: ' + filePath); handleGeneralErr(callBack, err); }); }; const myDeleteSync = filePath => { rimraf.sync(filePath, defaultMyDeleteOptions); }; const myDeletePromise = promisify(myDelete); /* end of del api */ module.exports = { // error handling // passbackControlToCallBack, // handleGeneralErr, // handleGeneralErrAndData, // file api exists, existsSync, existsPromise, writeFileAssumingDestDirExists, writeFileAssumingDestDirExistsSync, writeFileAssumingDestDirExistsPromise, writeFile, writeFileSync, writeFilePromise, createWriteStream, appendFile, appendFileSync, appendFilePromise, rename, renameSync, renamePromise, readFile, readFileSync, readFilePromise, createReadStream, copyFileAssumingDestDirExists, copyFileAssumingDestDirExistsSync, copyFileAssumingDestDirExistsPromise, copyFile, copyFileSync, copyFilePromise, copy, // most powerful copyPromise, //deleteFileSafe, //deleteFileSafeSync, stat, statSync, statPromise, isDirectory, isDirectorySync, isDirectoryPromise, base64Encode, base64EncodeSync, base64EncodePromise, base64Decode, base64DecodeSync, base64DecodePromise, // asar - Electron Archive createPackage, createPackagePromise, createPackageWithTransformOption, createPackageWithTransformOptionPromise, createPackageWithOptions, createPackageWithOptionsPromise, extractFile, extractAll, // directory api //mkdir, //mkdirSync, createDirectoryIfNotExists, createDirectoryIfNotExistsSync, createDirectoryIfNotExistsPromise, createAndOverwriteDirectoryIfExists, createAndOverwriteDirectoryIfExistsSync, createAndOverwriteDirectoryIfExistsPromise, readdir, readdirSync, readdirPromise, readdirWithStatPromise, readdirWithExtensionFilter, readdirWithExtensionFilterPromise, //deleteDirectorySafe, //deleteDirectorySafeSync, // rimraf api myDelete, myDeleteSync, myDeletePromise }; <file_sep>/src/components/router/privateRoute.js import React from 'react'; import {Route, Redirect} from 'react-router-dom'; import smalltalk from 'smalltalk'; import DefaultLoading from 'components/loading/defaultLoading'; import {getLocalizedMessage} from 'globals/contexts/locale/languageContext'; //import handleErrorWithUiDefault from 'utils/errorHandling/handleErrorWithUiDefault'; import {authenticateWithLicenseKeyPromise, getIsAuthenticated} from 'utils/authentication/auth'; // https://tylermcginnis.com/react-router-protected-routes-authentication/ class PrivateRoute extends React.Component { constructor(props) { super(props); this.state = { isAuthenticated: getIsAuthenticated(), isLicenseKeyInputPrompted: false }; [ 'routeRenderFunctionWithRedirectFactory', 'routeRenderFunctionWithLoadingFactory' ].forEach(methodName => { this[methodName] = this[methodName].bind(this); }); } async componentDidMount() { console.log('PrivateRoute componentDidMount'); const { isAuthenticated, isLicenseKeyInputPrompted } = this.state; if (!isAuthenticated && !isLicenseKeyInputPrompted) { const throwAuthenticationError = _ => { throw new Error('Authentication failed.'); }; try { /** * Important: * if 'cancel' button is pressed, an error will be thrown ? */ const newLicenseKeyEntered = await smalltalk.prompt(getLocalizedMessage('Prompt.AutenticationFailTitle'), getLocalizedMessage('Prompt.AutenticationFailMessage'), ''); if (newLicenseKeyEntered) { const newIsAuthenticated = await authenticateWithLicenseKeyPromise(newLicenseKeyEntered); if (newIsAuthenticated) { alert(getLocalizedMessage('Alert.AutenticationSuccessMessage')); this.setState({ isAuthenticated: newIsAuthenticated, isLicenseKeyInputPrompted: true }); } else { throwAuthenticationError(); } } else { throwAuthenticationError(); } } catch (err) { alert(getLocalizedMessage('Alert.AutenticationFailMessage')); this.setState({ isLicenseKeyInputPrompted: true }); // silence error //handleErrorWithUiDefault(err); } } } componentWillUnmount() { console.log('PrivateRoute componentWillUnmount'); } routeRenderFunctionWithRedirectFactory() { const { component: Component, fallBackRedirectPath } = this.props; const { isAuthenticated } = this.state; if (isAuthenticated === true) { return (someProps) => <Component {...someProps} />; } else { return (someProps) => <Redirect to={fallBackRedirectPath} />; } } // This allows time for prompting for license key input in componentDidMount(). // Using routeRenderFunctionWithRedirectFactory on 1st render may result in <Redirect />, // which triggers route change, and hence PrivateRoute component to br unmounted straight away. routeRenderFunctionWithLoadingFactory() { const { component: Component } = this.props; const { isAuthenticated } = this.state; if (isAuthenticated === true) { return (someProps) => <Component {...someProps} />; } else { return (someProps) => <DefaultLoading />; } } render() { const { component: Component, fallBackRedirectPath, ...rest } = this.props; const { isLicenseKeyInputPrompted } = this.state; const routeRenderFunction = !isLicenseKeyInputPrompted ? this.routeRenderFunctionWithLoadingFactory() : this.routeRenderFunctionWithRedirectFactory(); return ( <Route {...rest} render={routeRenderFunction} /> ); } } export default PrivateRoute;<file_sep>/public/utils/saveLoadProject/parseDataToSaveFormat.js // const jsonStringifyFormatted = ('../json/jsonStringifyFormatted'); const parseDataToSaveFormat = (projectName, entitiesList, assetsList) => { const resultJson = { projectName: projectName, entitiesList: entitiesList, assetsList: assetsList }; //console.log(jsonStringifyFormatted(resultJson)); return resultJson; }; module.exports = parseDataToSaveFormat;<file_sep>/public/utils/ffmpeg/ffmpegProcess.js const { promisify } = require('util'); const exec = promisify(require('child_process').exec); const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path; /* References: https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback https://www.npmjs.com/package/@ffmpeg-installer/ffmpeg https://stackoverflow.com/questions/24961127/how-to-create-a-video-from-images-with-ffmpeg ffmpeg command: ffmpeg -i "C:/Users/IOIO/Desktop/school vr temp/images/%07d.png" -c:v libx264 -vf fps=30 -pix_fmt yuv420p "C:/Users/IOIO/Desktop/school vr temp/videos/new.mp4" */ const imageSequenceToVideoPromise = async ( inputImgFileSelector, outputVideoPath, fps ) => { return await exec(`${ffmpegPath} -i ${inputImgFileSelector} -c:v libx264 -vf fps=${fps} -pix_fmt yuv420p ${outputVideoPath} `); }; module.exports = { imageSequenceToVideoPromise }; <file_sep>/src/utils/ui/isInViewport.js // https://gomakethings.com/how-to-test-if-an-element-is-in-the-viewport-with-vanilla-javascript/ export default function (elem) { var bounding = elem.getBoundingClientRect(); return ( bounding.top >= 0 && bounding.left >= 0 && bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) && bounding.right <= (window.innerWidth || document.documentElement.clientWidth) ); };<file_sep>/public/utils/aframeEditor/openFileDialog.js const { config, appDirectory, openFileDialogFilter } = require('../../globals/config'); const { BrowserWindow, dialog } = require('electron'); const { promisify } = require('util'); const DialogType = { Open: 'Open', Save: 'Save' }; // https://electronjs.org/docs/api/dialog // The browserWindow argument allows the dialog to attach itself to a parent window, making it modal. function showDialogCommon( fileFilters, dialogMessage, callBack, defaultPath, dialogType = DialogType.Open ) { const browserWindow = BrowserWindow.getFocusedWindow(); let dialogTitle = config.appName; let dialogFuncToCall = _ => {}; switch (dialogType) { case DialogType.Save: dialogTitle += ' - Save'; dialogFuncToCall = dialog.showSaveDialog; break; case DialogType.Open: default: dialogTitle = ' - Open'; dialogFuncToCall = dialog.showOpenDialog; break; } const optionsObj = { title: dialogTitle, defaultPath: defaultPath, filters: fileFilters, properties: ['openFile'], message: dialogMessage }; dialogFuncToCall(browserWindow, optionsObj, data => { const err = null; callBack(err, data); }); } function openImageDialog(callBack) { showDialogCommon( [openFileDialogFilter.image], 'Please select an image file.', callBack, null, DialogType.Open ); } const openImageDialogPromise = promisify(openImageDialog); // probably not used in future as now openImageDialog() includes open gif files function openGifDialog(callBack) { showDialogCommon( [openFileDialogFilter.gif], 'Please select a gif file.', callBack, null, DialogType.Open ); } const openGifDialogPromise = promisify(openGifDialog); function openVideoDialog(callBack) { showDialogCommon( [openFileDialogFilter.video], 'Please select a video file.', callBack, null, DialogType.Open ); } const openVideoDialogPromise = promisify(openVideoDialog); function openSchoolVrFileDialog(callBack) { showDialogCommon( [openFileDialogFilter.schoolVrFile], 'Please select a School VR file.', callBack, appDirectory.appProjectsDirectory, DialogType.Open ); } const openSchoolVrFileDialogPromise = promisify(openSchoolVrFileDialog); function saveSchoolVrFileDialog(callBack) { showDialogCommon( [openFileDialogFilter.schoolVrFile], 'Please select a School VR file.', callBack, appDirectory.appProjectsDirectory, DialogType.Save ); } const saveSchoolVrFileDialogPromise = promisify(saveSchoolVrFileDialog); function save360ImageDialog(callBack) { showDialogCommon( [openFileDialogFilter.image], 'Please select an image file.', callBack, `untitled${config.captured360ImageExtension}`, DialogType.Save ); } const save360ImageDialogPromise = promisify(save360ImageDialog); function save360VideoDialog(callBack) { showDialogCommon( [openFileDialogFilter.video], 'Please select a video file.', callBack, `untitled${config.captured360VideoExtension}`, DialogType.Save ); } const save360VideoDialogPromise = promisify(save360VideoDialog); module.exports = { openImageDialog, openImageDialogPromise, openGifDialog, openGifDialogPromise, openVideoDialog, openVideoDialogPromise, openSchoolVrFileDialog, openSchoolVrFileDialogPromise, saveSchoolVrFileDialog, saveSchoolVrFileDialogPromise, save360ImageDialog, save360ImageDialogPromise, save360VideoDialogPromise }; <file_sep>/public/utils/captures/captures.js const electron = require('electron'); const app = electron.app; const appName = app.getName(); const { config, appDirectory } = require('../../globals/config'); const uuid = require('uuid/v1'); const ExifTool = require('exiftool-vendored').ExifTool; const sphericalMetadata = require('@bubltechnology/spherical-metadata'); const myPath = require('../fileSystem/myPath'); const fileSystem = require('../fileSystem/fileSystem'); //const FfmpegCommand = require('../ffmpeg/ffmpegCommand'); const { imageSequenceToVideoPromise } = require('../ffmpeg/ffmpegProcess'); /* constants */ const writeMetaDataTo360ImageTimeoutInMillis = 5000; const numOfDigitsInImgSeqFileName = 7; /* end of constants */ /* temp image sequence file paths */ const getTempCaptureUniqueDirectoryPath = videoUuid => { return myPath.join(appDirectory.appTempCapturesContainerDirectory, videoUuid); }; const getTempImageSequenceDirectoryPath = videoUuid => { return myPath.join(getTempCaptureUniqueDirectoryPath(videoUuid), 'images'); }; const getTempImageSequenceFilePath = (videoUuid, currentFrame) => { return ( myPath.join( getTempImageSequenceDirectoryPath(videoUuid), String(currentFrame).padStart(numOfDigitsInImgSeqFileName, '0') ) + config.captured360ImageExtension ); }; const getTempImageSequenceFileSelectorForFfmpeg = videoUuid => { // e.g. 'assets/demo1/Sinewave3-1920x1080_%03d.png' return ( myPath.join( getTempImageSequenceDirectoryPath(videoUuid), `%0${numOfDigitsInImgSeqFileName}d` ) + config.captured360ImageExtension ); }; const getTempVideoOutputFilePath = videoUuid => { return ( myPath.join(getTempCaptureUniqueDirectoryPath(videoUuid), videoUuid) + config.captured360VideoExtension ); }; /* end of temp image sequence file paths */ /* writing meta-data */ const writeMetaDataTo360ImagePromise = async imgPath => { // https://www.npmjs.com/package/exiftool-vendored const exiftool = new ExifTool({ taskTimeoutMillis: writeMetaDataTo360ImageTimeoutInMillis }); // https://medium.com/hackernoon/capture-facebook-compatible-4k-360-videos-of-3d-scenes-in-your-browser-788226f2c75f await exiftool.write(imgPath, { ProjectionType: 'equirectangular' }); }; const writeMetaDataTo360VideoPromise = async ( existingVideoPath, newVideoPath ) => { // sphericalMetadata.injectMetadata() returns a promise. // https://www.npmjs.com/package/@bubltechnology/spherical-metadata // https://www.exiv2.org/tags-xmp-GPano.html // sourceCount is number of source images used to create the panorama // https://en.wikipedia.org/wiki/Cube_mapping // for cubemap, maybe sourceCount is 6 ??? return sphericalMetadata.injectMetadata({ source: existingVideoPath, destination: newVideoPath, software: appName, projection: 'equirectangular', sourceCount: 6, // 4, stereo: 'top-bottom' // this is key }); }; /* end of writing meta-data */ const write360ImageToPath = async ( path, imgBase64Str, isWrite360ImgMeta = true ) => { await fileSystem.base64DecodePromise(path, imgBase64Str); if (isWrite360ImgMeta) { await writeMetaDataTo360ImagePromise(path); } }; const write360ImageToTempPromise = async imgBase64Str => { const tmpImgId = uuid(); const tmpImgDirectoryName = tmpImgId; const tmpImgFilePath = myPath.join( appDirectory.appTempCapturesContainerDirectory, tmpImgDirectoryName, tmpImgId ) + config.captured360ImageExtension; await write360ImageToPath(tmpImgFilePath, imgBase64Str, true); return tmpImgFilePath; }; const write360ImageAsPartOfVideoToTempPromise = async ( videoUuid, currentFrame, imgBase64Str ) => { const tmpImgFilePath = getTempImageSequenceFilePath(videoUuid, currentFrame); console.log(tmpImgFilePath); await write360ImageToPath(tmpImgFilePath, imgBase64Str, false); return tmpImgFilePath; }; const convertTempImageSequenceToVideoPromise = async (videoUuid, fps) => { const inputImgFileSelector = getTempImageSequenceFileSelectorForFfmpeg( videoUuid ); const outputVideoPath = getTempVideoOutputFilePath(videoUuid); //const inputFps = fps; //const outputFps = fps; /* ffmpegCommand version */ //const command = new ffmpegCommand(); // const handleImageSequenceToVideoEnd = async _ => { // console.log('convertTempImageSequenceToVideoPromise: Finished processing'); // // const outputVideoWithMetaDataPath = // // myPath.getFileNameWithDirectoryWithoutExtension(outputVideoPath) + '_withmeta' + // // config.captured360VideoExtension; // // await writeMetaDataTo360VideoPromise( // // outputVideoPath, // // outputVideoWithMetaDataPath // // ); // }; // const result = command.imageSequenceToVideo( // inputImgFileSelector, // inputFps, // outputVideoPath, // outputFps, // handleImageSequenceToVideoEnd // ); // console.log('result:', result); /* end of ffmpegCommand version */ /* ffmpegProcess version */ // https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback const { stdout, stderr } = await imageSequenceToVideoPromise( inputImgFileSelector, outputVideoPath, fps ); if (stdout) { console.log('imageSequenceToVideoPromise stdout:', stdout); } if (stderr) { console.log('imageSequenceToVideoPromise stderr:', stderr); //throw new Error(stderr); } console.log( 'convertTempImageSequenceToVideoPromise: Writing metadata to 360 video' ); const outputVideoWithMetaDataPath = myPath.getFileNameWithDirectoryWithoutExtension(outputVideoPath) + '_withmeta' + config.captured360VideoExtension; await writeMetaDataTo360VideoPromise( outputVideoPath, outputVideoWithMetaDataPath ); console.log('convertTempImageSequenceToVideoPromise: Finished processing'); /* end of ffmpegProcess version */ return outputVideoWithMetaDataPath; }; module.exports = { write360ImageToTempPromise, write360ImageAsPartOfVideoToTempPromise, convertTempImageSequenceToVideoPromise }; <file_sep>/src/utils/number/stricterParseInt.js // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt const stricterParseInt = (value) => { if (/^(-|\+)?(\d+|Infinity)$/.test(value)) return Number(value); return NaN; } export default stricterParseInt; <file_sep>/src/containers/aframeEditor/homePage/infoPanel/timelineInfoRenderer.js /* info generation of right panel */ import React, {Component} from 'react'; import {rgba2hex} from 'globals/helperfunctions'; import transformModeId from 'globals/constants/transformModeId'; import isNonEmptyArray from 'utils/variableType/isNonEmptyArray'; // import {SketchPicker} from 'react-color'; import TransformMode from './transformMode'; import ColorPicker from './colorPicker'; import OpacityPicker from './opacityPicker'; // import ABox from 'utils/aBox'; import {LanguageContextMessagesConsumer} from 'globals/contexts/locale/languageContext'; import './infoTypeBox.css'; var Events = require('vendor/Events.js'); class TimelineInfoRenderer extends Component { constructor(props) { super(props); const self = this; this.editor = null; this.state = { editorMode: null, displayColorPicker: false, // color: props.timelineObj[props.timelinePosition]['material']['color'], additionalAttributes: {} // const color = rgba2hex(data.material.color) }; this.changeObjectField = this.changeObjectField.bind(this); this.changeObjectMultipleFields = this.changeObjectMultipleFields.bind(this); this.changeTransformMode = this.changeTransformMode.bind(this); this.events = { // transformmodechanged: (mode) => { // self.setState({ // editorMode: mode // }); // } }; // this.handleClick = this.handleClick.bind(this); // this.handleClose = this.handleClose.bind(this); // this.handleChange = this.handleChange.bind(this); } componentDidMount() { const props = this.props; if (props.animatableAttributes.position) { this.changeTransformMode(transformModeId.translate); } else if (props.animatableAttributes.rotation) { this.changeTransformMode(transformModeId.rotate); } else if (props.animatableAttributes.scale) { this.changeTransformMode(transformModeId.scale); } Events.on('editor-load', obj => { this.editor = obj; }) // Events.emit('transformmodechanged', transformModeId.translate); } // static getDerivedStateFromProps(nextProps, nextState) { // console.log('getDerivedStateFromProps'); // return { // displayColorPicker: false, // color: nextProps.timelineObj[nextProps.timelinePosition]['material']['color'] // } // } componentDidUpdate(prevProps, prevState) { const props = this.props; const state = this.state; // console.log(props, prevProps); // console.log(props.timelineObj.id, prevProps.timelineObj.id); // console.log(props.timelinePosition, prevProps.timelinePosition); if ( props.timelineObj.id !== prevProps.timelineObj.id || props.timelinePosition !== prevProps.timelinePosition ) { // console.log('reset'); // this.changeTransformMode(null); if (props.animatableAttributes.position) { this.changeTransformMode(transformModeId.translate); } else if (props.animatableAttributes.rotation) { this.changeTransformMode(transformModeId.rotate); } else if (props.animatableAttributes.scale) { this.changeTransformMode(transformModeId.scale); } } // if (state.additionalAttributes.radiusTop !== props.timelineObj[props.timelinePosition]) return true; } componentWillUnmount() { for (let eventName in this.events) { Events.removeListener(eventName, this.events[eventName]); } } changeTransformMode(transformMode) { // const sceneContext = props.sceneContext; this.setState({ editorMode: transformMode }); if (transformMode) { Events.emit('enablecontrols'); Events.emit('transformmodechanged', transformMode); } else { Events.emit('disablecontrols'); } } changeObjectField(field, value) { const { sceneContext } = this.props; const tmp = {}; let pointer = tmp; field.split('.').forEach((key, idx, arr) => { if (idx === arr.length - 1) { pointer[key] = value } else { pointer[key] = {} pointer = pointer[key] } }) // tmp[field] = value; // console.log(tmp); sceneContext.updateTimelinePositionAttributes( tmp ); // Events.emit('updateSelectedEntityAttribute', tmp); } changeObjectMultipleFields(objs) { const props = this.props; const tmp = {}; Object.keys(objs).forEach(field => { const value = objs[field]; let pointer = tmp; field.split('.').forEach((key, idx, arr) => { if (idx === arr.length - 1) { pointer[key] = value } else { if (!pointer[key]) pointer[key] = {} pointer = pointer[key] } }) // console.log(tmp); // console.log(pointer); }) // tmp[field] = value; props.sceneContext.updateTimelinePositionAttributes( tmp ); // Events.emit('updateSelectedEntityAttribute', tmp); } render() { const props = this.props; const state = this.state; const currentEntity = props.sceneContext.getCurrentEntity(); const data = props.timelineObj[props.timelinePosition]; // console.log(data.ttfFont, animatableAttributes.ttfFont && animatableAttributes.ttfFont.indexOf('fontSize') !== -1); // const color = rgba2hex(data.material.color); const animatableAttributes = props.animatableAttributes; const transformModes = []; if (animatableAttributes.position) { transformModes.push(transformModeId.translate); } if (animatableAttributes.rotation) { transformModes.push(transformModeId.rotate); } if (animatableAttributes.scale) { transformModes.push(transformModeId.scale); } // ABox return ( <div className="animatable-params"> { isNonEmptyArray(transformModes) && <div className={`vec3D-btn-col buttons-${transformModes.length}`}> <TransformMode modes={transformModes} isInTimeline={true} onUpdate={(newPosition, newRotation, newScale) => { this.changeObjectMultipleFields({ 'position': newPosition, 'rotation': newRotation, 'scale': newScale }); }} /> </div> } <div className="attribute-buttons-wrapper"> {animatableAttributes.material && animatableAttributes.material.indexOf('color') !== -1 && <div className="attribute-button color-col" title={rgba2hex(data.material.color)} onClick={_ => this.changeTransformMode(null)}> <ColorPicker key={props.timelineObj.id + data.material.color} field={'material'} color={rgba2hex(data.material.color)} timelineId={props.timelineObj.id} timelinePosition={props.timelinePosition} onUpdate={(newColor) => { this.changeObjectField('material.color', newColor) }} currentEntity={currentEntity} /> <div className="field-label"> <LanguageContextMessagesConsumer messageId="EditThingPanel.Color.ColorLabel" /> </div> </div> } {animatableAttributes.material && animatableAttributes.material.indexOf('opacity') !== -1 && <div className="attribute-button opacity-col" onClick={() => this.changeTransformMode(null)}> <OpacityPicker key={props.timelineObj.id} field={'material'} opacity={data.material.opacity} timelineId={props.timelineObj.id} timelinePosition={props.timelinePosition} onUpdate={(newOpacity) => { this.changeObjectField('material.opacity', newOpacity) }} currentEntity={currentEntity} /> <div className="field-label"> <LanguageContextMessagesConsumer messageId="EditThingPanel.Color.OpacityLabel" /> </div> </div> } {animatableAttributes.ttfFont && animatableAttributes.ttfFont.indexOf('color') !== -1 && <div className="attribute-button color-col" title={data.ttfFont.color} onClick={() => this.changeTransformMode(null)}> <ColorPicker key={props.timelineObj.id + data.ttfFont.color} field={'ttfFont'} color={data.ttfFont.color} timelineId={props.timelineObj.id} timelinePosition={props.timelinePosition} onUpdate={(newColor) => { this.changeObjectField('ttfFont.color', newColor) }} currentEntity={currentEntity} /> <div className="field-label">Text Color</div> </div> } {animatableAttributes.ttfFont && animatableAttributes.ttfFont.indexOf('opacity') !== -1 && <div className="attribute-button opacity-col" onClick={() => this.changeTransformMode(null)}> <OpacityPicker key={props.timelineObj.id} field={'ttfFont'} opacity={data.ttfFont.opacity} timelineId={props.timelineObj.id} timelinePosition={props.timelinePosition} onUpdate={(newOpacity) => { this.changeObjectField('ttfFont.opacity', newOpacity) }} currentEntity={currentEntity} /> <div className="field-label">Text Opacity</div> </div> } {animatableAttributes.ttfFont && animatableAttributes.ttfFont.indexOf('fontSize') !== -1 && <div className="attribute-button opacity-col" onClick={() => this.changeTransformMode(null)}> <input type="ttfFont" value={data.ttfFont.fontSize} onInput={(e) => { currentEntity.el.setAttribute('ttfFont', { fontSize: e.currentTarget.value }) {/* this.setState((prevState) => { return { additionalAttributes: { ...prevState.additionalAttributes, radiusTop: e.currentTarget.value } } }) */} this.changeObjectField('ttfFont.fontSize', e.currentTarget.value) }} onBlur={(e) => { this.changeObjectField('ttfFont.fontSize', e.currentTarget.value) }} /> <div className="field-label">Font Size</div> </div> } {animatableAttributes.geometry && animatableAttributes.geometry.indexOf('radiusTop') !== -1 && <div className="attribute-button opacity-col" onClick={() => this.changeTransformMode(null)}> <div className="field-label">Radius Top:</div> <input type="text" value={state.additionalAttributes.radiusTop} onInput={(e) => { currentEntity.el.setAttribute('geometry', { radiusTop: e.currentTarget.value }) this.setState((prevState) => { return { additionalAttributes: { ...prevState.additionalAttributes, radiusTop: e.currentTarget.value } } }) }} onBlur={(e) => { this.changeObjectField('geometry.radiusTop', state.additionalAttributes.radiusTop) }} /> </div> } {animatableAttributes.geometry && animatableAttributes.geometry.indexOf('radiusBottom') !== -1 && <div className="attribute-button opacity-col" onClick={_ => this.changeTransformMode(null)}> <div className="field-label">Radius Bottom:</div> <input type="text" value={state.additionalAttributes.radiusBottom} onInput={(e) => { currentEntity.el.setAttribute('geometry', { radiusBottom: e.currentTarget.value }) this.setState((prevState) => { return { additionalAttributes: { ...prevState.additionalAttributes, radiusBottom: e.currentTarget.value } } }) }} onBlur={(e) => { this.changeObjectField('geometry.radiusBottom', state.additionalAttributes.radiusBottom) }} /> </div> } {animatableAttributes.cameraPreview && <div className="attribute-button preview-col"> <canvas ref={ref=>{ {/* props.model.setEditorInstance(this.editor) */} props.model.setCameraPreviewEl(ref) props.model.setEditorInstance(props.sceneContext.editor) props.model.renderCameraPreview(); }} /> </div>} </div> </div> ); } } export default TimelineInfoRenderer;<file_sep>/src/utils/fileSaver/saveAs.js /** * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API * https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL * https://www.npmjs.com/package/file-saver * @param {Object} obj - A File, Blob or MediaSource object to create an object URL for. * @param {string} fileName - The placeholder name of the file to be saved, appearing in the Save Dialog. */ const saveAs = (obj, fileName = 'untitled') => { const url = URL.createObjectURL(obj); const a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; a.href = url; console.log('object url:', url); a.download = fileName; a.click(); window.URL.revokeObjectURL(url); }; export default saveAs;<file_sep>/public/electron.js const electron = require('electron'); const app = electron.app; const ipcMain = electron.ipcMain; const BrowserWindow = electron.BrowserWindow; //const globalShortcut = electron.globalShortcut; const dialog = electron.dialog; const shell = electron.shell; const { appDirectory, config } = require('./globals/config'); const myPath = require('./utils/fileSystem/myPath'); const isDev = require('electron-is-dev'); const { fork } = require('child_process'); const { forEach } = require('p-iteration'); const jsoncParser = require('jsonc-parser'); const mime = require('./utils/fileSystem/mime'); const fileSystem = require('./utils/fileSystem/fileSystem'); const { write360ImageToTempPromise, write360ImageAsPartOfVideoToTempPromise, convertTempImageSequenceToVideoPromise } = require('./utils/captures/captures'); const ProjectFile = require('./utils/saveLoadProject/ProjectFile'); const { saveProjectToLocalAsync } = require('./utils/saveLoadProject/saveProject'); const { loadProjectByProjectFilePathAsync, copyTempProjectDirectoryToExternalDirectoryAsync } = require('./utils/saveLoadProject/loadProject'); const { openImageDialog, openGifDialog, openVideoDialog, openSchoolVrFileDialog, saveSchoolVrFileDialog, save360ImageDialogPromise, save360VideoDialogPromise } = require('./utils/aframeEditor/openFileDialog'); const { showYesNoQuestionMessageBox, showYesNoWarningMessageBox } = require('./utils/aframeEditor/showMessageBox'); const { parseDataToSaveFormat } = require('./utils/saveLoadProject/parseDataToSaveFormat'); const getIpAddress = require('./utils/network/getIpAddress'); const { getMacAddressHelper, getMacAddressPromiseHelper } = require('./utils/network/getMacAddress'); const shallowMergeObjects = require('./utils/js/shallowMergeObjects'); const { hashForUniqueId } = require('./utils/crypto'); const jsonStringifyFormatted = require('./utils/json/jsonStringifyFormatted'); const { isMac } = require('./utils/platform/platform'); console.log('node version:', process.version); /* constants */ const configFilePath = './config.jsonc'; // default values let webServerPort = 1413; //let webServerRootDirPath = __dirname; // public folder let splashScreenDurationInMillis = 2000; let developmentServerPort = process.env.PORT || 1234; const appAsarInstallationPath = appDirectory.appAsarInstallationPath; console.log(`appAsarInstallationPath: ${appAsarInstallationPath}`); const webServerRootDirectory = appDirectory.webServerRootDirectory; console.log(`webServerRootDirectory: ${webServerRootDirectory}`); const webServerFilesDirectory = appDirectory.webServerFilesDirectory; console.log(`webServerFilesDirectory: ${webServerFilesDirectory}`); const serverProgramPath = myPath.join( __dirname, 'server', 'socketio-server.js' ); /* end of constants */ /* global variables */ let mainWindow; // https://fabiofranchino.com/blog/use-electron-as-local-webserver/ // let webServerProcess = fork(`${myPath.join(__dirname, 'server', 'easyrtc-server.js')}`); let webServerProcess; let paramsFromExternalConfigForReact; /* end of global variables */ async function readConfigFileAsync(configFile) { const data = await fileSystem.readFilePromise(configFile); const configObj = jsoncParser.parse(data); const configObjForElectron = configObj.electron; paramsFromExternalConfigForReact = configObj.react; // set some global variables developmentServerPort = configObjForElectron.developmentServerPort || developmentServerPort; webServerPort = configObjForElectron.webServerPort || webServerPort; //webServerRootDirPath = configObjForElectron.webServerRootDirPath || webServerRootDirPath; splashScreenDurationInMillis = configObjForElectron.splashScreenDurationInMillis || splashScreenDurationInMillis; } function createWindow() { const Menu = electron.Menu; const MenuItem = electron.MenuItem; let mainWindowReady = false; let splashScreenCountdowned = false; const splashScreen = new BrowserWindow({ width: 583, height: 333, resizable: false, movable: false, frame: false, skipTaskbar: true, show: false, transparent: true }); /* setting up mainWindow */ mainWindow = new BrowserWindow({ width: 1440, height: 810, minWidth: 800, minHeight: 600, frame: false, show: false, webPreferences: { webSecurity: false } // for saving and loading assets via local path }); splashScreen.loadURL(`file://${myPath.join(__dirname, 'splash.html')}`); splashScreen.on('ready-to-show', async _ => { splashScreen.show(); // things to do on start up // splashScreen will be shown when we are doing these things // this setTimeout is to allow time for splash screen to show // before the thread is being blocked by running fileSystem.extractAll() or something like that setTimeout(async _ => { console.log('splash screen'); // delete any cached temp project files await ProjectFile.deleteAllTempProjectDirectoriesAsync(); // create App Data directories if they do not exist await forEach( appDirectory.createOnStartUpDirectories, async directoryPath => { console.log('Directory created:', directoryPath); await fileSystem.createDirectoryIfNotExistsPromise(directoryPath); } ); console.log('App directories created.'); await openWebServerAsync(); // hide splash screen setTimeout(_ => { splashScreenCountdowned = true; //mainWindow.loadURL(isDev ? `http://localhost:${developmentServerPort}/file-explorer` : `file://${myPath.join(__dirname, '../build/index.html')}`); //mainWindow.loadURL(isDev ? `http://localhost:${developmentServerPort}` : `file://${myPath.join(__dirname, '../build/index.html')}`); mainWindow.loadURL( isDev ? `http://localhost:${developmentServerPort}/projectlist` : `file://${myPath.join(__dirname, '../build/index.html')}` ); }, splashScreenDurationInMillis); }, 1000); }); /* main window lifecycles */ mainWindow.on('ready-to-show', () => { mainWindowReady = true; mainWindow.show(); splashScreen.close(); }); mainWindow.on('closed', () => { mainWindow = null; }); mainWindow.on('maximize', () => { mainWindow.webContents.send('maximize'); }); mainWindow.on('unmaximize', () => { mainWindow.webContents.send('unmaximize'); }); /* end of main window lifecycles */ /* end of setting up mainWindow */ /* setting up menu for hot keys purpose only */ const menu = new Menu(); menu.append( new MenuItem({ label: 'Toggle DevTools', accelerator: 'F12', click: _ => { mainWindow.webContents.toggleDevTools(); } }) ); // https://electronjs.org/docs/tutorial/keyboard-shortcuts // const ret = globalShortcut.register('F5', () => { // mainWindow.reload(); // }) menu.append( new MenuItem({ label: 'Refresh', accelerator: 'F5', click: _ => { mainWindow.reload(); } }) ); // all windows of this application share same menu Menu.setApplicationMenu(menu); /* end of setting up menu for hot keys purpose only */ } /* web server */ async function openWebServerAsync() { await fileSystem.myDeletePromise(webServerFilesDirectory); await fileSystem.createDirectoryIfNotExistsPromise(webServerFilesDirectory); webServerProcess = fork(serverProgramPath); console.log('Presentation port to use:', webServerPort); if (webServerProcess.connected) { // https://nodejs.org/api/child_process.html#child_process_subprocess_send_message_sendhandle_options_callback webServerProcess.send({ address: 'open-server', port: webServerPort, rootDirPath: webServerRootDirectory, filesDirPath: webServerFilesDirectory, webServerStaticFilesPathPrefix: config.webServerStaticFilesPathPrefix }); } } function closeWebServer() { if (webServerProcess) { if (webServerProcess.connected) { webServerProcess.send({ address: 'close-server' }); } else { webServerProcess.kill('SIGUSR1'); } } console.log('Web server closed.'); } /* end of web server */ /* app lifecycles */ app.on('ready', async _ => { try { await readConfigFileAsync(configFilePath); } catch (err) { console.error('ready Error:'); console.error(err); } createWindow(); }); app.on('window-all-closed', async _ => { console.log('window-all-closed'); // delete any cached temp project files await ProjectFile.deleteAllTempProjectDirectoriesAsync(); await forEach( appDirectory.deleteOnCloseDownDirectories, async directoryPath => { console.log('Directory deleted:', directoryPath); await fileSystem.myDeletePromise(directoryPath); } ); console.log('App directories deleted.'); // Always check if web server is closed when all windows are closed closeWebServer(); // TODO: Rationale behind isMac check (now commented out): // In mac, when all windows are closed, the app does not necessarily quit. // But this in-mac behaviour may require Application Menu implementation as well, // so that a window can be opened again after all windows are closed. //if (!isMac) { console.log('App quit.'); app.quit(); //} }); app.on('activate', () => { if (mainWindow === null) { createWindow(); } }); /* end of app lifecycles */ /* ipc main event listeners */ /** * !!! Important !!! * Note Error object cannot be passed as argument. */ function getSenderWindowFromEvent(ipcEvent) { return BrowserWindow.fromWebContents(ipcEvent.sender); } // ipcMain.on('invokeAction', (event, arg) => { // const result = processData(data); // event.sender.send('actionReply', result); // }); // config ipcMain.on('getParamsFromExternalConfig', (event, arg) => { event.sender.send('getParamsFromExternalConfigResponse', { err: null, data: paramsFromExternalConfigForReact }); }); // app // // https://github.com/electron/electron/blob/master/docs/api/app.md#appgetpathname ipcMain.on('getAppData', (event, arg) => { const data = { appName: app.getName(), homePath: app.getPath('home'), appDataPath: app.getPath('appData'), documentsPath: app.getPath('documents') }; event.sender.send('getAppDataResponse', { err: null, data: data }); }); // network interfaces ipcMain.on('getMacAddress', (event, arg) => { getMacAddressHelper.one(function (err, mac) { if (err) { console.error('getMacAddress Error:'); console.error(err); event.sender.send('getMacAddressResponse', { err: err.toString(), data: null }); return; } console.log('Mac address for this host: %s', mac); event.sender.send('getMacAddressResponse', { err: null, data: { mac: mac } }); }); }); // shell ipcMain.on('shellOpenItem', (event, arg) => { const filePath = arg; shell.openItem(filePath); }); ipcMain.on('shellOpenExternal', (event, arg) => { const url = arg; shell.openExternal(url); }); // electron window api ipcMain.on('newBrowserWindow', (event, arg) => { const windowOptions = arg.windowOptions; const url = arg.url; const newWindow = new BrowserWindow(windowOptions); newWindow.loadURL(url); event.sender.send('newBrowserWindowResponse', { err: null, data: { newWindow: newWindow } }); }); ipcMain.on('close', (event, arg) => { const senderWindow = getSenderWindowFromEvent(event); senderWindow.close(); }); ipcMain.on('minimize', (event, arg) => { const senderWindow = getSenderWindowFromEvent(event); senderWindow.minimize(); }); ipcMain.on('toggleMaximize', (event, arg) => { const senderWindow = getSenderWindowFromEvent(event); const isMaximizedOld = senderWindow.isMaximized(); if (isMaximizedOld) { senderWindow.unmaximize(); } else { senderWindow.maximize(); } event.sender.send('toggleMaximizeResponse', { err: null, data: { isMaximized: !isMaximizedOld } }); }); ipcMain.on('toggleDevTools', (event, arg) => { event.sender.toggleDevTools(); }); // fileSystem ipcMain.on('mimeStat', (event, arg) => { const filePath = arg; try { const mimeStat = mime.statSync(filePath); event.sender.send('mimeStatResponse', { err: null, data: { mimeStat: mimeStat } }); } catch (err) { console.error('mimeStat error'); console.error(err); event.sender.send('mimeStatResponse', { err: err.toString(), data: null }); } }); ipcMain.on('mimeStats', (event, arg) => { const filePaths = arg; try { const mimeStats = filePaths.map(filePath => mime.statSync(filePath)); event.sender.send('mimeStatsResponse', { err: null, data: { mimeStats: mimeStats } }); } catch (err) { console.error('mimeStats error'); console.error(err); event.sender.send('mimeStatsResponse', { err: err.toString(), data: null }); } }); ipcMain.on('base64Encode', async (event, arg) => { const filePath = arg; try { const encodedStr = await fileSystem.base64EncodePromise(filePath); event.sender.send('base64EncodeResponse', { err: null, data: { encodedStr: encodedStr } }); } catch (err) { console.error('base64Encode Error:'); console.error(err); event.sender.send('base64EncodeResponse', { err: err.toString(), data: null }); } }); ipcMain.on('base64Decode', async (event, arg) => { try { await fileSystem.base64DecodePromise( arg.locationToSaveFile, arg.encodedStr ); event.sender.send('base64DecodeResponse', { err: null }); } catch (err) { console.error('base64Decode Error:'); console.error(err); event.sender.send('base64DecodeResponse', { err: err.toString() }); } }); ipcMain.on('createPackage', async (event, arg) => { try { await fileSystem.createPackagePromise(arg.src, arg.dest); event.sender.send('createPackageResponse', { err: null }); } catch (err) { console.error('createPackage Error:'); console.error(err); event.sender.send('createPackageResponse', { err: err.toString() }); } }); ipcMain.on('extractAll', (event, arg) => { try { fileSystem.extractAll(arg.archive, arg.dest); event.sender.send('extractAllResponse', { err: null }); } catch (err) { console.error('extractAll Error:'); console.error(err); event.sender.send('extractAllResponse', { err: err.toString() }); } }); ipcMain.on('readdir', async (event, arg) => { try { const dirPath = arg; const fileNames = await fileSystem.readdirPromise(dirPath); event.sender.send('readdirResponse', { err: null, data: { fileNames: fileNames } }); } catch (err) { console.error('readdir Error:'); console.error(err); event.sender.send('readdirResponse', { err: err.toString(), data: null }); } }); ipcMain.on('readFile', async (event, arg) => { try { const filePath = arg; const content = await fileSystem.readFilePromise(filePath); event.sender.send('readFileResponse', { err: null, data: { content: content } }); } catch (err) { console.error('readFile Error:'); console.error(err); event.sender.send('readFileResponse', { err: err.toString(), data: null }); } }); ipcMain.on('writeFile', async (event, arg) => { try { await fileSystem.writeFilePromise(arg.filePath, arg.content); event.sender.send('writeFileResponse', { err: null }); } catch (err) { console.error('writeFile Error:'); console.error(err); event.sender.send('writeFileResponse', { err: err.toString() }); } }); ipcMain.on('deleteFile', async (event, arg) => { try { const filePath = arg; await fileSystem.myDeletePromise(filePath); event.sender.send('deleteFileResponse', { err: null }); } catch (err) { console.error('deleteFile Error:'); console.error(err); event.sender.send('deleteFileResponse', { err: err.toString() }); } }); ipcMain.on('renameFile', async (event, arg) => { try { await fileSystem.renamePromise(arg.oldPath, arg.newPath); event.sender.send('renameFileResponse', { err: null }); } catch (err) { console.error('renameFile Error:'); console.error(err); event.sender.send('renameFileResponse', { err: err.toString() }); } }); ipcMain.on('copyFile', async (event, arg) => { try { await fileSystem.copyFilePromise(arg.src, arg.dest); event.sender.send('copyFileResponse', { err: null }); } catch (err) { console.error('copyFile Error:'); console.error(err); event.sender.send('copyFileResponse', { err: err.toString() }); } }); // saveLoadProject ipcMain.on('listProjects', async (event, arg) => { console.log('listProjects'); const isLoadProjectJson = true; ProjectFile.listProjectsAsync(isLoadProjectJson) .then(projectFileObjs => { event.sender.send('listProjectsResponse', { err: null, data: { projectFileObjs: projectFileObjs } }); }) .catch(err => { console.error('listProjects Error:'); console.error(err); event.sender.send('listProjectsResponse', { err: err.toString(), data: null }); }); }); ipcMain.on('saveProject', (event, arg) => { saveProjectToLocalAsync(arg.projectFilePath, arg.entitiesList, arg.assetsList) .then(data => { event.sender.send('saveProjectResponse', { err: null, data: { projectJson: data } }); }) .catch(err => { console.error('saveProject Error:'); console.error(err); event.sender.send('saveProjectResponse', { err: err.toString(), data: null }); }); }); ipcMain.on('parseDataToSaveFormat', (event, arg) => { parseDataToSaveFormat(arg.projectName, arg.entitiesList, arg.assetsList) .then(data => { event.sender.send('parseDataToSaveFormatResponse', { err: null, data: { projectJson: data } }); }) .catch(err => { console.error('parseDataToSaveFormat Error:'); console.error(err); event.sender.send('parseDataToSaveFormatResponse', { err: err.toString(), data: null }); }); }); ipcMain.on('loadProjectByProjectFilePath', (event, arg) => { const filePath = arg; loadProjectByProjectFilePathAsync(filePath) .then(data => { event.sender.send('loadProjectByProjectFilePathResponse', { err: null, data: { projectJson: data } }); }) .catch(err => { console.error('loadProjectByProjectFilePath Error:'); console.error(err); event.sender.send('loadProjectByProjectFilePathResponse', { err: err.toString(), data: null }); }); }); ipcMain.on('isCurrentLoadedProject', (event, arg) => { const projectFilePath = arg; const isCurrentLoadedProject = ProjectFile.isCurrentLoadedProject( projectFilePath ); event.sender.send('isCurrentLoadedProjectResponse', { err: null, data: { isCurrentLoadedProject: isCurrentLoadedProject } }); }); // window dialog // call back arguments (_, filePaths) "faking" error first approach, for easy promisification ipcMain.on('openImageDialog', (event, arg) => { openImageDialog((_, filePaths) => { event.sender.send('openImageDialogResponse', { data: { filePaths: filePaths } }); }); }); ipcMain.on('openGifDialog', (event, arg) => { openGifDialog((_, filePaths) => { event.sender.send('openGifDialogResponse', { data: { filePaths: filePaths } }); }); }); ipcMain.on('openVideoDialog', (event, arg) => { openVideoDialog((_, filePaths) => { event.sender.send('openVideoDialogResponse', { data: { filePaths: filePaths } }); }); }); ipcMain.on('openSchoolVrFileDialog', (event, arg) => { openSchoolVrFileDialog((_, filePaths) => { event.sender.send('openSchoolVrFileDialogResponse', { data: { filePaths: filePaths } }); }); }); ipcMain.on('saveSchoolVrFileDialog', (event, arg) => { saveSchoolVrFileDialog((_, filePath) => { event.sender.send('saveSchoolVrFileDialogResponse', { data: { filePath: filePath } }); }); }); // vanilla electron dialog ipcMain.on('showOpenDialog', (event, arg) => { const options = arg; dialog.showOpenDialog(options, filePaths => { event.sender.send('showOpenDialogResponse', { data: { filePaths: filePaths } }); }); }); ipcMain.on('showSaveDialog', (event, arg) => { const options = arg; dialog.showOpenDialog(options, filePath => { event.sender.send('showSaveDialogResponse', { data: { filePath: filePath } }); }); }); // show message showMessageBox ipcMain.on('showYesNoQuestionMessageBox', (event, arg) => { showYesNoQuestionMessageBox(arg.message, arg.detail, response => { const btnId = response; event.sender.send('showYesNoQuestionMessageBoxResponse', { data: { buttonId: btnId } }); }); }); ipcMain.on('showYesNoWarningMessageBox', (event, arg) => { showYesNoWarningMessageBox(arg.message, arg.detail, response => { const btnId = response; event.sender.send('showYesNoWarningMessageBoxResponse', { data: { buttonId: btnId } }); }); }); // for presentation ipcMain.on('getPresentationServerInfo', (event, arg) => { const interfaceIpMap = getIpAddress.getAllIps(); event.sender.send('getPresentationServerInfoResponse', { data: { interfaceIpMap: interfaceIpMap, port: webServerPort } }); }); ipcMain.on('openWebServerAndLoadProject', async (event, arg) => { try { /* load project file */ const filePath = arg; //console.log(`filePath: ${filePath}`); const projectFile = new ProjectFile(null, filePath, null); const hashedFilePath = projectFile.hashedSavedProjectFilePath; //console.log(`hashedFilePath: ${hashedFilePath}`); const staticAssetUrlPathPrefixForWebPresentation = myPath.join( config.webServerStaticFilesPathPrefix, hashedFilePath ); //console.log(`staticAssetUrlPathPrefixForWebPresentation: ${staticAssetUrlPathPrefixForWebPresentation}`); const projectJson = await loadProjectByProjectFilePathAsync(filePath); //console.log(projectJson); // TODO: poorly written (too many cross-references to ProjectFile class) // add staticAssetUrlPathPrefixForWebPresentation to asset's relativeSrc const newlyModifiedProjectJson = Object.assign({}, projectJson); newlyModifiedProjectJson.assetsList.forEach(asset => { const assetRelativeSrc = asset.relativeSrc; if (ProjectFile.isAssetPathRelative(assetRelativeSrc)) { asset.relativeSrc = myPath.join( staticAssetUrlPathPrefixForWebPresentation, assetRelativeSrc ); } }); /* end of load project file */ /* open web server */ // await openWebServerAsync(); const externalServerDirectory = myPath.join( webServerFilesDirectory, hashedFilePath ); await copyTempProjectDirectoryToExternalDirectoryAsync( filePath, externalServerDirectory ); /* end of open web server */ event.sender.send('openWebServerAndLoadProjectResponse', { err: null, data: { projectJson: newlyModifiedProjectJson } }); } catch (err) { console.error('openWebServerAndLoadProject Error:'); console.error(err); event.sender.send('openWebServerAndLoadProjectResponse', { err: err.toString(), data: null }); } }); ipcMain.on('closeWebServer', (event, arg) => { closeWebServer(); event.sender.send('closeWebServerResponse', { err: null }); }); // customized app data const getCustomizedAppDataObjFromFilePromise = async _ => { const appDataFileContent = await fileSystem.readFilePromise( appDirectory.customizedAppDataFile ); return JSON.parse(appDataFileContent); }; const mergeAndSetCustomizedAppDataObjToFilePromise = async objToMerge => { let existingObj = {}; try { existingObj = await getCustomizedAppDataObjFromFilePromise(); } catch (err) { console.error('mergeAndSetCustomizedAppDataObjToFilePromise Error:'); console.error(err); // silense customize app data file not existing error } const mergedObj = shallowMergeObjects(existingObj, objToMerge); const mergedObjStr = jsonStringifyFormatted(mergedObj); await fileSystem.writeFilePromise( appDirectory.customizedAppDataFile, mergedObjStr ); }; ipcMain.on('getCustomizedAppData', async (event, arg) => { try { const appDataObj = await getCustomizedAppDataObjFromFilePromise(); const appDataObjStr = JSON.stringify(appDataObj); event.sender.send('getCustomizedAppDataResponse', { err: null, data: { appDataObjStr: appDataObjStr } }); } catch (err) { console.error('getCustomizedAppData Error:'); console.error(err); event.sender.send('getCustomizedAppDataResponse', { err: err.toString(), data: null }); } }); ipcMain.on('setCustomizedAppData', async (event, arg) => { try { await mergeAndSetCustomizedAppDataObjToFilePromise( JSON.parse(arg.appDataObjStr) ); event.sender.send('setCustomizedAppDataResponse', { err: null }); } catch (err) { console.error('setCustomizedAppData Error:'); console.error(err); event.sender.send('setCustomizedAppDataResponse', { err: err.toString() }); } }); function getEvenIdxOfStr(str) { if (!str) { return ''; } const chars = str.split(''); const evenChars = chars.filter((_, idx) => idx % 2 === 0); return evenChars.join(); } const identityKeySpecialDelimiter = ':::::'; const encodeIdentityKeyPromise = async licenseKey => { const macAddress = await getMacAddressPromiseHelper.one(); return ( licenseKey + identityKeySpecialDelimiter + hashForUniqueId(licenseKey + getEvenIdxOfStr(macAddress)) ); }; const decodeIdentityKeyPromise = async _ => { const appDataObj = await getCustomizedAppDataObjFromFilePromise(); const identityKey = appDataObj.identityKey; if (!identityKey) { return null; } const identityKeySplitted = identityKey.split(identityKeySpecialDelimiter); if (identityKeySplitted.length !== 2) { return null; } const licenseKey = identityKeySplitted[0]; return { identityKey, licenseKey }; }; ipcMain.on('checkIdentity', async (event, arg) => { let isIdentityValid = false; try { const decodeIdentityKeyObj = await decodeIdentityKeyPromise(); if (decodeIdentityKeyObj) { const { identityKey, licenseKey } = decodeIdentityKeyObj; const supposedIdentityKey = await encodeIdentityKeyPromise(licenseKey); isIdentityValid = supposedIdentityKey === identityKey; } } catch (err) { console.error('checkIdentity Error:'); console.error(err); // silense error } event.sender.send('checkIdentityResponse', { err: null, data: { isIdentityValid: isIdentityValid } }); }); ipcMain.on('setLicenseKey', async (event, arg) => { try { const licenseKeyInput = arg.licenseKey; const identityKey = licenseKeyInput ? await encodeIdentityKeyPromise(licenseKeyInput) : ''; await mergeAndSetCustomizedAppDataObjToFilePromise({ identityKey: identityKey }); event.sender.send('setLicenseKeyResponse', { err: null }); } catch (err) { console.error('setLicenseKey Error:'); console.error(err); event.sender.send('setLicenseKeyResponse', { err: err.toString() }); } }); // 360 capture ipcMain.on('saveRaw360Capture', async (event, arg) => { // use let because I will have to use tmpImg in finally block let tmpImgFilePath; const imgBase64Str = arg.imgBase64Str; try { tmpImgFilePath = await write360ImageToTempPromise(imgBase64Str); const filePathToSave = await save360ImageDialogPromise(); console.log('tmpImgFilePath:', tmpImgFilePath); if (!filePathToSave) { event.sender.send('saveRaw360CaptureResponse', { err: null, data: null }); return; } await fileSystem.renamePromise(tmpImgFilePath, filePathToSave); event.sender.send('saveRaw360CaptureResponse', { err: null, data: { filePath: filePathToSave } }); } catch (err) { console.error('saveRaw360Capture Error:'); console.error(err); event.sender.send('saveRaw360CaptureResponse', { err: err.toString() }); } finally { // if (tmpImgFilePath) { // const tmpImgDirPath = myPath.dirname(tmpImgFilePath); // fileSystem.myDelete(tmpImgDirPath, (err) => { // if (err) { // // silence error // console.error('saveRaw360Capture deleting temp image Error:'); // console.error(err); // } // }); // } } }); ipcMain.on('saveRaw360CaptureForVideo', async (event, arg) => { // use let because I will have to use tmpImg in finally block let tmpImgFilePath; const videoUuid = arg.videoUuid; const fps = arg.fps; const currentFrame = arg.currentFrame; const totalFrame = arg.totalFrame; const imgBase64Str = arg.imgBase64Str; /** * if totalFrame is 30, * then currentFrame ranges from 0 to 30. * i.e. total number of frames is 30 */ const isLastFrame = currentFrame === totalFrame; try { tmpImgFilePath = await write360ImageAsPartOfVideoToTempPromise( videoUuid, currentFrame, imgBase64Str ); if (isLastFrame) { const outputVideoTempPath = await convertTempImageSequenceToVideoPromise( videoUuid, fps ); const filePathToSave = await save360VideoDialogPromise(); if (!filePathToSave) { event.sender.send('saveRaw360CaptureForVideoResponse', { err: null, data: null }); return; } await fileSystem.renamePromise(outputVideoTempPath, filePathToSave); event.sender.send('saveRaw360CaptureForVideoResponse', { err: null, data: { filePath: filePathToSave } }); } else { event.sender.send('saveRaw360CaptureForVideoResponse', { err: null, data: { filePath: tmpImgFilePath } }); } } catch (err) { console.error('saveRaw360CaptureForVideo Error:'); console.error(err); event.sender.send('saveRaw360CaptureForVideoResponse', { err: err.toString() }); } finally { // if (tmpImgFilePath) { // const tmpImgDirPath = myPath.dirname(tmpImgFilePath); // fileSystem.myDelete(tmpImgDirPath, (err) => { // if (err) { // // silence error // console.error('saveRaw360Capture deleting temp image Error:'); // console.error(err); // } // }); // } } }); /* end of ipc main event listeners */ /* * doing a cleanup action just before Node.js exits * https://stackoverflow.com/questions/14031763/doing-a-cleanup-action-just-before-node-js-exits */ function exitHandler(options, exitCode) { if (options.cleanup) { console.log('electron-main exitHandler: cleanup'); closeServer(); } if (exitCode || exitCode === 0) { console.log('electron-main exitHandler exitCode:', exitCode); } if (options.exit) { process.exit(); } } //do something when app is closing process.on('exit', _ => { console.log('electron-main on: exit'); }); //catches ctrl+c event process.on('SIGINT', _ => { console.log('electron-main on: SIGINT'); exitHandler.bind(null, { exit: true, clean: true }); }); // catches "kill pid" (for example: nodemon restart) process.on('SIGUSR1', _ => { console.log('electron-main on: SIGUSR1'); exitHandler.bind(null, { exit: true, clean: true }); }); process.on('SIGUSR2', _ => { console.log('electron-main on: SIGUSR2'); exitHandler.bind(null, { exit: true, clean: true }); }); //catches uncaught exceptions // https://stackoverflow.com/questions/40867345/catch-all-uncaughtexception-for-node-js-app process .on('unhandledRejection', (reason, p) => { console.error( 'electron-main on unhandledRejection:', reason, 'Unhandled Rejection at Promise', p ); }) .on('uncaughtException', err => { console.error( 'electron-main on uncaughtException:', err, 'Uncaught Exception thrown' ); process.exit(1); }); /* end of doing a cleanup action just before Node.js exits */ <file_sep>/src/pages/aframeEditor/viewerPage.js import React, {Component} from 'react'; import {withSceneContext} from 'globals/contexts/sceneContext'; import MenuComponent from 'components/menuComponent'; import ButtonsPanel from 'containers/aframeEditor/homePage/buttonsPanel'; import AFramePanel from 'containers/aframeEditor/homePage/aFramePanel'; import InfoPanel from 'containers/aframeEditor/homePage/infoPanel'; import SlidesPanel from 'containers/aframeEditor/homePage/slidesPanel'; import TimelinePanel from 'containers/aframeEditor/homePage/timelinePanel'; // import AssetsPanel from 'containers/aframeEditor/homePage/assetsPanel'; import io from 'socket.io-client'; import Editor from 'vendor/editor.js'; // import Editor from 'vendor/editor.js'; // import {addEntityAutoType} from 'utils/aFrameEntities'; // import {roundTo, jsonCopy} from 'globals/helperfunctions'; // import {TweenMax, TimelineMax, Linear} from 'gsap'; import './viewerPage.css'; const Events = require('vendor/Events.js'); // const io = require('socket.io-client'); // or with import syntax // const jsonSchemaValidator = require('jsonschema').Validator; // const validator = new jsonSchemaValidator(); // const schema = require('schema/aframe_schema_20181108.json'); class ViewerPage extends Component { constructor(props) { super(props); this.inited = false; this.state = { socket: null } // this.onEditorLoad = this.onEditorLoad.bind(this); // Events.on('editor-load', this.onEditorLoad); } componentDidMount() { const props = this.props; const sceneContext = props.sceneContext; this.editor = new Editor(); Events.on('editor-load', (editor) => { editor.close(); editor.currentCameraEl.removeAttribute('wasd-controls'); }) sceneContext.updateEditor(this.editor); // TODO // need to get the current machine ip and port from ipc const socket = io(window.location.origin); // const socket = io('http://10.0.1.111:1413'); socket.on('connect', () => { console.log('connected!!!'); // socket.connected); // true socket.emit('registerViewer'); }); socket.on('serverMsg', (msg) => { console.log('message from server: ', msg); }) socket.on('updateSceneData', (sceneData) => { console.log('sceneData recieved'); const autoInit = setInterval(() => { if (sceneContext.editor) { sceneContext.loadProject(sceneData); clearInterval(autoInit); } }, 100) }) socket.on('updateSceneStatus', (statusMsg) => { console.log('sceneStatus recieved: ', statusMsg); /** * statusMsg * action * details * slideId ? */ const autoPlay = true; switch (statusMsg.action) { case 'selectSlide': { sceneContext.selectSlide( statusMsg.details.slideId, statusMsg.details.autoPlay ); break; } case 'playSlide': { sceneContext.playSlide() break; } } }) this.setState({ socket: socket }) } componentWillUnmount() { if (this.state.socket) { this.state.socket.close(); } } // onClick() { // // socket.emit('roomCreate', 'room A') // } render() { const state = this.state; const sceneContext = this.props.sceneContext; return ( <div id="viewer"> {/* <LanguageContextConsumer render={ ({ language, messages }) => ( <Prompt when={true} message={messages['Prompt.UnsavedWorkMessage']} /> ) } /> */} {/* <SystemPanel projectName={this.projectName} /> */} {/* <MenuComponent // projectName="Untitled_1" menuButtons={[ { label: 'File', // onClick: _=> { console.log('file') }, children: [ { label: 'New', disabled: false, onClick: _=> { console.log('new'); // test open file with user defined extension // const fileDialog = document.createElement('input'); // fileDialog.type = 'file'; // fileDialog.multiple = true; // fileDialog.accept = ['image/x-png','image/gif']; // fileDialog.click(); } }, { label: 'Open', disabled: false, onClick: _=> { console.log('open') } }, { label: '-' }, { label: 'Exit', disabled: false, onClick: _=> { console.log('exit') } } ] } ]} /> */} {/* <ButtonsPanel /> */} <AFramePanel disableVR={false} user-mode="viewer" /> {/* <SlidesPanel isEditing={false} /> */} {/* <TimelinePanel /> */} {/* <InfoPanel /> */} </div> ); } } export default withSceneContext(ViewerPage); <file_sep>/src/utils/dateTime/formatDateTime.js import moment from 'moment'; // https://momentjs.com/ const dateFormatDefault = "YYYY/MM/DD"; const timeFormatDefault = "HH:mm"; const dateTimeFormatDefault = `${dateFormatDefault} ${timeFormatDefault}`; const dateTimeFormatForFileName = 'YYYY-MM-DD' + 'T' + 'HH-mm-ss'; const formatDate = (dateObj, format = dateFormatDefault) => { return moment(dateObj).format(format); }; const formatTime = (dateObj, format = timeFormatDefault) => { return moment(dateObj).format(format); }; const formatDateTime = (dateObj, format = dateTimeFormatDefault) => { return moment(dateObj).format(format); }; const formatDateTimeForFileName = (dateObj) => { return formatDateTime(dateObj, dateTimeFormatForFileName); } export { formatDate, formatTime, formatDateTime, formatDateTimeForFileName };<file_sep>/src/utils/aframeEditor/helperfunctions.js const Events = require('vendor/Events.js'); const uuid = require('uuid/v1'); let editor = null; Events.on('editor-load', obj => { editor = obj; }); function roundTo(num, digit) { return Math.round(num * Math.pow(10,digit)) / Math.pow(10,digit); } function jsonCopy(src) { return JSON.parse(JSON.stringify(src)); } function rgba2hex(rgb) { if (!rgb) return '#FFFFFF'; const parsedrgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i); return (parsedrgb && parsedrgb.length === 4) ? "#" + ("0" + parseInt(parsedrgb[1],10).toString(16)).slice(-2) + ("0" + parseInt(parsedrgb[2],10).toString(16)).slice(-2) + ("0" + parseInt(parsedrgb[3],10).toString(16)).slice(-2) : rgb; } function isClockwise(vertices=[]) { const len = vertices.length; let sum = vertices.map(({x, y}, index) => { let nextIndex = index + 1; if (nextIndex === len) nextIndex = 0; return { x1: x, x2: vertices[nextIndex].x, y1: x, y2: vertices[nextIndex].x }; }); console.log(sum); sum = sum.map(({ x1, x2, y1, y2}) => ((x2 - x1) * (y1 + y2))); console.log(sum); sum = sum.reduce((a, b) => a + b); console.log(sum); if (sum > 0) return true; if (sum <= 0) return false; } function polygonArea(vertices=[]) { const len = vertices.length; let sum = 0; vertices.forEach(({x, y}, index) => { let nextIndex = index + 1; if (nextIndex === len) nextIndex = 0; sum += x * vertices[nextIndex].y - y * vertices[nextIndex].x; }); return sum; } function addToAsset(el) { let assetEl = document.querySelector('a-asset'); if (!assetEl) { assetEl = document.createElement('a-asset'); editor.sceneEl.append(assetEl); } assetEl.append(el); const newId = uuid(); // switch (el.tagName) { // case 'VIDEO': // el.loop = true; // break; // case 'IMG': // break; // default: // console.log('editorFunctions_addToAsset: ???'); // } el.setAttribute('id', newId); return newId; } export {roundTo, jsonCopy, rgba2hex, isClockwise, polygonArea, addToAsset}<file_sep>/src/utils/aframeEditor/aBox.js import AEntity from "./aEntity"; class ABox extends AEntity { constructor(el) { super(el); this._messageId = 'SceneObjects.Box.DefaultName'; this._type = 'a-box'; this._animatableAttributes = { position: ['x', 'y', 'z'], scale: ['x', 'y', 'z'], rotation: ['x', 'y', 'z'], material: [ 'color', 'opacity' ] } this._staticAttributes = [ { type: 'image', name: 'Texture', attributeKey: 'material', attributeField: 'src' } ] this._fixedAttributes = { geometry: { primitive: 'box' } } this._animatableAttributesValues = { position: { x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 }, rotation: { x: 0, y: 0, z: 0 }, material: { color: '#FFFFFF', opacity: 1 } } } } export default ABox;<file_sep>/public/utils/platform/platform.js const platformName = process.platform.toLowerCase(); console.log('platformName:', platformName); const isMac = platformName === 'darwin'; console.log('isMac:', isMac); module.exports = { platformName, isMac, };<file_sep>/src/containers/aframeEditor/homePage/infoPanel/infoTypeBackground.js /* info generation of right panel */ import React, {Component} from 'react'; import {roundTo, addToAsset, rgba2hex} from 'globals/helperfunctions'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome' import {Rnd as ResizableAndDraggable} from 'react-rnd'; import './infoTypeBackground.css'; var Events = require('vendor/Events.js'); class InfoTypeBackground extends Component { constructor(props) { super(props); const self = this; this.changeObjectField = this.changeObjectField.bind(this); } componentDidMount() { } componentDidUpdate() { } componentWillUnmount() { } changeObjectField(field, value) { const tmp = {}; tmp[field] = value; Events.emit('updateSelectedEntityAttribute', tmp); } render() { const props = this.props; const data = props.timelineObj[props.timelinePosition]; const color = rgba2hex(data.background.color); return ( <div className="animatable-params"> <div className="attribute-col color-col"> <label title={color}> <div className="field-label">Color:</div><div className="color-preview" style={{backgroundColor: color}}/> <input type="color" value={color} onChange={(event) => this.changeObjectField('background.color', event.target.value)} hidden/> </label> </div> </div> ); } } export default InfoTypeBackground;<file_sep>/src/globals/contexts/locale/localizedData.js import {languages} from 'globals/config'; const localizedData = { [languages.english.code]: { /* menu */ "Menu.FileLabel": "File", "Menu.File.HomeLabel": "Home", "Menu.File.NewLabel": "New", "Menu.File.OpenLabel": "Open", "Menu.File.ExitLabel": "Exit", "Menu.LanguageLabel": "Language", "Menu.Language.English": "English", "Menu.Language.TraditionalChinese": "繁體中文", "Menu.CaptureImageLabel": "Capture Image", "Menu.CaptureImage.Normal": "Normal", "Menu.CaptureImage.360_2k": "360 (2K)", "Menu.CaptureImage.360_4k": "360 (4K)", "Menu.CaptureVideoLabel": "Capture Video", "Menu.CaptureVideo.360_2k": "360 (2K)", "Menu.CaptureVideo.360_4k": "360 (4K)", /* end of menu */ /* prompt */ "Prompt.UnsavedWorkMessage": "You have unsaved changes, are you sure you want to leave?", "Prompt.IncompleteRecordingMessage": "Your recording is incomplete, are you sure you want to leave?", "Prompt.AutenticationFailTitle": "Authentication", "Prompt.AutenticationFailMessage": "Authentication failed. Please contact IOIO Creative or enter your license key.", "Alert.AutenticationFailMessage": "Authenication failed.", "Alert.AutenticationSuccessMessage": "Authentication succeeded.", "Alert.CaptureSavedMessage": "Capture saved.", "Alert.ProjectSavedMessage": "Project saved.", /* end of prompt */ /* navigation */ "Navigation.SlideSelect.SlideIndexPrefix": "Slide", /* end of navigation */ /* project list page */ "ProjectOrderSelect.Options.MostRecentLabel": "Most recent", "ProjectOrderSelect.Options.LeastRecentLabel": "Least recent", "ProjectOrderSelect.Options.ByNameLabel": "By name", "ProjectOrderSelect.Options.ByNameReverseLabel": "By name reverse", "ProjectItem.Info.LastAccessedLabel": "Last accessed", "ProjectItem.Handles.PreviewLabel": "Preview", "ProjectItem.Handles.EditLabel": "Edit", "ProjectItem.Handles.OptionsLabel": "Options", "ProjectItem.Handles.RenameLabel": "Rename", "ProjectItem.Handles.CopyToNewLabel": "Copy to New", "ProjectItem.Handles.DeleteLabel": "Delete", "ProjectSearch.PlaceHolderLabel": "project name", /* end of project list page */ /* editor page */ "Menu.File.SaveLabel": "Save", "Menu.File.SaveAsLabel": "Save As...", "Menu.EditLabel": "Edit", "Menu.Edit.UndoLabel": "Undo", "Menu.Edit.RedoLabel": "Redo", "SceneObjects.Camera.DefaultName": "camera", "SceneObjects.Entity.DefaultName": "entity", "SceneObjects.Plane.DefaultName": "plane", "AddThingsPanel.ThreeD.AddBoxTooltip": "Add a box", "SceneObjects.Box.DefaultName": "box", "AddThingsPanel.ThreeD.AddSphereTooltip": "Add a sphere", "SceneObjects.Sphere.DefaultName": "sphere", "AddThingsPanel.ThreeD.AddTetrahedronTooltip": "Add a tetrahedron", "SceneObjects.Tetrahedron.DefaultName": "tetrahedron", "AddThingsPanel.ThreeD.AddPyramidTooltip": "Add a pyramid", "SceneObjects.Pyramid.DefaultName": "pyramid", "AddThingsPanel.ThreeD.AddCylinderTooltip": "Add a cylinder", "SceneObjects.Cylinder.DefaultName": "cylinder", "AddThingsPanel.ThreeD.AddConeTooltip": "Add a cone", "SceneObjects.Cone.DefaultName": "cone", "AddThingsPanel.TwoD.AddImageTooltip": "Add an image", "SceneObjects.Image.DefaultName": "image", "AddThingsPanel.TwoD.AddVideoTooltip": "Add a video", "SceneObjects.Video.DefaultName": "video", "AddThingsPanel.TwoD.AddTextTooltip": "Add a text", "SceneObjects.Text.DefaultName": "text", "AddThingsPanel.TwoD.AddSkyTooltip": "Add a sky", "SceneObjects.Sky.DefaultName": "sky", "AddThingsPanel.TwoD.AddNavigationTooltip": "Add a navigation", "SceneObjects.Navigation.DefaultName": "navigation", "PresentationPreparationPanel.ResetViewTooltip": "Reset view", "PresentationPreparationPanel.PlayTimelineTooltip": "Play timeline", "PresentationPreparationPanel.ShareLabel": "Share", "EditThingPanel.AddAnimationLabel": "Click to add animation", "EditThingPanel.TransformModes.TranslateLabel": "Position", "EditThingPanel.TransformModes.TranslateTooltip": "Translate", "EditThingPanel.TransformModes.RotateLabel": "Rotate", "EditThingPanel.TransformModes.RotateTooltip": "Rotate", "EditThingPanel.TransformModes.ScaleLabel": "Scale", "EditThingPanel.TransformModes.ScaleTooltip": "Scale", "EditThingPanel.TransformModes.RotateResetLabel": "Reset Rotation", "EditThingPanel.TransformModes.RotateResetTooltip": "Reset rotation", "EditThingPanel.Color.ColorLabel": "Color", "EditThingPanel.Color.OpacityLabel": "Opacity", "EditThingPanel.AddTextureLabel": "Add Texture", "EditThingPanel.AddVideoLabel": "Add Video", "EditThingPanel.Text.TextColorLabel": "Text Color", "EditThingPanel.Text.TextOpacityLabel": "Text Opacity", "EditThingPanel.Text.TextPlaceholder": "Input your text here", "EditThingPanel.Text.SizeLabel": "Size:", "EditThingPanel.Navigation.SelectSlideLabel": "Select Slide", "EditThingPanel.Navigation.CurrentSlideSuffix": "(This Slide)", "TimelinePanel.HeaderLabel": "Timeline", "TimelinePanel.AddAnimationLabel": "Add animation +", "TimelinePanel.Entity.ContextMenu.CopyLabel": "Copy object", "PreviewPanel.BackLabel": "Back", /* end of editor page */ /* presenter page */ "PresentationPanel.ExitLabel": "Exit", /* end of presenter page */ }, [languages.traditionalChinese.code]: { /* menu */ "Menu.FileLabel": "檔案", "Menu.File.HomeLabel": "主頁", "Menu.File.NewLabel": "開新専案", "Menu.File.OpenLabel": "開啟舊檔", "Menu.File.ExitLabel": "關閉 School VR", "Menu.LanguageLabel": "語言", "Menu.Language.English": "English", "Menu.Language.TraditionalChinese": "繁體中文", "Menu.CaptureImageLabel": "拍攝圖片", "Menu.CaptureImage.Normal": "長方", "Menu.CaptureImage.360_2k": "360 (2K)", "Menu.CaptureImage.360_4k": "360 (4K)", "Menu.CaptureVideoLabel": "拍攝視頻", "Menu.CaptureVideo.360_2k": "360 (2K)", "Menu.CaptureVideo.360_4k": "360 (4K)", /* end of menu */ /* prompt */ "Prompt.UnsavedWorkMessage": "您有未保存的更改,確定要離開嗎?", "Prompt.IncompleteRecordingMessage": "您有未完成的錄影,確定要離開嗎?", "Prompt.AutenticationFailTitle": "身份驗證", "Prompt.AutenticationFailMessage": "身份驗證失敗。請聯繫IOIO Creative或輸入您的許可證密鑰。", "Alert.AutenticationFailMessage": "身份驗證失敗。", "Alert.AutenticationSuccessMessage": "身份驗證成功。", "Alert.CaptureSavedMessage": "拍攝儲存成功", "Alert.ProjectSavedMessage": "専案儲存成功", /* end of prompt */ /* navigation */ "Navigation.SlideSelect.SlideIndexPrefix": "投影片", /* end of navigation */ /* project list page */ "ProjectOrderSelect.Options.MostRecentLabel": "時間最近", "ProjectOrderSelect.Options.LeastRecentLabel": "時間最遠", "ProjectOrderSelect.Options.ByNameLabel": "檔名順序", "ProjectOrderSelect.Options.ByNameReverseLabel": "檔名逆序", "ProjectItem.Info.LastAccessedLabel": "上次訪問", "ProjectItem.Handles.PreviewLabel": "簡報模式", "ProjectItem.Handles.EditLabel": "編輯", "ProjectItem.Handles.OptionsLabel": "選項", "ProjectItem.Handles.RenameLabel": "改名", "ProjectItem.Handles.CopyToNewLabel": "複製到新", "ProjectItem.Handles.DeleteLabel": "刪除", "ProjectSearch.PlaceHolderLabel": "専案名稱", /* end of project list page */ /* editor page */ "Menu.File.SaveLabel": "儲存専案", "Menu.File.SaveAsLabel": "另存新檔", "Menu.EditLabel": "編輯", "Menu.Edit.UndoLabel": "上一步", "Menu.Edit.RedoLabel": "下一步", "SceneObjects.Camera.DefaultName": "相機", "SceneObjects.Entity.DefaultName": "物件", "SceneObjects.Plane.DefaultName": "平面", "AddThingsPanel.ThreeD.AddBoxTooltip": "加立方體", "SceneObjects.Box.DefaultName": "立方體", "AddThingsPanel.ThreeD.AddSphereTooltip": "加球體", "SceneObjects.Sphere.DefaultName": "球體", "AddThingsPanel.ThreeD.AddTetrahedronTooltip": "加四面體", "SceneObjects.Tetrahedron.DefaultName": "四面體", "AddThingsPanel.ThreeD.AddPyramidTooltip": "加金字塔", "SceneObjects.Pyramid.DefaultName": "金字塔", "AddThingsPanel.ThreeD.AddCylinderTooltip": "加圓柱體", "SceneObjects.Cylinder.DefaultName": "圓柱體", "AddThingsPanel.ThreeD.AddConeTooltip": "加圓錐體", "SceneObjects.Cone.DefaultName": "圓錐體", "AddThingsPanel.TwoD.AddImageTooltip": "加圖片", "SceneObjects.Image.DefaultName": "圖片", "AddThingsPanel.TwoD.AddVideoTooltip": "加影片", "SceneObjects.Video.DefaultName": "影片", "AddThingsPanel.TwoD.AddTextTooltip": "加文字", "SceneObjects.Text.DefaultName": "文字", "AddThingsPanel.TwoD.AddSkyTooltip": "加天幕", "SceneObjects.Sky.DefaultName": "天幕", "AddThingsPanel.TwoD.AddNavigationTooltip": "加隨意門", "SceneObjects.Navigation.DefaultName": "隨意門", "PresentationPreparationPanel.ResetViewTooltip": "重置視角", "PresentationPreparationPanel.PlayTimelineTooltip": "播放時間線", "PresentationPreparationPanel.ShareLabel": "分享", "EditThingPanel.AddAnimationLabel": "點擊添加動畫", "EditThingPanel.TransformModes.TranslateLabel": "移位", "EditThingPanel.TransformModes.TranslateTooltip": "移位", "EditThingPanel.TransformModes.RotateLabel": "旋轉", "EditThingPanel.TransformModes.RotateTooltip": "旋轉", "EditThingPanel.TransformModes.ScaleLabel": "縮放", "EditThingPanel.TransformModes.ScaleTooltip": "縮放", "EditThingPanel.TransformModes.RotateResetLabel": "重置旋轉", "EditThingPanel.TransformModes.RotateResetTooltip": "重置\n旋轉", "EditThingPanel.Color.ColorLabel": "顏色", "EditThingPanel.Color.OpacityLabel": "不透明度", "EditThingPanel.AddTextureLabel": "加質地圖片", "EditThingPanel.AddVideoLabel": "加影片", "EditThingPanel.Text.TextColorLabel": "文字顏色", "EditThingPanel.Text.TextOpacityLabel": "文字不透明度", "EditThingPanel.Text.TextPlaceholder": "在這裡輸入文字", "EditThingPanel.Text.SizeLabel": "文字大小:", "EditThingPanel.Navigation.SelectSlideLabel": "選擇投影片", "EditThingPanel.Navigation.CurrentSlideSuffix": "(編輯中的投影片)", "TimelinePanel.HeaderLabel": "時間線", "TimelinePanel.AddAnimationLabel": "添加動畫 +", "TimelinePanel.Entity.ContextMenu.CopyLabel": "複製物件", "PreviewPanel.BackLabel": "返回", /* end of editor page */ /* presenter page */ "PresentationPanel.ExitLabel": "離開簡報模式", /* end of presenter page */ } } export default localizedData;<file_sep>/public/utils/base64/fromBase64Str.js module.exports = function fromBase64Str(base64EncodedStr) { return Buffer.from(base64EncodedStr, 'base64'); };<file_sep>/src/containers/aframeEditor/homePage/slidesPanel.js /* Left Panel should be similar to slides in powerpoint ( ▭ ) ▫▫▫▫▫▫▫▫▫▫▫ ▭ ┌──────┐ ▭ │AFRAME│ ▭ └──────◲ */ import React, {Component, Fragment} from 'react'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; import {withSceneContext} from 'globals/contexts/sceneContext'; import {TweenMax} from 'gsap'; // import {SortableContainer, SortableElement} from 'react-sortable-hoc'; // import EntitiesList from 'containers/panelItem/entitiesList'; import './slidesPanel.css'; //const Events = require('vendor/Events.js'); class SortableList extends Component { constructor(props) { super(props); this.state = { sourceElement: null, originalIdx: null, newIdx: null, currentElement: null, startX: null, startY: null, isHoverDeleteEl: false, }; [ 'onSortStart', 'onSorting', 'onSortEnd', ].forEach(methodName => { this[methodName] = this[methodName].bind(this); }) } componentDidMount() {} componentWillUnmount() { if (this.state.currentElement) { document.removeEventListener('mousemove', this.onSorting); document.removeEventListener('mouseup', this.onSortEnd); this.state.currentElement.removeEventListener('touchmove', this.onSorting); this.state.currentElement.removeEventListener('touchend', this.onSortEnd); } } onSortStart(event) { const props = this.props; if (props.children.length < 2) { return; } const state = this.state; const pointer = event.changedTouches ? event.changedTouches[ 0 ] : event; const targetElement = event.currentTarget; const originalIdx = [...targetElement.parentNode.children].indexOf(targetElement); const targetElementCloned = event.currentTarget.cloneNode(true); const onSortStart = props.onSortStart; const onSortEnd = props.onSortEnd; if (props.disabled) { if (typeof(onSortEnd) === "function") { onSortEnd( originalIdx, originalIdx ); } return; } if (typeof(onSortStart) === "function") { onSortStart( originalIdx ); } targetElementCloned.classList.add('cloned'); targetElementCloned.classList.remove('selected'); const eventType = event.type; targetElement.parentNode.appendChild(targetElementCloned); TweenMax.set(targetElementCloned, { position: 'absolute', left: targetElement.offsetLeft, top: targetElement.offsetTop, order: '' }); TweenMax.set(targetElement, { autoAlpha: 0.6 }); this.setState({ sourceElement: targetElement, originalIdx: originalIdx, newIdx: originalIdx, currentElement: targetElementCloned, startX: pointer.pageX, startY: pointer.pageY }, _=> { switch (eventType) { case 'mousedown': { document.addEventListener('mousemove', this.onSorting); document.addEventListener('mouseup', this.onSortEnd); break; } case 'touchstart': { targetElementCloned.addEventListener('touchmove', this.onSorting); targetElementCloned.addEventListener('touchend', this.onSortEnd); break; } } }) } onSorting(event) { const props = this.props; if (props.disabled) { return; } const pointer = event.changedTouches ? event.changedTouches[ 0 ] : event; const state = this.state; const currentElement = state.currentElement; const newState = { newIdx: Math.round((pointer.pageX - state.startX) / state.sourceElement.offsetWidth) + state.originalIdx, isHoverDeleteEl: false }; if (props.deleteDropEl) { const deleteArea = props.deleteDropEl.getBoundingClientRect(); if ((pointer.pageX >= deleteArea.left && pointer.pageX <= deleteArea.left + deleteArea.width) && (pointer.pageY >= deleteArea.top && pointer.pageY <= deleteArea.top + deleteArea.height)) { // is on delete element newState['isHoverDeleteEl'] = true; } } this.setState(newState); TweenMax.set(currentElement, { x: pointer.pageX - state.startX, y: pointer.pageY - state.startY }) } onSortEnd(event) { const props = this.props; const state = this.state; if (props.disabled) { return; } const pointer = event.changedTouches ? event.changedTouches[ 0 ] : event; const onSortEnd = props.onSortEnd; const onSlideDelete = props.onSlideDelete; const sourceEl = state.sourceElement; const placeholderEl = state.currentElement; document.removeEventListener('mousemove', this.onSorting); document.removeEventListener('mouseup', this.onSortEnd); placeholderEl.removeEventListener('touchmove', this.onSorting); placeholderEl.removeEventListener('touchend', this.onSortEnd); placeholderEl.parentNode.removeChild(placeholderEl); // test if the slide is in rubbish bin area if (props.deleteDropEl) { const deleteArea = props.deleteDropEl.getBoundingClientRect(); if ((pointer.pageX >= deleteArea.left && pointer.pageX <= deleteArea.left + deleteArea.width) && (pointer.pageY >= deleteArea.top && pointer.pageY <= deleteArea.top + deleteArea.height)) { // fire delete event if (typeof(onSlideDelete) === "function") { onSlideDelete(state.originalIdx); } TweenMax.set(sourceEl, { autoAlpha: 1 }); this.setState({ sourceElement: null, currentElement: null, originalIdx: null, newIdx: null }) return; } } // sort // fire sorted event if (typeof(onSortEnd) === "function") { onSortEnd( state.originalIdx, state.newIdx ); } TweenMax.set(sourceEl, { autoAlpha: 1 }); this.setState({ sourceElement: null, currentElement: null, originalIdx: null, newIdx: null }) } render() { const props = this.props; const state = this.state; const items = props.children; let children = React.Children.map( items, (child, idx) => { let currentIdx = idx; if (state.originalIdx !== null) { if (idx === state.originalIdx) { currentIdx = state.newIdx; } else { if (currentIdx > state.originalIdx) { currentIdx--; } if (currentIdx >= state.newIdx) { currentIdx++; } } } return React.cloneElement(child, { style: { order: currentIdx }, onMouseDown: (event) => { const originalMouseDownEvent = child.props.onMouseDown; if (typeof(originalMouseDownEvent) === "function") { originalMouseDownEvent(event); } this.onSortStart(event); }, onTouchStart: (event) => { const originalTouchStartEvent = child.props.onTouchStart; if (typeof(originalTouchStartEvent) === "function") { originalTouchStartEvent(event); } this.onSortStart(event); } }) } ); return <div className={`sortable-list ${state.isHoverDeleteEl? ' prepare-delete': ''}`}> {children} </div> } } class SlidePanel extends Component { constructor(props) { super(props); this.state = { selectedSlide: null, animateIndex: 0, isSorting: false, showContextMenu: false }; this.animateTick = null; this.addSlide = this.addSlide.bind(this); this.copySlide = this.copySlide.bind(this); this.selectSlide = this.selectSlide.bind(this); this.onSortStart = this.onSortStart.bind(this); this.onSortEnd = this.onSortEnd.bind(this); this.onSlideDelete = this.onSlideDelete.bind(this); this.showContextMenu = this.showContextMenu.bind(this); this.hideContextMenu = this.hideContextMenu.bind(this); } componentDidMount() { // for (let i = 4; i > 0; i--) { // this.props.sceneContext.addSlide(); // } } componentWillUnmount() { } addSlide() { // Events.emit('addSlide'); this.props.sceneContext.addSlide(); } copySlide() { const props = this.props; const sceneContext = props.sceneContext; const selectedSlideId = sceneContext.getCurrentSlideId(); this.props.sceneContext.addSlide(selectedSlideId); } previewAll() { console.log('preview all'); } onSortStart() { this.setState({ isSorting: true }) } onSortEnd(oldIdx, newIdx) { this.setState({ isSorting: false }) if (this.props.isEditing === false) { this.selectSlide(oldIdx); this.props.sceneContext.playSlide(); } else { this.props.sceneContext.sortSlide(oldIdx, newIdx); } } onSlideDelete(slideIdx) { this.setState({ isSorting: false }) this.props.sceneContext.deleteSlide(slideIdx); } selectSlide(slideIdx) { const slidesList = this.props.sceneContext.getSlidesList(); const selectedSlideId = slidesList[slideIdx].id; const autoPlay = this.props.isEditing === false; this.props.sceneContext.selectSlide(selectedSlideId, autoPlay); // Events.emit('setTimelinePositionSelected', null, slideId); if (this.props.socket) { this.props.socket.emit('updateSceneStatus', { action: 'selectSlide', details: { slideId: selectedSlideId, autoPlay: true } }) } } showContextMenu(e) { e.preventDefault(); if (this.props.isEditing === false) return; this.setState({ showContextMenu: true, menuPosition: { x: e.clientX, y: e.clientY, } }) } hideContextMenu(e) { e.preventDefault(); this.setState({ showContextMenu: false }) } render() { const props = this.props; const state = this.state; const sceneContext = props.sceneContext; const slidesList = sceneContext.getSlidesList(); const selectedSlideId = sceneContext.getCurrentSlideId(); // console.log(selectedSlideId); const panelClassList = []; if (state.isMinimized) { panelClassList.push('mini'); } if (state.isSorting) { panelClassList.push('sorting'); } return ( <div id="slides-panel" className={panelClassList.join(' ')}> <div className="slides-wrap" onWheel={(event) => event.currentTarget.scrollBy(event.deltaY / 8, 0)}> <div className="slide preview-all" onClick={this.previewAll}></div> <SortableList disabled={props.isEditing === false} onSortStart={this.onSortStart} onSortEnd={this.onSortEnd} onSlideDelete={this.onSlideDelete} deleteDropEl={this.deleteDropEl} > {slidesList.map((slide, idx) => { const slideId = slide['id']; const slideImg = slide['image']; {/* const totalTime = idx;// slide['totalTime']; */} const isSlideSelected = slideId === selectedSlideId; return ( <div key={slideId} className={"slide" + (isSlideSelected ? " selected" : "")} // onClick={()=>{ sceneContext.selectSlide(idx) }} onContextMenu={this.showContextMenu} > <div className="slide-idx">{idx + 1}</div> <div className="preview-img"> {slideImg && <img // className={((this.state.selectedSlide === slideId && this.state.animateIndex === idx)? 'active': '')} // key={idx} src={slideImg} />} </div> <div className="slide-info"> {/*Math.floor(totalTime / 60).toString().padStart(2,'0') + ':' + Math.floor(totalTime % 60).toString().padStart(2,'0')*/} {sceneContext.getSlideTotalTime(slideId)} </div> </div> ); })} </SortableList> {props.isEditing !== false && <Fragment> <div className="slide add-slide" onClick={this.addSlide}></div> <div className="slide delete-slide" ref={ref=>this.deleteDropEl=ref}> <svg viewBox="0 -20 43.15 50.54" xmlSpace="preserve"> <g> <path fill="currentColor" className="bin-cover" d="M40.72,6.42H30.24V4.85c0-2.68-2.17-4.85-4.85-4.85h-7.64c-2.68,0-4.85,2.17-4.85,4.85v1.58H2.42 C1.09,6.42,0,7.51,0,8.85c0,1.34,1.09,2.42,2.42,2.42h38.3c1.34,0,2.42-1.09,2.42-2.42C43.15,7.51,42.06,6.42,40.72,6.42z M17.75,6.42V3.89h7.64v2.53H17.75z"/> <path fill="currentColor" className="bin-body" d="M8.24,15.88c-1.34,0-2.42,1.09-2.42,2.42v23.75c0,4.69,3.8,8.48,8.48,8.48h14.54c4.69,0,8.48-3.8,8.48-8.48 V18.3c0-1.34-1.09-2.42-2.42-2.42s-2.42,1.09-2.42,2.42v23.75c0,2.01-1.63,3.64-3.64,3.64H14.3c-2.01,0-3.64-1.63-3.64-3.64V18.3 C10.67,16.96,9.58,15.88,8.24,15.88z"/> <path fill="currentColor" className="bin-body" d="M19.15,39.02V18.3c0-1.34-1.09-2.42-2.42-2.42s-2.42,1.09-2.42,2.42v20.72c0,1.34,1.09,2.42,2.42,2.42 S19.15,40.36,19.15,39.02z"/> <path fill="currentColor" className="bin-body" d="M28.84,39.02V18.3c0-1.34-1.09-2.42-2.42-2.42S24,16.96,24,18.3v20.72c0,1.34,1.09,2.42,2.42,2.42 S28.84,40.36,28.84,39.02z"/> </g> </svg> </div> </Fragment> } </div> <div className="toggle-size" onClick={_=>this.setState({ isMinimized: !this.state.isMinimized })}></div> {state.showContextMenu && <div className="context-menu-container" onClick={this.hideContextMenu} onContextMenu={this.hideContextMenu}> <div className="content-menu-overlay" /> <div className="context-menu" style={{ top: state.menuPosition.y, left: state.menuPosition.x, }}> <div className="menu-item-wrapper"> <div className="menu-item" onClick={this.copySlide}>Copy Slide</div> {/* <div className="seperator" onClick={(e)=>e.preventDefault()}></div> <div className="menu-item" onClick={_=>alert('maybe need some slide properties settings here')}>Properties</div> */} </div> </div> </div> } </div> ); } } export default withSceneContext(SlidePanel);<file_sep>/src/utils/aframeEditor/aNavigation.js import AEntity from "./aEntity"; import ACylinder from "./aCylinder"; import ACone from "./aCone"; const uuid_v1 = require('uuid/v1'); //const uuid = _=> 'uuid_' + uuid_v1().replace(/-/g, '_'); class ANavigation extends AEntity { constructor(el) { super(el); this._messageId = 'SceneObjects.Navigation.DefaultName'; this._type = 'a-navigation'; this._animatableAttributes = { position: ['x', 'y', 'z'], rotation: ['x', 'y', 'z'], scale: ['x', 'y', 'z'], material: [ 'color', 'opacity' ] } this._staticAttributes = [ { type: 'slidesList', name: 'Navigate To Slide', attributeKey: 'navigateToSlideId', attributeField: '' } ] this._fixedAttributes = { // geometry: { // primitive: 'box', // }, // scale: { // x: 1, // y: 1, // z: 1 // }, // material: { // src: '#iconNavigation', // // transparent: true, // color: '#FFFFFF', // opacity: 0.4 // }, 'cursor-listener': '' } // const cylinder = new ACylinder(); // // cylinder.animatableAttributesValues.rotation.x = 180; // cylinder.animatableAttributesValues.position.y = 0.75; // cylinder.animatableAttributesValues.scale.x = 0.1; // cylinder.animatableAttributesValues.scale.y = 0.5; // cylinder.animatableAttributesValues.scale.z = 0.1; // const cone = new ACone(); // cone.animatableAttributesValues.rotation.x = 180; // cone.animatableAttributesValues.position.y = 0.25; // cone.animatableAttributesValues.scale.x = 0.25; // cone.animatableAttributesValues.scale.y = 0.5; // cone.animatableAttributesValues.scale.z = 0.25; // this._children = [ // cylinder, // cone // ]; this._animatableAttributesValues = { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 }, material: { color: '#FFFFFF', opacity: 1 } } } // setEl(el) { // super.setEl(el); // const childrenEls = Array.prototype.slice.call(el.children); // if (childrenEls.length === 0) { // this._children.forEach(child => { // // const childElementId = uuid(); // // const newChildElement = { // // type: type, // // id: childElementId, // // name: type.split('-')[1], // // element: 'a-entity', // // timelines: [] // // }; // const newChildElementAttributes = { // id: uuid(), // ...child.animatableAttributesValues, // ...child.fixedAttributes // } // const newChildEl = document.createElement('a-entity'); // Object.keys(newChildElementAttributes).forEach(key => { // newChildEl.setAttribute(key, newChildElementAttributes[key]) // }) // el.append(newChildEl); // // this.editor.createNewEntity(newChildElement, newElement); // }) // } // } updateEntityAttributes(attrs) { if (typeof(attrs) !== 'object') return; const self = this; for (let key in attrs) { if (self._animatableAttributes.hasOwnProperty(key)) { // if (typeof(attrs[key]) === 'object') { // const subAttrs = attrs[key]; // const subAttrKeys = Object.keys(subAttrs); // let valueString = ''; // subAttrKeys.forEach( subKey => { // valueString += `${subKey}:${subAttrs[subKey]};`; // }) // self._el.setAttribute(key, valueString); // if (key === 'material') { // const childrenEls = Array.prototype.slice.call(self._el.children); // childrenEls.forEach(childEl => { // childEl.setAttribute(key, valueString); // }) // } // // } else if (typeof(keyOrObj[key]) === 'string') { // } else { self._el.setAttribute(key, attrs[key]); if (key === 'material') { const childrenEls = Array.prototype.slice.call(self._el.children); childrenEls.forEach(childEl => { childEl.setAttribute(key, attrs[key]); }) } // } } else { const staticAttribute = self.staticAttributes.find(attr => attr.attributeKey === key); if (staticAttribute) { // if (typeof(attrs[key]) === 'object') { // const subAttrs = attrs[key]; // const subAttrKeys = Object.keys(subAttrs); // let valueString = ''; // subAttrKeys.forEach( subKey => { // valueString += `${subKey}:${subAttrs[subKey]};`; // }) // self._el.setAttribute(key, valueString); // } else { self._el.setAttribute(key, attrs[key]); // } } } } } } export default ANavigation;<file_sep>/src/utils/aframeEditor/aSky.js import AEntity from "./aEntity"; class ASky extends AEntity { constructor(defaultAttributes) { super(defaultAttributes); this._messageId = 'SceneObjects.Sky.DefaultName'; this._type = 'a-sky'; this._animatableAttributes = { // position: ['x', 'y', 'z'], // scale: ['x', 'y', 'z'], rotation: ['x', 'y', 'z'], material: [ 'color', 'opacity' ], // geometry: [ // 'radius' // ] } this._staticAttributes = [ { type: 'image', name: 'Image360', attributeKey: 'material', attributeField: 'src' }, { type: 'video', name: 'Video360', attributeKey: 'material', attributeField: 'src' } ] this._fixedAttributes = { geometry: { primitive: 'sphere', radius: 5000 }, material: { side: 'back' }, scale: { x: -1, y: 1, z: 1 } } this._animatableAttributesValues = { rotation: { x: 0, y: 0, z: 0 }, material: { color: '#FFFFFF', opacity: 1 } } } } export default ASky; <file_sep>/public/utils/saveLoadProject/saveProject.js const ProjectFile = require('./ProjectFile'); const saveProjectToLocalAsync = async (projectFilePath, entitiesList, assetsList) => { const project = new ProjectFile(null, projectFilePath, null); return await project.saveToLocalAsync(entitiesList, assetsList); }; module.exports = { saveProjectToLocalAsync };<file_sep>/src/App.js import React, {Component} from 'react'; import {Switch, Route, Redirect} from 'react-router-dom'; import DefaultLoading from 'components/loading/defaultLoading'; import PrivateRoute from 'components/router/privateRoute'; import {authenticatePromise} from 'utils/authentication/auth'; import routes from 'globals/routes'; import {library} from '@fortawesome/fontawesome-svg-core' // import {faArrowsAlt, faArrowsAlt} from '@fortawesome/free-solid-svg-icons' import config, {setAppData, setParamsReadFromExternalConfig} from 'globals/config'; import ipcHelper from 'utils/ipc/ipcHelper'; import handleErrorWithUiDefault from 'utils/errorHandling/handleErrorWithUiDefault'; import {getCustomizedAppDataPromise} from 'globals/customizedAppData/customizedAppData'; import asyncLoadingComponent from 'components/loading/asyncLoadingComponent'; // import EditorPage from 'pages/aframeEditor/editorPage'; // import PresenterPage from 'pages/aframeEditor/presenterPage'; import {SceneContextProvider} from 'globals/contexts/sceneContext'; import {changeGlobalLanguageByCodePromise, LanguageContextProvider} from 'globals/contexts/locale/languageContext'; import './App.css'; const faIconsNeed = [ "faArrowsAlt", "faSyncAlt", "faExpandArrowsAlt", "faPlay", "faPause", "faTrashAlt", "faEye", "faEyeSlash", "faAngleLeft", "faAngleRight", "faVideo", "faVideoSlash", "faWindowMinimize", "faWindowMaximize", "faWindowRestore", "faWindowClose", //"faUndo", // could be used in MenuComponent ]; faIconsNeed.forEach(iconName => { const icon = require("@fortawesome/free-solid-svg-icons")[iconName]; library.add(icon); }); /* Note: Using async to load editor page causes some undesirable effects, hence not used. */ // Code Splitting and React Router v4 // https://serverless-stack.com/chapters/code-splitting-in-create-react-app.html const ViewerPage = require('pages/aframeEditor/viewerPage').default; const AsyncEditorPage = asyncLoadingComponent(_ => import('pages/aframeEditor/editorPage')); //const AsyncViewerPage = asyncLoadingComponent(_ => import('pages/aframeEditor/viewerPage')); const AsyncPresenterPage = asyncLoadingComponent(_ => import('pages/aframeEditor/presenterPage')); //const AsyncTestSaveLoad = asyncLoadingComponent(_ => import('pages/TestSaveLoad')); const AsyncTestFileExplorer = asyncLoadingComponent(_ => import('pages/TestFileExplorer/TestFileExplorer')); const AsyncProjectListPage = asyncLoadingComponent(_ => import('pages/ProjectListPage')); class App extends Component { constructor(props) { super(props); this.isElectronApp = config.isElectronApp; console.log('isElectronApp:', this.isElectronApp); this.state = { isGotAppData: this.isElectronApp ? false : true, isGotParamsReadFromExternalConfig: this.isElectronApp ? false : true, isGotCustomizedAppData: this.isElectronApp ? false : true, isAuthenticationDone: this.isElectronApp ? false : true, }; } componentDidMount() { if (this.isElectronApp) { ipcHelper.getAppData((err, data) => { if (err) { this.setState({ isGotAppData: true }); handleErrorWithUiDefault(err); return; } setAppData(data); this.setState({ isGotAppData: true }); }) ipcHelper.getParamsFromExternalConfig((err, data) => { if (err) { this.setState({ isGotParamsReadFromExternalConfig: true }); handleErrorWithUiDefault(err); return; } setParamsReadFromExternalConfig(data); this.setState({ isGotParamsReadFromExternalConfig: true }); }); getCustomizedAppDataPromise() .then(async customizedAppData => { const langCodeToUse = (customizedAppData && customizedAppData.langCode) || config.defaultLanguage.code; console.log('langCodeToUse:', langCodeToUse); await changeGlobalLanguageByCodePromise(langCodeToUse, false); }) .catch(handleErrorWithUiDefault) .finally(_ => { this.setState({ isGotCustomizedAppData: true }); }) authenticatePromise() .then((isAuthenticated) => { console.log('isAuthenticated:', isAuthenticated); }) .catch(handleErrorWithUiDefault) .finally(_ => { this.setState({ isAuthenticationDone: true }); }); } } render() { const { isGotAppData, isGotParamsReadFromExternalConfig, isGotCustomizedAppData, isAuthenticationDone } = this.state; // console.log('isGotAppData:', isGotAppData); // console.log('isGotParamsReadFromExternalConfig:', isGotParamsReadFromExternalConfig); // console.log('isGotCustomizedAppData:', isGotCustomizedAppData); // console.log('isAuthenticationDone:', isAuthenticationDone); return !(isGotAppData && isGotParamsReadFromExternalConfig && isGotCustomizedAppData && isAuthenticationDone) ? <DefaultLoading /> : ( <LanguageContextProvider> <SceneContextProvider> <div id="App"> {/* if !electron, return viewer page only */} { this.isElectronApp ? <Switch> <PrivateRoute exact path="/file-explorer" component={AsyncTestFileExplorer} fallBackRedirectPath={routes.home} fallBackRedirectPath={routes.home} /> <PrivateRoute exact path={routes.editor} component={AsyncEditorPage} fallBackRedirectPath={routes.home} /> <PrivateRoute exact path={routes.presenter} component={AsyncPresenterPage} fallBackRedirectPath={routes.home} /> <PrivateRoute exact path={routes.viewer} component={ViewerPage} fallBackRedirectPath={routes.home} /> <PrivateRoute exact path={routes.projectList} component={AsyncProjectListPage} /> <Route exact path={routes.home} component={AsyncProjectListPage} /> <Redirect to={routes.home} /> </Switch> : <Switch> <Route exact path={routes.home} component={ViewerPage} /> <Redirect to={routes.home} /> </Switch> } </div> </SceneContextProvider> </LanguageContextProvider> ); } } export default App;<file_sep>/src/components/twinklingContainer.js import React from 'react'; import styled, {keyframes} from 'styled-components'; import setNumberValueWithDefault from 'utils/js/setNumberValueWithDefault'; const twinklingKeyframes = (minOpacity, maxOpacity) => keyframes` 0% { opacity: ${minOpacity}; } 100% { opacity: ${maxOpacity}; } `; const TwinklingContainerStyleComponent = styled.div` animation-name: ${props => twinklingKeyframes(setNumberValueWithDefault(props.minOpacity, 0.5), setNumberValueWithDefault(props.maxOpacity, 1))}; animation-iteration-count: infinite; animation-timing-function: ease-in-out; animation-direction: alternate; animation-duration: ${props => setNumberValueWithDefault(props.animationDurationInSecs, 0)}s; `; // render props pattern // https://codeburst.io/animating-react-components-with-css-and-styled-components-cc5a0585f105 function TwinklingContainer(props) { const { minOpacity, maxOpacity, animationDurationInSecs, children } = props; return ( <TwinklingContainerStyleComponent minOpacity={minOpacity} maxOpacity={maxOpacity} animationDurationInSecs={animationDurationInSecs} > {children} </TwinklingContainerStyleComponent> ); } export default TwinklingContainer;<file_sep>/src/containers/aframeEditor/homePage/infoPanel/staticInfoRenderer.js /* info generation of right panel */ import React, {Component} from 'react'; import {rgba2hex} from 'globals/helperfunctions'; import transformModeId from 'globals/constants/transformModeId'; import isNonEmptyArray from 'utils/variableType/isNonEmptyArray'; // import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; // import {SketchPicker} from 'react-color'; import TransformMode from './transformMode'; import ColorPicker from './colorPicker'; import OpacityPicker from './opacityPicker'; // import {Rnd as ResizableAndDraggable} from 'react-rnd'; // import ABox from 'utils/aBox'; import {LanguageContextMessagesConsumer} from 'globals/contexts/locale/languageContext'; import './infoTypeBox.css'; var Events = require('vendor/Events.js'); class StaticInfoRenderer extends Component { constructor(props) { super(props); this.editor = null; this.state = { editorMode: null, displayColorPicker: false, // color: currentEntity[props.timelinePosition]['material']['color'], additionalAttributes: {} // const color = rgba2hex(data.material.color) }; [ 'changeObjectField', 'changeObjectMultipleFields', 'changeTransformMode', ].forEach(methodName => { this[methodName] = this[methodName].bind(this); }); this.events = { // transformmodechanged: (mode) => { // self.setState({ // editorMode: mode // }); // } }; } /* react lifecycles */ componentDidMount() { const props = this.props; if (props.animatableAttributes.position) { this.changeTransformMode(transformModeId.translate); } else if (props.animatableAttributes.rotation) { this.changeTransformMode(transformModeId.rotate); } else if (props.animatableAttributes.scale) { this.changeTransformMode(transformModeId.scale); } Events.on('editor-load', obj => { this.editor = obj; }) // Events.emit('transformmodechanged', transformModeId.translate); } componentWillUnmount() { for (let eventName in this.events) { Events.removeListener(eventName, this.events[eventName]); } } // static getDerivedStateFromProps(nextProps, nextState) { // console.log('getDerivedStateFromProps'); // return { // displayColorPicker: false, // color: nextProps.timelineObj[nextProps.timelinePosition]['material']['color'] // } // } componentDidUpdate(prevProps, prevState) { const props = this.props; const currentEntity = props.sceneContext.getCurrentEntity(); // console.log(props, prevProps); // console.log(currentEntity.id, prevProps.timelineObj.id); // console.log(props.timelinePosition, prevProps.timelinePosition); if ( currentEntity.id !== prevProps.entityId // props.timelinePosition !== prevProps.timelinePosition ) { // console.log('reset'); // this.changeTransformMode(null); if (props.animatableAttributes.position) { this.changeTransformMode(transformModeId.translate); } else if (props.animatableAttributes.rotation) { this.changeTransformMode(transformModeId.rotate); } else if (props.animatableAttributes.scale) { this.changeTransformMode(transformModeId.scale); } } // if (state.additionalAttributes.radiusTop !== currentEntity[props.timelinePosition]) return true; } /* end of react lifecycles */ /* methods */ changeTransformMode(transformMode) { // const sceneContext = props.sceneContext; this.setState({ editorMode: transformMode }); if (transformMode) { Events.emit('enablecontrols'); Events.emit('transformmodechanged', transformMode); } else { Events.emit('disablecontrols'); } } changeObjectField(field, value) { const { sceneContext } = this.props; const tmp = {}; let pointer = tmp; field.split('.').forEach((key, idx, arr) => { if (idx === arr.length - 1) { pointer[key] = value } else { pointer[key] = {} pointer = pointer[key] } }) // tmp[field] = value; // console.log(tmp); sceneContext.updateDefaultAttributes( tmp ); // Events.emit('updateSelectedEntityAttribute', tmp); } changeObjectMultipleFields(objs) { const { sceneContext } = this.props; const tmp = {}; Object.keys(objs).forEach(field => { const value = objs[field]; let pointer = tmp; field.split('.').forEach((key, idx, arr) => { if (idx === arr.length - 1) { pointer[key] = value; } else { pointer = pointer[key] || {}; } }) // console.log(tmp); // console.log(pointer); }) // tmp[field] = value; sceneContext.updateDefaultAttributes( tmp ); // Events.emit('updateSelectedEntityAttribute', tmp); } /* end of methods */ render() { const props = this.props; const state = this.state; const currentEntity = props.sceneContext.getCurrentEntity(); const data = currentEntity['components']; // console.log(data.ttfFont, animatableAttributes.ttfFont && animatableAttributes.ttfFont.indexOf('fontSize') !== -1); // const color = rgba2hex(data.material.color); const animatableAttributes = props.animatableAttributes; const transformModes = []; if (animatableAttributes.position) { transformModes.push(transformModeId.translate); } if (animatableAttributes.rotation) { transformModes.push(transformModeId.rotate); } if (animatableAttributes.scale) { transformModes.push(transformModeId.scale); } // ABox return ( <div className="animatable-params"> { isNonEmptyArray(transformModes) && <div className={`vec3D-btn-col buttons-${transformModes.length}`}> <TransformMode modes={transformModes} isInTimeline={false} onUpdate={(newPosition, newRotation, newScale) => { this.changeObjectMultipleFields({ 'position': newPosition, 'rotation': newRotation, 'scale': newScale }); }} /> </div> } <div className="attribute-buttons-wrapper"> {animatableAttributes.material && animatableAttributes.material.indexOf('color') !== -1 && <div className="attribute-button color-col" title={rgba2hex(data.material.color)} onClick={_ => this.changeTransformMode(null)}> <ColorPicker key={currentEntity.id + data.material.color} field={'material'} color={rgba2hex(data.material.color)} timelineId={currentEntity.id} timelinePosition={''} onUpdate={(newColor) => { this.changeObjectField('material.color', newColor) }} currentEntity={currentEntity} /> <div className="field-label"> <LanguageContextMessagesConsumer messageId="EditThingPanel.Color.ColorLabel" /> </div> </div> } {animatableAttributes.material && animatableAttributes.material.indexOf('opacity') !== -1 && <div className="attribute-button opacity-col" onClick={() => this.changeTransformMode(null)}> <OpacityPicker key={currentEntity.id} field={'material'} opacity={data.material.opacity} timelineId={currentEntity.id} timelinePosition={''} onUpdate={(newOpacity) => { this.changeObjectField('material.opacity', newOpacity) }} currentEntity={currentEntity} /> <div className="field-label"> <LanguageContextMessagesConsumer messageId="EditThingPanel.Color.OpacityLabel" /> </div> </div> } {animatableAttributes.ttfFont && animatableAttributes.ttfFont.indexOf('color') !== -1 && <div className="attribute-button color-col" title={data.ttfFont.color} onClick={() => this.changeTransformMode(null)}> <ColorPicker key={currentEntity.id + data.ttfFont.color} field={'ttfFont'} color={data.ttfFont.color} timelineId={currentEntity.id} timelinePosition={''} onUpdate={(newColor) => { this.changeObjectField('ttfFont.color', newColor) }} currentEntity={currentEntity} /> <div className="field-label"> <LanguageContextMessagesConsumer messageId='EditThingPanel.Text.TextColorLabel' /> </div> {/* <input type="color" value={color} onInput={(event) => this.changeObjectField('material.color', event.target.value)} hidden/> */} </div> } {animatableAttributes.ttfFont && animatableAttributes.ttfFont.indexOf('opacity') !== -1 && <div className="attribute-button opacity-col" onClick={() => this.changeTransformMode(null)}> <OpacityPicker key={currentEntity.id} field={'ttfFont'} opacity={data.ttfFont.opacity} timelineId={currentEntity.id} timelinePosition={''} onUpdate={(newOpacity) => { this.changeObjectField('ttfFont.opacity', newOpacity) }} currentEntity={currentEntity} /> <div className="field-label"> <LanguageContextMessagesConsumer messageId='EditThingPanel.Text.TextOpacityLabel' /> </div> </div> } {animatableAttributes.ttfFont && animatableAttributes.ttfFont.indexOf('fontSize') !== -1 && <div className="attribute-button opacity-col" onClick={() => this.changeTransformMode(null)}> <div className="field-label">Font Size:</div> <input type="ttfFont" value={data.ttfFont.fontSize} onInput={(e) => { currentEntity.el.setAttribute('ttfFont', { fontSize: e.currentTarget.value }) {/* this.setState((prevState) => { return { additionalAttributes: { ...prevState.additionalAttributes, radiusTop: e.currentTarget.value } } }) */} this.changeObjectField('ttfFont.fontSize', e.currentTarget.value) }} onBlur={(e) => { this.changeObjectField('ttfFont.fontSize', e.currentTarget.value) }} /> </div> } {animatableAttributes.geometry && animatableAttributes.geometry.indexOf('radiusTop') !== -1 && <div className="attribute-button opacity-col" onClick={() => this.changeTransformMode(null)}> <div className="field-label">Radius Top:</div> <input type="text" value={state.additionalAttributes.radiusTop} onInput={(e) => { currentEntity.el.setAttribute('geometry', { radiusTop: e.currentTarget.value }) this.setState((prevState) => { return { additionalAttributes: { ...prevState.additionalAttributes, radiusTop: e.currentTarget.value } } }) }} onBlur={(e) => { this.changeObjectField('geometry.radiusTop', state.additionalAttributes.radiusTop) }} /> </div> } {animatableAttributes.geometry && animatableAttributes.geometry.indexOf('radiusBottom') !== -1 && <div className="attribute-button opacity-col" onClick={() => this.changeTransformMode(null)}> <div className="field-label">Radius Bottom:</div> <input type="text" value={state.additionalAttributes.radiusBottom} onInput={(e) => { currentEntity.el.setAttribute('geometry', { radiusBottom: e.currentTarget.value }) this.setState((prevState) => { return { additionalAttributes: { ...prevState.additionalAttributes, radiusBottom: e.currentTarget.value } } }) }} onBlur={(e) => { this.changeObjectField('geometry.radiusBottom', state.additionalAttributes.radiusBottom) }} /> </div> } {animatableAttributes.cameraPreview && <div className="attribute-button preview-col"> <canvas ref={ref=>{ {/* props.model.setEditorInstance(this.editor) */} props.model.setCameraPreviewEl(ref) props.model.setEditorInstance(props.sceneContext.editor) props.model.renderCameraPreview(); }} /> </div>} </div> </div> ); } } export default StaticInfoRenderer;<file_sep>/src/utils/js/myPromisify.js // https://medium.com/better-programming/why-coding-your-own-makes-you-a-better-developer-5c53439c5e4a // const promisifyForFuncThatOnlyHasCallBackAsArgument = (functionWithCallBack) => { // return _ => new Promise((resolve, reject) => { // functionWithCallBack((err, result) => { // return err ? reject(err) : resolve(result); // }); // }); // } const promisify = (functionWithCallBack) => { return function() { const simulatedCallBack = (resolve, reject) => { return (err, result) => { return err ? reject(err) : resolve(result); } } let argumentsForFunc = []; if (arguments.length > 0) { argumentsForFunc = Array.prototype.slice.call(arguments); } return new Promise((resolve, reject) => { argumentsForFunc.push(simulatedCallBack(resolve, reject)); functionWithCallBack(...argumentsForFunc); }); } } export default promisify;<file_sep>/src/utils/ipc/ipcHelper.js import isFunction from 'utils/variableType/isFunction'; import promisify from 'utils/js/myPromisify'; const electron = window.require ? window.require('electron') : null; const dummyFunc = (param1, param2, param3) => { // console.log(param1, param2, param3); // console.log('not in electron app, no ipc') if (param1 === "saveProject") { localStorage.setItem('schoolVRSave', JSON.stringify(param2)); } else if (param1 === "openSchoolVrFileDialogResponse") { // const loadFile = JSON.parse(localStorage.getItem('schoolVRSave')); param2(null, { data: { filePaths: ['hello'] } }); } else if (param1 === "saveSchoolVrFileDialogResponse") { param2(null, { data: { filePath: 'schoolVRWebSave.test' } }); } else if (param1 === "isCurrentLoadedProjectResponse") { // const loadFile = JSON.parse(localStorage.getItem('schoolVRSave')); param2(null, { data: { isCurrentLoadedProject: false } }); } else if (param1 === "loadProjectByProjectFilePathResponse") { const loadFile = JSON.parse(localStorage.getItem('schoolVRSave')); param2(null, { data: { projectJson: loadFile } }); } // debugger; }; const ipc = electron ? electron.ipcRenderer : { on: dummyFunc, removeListener: dummyFunc, once: dummyFunc, send: dummyFunc }; /* listeners */ function addListener(channel, listener) { ipc.on(channel, listener); } function removeListener(channel, listener) { ipc.removeListener(channel, listener); } /* end of listeners */ function generalIpcCall(channelName, callBack = null, objToSend = null) { if (isFunction(callBack)) { ipc.once(`${channelName}Response`, (event, arg) => { if (arg.err) { callBack(`${channelName}: ${arg.err}`, arg.data); } else { callBack(null, arg.data); } }); } if (objToSend) { ipc.send(channelName, objToSend); } else { ipc.send(channelName); } } /* config */ function getParamsFromExternalConfig(callBack) { generalIpcCall('getParamsFromExternalConfig', callBack); }; /* end of config */ /* app */ function getAppData(callBack) { generalIpcCall('getAppData', callBack); }; /* end of app */ /* network interfaces */ function getMacAddress(callBack) { generalIpcCall('getMacAddress', callBack); } const getMacAddressPromise = promisify(getMacAddress); /* end of network interfaces */ /* shell */ function shellOpenItem(filePath) { generalIpcCall('shellOpenItem', null, filePath); }; function shellOpenExternal(url) { generalIpcCall('shellOpenExternal', null, url); } /* end of shell */ /* electron window api */ function newBrowserWindow(windowOptions, url, callBack) { generalIpcCall('newBrowserWindow', callBack, { windowOptions: windowOptions, url: url }); } function closeWindow() { generalIpcCall('close'); }; function minimizeWindow() { generalIpcCall('minimize'); }; function toggleMaximizeWindow(callBack) { generalIpcCall('toggleMaximize', callBack); }; function toggleDevTools() { generalIpcCall('toggleDevTools', true); }; /* end of electron window api */ /* fileSystem */ function mimeStat(filePath, callBack) { generalIpcCall('mimeStat', callBack, filePath); } function mimeStats(filePaths, callBack) { generalIpcCall('mimeStats', callBack, filePaths); } function base64Encode(filePath, callBack) { generalIpcCall('base64Encode', callBack, filePath); } function base64Decode(locationToSaveFile, encodedStr, callBack) { generalIpcCall('base64Decode', callBack, { locationToSaveFile: locationToSaveFile, encodedStr: encodedStr }); } function createPackage(src, dest, callBack) { generalIpcCall('createPackage', callBack, { src: src, dest: dest }); }; function extractAll(archive, dest, callBack) { generalIpcCall('extractAll', callBack, { archive: archive, dest: dest }); } function readdir(dirPath, callBack) { generalIpcCall('readdir', callBack, { dirPath: dirPath, }); } function readFile(filePath, callBack) { generalIpcCall('readFile', callBack, filePath); } function writeFile(filePath, content, callBack) { generalIpcCall('writeFile', callBack, { filePath: filePath, content: content }); } function deleteFile(filePath, callBack) { generalIpcCall('deleteFile', callBack, filePath); } function renameFile(oldPath, newPath, callBack) { generalIpcCall('renameFile', callBack, { oldPath: oldPath, newPath: newPath }); } function copyFile(src, dest, callBack) { generalIpcCall('copyFile', callBack, { src: src, dest: dest }); } /* end of fileSystem */ /* saveLoadProject */ function listProjects(callBack) { generalIpcCall('listProjects', callBack); } function saveProject(projectFilePath, entitiesList, assetsList, callBack) { generalIpcCall('saveProject', callBack, { projectFilePath: projectFilePath, entitiesList: entitiesList, assetsList: assetsList }); } function parseDataToSaveFormat(projectName, entitiesList, assetsList, callBack) { generalIpcCall('parseDataToSaveFormat', callBack, { projectName: projectName, entitiesList: entitiesList, assetsList: assetsList }); } function loadProjectByProjectFilePath(filePath, callBack) { generalIpcCall('loadProjectByProjectFilePath', callBack, filePath); } function isCurrentLoadedProject(projectFilePath, callBack) { generalIpcCall('isCurrentLoadedProject', callBack, projectFilePath); } /* end of saveLoadProject */ /* window diaglog */ function openImageDialog(callBack) { generalIpcCall('openImageDialog', callBack); } function openGifDialog(callBack) { generalIpcCall('openGifDialog', callBack); } function openVideoDialog(callBack) { generalIpcCall('openVideoDialog', callBack); } function openSchoolVrFileDialog(callBack) { generalIpcCall('openSchoolVrFileDialog', callBack); } function saveSchoolVrFileDialog(callBack) { generalIpcCall('saveSchoolVrFileDialog', callBack); } /* end of window dialog */ /* vanilla electron dialog */ function showOpenDialog(options, callBack) { generalIpcCall('showOpenDialog', callBack, options); } function showSaveDialog(options, callBack) { generalIpcCall('showSaveDialog', callBack, options); } /* end of vanilla electron dialog */ /* show message box */ function showYesNoQuestionMessageBox(message, detail, callBack) { generalIpcCall('showYesNoQuestionMessageBox', callBack, { message: message, detail: detail }); } function showYesNoWarningMessageBox(message, detail, callBack) { generalIpcCall('showYesNoWarningMessageBox', callBack, { message: message, detail: detail }); } /* end of show message box */ /* for presentation */ function getPresentationServerInfo(callBack) { generalIpcCall('getPresentationServerInfo', callBack); } function openWebServerAndLoadProject(filePath, callBack) { generalIpcCall('openWebServerAndLoadProject', callBack, filePath); } function closeWebServer(callBack) { generalIpcCall('closeWebServer', callBack); } /* end of for presentation */ /* app data */ function getCustomizedAppData(callBack) { generalIpcCall('getCustomizedAppData', (err, data) => { callBack(err, data && data.appDataObjStr && JSON.parse(data.appDataObjStr)); }); } function setCustomizedAppData(appDataObj, callBack) { generalIpcCall('setCustomizedAppData', callBack, { appDataObjStr: JSON.stringify(appDataObj) }); } function checkIdentity(callBack) { generalIpcCall('checkIdentity', callBack); } const checkIdentityPromise = promisify(checkIdentity); function setLicenseKey(licenseKey, callBack) { generalIpcCall('setLicenseKey', callBack, { licenseKey: licenseKey }); } const setLicenseKeyPromise = promisify(setLicenseKey); /* end of app data */ /* 360 capture */ function saveRaw360Capture(imgBase64Str, callBack) { generalIpcCall('saveRaw360Capture', callBack, { imgBase64Str: imgBase64Str }); } function saveRaw360CaptureForVideo(videoUuid, fps, currentFrame, totalFrame, imgBase64Str, callBack) { generalIpcCall('saveRaw360CaptureForVideo', callBack, { videoUuid: videoUuid, fps: fps, currentFrame: currentFrame, totalFrame: totalFrame, imgBase64Str: imgBase64Str }); } /* end of 360 capture */ /* presentation mode 2D recording */ // function savePresentationRecordingInMp4(videoBlob, callBack) { // generalIpcCall('savePresentationRecordingInMp4', callBack, { // videoBlob: videoBlob // }); // } /* end of presentation mode 2D recording */ export default { // listeners addListener, removeListener, // config getParamsFromExternalConfig, // app getAppData, // network interfaces getMacAddress, getMacAddressPromise, // shell shellOpenItem, shellOpenExternal, // electron window api newBrowserWindow, closeWindow, minimizeWindow, toggleMaximizeWindow, toggleDevTools, // fileSystem mimeStat, mimeStats, base64Encode, base64Decode, createPackage, extractAll, readdir, readFile, writeFile, deleteFile, renameFile, copyFile, // saveLoadProject listProjects, saveProject, parseDataToSaveFormat, loadProjectByProjectFilePath, isCurrentLoadedProject, // window dialog openImageDialog, openGifDialog, openVideoDialog, openSchoolVrFileDialog, saveSchoolVrFileDialog, // vanilla electron dialog showOpenDialog, showSaveDialog, // show message box showYesNoQuestionMessageBox, showYesNoWarningMessageBox, // for presentation getPresentationServerInfo, openWebServerAndLoadProject, closeWebServer, // customized app data getCustomizedAppData, setCustomizedAppData, checkIdentity, checkIdentityPromise, setLicenseKey, setLicenseKeyPromise, // 360 capture saveRaw360Capture, saveRaw360CaptureForVideo, // presentation mode 2D recording //savePresentationRecordingInMp4 };<file_sep>/src/utils/authentication/auth.js import config from 'globals/config'; import ipcHelper from 'utils/ipc/ipcHelper'; import {postAuthenticateLicensePromise} from 'utils/apis/authApi'; // https://tylermcginnis.com/react-router-protected-routes-authentication/ let isAuthenticated = false; let currentMacAddress; const getMacAddressPromise = async _ => { if (!currentMacAddress) { currentMacAddress = await ipcHelper.getMacAddressPromise(); } return currentMacAddress; }; const checkLicenseKeyAndMacAddressOnCloudPromise = async (licenseKey, mac) => { try { const { isAuthenticated: isIdentityValid } = await postAuthenticateLicensePromise(licenseKey, mac); return isIdentityValid; } catch (err) { console.error('checkLicenseKeyAndMacAddressOnCloudPromise Error:'); console.error(err); // silence error // reject return false; } } // return boolean indicating isIdentityValid const checkIdentityPromise = async (licenseKeyEntered) => { // if it's electron app, return true if (!config.isElectronApp) { return true; } // check identity by checking local files const { isIdentityValid: isIdentityValidCheckResultFromLocalFiles } = await ipcHelper.checkIdentityPromise(); // if local file check is positive, return true if (isIdentityValidCheckResultFromLocalFiles) { return true; } // if local file check is negative, have to check on cloud // by sending licenseKeyEntered and macAddress to cloud api // if no license key is input, return false if (!licenseKeyEntered) { return false; } const { mac: macAddress } = await getMacAddressPromise(); const isIdentityValidCheckResultFromCloud = await checkLicenseKeyAndMacAddressOnCloudPromise(licenseKeyEntered, macAddress); // save license key to local files, // set empty string meaning erasing license key record in local files let licenseKeyToSetToLocalFile = isIdentityValidCheckResultFromCloud ? licenseKeyEntered : ''; ipcHelper.setLicenseKeyPromise(licenseKeyToSetToLocalFile); return isIdentityValidCheckResultFromCloud; } const authenticatePromise = async _ => { isAuthenticated = await checkIdentityPromise(null); return isAuthenticated; }; const authenticateWithLicenseKeyPromise = async (licenseKeyEntered) => { isAuthenticated = await checkIdentityPromise(licenseKeyEntered); return isAuthenticated; }; // no use currently const signoutPromise = new Promise((resolve, reject) => { isAuthenticated = false; setTimeout(_ => { resolve(); }, 1000); // fake async }); const getIsAuthenticated = _ => { return isAuthenticated; } export { authenticatePromise, authenticateWithLicenseKeyPromise, signoutPromise, // no use currently getIsAuthenticated };<file_sep>/src/components/pulsatingContainer.js import React from 'react'; import styled, {keyframes} from 'styled-components'; import setNumberValueWithDefault from 'utils/js/setNumberValueWithDefault'; const pulsatingKeyframes = (minScale, maxScale) => keyframes` 0% { transform: scale(${minScale}); } 100% { transform: scale(${maxScale}); } `; const PulsatingContainerStyleComponent = styled.div` animation-name: ${props => pulsatingKeyframes(setNumberValueWithDefault(props.minScale, 0.8), setNumberValueWithDefault(props.maxScale, 1.2))}; animation-iteration-count: infinite; animation-timing-function: linear; animation-direction: alternate; animation-duration: ${props => setNumberValueWithDefault(props.animationDurationInSecs, 0)}s; `; // render props pattern // https://codeburst.io/animating-react-components-with-css-and-styled-components-cc5a0585f105 function PulsatingContainer(props) { const { minScale, maxScale, animationDurationInSecs, children } = props; return ( <PulsatingContainerStyleComponent minScale={minScale} maxScale={maxScale} animationDurationInSecs={animationDurationInSecs} > {children} </PulsatingContainerStyleComponent> ); } export default PulsatingContainer;<file_sep>/src/containers/aframeEditor/homePage/infoPanel/colorPicker.js import React, {Component, Fragment} from 'react'; import {SketchPicker} from 'react-color'; import iconPrev from 'media/icons/prev.svg'; class ColorPicker extends Component { constructor(props) { super(props); this.state = { displayColorPicker: false, color: props.color } this.callback = this.props.onUpdate || function() {}; this.props.currentEntity.el.setAttribute(props.field, 'color:' + props.color); this.handleClick = this.handleClick.bind(this); this.handleClose = this.handleClose.bind(this); this.handleChange = this.handleChange.bind(this); } componentDidUpdate(prevProps, prevState) { const props = this.props; // const state = this.state; // console.log(props.timelineId, prevProps.timelineId, props.timelinePosition, prevProps.timelinePosition); if (props.timelinePosition !== prevProps.timelinePosition) { const element = this.props.currentEntity.el; element.setAttribute(props.field, 'color:' + props.color); if (element.children) { Array.prototype.slice.call(element.children).forEach(child => { child.setAttribute(props.field, 'color:' + props.color); }) } this.setState({ color: props.color }) } return true; } handleClick() { this.setState({ displayColorPicker: !this.state.displayColorPicker }) }; handleClose() { this.setState({ displayColorPicker: false }) // update final color // console.log('final color: ', this.state.color) const callback = this.callback; if (typeof(callback) === "function") { callback(this.state.color); } }; handleChange(color) { // console.log(color); const props = this.props; const element = props.currentEntity.el; this.setState({ color: color.hex }); element.setAttribute(props.field, 'color:' + color.hex); if (element.children) { Array.prototype.slice.call(element.children).forEach(child => { child.setAttribute(props.field, 'color:' + color.hex); }) } }; render() { // const props = this.props; const state = this.state; return <Fragment> <div className="color-preview" style={{backgroundColor: state.color}} onClick={ this.handleClick } /> { this.state.displayColorPicker ? <div style={{ position: 'absolute', zIndex: 2, top: 0, right: 0, bottom: 0, left: 0, borderRadius: 15 }}> <div style={{ position: 'fixed', top: '0px', right: '0px', bottom: '0px', left: '0px', }} onClick={this.handleClose} /> <div className="back-button" onClick={this.handleClose}> <img src={iconPrev} alt="Back"/> </div> <SketchPicker color={state.color} onChange={this.handleChange} disableAlpha={true} presetColors={[ "#FF0000", "#FF8000", "#FFFF00", "#008000", "#0000FF", "#8000FF", "#FFFFFF", "#000000", ]} styles={{ default: { picker: { background: '#03141c', width: '100%', //height: '100%', boxSizing: 'border-box', borderRadius: 15, paddingTop: 0, }, hue: { position: 'relative', height: '20px', overflow: 'hidden' }, saturation: { paddingBottom: '30%' } }, disableAlpha: { hue: { height: '20px' }, color: { height: '20px' } } }} /> </div> : null } </Fragment> } } export default ColorPicker;<file_sep>/public/utils/crypto.js const crypto = require('crypto'); function cleanString(str) { return str.replace(/[\\\/\.]/g, ''); } // https://medium.com/@chris_72272/what-is-the-fastest-node-js-hashing-algorithm-c15c1a0e164e function someHash(data) { const sha1Hash = crypto.createHash('sha1'); const intermediateResult = sha1Hash.update(data).digest('base64'); const result = cleanString(intermediateResult); return result; } function hashForUniqueId(data) { return someHash(data); } module.exports = { hashForUniqueId };<file_sep>/src/pages/aframeEditor/presenterPage.js import React, {Component} from 'react'; // import SystemPanel from 'containers/aframeEditor/homePage/systemPanel'; import {withRouter, Link, Prompt} from 'react-router-dom'; import {withSceneContext} from 'globals/contexts/sceneContext'; import {LanguageContextConsumer, LanguageContextMessagesConsumer} from 'globals/contexts/locale/languageContext'; import MenuComponent from 'components/menuComponent'; import Mousetrap from 'mousetrap'; //import ButtonsPanel from 'containers/aframeEditor/homePage/buttonsPanel'; import AFramePanel from 'containers/aframeEditor/homePage/aFramePanel'; //import InfoPanel from 'containers/aframeEditor/homePage/infoPanel'; import SlidesPanel from 'containers/aframeEditor/homePage/slidesPanel'; //import TimelinePanel from 'containers/aframeEditor/homePage/timelinePanel'; // import AssetsPanel from 'containers/aframeEditor/homePage/assetsPanel'; import TwinklingContainer from 'components/twinklingContainer'; import PulsatingContainer from 'components/pulsatingContainer'; import Editor from 'vendor/editor.js'; // import {addEntityAutoType} from 'utils/aFrameEntities'; // import {roundTo, jsonCopy} from 'globals/helperfunctions'; // import {TweenMax, TimelineMax, Linear} from 'gsap'; import io from 'socket.io-client'; import isNonEmptyArray from 'utils/variableType/isNonEmptyArray'; import handleErrorWithUiDefault from 'utils/errorHandling/handleErrorWithUiDefault'; import ipcHelper from 'utils/ipc/ipcHelper'; //import fileHelper from 'utils/fileHelper/fileHelper'; import {jsonCopy} from "globals/helperfunctions"; import routes from 'globals/routes'; import config from 'globals/config'; import {getSearchObjectFromHistory} from 'utils/queryString/getSearchObject'; import getProjectFilePathFromSearchObject from 'utils/queryString/getProjectFilePathFromSearchObject'; import saveAs from 'utils/fileSaver/saveAs'; import {formatDateTimeForFileName} from 'utils/dateTime/formatDateTime'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; //import iconViewer from 'media/icons/viewer.svg'; import './presenterPage.css'; const Events = require('vendor/Events.js'); //const uuid = require('uuid/v1'); // const jsonSchemaValidator = require('jsonschema').Validator; // const validator = new jsonSchemaValidator(); // const schema = require('schema/aframe_schema_20181108.json'); function PresenterPageMenu(props) { const { handleOpenProjectButtonClick, } = props; return ( <MenuComponent // projectName="Untitled_1" menuButtons={[ { labelId: 'Menu.FileLabel', // onClick: _=> { console.log('file') }, children: [ { labelId: 'Menu.File.HomeLabel', disabled: false, methodNameToInvoke: 'goToHomePage' }, { labelId: '-' }, { labelId: 'Menu.File.OpenLabel', disabled: false, onClick: handleOpenProjectButtonClick }, { labelId: '-' }, { labelId: 'Menu.File.ExitLabel', disabled: false, methodNameToInvoke: 'closeApp' } ] } ]} /> ); } class PresenterPage extends Component { constructor(props) { super(props); // constants this.recordingTimerIntervalInMillis = 1000; this.state = { socket: null, localIps: [], viewerCount: 0, loadedProjectFilePath: '', showUi: true, recordingTimerInfo: null }; [ // event handlers 'onEditorLoad', 'handleRecordingTimerEvent', 'handleButtonRecordSlideClick', 'handleButtonPrevSlideClick', 'handleButtonPlaySlideClick', 'handleButtonNextSlideClick', // menu buttons 'handleOpenProjectButtonClick', // methods 'loadProject', 'getNewSceneDataWithAssetsListChangedToUsingRelativePaths', 'showUi', 'hideUi', 'saveRecording', 'startRecording', 'stopRecording', ].forEach(methodName => { this[methodName] = this[methodName].bind(this); }); this.hideUiTimer = null; } /* react lifecycles */ componentDidMount() { const props = this.props; const sceneContext = props.sceneContext; this.editor = new Editor(); Events.on('editor-load', this.onEditorLoad) sceneContext.updateEditor(this.editor); ipcHelper.getPresentationServerInfo((err, data) => { if (err) { handleErrorWithUiDefault(err); return; } const presentationServerPort = data.port; // get the ip and port from ipc // const socket = io(window.location.origin); const presentationUrl = `http://localhost:${presentationServerPort}`; const socket = io(presentationUrl); socket.on('connect', () => { console.log('connected!!!'); // socket.connected); // true // ipcHelper.shellOpenExternal(presentationUrl); socket.emit('registerPresenter'); }); socket.on('serverMsg', (msg) => { console.log('message from server: ', msg); }) socket.on('updateViewerCount', (count) => { this.setState({ viewerCount: count }) }) // document.addEventListener('dblclick', this.sendMessage); const interfaceIpArr = Object.keys(data.interfaceIpMap).map(interfaceName => { return { interface: interfaceName, ip: data.interfaceIpMap[interfaceName] } }); this.setState({ localIps: interfaceIpArr, port: presentationServerPort, socket: socket }); }); Mousetrap.bind('left', (e) => { e.preventDefault(); // get current slide const slidesList = sceneContext.getSlidesList(); const currentSlide = sceneContext.getCurrentSlideId(); const currentSlideIdx = slidesList.findIndex(slide => slide.id === currentSlide); const prevSlide = (currentSlideIdx < 1? null: slidesList[currentSlideIdx - 1]['id']); const { socket } = this.state; if (prevSlide) { sceneContext.selectSlide(prevSlide); if (socket) { socket.emit('updateSceneStatus', { action: 'selectSlide', details: { slideId: prevSlide } }); } } return false; }); Mousetrap.bind('right', (e) => { e.preventDefault(); const slidesList = sceneContext.getSlidesList(); const currentSlide = sceneContext.getCurrentSlideId(); const currentSlideIdx = slidesList.findIndex(slide => slide.id === currentSlide); const nextSlide = (currentSlideIdx > slidesList.length - 2? null: slidesList[currentSlideIdx + 1]['id']); const { socket } = this.state; if (nextSlide) { sceneContext.selectSlide(nextSlide); if (socket) { socket.emit('updateSceneStatus', { action: 'selectSlide', details: { slideId: nextSlide } }) } } return false; }); this.hideUi(); } componentWillUnmount() { this.editor = null; // ipcHelper.closeWebServer((err) => { // if (err) { // handleErrorWithUiDefault(err); // return; // } // }); const { sceneContext } = this.props; sceneContext.setProjectName(''); Events.removeListener('editor-load', this.onEditorLoad); this.stopRecording(false); } /* end of react lifecycles */ /* event handlers */ // event handlers onEditorLoad(editor) { const props = this.props; editor.close(); // load project const searchObj = getSearchObjectFromHistory(props.history); const projectFilePathToLoad = getProjectFilePathFromSearchObject(searchObj); console.log("project path to load: " + projectFilePathToLoad); if (projectFilePathToLoad) { this.loadProject(projectFilePathToLoad); } } handleRecordingTimerEvent(recordingTimerInfo) { this.setState({ recordingTimerInfo: recordingTimerInfo }); } handleButtonRecordSlideClick(event) { const { sceneContext } = this.props; if (!sceneContext.isInPresentationRecording) { this.startRecording(); } else { this.stopRecording(true); } } handleButtonPrevSlideClick(event) { const { sceneContext } = this.props; const { socket } = this.state; const slidesList = sceneContext.getSlidesList(); const currentSlide = sceneContext.getCurrentSlideId(); const currentSlideIdx = slidesList.findIndex(slide => slide.id === currentSlide); const prevSlide = (currentSlideIdx < 1? null: slidesList[currentSlideIdx - 1]['id']); if (prevSlide) { sceneContext.selectSlide(prevSlide); if (socket) { socket.emit('updateSceneStatus', { action: 'selectSlide', details: { slideId: prevSlide, autoPlay: false } }) } } } handleButtonPlaySlideClick(event) { const { sceneContext } = this.props; const { socket } = this.state; sceneContext.playSlide(); if (socket) { socket.emit('updateSceneStatus', { action: 'playSlide' }); } } handleButtonNextSlideClick(event) { const { sceneContext } = this.props; const { socket } = this.state; const slidesList = sceneContext.getSlidesList(); const currentSlide = sceneContext.getCurrentSlideId(); const currentSlideIdx = slidesList.findIndex(slide => slide.id === currentSlide); const nextSlide = (currentSlideIdx > slidesList.length - 2? null: slidesList[currentSlideIdx + 1]['id']); if (nextSlide) { sceneContext.selectSlide(nextSlide); if (socket) { socket.emit('updateSceneStatus', { action: 'selectSlide', details: { slideId: nextSlide, autoPlay: false } }) } } } // menu buttons handleOpenProjectButtonClick(event) { ipcHelper.openSchoolVrFileDialog((err, data) => { if (err) { handleErrorWithUiDefault(err); return; } const filePaths = data.filePaths; if (!isNonEmptyArray(filePaths)) { return; } this.loadProject(filePaths[0]); }); } /* end of event handlers */ /* methods */ loadProject(projectFilePath) { const { socket } = this.state; const sceneContext = this.props.sceneContext; this.setState({ loadedProjectFilePath: projectFilePath }); ipcHelper.openWebServerAndLoadProject(projectFilePath, (err, data) => { // ipcHelper.loadProjectByProjectFilePath(projectFilePath, (err, data) => { if (err) { handleErrorWithUiDefault(err); return; } const projectJsonData = data.projectJson; //console.log(projectJsonData); // send a copy to server if (socket) { // for the following projectJsonData, the assetsList's paths all are changed to web server relative path const newProjectJsonData = this.getNewSceneDataWithAssetsListChangedToUsingRelativePaths(projectJsonData); socket.emit('useSceneData', newProjectJsonData); } sceneContext.loadProject(projectJsonData); }); } // TODO: poorly written (too many cross-references to ProjectFile class) // for web server presentation, use asset's relativeSrc to replace src getNewSceneDataWithAssetsListChangedToUsingRelativePaths(sceneData) { const projectJson = jsonCopy(sceneData); const assetsList = projectJson.assetsList; assetsList.forEach(asset => { asset.src = asset.relativeSrc; }); return projectJson; } showUi() { if (this.hideUiTimer) { clearTimeout(this.hideUiTimer); } this.setState({ showUi: true }) } hideUi() { if (this.hideUiTimer) { clearTimeout(this.hideUiTimer); } this.hideUiTimer = setTimeout(()=>{ this.setState({ showUi: false }) }, 2500); } saveRecording(mediaObjToSave) { const tempMediaFileName = `sharingRecording_${formatDateTimeForFileName(Date.now())}${config.presentationRecordingVideoExtension}`; saveAs(mediaObjToSave, tempMediaFileName); // if (fileHelper.getFileExtensionWithoutLeadingDot(tempMediaFileName) === 'mp4') { // } else { // saveAs(mediaObjToSave, tempMediaFileName); // } } startRecording() { const { sceneContext } = this.props; if (!sceneContext.isInPresentationRecording) { const fps = config.presentationRecordingVideoFps; const handleRecordingErrorCallback = err => { console.error('mediaRecorder.onerror', err); alert('mediaRecorder.onerror', err); }; sceneContext.startRecording(fps, this.recordingTimerIntervalInMillis, this.handleRecordingTimerEvent, handleRecordingErrorCallback); } } stopRecording(isDownloadVideo) { const { sceneContext } = this.props; if (sceneContext.isInPresentationRecording) { const videoOutputExtensionWithDot = config.presentationRecordingVideoExtension; const handleRecordingAvailableCallback = isDownloadVideo ? this.saveRecording : null; sceneContext.stopRecording(videoOutputExtensionWithDot, handleRecordingAvailableCallback); this.setState({ recordingTimerInfo: null }); } } /* end of methods */ render() { const { sceneContext } = this.props; const { localIps, port, viewerCount, loadedProjectFilePath: projectFilePathToLoad, showUi, socket, recordingTimerInfo } = this.state; const slidesList = sceneContext.getSlidesList(); const currentSlide = sceneContext.getCurrentSlideId(); const currentSlideIdx = slidesList.findIndex(slide => slide.id === currentSlide); const isInPresentationRecording = sceneContext.isInPresentationRecording; // for exit button // const searchObj = getSearchObjectFromHistory(this.props.history); //console.log(loadedProjectFilePath); return ( <div id="presenter" className={showUi? 'show-ui': 'hide-ui'}> <LanguageContextConsumer render={ ({ messages }) => ( <Prompt when={isInPresentationRecording} message={messages['Prompt.IncompleteRecordingMessage']} /> ) } /> {/* <SystemPanel projectName={this.projectName} /> */} <PresenterPageMenu handleOpenProjectButtonClick={this.handleOpenProjectButtonClick} /> {/* <ButtonsPanel /> */} <AFramePanel disableVR={true} socket={socket} user-mode="presenter" /> <SlidesPanel isEditing={false} socket={socket} /> {/* <TimelinePanel /> */} {/* <InfoPanel /> */} <div className="interfaceIp-panel" onMouseEnter={this.showUi} onMouseLeave={this.hideUi} > {localIps.map(localIp => { return <div className="interfaceIp-data" key={localIp.ip}> <div className="interface">{localIp.interface}</div> <div className="ip">{localIp.ip}:{port}</div> </div>; })} </div> <div className="viewerCount-panel" onMouseEnter={this.showUi} onMouseLeave={this.hideUi} > <svg viewBox="0 0 27.43 30.17" xmlSpace="preserve"> <g transform="translate(-380.000000, -1646.000000)"> <g transform="translate(0.000000, 1519.000000)"> <g transform="translate(380.000000, 127.371429)"> <path style={{ fillRule: 'evenodd', clipRule: 'evenodd', fill: 'currentColor' }} d="M6.49,18.13c0.63,0,1.15,0.52,1.15,1.16c0,0.41-0.2,0.76-0.52,0.97c-2.65,1.9-4.49,4.91-4.82,8.37 c0,0,0,0,0,0c0,0.64-0.51,1.16-1.15,1.16c-0.63,0-1.15-0.52-1.15-1.16L0,28.64c0.34-4.25,2.55-7.95,5.8-10.27 C5.99,18.22,6.23,18.13,6.49,18.13 M27.41,28.64l0.02,0.21c-0.01-0.06-0.02-0.13-0.02-0.19c-0.01,0.63-0.52,1.15-1.14,1.15 c-0.63,0-1.15-0.52-1.15-1.16h0c-0.57-5.9-5.46-10.51-11.4-10.51l-0.01,0c-0.01,0-0.02,0-0.03,0c-5.02,0-9.09-4.14-9.09-9.25 s4.07-9.25,9.09-9.25c0.01,0,0.01,0,0.02,0c0.01,0,0.01,0,0.02,0c5.02,0,9.09,4.14,9.09,9.24c0,1.91-0.58,3.67-1.56,5.14 c-0.01,0.02-0.02,0.03-0.03,0.04c-0.14,0.21-0.29,0.42-0.45,0.62c-0.05,0.07-0.11,0.14-0.17,0.2c-0.15,0.17-0.29,0.34-0.45,0.5 c-0.11,0.12-0.24,0.23-0.36,0.34c-0.18,0.16-0.36,0.32-0.55,0.47c-0.19,0.15-0.38,0.29-0.59,0.43c-0.04,0.02-0.07,0.05-0.1,0.08 c4.8,1.83,8.32,6.31,8.85,11.68C27.4,28.46,27.41,28.55,27.41,28.64 M13.71,15.79c0.23,0,0.46-0.01,0.68-0.04 c3.42-0.36,6.09-3.3,6.09-6.88c0-3.82-3.04-6.91-6.8-6.91C13.45,1.96,13.22,1.97,13,2C9.58,2.36,6.91,5.3,6.91,8.87 C6.91,12.69,9.95,15.79,13.71,15.79"/> </g> </g> </g> </svg> <div className="viewCount-text">{viewerCount}</div> </div> <div className="slideFunctions-panel" onMouseEnter={this.showUi} onMouseLeave={this.hideUi} > <div className="buttons-group"> <div className={`button-prevSlide${currentSlideIdx === 0 ? ' disabled' : ''}`} onClick={this.handleButtonPrevSlideClick} > <FontAwesomeIcon icon="angle-left"/> </div> <div className="button-playSlide" onClick={this.handleButtonPlaySlideClick} > <FontAwesomeIcon icon="play"/> </div> <div className={`button-nextSlide${currentSlideIdx === slidesList.length - 1? ' disabled': ''}`} onClick={this.handleButtonNextSlideClick} > <FontAwesomeIcon icon="angle-right"/> </div> </div> <div className="buttons-group"> <div className={`button-recordSlide`} onClick={this.handleButtonRecordSlideClick}> {isInPresentationRecording? <FontAwesomeIcon icon="video-slash"/> : <FontAwesomeIcon icon="video"/> } </div> </div> <div className="buttons-group"> <LanguageContextConsumer render={ ({ messages }) => ( <select value={currentSlide} onChange={e => { sceneContext.selectSlide(e.currentTarget.value); if (socket) { socket.emit('updateSceneStatus', { action: 'selectSlide', details: { slideId: e.currentTarget.value, autoPlay: false } }) } }} > { slidesList.map((slide, idx) => { return <option key={slide.id} value={slide.id}>{`${messages['Navigation.SlideSelect.SlideIndexPrefix']} ${idx + 1}`}</option> }) } </select> ) } /> </div> <div className="buttons-group"> <Link to={routes.editorWithProjectFilePathQuery(projectFilePathToLoad)}> <LanguageContextMessagesConsumer messageId='PresentationPanel.ExitLabel' /> </Link> </div> </div> <div className="show-ui-hints" onMouseEnter={this.showUi} /> { isInPresentationRecording && <div className="recordingInfo-panel"> <TwinklingContainer animationDurationInSecs={1} minOpacity={0.2} maxOpacity={1} > <PulsatingContainer animationDurationInSecs={1} minScale={0.95} maxScale={1.05} > <div className="is-recording-hint"><FontAwesomeIcon icon="video"/></div> </PulsatingContainer> </TwinklingContainer> { <div className="is-recording-timer"> { ( recordingTimerInfo ? [ recordingTimerInfo.hours, recordingTimerInfo.minutes, recordingTimerInfo.seconds ] : [0, 0, 0] ) .map(num => String(num).padStart(2, '0')).join(':') } </div> } </div> } </div> ); } } export default withSceneContext(withRouter(PresenterPage));<file_sep>/src/components/pulsatingImage.js import React, { Component } from 'react'; import PulsatingContainer from 'components/pulsatingContainer'; import './pulsatingImage.css'; function PulsatingImageContent(props) { const pulsatingImageStyle = { width: props.width, height: props.height }; return ( <div className={`pulsating-image ${props.imageContainerClassName || ''}`} style={pulsatingImageStyle}> <img src={props.src} alt={props.alt} /> </div> ); } class PulsatingImage extends Component { render() { const { animationDurationInSecs, ...rest } = this.props; return ( <PulsatingContainer animationDurationInSecs={animationDurationInSecs}> <PulsatingImageContent {...rest} /> </PulsatingContainer> ); } } export default PulsatingImage; export {PulsatingImageContent};<file_sep>/src/containers/aframeEditor/panelItem/editorFunctions.js import React from 'react'; import AFRAME from 'aframe'; // do not uncomment as aframe-gif-shader requires AFRAME import 'aframe-gif-shader'; const Events = require('vendor/Events.js'); const uuid_0 = require('uuid/v1'); const uuid = _=> 'uuid_' + uuid_0().split('-')[0]; let editor = null; Events.on('editor-load', obj => { editor = obj; }); function addToAsset(el) { let assetEl = document.querySelector('a-asset'); if (!assetEl) { assetEl = document.createElement('a-asset'); editor.sceneEl.append(assetEl); } assetEl.append(el); let newid; switch (el.tagName) { case 'VIDEO': newid = 'vid_' + uuid() // 'vid_' + document.querySelectorAll('video').length; el.loop = true; break; case 'IMG': newid = 'img_' + uuid() // 'img_' + document.querySelectorAll('img').length; break; default: console.log('editorFunctions_addToAsset: ???'); break; } el.setAttribute('id', newid); Events.emit('addAsset', (el.tagName === 'VIDEO'? 'video': 'image'), newid, el.src ); return newid; } // this function may use later to combine the handleUpload functions function getFileType(base64file) { // console.log(base64file); let fileinfo = base64file.split(/[:;\/]/); let filetype = fileinfo[1]; let fileext = fileinfo[2]; return fileext; } function addNewBox(renderBtn = true) { function clickBtn() { // let x = prompt('width',1); // let y = prompt('height',1); // let z = prompt('depth',1); const id = uuid(); var newEl = editor.createNewEntity({ element: 'a-box', components: { 'id': id, // 'geometry': { // 'primitive': 'box', // 'width': 1, // x, // 'height': 1, // y, // 'depth': 1, // z, // }, 'material': { 'color': '#FFFFFF', opacity: 0.1, transparent: true }, 'rotation': { x: 0, y: 45, z: 0 } } }); // newEl.setAttribute('geometry',{ // // 'primitive': 'box', // 'width': 1, // x, // 'height': 1, // y, // 'depth': 1, // z, // }); // newEl.setAttribute('material', {'color': '#FFFF00'}); // newEl.setAttribute('position', {x:0, y:0, z:0}); } if (renderBtn) { return <button key="addNewBox" onClick={clickBtn}> Add a Box </button>; } else { return clickBtn(); } } function addNewCone() { function clickBtn() { var newEl = editor.createNewEntity({ element: 'a-cone' }); newEl.setAttribute('geometry', { // 'primitive': 'cone' 'radiusTop': 0, // 'radiusBottom': 0.2, 'radius': 0.5 }); newEl.setAttribute('material', 'color', '#FFFFFF'); newEl.setAttribute('position', { x: 0, y: 1, z: 0 }); } return <button key="addNewCone" onClick={clickBtn}> Add a Cone </button>; } function addNewCylinder() { function clickBtn() { var newEl = editor.createNewEntity({ element: 'a-cylinder' }); newEl.setAttribute('geometry', { // 'primitive': 'cylinder', 'radius': 0.5 }); newEl.setAttribute('material', 'color', '#FFFFFF'); newEl.setAttribute('position', { x: 0, y: 1, z: 0 }); } return <button key="addNewCylinder" onClick={clickBtn}> Add a Cylinder </button>; } function addNewPlane() { function clickBtn() { var newEl = editor.createNewEntity({ element: 'a-plane' }); // newEl.setAttribute('geometry',{ // 'primitive': 'torusKnot', // 'p': 3, // 'q': 7 // }); newEl.setAttribute('material', 'color', '#FFFFFF'); newEl.setAttribute('position', { x: 0, y: 1, z: 0 }); } return <button key="addNewPlane" onClick={clickBtn}> Add a Plane </button>; } function addNewTriangle() { function clickBtn() { var newEl = editor.createNewEntity({ element: 'a-triangle' }); newEl.setAttribute('geometry', { 'primitive': 'triangle', }); newEl.setAttribute('material', { 'color': '#FFFFFF', 'opacity': 0.3, 'transparent': true }); newEl.setAttribute('position', { x: 0, y: 1, z: 0 }); } return <button key="addNewTriangle" onClick={clickBtn}> Add a Triangle </button>; } function addNewImage() { function clickBtn() { let fileupload = document.getElementById('selectImage'); fileupload.click(); } function handleUpload(event) { var self = event.target; if (self.files && self.files[0]) { var reader = new FileReader(); reader.onload = function (e) { let img = new Image(); img.onload = function () { let w = this.width; let h = this.height; if (w > h) { w = w / h; h = 1; } else { h = h / w; w = 1; } let newid = addToAsset(img); var newEl = editor.createNewEntity({ element: 'a-image' }); newEl.setAttribute('geometry', { 'height': h, 'width': w }); newEl.setAttribute('src', '#' + newid); newEl.setAttribute('position', { x: 0, y: 1, z: 0 }); // after the file loaded, clear the input self.value = ''; } img.src = e.target.result; }; reader.readAsDataURL(self.files[0]); } } return <span key="addNewImage"> <input id="selectImage" type="file" onChange={handleUpload} hidden /> <button onClick={clickBtn}> Add an Image </button> </span>; } function addNewGif() { function clickBtn() { let fileupload = document.getElementById('selectGif'); fileupload.click(); } function handleUpload(event) { var self = event.target; if (self.files && self.files[0]) { var reader = new FileReader(); reader.onload = function (e) { let img = new Image(); img.onload = function () { let w = this.width; let h = this.height; if (w > h) { w = w / h; h = 1; } else { h = h / w; w = 1; } let newid = addToAsset(img); var newEl = editor.createNewEntity({ element: 'a-image' }); newEl.setAttribute('geometry', { 'height': h, 'width': w }); // newEl.setAttribute('src', '#'+ newid ); newEl.setAttribute('material', 'shader:gif;src:#' + newid + ''); newEl.setAttribute('position', { x: 0, y: 1, z: 0 }); // after the file loaded, clear the input self.value = ''; } img.src = e.target.result; }; reader.readAsDataURL(self.files[0]); } } return <span key="addNewGif"> <input id="selectGif" type="file" onChange={handleUpload} hidden /> <button onClick={clickBtn}> Add a Gif </button> </span>; } function addNewVideo() { function clickBtn() { let fileupload = document.getElementById('selectVideo'); fileupload.click(); } function handleUpload(event) { var self = event.target; if (self.files && self.files[0]) { var reader = new FileReader(); reader.onload = function (e) { let vid = document.createElement('video'); vid.addEventListener('loadedmetadata', function () { let w = vid.videoWidth; let h = vid.videoHeight; // let d = vid.duration; // vid.playbackRate if (w > h) { w = w / h; h = 1; } else { h = h / w; w = 1; } let newid = addToAsset(vid); var newEl = editor.createNewEntity({ element: 'a-video' }); newEl.setAttribute('geometry', { 'height': h, 'width': w }); newEl.setAttribute('src', '#' + newid); // handle the video playing when toogle editor // delete will cause error, comment out first // Events.on('editormodechanged', is_open => { // if (is_open) { // newEl.getObject3D('mesh').material.map.image.pause(); // } else { // newEl.getObject3D('mesh').material.map.image.play(); // } // }); // direct use the video without a-asset // newEl.setAttribute('src', e.target.result ); // pause on add // newEl.getObject3D('mesh').material.map.image.pause(); newEl.setAttribute('position', { x: 0, y: 1, z: 0 }); // after the file loaded, clear the input self.value = ''; }); vid.setAttribute('src', e.target.result); }; reader.readAsDataURL(self.files[0]); } } return <span key="addNewVideo"> <input id="selectVideo" type="file" onChange={handleUpload} hidden /> <button onClick={clickBtn}> Add a Video </button> </span>; } function addNewText() { function clickBtn() { let text = prompt('Please enter the text to add', 'type text here'); if (text) { let textSize = 10; let width = text.length; let textCount = text.length; let wrapCount = text.length; var newEl = editor.createNewEntity({ element: 'a-text' }); // newEl.setAttribute('value',text); // newEl.setAttribute('width', textSize); // newEl.setAttribute('align','center'); // newEl.setAttribute('side','double'); // newEl.setAttribute('wrap-count', wrapCount ); newEl.setAttribute('text', { 'value': text, 'width': width, 'align': 'center', 'color': '#FFFF00', // 'side':'double', 'side': 'front', 'wrapCount': wrapCount }); newEl.setAttribute('position', { x: 0, y: 1, z: 0 }); // add a transparent plane to make sit selectable // newEl.setAttribute('geometry', 'primitive: plane; height: auto; width: auto;'); newEl.setAttribute('geometry', { primitive: 'plane', height: 1.4 * width / textCount, width: width }); newEl.setAttribute('material', { 'color': '#FF0000', 'transparent': true, 'opacity': 0.3 }); } } return <button key="addNewText" onClick={clickBtn}> Add a Text </button>; } function addNewImageSphere() { function clickBtn() { let fileupload = document.getElementById('select360Image'); fileupload.click(); } function handleUpload(event) { const self = event.target; if (self.files && self.files[0]) { console.log("filechoose"); var reader = new FileReader(); reader.onload = function (e) { const img = document.createElement('img'); const newid = addToAsset(img); const newEl = editor.createNewEntity({ element: 'a-sky' }); newEl.setAttribute('src', '#' + newid); // handle the video playing when toogle editor // delete will cause error, comment out first // Events.on('editormodechanged', is_open => { // if (is_open) { // newEl.getObject3D('mesh').material.map.image.pause(); // } else { // newEl.getObject3D('mesh').material.map.image.play(); // } // }); // direct use the video without a-asset // newEl.setAttribute('src', e.target.result ); // pause on add // newEl.getObject3D('mesh').material.map.image.pause(); newEl.setAttribute('position', { x: 0, y: 0, z: 0 }); // after the file loaded, clear the input self.value = ''; img.setAttribute('src', e.target.result); }; reader.readAsDataURL(self.files[0]); } else { console.log('no file choosed'); } } return <span key="addNewImageSphere"> <input id="select360Image" type="file" onChange={handleUpload} hidden /> <button onClick={clickBtn}> Add a 360 Background Image </button> </span>; } function addNewVideoSphere() { function clickBtn() { let fileupload = document.getElementById('select360Video'); fileupload.click(); } function handleUpload(event) { var self = event.target; if (self.files && self.files[0]) { console.log("filechoose"); var reader = new FileReader(); reader.onload = function (e) { let vid = document.createElement('video'); let newid = addToAsset(vid); var newEl = editor.createNewEntity({ element: 'a-videosphere' }); newEl.setAttribute('src', '#' + newid); // handle the video playing when toogle editor // delete will cause error, comment out first // Events.on('editormodechanged', is_open => { // if (is_open) { // newEl.getObject3D('mesh').material.map.image.pause(); // } else { // newEl.getObject3D('mesh').material.map.image.play(); // } // }); // direct use the video without a-asset // newEl.setAttribute('src', e.target.result ); // pause on add // newEl.getObject3D('mesh').material.map.image.pause(); newEl.setAttribute('position', { x: 0, y: 0, z: 0 }); // after the file loaded, clear the input self.value = ''; vid.setAttribute('src', e.target.result); }; reader.readAsDataURL(self.files[0]); } else { console.log('no file choosed'); } } return <span key="addNewVideoSphere"> <input id="select360Video" type="file" onChange={handleUpload} hidden /> <button onClick={clickBtn}> Add a 360 Background Video </button> </span>; } function setControlMode() { function setRotate() { Events.emit('transformmodechanged', 'rotate'); } function setTranslate() { Events.emit('transformmodechanged', 'translate'); } function setScale() { Events.emit('transformmodechanged', 'scale'); } // function setSpace() { // Events.emit('transformmodechanged','scale'); // } return <span key="control-type"> <button onClick={setTranslate}> Translate </button> <button onClick={setRotate}> Rotate </button> <button onClick={setScale}> Scale </button> </span>; } function takeSnapshot() { function snapshot() { Events.emit('takeSnapshot', function (data) { // let list = document.getElementById('entitiesList'); // let snapshotwrapper = document.createElement('div'); // let imgEl = document.createElement('img'); // imgEl.style.width = '100%'; // imgEl.src = data.image; // snapshotwrapper.append(imgEl); // snapshotwrapper.append('<div>position</div>'); // snapshotwrapper.append('<div>'+ // 'x: '+ data.camera.position.x + // ',y: '+ data.camera.position.y + // ',z: '+ data.camera.position.z + // '</div>'); // snapshotwrapper.append('<div>rotation</div>'); // snapshotwrapper.append('<div>'+ // 'x: '+ data.camera.rotation.x + // ',y: '+ data.camera.rotation.y + // ',z: '+ data.camera.rotation.z + // '</div>'); // list.append(snapshotwrapper); }); } return ( <button key="snapshot" onClick={snapshot}> Snapshot </button> ); } export { addNewBox, addNewCone, addNewCylinder, addNewPlane } export { addNewText, addNewTriangle, addNewImage, addNewGif, addNewVideo } export { addNewVideoSphere, addNewImageSphere } export { takeSnapshot } export { setControlMode } <file_sep>/public/globals/config.js const electron = require('electron'); const {app} = electron; const myPath = require('../utils/fileSystem/myPath'); const appName = app.getName(); // https://github.com/electron/electron/blob/master/docs/api/app.md#appgetpathname const appDirectory = {}; appDirectory.appProjectsDirectory = myPath.join(app.getPath('documents'), `${appName}-Projects`); appDirectory.appDataDirectory = myPath.join(app.getPath('appData'), `${appName}-Data`); /* customized app data */ appDirectory.customizedAppDataFile = myPath.join(appDirectory.appDataDirectory, 'customizedAppData.json'); appDirectory.appTempDirectory = myPath.join(app.getPath('appData'), `${appName}-Temp`); appDirectory.appTempProjectsDirectory = myPath.join(appDirectory.appTempDirectory, `${appName}-Projects`); appDirectory.appTempAppWorkingDirectory = myPath.join(appDirectory.appTempDirectory, `${appName}-App-Working`); appDirectory.appTempWebContainerDirectory = myPath.join(appDirectory.appTempAppWorkingDirectory, 'web'); appDirectory.appTempCapturesContainerDirectory = myPath.join(appDirectory.appTempAppWorkingDirectory, 'captures'); console.log('app.getAppPath():', app.getAppPath()); //appDirectory.appAsarInstallationPath = myPath.join(app.getPath('appData'), '..', 'Local', 'Programs', app.getName(), 'resources', 'app.asar'); appDirectory.appAsarInstallationPath = app.getAppPath(); appDirectory.webServerRootDirectory = myPath.join(appDirectory.appAsarInstallationPath, 'build'); // directly serves within app.asar (which acts as a directory) appDirectory.webServerFilesDirectory = myPath.join(appDirectory.appTempWebContainerDirectory, 'files'); /* !!! Important !!! Directories to be created on app start-up */ appDirectory.createOnStartUpDirectories = [ appDirectory.appProjectsDirectory, appDirectory.appDataDirectory, appDirectory.appTempDirectory, appDirectory.appTempProjectsDirectory, appDirectory.appTempAppWorkingDirectory, appDirectory.appTempWebContainerDirectory, appDirectory.appTempCapturesContainerDirectory ]; /* !!! Important !!! Directories to be deleted on app close-down */ appDirectory.deleteOnCloseDownDirectories = [ appDirectory.webServerFilesDirectory, appDirectory.appTempCapturesContainerDirectory ]; const config = { appName: appName, appDirectory: appDirectory, webServerStaticFilesPathPrefix: 'files', schoolVrProjectArchiveExtensionWithLeadingDot: '.ivr', jsonFileExtensionWithLeadingDot: '.json', captured360ImageExtension: '.png', captured360VideoExtension: '.mp4', saveFileTempName: 'untitled', }; // https://electronjs.org/docs/api/dialog const Media = { image: { typeName: 'image', directoryUnderProjectDirectory: 'Images', openFileDialogFilter: { name: 'Images', extensions: ['jpeg', 'jpg', 'png', 'gif', 'svg'] } }, gif: { typeName: 'gif', directoryUnderProjectDirectory: 'Gifs', openFileDialogFilter: { name: 'Gifs', extensions: ['gif'] } }, video: { typeName: 'video', directoryUnderProjectDirectory: 'Videos', openFileDialogFilter: { name: 'Videos', extensions: ['mp4'] } } }; /* derivatives from Media */ let mediaType = {}, projectDirectoryStructure = {}, openFileDialogFilter = {}; for (let key of Object.keys(Media)) { const MediumTypeObj = Media[key]; mediaType[key] = MediumTypeObj.typeName; projectDirectoryStructure[key] = MediumTypeObj.directoryUnderProjectDirectory; // https://electronjs.org/docs/api/dialog openFileDialogFilter[key] = MediumTypeObj.openFileDialogFilter; } openFileDialogFilter.schoolVrFile = { name: 'School VR Files', extensions: [config.schoolVrProjectArchiveExtensionWithLeadingDot.substr(1)] }; openFileDialogFilter.allFiles = { name: 'All Files', extensions: ['*'] }; /* end of derivatives from Media */ let paramsReadFromExternalConfig = { something: 1, }; let setParamsReadFromExternalConfig = (configObj) => { paramsReadFromExternalConfig = {...paramsReadFromExternalConfig, ...configObj}; }; /* to prove that export is "pass-by-reference"*/ // let something = 1; // let changeSomething = (val) => { // something = val; // }; module.exports = { config, mediaType, appDirectory, projectDirectoryStructure, openFileDialogFilter, // something, // changeSomething, paramsReadFromExternalConfig, setParamsReadFromExternalConfig }; // something = 2;<file_sep>/public/utils/aframeEditor/showMessageBox.js // https://electronjs.org/docs/api/dialog // https://www.christianengvall.se/electron-show-messagebox/ const { BrowserWindow, dialog } = require('electron'); const { config } = require('../../globals/config'); function showMessageBoxCommon(options, callBack) { const browserWindow = BrowserWindow.getFocusedWindow(); options.title = config.appName; dialog.showMessageBox(browserWindow, options, (response, checkboxChecked) => { callBack(response); }); } function showYesNoQuestionMessageBox(message, detail, callBack) { const options = { type: 'question', buttons: ['Yes', 'No'], defaultId: 1, cancelId: 1, message: message, detail: detail, // checkboxLabel: 'Remember my answer', // checkboxChecked: true }; showMessageBoxCommon(options, callBack); } function showYesNoWarningMessageBox(message, detail, callBack) { const options = { type: 'warning', buttons: ['Yes', 'No'], defaultId: 1, cancelId: 1, message: message, detail: detail, // checkboxLabel: 'Remember my answer', // checkboxChecked: true }; showMessageBoxCommon(options, callBack); } module.exports = { showYesNoQuestionMessageBox, showYesNoWarningMessageBox };<file_sep>/public/utils/json/jsonStringifyFormatted.js const jsonStringifyFormatted = (obj) => { return JSON.stringify(obj, null, 2); } module.exports = jsonStringifyFormatted;<file_sep>/public/server/socketio-server.js // https://github.com/networked-aframe/networked-aframe/blob/master/server/easyrtc-server.js // Load required modules var http = require("http"); // http server core module var express = require("express"); // web framework external module var socketIo = require("socket.io"); // web socket external module // Set process name process.title = "node-socketio-server"; // Get port or default to 8080 //var port = process.env.PORT || 8080; // constants //var closeServerTimeoutInMillis = 3000; // global variables var webServer; // node http var app; // e.g. express var socketServer; // socket.io server /* open server */ function openServer(port, rootDirPath = 'public/server/static', filesDirPath = null, webServerStaticFilesPathPrefix = null) { console.log('socketio-server: openServer'); // Setup and configure Express http server. Expect a subfolder called "static" to be the web root. app = express(); console.log('rootDirPath: ' + rootDirPath); app.use(express.static(rootDirPath, {'index': ['index.html']})); if (filesDirPath) { console.log('filesDirPath: ' + filesDirPath); app.use(`/${webServerStaticFilesPathPrefix}`, express.static(filesDirPath)); } // Start Express http server webServer = http.createServer(app); // Start Socket.io so it attaches itself to Express server socketServer = socketIo.listen(webServer); // listen on port webServer.listen(port, function () { console.log('listening on http://localhost:' + port); }); let presenter = null; let sceneData = null; let viewer = []; socketServer.on('connection', (socket) => { // console.log('a user connected'); socket.on('registerPresenter', (projectData) => { console.log('presenter connected'); presenter = socket; socket.emit('serverMsg', 'You are now presenter'); // console.log(getIp()); presenter.emit('updateViewerCount', viewer.length); }); socket.on('registerViewer', () => { console.log('viewer connected'); socket.emit('serverMsg', 'You are now viewer'); viewer.push(socket); // console.log(sceneData); if (sceneData) { socket.emit('updateSceneData', sceneData); } if (presenter) { presenter.emit('updateViewerCount', viewer.length); } }); socket.on('disconnect', () => { console.log('user disconnected'); if (presenter && (socket !== presenter)) { viewer = viewer.filter((val, idx, arr) => { return val !== socket; }) presenter.emit('updateViewerCount', viewer.length); } }); socket.on('test', (data) => { console.log('test'); if (presenter === socket) { // only let presenter send msg // if (data.action === "hello") { socket.broadcast.emit('test', data); // } } }); socket.on('useSceneData', (data) => { console.log('useSceneData'); if (presenter.id === socket.id) { console.log('useSceneData'); // only let presenter send msg // if (data.action === "hello") { sceneData = data; socket.broadcast.emit('updateSceneData', data); // } } }); socket.on('updateSceneStatus', (data) => { // console.log('updateSceneStatus', presenter.id, socket.id); console.log('updateSceneStatus'); if (presenter.id === socket.id) { // console.log('updateSceneStatus'); // only let presenter send msg // if (data.action === "hello") { socket.broadcast.emit('updateSceneStatus', data); // } } }); // basic flow /* registerViewer - check if presenter present > yes, reply the presenter project data > if the presentation started, may be need to send the current progress data > no, reply waiting message registerPresenter - store the presenter project data - reply the ip address of current computer - may be a general endpoint for all the messages from the presenter, then broadcast to all viewers disconnected viewer - should be nothing to handle presenter - broadcast to the viewer? (do we need a chatting system also?) */ }) } /* end of open server */ /* close server */ function closeServer() { if (socketServer) { socketServer.close(_ => { /* Probably no need to call webServer.close() if socketServer.close() is called already. */ // if (webServer) { // console.log('socketio-server: closing server'); // webServer.close((err) => { // if (err) { // console.error('socketio-server closeServer error:', err); // } // }); // } socketServer = null; webServer = null; app = null; console.log('socketio-server: closeServer'); exitSuccess(); }); } // setTimeout(_ => { // socketServer = null; // app = null; // webServer = null; // }, closeServerTimeoutInMillis); } function exitSuccess() { console.log('socketio-server: exitSuccess'); exitHandler.bind(null, { cleanup: true, exit: true }); } /* end of close server */ /* ipc */ // https://nodejs.org/api/child_process.html#child_process_subprocess_send_message_sendhandle_options_callback process.on('message', (message) => { switch (message.address) { case 'open-server': openServer(message.port, message.rootDirPath, message.filesDirPath, message.webServerStaticFilesPathPrefix); break; case 'close-server': closeServer(); break; } }); /* end of ipc */ // openServer(1111, './'); /* * doing a cleanup action just before Node.js exits * https://stackoverflow.com/questions/14031763/doing-a-cleanup-action-just-before-node-js-exits */ function exitHandler(options, exitCode) { if (options.cleanup) { console.log('socketio-server exitHandler: cleanup'); closeServer(); } if (exitCode || exitCode === 0) { console.log('socketio-server exitHandler exitCode:', exitCode); } if (options.exit) { process.exit(); } } //do something when app is closing process.on('exit', _ => { console.log('socketio-server on: exit'); }); //catches ctrl+c event process.on('SIGINT', _ => { console.log('socketio-server on: SIGINT'); exitHandler.bind(null, { exit: true, clean: true }); }); // catches "kill pid" (for example: nodemon restart) process.on('SIGUSR1', _ => { console.log('socketio-server on: SIGUSR1'); exitHandler.bind(null, { exit: true, clean: true }); }); process.on('SIGUSR2', _ => { console.log('socketio-server on: SIGUSR2'); exitHandler.bind(null, { exit: true, clean: true }); }); //catches uncaught exceptions // https://stackoverflow.com/questions/40867345/catch-all-uncaughtexception-for-node-js-app process .on('unhandledRejection', (reason, p) => { console.error('socketio-server on unhandledRejection:', reason, 'Unhandled Rejection at Promise', p); }) .on('uncaughtException', err => { console.error('socketio-server on uncaughtException:', err, 'Uncaught Exception thrown'); process.exit(1); }); /* end of doing a cleanup action just before Node.js exits */<file_sep>/src/containers/aframeEditor/homePage/assetsPanel.js import React, {Component} from 'react'; // import ipcHelper from 'utils/ipc/ipcHelper'; // import handleErrorWithUiDefault from 'utils/errorHandling/handleErrorWithUiDefault'; // import isNonEmptyArray from 'utils/variableType/isNonEmptyArray'; import './assetsPanel.css'; //const Events = require('vendor/Events.js'); function handleUpload(event, callback) { var self = event.target; if (self.files && self.files[0]) { var reader = new FileReader(); reader.onload = function (e) { const img = new Image(); imageResize(img, undefined, undefined, callback); img.src = e.target.result; }; reader.readAsDataURL(self.files[0]); self.value = ''; } } // if have time, this one seems funny // http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ // current method // https://stackoverflow.com/questions/19262141/resize-image-with-javascript-canvas-smoothly function imageResize(img, width, height, callback) { img.onload = function() { if (width === undefined && height === undefined) { // make a nearest power of 2 let finalWidth = 2; let i = 0; while (finalWidth << i < img.width) { i++; } if (img.width - finalWidth << (i - 1) < finalWidth << i - img.width ) { i--; } width = height = finalWidth << i; // height = width / img.width * img.height; } else if (width === undefined) { width = height / img.height * img.width; } else if (height === undefined) { height = width / img.width * img.height; } const canvas = document.createElement('canvas'), ctx = canvas.getContext("2d"), oc = document.createElement('canvas'), octx = oc.getContext('2d'); canvas.width = width; canvas.height = height; const cur = { width: img.width, height: img.height } oc.width = cur.width; oc.height = cur.height; octx.drawImage(img, 0, 0, cur.width, cur.height); while (cur.width * 0.5 > width) { cur.width = Math.floor(cur.width * 0.5); cur.height = Math.floor(cur.height * 0.5); octx.drawImage(oc, 0, 0, cur.width * 2, cur.height * 2, 0, 0, cur.width, cur.height); } ctx.drawImage(oc, 0, 0, cur.width, cur.height, 0, 0, canvas.width, canvas.height); callback({ src: canvas.toDataURL(), width: canvas.width, height: canvas.height }); } } class AssetsPanel extends Component { constructor(props) { super(props); this.addAsset = this.addAsset.bind(this); this.state = { assetsList: [] } } componentDidMount() { } componentWillUnmount() { } addAsset(img) { this.setState({ assetsList: [...this.state.assetsList, img] }); } render() { const props = this.props; const self = this; return ( <div id="assets-panel"> <div className="panel-background" /> <div className="panel"> <div className="panel-header">Assets - Image <div className="close-btn"></div> </div> <div className="panel-body"> <div className="assets-buttons"> <button id="add-assets" onClick={_=>this.fileUpload.click()}>Add</button> <input type="file" ref={ref=>this.fileUpload = ref} onChange={event=>handleUpload(event, self.addAsset)} hidden /> </div> <div className="assets-list"> {this.state.assetsList.map((asset, idx) => { return ( <div className="asset-item" key={idx}> <div className="asset-image"> <img src={asset.src} alt=""/> </div> <div className="asset-info"> <div className="asset-size">{asset.width + ' x ' + asset.height}</div> <div className="asset-name">{asset.width + ' x ' + asset.height}</div> </div> </div> ); })} </div> </div> </div> </div> ); } } export default AssetsPanel;<file_sep>/src/utils/aframeEditor/aCamera.js import AEntity from "./aEntity"; var Events = require('vendor/Events.js'); class ACamera extends AEntity { constructor(el) { super(el); this._messageId = 'SceneObjects.Camera.DefaultName'; this._type = 'a-camera'; this._animatableAttributes = { position: ['x', 'y', 'z'], rotation: ['x', 'y', 'z'], //cameraPreview: true } this._staticAttributes = [ // { // type: 'image', // name: 'Texture', // attributeKey: 'material', // attributeField: 'src' // } ] this._fixedAttributes = {}; this._animatableAttributesValues = { position: { x: 0, y: 0, z: 10 }, scale: { x: 1, y: 1, z: 1 }, rotation: { x: 0, y: 0, z: 0 }, } // Events.emit('getEditorInstance', obj => { // this.editor = obj; // }); this.renderCameraPreview = this.renderCameraPreview.bind(this); Events.on('refreshsidebarobject3d', this.renderCameraPreview); } setEditorInstance(editorInstance) { this.editor = editorInstance; } setCameraPreviewEl(canvasEl) { this.cameraPreviewEl = canvasEl || this.cameraPreviewEl ; } updateEntityAttributes(attrs) { if (typeof(attrs) !== 'object') return; //console.log(attrs); const self = this; for (let key in attrs) { if (self.animatableAttributes.hasOwnProperty(key)) { //self._el.setAttribute(key, self._el.getAttribute(key)); self._el.setAttribute(key, attrs[key]); // if (key === 'rotation') { // self._el.components['look-controls'].yawObject.rotation.x = attrs[key]['x']; // self._el.components['look-controls'].yawObject.rotation.y = attrs[key]['y']; // self._el.components['look-controls'].yawObject.rotation.z = attrs[key]['z']; // self._el.components['look-controls'].pitchObject.rotation.x = attrs[key]['x']; // self._el.components['look-controls'].pitchObject.rotation.y = attrs[key]['y']; // self._el.components['look-controls'].pitchObject.rotation.z = attrs[key]['z']; // } } else { const staticAttribute = self.staticAttributes.find(attr => attr.attributeKey === key); if (staticAttribute) { self._el.setAttribute(key, attrs[key]); //self._el.parentEl.setAttribute(key, attrs[key]); } } } } renderCameraPreview() { if (this.cameraPreviewEl) { const editor = this.editor; if (!editor) return this.unmount(); const renderer = editor.sceneEl.renderer; const scene = editor.sceneEl.object3D; const camera = editor.currentCameraEl.getObject3D('camera'); if (!camera) return this.unmount(); const newWidth = this.cameraPreviewEl.parentElement.offsetWidth; const width = renderer.domElement.width; const height = renderer.domElement.height; const newHeight = newWidth / width * height; const canvas = this.cameraPreviewEl; const ctx = canvas.getContext('2d'); const helper_status = []; for (let i = 0; i < editor.sceneHelpers.children.length; i++){ helper_status[i] = editor.sceneHelpers.children[i].visible; editor.sceneHelpers.children[i].visible = false; } camera.aspect = width / height; camera.updateProjectionMatrix(); renderer.render(scene, camera); for (let i = 0; i < editor.sceneHelpers.children.length; i++){ editor.sceneHelpers.children[i].visible = helper_status[i]; } canvas.width = newWidth; canvas.height = newHeight; // if (camera.aspect > 1) { // this.cameraPreviewScreenEl.setAttribute( 'width', canvas.width / 270 * 0.6 ); // this.cameraPreviewScreenEl.setAttribute( 'height', canvas.height / 270 * 0.6 ); // } else { // this.cameraPreviewScreenEl.setAttribute( 'width', canvas.width / newHeight * 0.6 ); // this.cameraPreviewScreenEl.setAttribute( 'height', canvas.height / newHeight * 0.6 ); // } ctx.drawImage(renderer.domElement, 0, 0, canvas.width, canvas.height); if (editor.opened) { const editorCamera = editor.editorCameraEl.getObject3D('camera'); renderer.render(scene, editorCamera); } } else { // assume unmounted this.unmount(); } } unmount() { Events.removeListener('refreshsidebarobject3d', this.renderCameraPreview); return false; } } export default ACamera;<file_sep>/src/utils/apis/authApi.js import promisify from 'utils/js/myPromisify'; //const authUrlRoot = 'http://localhost:59825'; const authUrlRoot = 'https://605wk4ih1m.execute-api.ap-east-1.amazonaws.com/Prod/'; const authUrl = `${authUrlRoot}/api/auth/authenticatelicense`; const authUrlAuthCode = '<KEY>'; const postAuthenticateLicense = (licenseKey, macAddress, callBack) => { fetch(authUrl, { method: 'POST', body: JSON.stringify({ apiAuthCode: authUrlAuthCode, licenseKey: licenseKey, macAddress: macAddress }), headers: { 'Content-Type': 'application/json' //'text/plain' } }) .then(res => { // !!!Note!!! use '!=' instead of '!==' for status code check if (res.status != 200) { throw new Error('Error when postAuthenticateLicense\n' + `url: ${authUrl}\n` + `status: ${res.status}\n` + `licenseKey: ${licenseKey}\n` + `macAddress: ${macAddress}` ); } return res.json(); }) .then(resJson => { callBack(null, { isAuthenticated: resJson.isAuthenticated }); }) .catch((err) => { callBack(err, null); }); } const postAuthenticateLicensePromise = promisify(postAuthenticateLicense); export { postAuthenticateLicense, postAuthenticateLicensePromise };<file_sep>/src/containers/aframeEditor/homePage/infoPanel.js /* Right Panel should be something that show the selected entity's info ( ◲ ) ▫▫▫▫▫▫▫▫▫▫▫ ▭ ┌──────┐ ▭ │AFRAME│ ▭ └──────◲ */ import React, {Component, Fragment} from 'react'; // import EntitiesList from 'containers/aframeEditor/panelItem/entitiesList'; import timelineInfoRenderer from 'containers/aframeEditor/homePage/infoPanel/timelineInfoRenderer'; import staticInfoRenderer from 'containers/aframeEditor/homePage/infoPanel/staticInfoRenderer'; // import InfoTypeCone from 'containers/aframeEditor/homePage/infoPanel/infoTypeCone'; // import InfoTypeCylinder from 'containers/aframeEditor/homePage/infoPanel/infoTypeCylinder'; // import InfoTypePlane from 'containers/aframeEditor/homePage/infoPanel/infoTypePlane'; // import InfoTypeTriangle from 'containers/aframeEditor/homePage/infoPanel/infoTypeTriangle'; // import InfoTypeImage from 'containers/aframeEditor/homePage/infoPanel/infoTypeImage'; // import InfoTypeCamera from 'containers/aframeEditor/homePage/infoPanel/infoTypeCamera'; // import InfoTypeBackground from 'containers/aframeEditor/homePage/infoPanel/infoTypeBackground'; //import {FontAwesomeIcon} from '@fortawesome/react-fontawesome' // import {roundTo} from 'globals/helperfunctions'; import './infoPanel.css'; import {withSceneContext} from 'globals/contexts/sceneContext'; import {LanguageContextConsumer, LanguageContextMessagesConsumer} from 'globals/contexts/locale/languageContext'; import ABox from 'utils/aframeEditor/aBox'; import ASphere from 'utils/aframeEditor/aSphere'; import ACone from 'utils/aframeEditor/aCone'; import APyramid from 'utils/aframeEditor/aPyramid'; import ANavigation from 'utils/aframeEditor/aNavigation'; import APlane from 'utils/aframeEditor/aPlane'; import AText from 'utils/aframeEditor/aText'; import ASky from 'utils/aframeEditor/aSky'; import ACamera from 'utils/aframeEditor/aCamera'; import AVideo from 'utils/aframeEditor/aVideo'; import ipcHelper from 'utils/ipc/ipcHelper'; import handleErrorWithUiDefault from 'utils/errorHandling/handleErrorWithUiDefault'; import isNonEmptyArray from 'utils/variableType/isNonEmptyArray'; //import fileHelper from 'utils/fileHelper/fileHelper'; import iconCirclePlus from 'media/icons/circleplus.svg'; import iconCircleMinus from 'media/icons/circleminus.svg'; import iconImage from 'media/icons/image.svg'; import iconVideo from 'media/icons/video.svg'; //var Events = require('vendor/Events.js'); // const infoRenderer = { // 'a-box': InfoTypeBox, // 'a-text': InfoTypeBox, // 'a-cone': InfoTypeBox, //InfoTypeCone, // 'a-cylinder': InfoTypeBox, //InfoTypeCylinder, // 'a-tetrahedron': InfoTypeBox, // 'a-sphere': InfoTypeBox, // 'a-plane': InfoTypeBox, //InfoTypePlane, // 'a-triangle': InfoTypeBox, //InfoTypeTriangle, // 'a-image': InfoTypeBox, //InfoTypeImage // 'a-camera': InfoTypeCamera, // 'a-sky': InfoTypeBox, // 'a-navigation': InfoTypeBox, // }; const entityModel = { 'a-box': ABox, 'a-text': AText, 'a-cone': ACone, //InfoTypeCone, 'a-cylinder': ABox, //InfoTypeCylinder, 'a-tetrahedron': ABox, 'a-pyramid': APyramid, 'a-sphere': ASphere, 'a-plane': APlane, //InfoTypePlane, 'a-triangle': ABox, //InfoTypeTriangle, 'a-image': ABox, //InfoTypeImage 'a-video': AVideo, //InfoTypeImage 'a-camera': ACamera, 'a-sky': ASky, 'a-navigation': ANavigation, } function EntityDetails(props) { const entity = props.sceneContext.getCurrentEntity();// entitiesList[props.selectedEntity]['el']; const timeline = props.sceneContext.getCurrentTimeline();// entitiesList[props.selectedEntity]['el']; const Model = new entityModel[entity['type']]; if (timeline) { const Renderer = timelineInfoRenderer; return ( <Renderer key={entity.id + '_' + timeline.id} {...props} animatableAttributes={Model.animatableAttributes}/> ); } else { // render a panel same as above but not setting any timeline const Renderer = staticInfoRenderer; return ( <Renderer key={entity.id} {...props} animatableAttributes={Model.animatableAttributes}/> ); } } class InfoPanel extends Component { constructor(props) { super(props); // this.sceneContext = props.sceneContext; [ 'addTimeline', 'selectTimelinePosition', 'deleteTimeline', 'renderStaticAttribute' ].forEach(methodName => { this[methodName] = this[methodName].bind(this); }); // this.state = { // currentEntity: props.sceneContext.getCurrentEntity(), // // model: null // } } componentDidMount() { // Events.emit('disablecontrols'); // const entity = this.props.sceneContext.getCurrentEntity(); // if (entity) // this.Model = new entityModel[entity['type']]; } componentWillUnmount() { } // componentDidUpdate(prevProps, prevState) { // const props = this.props; // const newEntity = props.sceneContext.getCurrentEntity(); // if ((!prevState.currentEntity && newEntity) || (newEntity && newEntity.id !== prevState.currentEntity.id)) { // this.setState({ // currentEntity: newEntity, // model: new entityModel[newEntity['type']] // }) // } else if (prevState.currentEntity !== this.state.currentEntity) { // this.setState({ // currentEntity: null, // model: null // }) // } // } addTimeline() { const props = this.props; const sceneContext = props.sceneContext; const selectedEntity = sceneContext.getCurrentEntity(); sceneContext.addTimeline(selectedEntity.id); } selectTimelinePosition(position, timelineId) { const props = this.props; const sceneContext = props.sceneContext; sceneContext.selectTimelinePosition(position, timelineId); } deleteTimeline() { const props = this.props; const sceneContext = props.sceneContext; const currentTimelineId = sceneContext.getCurrentTimelineId(); sceneContext.deleteTimeline(currentTimelineId); } renderStaticAttribute(staticAttribute, selectedEntity, model, sceneContext, messages) { let inputField = null; let currentValue = ''; if (staticAttribute.attributeField) { const attrsObj = selectedEntity.el.getAttribute(staticAttribute.attributeKey); if (attrsObj) { currentValue = attrsObj[staticAttribute.attributeField]; } } else { currentValue = selectedEntity.el.getAttribute(staticAttribute.attributeField) } // try to prompt an input field from electron? {/* console.log(staticAttribute.type); */} switch (staticAttribute.type) { case 'text': { inputField = <div key={staticAttribute.name} className="attribute-row"> <LanguageContextConsumer render={ ({ messages }) => ( <input type="text" className="contentTextInput" key={selectedEntity.el.id} onInput={(event) => { {/* selectedEntity.el.setAttribute(staticAttribute.attributeKey, { [staticAttribute.attributeField]: event.target.value }); */} if (staticAttribute.attributeField) { model.updateEntityAttributes({ [staticAttribute.attributeKey]: { [staticAttribute.attributeField]: event.target.value } }); sceneContext.updateEntity({ [staticAttribute.attributeKey]: { [staticAttribute.attributeField]: event.target.value } }, selectedEntity['id']); } else { model.updateEntityAttributes({ [staticAttribute.attributeKey]: event.target.value }); sceneContext.updateEntity({ [staticAttribute.attributeKey]: event.target.value // [staticAttribute.attributeKey]: { // [staticAttribute.attributeField]: event.target.value // } }, selectedEntity['id']); } }} onBlur={(event) => { {/* if (staticAttribute.attributeField) { sceneContext.updateEntity({ [staticAttribute.attributeKey]: { [staticAttribute.attributeField]: event.target.value } }, selectedEntity['id']); } else { sceneContext.updateEntity({ [staticAttribute.attributeKey]: event.target.value // [staticAttribute.attributeKey]: { // [staticAttribute.attributeField]: event.target.value // } }, selectedEntity['id']); } */} }} value={currentValue} placeholder={messages['EditThingPanel.Text.TextPlaceholder']} /> ) } /> </div> break; } case 'image': { // use electron api to load inputField = <div key={staticAttribute.name} className="attribute-button"> <div onClick={_ => { ipcHelper.openImageDialog((err, data) => { if (isNonEmptyArray(data.filePaths)) { const filePath =data.filePaths[0]; const ext = filePath.split('.').slice(-1)[0]; const newAssetData = sceneContext.addAsset({ filePath: filePath, type: (ext === 'gif'? 'gif': 'image') }); sceneContext.updateEntity({ material: { src: `#${newAssetData.id}`, shader: newAssetData.shader } }, selectedEntity['id']); selectedEntity.el.setAttribute('material', `src:#${newAssetData.id};shader:${newAssetData.shader}`); } else { selectedEntity.el.removeAttribute('material', 'src'); } }) }}> <img src={iconImage} alt={messages['EditThingPanel.AddTextureLabel']} /> <div>{messages['EditThingPanel.AddTextureLabel']}</div> </div> </div> // temp use browser api to debug // inputField = <input type="file" accept="image/svg+xml,image/jpeg,image/png" onChange={(event) => { // if (event.target.files && event.target.files[0]) { // {/* const FR= new FileReader(); // FR.addEventListener("load", function(e) { // // console.log(e.target.result); // selectedEntity.el.setAttribute('material', `src:url(${e.target.result})`); // sceneContext.updateEntity({ // material: { // src: `url(${e.target.result})` // } // // [staticAttribute.attributeKey]: { // // [staticAttribute.attributeField]: event.target.value // // } // }, selectedEntity['id']); // }); // FR.readAsDataURL( event.target.files[0] ); */} // {/* console.log(event.target.files[0].type); */} // /** // image/svg+xml // image/jpeg // image/gif // image/png // video/mp4 // */ // const newAssetData = sceneContext.addAsset(event.target.files[0]); // selectedEntity.el.setAttribute('material', `src:#${newAssetData.id};shader: ${newAssetData.shader}`); // sceneContext.updateEntity({ // material: { // src: `#${newAssetData.id}`, // shader: newAssetData.shader // } // }, selectedEntity['id']); // // } else { // selectedEntity.el.removeAttribute('material', 'src'); // } // }} /> break; } case 'video': { // use electron api to load inputField = <div key={staticAttribute.name} className="attribute-button"> <div onClick={_=> { ipcHelper.openVideoDialog((err, data) => { if (err) { handleErrorWithUiDefault(err); return; } const filePaths = data.filePaths; if (!isNonEmptyArray(filePaths)) { selectedEntity.el.removeAttribute('material', 'src'); } else { const newAssetData = sceneContext.addAsset({ filePath: filePaths[0], type: 'video/mp4', // data.type not pass from the ipc }); selectedEntity.el.setAttribute('material', `src:#${newAssetData.id};shader: ${newAssetData.shader}`); sceneContext.updateEntity({ material: { src: `#${newAssetData.id}`, shader: newAssetData.shader } }, selectedEntity['id']); } {/* const mimeType = fileHelper.getMimeType(filePaths[0]); */} {/* sceneContext.updateEntity({ material: { src: `url(${data.filePaths})` } }, selectedEntity['id']); */} {/* selectedEntity.el.setAttribute('material', `src:url(${data.filePaths})`); */} }) }}> <img src={iconVideo} alt="Add Video"/> <div>{messages['EditThingPanel.AddVideoLabel']}</div> </div> </div> // temp use browser api to debug {/* inputField = <input type="file" accept="video/mp4" onChange={(event) => { if (event.target.files && event.target.files[0]) { const newAssetData = sceneContext.addAsset(event.target.files[0]); selectedEntity.el.setAttribute('material', `src:#${newAssetData.id};shader: ${newAssetData.shader}`); sceneContext.updateEntity({ material: { src: `#${newAssetData.id}`, shader: newAssetData.shader } }, selectedEntity['id']); } else { selectedEntity.el.removeAttribute('material', 'src'); } }} /> */} break; } case 'number': { inputField = <div key={staticAttribute.name} className="attribute-row"> <div className="numberSelector"> <div className={`decreaseFontSize${(!currentValue || currentValue === 1)?' disabled': ''}`} onClick={() => { const newValue = Math.max(currentValue - 1, 1); if (staticAttribute.attributeField) { model.updateEntityAttributes({ [staticAttribute.attributeKey]: { [staticAttribute.attributeField]: newValue } }); sceneContext.updateEntity({ [staticAttribute.attributeKey]: { [staticAttribute.attributeField]: newValue } }, selectedEntity['id']); } else { model.updateEntityAttributes({ [staticAttribute.attributeKey]: newValue }); sceneContext.updateEntity({ [staticAttribute.attributeKey]: newValue }, selectedEntity['id']); } }}> <img className="buttonImg" src={iconCircleMinus} /> </div> <div className="currentFontSize"> <div className="label"> <LanguageContextMessagesConsumer messageId="EditThingPanel.Text.SizeLabel" /> </div> <div className="value">{currentValue || 1}</div> </div> <div className={`increaseFontSize${currentValue === 20? ' disabled': ''}`} onClick={() => { const newValue = Math.min(currentValue + 1, 20); if (staticAttribute.attributeField) { model.updateEntityAttributes({ [staticAttribute.attributeKey]: { [staticAttribute.attributeField]: newValue } }); sceneContext.updateEntity({ [staticAttribute.attributeKey]: { [staticAttribute.attributeField]: newValue } }, selectedEntity['id']); } else { model.updateEntityAttributes({ [staticAttribute.attributeKey]: newValue }); sceneContext.updateEntity({ [staticAttribute.attributeKey]: newValue }, selectedEntity['id']); } }}> <img className="buttonImg" src={iconCirclePlus} /> </div> </div> </div>; break; } case 'slidesList': { const currentSlideId = sceneContext.getCurrentSlideId(); const slidesList = sceneContext.getSlidesList(); const selected = selectedEntity[staticAttribute.attributeKey]; inputField = <div key={staticAttribute.name} className="attribute-row"> <LanguageContextConsumer render={ ({ messages }) => ( <select onChange={(event) => { model.updateEntityAttributes({ [staticAttribute.attributeKey]: event.target.value }); sceneContext.updateEntity({ [staticAttribute.attributeKey]: event.target.value // [staticAttribute.attributeKey]: { // [staticAttribute.attributeField]: event.target.value // } }, selectedEntity['id']); }} value={selected || ""} > <option>{messages['EditThingPanel.Navigation.SelectSlideLabel']}</option> {slidesList.map((slide, slideIdx) => { {/* if (slide.id === currentSlideId) return null; */} return <option key={slide.id} value={slide.id} disabled={slide.id === currentSlideId} > {`${messages['Navigation.SlideSelect.SlideIndexPrefix']} ${slideIdx + 1}${slide.id === currentSlideId? ` ${messages['EditThingPanel.Navigation.CurrentSlideSuffix']}`: ''}`} </option> })} </select> ) } /> </div> } } return inputField; // <div key={staticAttribute.name} className="attribute-row"> {/* <div className="field-label" onClick={(e) => { const nextSiblingPosition = e.currentTarget.nextSibling.style.position; e.currentTarget.nextSibling.style.position = (nextSiblingPosition === 'fixed'? '': 'fixed'); }} title={currentValue} >{staticAttribute.name} :</div> */} // {inputField} // </div> } render() { const props = this.props; const sceneContext = props.sceneContext; const selectedEntity = sceneContext.getCurrentEntity(); if (!selectedEntity) { return null; } // const selectedSlide = selectedEntity['slide'][props.selectedSlide]; // if (!selectedSlide) return null; const selectedTimeline = sceneContext.getCurrentTimeline(); const allTimelines = sceneContext.getTimelinesList(selectedEntity['id']); const selectedTimelinePosition = sceneContext.getCurrentTimelinePosition(); const model = new entityModel[selectedEntity['type']]; model.setEl(selectedEntity.el); // console.log(model); const staticAttributes = model.staticAttributes; let staticPanel = null; if (staticAttributes.length) { staticPanel = <div id="content-panel"> <div className="panel"> {/* <div className="panel-header"> Content - {selectedEntity['name']} </div> */} <div className={`panel-body buttons-${staticAttributes.length}`}> <LanguageContextConsumer render={ ({ language, messages }) => ( <> { staticAttributes.map(staticAttribute => this.renderStaticAttribute(staticAttribute, selectedEntity, model, sceneContext, messages)) } </> ) } /> </div> </div> </div> } if (!selectedTimeline) { // check if any timelines exist // if (selectedEntity['timelines'].length === 0) { // no timeline exist, display hints box return ( <Fragment> {staticPanel} <div id="info-panel"> <div className="panel"> {/* <div className="panel-header"> Animation - {selectedEntity['name']} </div> */} <div className="panel-body"> {/* check if any timelines exist */} {/* no timeline exist, display hints box */} {selectedEntity['timelines'].length === 0 ? <Fragment> <div className="attribute-col"> <button className="new-timeline-btn" onClick={this.addTimeline}> <LanguageContextMessagesConsumer messageId="EditThingPanel.AddAnimationLabel" /> </button> </div> <EntityDetails key={selectedEntity.id} entityId={selectedEntity['id']} {...props} model={model} /> </Fragment> : <div className="timelines-col"> {/* timelines exist, display timeline selecting box */} {allTimelines.map(timeline => { return <div key={timeline.id} className="timeline-btns-col"> <button className="new-timeline-btn" onClick={_=>{ this.selectTimelinePosition("startAttribute", timeline.id) }} > {`${timeline.start}`} </button> <button className="new-timeline-btn" onClick={_=>{ this.selectTimelinePosition("endAttribute", timeline.id) }} > {`${timeline.start + timeline.duration}`} </button> </div> })} </div> } </div> </div> </div> </Fragment> ) // } else { // } // return null; } else { return ( <Fragment> {staticPanel} <div id="info-panel"> <div className="panel"> <div className="menu-item delete-timeline" onClick={_ => { this.deleteTimeline(); }}> <svg viewBox="0 0 43.15 50.54" xmlSpace="preserve"> <g> <path fill="currentColor" className="bin-cover" d="M40.72,6.42H30.24V4.85c0-2.68-2.17-4.85-4.85-4.85h-7.64c-2.68,0-4.85,2.17-4.85,4.85v1.58H2.42 C1.09,6.42,0,7.51,0,8.85c0,1.34,1.09,2.42,2.42,2.42h38.3c1.34,0,2.42-1.09,2.42-2.42C43.15,7.51,42.06,6.42,40.72,6.42z M17.75,6.42V3.89h7.64v2.53H17.75z"/> <path fill="currentColor" className="bin-body" d="M8.24,15.88c-1.34,0-2.42,1.09-2.42,2.42v23.75c0,4.69,3.8,8.48,8.48,8.48h14.54c4.69,0,8.48-3.8,8.48-8.48 V18.3c0-1.34-1.09-2.42-2.42-2.42s-2.42,1.09-2.42,2.42v23.75c0,2.01-1.63,3.64-3.64,3.64H14.3c-2.01,0-3.64-1.63-3.64-3.64V18.3 C10.67,16.96,9.58,15.88,8.24,15.88z"/> <path fill="currentColor" className="bin-body" d="M19.15,39.02V18.3c0-1.34-1.09-2.42-2.42-2.42s-2.42,1.09-2.42,2.42v20.72c0,1.34,1.09,2.42,2.42,2.42 S19.15,40.36,19.15,39.02z"/> <path fill="currentColor" className="bin-body" d="M28.84,39.02V18.3c0-1.34-1.09-2.42-2.42-2.42S24,16.96,24,18.3v20.72c0,1.34,1.09,2.42,2.42,2.42 S28.84,40.36,28.84,39.02z"/> </g> </svg> </div> {/* <div className="panel-header"> Animation - {selectedEntity['name']} <div className="menu-wrapper"> <div className="menu-btn"> <div className="dot"></div> </div> <div className="menu-list"> </div> </div> </div> */} <div className={"panel-body " + selectedTimelinePosition}> <div className="timeline-position-wrap"> <div className={"timeline-position" + (selectedTimelinePosition === "startAttribute"? " selected": "")} onClick={()=>{ this.selectTimelinePosition("startAttribute", selectedTimeline.id); }} title="Start time" >{selectedTimeline.start}</div> <div className={"timeline-position" + (selectedTimelinePosition === "endAttribute"? " selected": "")} onClick={()=>{ this.selectTimelinePosition("endAttribute", selectedTimeline.id); }} title="End time" >{selectedTimeline.start + selectedTimeline.duration}</div> {selectedTimelinePosition && <div className="underline-indicator" style={{left: (selectedTimelinePosition === "startAttribute"? "0%": "50%")}}></div> } </div> {(selectedTimelinePosition === "startAttribute") && <EntityDetails key={selectedTimeline.id} {...props} timelineObj={selectedTimeline} model={model} timelinePosition="startAttribute" /> } {(selectedTimelinePosition === "endAttribute") && <EntityDetails key={selectedTimeline.id} {...props} timelineObj={selectedTimeline} model={model} timelinePosition="endAttribute" /> } </div> </div> </div> </Fragment> ); } } } export default withSceneContext(InfoPanel);<file_sep>/src/utils/queryString/getSearchObject.js function getSearchObjectFromHistory(history) { return getSearchObjectFromLocation(history.location); }; function getSearchObjectFromLocation(location = window.location) { return getSearchObjectFromQueryString(location.search); }; // https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ function getSearchObjectFromQueryString(queryStr = window.location.search) { const searchParams = new URLSearchParams(queryStr); const searchHandler = { get: function(obj, prop) { return obj.has(prop) ? obj.get(prop) : null; } } return new Proxy(searchParams, searchHandler); }; export { getSearchObjectFromQueryString, getSearchObjectFromLocation, getSearchObjectFromHistory };
e7835aa06c75a1e97296086ddccbc9a95a61ab92
[ "JavaScript" ]
73
JavaScript
ioio-creative/School-VR
e930fb38307d25d9cef7ab49f19bb23614db36b7
0297434bc2d62971bfab68cb4baa6b5b72c051c2
refs/heads/master
<file_sep>#!/bin/bash set -e readonly PROGNAME=$(basename $0) readonly PROGDIR=$(dirname $0) # don't care about readlink : ${AWS:=aws} MIME=$PROGDIR/mime s3() { $AWS s3 "$@" } s3_create_bucket() { local bucket="$1" echo "Creating bucket $bucket" if s3 mb "s3://$bucket" > /dev/null; then echo "Bucket $bucket created" else echo "Bucket $bucket exists" fi } s3_setup_website() { local bucket="$1" echo "Setting up $bucket to serve websites" s3 website \ "s3://$bucket" \ --index-document index.html \ --error-document 404.html } deploy_short_expiry() { local bucket="$1"; shift local files=$@ local f echo "Syncing short-expiry files $files to $bucket" for f in $files; do s3 cp \ "$f" \ "s3://$bucket/${f#$FOLDER/}" \ --acl public-read --cache-control "max-age=600" done } deploy_gzip() { local bucket="$1"; shift local files=$@ local f echo "Syncing gzipped files $files to $bucket" for f in $files; do local mime=$($MIME "$f") if [[ $SELF_GZIP ]]; then echo "Gzipping $f" local file=$(mktemp /tmp/.blofeld-XXXXXXX) gzip -9 $f -c > $file else local file=$f fi s3 cp \ "$file" \ "s3://$bucket/${f#$FOLDER/}" \ --acl public-read \ --cache-control "max-age=31536000" \ --content-encoding gzip \ --content-type "$mime" done } deploy_folder() { local bucket="$1" local folder="$2" echo "Syncing $folder to $bucket" s3 sync \ "$folder" \ "s3://$bucket" \ --acl public-read \ --cache-control "max-age=31536000" \ --delete } usage() { echo "$PROGNAME -t target_bucket -f folder [-s short_expiry_files] [-g gziped_files]" } cmdline() { while getopts ":t:f:s:g:xhG" OPTION; do case $OPTION in x) set -x ;; t) readonly TARGET_BUCKET="$OPTARG" ;; f) readonly FOLDER="$OPTARG" ;; g) readonly GZIP_FILES="$OPTARG" ;; G) readonly SELF_GZIP=1 ;; s) readonly SHORT_EXPIRY="$OPTARG" ;; h) usage; exit 0 ;; \?) echo "Unknown option $OPTARG" ; usage ; exit 1 ;; \:) echo "$OPTARG requires an argument" ; exit 1 ;; esac; done } main() { cmdline "$@" [[ -z $TARGET_BUCKET || -z $FOLDER ]] && { usage ; exit 1 ; } s3_create_bucket $TARGET_BUCKET s3_setup_website $TARGET_BUCKET deploy_folder "$TARGET_BUCKET" "$FOLDER" [[ -z $GZIP_FILES ]] || deploy_gzip $TARGET_BUCKET $GZIP_FILES [[ -z $SHORT_EXPIRY ]] || deploy_short_expiry $TARGET_BUCKET $SHORT_EXPIRY } main "$@" <file_sep># Blofeld Setup and sync an S3 bucket for website serving ## Installation ``` npm install -g blofeld ``` Yes, I'm using npm to distribute a shell script. ![Deal with it.](https://dl.dropboxusercontent.com/u/3723930/deal_with_it.gif) ## Usage ```sh blofeld -t target_bucket -f folder [-s short_expiry_files] [-g gzipped_files] ``` Let's say you have a folder, `dist`, that you want to serve from the S3 bucket `my-awesome-website`. That's easy, it ```sh blofeld -t my-awesome-website -f dist ``` This creates the bucket, tells S3 to serve it as a website, and syncs `dist` to it. Nice. By default, Blofeld sets the expiry to one year. You probably want say HTML files to expire quickly, so list them on the `-s` option: ```sh blofeld -t my-awesome-website -f dist -s "dist/index.html dist/faq.html" ``` And now they have five-minute expiry. Ok, so S3 doesn't support dynamic GZIP, and maybe you'd like to compress your Javascript files. Add them to the `-g` option: ```sh blofeld -t my-awesome-website -f dist -g "dist/app.js" ``` If you want Blofeld to gzip the files itself, add the `-G` option. More configuration coming soon. ## Prerequisites Blofeld requires the AWS command line tool, which can be installed via Pip: ```sh pip install awscli ``` Run `aws configure` to set up your credentials. ## Licence MIT. &copy; MMXIV <NAME>
9c393fb2d9bf4115507877c8987390cf37974bfb
[ "Markdown", "Shell" ]
2
Shell
apaleslimghost/Blofeld
c183673e6cd68431a07ebd68fc07db9fd091b8de
7b33e480c283c626dda08a8e6507b98f5a93655d
refs/heads/master
<file_sep># Optimization Benchmarks for meta-heuristic optimization algorithms ## Meta-heuristic algorithms * Intensification: <br/> &nbsp; The ability of improving the existing solutions by exploiting locally the neighborhood of current solutions. * Diversification: <br/> &nbsp; Generate diverse solutions and explore the search space on global scale. ### Implemented meta-heuristic algorithms * [Particle Swarm Optimization](https://en.wikipedia.org/wiki/Particle_swarm_optimization) * [Cuckoo Search](https://www.cs.tufts.edu/comp/150GA/homeworks/hw3/_reading7%20Cuckoo%20search.pdf) * [Improved Cuckoo Search](https://ieeexplore.ieee.org/document/8412665) + Improved version of cuckoo search with genetic algorithm. * [Conformation Space Annealing](https://www.sciencedirect.com/science/article/pii/S0010465517303351) ### Benchmark functions * Refers to https://www.sfu.ca/~ssurjano/optimization.html <file_sep>''' Implementation of Improved Cuckoo Search ''' import math import numpy as np from time import time from algorithms.alg import ALG class ICS(ALG): def __init__(self, args, function_name): # Call __init__ function of a parent class super(ICS, self).__init__(args) # Get function's statistics self.get_function_statistics(function_name) def run(self): # Initialize the number of function called self.reset() # Random initial nests # Random initial cuckoo self.nests = self.make_new(self.args.num_agents) cuckoo = self.make_new(self.args.num_agents) self.position_history.append(np.copy(self.nests)) # Global best position global_best = self.nests[np.array([self.f(x) for x in self.nests]).argmin()] # Number of worst nests to be replaced num_worst_nests = int(self.args.pa * self.args.num_agents) levy_step = self.levy_flight_step(self.args.LAMBDA) for t in range(self.args.iterations): # Choose a nest randomly and replace by the new solution based on fitness score. for c in cuckoo: random_val = np.random.randint(0, self.args.num_agents) if self.f(c) < self.f(self.nests[random_val]): self.nests[random_val] = c # function evaluation of agents func_nests = [(self.f(nest), i) for i, nest in enumerate(self.nests)] func_cuckoo = [(self.f(c), i) for i, c, in enumerate(cuckoo)] # Sort based on fitness score # From best func_nests.sort() # From worst func_cuckoo.sort(reverse=True) # Get worst nest index worst_nests_idx = [func_nests[-i-1][1] for i in range(num_worst_nests)] best_nests_idx = [func_nests[i][1] for i in range(self.args.num_agents - num_worst_nests)] ''' Original Cuckoo: Randomly subsitute worst nests with uniform probability distribution. Improved cuckoo: Genetically replacing abandoned nests. ''' for i in worst_nests_idx: if np.random.rand() <= self.args.prob_genetic_replace: self.nests[i] = self.make_new(1) else: # Select two parents among good nests parents_idx = np.random.choice(best_nests_idx, 2, replace=False) self.nests[i] = self.genetic_replace(parents_idx) # Clipping with bound # Add new objective, if not, all of 'self.nests' will be updated to latest one. self.nests = self.clip_bound(self.nests) # Update cuckoo's position # cuckoo's next generation for i in range(min(self.args.num_agents, self.args.num_cuckoo)): if func_nests[i][0] < func_cuckoo[i][0]: cuckoo[func_cuckoo[i][1]] = self.nests[func_nests[i][1]] # Levy fly for cuckoo for i in range(self.args.num_agents): stepsize = self.args.step_size * levy_step #* (global_best - cuckoo[i]) cuckoo[i] += stepsize * np.random.normal(0, self.args.sigma, size=self.dimension) # Clipping with bound cuckoo = self.clip_bound(cuckoo) current_best = self.nests[np.array([self.f(x) for x in self.nests]).argmin()] global_best_eval = self.f(global_best) current_best_eval = self.f(current_best) if global_best_eval > current_best_eval: global_best = current_best self.print_result(t, global_best, global_best_eval) # Stop optimization when minimum value is near to real minimum value if abs(self.min_value - global_best_eval) <= self.args.tolerance: self.correct_flag = True self.duration = time() - self.start_time break # Add to position history self.position_history.append(np.copy(self.nests)) self.set_global_best(global_best) def genetic_replace(self, parents_idx): num_crossover = np.random.randint(0, int(self.args.dimension*self.args.max_crossover_ratio)) daughter1 = np.copy(self.nests[parents_idx[0]]) daughter2 = np.copy(self.nests[parents_idx[1]]) crossover_idx = np.random.choice(self.dimension, size=num_crossover, replace=False) # Crossover crossover_sect1 = np.copy(daughter1[crossover_idx]) crossover_sect2 = np.copy(daughter2[crossover_idx]) daughter1[crossover_idx] = crossover_sect2 daughter2[crossover_idx] = crossover_sect1 # Mutate mutation_index = [i for i in range(self.dimension) if np.random.rand() > self.args.mutation_prob] origin_param1 = daughter1[mutation_index] origin_param2 = daughter2[mutation_index] for i in range(len(mutation_index)): mutate_param1 = np.random.uniform((1-self.args.cuckoo_mutation_range)*origin_param1[i], (1+self.args.cuckoo_mutation_range)*origin_param1[i]) daughter1[mutation_index[i]] = mutate_param1 mutate_param2 = np.random.uniform((1-self.args.cuckoo_mutation_range)*origin_param2[i], (1+self.args.cuckoo_mutation_range)*origin_param2[i]) daughter2[mutation_index[i]] = mutate_param2 # Pass most fittable one if self.f(daughter1) < self.f(daughter2): return daughter1 else: return daughter2 def levy_flight_step(self, LAMBDA): ''' A random walk in which the step-lengths have a heavy-tailed probability distribution. Generate step from levy distribution. ''' sigma1 = np.power((math.gamma(1+LAMBDA) * np.sin(np.pi*LAMBDA/2)) \ / (math.gamma((1+LAMBDA)/2)*np.power(2,(LAMBDA-1)/2)), 1/LAMBDA) sigma2 = 1 u = np.random.normal(0, sigma1, size=self.dimension) v = np.random.normal(0, sigma2, size=self.dimension) step = u / np.power(np.abs(v), 1/LAMBDA) return step <file_sep>import numpy as np import tensorflow as tf import argparse import logging import importlib from algorithms.test_func import TEST_FUNC as tf if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--algorithm', nargs='+') parser.add_argument('--iterations', type=int) parser.add_argument('--num_agents', type=int) parser.add_argument('--dimension', type=int) parser.add_argument('--func', type=str) parser.add_argument('--tolerance', type=float) parser.add_argument('--num_tests', type=int) # Particle swarm optimization parser.add_argument('--w', type=float, default=0.5) parser.add_argument('--c1', type=float, default=1) parser.add_argument('--c2', type=float, default=1) # Cuckoo Search(including Improved version) parser.add_argument('--LAMBDA', type=float, default=1.5) parser.add_argument('--num_cuckoo', type=int, default=1000) parser.add_argument('--pa', type=float, default=0.25) parser.add_argument('--step_size', type=float, default=0.02) parser.add_argument('--sigma', type=float, default=1.0) parser.add_argument('--mutation_prob', type=float, default=0.1) parser.add_argument('--cuckoo_mutation_range', type=float, default=0.2) parser.add_argument('--max_crossover_ratio', type=float, default=0.5) parser.add_argument('--prob_genetic_replace', type=float, default=0.5) # Conformation Space Annealing parser.add_argument('--seed_ratio', type=float, default=0.4) parser.add_argument('--max_rounds', type=int, default=3) parser.add_argument('--max_crossover_ratio_type1', type=float, default=0.5) parser.add_argument('--max_crossover_ratio_type2', type=float, default=0.2) parser.add_argument('--mutation_range', type=float, default=0.2) parser.add_argument('--num_mutations', type=int, default=1) parser.add_argument('--num_unused', type=int, default=10) parser.add_argument('--d_cut_reduce', type=float, default=0.983912) parser.add_argument('--d_cut_initial', type=float, default=2.0) parser.add_argument('--d_cut_low', type=float, default=5.0) parser.add_argument('--min_maxiter', type=int, default=1000) parser.set_defaults(algorithm=['improved_cuckoo_search', 'particle_swarm_optimization', 'cuckoo_search', 'conformation_space_annealing'], iterations=100000, num_agents=16, dimension=5, func='eggholder', tolerance=1e-2, num_tests=100, test_result='test_result_dim5.txt') args = parser.parse_args() # Set logging format logging.basicConfig(level=logging.INFO, format='[%(levelname)s][%(filename)s:%(lineno)d]: %(message)s]') with open(args.test_result, 'a') as f: for alg in args.algorithm: f.write('['+alg+']\n') f.write('\tFor %d tests' % args.num_tests) logging.info('For %d tests' % args.num_tests) logging.info('%s algorithm' % alg) module_name = 'algorithms.' + alg module = importlib.import_module(module_name) alg_name = ''.join([word[0] for word in alg.split('_')]).upper() algorithm = getattr(module, alg_name) logging.info('Import %s module' % algorithm) for func in tf.funcs: num_func_evals = 0 num_correct = 0 total_duration = 0 function_name = func + '_function' f.write('\n\t['+function_name+']\n') opt = algorithm(args, function_name=function_name) for test in range(args.num_tests): opt.run() if opt.correct_flag: num_func_evals += opt.get_func_count() num_correct += 1 total_duration += opt.duration if num_correct == 0: f.write('\tOptimization fail\n') else: num_func_evals /= num_correct total_duration /= num_correct accuracy = num_correct * 100 / args.num_tests f.write('\tAccuracy %.4f within tolerance %.4f\n' % (accuracy, args.tolerance)) f.write('\tAverage duration for optimization %.4f secs\n' % total_duration) f.write('\tAverage number of function evaluation: %.4f\n' % num_func_evals) logging.info('\tAccuracy %.4f within tolerance %.4f' % (accuracy, args.tolerance)) logging.info('\tAverage duration for optimization %.4f secs' % total_duration) logging.info('\tAverage number of function evaluation: %.4f' % num_func_evals) # logging.info('Global best position: %s'% opt.g_best) # opt.animation(alg_name, opt.position_history, opt.f, opt.lower_bound, opt.upper_bound, save=False) <file_sep>''' Implementation of Particle Swarm Optimization ''' import numpy as np from algorithms.alg import ALG from time import time class PSO(ALG): def __init__(self, args, function_name): # Call __init__ function of a parent class super(PSO, self).__init__(args) # Get function's statistics self.get_function_statistics(function_name) def run(self): # Initialize the number of function called self.reset() # Random initialization of agents between lower bound and upper bound of input parameters self.agents = self.make_new(self.args.num_agents) # Add to position history self.position_history.append(np.copy(self.agents)) # Particle's best position particle_best = self.agents # Global best position global_best = particle_best[np.array([self.f(x) for x in particle_best]).argmin()] # Velocity zero initialization velocity = np.zeros((self.args.num_agents, self.dimension)) for t in range(self.args.iterations): # r1 and r2 are random values [0,1] regenrated every velocity update r1 = np.random.random((self.args.num_agents, self.dimension)) r2 = np.random.random((self.args.num_agents, self.dimension)) ''' Update each particle i's position given velocity equation: v_i(t+1) = w*v_i(t)+c1*r1(i's best solution-i's current position)+c2*r2[global solution-i's current position] ''' velocity = self.args.w * velocity + self.args.c1*r1*(particle_best - self.agents) + self.args.c2*r2*(global_best - self.agents) self.agents += velocity # Clipping with bound self.agents = self.clip_bound(self.agents) # Update particle's best position for i in range(self.args.num_agents): if self.f(self.agents[i]) < self.f(particle_best[i]): particle_best[i] = self.agents[i] # Update global best position global_best = particle_best[np.array([self.f(x) for x in particle_best]).argmin()] global_best_eval = self.f(global_best) self.print_result(t, global_best, global_best_eval) # Stop optimization when minimum value is near to real miminum value if abs(self.min_value - global_best_eval) <= self.args.tolerance: self.correct_flag = True self.duration = time() - self.start_time break # Add to position history self.position_history.append(np.copy(self.agents)) # Setting global best position self.set_global_best(global_best) <file_sep>import numpy as np from algorithms.test_func import TEST_FUNC as tf from matplotlib import pyplot as plt import matplotlib.animation from time import time class ALG(object): def __init__(self, args): self.args = args self.position_history = list() self.correct_flag = False self.duration = 0 # Function name: function, {dim:(min_value, coordinate, limits)} self.test_func = { 'eggholder_function':(tf.eggholder_function, \ {2:(-959.6407, (512.0, 404.2318), [(-512, 512) for _ in range(2)]), 5:(-3719.72, (485.590, 436.124, 451.083, 466.431, 421.959), [(-512, 512) for _ in range(5)]), 10:(-8291.24, (480.85, 431.37, 444.91, 457.55, 471.96, 427.50, 442.09, 455.12, 469.43, 424.94), [(-512, 512) for _ in range(10)]), 20:(-17455.9, (481.0, 431.5, 445.1, 457.9, 472.4, 428.0, 443.0, 456.5, 471.7, 427.3, 442.5, 456.3, 471.6, 427.1, 442.5, 456.3, 471.7, 427.3, 442.8, 456.9), [(-512, 512) for _ in range(20)])}), 'ackley_function':(tf.ackley_function, \ lambda x: (0, [0 for _ in range(x)], [(-32.768, 32.768) for _ in range(x)])), 'bukin_function':(tf.bukin_function, \ {2:(0, (-10, 1), [(-15, -5), (-3, 3)])}), 'cross_in_tray_function':(tf.cross_in_tray_function, \ {2:(-2.06261, ((1.3491, -1.3491), (1.3491, 1.3491), (-1.3491, 1.3491), (-1.3491, -1.3491)), [(-10, 10) for _ in range(2)])}), 'sphere_function':(tf.sphere_function, \ lambda x: (0, [0 for _ in range(x)], [(-5, 5) for _ in range(x)])), 'bohachevsky_function':(tf.bohachevsky_function, \ {2:(0, (0,0), [(-10, 10) for _ in range(2)])}), 'sum_squares_function':(tf.sum_squares_function, \ lambda x: (0, [0 for _ in range(x)], [(-10, 10) for _ in range(x)])), 'sum_of_different_powers_function':(tf.sum_of_different_powers_function, \ lambda x: (0, [0 for _ in range(x)], [(-1, 1) for _ in range(x)])), 'booth_function':(tf.booth_function, \ {2:(0, (1,3), [(-10, 10) for _ in range(2)])}), 'matyas_function':(tf.matyas_function, \ {2:(0, (0,0), [(-10, 10) for _ in range(2)])}), 'mccormick_function':(tf.mccormick_function, \ {2:(-1.9133, (-0.54719, -1.54719), [(-1.5, 4), (-3, 4)])}), 'dixon_price_function':(tf.dixon_price_function, \ lambda x: (0, [np.power(2, -((np.power(2, i)-2)/np.power(2, i))) for i in range(1, x+1)], [(-10, 10) for _ in range(x)])), 'six_hump_camel_function':(tf.six_hump_camel_function, \ {2:(-1.0316, ((0.0898, -0.7126), (-0.0898, 0.7126)), [(-3, 3), (-2, 2)])}), 'three_hump_camel_function':(tf.three_hump_camel_function, \ {2:(0, (0,0), [(-5, 5) for _ in range(2)])}), 'easom_function':(tf.easom_function, {2:(-1, (np.pi, np.pi), [(-100, 100) for _ in range(2)])}), 'michalewicz_function':(tf.michalewicz_function, \ {2:(-1.8013, (2,20, 1.57), [(0, np.pi) for _ in range(2)]), 5:(-4.687658, (None), [(0, np.pi) for _ in range(5)]), 10:(-9.66015, (None), [(0, np.pi) for _ in range(10)])}), 'beale_function':(tf.beale_function, \ {2:(0, (3, 0.5), [(-4.5, 4.5) for _ in range(2)])}), 'drop_wave_function':(tf.drop_wave_function, \ {2:(-1, (0,0), [(-5.12, 5.12) for _ in range(2)])}), 'griewank_function':(tf.griewank_function, \ lambda x: (0, [0 for _ in range(x)], [(-600, 600) for _ in range(x)])) } def reset(self): self.correct_flag = False self.start_time = time() self.duration = 0 tf.reset_func_count() def get_func_count(self): return tf.get_func_count() def get_agents(self): return self.position_history def set_global_best(self, global_best): self.g_best = global_best def get_function_statistics(self, function_name): function_info = self.test_func[function_name] self.f = function_info[0] self.dimension = self.args.dimension if isinstance(function_info[1], dict): if self.dimension not in function_info[1].keys(): raise KeyError else: f_info = function_info[1][self.dimension] else: f_info = function_info[1](self.dimension) self.min_value = f_info[0] self.real_coord = f_info[1] self.limits = f_info[2] def make_new(self, num_new): target = list() for i in range(self.dimension): target.append(np.random.uniform(self.limits[i][0], self.limits[i][1], (num_new,))) # Make (self.args.num_agents, self.dimension) target = np.stack(target, axis=1) return target def clip_bound(self, before_clip): after_clip = list() for i in range(self.dimension): after_clip.append(np.clip(before_clip[:,i], self.limits[i][0], self.limits[i][1])) after_clip = np.stack(after_clip, axis=1) return after_clip def print_result(self, it, global_best, global_best_eval): print('\nAt iteration %d' % it) print('Optimization result with tolerance %.5f' % self.args.tolerance) print('\tReal global minimum value: %.5f at ' % (self.min_value), end="") print(*self.real_coord, sep=',') print('\tOptimized global minimum value: %.5f at ' % (global_best_eval), end="") print(*global_best, sep=',') print('\tNumber of function evaluation: %d' % self.get_func_count()) def animation(self, alg_name, position_history, function, lb, ub, save=False): # 3d plot for 2 input parameters grid = np.linspace(lb, ub, int(ub-lb)*10) ''' Generate grid point by np.meshgrid(x,y) ex) X, Y = np.meshgrid(x,y) for x = array([0,1]), y = array([0,1,2]) => Make 3*2 grid X = array([[0,1], Y = array([[0,0], [0,1], [1,1], [0,1]]) [2,2]]) ''' print('Make x-y grid') X, Y = np.meshgrid(grid, grid) Z = np.array([function([x,y]) for x, y in zip(np.ravel(X), np.ravel(Y))]) Z = np.reshape(Z, X.shape) fig = plt.figure() plt.axes(xlim=(lb, ub), ylim=(lb, ub)) # Color-mapping Z values in 2d plot plt.pcolormesh(X, Y, Z, shading='gouraud') # Initial agent point x = np.array([j[0] for j in position_history[0]]) y = np.array([j[1] for j in position_history[0]]) sc = plt.scatter(x, y, color='black') plt.title(function.__name__, loc='left') def plot(i): x = np.array([j[0] for j in position_history[i]]) y = np.array([j[1] for j in position_history[i]]) # Scatter update (x,y) through animation sc.set_offsets(list(zip(x,y))) plt.title('Iteration: {}'.format(i), loc='right') ani = matplotlib.animation.FuncAnimation(fig, plot, frames=len(position_history)-1) if save: ani.save('%s.mp4' % function.__name__) plt.show() <file_sep>''' Implementation of Cuckoo Search ''' import math import numpy as np from algorithms.alg import ALG from time import time class CS(ALG): def __init__(self, args, function_name): # Call __init__ function of a parent class super(CS, self).__init__(args) # Get function's statistics self.get_function_statistics(function_name) def run(self): # Initialize the number of function called self.reset() # Random initial nests # Random initial cuckoo self.nests = self.make_new(self.args.num_agents) cuckoo = self.make_new(self.args.num_agents) self.position_history.append(np.copy(self.nests)) # Global best position global_best = self.nests[np.array([self.f(x) for x in self.nests]).argmin()] # Number of worst nests to be replaced num_worst_nests = int(self.args.pa * self.args.num_agents) levy_step = self.levy_flight_step(self.args.LAMBDA) for t in range(self.args.iterations): # Choose a nest randomly and replace by the new solution based on fitness score. for c in cuckoo: random_val = np.random.randint(0, self.args.num_agents) if self.f(c) < self.f(self.nests[random_val]): self.nests[random_val] = c # function evaluation of agents func_nests = [(self.f(nest), i) for i, nest in enumerate(self.nests)] func_cuckoo = [(self.f(c), i) for i, c, in enumerate(cuckoo)] # Sort based on fitness score func_nests.sort() func_cuckoo.sort(reverse=True) # Get worst nest index worst_nests = [func_nests[-i-1][1] for i in range(num_worst_nests)] # Randomly subsitute worst nests with uniform probability distribution for i in worst_nests: self.nests[i] = self.make_new(1) # Clipping with bound # Add new objective, if not, all of 'self.nests' will be updated to latest one. self.nests = self.clip_bound(self.nests) # Update cuckoo's position # cuckoo's next generation for i in range(min(self.args.num_agents, self.args.num_cuckoo)): if func_nests[i][0] < func_cuckoo[i][0]: cuckoo[func_cuckoo[i][1]] = self.nests[func_nests[i][1]] # Levy fly for cuckoo for i in range(self.args.num_agents): stepsize = self.args.step_size * levy_step #* (global_best - cuckoo[i]) cuckoo[i] += stepsize * np.random.normal(0, self.args.sigma, size=self.dimension) # Clipping with bound cuckoo = self.clip_bound(cuckoo) current_best = self.nests[np.array([self.f(x) for x in self.nests]).argmin()] global_best_eval = self.f(global_best) current_best_eval = self.f(current_best) if global_best_eval > current_best_eval: global_best = current_best self.print_result(t, global_best, global_best_eval) # Stop optimization when minimum value is near to real minimum value if abs(self.min_value - global_best_eval) <= self.args.tolerance: self.correct_flag = True self.duration = time() - self.start_time break # Add to position history self.position_history.append(np.copy(self.nests)) self.set_global_best(global_best) def levy_flight_step(self, LAMBDA): ''' A random walk in which the step-lengths have a heavy-tailed probability distribution. Generate step from levy distribution. ''' sigma1 = np.power((math.gamma(1+LAMBDA) * np.sin(np.pi*LAMBDA/2)) \ / (math.gamma((1+LAMBDA)/2)*np.power(2,(LAMBDA-1)/2)), 1/LAMBDA) sigma2 = 1 u = np.random.normal(0, sigma1, size=self.dimension) v = np.random.normal(0, sigma2, size=self.dimension) step = u / np.power(np.abs(v), 1/LAMBDA) return step <file_sep>''' https://www.sfu.ca/~ssurjano/index.html ''' from math import * import numpy as np class TEST_FUNC(object): num_func_called = 0 funcs = ['eggholder', 'ackley', # 'bukin', # 'cross_in_tray', 'sphere', # 'bohachevsky', 'sum_squares', 'sum_of_different_powers', # 'booth', # 'matyas', # 'mccormick', 'dixon_price', # 'six_hump_camel', # 'three_hump_camel', # 'easom', # 'michalewicz', # 'beale', # 'drop_wave', 'griewank'] @classmethod def eggholder_function(cls, x): cls.num_func_called += 1 x0 = x[:-1] x1 = x[1:] return np.sum([-(x_next+47)*np.sin(np.sqrt(np.absolute(0.5*x_prev+x_next+47)))-x_prev*np.sin(np.sqrt(np.absolute(x_prev-x_next-47))) for (x_prev, x_next) in zip(x0,x1)]) @classmethod def ackley_function(cls, x): cls.num_func_called += 1 return -20*exp(-0.02*sqrt(0.5*sum([i**2 for i in x]))) - \ exp(0.5*sum([cos(i) for i in x])) + 20 + exp(1) @classmethod def bukin_function(cls, x): cls.num_func_called += 1 return 100*sqrt(abs(x[1]-0.01*x[0]**2)) + 0.01*abs(x[0] + 10) @classmethod def cross_in_tray_function(cls, x): cls.num_func_called += 1 return round(-0.0001*(abs(sin(x[0])*sin(x[1])*exp(abs(100 - sqrt(sum([i**2 for i in x]))/pi))) + 1)**0.1, 7) @classmethod def sphere_function(cls, x): cls.num_func_called += 1 return sum([i**2 for i in x]) @classmethod def bohachevsky_function(cls, x): cls.num_func_called += 1 return x[0]**2 + 2*x[1]**2 - 0.3*cos(3*pi*x[0]) - 0.4*cos(4*pi*x[1]) + 0.7 @classmethod def sum_squares_function(cls, x): cls.num_func_called += 1 return sum([(i+1)*x[i]**2 for i in range(len(x))]) @classmethod def sum_of_different_powers_function(cls, x): cls.num_func_called += 1 return sum([abs(x[i])**(i+2) for i in range(len(x))]) @classmethod def booth_function(cls, x): cls.num_func_called += 1 return (x[0] + 2*x[1] - 7)**2 + (2*x[0] + x[1] - 5)**2 @classmethod def matyas_function(cls, x): cls.num_func_called += 1 return 0.26*sum([i**2 for i in x]) - 0.48*x[0]*x[1] @classmethod def mccormick_function(cls, x): cls.num_func_called += 1 return sin(x[0] + x[1]) + (x[0] - x[1])**2 - 1.5*x[0] + 2.5*x[1] + 1 @classmethod def dixon_price_function(cls, x): cls.num_func_called += 1 return (x[0] - 1)**2 + sum([(i+1)*(2*x[i]**2 - x[i-1])**2 for i in range(1, len(x))]) @classmethod def six_hump_camel_function(cls, x): cls.num_func_called += 1 return (4 - 2.1*x[0]**2 + x[0]**4/3)*x[0]**2 + x[0]*x[1]\ + (-4 + 4*x[1]**2)*x[1]**2 @classmethod def three_hump_camel_function(cls, x): cls.num_func_called += 1 return 2*x[0]**2 - 1.05*x[0]**4 + x[0]**6/6 + x[0]*x[1] + x[1]**2 @classmethod def easom_function(cls, x): cls.num_func_called += 1 return -cos(x[0])*cos(x[1])*exp(-(x[0] - pi)**2 - (x[1] - pi)**2) @classmethod def michalewicz_function(cls, x): cls.num_func_called += 1 return -sum([sin(x[i])*sin((i+1)*x[i]**2/pi)**20 for i in range(len(x))]) @classmethod def beale_function(cls, x): cls.num_func_called += 1 return (1.5 - x[0] + x[0]*x[1])**2 + (2.25 - x[0] + x[0]*x[1]**2)**2 + \ (2.625 - x[0] + x[0]*x[1]**3)**2 @classmethod def drop_wave_function(cls, x): cls.num_func_called += 1 return -(1 + cos(12*sqrt(sum([i**2 for i in x]))))/(sum([i**2 for i in x]) + 2) @classmethod def griewank_function(cls, x): cls.num_func_called += 1 return np.sum([np.power(x[i], 2)/4000 for i in range(len(x))]) - np.prod([np.cos(x[i]/np.sqrt(i+1)) for i in range(len(x))]) + 1 @classmethod def get_func_count(cls): return cls.num_func_called @classmethod def reset_func_count(cls): cls.num_func_called = 0 print('# of function called is initialized to 0') <file_sep>''' Implementation of Conformation Space Annealing ''' import math import numpy as np from algorithms.alg import ALG from scipy import optimize from time import time as measure_time class CSA(ALG): def __init__(self, args, function_name): # Call __init__ function of a parent class super(CSA, self).__init__(args) # Get function's statistics self.get_function_statistics(function_name) self.num_seeds = int(self.args.num_agents*self.args.seed_ratio) def run(self): # Initialize the number of function called self.reset() self.first_bank, self.bank = self.create_banks() # Global best position global_best = self.bank[np.array([self.f(x) for x in self.bank]).argmin()] self.position_history.append(np.copy(self.bank)) for stage in range(self.args.iterations): print('Stage %d' % stage) # At the beginning of each stage d_cut is set as d_avg/2 d_avg = self.get_average_distance() print('Average distance among the first bank: %.4f' % d_avg) d_cut = d_avg / self.args.d_cut_initial self.num_solutions = self.bank.shape[0] for round in range(self.args.max_rounds): print('\tRound %d' % round) # Round is completed, all bank solutions are mareked as unused self.bank_status = [False for _ in range(self.num_solutions)] time = 0 while True: print('\t\tTime %d' % time) # Seeds are selected from unused solutions unselected_solution_idxs = np.where(np.asarray(self.bank_status) == False)[0].tolist() seed_idxs = self.get_seeds(round, unselected_solution_idxs, d_avg) # Daughter solutions are generated bank seeds = self.bank[seed_idxs] # For each seed, 3 types of crossover and mutation methods are used 10 times, generating 30 daughter solution daughter_solutions = list() for seed, seed_idx in zip(seeds, seed_idxs): # First type crossover: Partner solution comes from a bank daughter_solution = self.crossover(seed, seed_idx, round, partner_src='b', max_crossover_ratio=self.args.max_crossover_ratio_type1) # Subsequently energy minimized daughter_solution = self.local_minimize(daughter_solution) daughter_solutions.append(daughter_solution) # Second type crossover: Partner solution comes from a first bank daughter_solution = self.crossover(seed, seed_idx, round, partner_src='f', max_crossover_ratio=self.args.max_crossover_ratio_type2) daughter_solution = self.local_minimize(daughter_solution) daughter_solutions.append(daughter_solution) # Mutation daughter_solution = self.mutation(seed, self.args.mutation_range, self.args.num_mutations) daughter_solution = self.local_minimize(daughter_solution) daughter_solutions.append(daughter_solution) # All daughter solution update bank one by one for daughter in daughter_solutions: self.bank_update(daughter, d_cut) # print('Bank status: %s' % self.bank_status) # Update global best position current_best = self.bank[np.array([self.f(x) for x in self.bank]).argmin()] global_best_eval = self.f(global_best) if global_best_eval > self.f(current_best): global_best = current_best # Stop optimization when minimum value is near to real minimum value # Add to position history self.position_history.append(self.bank) # Decrease d_cut d_cut = max(d_cut*self.args.d_cut_reduce, d_avg/self.args.d_cut_low) # Cound unused solutions num_unused = self.count_unused_bank(seed_idxs) # print('# of unused solutions: %d\n' % num_unused) time += 1 if (num_unused < self.args.num_unused) or (time % 100 == 0): break self.print_result(stage, global_best, global_best_eval) if abs(self.min_value - global_best_eval) <= self.args.tolerance: self.correct_flag = True self.duration = measure_time() - self.start_time break # At the beginning of a new stage, add randomly-generated and subsequently-minimized solutions to both banks new_first_bank, new_bank = self.create_banks() # Concatenate to previous banks self.first_bank = np.concatenate((self.first_bank, new_first_bank), axis=0) self.bank = np.concatenate((self.bank, new_bank), axis=0) self.set_global_best(global_best) def create_banks(self): # First bank contains solutions that are randomly generated and each solutions are locally minimized first_bank = self.make_new(self.args.num_agents) for i in range(first_bank.shape[0]): first_bank[i] = self.local_minimize(first_bank[i]) # The bank holds the evolving population and initially identical to the first bank bank = np.copy(first_bank) return first_bank, bank def get_seeds(self, round, unselected_idx, d_avg): if round == 0: seed_idxs = np.random.choice([i for i in range(self.num_solutions - self.args.num_agents, self.num_solutions)], size=self.num_seeds, replace=False).tolist() else: num_unused = len(unselected_idx) if num_unused >= self.num_seeds: seed_idxs = list() # One is selected randomly, seed_idx = np.random.choice(unselected_idx, size=1, replace=False)[0] seed_idxs.append(seed_idx) # print('%d added to seeds' % seed_idx) for _ in range(self.num_seeds-1): over_avg_solutions = list() under_avg_solutions = list() unselected_idx.remove(seed_idx) # Distances are measured between the selected seed and non-selected unused solutions. for i in unselected_idx: distance = self.get_distance(self.bank[seed_idx], self.bank[i]) # print('For %d, distance: %.4f' % (i, distance)) if self.get_distance(self.bank[seed_idx], self.bank[i]) > d_avg: over_avg_solutions.append((self.f(self.bank[i]), i)) else: under_avg_solutions.append((self.f(self.bank[i]), i)) over_avg_solutions.sort() if len(over_avg_solutions) == 0: under_avg_solutions.sort() seed_idx = under_avg_solutions[0][1] else: seed_idx = over_avg_solutions[0][1] # print('%d added to seeds' % seed_idx) seed_idxs.append(seed_idx) else: seed_idxs = unselected_idx for _ in range(self.num_seeds - len(seed_idxs)): solutions = list() for i in range(self.bank.shape[0]): if i in seed_idxs: continue solutions.append((self.f(self.bank[i]), i)) solutions.sort() seed_idx = solutions[0][1] # print('%d added to seeds' % seed_idx) seed_idxs.append(seed_idx) # Mark selected seeds as used for seed_idx in seed_idxs: self.bank_status[seed_idx] = True return seed_idxs def crossover(self, seed, seed_index, round, partner_src='b', max_crossover_ratio=0.5): ''' Crossover between a seed and a bank Seed's partner is selected from bank in a random fashion exluding the seed itself partner_src: 'b'=bank, 'f'=first bank ''' # First, we copy the seed as a daughter daughter = np.copy(seed) # Crossover size is set in a random fashion between 1 and half of the total number of variables num_crossover = np.random.randint(1, max(2, int(self.dimension*max_crossover_ratio))) # Pick the indexes for the crossover # Use random sampling with np.random.choice crossover_idx = np.random.choice(self.dimension, size=num_crossover, replace=False) # At the first round, partner conformations for crossover are selected only among the newly added. if round == 0: while True: partner_idx = np.random.randint(self.num_solutions-self.args.num_agents, self.num_solutions) if partner_idx != seed_index: break else: partner_idx = np.random.randint(0, self.num_solutions) if partner_src == 'b': daughter[crossover_idx] = self.bank[partner_idx][crossover_idx] elif partner_src == 'f': daughter[crossover_idx] = self.first_bank[partner_idx][crossover_idx] else: raise Exception('Not proper partner solution type') return daughter def mutation(self, seed, mutate_range=0.2, num_mutations=1): mutation_index = np.random.choice([i for i in np.arange(self.dimension)], size=num_mutations, replace=False) daughter = np.copy(seed) origin_param = daughter[mutation_index] for i in range(len(origin_param)): mutate_param = np.random.uniform((1-mutate_range)*origin_param[i], (1+mutate_range)*origin_param[i]) daughter[mutation_index[i]] = mutate_param return daughter def count_unused_bank(self, seed_mask): count = 0 for i in range(len(self.bank_status)): if self.bank_status[i] == False: count += 1 return count def bank_update(self, daughter_solution, d_cut): ''' For each daughter solution, dsitance to all the bank solutions are measured to identify its closest solution ''' # print('Bank before update') # print(self.bank) distances = list() worst_bank_evals = self.f(self.bank[0]) worst_bank_index = 0 for i in range(self.num_solutions): distances.append(self.get_distance(daughter_solution, self.bank[i])) bank_evals = self.f(self.bank[i]) if (worst_bank_evals < bank_evals) and (i > 0): worst_bank_evals = bank_evals worst_bank_index = i # Get closest distance for daughter solution closest_distance, closest_idx = distances[np.asarray(distances).argmin()], np.asarray(distances).argmin() daughter_eval = self.f(daughter_solution) # If the closest distance is less than or equal to d_cut and daughter solution is more optimzal than closest solution, replace if (closest_distance <= d_cut) and (daughter_eval < self.f(self.bank[closest_idx])): self.bank[closest_idx] = daughter_solution self.bank_status[closest_idx] = False # If the closest distance is more than d_cut and daughter solution is more optimal than worst solution, replace if (closest_distance > d_cut) and (daughter_eval < worst_bank_evals): self.bank[worst_bank_index] = daughter_solution self.bank_status[worst_bank_index] = False self.bank = self.clip_bound(self.bank) # print('Bank after update') # print(self.bank) # Otherwise, daughter solution is discarded # Average distance among the first bank solutions def get_average_distance(self): distance = 0 count = 0 for i in range(self.first_bank.shape[0]): for j in range(i, self.first_bank.shape[0]): count += 1 distance += self.get_distance(self.first_bank[i], self.first_bank[j]) return distance / count # Euclidian distance of the two solutions def get_distance(self, param1, param2): return np.sqrt(np.sum((param1-param2)**2)) def local_minimize(self, param): # param range: [(min1, max1), (min2, max2)..] param_range = [(self.limits[i][0], self.limits[i][1]) for i in range(self.dimension)] # OptimizeResult object res = optimize.minimize(self.f, param, method='L-BFGS-B', bounds=param_range, options={'maxiter':self.args.min_maxiter}) # Local minimum function value score = res.fun # If local minimization is failed, replace score with very big number if np.isnan(score): score = 1.e10 # Minimized conformation min_param = res.x return min_param
bd1ab268a9a23835a44d821473ddf6ba989ea36f
[ "Markdown", "Python" ]
8
Markdown
yjhong89/Optimization
ab10ffee04fbf40108d1a1bec1120378272f93bd
e8cf4943b7ac464d0dbb81b498aa0e94e1a4a01b
refs/heads/master
<repo_name>productiveAnalytics/dynamodb-stream-based-backup<file_sep>/version_change_hander.js const EventEmitter = require('events'); const VERSION_CHANGE_EVENT = 'recordChanged'; const AWS = require('aws-sdk'); AWS.config.update({ region: "us-east-1" }); /* Run following inside /hds/hds folder: aws cloudformation create-stack \ --stack-name hds-ddb-hds-payer-history-stack \ --template-body file://dataload/src/main/CloudFormation/hds_payer_history_DDB.yml \ --parameters ParameterKey=TABLENAME,ParameterValue=hds_payer_history */ const HDS_PAYER_HISTORY_TABLE = "hds_payer_history"; // TODO: use stage to customize the table /** * Even handler for Payer Configuration DDB record change * Pass implType = DDB or DynamoDB to use DynamoDB * * @author LChawathe */ class VersionChangeHandler extends EventEmitter { constructor(implType) { super(); console.log(`Using implementation ${implType}...`); // var docClient = new AWS.DynamoDB.DocumentClient(); var ddbClient = new AWS.DynamoDB(); this.on(VERSION_CHANGE_EVENT, (eventArgs) => { var oldImageJson = /*JSON.stringify(eventArgs)*/eventArgs; var putRequestParams = { TableName: HDS_PAYER_HISTORY_TABLE, Item: oldImageJson // NOTE: Image provided by DDB Stream has DynamoDB raw format // Either use DynamoDB client // Or use "dynamoDb-marshaler" // Refer: https://github.com/CascadeEnergy/dynamoDb-marshaler } console.log("JSON to Put "+ JSON.stringify(putRequestParams)); if (implType == 'DDB' || implType == 'DynamoDB') { //docClient.put(putRequestParams, (err, data) => { ddbClient.putItem(putRequestParams, (err, data) => { if (err) { console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2)); } else { console.log("Added item:", JSON.stringify(data, null, 2)); } }); } }); } versionChanged(eventParams) { this.emit(VERSION_CHANGE_EVENT, eventParams) } }; module.exports = VersionChangeHandler;<file_sep>/handler.js 'use strict'; const VersionChangeHandler = require('./version_change_hander'); const versionChangeHandler = new VersionChangeHandler('DynamoDB'); module.exports.processVersion = async (event, context, callback) => { console.log(`Successfully received ${event.Records.length} records.`); event.Records.forEach((record) => { console.log('Stream record: ', JSON.stringify(record, null, 2)); console.log(`Event: ${record.eventName}, Event ID: ${record.eventID}`); if ('INSERT' == record.eventName) { console.log('INSERT: DynamoDB NEW Record: %j', record.dynamodb.NewImage); } else if ('MODIFY' == record.eventName || 'REMOVE' == record.eventName) { if ('MODIFY' == record.eventName) { console.log('UPDATE: DynamoDB OLD Record: %j', record.dynamodb.OldImage); console.log('UPDATE: DynamoDB NEW Record: %j', record.dynamodb.NewImage); } else { console.log('DELETE: DynamoDB OLD Record: %j', record.dynamodb.OldImage); } var oldRecordJson = record.dynamodb.OldImage; var newRecordJson; // insertedDatetime and insertedBy is only available for MODIFY var insertedTimestamp, insertedBy; if ('MODIFY' == record.eventName) { newRecordJson = record.dynamodb.NewImage; insertedTimestamp = newRecordJson.insertedDatetime; insertedBy = newRecordJson.insertedBy; } console.log('insertedTimestamp==='+ JSON.stringify(insertedTimestamp)); oldRecordJson.expiredOn = getDDBJsonForDatetime(insertedTimestamp); console.log('insertedBy==='+ JSON.stringify(insertedBy)); oldRecordJson.expiredBy = getDDBJsonForUser(insertedBy); // console.log("Type of oldRecordJson="+ (typeof oldRecordJson)); // fire VersionChange event versionChangeHandler.versionChanged(oldRecordJson); } }); callback(null, `Successfully processed ${event.Records.length} records.`); }; function getDDBJsonForDatetime(insertedTimestamp) { ; if (insertedTimestamp == undefined) { var placeholder = getFormattedDatetime(); var jsonStr = `{"S":"${placeholder}"}`; return JSON.parse(jsonStr); } else { return insertedTimestamp; } } function getDDBJsonForUser(insertedBy) { if (insertedBy == undefined) { var placeholder = getCurrentUser(); var jsonStr = `{"S":"${placeholder}"}`; return JSON.parse(jsonStr); } else { return insertedBy; } } // TODO: PLACEHOLDER. User currentDate to format function getFormattedDatetime() { var currentDate = new Date(); console.log("TODO: using default date..."); return "2019-04-29 11:30:13.123 CST"; } // TODO: PLACEHOLDER. Extract current user function getCurrentUser() { console.log("TODO: using default user..."); return "VersioningSystem"; }<file_sep>/README.md Micro Service for DynamoDB table and its backup based on Streams # To test locally: sls invoke local -f payerConfigVersionLambda -p ./tests/test_ddb_stream_event.json # To deploy: sls deploy -v
336252b4ab3c2646b1b7bc40bddb3c69db9e3c1b
[ "JavaScript", "Markdown" ]
3
JavaScript
productiveAnalytics/dynamodb-stream-based-backup
27cae86131f48924033c4f61e29b54576887a189
1402db26a7afc8976dc88fb5dee5841154950732
refs/heads/master
<file_sep># MC404 - "Organização de Computadores e Linguagem de Montagem" Repositório para constar arquivos feitos durante a disciplina MC404 - "Organização de Computadores e Linguagem de Montagem" <file_sep>#include "montador.h" #include <stdio.h> /* ---- Voce deve implementar essa função para a Parte 2! ---- Utilize os tokens da estrutura de tokens para montar seu código! Retorna: * 1 caso haja erro na montagem; (imprima o erro em stderr) * 0 caso não haja erro. */ int emitirMapaDeMemoria() { /* printf("Voce deve implementar essa função para a Parte 2!");*/ return 0; } <file_sep> construir: lab9.s riscv32-unknown-elf-gcc -g lab9.s -o lab9 python: program bridge.py riscv32-unknown-elf-gdb lab9 -ex 'target remote | python3 bridge.py' <file_sep>from http.server import HTTPServer, BaseHTTPRequestHandler from threading import Timer from io import BytesIO from sys import stdin, stdout, stderr import os def exit_bridge(): os._exit(0) DEBUG_ENABLED = False def err_print(m): if(not DEBUG_ENABLED): return stderr.write(m) stderr.flush() def putDebugChar(c): stdout.write(c) def getDebugChar(n=1): return stdin.read(n) def readFromGDB(): data = "" ch = ' ' while 1: while ch != '$': ch = getDebugChar() sum = 0 # checksum while 1: ch = getDebugChar() if (ch == '$' or ch == '#'): break sum += ord(ch) data += ch if (ch == '$'): continue if (ch == '#'): pacSum = int(getDebugChar(n=2), base=16) if (sum&0xFF != pacSum): putDebugChar('-') # Signal failed reception. stdout.flush() stderr.write("Signal failed reception. %d != %d\n" % (sum&0xFF, pacSum)) stderr.write() else: putDebugChar('+') # Signal successul reception. stdout.flush() # If sequence char present, reply with sequence id. if (len(data) >= 3 and data[2] == ':'): putDebugChar(data[0]) putDebugChar(data[1]) stdout.flush() data = data[3:] return data return data def writeToGDB(data): while 1: putDebugChar('$') checksum = 0x1000000 for c in data: putDebugChar(c) checksum += ord(c) putDebugChar('#') putDebugChar(hex(checksum)[-2:]) stdout.flush() c = getDebugChar() if (c == '+'): return class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Access-Control-Allow-Origin", "*") self.send_header('Content-type','text/html') self.end_headers() err_print("[BRIDGE DEBUG] Reading from GDB\n") res = readFromGDB() self.wfile.write(bytes(res, "utf-8")) err_print("[BRIDGE DEBUG] Sent: " + str(res) + '\n') if(res[0] == "k" or (res[0] == "v" and "vKill;" in res)): err_print("[BRIDGE DEBUG] Killing bridge in 3 seconds...\n") t = Timer(3.0, exit_bridge) t.start() def do_POST(self): content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) self.send_response(200) self.send_header("Access-Control-Allow-Origin", "*") self.send_header('Content-type','text/html') self.end_headers() err_print("[BRIDGE DEBUG] Writing to GDB\n") writeToGDB(body.decode("utf-8")) err_print("[BRIDGE DEBUG] Received: " + body.decode("utf-8") + '\n') # response = BytesIO() # response.write(b'Written to GDB: ') # response.write(body) # self.wfile.write(response.getvalue()) def log_message(self, format, *args): return httpd = HTTPServer(('localhost', 5689), SimpleHTTPRequestHandler) httpd.serve_forever()<file_sep>mapa_s: mapa.c riscv32-unknown-elf-gcc -g mapa.c -S -o mapa.s arquivos_objetos: mapa.s ra185137.s riscv32-unknown-elf-as -g mapa.s -o mapa.o riscv32-unknown-elf-as -g ra185137.s -o dfs.o ligacao: riscv32-unknown-elf-ld -g mapa.o dfs.o -o program construir: mapa.c ra185137.s make mapa_s make arquivos_objetos make ligacao python: program bridge.py riscv32-unknown-elf-gdb program -ex 'target remote | python3 bridge.py' <file_sep>montagem: ra185137.s export PATH=$PATH:/opt/riscv/bin riscv32-unknown-elf-as -g ra185137.s -o resultado.o ligador: resultado.o riscv32-unknown-elf-ld -g resultado.o -o saida_ligador montagem1: teste.s export PATH=$PATH:/opt/riscv/bin riscv32-unknown-elf-as -g teste.s -o resul.o ligador1: resul.o riscv32-unknown-elf-ld -g resul.o -o saida_ligador <file_sep>export PATH=$PATH:/opt/riscv/bin <file_sep>#include "api_robot.h" #include <stdlib.h> int abs(int x) { if (x < 0) return -x; return x; } double sqrt(int x) { double temp, saida; saida = x/2; temp = 0; while (saida != temp) { temp = saida; saida = (x/temp + temp)/2; } return saida; } int pow(int num, int p) { int i; int saida = 1; for (i = 0; i < p; i++) { saida = saida * num; } return saida; } double cos(int x1, int y1, int x2, int y2) { double saida; saida = ((x1*x2)+(y1*y2))/(sqrt(pow(x1,2)+pow(y1,2))*sqrt(pow(x2,2)+pow(y2,2))); return saida; } int encontrar_amigo(Vector3 amigo) { Vector3 uoli; get_current_GPS_position(&uoli); if (abs(uoli.x-amigo.x) <= 5 && abs(uoli.z-amigo.z) <= 5) return 1; return 0; } int quadrante(Vector3 amigo) { Vector3 pos_uoli; int dif_x; int dif_z; get_current_GPS_position(&pos_uoli); dif_x = pos_uoli.x - amigo.x; dif_z = pos_uoli.z - amigo.z; if (dif_x >= 0 && dif_z >= 0) return 4; if (dif_x < 0 && dif_z < 0) return 2; if (dif_x >= 0 && dif_z < 0) return 1; if (dif_x < 0 && dif_z >= 0) return 3; return 0; } void girar_direita(int valor) { Vector3 angulo_uoli; int atual, final; get_gyro_angles(&angulo_uoli); atual = angulo_uoli.y; final = atual + valor; if (final > 360) final -= 360; while (atual < final || atual > final) { set_torque(10, -10); get_gyro_angles(&angulo_uoli); atual = angulo_uoli.y; } set_torque(0,0); } void girar_esquerda(int valor) { Vector3 angulo_uoli; int atual,final; get_gyro_angles(&angulo_uoli); atual = angulo_uoli.y; final = atual - valor; if (final > 360) final -= 360; while (atual < final || atual > final) { set_torque(-10,10); get_gyro_angles(&angulo_uoli); atual = angulo_uoli.y; } set_torque(0,0); } void espera(int valor){ int time, final; time = get_time(); final = time + valor; while (time < final) { time = get_time(); } } void rotaciona(int angulo){ Vector3 uoli; get_gyro_angles(&uoli); if (angulo > 350 || angulo < 10) return; if (uoli.y > 180) { while (uoli.y < angulo-10 || uoli.y > angulo+10) { girar_esquerda(5); espera(300); get_gyro_angles(&uoli); } } else { while (uoli.y < angulo-10 || uoli.y > angulo+10) { girar_direita(5); espera(300); get_gyro_angles(&uoli); } } } int main() { int i; char c; int quadrante_anterior = 0; //char c; Vector3 amigo_i, uoli; for(i = 0; i < 5; i++){ amigo_i = friends_locations[i]; puts("Teste\n"); while (!encontrar_amigo(amigo_i)) { //c = (char)quadrante_anterior; //puts(&c); c = (char)(48 + quadrante(amigo_i)); puts(&c); puts("\nproximo\n"); //aqui da erro // if (quadrante(amigo_i) == quadrante_anterior) { // miss... } else if (quadrante(amigo_i) == 4) { rotaciona(225); } else if (quadrante(amigo_i) == 3) { rotaciona(135); } else if (quadrante(amigo_i) == 2) { rotaciona(45); } else { rotaciona(315); } set_torque(20,20); espera(2000); set_torque(0,0); espera(2000); } } while (1) {} return 0; }<file_sep>montagem: ra185137-lab6.s riscv32-unknown-elf-as -g ra185137-lab6.s -o resultado.o ligador: resultado.o riscv32-unknown-elf-ld -g resultado.o -o saida_ligador <file_sep>#include "montador.h" #include "token.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdbool.h> char *strdup(const char *s); char *listaInstrucoes[] = { "ld", "ldinv", "ldabs", "ldmq", "ldmqmx", "store", "jump", "jge", "add", "addabs", "sub", "subabs", "mult", "div", "lsh", "rsh", "storend" }; int listaNumeroParametrosInstrucoes[] = { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1}; char *listaDiretivas[] = { ".set", ".org", ".align", ".wfill", ".word"}; int listaNumeroParametrosDiretivas[] = { 2, 1, 1, 2, 1}; TipoDoToken analisadorLexico(char *entrada, unsigned tamanho) { bool diretiva = true; bool def_rotulo = true; bool hexadecimal = true; bool decimal = true; bool nome = true; bool instrucao = true; // Verificacao diretiva if (entrada[0] == '.') { // diretiva = true; def_rotulo = false; hexadecimal = false; decimal = false; nome = false; instrucao = false; // verificação for (unsigned i = 1; i < tamanho; i++) { if (!isalpha(entrada[i])) { diretiva = false; continue; } } if (diretiva) { diretiva = false; for (unsigned i = 0; i < 5; i++) { if (strcmp(entrada, listaDiretivas[i]) == 0) { diretiva = true; continue; } } if (diretiva) return Diretiva; } } // Verificação def_rotulo if (!isdigit(entrada[0]) && entrada[0] != '.' && entrada[tamanho - 1] == ':') { diretiva = false; // def_rotulo = true; hexadecimal = false; decimal = false; nome = false; instrucao = false; for (unsigned i = 1; i < tamanho - 1; i++) { if (!isalnum(entrada[i]) && entrada[i] != '_') { def_rotulo = false; } } if (def_rotulo) return DefRotulo; } // Verificação hexadecimal if (entrada[0] == '0' && entrada[1] == 'x') { diretiva = false; def_rotulo = false; // hexadecimal = true; decimal = false; nome = false; instrucao = false; if (strlen(entrada) > 12) hexadecimal = false; for (int i = 2; i < tamanho; i++) { if (!isxdigit(entrada[i])) { hexadecimal = false; continue; } } if (hexadecimal) return Hexadecimal; } // Verificação decimal if (isdigit(entrada[0])) { diretiva = false; def_rotulo = false; hexadecimal = false; // decimal = false; instrucao = false; for (int i = 1; i < tamanho; i++) { if (!isdigit(entrada[i])) { decimal = false; continue; } } if (decimal) return Decimal; } // Verificação instrucao if (instrucao) { instrucao = false; for (unsigned i = 0; i < 17; i++) { if (strcmp(entrada, listaInstrucoes[i]) == 0) { instrucao = true; continue; } } if (instrucao) return Instrucao; } // Verificação nome if (!isdigit(entrada[0]) && entrada[0] != '.') { diretiva = false; def_rotulo = false; hexadecimal = false; decimal = false; instrucao = false; nome = true; for (int i = 1; i < tamanho; i++) { if (!isalnum(entrada[i]) && entrada[i] != '_') { nome = false; } } if (nome) return Nome; } return -1; } bool validaParametroDiretiva(Token tokens_linha[], unsigned inicio, unsigned fim) { if (strcmp(tokens_linha[inicio].palavra, ".set") == 0) { if (fim - inicio - 1 != listaNumeroParametrosDiretivas[0]) return false; if (tokens_linha[inicio + 1].tipo == Nome) if (tokens_linha[inicio + 2].tipo == Hexadecimal || (tokens_linha[inicio + 2].tipo == Decimal && atoi(tokens_linha[inicio + 2].palavra) >= 0 && atoi(tokens_linha[inicio + 2].palavra) <= 2147483647)) return true; else return false; else return false; } else if (strcmp(tokens_linha[inicio].palavra, ".org") == 0) { if (fim - inicio - 1 != listaNumeroParametrosDiretivas[1]) return false; if (tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; else return false; } else if (strcmp(tokens_linha[inicio].palavra, ".align") == 0) { if (fim - inicio - 1 != listaNumeroParametrosDiretivas[2]) return false; if (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 1 && atoi(tokens_linha[inicio + 1].palavra) <= 1023) return true; else return false; } else if (strcmp(tokens_linha[inicio].palavra, ".wfill") == 0) { if (fim - inicio - 1 != listaNumeroParametrosDiretivas[3]) return false; if (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 1 && atoi(tokens_linha[inicio + 1].palavra) <= 1023) { if (tokens_linha[inicio + 2].tipo == Hexadecimal || tokens_linha[inicio + 2].tipo == Nome || (tokens_linha[inicio + 2].tipo == Decimal && atoi(tokens_linha[inicio + 2].palavra) >= -2147483648 && atoi(tokens_linha[inicio + 2].palavra) <= 2147483647)) return true; else return false; } else return false; } else if (strcmp(tokens_linha[inicio].palavra, ".word") == 0) { if (fim - inicio - 1 != listaNumeroParametrosDiretivas[4]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= -2147483648 && atoi(tokens_linha[inicio + 1].palavra) <= 2147483647)) return true; else return false; } return false; } // se o intervalo para uma dada instrucao for muito grande, já podemos descartar automaticamente bool validaParametroInstrucao(Token tokens_linha[], unsigned inicio, unsigned fim) { bool resultado = true; if (strcmp(tokens_linha[inicio].palavra, "ld") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[0]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "ldinv") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[1]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "ldabs") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[2]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "ldmq") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[3]) return false; } else if (strcmp(tokens_linha[inicio].palavra, "ldmqmx") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[4]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "store") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[5]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "jump") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[6]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "jge") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[7]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "add") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[8]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "addabs") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[9]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "sub") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[10]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "subabs") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[11]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "mult") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[12]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "div") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[13]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else if (strcmp(tokens_linha[inicio].palavra, "lsh") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[14]) return false; return true; } else if (strcmp(tokens_linha[inicio].palavra, "rsh") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[15]) return false; return true; } else if (strcmp(tokens_linha[inicio].palavra, "storend") == 0) { if (fim - inicio - 1 != listaNumeroParametrosInstrucoes[16]) return false; if (tokens_linha[inicio + 1].tipo == Nome || tokens_linha[inicio + 1].tipo == Hexadecimal || (tokens_linha[inicio + 1].tipo == Decimal && atoi(tokens_linha[inicio + 1].palavra) >= 0 && atoi(tokens_linha[inicio + 1].palavra) <= 1023)) return true; } else { resultado = false; } return resultado; } bool processamentoGramaticalLinha(Token tokens_linha[], int numero_de_tokens) { if (tokens_linha[0].tipo == DefRotulo) { if (numero_de_tokens == 1) { return true; } else if (tokens_linha[1].tipo == Instrucao && validaParametroInstrucao(tokens_linha, 1, numero_de_tokens)) { return true; } else if (tokens_linha[1].tipo == Diretiva && validaParametroDiretiva(tokens_linha, 1, numero_de_tokens)) { return true; } else { return false; } } else if (tokens_linha[0].tipo == Diretiva && validaParametroDiretiva(tokens_linha, 0, numero_de_tokens)) { return true; } else if (tokens_linha[0].tipo == Instrucao && validaParametroInstrucao(tokens_linha, 0, numero_de_tokens)) { return true; } else { return false; } } int processarEntrada(char *entrada, unsigned tamanho) { // Variáveis para processar comentários bool comentario = false; // Variáveis para processar palavra por palavra (em que uma palavra acaba depois de um espaço ou caractere) bool mudanca_palavra = false; bool espaco = false; char palavra_auxiliar[200]; unsigned posicao_palavra_auxiliar = 0; unsigned numero_de_palavras = 0; unsigned linha = 1; // Variáveis para processar quebra de linha bool quebra_de_linha = false; unsigned int numero_da_linha = 1; // Variáveis para criação dos Tokens TipoDoToken tipo_token; // Vetor para processamento linha a linha de tokens para verificação gramatical Token tokens_da_linha[500]; int quantidade_tokens_linha = 0; // Obtendo a lista de Tokens for (unsigned i = 0; i < strlen(entrada); i++) { // Tirando comentários if (entrada[i] == '#') comentario = true; if (entrada[i] == '\n' && comentario) comentario = false; // Identificando espaços if (entrada[i] == ' ' || entrada[i] == '\t') espaco = true; else espaco = false; // Identificando quebra de linha if (entrada[i] == '\n') quebra_de_linha = true; else quebra_de_linha = false; // Processando string sem comentário para termos a lista de Tokens if (!comentario) { if (!espaco && !quebra_de_linha) { if (!quebra_de_linha) { // Dessa forma todas as minhas palavras serão em letra minuscula automáticamente palavra_auxiliar[posicao_palavra_auxiliar] = (char)tolower((int)entrada[i]); posicao_palavra_auxiliar++; } // Se tivermos uma quebra de linha, o número da linha é aumentado. mudanca_palavra = true; } else { linha = numero_da_linha; if (mudanca_palavra) { mudanca_palavra = false; palavra_auxiliar[posicao_palavra_auxiliar] = '\0'; tipo_token = analisadorLexico(palavra_auxiliar, posicao_palavra_auxiliar); if (tipo_token == -1) { fprintf(stderr, "ERRO LEXICO: palavra inválida na linha %d!\n", linha); return 1; } adicionarToken(tipo_token, strdup(palavra_auxiliar), linha); tokens_da_linha[quantidade_tokens_linha] = *(recuperaToken(getNumberOfTokens()-1)); quantidade_tokens_linha++; numero_de_palavras++; posicao_palavra_auxiliar = 0; } if (quebra_de_linha) { // Aqui eu posso fazer meu processamento gramatical if (quantidade_tokens_linha != 0) { if (!processamentoGramaticalLinha(tokens_da_linha, quantidade_tokens_linha)) { fprintf(stderr, "ERRO GRAMATICAL: palavra na linha %d!\n", numero_da_linha); return 1; } } numero_da_linha++; quantidade_tokens_linha = 0; } } } } return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> // strtol (https://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm) // struct para symb; // struct para rot; struct key_val{ char* rotulo; int endereço; int eDireita; }; struct key_val[100]; int tam_key_val; int main() { tam_key_val = 0; char temp[100]; int a = 15; sprintf(temp, "%02X %03d ", a, 32878); printf("%s\n", temp); return 0; }
7a082a96c9f50d8a3be03da29fc7651734a20427
[ "Markdown", "Makefile", "Python", "Text", "C" ]
11
Markdown
NicolasFrancaX/mc404-2s-2019
409747be42beffc266087ed42f6053e1ebc4fa3f
d12e39fce86242a0514df7725c5befa070189a2e
refs/heads/master
<file_sep>const createBowl = ({ jumpDistance } = {}) => { const decal = random(-X_POS + BOWL_SIZE, width-300); const color = random(COLORS) const x = X_POS + decal; let y = 0; let speed = 0; let jumping = false; let jumped = false; let dead = false; let error = Infinity; const jump = () => { if (!jumping) { jumping = true; jumped = true; speed = JUMP_FORCE; } } const show = () => { push(); noStroke(); fill(color); ellipse(x, y + BOWL_SIZE/2, BOWL_SIZE, BOWL_SIZE); pop(); } const die = () => { dead = true; } return { get x () { return x }, get y () { return y }, get error () { return error }, get alive () { return !dead }, get dna () { return { jumpDistance }}, update: obstacleDistance => { error = error > obstacleDistance ? obstacleDistance : error; if (obstacleDistance <= jumpDistance && !jumped) { jump() }; y += speed; if (jumping) { if (y <= 0) { y = 0; speed = 0; jumping = false } else { speed -= GRAVITY; }; } if (obstacleDistance > (BOWL_SIZE + BAD_BOWL_SIZE)/2) { if (!dead) show(); } else { die(); } } } }
a6053932800154ce956971ed2337a1980d88c29d
[ "JavaScript" ]
1
JavaScript
m0wh/genetic-algorithm
b2b4a777c493c201a6d3a07f65e8b007315e0a74
d36729b989c5cd55f15cfb0d74d26e7cc2e06419
refs/heads/master
<file_sep>#!/usr/bin/env python import os,sys import fitsio import astropy.io.fits as pyfits from astropy.table import Table import matplotlib.pyplot as plt import numpy as np from desimeter.transform.radec2tan import hadec2xy from desimeter.simplecorr import SimpleCorr import argparse parser = argparse.ArgumentParser(description='Compare desimeter & dither fiber positions') parser.add_argument('dither_file', type=str, help='dither file name') parser.add_argument('fvc_file', type=str, help='desi_fvc_proc file name') parser.add_argument('fiberassign_file', type=str, help='fiberassign file name') parser.add_argument('-e', '--expid', type=int, default=None, help='expid to use from dither file') args = parser.parse_args() quiver_units="width" quiver_scale=20. def arrow() : xarrow=-0.025 dxarrow=2.#arcsec plt.quiver(xarrow,-0.025,dxarrow,0.,color="black",units=quiver_units,scale=quiver_scale) plt.text(xarrow,-0.029,"{} arcsec".format(dxarrow)) def text(blabla) : props = dict(boxstyle='round', facecolor='white', alpha=0.5) plt.text(0.029,-0.029,blabla,fontsize=8, bbox=props,verticalalignment='bottom', horizontalalignment='right') dither_file = args.dither_file fvc_file = args.fvc_file fiberassign_file = args.fiberassign_file # Eddie's dithers t=fitsio.read(dither_file) print(t.dtype.names) if args.expid is None: i=0 else: ind = np.flatnonzero(t['expid'][0, :] == args.expid) if len(ind) > 0: i = ind[0] else: raise ValueError(f'could not find expid {args.expid} in dither file.') err=np.sqrt(t['dxfiboff'][:,i]**2+t['dyfiboff'][:,i]**2) roff=np.sqrt(t['xfiboff'][:,i]**2+t['yfiboff'][:,i]**2) jj=np.where((err<0.02)&(roff<4.))[0] dither_ra = t['fiber_ditherfit_ra'][jj,i] dither_dec = t['fiber_ditherfit_dec'][jj,i] dither_fiber = t['fiber'][jj,i].astype(int) # desimeter RA Dec t=Table.read(fvc_file) ii=(t["RA"]!=0) t=t[:][ii] desimeter_ra = t["RA"] desimeter_dec = t["DEC"] # fiberassign f=Table.read(fiberassign_file) head = fitsio.read_header(fiberassign_file) dico = { loc : i for i,loc in enumerate(f["LOCATION"])} target_ra=np.zeros(len(t)) target_dec=np.zeros(len(t)) target_fiber=np.zeros(len(t)) for j,loc in enumerate(t["LOCATION"]) : if loc in dico : i=dico[loc] target_ra[j] = f["TARGET_RA"][i] target_dec[j] = f["TARGET_DEC"][i] target_fiber[j] = f["FIBER"][i] tel_ra=head["REQRA"] tel_dec=head["REQDEC"] desimeter_x,desimeter_y=hadec2xy(-desimeter_ra+tel_ra,desimeter_dec,0,tel_dec) target_x,target_y=hadec2xy(-target_ra+tel_ra,target_dec,0,tel_dec) dither_x,dither_y=hadec2xy(-dither_ra+tel_ra,dither_dec,0,tel_dec) # Now find match to dithers dither_index = np.zeros(dither_fiber.size,dtype=int) for i,fiber in enumerate(dither_fiber) : jj=np.where(target_fiber == fiber)[0] if jj.size == 1 : dither_index[i] = jj[0] else : dither_index[i] = -1 desimeter_x = desimeter_x[dither_index[dither_index>=0]] desimeter_y = desimeter_y[dither_index[dither_index>=0]] target_x = target_x[dither_index[dither_index>=0]] target_y = target_y[dither_index[dither_index>=0]] dither_x = dither_x[dither_index>=0] dither_y = dither_y[dither_index>=0] rad2arcsec = 180.*3600/np.pi desimeter_dx=(desimeter_x-target_x)*rad2arcsec # now arcsec desimeter_dy=(desimeter_y-target_y)*rad2arcsec # now arcsec dither_dx=(dither_x-target_x)*rad2arcsec dither_dy=(dither_y-target_y)*rad2arcsec ddx = desimeter_dx-dither_dx ddy = desimeter_dy-dither_dy d=np.sqrt(ddx**2+ddy**2) # arcsec ii=(d<10) desimeter_dx = desimeter_dx[ii] desimeter_dy = desimeter_dy[ii] desimeter_x = desimeter_x[ii] desimeter_y = desimeter_y[ii] target_x = target_x[ii] target_y = target_y[ii] dither_dx = dither_dx[ii] dither_dy = dither_dy[ii] dither_x = dither_x[ii] dither_y = dither_y[ii] ddx = ddx[ii] ddy = ddy[ii] # fit a transform to adjust desimeter to the dither results corr=SimpleCorr() corr.fit(desimeter_x,desimeter_y,dither_x,dither_y) desimeter_x_bis , desimeter_y_bis = corr.apply(desimeter_x,desimeter_y) desimeter_dx_bis=(desimeter_x_bis-target_x)*rad2arcsec # now arcsec desimeter_dy_bis=(desimeter_y_bis-target_y)*rad2arcsec # now arcsec ddx_bis = desimeter_dx_bis-dither_dx ddy_bis = desimeter_dy_bis-dither_dy title=os.path.basename(dither_file).replace(".fits","-vs-desimeter") plt.figure(title) a = plt.subplot(3,2,1) a.set_title("dither") plt.quiver(target_x,target_y,dither_dx,dither_dy,color="red",units=quiver_units,scale=quiver_scale,label="dither") arrow() rms=np.sqrt(np.mean(dither_dx**2+dither_dy**2)) text("rms = {:3.2f}''".format(rms)) a = plt.subplot(3,2,2) #a.set_title("desimeter -> dither") #plt.plot([0,1],[0,1],color="white") plt.axis('off') rad2arcsec = 180*3600/np.pi blabla = "tranformation\n" blabla += "desimeter -> dither\n\n" blabla += "dx = {:3.2f}''\n".format(corr.dx*rad2arcsec) blabla += "dy = {:3.2f}''\n".format(corr.dy*rad2arcsec) blabla += "sxx = {:6.5f}\n".format(corr.sxx-1) blabla += "syy = {:6.5f}\n".format(corr.syy-1) blabla += "sxy = {:6.5f}\n".format(corr.sxy) blabla += "rot = {:3.2f}''\n".format(corr.rot_deg*3600) blabla += "rms = {:3.2f}''\n".format(corr.rms*180*3600/np.pi) plt.text(0,0,blabla,fontsize=12) a = plt.subplot(3,2,3) a.set_title("desimeter") plt.quiver(target_x,target_y,desimeter_dx,desimeter_dy,color="red",units=quiver_units,scale=quiver_scale,label="dither") arrow() rms=np.sqrt(np.mean(desimeter_dx**2+desimeter_dy**2)) text("rms = {:3.2f}''".format(rms)) a = plt.subplot(3,2,4) a.set_title("desimeter(corr)") plt.quiver(target_x,target_y,desimeter_dx_bis,desimeter_dy_bis,color="red",units=quiver_units,scale=quiver_scale,label="dither") arrow() rms=np.sqrt(np.mean(desimeter_dx_bis**2+desimeter_dy_bis**2)) text("rms = {:3.2f}''".format(rms)) a = plt.subplot(3,2,5) a.set_title("desimeter-dither") plt.quiver(target_x,target_y,desimeter_dx-dither_dx,desimeter_dy-dither_dy,color="red",units=quiver_units,scale=quiver_scale,label="dither") arrow() rms=np.sqrt(np.mean((desimeter_dx-dither_dx)**2+(desimeter_dy-dither_dy)**2)) text("rms = {:3.2f}''".format(rms)) a = plt.subplot(3,2,6) a.set_title("desimeter(corr)-dither") plt.quiver(target_x,target_y,desimeter_dx_bis-dither_dx,desimeter_dy_bis-dither_dy,color="red",units=quiver_units,scale=quiver_scale,label="dither") arrow() rms=np.sqrt(np.mean((desimeter_dx_bis-dither_dx)**2+(desimeter_dy_bis-dither_dy)**2)) text("rms = {:3.2f}''".format(rms)) plt.show() rms = np.sqrt(np.mean(ddx**2+ddy**2)) text = "rms desimeter = {:3.2f}''\n".format(rms) rms = np.sqrt(np.mean(dither_dx**2+dither_dy**2)) text += "rms dither(platemaker) = {:3.2f}''\n".format(rms) plt.xlabel("x_tan") plt.ylabel("y_tan") plt.legend(loc="upper left") plt.subplot(3,2,2) plt.quiver(target_x,target_y,desimeter_dx_bis,desimeter_dy_bis,color="gray",alpha=0.8,units=quiver_units,scale=quiver_scale,label="desimeter (corr)") plt.quiver(target_x,target_y,dither_dx,dither_dy,color="red",units=quiver_units,scale=quiver_scale,label="dither") plt.quiver(xarrow,-0.025,dxarrow,0.,color="black",units=quiver_units,scale=quiver_scale) plt.text(xarrow,-0.029,"{} arcsec".format(dxarrow)) plt.xlabel("x_tan") plt.ylabel("y_tan") plt.legend(loc="upper left") plt.subplot(3,2,1) plt.quiver(target_x,target_y,desimeter_dx,desimeter_dy,color="grey",alpha=0.8,units=quiver_units,scale=quiver_scale,label="desimeter (uncorr)") plt.quiver(target_x,target_y,dither_dx,dither_dy,color="red",units=quiver_units,scale=quiver_scale,label="dither") xarrow=-0.025 dxarrow=2.#arcsec plt.quiver(xarrow,-0.025,dxarrow,0.,color="black",units=quiver_units,scale=quiver_scale) plt.text(xarrow,-0.029,"{} arcsec".format(dxarrow)) rms = np.sqrt(np.mean(ddx**2+ddy**2)) text = "rms desimeter = {:3.2f}''\n".format(rms) rms = np.sqrt(np.mean(dither_dx**2+dither_dy**2)) text += "rms dither(platemaker) = {:3.2f}''\n".format(rms) props = dict(boxstyle='round', facecolor='white', alpha=0.5) plt.text(0.03,-0.03,text,fontsize=8, bbox=props,verticalalignment='bottom', horizontalalignment='right') plt.xlabel("x_tan") plt.ylabel("y_tan") plt.legend(loc="upper left") plt.subplot(3,2,2) plt.quiver(target_x,target_y,desimeter_dx_bis,desimeter_dy_bis,color="gray",alpha=0.8,units=quiver_units,scale=quiver_scale,label="desimeter (corr)") plt.quiver(target_x,target_y,dither_dx,dither_dy,color="red",units=quiver_units,scale=quiver_scale,label="dither") plt.quiver(xarrow,-0.025,dxarrow,0.,color="black",units=quiver_units,scale=quiver_scale) plt.text(xarrow,-0.029,"{} arcsec".format(dxarrow)) rad2arcsec = 180*3600/np.pi text = "dx = {:3.2f}''\n".format(corr.dx*rad2arcsec) text += "dy = {:3.2f}''\n".format(corr.dy*rad2arcsec) text += "sxx = {:6.5f}\n".format(corr.sxx-1) text += "syy = {:6.5f}\n".format(corr.syy-1) text += "sxy = {:6.5f}\n".format(corr.sxy) text += "rot = {:3.2f}''\n".format(corr.rot_deg*3600) text += "rms = {:3.2f}''\n".format(corr.rms*180*3600/np.pi) #text += "rms_dither= {:3.2f}''\n".format(rms_dither) props = dict(boxstyle='round', facecolor='white', alpha=0.5) plt.text(0.03,-0.03,text,fontsize=8, bbox=props,verticalalignment='bottom', horizontalalignment='right') plt.xlabel("x_tan") plt.ylabel("y_tan") plt.legend(loc="upper left") plt.subplot(2,2,3) plt.quiver(target_x,target_y,ddx,ddy,color="k",units=quiver_units,scale=quiver_scale,label="desimeter - dither") rms = np.sqrt(np.mean(ddx**2+ddy**2)) text = "rms = {:3.2f}''\n".format(rms) props = dict(boxstyle='round', facecolor='white', alpha=0.5) plt.text(0.03,-0.03,text,fontsize=8, bbox=props,verticalalignment='bottom', horizontalalignment='right') plt.xlabel("x_tan") plt.ylabel("y_tan") plt.legend(loc="upper left") plt.subplot(2,2,4) plt.quiver(target_x,target_y,ddx_bis,ddy_bis,color="k",units=quiver_units,scale=quiver_scale,label="desimeter (corr) - dither") rms = np.sqrt(np.mean(ddx_bis**2+ddy_bis**2)) text = "rms = {:3.2f}''\n".format(rms) props = dict(boxstyle='round', facecolor='white', alpha=0.5) plt.text(0.03,-0.03,text,fontsize=8, bbox=props,verticalalignment='bottom', horizontalalignment='right') plt.xlabel("x_tan") plt.ylabel("y_tan") plt.legend(loc="upper left") plt.show() plt.show() <file_sep>#!/usr/bin/env python """Generate guider and spectrograph ICS sequences for running telescope dither tests. Can run in two modes: 1. rastermode, which will move the telescope boresight given a tile ID and step size. One can specify an offset of the raster center from the current location; the script will return to the current location at the end. And the labels on the raster positions will be relative to the current location. This is so that one can do multiple rasters in the same coordinate system. 2. fibermode, which will move the positioners given a range of consecutive tile IDs. Based on instructions available at https://desi.lbl.gov/trac/wiki/DESIOperations/DithSeq """ import os import json import logging as log import numpy as np from astropy import units as u from astropy.io import fits from argparse import ArgumentParser def get_tile_coords(tileid, dryrun=False): """Open fiberassign file and read tile location. Parameters ---------- tileid : int Tile ID. dryrun : bool If true, return dummy values. Returns ------- ra : float Boresight RA for this tile. dec : float Boresight declination for this tile. """ if dryrun: return 0., 0. if 'DOS_DESI_TILES' in os.environ: path = os.environ['DOS_DESI_TILES'] else: # Fallback to hardcoded path (issue a warning). path = '/data/tiles/ALL_tiles/20191119' log.warning('DOS_DESI_TILES undefined; using {}'.format(path)) fibfile = '/'.join([path, 'fiberassign-{:06d}.fits'.format(tileid)]) try: hdus = fits.open(fibfile) except FileNotFoundError as e: log.error('TILE {} cannot be found.\n{}.'.format(tileid, e)) raise SystemExit header = hdus['PRIMARY'].header ra, dec = header['TILERA'], header['TILEDEC'] return ra, dec def setup_rastermode(args): """Set up and write out JSON telescope raster script for dither tests. Parameters ---------- args : argparse.Namespace Argument list from command line rastermode subprogram. """ RA = args.deltara*u.arcsec DEC = args.deltadec*u.arcsec ra = RA dec = DEC # Set step size. Add a unit from astropy, does not change value. step = args.step*u.arcsec tile_id = args.tileid tile_ra, tile_dec = get_tile_coords(tile_id, args.dryrun) # Standard raster: 3x3 with 3 visits to (0,0), 11 exposures total. if args.pattern == '3x3': stepx = np.asarray([ 0, 1, -1, -1, 0, 1, 1, 0, -1, -1, 1])*step stepy = np.asarray([ 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, 1])*step # Extended raster: 5x5 with 3 visits to (0,0), 27 exposures in total. elif args.pattern == '5x5': # Inner 3x3: stepx = np.asarray([ 0, 1, -1, -1, 0, 0, 1, 1, 0, -1]) stepy = np.asarray([ 0, 1, 0, 0, -1, -1, 0, 0, 1, 0]) # Outer 5x5: _stepx = np.asarray([ 2, -1, -1, -1, -1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, -2]) _stepy = np.asarray([ 2, 0, 0, 0, 0, -1, -1, -1, -1, 0, 0, 0, 0, 1, 1, 1, -1]) stepx = np.concatenate((stepx, _stepx)) * step stepy = np.concatenate((stepy, _stepy)) * step # Generate single interleaved guider+spectrograph script: dith_script = [] log.debug('{:>5s} {:>5s} {:>5s} {:>5s}'.format('dx', 'dy', 'dRA', 'dDec')) for j, (dx, dy) in enumerate(zip(stepx, stepy)): ra = ra + dx dec = dec + dy log.debug('{:5g} {:5g} {:5g} {:5g}'.format( dx.to('arcsec').value, dy.to('arcsec').value, (ra-RA).to('arcsec').value, (dec-DEC).to('arcsec').value)) # Logging variables sent to ICS for output to FITS headers: passthru = '{{ OFFSTRA:{:g}, OFFSTDEC:{:g}, TILEID:{:d}, TILERA:{:g}, TILEDEC:{:g} }}'.format((ra-RA).to('arcsec').value, (dec-DEC).to('arcsec').value, tile_id, tile_ra, tile_dec) # Start a guide sequence. dith_script.append({'sequence' : 'Guide', 'flavor' : 'science', 'guider_exptime' : 5.0, 'action' : 'start_guiding', 'acquisition_time' : 15.0, 'deltara' : dx.to('arcsec').value, 'deltadec' : dy.to('arcsec').value, 'correct_for_adc' : False, 'usetemp' : False, 'uselut' : False, 'resetrot' : False, 'passthru' : passthru, 'program' : 'Dither tile_id {:05d} ({:g} {:g})'.format(tile_id, ra.to('arcsec').value, dec.to('arcsec').value)}) # Take a spectrograph exposure. dith_script.append({'sequence' : 'Spectrographs', 'flavor' : 'science', 'obstype' : 'SCIENCE', 'correct_for_adc' : False, 'usetemp' : False, 'uselut' : False, 'resetrot' : False, 'exptime' : 60.0, 'passthru' : passthru, 'program' : 'Dither tile_id {:05d} ({:g} {:g})'.format(tile_id, ra.to('arcsec').value, dec.to('arcsec').value)}) # Break, then manually stop guiding before starting the next exposure. dith_script.append({'sequence' : 'Break'}) # Dump JSON guider + spectrograph script into one file. dith_filename = 'dithseq_tile_{:06d}_step_{}arcsec_dra{}_ddec{}_{}.json'.format(tile_id, step.value, args.deltara, args.deltadec, args.pattern) json.dump(dith_script, open(dith_filename, 'w'), indent=4) log.info('Use {} in the DESI observer console.'.format(dith_filename)) def setup_fibermode(args): """Set up and write out JSON script for a fiber dithering sequence. Parameters ---------- args : argparse.Namespace Argument list from command line fibermode subprogram. """ # Generate single interleaved DESI sequence + spectrograph script: dith_script = [] minid, maxid = args.tilerange tile_ids = range(minid, maxid+1, 1) log.debug('{:>7s} {:>7s} {:>7s}'.format('Tile', 'RA', 'Dec')) for i, tile_id in enumerate(tile_ids): tile_ra, tile_dec = get_tile_coords(tile_id, args.dryrun) log.debug('{:7d} {:7g} {:7g}'.format(tile_id, tile_ra, tile_dec)) # Logging variables sent to ICS for output to FITS headers: passthru = '{{ TILEID:{:d}, TILERA:{:g}, TILEDEC:{:g} }}'.format(tile_id, tile_ra, tile_dec) # Stack up DESI sequences. Note: exptime is for spectrographs. dith_script.append({'sequence' : 'DESI', 'flavor' : 'science', 'obstype' : 'SCIENCE', 'fiberassign' : tile_id, 'exptime' : 60.0, 'guider_exptime' : 5.0, 'acquisition_exptime' : 15.0, 'fvc_exptime' : 2.0, 'usespectrographs' : True, 'stop_guiderloop_when_done' : True, 'passthru' : passthru, 'program' : 'Dither fibermode tile {:d} ({:g}, {:g})'.format(tile_id, tile_ra, tile_dec)}) # if i > 0: # dith_script[-1]['correct_for_adc'] = False # # # Break needed to manually stop guiding? # dith_script.append({'sequence' : 'Break'}) # Dump JSON DESI + spectrograph list into a file. dith_filename = 'dithseq_fibermode_{:06d}_{:06d}.json'.format(minid, maxid) json.dump(dith_script, open(dith_filename, 'w'), indent=4) log.info('Use {} in the DESI observer console.'.format(dith_filename)) if __name__ == '__main__': # Main options specified before rastermode and fibermode subcommands. p = ArgumentParser(description='Raster/fiber dithering JSON ICS setup program') p.add_argument('-d', '--dryrun', action='store_true', default=False, help='Dry run: do not check for fiberassign files') p.add_argument('-v', '--verbose', action='store_true', default=False, help='Verbose output for debugging') sp = p.add_subparsers(title='subcommands', description='valid subcommands', help='additional help') # Raster mode: move telescope boresight with deltara/deltadec prmode = sp.add_parser('rastermode', help='Telescope raster program') prmode.add_argument('-t', '--tileid', required=True, type=int, help='Tile ID used for raster') prmode.add_argument('-s', '--step', required=True, type=float, help='Raster step size in arcsec') prmode.add_argument('-p', '--pattern', choices=['3x3','5x5'], default='3x3', help='Raster pattern') prmode.add_argument('--plot', action='store_true', default=False, help='Plot raster pattern for debugging') prmode.add_argument('--deltara', default=0, type=float, help='RA offset raster center from Tile RA') prmode.add_argument('--deltadec', default=0, type=float, help='Dec offset raster center from Tile Dec') prmode.set_defaults(func=setup_rastermode) # Fiber mode: set up a sequence of fiberassign tiles. pfmode = sp.add_parser('fibermode', help='Fiber dither program') pfmode.add_argument('-t', '--tilerange', required=True, nargs=2, type=int, help='Min/max tile ID for positioners') pfmode.set_defaults(func=setup_fibermode) args = p.parse_args() if 'func' in args: if args.verbose: log.basicConfig(format='%(levelname)s: %(message)s', level=log.DEBUG) else: log.basicConfig(format='%(levelname)s: %(message)s', level=log.INFO) args.func(args) else: p.print_help() <file_sep>#!/usr/bin/env python import os,sys import fitsio import astropy.io.fits as pyfits from astropy.table import Table import matplotlib.pyplot as plt import numpy as np from desimeter.transform.radec2tan import hadec2xy from desimeter.simplecorr import SimpleCorr dither_file = sys.argv[1] fvc_file = sys.argv[2] fiberassign_file = sys.argv[3] t=fitsio.read(dither_file) print(t.dtype.names) i=0 err=np.sqrt(t['dxfiboff'][:,i]**2+t['dyfiboff'][:,i]**2) roff=np.sqrt(t['xfiboff'][:,i]**2+t['yfiboff'][:,i]**2) jj=np.where((err<0.02)&(roff<4.))[0] dither_ra = t['fiber_ditherfit_ra'][jj,i] dither_dec = t['fiber_ditherfit_dec'][jj,i] # Eddie: xfiboff = PM RA of star - true RA of star # opposite sign because xtan goes as -RA dither_dx = -t['xfiboff'][jj,i] dither_dy = t['yfiboff'][jj,i] dither_fiber = t['fiber'][jj,i].astype(int) t=Table.read(fvc_file) ii=(t["RA"]!=0) t=t[:][ii] desimeter_ra=t["RA"] desimeter_dec=t["DEC"] f=Table.read(fiberassign_file) head = fitsio.read_header(fiberassign_file) dico = { loc : i for i,loc in enumerate(f["LOCATION"])} target_ra=np.zeros(len(t)) target_dec=np.zeros(len(t)) target_fiber=np.zeros(len(t)) for j,loc in enumerate(t["LOCATION"]) : if loc in dico : i=dico[loc] target_ra[j] = f["TARGET_RA"][i] target_dec[j] = f["TARGET_DEC"][i] target_fiber[j] = f["FIBER"][i] tel_ra=head["REQRA"] tel_dec=head["REQDEC"] x1,y1=hadec2xy(-desimeter_ra+tel_ra,desimeter_dec,0,tel_dec) x2,y2=hadec2xy(-target_ra+tel_ra,target_dec,0,tel_dec) desimeter_dx=(x1-x2)*180.*3600/np.pi # now arcsec desimeter_dy=(y1-y2)*180.*3600/np.pi # now arcsec dither_x,dither_y=hadec2xy(-dither_ra+tel_ra,dither_dec,0,tel_dec) # Now find match to dithers dither_index = np.zeros(dither_fiber.size,dtype=int) for i,fiber in enumerate(dither_fiber) : jj=np.where(target_fiber == fiber)[0] if jj.size == 1 : dither_index[i] = jj[0] else : dither_index[i] = -1 d=np.sqrt(desimeter_dx**2+desimeter_dy**2) # arcsec ii=(target_ra!=0)&(d<10) corr=SimpleCorr() if 0 : # fit to fiber assign corr.fit(x1[ii],y1[ii],x2[ii],y2[ii]) print(corr) else : # fit to dither test ii1=dither_index[dither_index>=0] ii2=(dither_index>=0) corr.fit(x1[ii1],y1[ii1],(dither_x+dither_dx*np.pi/(180.*3600.))[ii2],(dither_y+dither_dy*np.pi/(180.*3600.))[ii2]) print(corr) x3,y3 = corr.apply(x1,y1) desimeter_dx_bis=(x3-x2)*180.*3600/np.pi # now arcsec desimeter_dy_bis=(y3-y2)*180.*3600/np.pi # now arcsec dist=np.sqrt(desimeter_dx_bis**2+desimeter_dy_bis**2) # arcsec ii=(target_ra!=0)&(dist<3) target_ra = target_ra[ii] target_dec = target_dec[ii] desimeter_ra = desimeter_ra[ii] desimeter_dec = desimeter_dec[ii] desimeter_x = x1[ii] desimeter_y = y1[ii] desimeter_dx = desimeter_dx[ii] desimeter_dy = desimeter_dy[ii] desimeter_dx_bis = desimeter_dx_bis[ii] desimeter_dy_bis = desimeter_dy_bis[ii] print(np.std(desimeter_dx)) print(np.std(dither_dx)) title=os.path.basename(dither_file).replace(".fits","-vs-desimeter") plt.figure(title) scale=20. plt.subplot(121) plt.quiver(desimeter_x,desimeter_y,desimeter_dx,desimeter_dy,color="grey",alpha=0.8,units="width",scale=scale,label="desimeter (uncorr)") plt.quiver(dither_x,dither_y,dither_dx,dither_dy,color="red",units="width",scale=scale,label="dither") x=-0.03 dx=2 plt.quiver(x,-0.025,dx,0.,color="black",units="width",scale=scale) plt.text(x,-0.029,"{} arcsec".format(dx)) plt.xlabel("x_tan") plt.ylabel("y_tan") plt.legend(loc="upper left") plt.subplot(122) plt.quiver(desimeter_x,desimeter_y,desimeter_dx_bis,desimeter_dy_bis,color="gray",alpha=0.8,units="width",scale=scale,label="desimeter (corr)") plt.quiver(dither_x,dither_y,dither_dx,dither_dy,color="red",units="width",scale=scale,label="dither") plt.quiver(x,-0.025,dx,0.,color="black",units="width",scale=scale) plt.text(x,-0.029,"{} arcsec".format(dx)) rad2arcsec = 180*3600/np.pi text = "dx = {:3.2f}''\n".format(corr.dx*rad2arcsec) text += "dy = {:3.2f}''\n".format(corr.dy*rad2arcsec) text += "sxx = {:6.5f}\n".format(corr.sxx-1) text += "syy = {:6.5f}\n".format(corr.syy-1) text += "sxy = {:6.5f}\n".format(corr.sxy) text += "rot = {:3.2f}''\n".format(corr.rot_deg*3600) props = dict(boxstyle='round', facecolor='white', alpha=0.5) plt.text(0.03,-0.03,text,fontsize=8, bbox=props,verticalalignment='bottom', horizontalalignment='right') plt.xlabel("x_tan") plt.ylabel("y_tan") plt.legend(loc="upper left") plt.show() plt.show()
8bf6077e6e9bf3dce619280fd27c40978f3b42c9
[ "Python" ]
3
Python
noahfranz13/desicmx
12296997f9dea2488c54f9c6f22681fff2f52eb3
96775233eba5ba5dadf09ec5991bf4f4a925a36d
refs/heads/master
<repo_name>kujyp/robster_project_newscommentcrawler_191106<file_sep>/app.py import atexit import os import queue from urllib.parse import urlparse from selenium import webdriver from selenium.webdriver.remote.webdriver import WebDriver from crawler import download_driver from crawler.utils import console from crawler.utils.fileio import save_as_json def open_browser(driver_path): # type: (str) -> WebDriver console.info() target_directory = os.path.dirname(driver_path) download_driver.install_driver_if_not_installed(target_directory) driver = webdriver.Chrome(driver_path) return driver def retrieve(driver, url, dynamic_table): # type: (WebDriver, str, DynamicTable) -> None driver.get(url) console.info(f"Crawl path [{url}]...") console.info(f"url_target_queue.qsize() [{dynamic_table.url_target_queue.qsize()}]...") a_tags = driver.find_elements_by_tag_name("a") # each_a_tag = a_tags[10] for each_a_tag in a_tags: href = each_a_tag.get_property("href") if not href: continue parsed = urlparse(href) url_path = parsed.netloc + parsed.path if url_path in dynamic_table.parsed: # console.info(f"Skip parsed path [{url_path}]") continue dynamic_table.parsed.add(url_path) if url_path.startswith("v.media.daum.net/v/"): console.info(f"Add found path [{url_path}]...") dynamic_table.url.add(url_path) elif (url_path not in dynamic_table.parsed) \ and url_path.startswith("media.daum.net/issue/") \ or url_path.startswith("media.daum.net/series/") \ or url_path.startswith("media.daum.net/ranking/age/") \ or url_path.startswith("media.daum.net/ranking/bestreply/") \ or url_path.startswith("media.daum.net/breakingnews/"): dynamic_table.url_target_queue.put(url_path) if dynamic_table.url_target_queue.empty(): return url_target = dynamic_table.url_target_queue.get_nowait() retrieve(driver, "https://" + url_target, dynamic_table) class DynamicTable: def __init__(self): super().__init__() self.url = set() self.parsed = set() self.url_target_queue = queue.Queue() if __name__ == '__main__': driver_path = os.path.join("driver", "chromedriver") driver = open_browser(driver_path) atexit.register(lambda: driver.quit()) dynamic_table = DynamicTable() seed_url = "https://media.daum.net/politics/" retrieve(driver, seed_url, dynamic_table) for url in dynamic_table.url: filepath = os.path.join("data", "daum", "articles", url) if os.path.exists(filepath): console.error(f"File already exists. [{filepath}]") continue save_as_json(filepath, { "url": url, }) <file_sep>/crawler/download_driver.py import os from crawler.utils import fileio, console from crawler.utils.shell import get_statement_with_cd, execute_with_message def download_driver(target_directory): fileio.make_path_if_doesnt_exist(target_directory) url = "https://chromedriver.storage.googleapis.com/2.43/chromedriver_mac64.zip" statement = get_statement_with_cd(target_directory, "wget -O {} {}".format("chromedriver.zip", url)) execute_with_message(statement) def extract_driver(target_directory): statement = get_statement_with_cd(target_directory, "tar xf {}".format("chromedriver.zip")) execute_with_message(statement) def install_driver(target_directory): console.info() download_driver(target_directory) extract_driver(target_directory) def install_driver_if_not_installed(target_directory): chromedriver_path = os.path.join(target_directory, "chromedriver") if os.path.exists(chromedriver_path): console.info("Driver already installed skip...") return install_driver(target_directory)
d7cd799e8923c876cb2c280b3683806867a8f841
[ "Python" ]
2
Python
kujyp/robster_project_newscommentcrawler_191106
41507ca585c7e724dde7efe7c7e19f56f8cbc1fe
d3a3fe0ace3f883b8022be181c288f8c45b16b4d
refs/heads/master
<repo_name>sultansidhu/jobCrawler<file_sep>/WelcomeScreen.py """ ============================================================================= Name of Software: jobCrawler Author: <NAME> and <NAME> Date: July 25th, 2018 USE OF PYTHON 3.6 OR HIGHER IS RECOMMENDED ============================================================================= """ import sys from PyQt5 import QtWidgets, QtGui, QtCore from PIL import * from PyQt5.QtGui import QIcon, QPixmap import JobCrawlerMain class WelcomeWindow(QtWidgets.QMainWindow): def __init__(self): """ Initializes a new MainWindow object, and creates the display screen """ super(WelcomeWindow, self).__init__() self.setGeometry(50,50,700,400) self.setWindowTitle("pyWeather - Enter City and Units") label2 = QtWidgets.QLabel(self) label2.setGeometry(0,0,700,400) label2.setPixmap(QPixmap("background.jpg")) lblLogo = QtWidgets.QLabel(self) lblLogo.setGeometry(55,2,300,70) lblLogo.setPixmap(QPixmap("logo.png")) self.city_entry = QtWidgets.QLineEdit(self) self.city_entry.setGeometry(5,370,350,20) font = QtGui.QFont() font.setItalic(True) font.setBold(True) font.setPointSize(12) lblCopyrightInfo = QtWidgets.QLabel("© Copyright Sultan Sidhu and Abhi Kapoor 2018", self) lblCopyrightInfo.setGeometry(405, 0, 300, 30) lblCopyrightInfo.setFont(font) self.lbl_enter_city = QtWidgets.QLabel(self) self.lbl_enter_city.setText("Enter a City: ") self.lbl_enter_city.setGeometry(5,342,350,25) self.lbl_enter_city.setFont(font) button_new = QtWidgets.QPushButton("Search", self) button_new.setGeometry(360,362,100,38) button_new.clicked.connect(self.display_options) self.show() def display_options(self): """ This method saves the user-entered city and launches the new screen, which displays the job fields and connects to the internet :return: None """ city = self.city_entry.text().strip() self.city_entry.setText("") self.screen2 = JobCrawlerMain.MainWindow(city) self.screen2.show() self.screen2.setWindowTitle("JobCrawler - Home") self.close() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) GUI = WelcomeWindow() sys.exit(app.exec_()) <file_sep>/JobCrawlerMain.py """ ============================================================= Name of Software: jobCrawler Author: <NAME> and <NAME> Date: July 25th, 2018 USE OF PYTHON 3.6 OR HIGHER IS RECOMMENDED ============================================================= """ import sys from PyQt5 import QtWidgets, QtGui, QtCore from PIL import * from PyQt5.QtGui import QIcon, QPixmap import requests from bs4 import BeautifulSoup import random class MainWindow(QtWidgets.QMainWindow): def __init__(self, city): """ Initializes a new MainWindow object, and creates the display screen """ super(MainWindow, self).__init__() self.setGeometry(50,50,700,400) self.setWindowTitle("pyWeather - Enter City and Units") self.city = city label2 = QtWidgets.QLabel(self) label2.setGeometry(0,0,700,400) label2.setPixmap(QPixmap("background.jpg")) lblLogo = QtWidgets.QLabel(self) lblLogo.setGeometry(55, 2, 300, 70) lblLogo.setPixmap(QPixmap("logo.png")) self.opts_lbl = QtWidgets.QLabel(self) self.opts_lbl.setGeometry(55, 0, 700, 400) self.logOutput = QtWidgets.QTextEdit(self) self.logOutput.setGeometry(25,70,640,270) self.logOutput.setVisible(False) self.city_entry = QtWidgets.QLineEdit(self) self.city_entry.setGeometry(5,370,350,20) self.new = QtWidgets.QLineEdit(self) self.new.setGeometry(5,370,350,20) self.new.setVisible(False) self.font = QtGui.QFont() self.font.setItalic(True) self.font.setBold(True) self.font.setPointSize(12) lblCopyrightInfo = QtWidgets.QLabel("© Copyright <NAME> and <NAME> 2018", self) lblCopyrightInfo.setGeometry(405, 0, 300, 30) lblCopyrightInfo.setFont(self.font) self.lbl_enter_city = QtWidgets.QLabel(self) self.lbl_enter_city.setText("Choose a Job Field from Above: ") self.lbl_enter_city.setGeometry(5,342,350,25) self.lbl_enter_city.setFont(self.font) button_new = QtWidgets.QPushButton("Search", self) button_new.setGeometry(360,362,100,38) button_new.clicked.connect(self.connect) self._display_job_fields() self.show() def _display_job_fields(self): """ This function displays all the possible job fields on the GUI in a visually appealing fashion :return: None """ lst = ['engineering and architecture', 'software', 'accounting', 'finance', 'administration', 'office', 'art', 'media', 'design', 'biotech', 'science', 'business', 'management', 'customer service', 'hr', 'education', 'miscellaneous', 'food', 'hospitality', 'general', 'labour', 'government'] str = "" for x in range(len(lst)): if x % 4 == 0: str += lst[x]+"\n\n" else: str += random.choice([2,3,4]) * " " +lst[x]+ " " * random.choice([2,3,4,5,6,7,8,9]) rfont = QtGui.QFont() rfont.setItalic(True) rfont.setBold(True) rfont.setPointSize(14) self.opts_lbl.setText(str) self.opts_lbl.setFont(rfont) def _jobchecker(self, choice: str): """ This function takes the user-entered job choice and returns the code word related to that job choice. The code word is then used in forming the URL :param choice: str :return: None """ if choice == 'engineering and architecture': return 'egr' elif choice == 'software': return 'sof' elif choice == "accounting" or "finance": return "acc" elif choice == "administration" or "admin" or "office": return "ofc" elif choice == "art" or "media" or "design": return "med" elif choice == "biotech" or "science": return "sci" elif choice == "business" or "management": return "bus" elif choice == "customer service" or "hr": return "csr" elif choice == "education" or "teaching": return "edu" elif choice == "miscellaneous": return "etc" elif choice == "food" or "hospitality": return "fbh" elif choice == "general" or "labour" or "general labour": return "lab" elif choice == "government": return "gov" else: raise Exception("invalid job choice entered.") def connect(self): """ This function connects to the Craigslist website using the BeautifulSoup library and extracts useful information from it :return: None """ job_choice = self.city_entry.text().lower() job_code = self._jobchecker(job_choice) url = "http://" + str(self.city) + ".craigslist.org/search/" + str(job_code) self.lbl_enter_city.setText("CONNECTING.....") self.lbl_enter_city.setFont(self.font) self.lbl_enter_city.repaint() response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') soup.prettify() dictionary = {"class": "result-title hdrlnk"} answer = soup.find_all('a', attrs=dictionary) names = [] links = [] for thing in answer: names.append(thing.string) links.append(thing.attrs["href"]) self.display_answer(names, links) def display_answer(self, names, links): """ Displays the links and the names of the jobs, found by parsing Craigslist :param names: List :param links: List :return: None """ results = "" if len(names) == len(links): for i in range(len(names)): results += "\n" #print("\n") nameres = "Job: " + names[i] results + "\n" results += nameres #print(nameres) lnk = "URL: " + links[i] results += "\n" results += lnk #print(lnk) results += "\n\n" #print("\n\n\n") print(results) self.logOutput.setVisible(True) self.logOutput.setText(results) self.opts_lbl.setText("") self.lbl_enter_city.setText("CONNECTION SUCCESSFUL") self.lbl_enter_city.setFont(self.font) self.lbl_enter_city.repaint() else: raise Exception("Incompatible data") if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) GUI = MainWindow() sys.exit(app.exec_())
52821b7a066c77f2cdd5e006699be09c69f9dae9
[ "Python" ]
2
Python
sultansidhu/jobCrawler
5fdf764b786a360f98756b968d3e36731326531a
5e31dbd09c32d1ad7f583c38708cfadc36627f36
refs/heads/master
<repo_name>cjw296/ForJames<file_sep>/src/model_vfvt/base.py ''' Created on Nov 10, 2012 @author: peterb ''' from sqlalchemy.ext.declarative import declarative_base, declared_attr,\ has_inherited_table import datetime from sqlalchemy.schema import Column from sqlalchemy.types import DateTime, Integer, String from sqlalchemy.sql.expression import and_, or_ from sqlalchemy.orm.deprecated_interfaces import SessionExtension from sqlalchemy.orm import attributes from sqlalchemy.orm.session import make_transient, object_session Base = declarative_base() class Common(object): @declared_attr def __tablename__(self): if (has_inherited_table(self) and Common not in self.__bases__): return None return self.__name__.lower() @declared_attr def __table_args__(self): return { 'mysql_engine':'InnoDB' } class Find_or_Create_by_Name(object): @classmethod def find_or_create(cls, session, name, **kwargs): query = session.query(cls).filter_by(name=name) result = query.first() if result is None: result = cls(name=name, **kwargs) session.add(result) return result class Find_or_Create_by_Name_On(object): @classmethod def find_or_create(cls, session, name, on_date=None): if on_date is None: on_date = datetime.datetime.now() result = session.query(cls).filter(and_(cls.name==name, cls.valid_on(on_date=on_date))).first() if result is None: ''' check to see there is not one in the future ''' next_one = session.query(cls).filter(and_(cls.name==name, cls.valid_from > on_date)).first() if next_one: on_date = next_one.valid_from result = cls(name=name, valid_from=on_date) session.add(result) return result class Reference(Base, Common, Find_or_Create_by_Name): id = Column(Integer, primary_key=True) name = Column(String(length=80)) ref = Column(Integer, default=0) @classmethod def next_ref(cls, session, name): ref = cls.find_or_create(session, name, ref=0) ref.ref = ref.ref+1 return ref.ref class ValidFromValidTo(Common): id = Column('id',Integer, primary_key=True) ref = Column(Integer, index=True) valid_from = Column(DateTime(), default=datetime.datetime.now) valid_to = Column(DateTime(), default=None) def new_version(self, session): # make us transient (removes persistent # identity). make_transient(self) old_version = session.query(self.__class__).get(self.id) self.valid_from = datetime.datetime.now() old_version.valid_to = self.valid_from # set 'id' to None. # a new PK will be generated on INSERT. self.id = None @classmethod def by_ref(cls, session, ref, on_date=None): return session.query(cls).filter(and_(cls.ref==ref, cls.valid_on(on_date))).first() @classmethod def query(cls, session, on_date=None): return session.query(cls).filter(cls.valid_on(on_date)) @classmethod def valid_on(cls,on_date=None): if on_date is None: on_date=datetime.datetime.now() return and_(cls.valid_from <= on_date, or_(cls.valid_to > on_date, cls.valid_to == None)) class VersionExtension(SessionExtension): def before_flush(self, session, flush_context, instances): for instance in session.dirty: if not isinstance(instance, ValidFromValidTo): continue if not session.is_modified(instance, passive=True): continue if not attributes.instance_state(instance).has_identity: continue # make it transient if instance.valid_to is None: instance.new_version(session) # re-add session.add(instance) def after_attach(self, session, instance): if isinstance(instance, ValidFromValidTo) and instance.ref is None: instance.ref = Reference.next_ref(session, instance.__class__.__name__) class _M2MCollection_(): def __init__(self, item, related_cls, relation_cls): self.item = item self.session = object_session(item) self.related_cls = related_cls self.relation_cls = relation_cls def __iter__(self): return self.on_date() def on_date(self, on_date=None): subselect = self.session.query(self.relation_cls.to_ref).filter(and_(self.relation_cls.from_ref==self.item.ref, self.relation_cls.valid_on(on_date))) query = self.session.query(self.related_cls).filter(and_(self.related_cls.ref.in_(subselect), self.related_cls.valid_on(on_date))) return iter(query) ''' Tag support ''' def append(self, obj, on_date=None): if self.item.ref is None or obj.ref is None: raise Exception("Add to relation on versioned object before adding to session") if on_date is None: on_date = datetime.datetime.now() self.session.add(self.relation_cls(from_ref=self.item.ref, to_ref=obj.ref, valid_from=on_date)) def remove(self, obj, on_date=None): if self.item.ref is None or obj.ref is None: raise Exception("Remove from relation on versioned object before adding to session") if on_date is None: on_date = datetime.datetime.now() result = self.session.query(self.relation_cls).filter(and_(self.relation_cls.from_ref==self.item.ref, self.relation_cls.to_ref==obj.ref, self.relation_cls.valid_on())).first() if result is not None: result.valid_to = on_date <file_sep>/src/simple_publish/server.py ''' The idea here was to create a model without version and then build a model with valid_from valid_to so that we can see what the data looked like at any particular time. This then allows us to have a publishing date and leave the view fixed at that date but continue to edit the data. Then publishing is changing the view date. If we mess up, just go back to the old date.... Note that this model is slow - but we will have pages in memory. if works the same with model or model_vfvt Created on Nov 17, 2012 @author: peterb ''' from pkg_resources import resource_filename from tornado.options import options, define import tornado.options import tornado.ioloop import tornado.web import model_vfvt as model import logging import time from sqlalchemy.sql.expression import and_ import json import datetime define("port", 8080, type=int, help="server port number (default: 8080)") define("db_url", 'sqlite:///simple_publish_vfvt.db', help="sqlalchemy db url") COOKIE_NAME = "simple_publish_session" class AccessHandler(tornado.web.RequestHandler): ''' Given a GET of no action Then renders login.html. Given a GET with action logout Then clear cookie and redirect to /. Given a POST will authenticate email, password with control and set cookie and redirect to next_url. ''' def get(self, error=None): if self.get_argument("action", None) == 'logout': self.clear_cookie(COOKIE_NAME) self.redirect('/') return email = self.get_argument("email",default=None) self.render("login.html", email=email, error=error) def post(self): session = self.application.Session() try: email = self.get_argument("email") password = self.get_argument("password") person = model.Person.query(session).filter(and_(model.Person.email==email, model.Person.password==password)).first() if person is None: raise Exception("Email or password incorrect!") self.set_secure_cookie(COOKIE_NAME, str(person.ref)) next_url = self.get_argument('next', '/') self.redirect(next_url) except Exception, ex: self.get(error=str(ex)) finally: session.close() @classmethod def get_auth_user_from_cookie(cls, handler): return handler.get_secure_cookie(COOKIE_NAME) class MainHandler(tornado.web.RequestHandler): def get(self): self.redirect("/page/") class PageHandler(tornado.web.RequestHandler): tmpl = "page-tmpl.html" def get(self, label, *args): session = self.application.Session() try: on_date = model.Publication.publication_date(session) page = None pages = list(model.Page.query(session, on_date).order_by(model.Page.sequence).all()) if label: for item in pages: if item.label == label: page = item break else: page = pages[0] self.render(self.tmpl, page=page, pages=pages, on_date=on_date) finally: session.close() class UserEditHandler(tornado.web.RequestHandler): tmpl = "users-edit-tmpl.html" def get_current_user(self): return AccessHandler.get_auth_user_from_cookie(self) @tornado.web.authenticated def get(self, *args, **kwargs): session = self.application.Session() try: criteria = self.get_argument("criteria","") offset = int(self.get_argument("offset", "0")) limit = int(self.get_argument("limit", "10")) query = model.Person.query(session) if criteria: query = query.filter(model.Person.email.like("%s%%" % criteria)) count = query.count() people = list(query.offset(offset).limit(limit)) permissions = list(model.Permission.query(session).all()) self.render(self.tmpl, page_name='users', offset=offset, limit=limit, count=count, criteria=criteria, people=people, permissions=permissions, error=kwargs.get("error"), action=kwargs.get("action")) finally: session.close() @tornado.web.authenticated def post(self): error = None session = self.application.Session() now = datetime.datetime.now() try: data = json.loads(self.get_argument("data")) for person_dict in data: ref = person_dict.get("ref") if ref is not None: person = model.Person.by_ref(session, abs(int(ref))) if int(ref) < 0: person.valid_to = now continue else: person = model.Person() session.add(person) person.email = person_dict.get("email") person.password = <PASSWORD>("password") current_perms = set([perm.ref for perm in person.permissions]) new_perms = set(person_dict.get("permissions")) for perm_ref in current_perms - new_perms: person.permissions.remove(model.Permission.by_ref(session, perm_ref)) for perm_ref in new_perms - current_perms: person.permissions.append(model.Permission.by_ref(session, perm_ref)) session.commit() except Exception,ex: error = str(ex) finally: session.close() self.get(error=error) class PageEditHandler(tornado.web.RequestHandler): tmpl = "page-edit-tmpl.html" def get_current_user(self): return AccessHandler.get_auth_user_from_cookie(self) @tornado.web.authenticated def get(self, ref, *args, **kwargs): session = self.application.Session() try: page = None pages = list(model.Page.query(session).order_by(model.Page.sequence).all()) if ref and ref != '-': page = model.Page.by_ref(session, ref) else: self.redirect("/page/%s/edit-html" % pages[0].ref) self.render(self.tmpl, page_name='pages', page=page, pages=pages, error=kwargs.get("error"), action=kwargs.get("action")) finally: session.close() @tornado.web.authenticated def post(self, ref, *args): error = None session = self.application.Session() try: action = self.get_argument("submit") if action == "Create": page = model.Page(title=self.get_argument('title'), content=self.get_argument('content')) session.add(page) session.commit() ref = page.ref elif action == "Save": page = model.Page.by_ref(session, ref) page.title = self.get_argument('title') page.content = self.get_argument('content') session.commit() elif action == "Delete": if session.query(model.Page).count() == 1: raise Exception("Cannot delete last page!") page = model.Page.by_ref(session, ref) session.delete(page) session.commit() elif action == "Add": page = model.Page.by_ref(session, ref) page.tags.append(model.Tag.find_or_create(session, self.get_argument("tag"))) session.commit() elif action == "Remove": page = model.Page.by_ref(session, ref) for tag_id in self.get_arguments("remove_tag_id"): tag = model.Tag.by_ref(session, tag_id) page.tags.remove(tag) session.commit() elif action == "Publish": model.Publication.publish(session) session.commit() elif action == "Save Order": sequence = [int(i) for i in self.get_argument('page_order').split(',')] for i,sequence_ref in enumerate(sequence): model.Page.by_ref(session, sequence_ref).sequence=i session.commit() except Exception,ex: error = str(ex) finally: session.close() if error is None and action=="Create": self.redirect("/page/%s/edit-html" % ref) elif error is None and action=="Delete": page = session.query(model.Page).first() self.redirect("/page/%s/edit-html" % page.ref) elif error is None and action=="Publish": self.redirect("/page/") else: self.get(ref, *args, error=error, action=action) class Application(tornado.web.Application): def __init__(self, *args, **kwargs): tornado.web.Application.__init__(self, *args, **kwargs) self.Session, self.engine = model.create_initialize_db(options.db_url) session = self.Session() try: page = model.Page.query(session).first() if page is None: session.add(model.Page(title="Index",content="Sample Page.")) session.commit() time.sleep(0.2) model.Publication.publish(session) session.commit() finally: session.close() def main(): tornado.options.parse_command_line() application = Application([ (r"/", MainHandler), (r"/login", AccessHandler), (r"/page/(.*)/edit.html", PageEditHandler), (r"/page/(.*)", PageHandler), (r"/users", UserEditHandler), ], static_path=resource_filename("web","www/static"), template_path=resource_filename("simple_publish","templates"), cookie_secret="it_was_a_dark_and_stormy_night_for_publishing", login_url="/login", debug=True) application.listen(options.port) logging.info('listening on port %s', options.port) tornado.ioloop.IOLoop.instance().start() if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) main()<file_sep>/src/model/tag.py ''' Created on Nov 18, 2012 @author: peterb ''' from sqlalchemy.types import Integer, String from sqlalchemy.schema import Column, Table, ForeignKey from sqlalchemy.orm import relationship from model.base import Base, Common class Tag(Base, Common): id = Column(Integer, primary_key=True) name = Column(String(80), unique=True, nullable=False) ''' one to many relation ''' parent_id = Column(Integer, ForeignKey('tag.id')) parent = relationship('Tag', remote_side='tag.c.id', backref="children") pages = relationship('Page', secondary="page_tag", back_populates="tags") def __init__(self, name): '''so you can construct as Tag('foo') rather than Tag(name-'foo') ''' self.name = name def __repr__(self): return "<Tag name=%r>" % self.name @classmethod def find_or_create_all(cls, session, names): result = session.query(cls).filter(cls.name.in_(names)).all() missing_names = set(names) - set([e.name for e in result]) for name in missing_names: tag = cls(name) session.add(tag) result.append(tag) return result @classmethod def find_or_create(cls, session, name): result = session.query(cls).filter(cls.name==name).first() if result is None: result = cls(name) session.add(result) return result page_tag = Table('page_tag', Base.metadata, Column('page_id', Integer, ForeignKey('page.id')), Column('tag_id', Integer, ForeignKey('tag.id')), mysql_engine='InnoDB' ) <file_sep>/src/model_vfvt/publication.py ''' Created on Nov 19, 2012 @author: peterb ''' from sqlalchemy.schema import Column from sqlalchemy.types import Integer, DateTime from model_vfvt import Base from model_vfvt.base import Common import datetime from sqlalchemy.sql.expression import func class Publication(Base, Common): id = Column(Integer, primary_key=True) on_date = Column(DateTime) @classmethod def publish(cls, session, on_date=None): if on_date is None: on_date = datetime.datetime.now() result = cls(on_date=on_date) session.add(result) return result @classmethod def publication_date(cls, session): return session.query(func.MAX(cls.on_date)).first()[0]<file_sep>/src/test/test_vfvt.py ''' Created on Nov 18, 2012 @author: peterb ''' import unittest from model_vfvt import create_initialize_db, Person, Tag, Page, Publication class Test(unittest.TestCase): def setUp(self): self._Session, self._engine = create_initialize_db("sqlite://", echo=False) self.session = self._Session() def tearDown(self): self.session.close() self._engine.dispose() self._Session = self._engine = None def test_publication(self): dt = Publication.publish(self.session).on_date self.session.commit() self.assertEquals(dt, Publication.publication_date(self.session)) dt = Publication.publish(self.session).on_date self.session.commit() self.assertEquals(dt, Publication.publication_date(self.session)) def test_person(self): print '------------ person' for person in self.session.query(Person).filter(Person.valid_on()): print person.id, person.ref, person.email, person.valid_from, person.valid_to for perm in person.permissions: print '\t', perm.id, perm.ref, perm.name, perm.valid_from, perm.valid_to def testTag(self): tag = Tag.find_or_create(self.session,'foo') self.session.commit() tag.name = 'harry' self.session.commit() print '------------ tag 1' for tag in self.session.query(Tag): print tag.id, tag.ref, tag.name, tag.valid_from, tag.valid_to print '------------ tag 2' for tag in self.session.query(Tag).filter(Tag.valid_on()): print tag.id, tag.ref, tag.name, tag.valid_from, tag.valid_to def testPage(self): tag = Tag.find_or_create(self.session,'bar') page = Page(title='foo') self.session.add(page) page.tags.append(tag) self.session.commit() print '------------ page' for page in self.session.query(Page).filter(Page.valid_on()): print page.id, page.ref, page.title, page.valid_from, page.valid_to for tag in page.tags: print '\t', tag.id, tag.ref, tag.name, tag.valid_from, tag.valid_to def testChange(self): tag = Tag.find_or_create(self.session,'bar') self.session.commit() print '------------ change' print tag.id, tag.ref, tag.name, tag.valid_from, tag.valid_to tag.name = 'foo' self.session.commit() print tag.id, tag.ref, tag.name, tag.valid_from, tag.valid_to def testOwner(self): tag = Tag(name='bar') page = Page(title='foo') person = Person(email="<EMAIL>") self.session.add_all([page, tag, person]) page.tags.append(tag) page.owner = person self.session.commit() self.session.expire_all() print '------------ owner' for page in self.session.query(Page).filter(Page.valid_on()): print page.id, page.ref, page.title, page.valid_from, page.valid_to, page.owner_ref owner = page.owner if owner: print '\t', owner.id, owner.ref, owner.email, owner.valid_from, owner.valid_to page.owner = None self.session.commit() self.session.expire_all() for page in self.session.query(Page).filter(Page.valid_on()): print page.id, page.ref, page.title, page.valid_from, page.valid_to, page.owner_ref owner = page.owner if owner: print '\t', owner.id, owner.ref, owner.email, owner.valid_from, owner.valid_to if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()<file_sep>/src/model_vfvt/person.py ''' Created on Nov 18, 2012 @author: peterb ''' from sqlalchemy.types import String, Integer from sqlalchemy.schema import Column from model_vfvt.base import Base,ValidFromValidTo, Find_or_Create_by_Name_On,\ _M2MCollection_ from model_vfvt.permission import Permission class Person(Base, ValidFromValidTo, Find_or_Create_by_Name_On): email = Column(String(80), nullable=False) password = Column(String(80)) @property def permissions(self): return _M2MCollection_(self,Permission,PersonPermission) class PersonPermission(Base, ValidFromValidTo): from_ref = Column(Integer) to_ref = Column(Integer) <file_sep>/src/web/__init__.py ''' This package will contain common web modules It also contains common web resources in the www folder '''<file_sep>/src/model_vfvt/page.py ''' Created on Nov 18, 2012 @author: peterb ''' from sqlalchemy.types import String, Integer, Text from sqlalchemy.schema import Column from sqlalchemy.orm import object_session from model_vfvt.base import Base,ValidFromValidTo, _M2MCollection_ from model_vfvt.tag import Tag from sqlalchemy.sql.expression import and_ from model_vfvt.person import Person class Page(Base, ValidFromValidTo): title = Column(String(80), nullable=False) content = Column(Text()) sequence = Column(Integer, default=0) @property def label(self): return self.title.lower().replace(' ','_') ''' Owner Support ''' owner_ref = Column(Integer) @property def owner(self): if self.owner_ref is None: return None session = object_session(self) query = session.query(Person).filter(and_(Person.ref==self.owner_ref, Person.valid_on())) return query.first() @owner.setter def owner(self, value): if value is None: self.owner_ref = None elif value.ref is None: raise Exception("Set relation before added to session") else: self.owner_ref = value.ref @property def tags(self): return _M2MCollection_(self,Tag,PageTag) class PageTag(Base, ValidFromValidTo): from_ref = Column(Integer) to_ref = Column(Integer) <file_sep>/src/model_vfvt/permission.py ''' Created on Nov 18, 2012 @author: peterb ''' from sqlalchemy.types import String from sqlalchemy.schema import Column from model_vfvt.base import Base,ValidFromValidTo from sqlalchemy.sql.expression import and_ import datetime ADMIN_ROLE = u'admin' USER_ROLE = u'user' DEV_ROLE = u'dev' AUTOMATIC_ROLE = 'automatic' REMOTE_ROLE = "remote" class Permission(Base, ValidFromValidTo): ROLES = [ADMIN_ROLE, USER_ROLE, DEV_ROLE, AUTOMATIC_ROLE, REMOTE_ROLE] name = Column(String(80), nullable=False) <file_sep>/setup.py #!/usr/bin/env python from setuptools import setup, find_packages import sys, os version = '0.25' setup(name='for_james', version=version, description="samples in tornado", long_description="""a hello world in tornado""", author='<NAME>', author_email='<EMAIL>', url='http://www.blueshed.co.uk/for_james', packages=find_packages('src',exclude=['*tests*']), package_dir = {'':'src'}, include_package_data = True, exclude_package_data = { '': ['tests/*'] }, install_requires = [ 'setuptools', 'tornado>=2.4', 'sockjs-tornado', 'sqlalchemy>=0.7.9' ], entry_points = { 'console_scripts' : [ 'publish_for_james = simple_publish.server:main', ] })<file_sep>/src/simple_tornado/web.py ''' This is from: http://www.tornadoweb.org I've changed the port to 8080 as that is what I'm used to... Just select web.py and choose 'Run As / Python Run' from the Run menu. Then open your browser to http://localhost:8080 Created on Nov 13, 2012 @author: peterb ''' import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8080) print "listening on 8080" tornado.ioloop.IOLoop.instance().start()<file_sep>/src/model/permission.py ''' Created on Nov 10, 2012 @author: peterb ''' from sqlalchemy.types import Integer, String from sqlalchemy.schema import Column from model.base import Base, Common ADMIN_ROLE = u'admin' USER_ROLE = u'user' DEV_ROLE = u'dev' AUTOMATIC_ROLE = 'automatic' REMOTE_ROLE = "remote" class Permission(Base, Common): ROLES = [ADMIN_ROLE, USER_ROLE, DEV_ROLE, AUTOMATIC_ROLE, REMOTE_ROLE] id = Column(Integer, primary_key=True) name = Column(String(80), nullable=False, unique=True) @classmethod def find_or_create(cls, session, name): result = session.query(cls).filter(cls.name==name).first() if result is None: result = cls(name=name) session.add(result) session.flush() return result<file_sep>/src/model/__init__.py ''' This will contain a common model for these sample applications, sorry, I'm lazy. ''' from sqlalchemy.engine import create_engine from sqlalchemy.orm.session import sessionmaker from sqlalchemy.exc import IntegrityError import logging from model.base import Base from model.permission import Permission from model.person import Person from model.page import Page from model.tag import Tag def create_initialize_db(db_url, echo=False): engine = create_engine(db_url, echo=echo) Base.metadata.create_all(engine) Session = sessionmaker(engine) session = Session() try: permissions = [Permission(name=name) for name in Permission.ROLES] session.add_all(permissions) admin = Person(email="admin",password="<PASSWORD>") user = Person(email="user",password="<PASSWORD>") session.add_all([admin, user]) admin.permissions.append(permissions[0]) admin.permissions.append(permissions[1]) user.permissions.append(permissions[1]) session.commit() except IntegrityError: pass except Exception, ex: logging.warn(ex) finally: session.close() return Session, engine<file_sep>/src/simple_xml/run.py ''' This uses the common model package. Just select web.py and choose 'Run As / Python Run' from the Run menu. Then read the console and the code... Created on Nov 13, 2012 @author: peterb ''' import xml.etree.ElementTree as ET import model import logging def run(db_url="sqlite://", xml_path="people.xml"): Session,engine = model.create_initialize_db(db_url, echo=True) session = Session() try: tree = ET.parse(xml_path) root = tree.getroot() for child in root: if child.tag == "person": email = child.find("email").text permissions_list = child.find("permissions").text.split(',') person = model.Person(email=email) session.add(person) for name in permissions_list: person.permissions.append(model.Permission.find_or_create(session, name)) session.commit() for person in session.query(model.Person).all(): print person finally: session.close() if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) run()<file_sep>/src/model_vfvt/tag.py ''' Created on Nov 18, 2012 @author: peterb ''' from sqlalchemy.types import String from sqlalchemy.schema import Column from model_vfvt.base import Base,ValidFromValidTo, Find_or_Create_by_Name_On class Tag(Base, ValidFromValidTo, Find_or_Create_by_Name_On): name = Column(String(80), nullable=False) <file_sep>/README.txt To install this: 1. create a python virtualenv using virtualenv.py 2. change directory to your new virtualenv 3. bin/pip install git+git://github.com/blueshedfriends/ForJames.git 4. bin/publish_for_james 5. browse to http://localhost:8080 6. to edit you'll need to login - try admin:admin - it usually works. <file_sep>/src/model/person.py ''' Created on Nov 10, 2012 @author: peterb ''' from sqlalchemy.types import Integer, String from sqlalchemy.schema import Column, Table, ForeignKey from sqlalchemy.orm import relationship from model.base import Base, Common class Person(Base, Common): id = Column(Integer, primary_key=True) email = Column(String(80), unique=True, nullable=False) password = Column(String(80)) permissions = relationship('Permission', secondary="person_permission", lazy='joined') '''Many to One relation with cascading delete ''' pages = relationship('Page', remote_side='page.c.owner_id', back_populates="owner", lazy='joined', cascade="all, delete-orphan") def __repr__(self): return "<Person email=%r>" % self.email def has_permissions(self, permissions): for permission in self.permissions: if permission.name in permissions: return True return False person_permission = Table('person_permission', Base.metadata, Column('person_id', Integer, ForeignKey('person.id')), Column('permission_id', Integer, ForeignKey('permission.id')), mysql_engine='InnoDB' ) <file_sep>/src/model/base.py ''' Created on Nov 10, 2012 @author: peterb ''' from sqlalchemy.ext.declarative import declarative_base, declared_attr,\ has_inherited_table Base = declarative_base() class Common(object): @declared_attr def __tablename__(self): if (has_inherited_table(self) and Common not in self.__bases__): return None return self.__name__.lower() @declared_attr def __table_args__(self): return { 'mysql_engine':'InnoDB' } @classmethod def by_ref(cls, session, id, on_date=None): return session.query(cls).get(id) @classmethod def query(cls, session, on_date=None): return session.query(cls) @property def ref(self): return self.id<file_sep>/src/model/page.py ''' Created on Nov 14, 2012 @author: peterb ''' from sqlalchemy.types import Integer, String from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.orm import relationship from model.base import Base, Common class Page(Base, Common): id = Column(Integer, primary_key=True) title = Column(String(80), unique=True, nullable=False) content = Column(String(80)) sequence = Column(Integer, default=0) ''' one to many relation ''' owner_id = Column(Integer, ForeignKey('person.id')) owner = relationship('Person', remote_side='person.c.id', back_populates="pages") tags = relationship('Tag', secondary="page_tag", back_populates="pages") @property def label(self): return self.title.lower().replace(' ','_') def __repr__(self): return "<Person email=%r>" % self.email def has_permissions(self, permissions): for permission in self.permissions: if permission.name in permissions: return True return False <file_sep>/src/model_vfvt/__init__.py ''' This will contain a common model for these sample applications, sorry, I'm lazy. ''' from sqlalchemy.engine import create_engine from sqlalchemy.orm.session import sessionmaker from sqlalchemy.exc import IntegrityError from sqlalchemy.schema import Index import logging from model_vfvt.base import Base, VersionExtension, Reference from model_vfvt.tag import Tag from model_vfvt.page import Page, PageTag from model_vfvt.permission import Permission from model_vfvt.person import Person, PersonPermission from model_vfvt.publication import Publication Index("tag_ref",Tag.ref,Tag.valid_from,Tag.valid_to) Index("page_ref",Page.ref,Page.valid_from,Page.valid_to) Index("page_tag_ref",PageTag.ref,PageTag.valid_from,PageTag.valid_to) Index("permission_ref",Permission.ref,Permission.valid_from,Permission.valid_to) Index("person_ref",Person.ref,Person.valid_from,Person.valid_to) Index("person_permission_ref",PersonPermission.ref,PersonPermission.valid_from,PersonPermission.valid_to) def create_initialize_db(db_url, echo=False): engine = create_engine(db_url, echo=echo) Base.metadata.create_all(engine) Session = sessionmaker(engine,extension=[VersionExtension()]) session = Session() try: if Permission.by_ref(session, 1) is None: permissions = [Permission(name=name) for name in Permission.ROLES] session.add_all(permissions) admin = Person(email="admin",password="<PASSWORD>") user = Person(email="user",password="<PASSWORD>") session.add_all([admin, user]) admin.permissions.append(permissions[0]) admin.permissions.append(permissions[1]) user.permissions.append(permissions[1]) session.commit() except IntegrityError: pass except Exception, ex: logging.warn(ex) finally: session.close() return Session, engine<file_sep>/src/simple_validation/run.py ''' This is from: http://www.tornadoweb.org I've changed the port to 8080 as that is what I'm used to... Just select web.py and choose 'Run As / Python Run' from the Run menu. Then open your browser to http://localhost:8080 Created on Nov 13, 2012 @author: peterb ''' from pkg_resources import resource_filename # we use this to make our paths relative to our packages! import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.render("index.html") def run(): static_path=resource_filename("web","www/static") template_path=resource_filename("simple_validation","/") application = tornado.web.Application([ (r"/", MainHandler), ], static_path=static_path, template_path=template_path, debug=True) application.listen(8080) print "listening on 8080" tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": run()
c81704e8d8b18f76ddabada3328c22fb75ecf18e
[ "Python", "Text" ]
21
Python
cjw296/ForJames
394bdade3f5175571a965c3c1777b9b528951920
883094bb6a91fa13403f56604254a368e52ca907
refs/heads/master
<file_sep>import grapesjs from 'grapesjs'; const editor = grapesjs.init({ autorender: 0, container: '#editor', fromElement: true, storageManager: { type: null}, layerManager: { appendTo: '.layers-container' }, panels: { defaults: [{ id: 'panel-top', el: '.panel__top' }, { id: 'basic-actions', el: '.panel__basic-actions', buttons: [{ id: 'visibility', active: true, // active by default className: 'btn-toggle-borders', label: '<u>B</u>', command: 'sw-visibility', // Built-in command }, { id: 'export', className: 'btn-open-export', label: 'Exp', command: 'export-template', context: 'export-template', // For grouping context of buttons from the same panel }, { id: 'show-json', className: 'btn-show-json', label: 'JSON', context: 'show-json', command(editor) { editor.Modal.setTitle('Components JSON') .setContent(`<textarea style="width:100%; height: 250px;"> ${JSON.stringify(editor.getComponents())} </textarea>`) .open(); } }] },{ id: 'layers', el: '.panel__right', resizable: { maxDim: 350, minDim: 200, tc: 0, cl: 1, cr: 0, bc: 0, keyWidth: 'flex-basis' } }] } }); export default editor;
6e5ce632898536c5e0670feb8f94316ce0fe74db
[ "JavaScript" ]
1
JavaScript
vkkotha/he-editor
cc6149deb73cf36c1832b29381c425d009518255
2ab2efe23b0cc44354abe6386a40d3b977b205af
refs/heads/master
<file_sep>const insertValue = (num) => { const input = document.getElementById('input-value').value document.getElementById('input-value').value = input + num } const calculate = () => { const input = document.getElementById('input-value').value document.getElementById('input-value').value = eval(input) } const clearInput = () => { document.getElementById('input-value').value = " " } const invertValue = () => { calculate() const input = document.getElementById('input-value').value document.getElementById('input-value').value = input * -1 } const percent = (num) => { calculate() const input = document.getElementById('input-value').value document.getElementById('input-value').value = eval(input) / 100 }
24e27504eb4d5764bddbe752116420fc61d768c9
[ "JavaScript" ]
1
JavaScript
Limarychard/calculator
011368ec33111880544101c87fbb98c255f03530
5c5f541b3e132783132e3a48f55bc4e4e2c9b644
refs/heads/master
<repo_name>Qwanead/973785-keksobooking-17<file_sep>/js/upload.js 'use strict'; (function () { var FILE_TYPES = ['gif', 'jpg', 'jpeg', 'png']; var avatarFileChooser = document.querySelector('#avatar'); var avatar = document.querySelector('.ad-form-header__preview img'); var isFileMatches = function (file) { var fileName = file.name.toLowerCase(); var matches = FILE_TYPES.some(function (it) { return fileName.endsWith(it); }); return matches; }; avatarFileChooser.addEventListener('change', function () { var file = avatarFileChooser.files[0]; if (file) { if (isFileMatches(file)) { var reader = new FileReader(); reader.addEventListener('load', function () { avatar.src = reader.result; }); reader.readAsDataURL(file); } } }); var resetAvatar = function () { var INITIAL_AVATAR_SRC = 'img/muffin-grey.svg'; avatar.src = INITIAL_AVATAR_SRC; }; var galleryFileChooser = document.querySelector('#images'); var galleryContainer = document.querySelector('.ad-form__photo-container'); var galleryBlock = document.querySelector('.ad-form__photo'); var galleryBlockTemplate = galleryBlock.cloneNode(); var onGalleryChange = function () { resetGallery(); var files = Array.from(galleryFileChooser.files); galleryBlock.parentNode.removeChild(galleryBlock); if (files) { files.forEach(function (file) { if (isFileMatches(file)) { var reader = new FileReader(); reader.addEventListener('load', function () { var galleryItem = galleryBlockTemplate.cloneNode(); var img = document.createElement('img'); galleryItem.appendChild(img); galleryContainer.appendChild(galleryItem); img.className = 'ad-form__photo'; img.src = reader.result; }); reader.readAsDataURL(file); } }); } }; galleryFileChooser.addEventListener('change', onGalleryChange); var resetGallery = function () { var galleryItems = Array.from(galleryContainer.querySelectorAll('div .ad-form__photo')); galleryItems.forEach(function (item) { item.parentNode.removeChild(item); }); galleryContainer.appendChild(galleryBlock); }; window.upload = { resetAvatar: resetAvatar, resetGallery: resetGallery }; })(); <file_sep>/js/form.js 'use strict'; (function () { var ESC_KEYCODE = 27; var lastTimeout; var debounce = function (cb) { var DEBOUNCE_INTERVAL = 500; if (lastTimeout) { window.clearTimeout(lastTimeout); } lastTimeout = window.setTimeout(cb, DEBOUNCE_INTERVAL); }; var loadedOffers; var createPin = function (offer) { var OFFER_PIN_WIDTH = 50; var OFFER_PIN_HEIGHT = 70; if (!offer) { return undefined; } var pinTemplate = document.querySelector('#pin').content.querySelector('.map__pin'); var pin = pinTemplate.cloneNode(true); var img = pin.querySelector('img'); pin.data = offer; pin.classList.add('map__pin--offer'); pin.style.left = (offer.location.x - OFFER_PIN_WIDTH / 2) + 'px'; pin.style.top = (offer.location.y - OFFER_PIN_HEIGHT) + 'px'; img.src = offer.author.avatar; img.alt = offer.offer.title; return pin; }; var removeCard = function () { var card = document.querySelector('.map__card'); if (card) { card.pin.classList.remove('map__pin--active'); card.parentNode.removeChild(card); } document.removeEventListener('keydown', onCardEscPress); }; var onCardEscPress = function (evt) { if (evt.keyCode === ESC_KEYCODE) { evt.preventDefault(); removeCard(); } }; var renderCard = function (pin) { removeCard(); var cardTemplate = document.querySelector('#card').content.querySelector('.map__card'); var card = cardTemplate.cloneNode(true); var avatar = card.querySelector('.popup__avatar'); var title = card.querySelector('.popup__title'); var address = card.querySelector('.popup__text--address'); var price = card.querySelector('.popup__text--price'); var type = card.querySelector('.popup__type'); var capacity = card.querySelector('.popup__text--capacity'); var time = card.querySelector('.popup__text--time'); var description = card.querySelector('.popup__description'); card.pin = pin; avatar.src = pin.data.author.avatar; title.textContent = pin.data.offer.title; address.textContent = pin.data.offer.address; price.textContent = pin.data.offer.price + '\u20bd' + '/ночь'; description.textContent = pin.data.offer.description; switch (pin.data.offer.type) { case 'flat': type.textContent = 'Квартира'; break; case 'bungalo': type.textContent = 'Бунгало'; break; case 'house': type.textContent = 'Дом'; break; case 'palace': type.textContent = 'Дворец'; break; } capacity.textContent = pin.data.offer.rooms + ' комнаты для ' + pin.data.offer.guests + ' гостей'; time.textContent = 'Заезд после ' + pin.data.offer.checkin + ', выезд до ' + pin.data.offer.checkout; var featuresList = card.querySelector('.popup__features'); var wifi = featuresList.querySelector('.popup__feature--wifi'); var dishwasher = featuresList.querySelector('.popup__feature--dishwasher'); var parking = featuresList.querySelector('.popup__feature--parking'); var washer = featuresList.querySelector('.popup__feature--washer'); var elevator = featuresList.querySelector('.popup__feature--elevator'); var conditioner = featuresList.querySelector('.popup__feature--conditioner'); while (featuresList.lastChild) { featuresList.removeChild(featuresList.lastChild); } pin.data.offer.features.forEach(function (feature) { switch (feature) { case 'wifi': featuresList.appendChild(wifi); break; case 'dishwasher': featuresList.appendChild(dishwasher); break; case 'parking': featuresList.appendChild(parking); break; case 'washer': featuresList.appendChild(washer); break; case 'elevator': featuresList.appendChild(elevator); break; case 'conditioner': featuresList.appendChild(conditioner); break; } }); var photosList = card.querySelector('.popup__photos'); var photo = photosList.querySelector('.popup__photo'); photosList.removeChild(photo); pin.data.offer.photos.forEach(function (srcPhoto) { var insertedPhoto = photo.cloneNode(); insertedPhoto.src = srcPhoto; photosList.appendChild(insertedPhoto); }); document.querySelector('.map__filters-container').insertAdjacentElement('beforebegin', card); var closeButton = document.querySelector('.popup__close'); closeButton.addEventListener('click', function () { removeCard(); }); document.addEventListener('keydown', onCardEscPress); }; var removePins = function () { var pins = document.querySelector('.map__offers'); if (pins) { pins.parentNode.removeChild(pins); } }; var renderPins = function (offers) { var NUM_OF_PINS = 5; if (offers.length === 0) { return undefined; } var fragment = document.createDocumentFragment(); var div = document.createElement('div'); div.className = 'map__offers'; fragment.appendChild(div); offers.slice(0, NUM_OF_PINS).forEach(function (pin) { if (pin.offer) { div.appendChild(createPin(pin)); } }); return fragment; }; var addHandlersOnPins = function (pins) { pins.forEach(function (pin) { pin.addEventListener('click', function () { pin.classList.add('map__pin--active'); renderCard(pin); }); }); }; var onLoad = function (offers) { loadedOffers = offers; document.querySelector('.map__pins').appendChild(renderPins(loadedOffers)); var pins = document.querySelectorAll('.map__pin--offer'); addHandlersOnPins(pins); }; var resetPage = function () { removeCard(); enableForm(false); removePins(); resetMapPin(); window.form.isEnabled = false; window.upload.resetAvatar(); window.upload.resetGallery(); }; var resetMapPin = function () { var MAP_PIN_INITIAL_COORD_X = 570; var MAP_PIN_INITIAL_COORD_Y = 375; var INITIAL_ADDRESS_VALUE = '603, 462'; var mapPin = document.querySelector('.map__pin--main'); var address = document.querySelector('input[name=address]'); address.value = INITIAL_ADDRESS_VALUE; mapPin.style.left = MAP_PIN_INITIAL_COORD_X + 'px'; mapPin.style.top = MAP_PIN_INITIAL_COORD_Y + 'px'; }; var removeMessage = function () { var message = document.querySelector('.success'); message.parentNode.removeChild(message); document.removeEventListener('click', onMessageClick); document.removeEventListener('keydown', onMessageEscPress); }; var onMessageClick = function () { removeMessage(); }; var onMessageEscPress = function (evt) { if (evt.keyCode === ESC_KEYCODE) { evt.preventDefault(); removeMessage(); } }; var showSuccessMessage = function () { var messageTemplate = document.querySelector('#success').content.querySelector('.success'); var message = messageTemplate.cloneNode(true); document.querySelector('body').appendChild(message); document.addEventListener('click', onMessageClick); document.addEventListener('keydown', onMessageEscPress); }; var onSave = function () { resetPage(); showSuccessMessage(); }; var removeErrorMessage = function () { var error = document.querySelector('.error'); error.parentNode.removeChild(error); document.removeEventListener('keydown', onErrorEscPress); }; var onErrorClick = function () { removeErrorMessage(); }; var onErrorEscPress = function (evt) { if (evt.keyCode === ESC_KEYCODE) { evt.preventDefault(); removeErrorMessage(); } }; var onError = function (response) { var errorTemplate = document.querySelector('#error').content.querySelector('.error'); var errorBlock = errorTemplate.cloneNode(true); var errorMessage = errorBlock.querySelector('.error__message'); errorMessage.textContent = response; document.querySelector('body').appendChild(errorBlock); var closeErrorButton = document.querySelector('.error__button'); closeErrorButton.addEventListener('click', onErrorClick); document.addEventListener('keydown', onErrorEscPress); }; var isFormEnabled = false; var enableForm = function (formEnabled) { var form = document.querySelector('.ad-form'); var fildsets = document.querySelectorAll('fieldset'); var selects = document.querySelectorAll('select'); for (var i = 0; i < fildsets.length; i++) { fildsets[i].disabled = !formEnabled; } for (i = 0; i < selects.length; i++) { selects[i].disabled = !formEnabled; } if (formEnabled) { document.querySelector('.map').classList.remove('map--faded'); form.classList.remove('ad-form--disabled'); window.backend.load(onLoad, onError); } else { document.querySelector('.map').classList.add('map--faded'); form.reset(); form.classList.add('ad-form--disabled'); } }; var syncTypeAndPrice = function () { var BUNGALO_MIN_PRICE = 0; var FLAT_MIN_PRICE = 1000; var HOUSE_MIN_PRICE = 5000; var PALACE_MIN_PRICE = 10000; switch (typeOfHousing.value) { case 'bungalo': price.min = BUNGALO_MIN_PRICE; price.placeholder = BUNGALO_MIN_PRICE; break; case 'flat': price.min = FLAT_MIN_PRICE; price.placeholder = FLAT_MIN_PRICE; break; case 'house': price.min = HOUSE_MIN_PRICE; price.placeholder = HOUSE_MIN_PRICE; break; case 'palace': price.min = PALACE_MIN_PRICE; price.placeholder = PALACE_MIN_PRICE; break; } }; var timein = document.querySelector('select[name=timein]'); var timeout = document.querySelector('select[name=timeout]'); var typeOfHousing = document.querySelector('select[name=type]'); var price = document.querySelector('input[name=price'); var syncTimeinAndTimeout = function () { timeout.selectedIndex = timein.selectedIndex; }; var syncTimeoutAndTimein = function () { timein.selectedIndex = timeout.selectedIndex; }; typeOfHousing.addEventListener('change', function () { syncTypeAndPrice(); }); timein.addEventListener('change', function () { syncTimeinAndTimeout(); }); timeout.addEventListener('change', function () { syncTimeoutAndTimein(); }); var disableOptions = function (numsOfOptions) { Array.from(capacity.options).forEach(function (option, index) { option.disabled = numsOfOptions.indexOf(index) !== -1; }); }; var selectOption = function (numOfOption) { capacity.options[numOfOption].selected = true; }; var syncRoomAndCapacity = function () { switch (roomsSelect.value) { case '1': disableOptions([0, 1, 3]); selectOption(2); break; case '2': disableOptions([0, 3]); selectOption(1); break; case '3': disableOptions([3]); selectOption(0); break; case '100': disableOptions([0, 1, 2]); selectOption(3); break; } }; var roomsSelect = document.querySelector('select[name=rooms]'); var capacity = document.querySelector('select[name=capacity]'); roomsSelect.addEventListener('change', function () { syncRoomAndCapacity(); }); var updatePins = function () { var resultPins = loadedOffers; removePins(); removeCard(); if (resultPins) { var housingType = document.querySelector('select[name=housing-type]'); switch (housingType.value) { case 'palace': resultPins = resultPins.filter(function (pins) { return pins.offer.type === 'palace'; }); break; case 'flat': resultPins = resultPins.filter(function (pins) { return pins.offer.type === 'flat'; }); break; case 'house': resultPins = resultPins.filter(function (pins) { return pins.offer.type === 'house'; }); break; case 'bungalo': resultPins = resultPins.filter(function (pins) { return pins.offer.type === 'bungalo'; }); break; } var housingPrice = document.querySelector('select[name=housing-price]'); switch (housingPrice.value) { case 'middle': resultPins = resultPins.filter(function (pins) { return (pins.offer.price >= 10000) && (pins.offer.price <= 50000); }); break; case 'low': resultPins = resultPins.filter(function (pins) { return pins.offer.price < 10000; }); break; case 'high': resultPins = resultPins.filter(function (pins) { return pins.offer.price > 50000; }); break; } var housingRoom = document.querySelector('select[name=housing-rooms]'); switch (housingRoom.value) { case '1': resultPins = resultPins.filter(function (pins) { return pins.offer.rooms === 1; }); break; case '2': resultPins = resultPins.filter(function (pins) { return pins.offer.rooms === 2; }); break; case '3': resultPins = resultPins.filter(function (pins) { return pins.offer.rooms === 3; }); break; } var housingGuest = document.querySelector('select[name=housing-guests]'); switch (housingGuest.value) { case '2': resultPins = resultPins.filter(function (pins) { return pins.offer.guests === 2; }); break; case '1': resultPins = resultPins.filter(function (pins) { return pins.offer.guests === 1; }); break; case '0': resultPins = resultPins.filter(function (pins) { return pins.offer.guests === 0; }); break; } var wifi = document.querySelector('#filter-wifi'); if (wifi.checked) { resultPins = resultPins.filter(function (pins) { return pins.offer.features.indexOf('wifi') !== -1; }); } var dishwasher = document.querySelector('#filter-dishwasher'); if (dishwasher.checked) { resultPins = resultPins.filter(function (pins) { return pins.offer.features.indexOf('dishwasher') !== -1; }); } var parking = document.querySelector('#filter-parking'); if (parking.checked) { resultPins = resultPins.filter(function (pins) { return pins.offer.features.indexOf('parking') !== -1; }); } var washer = document.querySelector('#filter-washer'); if (washer.checked) { resultPins = resultPins.filter(function (pins) { return pins.offer.features.indexOf('washer') !== -1; }); } var elevator = document.querySelector('#filter-elevator'); if (elevator.checked) { resultPins = resultPins.filter(function (pins) { return pins.offer.features.indexOf('elevator') !== -1; }); } var conditioner = document.querySelector('#filter-conditioner'); if (conditioner.checked) { resultPins = resultPins.filter(function (pins) { return pins.offer.features.indexOf('conditioner') !== -1; }); } if (resultPins.length > 0) { document.querySelector('.map__pins').appendChild(renderPins(resultPins)); var pins = document.querySelectorAll('.map__pin--offer'); addHandlersOnPins(pins); } } }; var formMapFilter = document.querySelector('.map__filters'); var filterSelectors = Array.from(formMapFilter.querySelectorAll('select')); var filterInputs = Array.from(formMapFilter.querySelectorAll('input')); var formFiltrs = filterSelectors.concat(filterInputs); formFiltrs.forEach(function (filter) { filter.addEventListener('change', function () { debounce(updatePins); }); }); var form = document.querySelector('.ad-form'); form.addEventListener('submit', function (evt) { evt.preventDefault(); window.backend.save(new FormData(form), onSave, onError); }); var resetButton = form.querySelector('.ad-form__reset'); resetButton.addEventListener('click', function (evt) { evt.preventDefault(); resetPage(); }); window.form = { enable: enableForm, isEnabled: isFormEnabled }; })();
1d0e25232102a2ccc2c3b2bb25df7fa9f666cfa9
[ "JavaScript" ]
2
JavaScript
Qwanead/973785-keksobooking-17
5286a746030fc75707c88a6ff278996e40c328ca
8add1844d9ebc05c61f614b0cef02db0e9e11a53
HEAD
<repo_name>lao-guan/Pythongit<file_sep>/readme.txt 这是我学习 Think Python 2e 过程中的代码 <file_sep>/ex3.2.py # coding:utf-8 # 第三章函数 Exercise 3.2. def do_twice(func,arg): # Runs a function twice func(arg) # func:function object func(arg) # arg : argument passed to the function def print_twice(arg): # Prints the argument twice. print(arg) # arg : anything printable print(arg) def do_four(func,arg): # Runs a function four time. do_twice(func,arg) # func: function object do_twice(func,arg) # arg : argument passed to the function do_twice(print_twice,'spam') print('') do_four(print_twice,'spam')
8cd47173d50a3267b7a25db805c4c56f34221bf4
[ "Python", "Text" ]
2
Text
lao-guan/Pythongit
e206b17fe27dbad35384e70de364d570fca42df2
49592f27af688a932f58212fe9ad68ed4dd68312
refs/heads/master
<repo_name>seppo0010/notion-ios<file_sep>/README.md # notion-ios guess words through the association of icons <file_sep>/Podfile platform :ios, '8.0' pod "ohmoc" pod "iCarousel" pod "MD5Digest"
b5a8bdab378a937d19f959ea4b25cca208d5dbed
[ "Markdown", "Ruby" ]
2
Markdown
seppo0010/notion-ios
30f65bd00165fa751acf1856980eddd594eb8ead
632db489c26e327422f17ecddbd43f0869499def
refs/heads/master
<repo_name>PSmigielski/Faceprism<file_sep>/src/Controller/ResetPasswordController.php <?php namespace App\Controller; use App\Entity\User; use App\Controller\SchemaController; use Opis\JsonSchema\Schema; use Opis\JsonSchema\Validator; use Symfony\Bridge\Twig\Mime\TemplatedEmail; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mime\Address; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait; use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface; use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface; /** * @Route("/v1/api/auth/resetpaswd", methods={"POST"}, defaults={"_is_api": true}) */ class ResetPasswordController extends AbstractController { use ResetPasswordControllerTrait; private $resetPasswordHelper; public function __construct(ResetPasswordHelperInterface $resetPasswordHelper) { $this->resetPasswordHelper = $resetPasswordHelper; } /** * Display & process form to request a password reset. * * @Route("", name="app_forgot_password_request") */ public function request(Request $request, MailerInterface $mailer, SchemaController $schemaController): Response { $reqData = []; if($content = $request->getContent()){ $reqData=json_decode($content, true); } $result = $schemaController->validateSchema('/../Schemas/resetPasswordRequestSchema.json', (object)$reqData); if($result===true){ return $this->processSendingPasswordResetEmail( $reqData['email'], $mailer ); } else{ return $result; } } /** * Validates and process the reset URL that the user clicked in their email. * * @Route("/{token}") */ public function reset(Request $request, UserPasswordEncoderInterface $passwordEncoder, string $token= null): JsonResponse { if (null === $token) { return new JsonResponse(["message" => 'No reset password token found in the URL or in the session.'], 400); } try { $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token); } catch (ResetPasswordExceptionInterface $e) { return new JsonResponse(["message" => sprintf( 'There was a problem validating your reset request - %s', $e->getReason() )], 200); } $reqData = []; if($content = $request->getContent()){ $reqData=json_decode($content, true); } $schema = Schema::fromJsonString(file_get_contents(__DIR__.'/../Schemas/resetPasswordSchema.json')); $validator = new Validator(); $result = $validator->schemaValidation((object)$reqData, $schema); if($result->isValid()){ $password = $reqData['password']; $encodedPassword = $passwordEncoder->encodePassword( $user, $password ); $user->setPassword($encodedPassword); $this->getDoctrine()->getManager()->flush(); return new JsonResponse(["message" => "password has been changed"], 200); } } private function processSendingPasswordResetEmail(string $email, MailerInterface $mailer): JsonResponse { $user = $this->getDoctrine()->getRepository(User::class)->findOneBy([ 'us_email' => $email ]); if (!$user) { return new JsonResponse(["message" => "email hasn't been sent"], 400); } try { $resetToken = $this->resetPasswordHelper->generateResetToken($user); } catch (ResetPasswordExceptionInterface $e) { return new JsonResponse(["message" => "email hasn't been sent"], 400); } $email = (new TemplatedEmail()) ->from(new Address('<EMAIL>', 'bot')) ->to($user->getEmail()) ->subject('Your password reset request') ->htmlTemplate('reset_password/email.html.twig') ->context([ 'resetToken' => $resetToken, ]); $mailer->send($email); return new JsonResponse(["message" => "email has been sent"], 200); } } <file_sep>/src/Controller/FriendRequestController.php <?php namespace App\Controller; use App\Entity\Friend; use App\Entity\FriendRequest; use App\Entity\User; use App\Repository\FriendRequestRepository; use DateTime; use Pagerfanta\Doctrine\ORM\QueryAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; use Pagerfanta\Pagerfanta; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Serializer; /** * @Route("/v1/api/friendRequest", defaults={"_is_api": true}) */ class FriendRequestController extends AbstractController { /** * @Route("/{userID}", methods={"GET"}) */ public function index(FriendRequestRepository $repo, Request $request, string $userID): JsonResponse { try{ $page = $request->query->get('page', 1); $qb = $repo->createGetAllFriendRequests($userID); $adapter = new QueryAdapter($qb); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage(25); $pagerfanta->setCurrentPage($page); $requests = array(); foreach($pagerfanta->getCurrentPageResults() as $req){ $requests[] = $req; } $data = [ "page"=> $page, "totalPages" => $pagerfanta->getNbPages(), "count" => $pagerfanta->getNbResults(), "requests"=> $requests ]; $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]); $resData = $serializer->serialize($data, "json",['ignored_attributes' => ['usPosts', "transitions", "timezone", "password", "email", "username","roles","gender", "salt", "post"]]); return JsonResponse::fromJsonString($resData, 200); } catch(OutOfRangeCurrentPageException $e){ return new JsonResponse(["message"=>"Page not found"], 404); } } /** * @Route("", methods={"POST"}) */ public function add(Request $req, SchemaController $schemaController){ $reqData = []; if($content = $req->getContent()){ $reqData = json_decode($content, true); } $result = $schemaController->validateSchema('/../Schemas/friendRequestSchema.json', (object) $reqData); if($result === true){ $em = $this->getDoctrine()->getManager(); $fr_req = new FriendRequest(); if($reqData['userID']===$reqData['friendID']){ return new JsonResponse(["error" => "You can't request yourself!"],400); } $user = $em->getRepository(User::class)->find($reqData['userID']); $friend = $em->getRepository(User::class)->find($reqData['friendID']); if(!$user || !$friend){ return new JsonResponse(["error" => "User with this id does not exist!"], 404); } $tempFriend = $em->getRepository(Friend::class)->findBy([ "fr_user" => $user, "fr_friend" => $friend ]); $tempReq = $em->getRepository(FriendRequest::class)->findBy([ "fr_req_user" => $user, "fr_req_friend" => $friend ]); if($tempFriend){ return new JsonResponse(["error" => "You have this pearson in friends!"], 400); } if(!$tempReq){ $fr_req->setUser($user); $fr_req->setFriend($friend); $fr_req->setRequestDate(new DateTime("now")); $fr_req->setAccepted(false); $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]); $resData = $serializer->serialize($fr_req, "json",['ignored_attributes' => ['usPosts', "transitions", "password", "salt", "dateOfBirth", "roles"]]); $em->persist($fr_req); $em->flush(); return JsonResponse::fromJsonString($resData, 201); }else{ return new JsonResponse(["error" => "request with this friend exist!"], 400); } } } /** * @Route("/accept/{requestID}", methods={"POST"}) */ public function accept(Request $req, string $requestID){ $em = $this->getDoctrine()->getManager(); $fr_req = $em->getRepository(FriendRequest::class)->find($requestID); if($fr_req){ $friend = new Friend(); $friend->setFriend($fr_req->getFriend()); $friend->setUser($fr_req->getUser()); $friend->setAcceptDate(new Datetime('now')); $em->remove($fr_req); $em->persist($friend); $em->flush(); return new JsonResponse(["message" => "friend added successfully!"], 201); }else{ return new JsonResponse(["error" => "request with this id does not exist!"], 404); } } } <file_sep>/README.md # Faceprism ## Getting Started Prerequisites for backend: * Composer * MariaDB server * openssl prerequisites for frontend: * NodeJS * npm ## Setup project 1. clone this repo ```text $ git clone git@github.com:PSmigielski/Faceprism.git ``` 2. Install required dependencies for backend and frontend ```text $ npm install $ composer install ``` 3. create directiory for public and private keys and generate them ```text $ mkdir config/jwt $ openssl genrsa -out config/jwt/private.pem -aes256 4096 $ openssl rsa -pubout -in config/jwt/private.pem -out config/jwt/public.pem ``` ## Used technologies and libraries * Symfony 5 * Mercure * MariaDB * Doctrine * Twig * React * Formik * Gsap * React Context API <file_sep>/assets/src/components/Navbar/index.js import React from 'react' import Logo from '../Logo'; import logoPath from '../../../images/default.png'; const Navbar = () => { const style = { backgroundSize:'contain', backgroundPosition: 'center', backgroundRepeat: 'no-repeat', backgroundImage: `url(${logoPath})` } return ( <div className="navbarWrapper"> <div className="navElementsWrapper"> <div className="searchBar"> <Logo minimal={true} /> <input type="text" className="navbarInput" placeholder="Szukaj" /> </div> <div className="menu"> <button className="navItem" style={style}/> <button className="navItem"> <svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M44.8 16.0269H19.2C17.44 16.0269 16.016 17.4682 16.016 19.2298L16 48.0565L22.4 41.6506H44.8C46.56 41.6506 48 40.2092 48 38.4476V19.2298C48 17.4682 46.56 16.0269 44.8 16.0269Z" fill="#201F1F"/> </svg> </button> <button className="navItem"> <svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M32 48C33.7875 48 35.25 46.5231 35.25 44.7179H28.75C28.75 46.5231 30.1962 48 32 48ZM41.75 38.1538V29.9487C41.75 24.9108 39.085 20.6933 34.4375 19.5774V18.4615C34.4375 17.0995 33.3488 16 32 16C30.6512 16 29.5625 17.0995 29.5625 18.4615V19.5774C24.8988 20.6933 22.25 24.8944 22.25 29.9487V38.1538L19 41.4359V43.0769H45V41.4359L41.75 38.1538Z" fill="#201F1F"/> </svg> </button> <button className="navItem"> <svg width="22" height="14" viewBox="0 0 22 14" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M12.5119 13.2543C11.7143 14.1752 10.2857 14.1752 9.48814 13.2543L0.875566 3.30931C-0.246186 2.01402 0.673919 1.78814e-06 2.38742 1.78814e-06L19.6126 1.78814e-06C21.3261 1.78814e-06 22.2462 2.01402 21.1244 3.30931L12.5119 13.2543Z" fill="black"/> </svg> </button> </div> </div> </div> ) } export default Navbar;<file_sep>/src/Controller/AuthController.php <?php namespace App\Controller; use App\Entity\User; use DateTime; use Gesdinet\JWTRefreshTokenBundle\Entity\RefreshToken; use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Serializer; /** * @Route("/v1/api/auth", methods={"POST"}, defaults={"_is_api": true}) */ class AuthController extends AbstractController { /** * @Route("/login") */ public function login(Request $req): JsonResponse { $user = new User(); $reqData = []; if($content = $req->getContent()){ $reqData=json_decode($content, true); } $user->setEmail($reqData['email']); $user->getId(); $res = new JsonResponse([ "data"=>[ "id" => $this->getUser()->getId(), "email" => $this->getUser()->getEmail(), "roles" => $this->getUser()->getRoles() ] ],200); return $res; } /** * @Route("/register") */ public function add(Request $req,SchemaController $schemaController, UserPasswordEncoderInterface $passEnc):JsonResponse { $reqData = []; if($content = $req->getContent()){ $reqData=json_decode($content, true); } $result = $schemaController->validateSchema('/../Schemas/registerSchema.json', (object)$reqData); if($result === true){ $user = new User(); $em = $this->getDoctrine()->getManager(); if(!$em->getRepository(User::class)->findOneBy(["us_email" => $reqData['email']])){ $user->setEmail($reqData['email']); $user->setPassword($passEnc->encodePassword($user, $reqData['password'])); if(!$schemaController->verifyDate($reqData['date_of_birth'])){ return new JsonResponse(["error"=>"invalid date"], 400); } $user->setDateOfBirth(new DateTime($reqData['date_of_birth'])); $user->setGender($reqData['gender']); $user->setName($reqData['name']); $user->setSurname( $reqData['surname']); $user->setRoles([]); $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]); $resData = $serializer->serialize($user, "json",['ignored_attributes' => ['usPosts', "transitions"]]); $em->persist($user); $em->flush(); return JsonResponse::fromJsonString($resData, 201); }else{ return new JsonResponse(["error"=>"user with this email exist!"], 400); } } else{ return $result; } } /** * @Route("/account", methods={"DELETE"}) */ public function remove(string $id) : JsonResponse{ $em = $this->getDoctrine()->getManager(); $user = $em->getRepository(User::class)->find($id); if(!$user){ return new JsonResponse(["error" => "User with this id does not exist!"], 404); } $em->remove($user); $em->flush(); return new JsonResponse(["message"=>"User has been deleted"], 201); } //add token refresh method /** * @Route("/logout", methods={"POST"}) */ public function logout(Request $request, JWTEncoderInterface $token) : JsonResponse { $decodedToken = $token->decode($request->cookies->get("BEARER")); $em = $this->getDoctrine()->getManager(); $refToken = $em->getRepository(RefreshToken::class)->findBy(["username" => $decodedToken["username"]]); if(gettype($refToken) == "array"){ foreach($refToken as $token){ $em->remove($token); $em->flush(); } } else{ $em->remove($refToken); $em->flush(); } $response = new JsonResponse(["message" => "successfully logged out"]); $response->headers->clearCookie("BEARER"); $response->headers->clearCookie("REFRESH_TOKEN"); return $response; //dump($refToken); die; } }<file_sep>/src/Controller/PostController.php <?php namespace App\Controller; use App\Entity\Post; use App\Entity\User; use App\Controller\SchemaController; use App\Repository\PostRepository; use DateTime; use Pagerfanta\Exception\OutOfRangeCurrentPageException; use Pagerfanta\Doctrine\ORM\QueryAdapter; use Pagerfanta\Pagerfanta; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Serializer; use Symfony\Component\Serializer\SerializerInterface; /** * @Route("/v1/api/posts", defaults={"_is_api": true}) * */ class PostController extends AbstractController { /** * @Route("", name="get_posts", methods={"GET"}) */ public function index(PostRepository $repo, SerializerInterface $serializer, Request $request): JsonResponse { try{ $page = $request->query->get('page', 1); $qb = $repo->createFindAllQuery(); $adapter = new QueryAdapter($qb); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage(25); $pagerfanta->setCurrentPage($page); $posts = array(); foreach($pagerfanta->getCurrentPageResults() as $post){ $posts[] = $post; } $data = [ "page"=> $page, "totalPages" => $pagerfanta->getNbPages(), "count" => $pagerfanta->getNbResults(), "posts"=> $posts ]; $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]); $resData = $serializer->serialize($data, "json",['ignored_attributes' => ['usPosts', "transitions", "timezone", "password", "email", "username","roles","gender", "salt", "post"]]); return JsonResponse::fromJsonString($resData, 200); } catch(OutOfRangeCurrentPageException $e){ return new JsonResponse(["message"=>"Page not found"], 404); } } /** * @Route("/{id}", name="get_post", methods={"GET"}) */ public function show(int $id): JsonResponse { $post = $this->getDoctrine()->getRepository(Post::class)->find($id); if(!$post){ return new JsonResponse(["message" => "no posts found"],404); } return new JsonResponse($post, 200); } /** * @Route("", name="add_post", methods={"POST"}) */ public function create(Request $request, SchemaController $schemaController):JsonResponse { $reqData = []; if($content = $request->getContent()){ $reqData=json_decode($content, true); } $result = $schemaController->validateSchema('/../Schemas/postSchema.json', (object) $reqData); if($result === true){ $author_id = $reqData['author_uuid']; $post = new Post(); $author = $this->getDoctrine()->getRepository(User::class)->find($author_id); if(!$author){ return new JsonResponse(["error"=> "user with this id does not exist!"], 404); } $post->setAuthor($author); if(array_key_exists('text', $reqData)||array_key_exists('img', $reqData)){ if(array_key_exists('text', $reqData)){ $post->setText($reqData['text']); } if(array_key_exists('img', $reqData)){ $post->setImage($reqData['img']); } } else{ return new JsonResponse(["error"=> "text or image required!"], 400); } $post->setCreatedAt(new DateTime("now")); $post->setLikeCount(0); $post->setCommentCount(0); $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]); $resData = $serializer->serialize($post, "json",['ignored_attributes' => ['usPosts', "transitions", "password", "salt", "dateOfBirth", "roles"]]); $em = $this->getDoctrine()->getManager(); $em->persist($post); $em->flush(); return JsonResponse::fromJsonString($resData, 201); } else{ return $result; } } /** * @Route("/{id}", name="edit_comment", methods={"PUT"}) */ public function edit(Request $request, string $id, SchemaController $schemaController) { $reqData = []; if($content = $request->getContent()){ $reqData=json_decode($content, true); } $result = $schemaController->validateSchema('/../Schemas/editPostSchema.json', (object) $reqData); if($result===true){ $em = $this->getDoctrine()->getManager(); $post = $em->getRepository(Post::class)->find($id); if(!$post){ return new JsonResponse(["message"=>"Post does not exist"], 404); } if(array_key_exists('text', $reqData)||array_key_exists('img', $reqData)){ if(array_key_exists('text', $reqData)){ $post->setText($reqData['text']); } if(array_key_exists('img', $reqData)){ $post->setImage($reqData['img']); } } else{ return new JsonResponse(["error"=> "text or image required!"], 400); } $em->persist($post); $em->flush(); return new JsonResponse(["message"=>"Post has been edited"], 200); } else{ return $result; } } /** * @Route("/{id}", name="delete_post", methods={"DELETE"}) */ public function remove(string $id) { $em = $this->getDoctrine()->getManager(); $post = $em->getRepository(Post::class)->find($id); if(!$post){ return new JsonResponse(["message"=>"Post does not exist"], 404); } $em->remove($post); $em->flush(); return new JsonResponse(["message"=>"Post has been deleted"], 200); } } <file_sep>/src/Entity/Friend.php <?php namespace App\Entity; use App\Repository\FriendRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=FriendRepository::class) */ class Friend { /** * @ORM\Id * @ORM\Column(name="fr_id", type="guid") * @ORM\GeneratedValue(strategy="UUID") */ private $fr_id; /** * @ORM\ManyToOne(targetEntity=User::class) * @ORM\JoinColumn(name="fr_user",referencedColumnName = "us_id", nullable=false) */ private $fr_user; /** * @ORM\ManyToOne(targetEntity=User::class) * @ORM\JoinColumn(name="fr_friend",referencedColumnName = "us_id",nullable=false) */ private $fr_friend; /** * @ORM\Column(type="datetime") */ private $fr_accept_date; public function getId(): ?string { return $this->fr_id; } public function getUser(): ?User { return $this->fr_user; } public function setUser(?User $fr_user): self { $this->fr_user = $fr_user; return $this; } public function getFriend(): ?User { return $this->fr_friend; } public function setFriend(?User $fr_friend): self { $this->fr_friend = $fr_friend; return $this; } public function getAcceptDate(): ?\DateTimeInterface { return $this->fr_accept_date; } public function setAcceptDate(\DateTimeInterface $fr_accept_date): self { $this->fr_accept_date = $fr_accept_date; return $this; } } <file_sep>/src/Entity/User.php <?php namespace App\Entity; use App\Repository\UserRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Security\Core\User\UserInterface; /** * @ORM\Entity(repositoryClass=UserRepository::class) */ class User implements UserInterface { /** * @ORM\Id * @ORM\Column(name="us_id", type="guid") * @ORM\GeneratedValue(strategy="UUID") */ private $us_id; /** * @ORM\Column(type="string", length=180, unique=true) */ private $us_email; /** * @ORM\Column(type="json") */ private $us_roles = []; /** * @var string The hashed password * @ORM\Column(type="string") */ private $us_password; /** * @ORM\Column(type="string", length=30) */ private $us_name; /** * @ORM\Column(type="string", length=100) */ private $us_surname; /** * @ORM\Column(type="date") */ private $us_date_of_birth; /** * @ORM\Column(type="string", length=20) */ private $us_gender; /** * @ORM\OneToMany(targetEntity=Post::class, mappedBy="po_author", orphanRemoval=true) */ private $us_posts; public function __construct() { $this->us_posts = new ArrayCollection(); } public function getId(): ?string { return $this->us_id; } public function getEmail(): ?string { return $this->us_email; } public function setEmail(string $email): self { $this->us_email = $email; return $this; } /** * A visual identifier that represents this user. * * @see UserInterface */ public function getUsername(): string { return (string) $this->us_email; } /** * @see UserInterface */ public function getRoles(): array { $roles = $this->us_roles; // guarantee every user at least has ROLE_USER $roles[] = 'ROLE_USER'; return array_unique($roles); } public function setRoles(array $roles): self { $this->us_roles = $roles; return $this; } /** * @see UserInterface */ public function getPassword(): string { return (string) $this->us_password; } public function setPassword(string $password): self { $this->us_password = $password; return $this; } /** * @see UserInterface */ public function getSalt() { // not needed when using the "bcrypt" algorithm in security.yaml } /** * @see UserInterface */ public function eraseCredentials() { // If you store any temporary, sensitive data on the user, clear it here // $this->plainPassword = null; } public function getName(): ?string { return $this->us_name; } public function setName(string $us_name): self { $this->us_name = $us_name; return $this; } public function getSurname(): ?string { return $this->us_surname; } public function setSurname(string $us_surname): self { $this->us_surname = $us_surname; return $this; } public function getDateOfBirth(): ?\DateTimeInterface { return $this->us_date_of_birth; } public function setDateOfBirth(\DateTimeInterface $us_date_of_birth): self { $this->us_date_of_birth = $us_date_of_birth; return $this; } public function getGender(): ?string { return $this->us_gender; } public function setGender(string $us_gender): self { $this->us_gender = $us_gender; return $this; } /** * @return Collection|Post[] */ public function getUsPosts(): Collection { return $this->us_posts; } public function addUsPost(Post $usPost): self { if (!$this->us_posts->contains($usPost)) { $this->us_posts[] = $usPost; $usPost->setAuthor($this); } return $this; } public function removeUsPost(Post $usPost): self { if ($this->us_posts->removeElement($usPost)) { // set the owning side to null (unless already changed) if ($usPost->getAuthor() === $this) { $usPost->setAuthor(null); } } return $this; } } <file_sep>/assets/src/components/Arrow/index.js import React from 'react' import { Link } from 'react-router-dom'; const Arrow = (props) => { return ( <Link className="arrowLink" to={props.route}> <svg width="72" height="67" viewBox="0 0 72 67" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M63 30.7083H20.49L31.23 20.6862L27 16.75L9 33.5L27 50.25L31.23 46.3138L20.49 36.2917H63V30.7083Z" fill="black"/> </svg> </Link> ) } export default Arrow;<file_sep>/src/Controller/LikeController.php <?php namespace App\Controller; use App\Entity\Like; use App\Entity\Post; use App\Entity\User; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/v1/api/like", defaults={"_is_api": true}) */ class LikeController extends AbstractController { /** * @Route("/{postID}", methods={"POST"}) */ public function index(string $postID, Request $request) : JsonResponse { $reqData = []; if($content = $request->getContent()){ $reqData = json_decode($content, true); } if(array_key_exists('user_uuid', $reqData)&&isset($reqData['user_uuid'])){ $em = $this->getDoctrine()->getManager(); $user = $em->getRepository(User::class)->find($reqData["user_uuid"]); $post = $em->getRepository(Post::class)->find($postID); if(!$user){ return new JsonResponse(["error"=>"user with this id doesn't exist!"], 400); } if(!$post){ return new JsonResponse(["error"=>"post with this id doesn't exist!"], 400); } if($em->getRepository(Like::class)->findBy(["li_post"=>$postID,"li_user"=>$reqData['user_uuid']])){ $like = $em->getRepository(Like::class)->findBy(["li_post"=>$postID,"li_user"=>$reqData['user_uuid']]); $em->remove($like[0]); $post->setLikeCount($post->getLikeCount()-1); $em->persist($post); $em->flush(); return new JsonResponse(["message"=>"like removed successfully"], 201); } $like = new Like(); $like->setPost($post); $like->setUser($user); $post->setLikeCount($post->getLikeCount()+1); $em->persist($like); $em->persist($post); $em->flush(); return new JsonResponse(["message"=>"like added successfully"], 201); }else{ return new JsonResponse(["error"=>"provide user uuid!"], 400); } } } <file_sep>/docs/v1-api-auth/untitled.md # /login {% api-method method="post" host="https://localhost:8000" path="/v1/api/auth/login" %} {% api-method-summary %} Login {% endapi-method-summary %} {% api-method-description %} This endpoint validates credentials and authorize user to service {% endapi-method-description %} {% api-method-spec %} {% api-method-request %} {% api-method-body-parameters %} {% api-method-parameter name="email" type="string" required=true %} user validated email {% endapi-method-parameter %} {% api-method-parameter name="password" type="string" required=true %} user password {% endapi-method-parameter %} {% endapi-method-body-parameters %} {% endapi-method-request %} {% api-method-response %} {% api-method-response-example httpCode=200 %} {% api-method-response-example-description %} {% endapi-method-response-example-description %} ``` { "id": "62f096ee-08d6-11ec-b09d-1c1b0da97ebc", "email": "<EMAIL>", "roles": [ "ROLE_USER" ], "profile_pic": "https://res.cloudinary.com/faceprism/image/upload/v1626432519/profile_pics/default_bbdyw0.png" } + BEARER and REFRESH_TOKEN cookies ``` {% endapi-method-response-example %} {% api-method-response-example httpCode=401 %} {% api-method-response-example-description %} {% endapi-method-response-example-description %} ``` { "code": 401, "message": "Invalid credentials." } ``` {% endapi-method-response-example %} {% endapi-method-response %} {% endapi-method-spec %} {% endapi-method %} <file_sep>/assets/src/components/RegisterFirstStep/index.js import React,{useRef} from 'react' import {useFormik} from 'formik' const RegisterFirstStep = React.forwardRef(({nextStep, setFirstStepData}, ref) => { const datepicker = useRef(null); const handleStepChange = (values) =>{ setFirstStepData(values) nextStep(); } const validate = (values) => { const errors = {}; if (!values.name) { errors.name = 'Pole jest wymagane'; } else if(values.name.length > 30) { errors.name = 'Imię nie może być dłuże niż 30 znaków'; } else if(!/^[a-ząęśćźżńółA-ZĄĘŚĆŻŹŃÓŁ]{1,}$/i.test(values.name)) { errors.name = 'Imię zawiera niedozwolone znaki'; } if (!values.surname) { errors.surname = 'Pole jest wymagane'; } else if(values.surname.length > 100) { errors.surname = 'Nazwisko nie może być dłuże niż 100 znaków'; } else if(!/^[a-ząęśćźżńółA-ZĄĘŚĆŻŹŃÓŁ]{1,}$/i.test(values.surname)){ errors.surname = 'Nazwisko zawiera niedozwolone znaki'; } if(!values.dateOfBirth){ errors.dateOfBirth = 'Pole jest wymagane'; } else if(!/^\d{4}-\d{2}-\d{2}$/.test(values.dateOfBirth)){ errors.dateOfBirth = 'Data nie spełnia formatu YYYY-MM-DD'; } return errors; } const formik = useFormik({ initialValues:{ name:'', surname:'', gender:'', dateOfBirth:'' }, validate, onSubmit: handleStepChange }) const setMaxDate = () => { const date = new Date(); return `${date.getFullYear()}-${date.getMonth()+1 < 10 ? `0${date.getMonth()+1}` : date.getMonth()+1}-${date.getDate() <10 ? `0${date.getDate()}` : date.getDate()}` } return ( <form onSubmit={formik.handleSubmit} className="registerModalStep" ref={ref}> <div className="inputContainer"> <input id="name" name="name" type="text" className="registerInput" onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.email} placeholder="Imię" /> <p className="error">{formik.touched.name && formik.errors.name ? formik.errors.name : null}</p> </div> <div className="inputContainer"> <input id="surname" name="surname" type="text" className="registerInput" onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.email} placeholder="Nazwisko" /> <p className="error">{formik.touched.surname && formik.errors.surname? formik.errors.surname : null}</p> </div> <div className="registerRadiosContainer"> <p className="registerRadioLabel">Płeć:</p> <div className="radios"> <div className="registerRadioContainer"> <label className="registerRadioLabel">mężczyzna</label> <input id="gender" name="gender" type="radio" value="male" className="registerRadioInput" onBlur={formik.handleBlur} onChange={formik.handleChange} /> </div> <div className="registerRadioContainer"> <label className="registerRadioLabel">kobieta</label> <input id="gender" name="gender" type="radio" value="female" className="registerRadioInput" onBlur={formik.handleBlur} onChange={formik.handleChange} /> </div> </div> </div> <div className="inputContainer"> <input ref={datepicker} id="dateOfBirth" name="dateOfBirth" type="text" onBlur={()=>formik.values.dateOfBirth == '' ? datepicker.current.type = "text" : datepicker.current.type = "date"} onFocus={()=>datepicker.current.type = "date"} className="registerInput" onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.email} placeholder="<NAME>" max={setMaxDate()} /> <p className="error">{formik.touched.dateOfBirth && formik.errors.dateOfBirth ? formik.errors.dateOfBirth : null}</p> </div> <button className="registerStepButton" type="submit">Następny etap</button> </form> ) }); export default RegisterFirstStep;<file_sep>/SUMMARY.md # Table of contents * [Faceprism](README.md) ## /v1/api/auth * [/login](docs/v1-api-auth/untitled.md) <file_sep>/src/Entity/Comment.php <?php namespace App\Entity; use App\Repository\CommentRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=CommentRepository::class) */ class Comment { /** * @ORM\Id * @ORM\Column(name="co_id", type="guid") * @ORM\GeneratedValue(strategy="UUID") */ private $co_id; /** * @ORM\ManyToOne(targetEntity=User::class) * @ORM\JoinColumn(name="co_author",referencedColumnName = "us_id", nullable=false) */ private $co_author; /** * @ORM\ManyToOne(targetEntity=Post::class, inversedBy="po_comments") * @ORM\JoinColumn(name="co_post",referencedColumnName = "po_id", nullable=false) */ private $co_post; /** * @ORM\Column(type="string", length=255) */ private $co_text; /** * @ORM\Column(type="datetime") */ private $co_created_at; /** * @ORM\Column(type="datetime",nullable=true) */ private $co_edited_at; /** * @ORM\OneToOne(targetEntity=Comment::class, inversedBy="co_reply", cascade={"persist", "remove"}) * @ORM\JoinColumn(name="co_reply_to",referencedColumnName = "co_id", nullable=true) */ private $co_reply_to; /** * @ORM\OneToOne(targetEntity=Comment::class, mappedBy="co_reply_to", cascade={"persist", "remove"}) * @ORM\JoinColumn(name="co_reply",referencedColumnName = "co_id", nullable=true) */ private $co_reply; public function getId(): ?string { return $this->co_id; } public function getAuthor(): ?User { return $this->co_author; } public function setAuthor(?User $co_author): self { $this->co_author = $co_author; return $this; } public function getPost(): ?Post { return $this->co_post; } public function setPost(?Post $co_post): self { $this->co_post = $co_post; return $this; } public function getText(): ?string { return $this->co_text; } public function setText(string $co_text): self { $this->co_text = $co_text; return $this; } public function getCreatedAt(): ?\DateTimeInterface { return $this->co_created_at; } public function setCreatedAt(\DateTimeInterface $co_created_at): self { $this->co_created_at = $co_created_at; return $this; } public function getEditedAt(): ?\DateTimeInterface { return $this->co_edited_at; } public function setEditedAt(\DateTimeInterface $co_edited_at): self { $this->co_edited_at = $co_edited_at; return $this; } public function getReplyTo(): ?self { return $this->co_reply_to; } public function setReplyTo(?self $co_reply_to): self { $this->co_reply_to = $co_reply_to; return $this; } public function getReplies(): ?self { return $this->co_reply; } public function setReplies(?self $co_reply): self { // unset the owning side of the relation if necessary if ($co_reply === null && $this->co_reply !== null) { $this->co_reply->setCoReplyTo(null); } // set the owning side of the relation if necessary if ($co_reply !== null && $co_reply->getReplyTo() !== $this) { $co_reply->setReplyTo($this); } $this->co_replies = $co_reply; return $this; } } <file_sep>/assets/src/views/RemindPassword/index.js import React from 'react' import Arrow from '../../components/Arrow' import Logo from '../../components/Logo' import RemindPasswordForm from '../../components/RemindPasswordForm' const RemindPassword = () => { return ( <div className="remindPasswordWrapper"> <Arrow route="/"/> <Logo /> <RemindPasswordForm /> </div> ) } export default RemindPassword<file_sep>/src/Entity/FriendRequest.php <?php namespace App\Entity; use App\Repository\FriendRequestRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=FriendRequestRepository::class) */ class FriendRequest { /** * @ORM\Id * @ORM\Column(name="fr_req_id", type="guid") * @ORM\GeneratedValue(strategy="UUID") */ private $fr_req_id; /** * @ORM\ManyToOne(targetEntity=User::class) * @ORM\JoinColumn(name="fr_req_user",referencedColumnName = "us_id",nullable=false) */ private $fr_req_user; /** * @ORM\ManyToOne(targetEntity=User::class) * @ORM\JoinColumn(name="fr_req_friend",referencedColumnName = "us_id",nullable=false) */ private $fr_req_friend; /** * @ORM\Column(type="datetime") */ private $fr_req_requestDate; /** * @ORM\Column(type="boolean", options={"default" : 0}) */ private $fr_req_accepted; public function getId(): ?string { return $this->fr_req_id; } public function getUser(): ?User { return $this->fr_req_user; } public function setUser(?User $fr_req_user): self { $this->fr_req_user = $fr_req_user; return $this; } public function getFriend(): ?User { return $this->fr_req_friend; } public function setFriend(?User $fr_req_friend): self { $this->fr_req_friend = $fr_req_friend; return $this; } public function getRequestDate(): ?\DateTimeInterface { return $this->fr_req_requestDate; } public function setRequestDate(\DateTimeInterface $fr_req_requestDate): self { $this->fr_req_requestDate = $fr_req_requestDate; return $this; } public function getAccepted(): ?bool { return $this->fr_req_accepted; } public function setAccepted(bool $fr_req_accepted): self { $this->fr_req_accepted = $fr_req_accepted; return $this; } } <file_sep>/assets/src/components/Hero/index.js import React from "react"; import Logo from "../../components/Logo"; const Hero = () => { return ( <div className="heroWrapper"> <Logo /> <p className="heroParagraph">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ac felis sed neque congue fermentum. Etiam quis interdum tellus, nec pulvinar sem. </p> </div> ) } export default Hero;<file_sep>/assets/src/components/RegisterSecondStep/index.js import React from 'react' import {useFormik} from "formik" const RegisterSecondStep = React.forwardRef(({prevStep, handleSubmitEvent}, ref) => { const handleSubmit = (values) => handleSubmitEvent(values) const validate = (values) => { const errors = {}; if (!values.email) { errors.email = 'Pole jest wymaganie'; } else if (!/^(([^<>()[\]\\.,;:\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,}))$/.test(values.email)) { errors.email = 'Nieprawidłowy adres email'; } if(!values.password){ errors.password = '<PASSWORD>'; } else if(!/^(?=.*\d)(?=.*[a-z])(?=.*[\!\@\#\$\%\^\&\*\(\)\_\+\-\=])(?=.*[A-Z])(?!.*\s).{8,}$/.test(values.password)){ errors.password = 'Hasło powinno się sk<PASSWORD>ć z minimum 8 znaków w tym jednej dużej litery, cyfry i znaku specjalnego'; } if(!values.passwordConf){ errors.passwordConf = '<PASSWORD>'; } else if(values.password != values.passwordConf){ errors.passwordConf = 'Hasła nie są do siebie podobne'; } return errors; } const formik = useFormik({ initialValues:{ password:'', email:'', passwordConf:'' }, validate, onSubmit: handleSubmit }) const style = { display:'none', transfom: "translateX(100%)" } return ( <form onSubmit={formik.handleSubmit} className="registerModalStep" ref={ref} style={style}> <div className="inputContainer"> <input id="email" name="email" type="email" className="registerInput" onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.email} placeholder="Email" /> <p className="error">{formik.touched.email && formik.errors.email ? formik.errors.email : null}</p> </div> <div className="inputContainer"> <input id="password" name="password" type="password" className="registerInput" onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.password} placeholder="Hasło" /> <p className="error">{formik.touched.password && formik.errors.password ? formik.errors.password : null}</p> </div> <div className="inputContainer"> <input id="passwordConf" name="passwordConf" type="password" className="registerInput" onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.passwordConf} placeholder="Pow<NAME>" /> <p className="error">{formik.touched.passwordConf && formik.errors.passwordConf ? formik.errors.passwordConf : null}</p> </div> <div className="registerButtonContainer"> <button className="registerStepButton" onClick={prevStep} type="button">Wróć</button> <button className="registerStepButton" type="submit">Zarejestruj się</button> </div> </form> ) }); export default RegisterSecondStep; <file_sep>/assets/src/components/RemindPasswordForm/index.js import React from 'react' import {useFormik} from 'formik' const RemindPasswordForm = () => { const handleSubmit = (values) => handleSubmitEvent(values) const validate = (values) => { const errors = {}; if (!values.email) { errors.email = 'Pole jest wymaganie'; } else if (!/^(([^<>()[\]\\.,;:\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,}))$/.test(values.email)) { errors.email = 'Nieprawidłowy adres email'; } return errors; } const formik = useFormik({ initialValues:{ email:'' }, validate, onSubmit:handleSubmit }) return ( <div className="remindPasswordFormWrapper"> <form className="remindPasswordForm"> <p className="remindPasswordParagraph">Przypomnij hasło</p> <div className="inputContainer"> <input id="email" name="email" type="email" className="remindInput" onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.email} placeholder="Email" /> <p className="error">{formik.touched.email && formik.errors.email ? formik.errors.email : null}</p> </div> <button className="remindPasswordSubmit" type="submit">Wyślij email</button> </form> </div> ) } export default RemindPasswordForm;<file_sep>/src/Entity/Like.php <?php namespace App\Entity; use App\Repository\LikeRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=LikeRepository::class) * @ORM\Table(name="`like`") */ class Like { /** * @ORM\Id * @ORM\Column(name="li_id", type="guid") * @ORM\GeneratedValue(strategy="UUID") */ private $li_id; /** * @ORM\ManyToOne(targetEntity=User::class) * @ORM\JoinColumn(name="li_user",referencedColumnName = "us_id", nullable=false) */ private $li_user; /** * @ORM\ManyToOne(targetEntity=Post::class) * @ORM\JoinColumn(name="li_post",referencedColumnName = "po_id", nullable=false) */ private $li_post; public function getId(): ?string { return $this->li_id; } public function getUser(): ?User { return $this->li_user; } public function setUser(?User $li_user): self { $this->li_user = $li_user; return $this; } public function getPost(): ?Post { return $this->li_post; } public function setPost(?Post $li_post): self { $this->li_post = $li_post; return $this; } } <file_sep>/assets/src/views/ChangePassword/index.js import React from 'react' import ChangePasswordForm from '../../components/ChangePasswordForm' import Logo from '../../components/Logo' export default function ChangePassword() { return ( <div className="changePasswordWrapper"> <Logo /> <ChangePasswordForm /> </div> ) } <file_sep>/src/Controller/FriendController.php <?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/v1/api/friend", defaults={"_is_api": true}) */ class FriendController extends AbstractController { /** * @Route("/{userID}", methods={"GET"}) */ public function index() : JsonResponse { return new JsonResponse(["message"]); } /** * @Route("", methods={"POST"}) */ public function add() : JsonResponse { return new JsonResponse(["message"]); } /** * @Route("/{userID}/{friendID}", methods={"DELETE"}) */ public function remove(string $userID, string $friendID) : JsonResponse { return new JsonResponse(["message"]); } } <file_sep>/src/Entity/Post.php <?php namespace App\Entity; use App\Repository\PostRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=PostRepository::class) */ class Post { /** * @ORM\Id * @ORM\Column(name="po_id", type="guid") * @ORM\GeneratedValue(strategy="UUID") */ private $po_id; /** * @ORM\ManyToOne(targetEntity=User::class, inversedBy="us_posts") * @ORM\JoinColumn(name="po_author",referencedColumnName = "us_id", nullable=false) */ private $po_author; /** * @ORM\Column(type="datetime") */ private $po_created_at; /** * @ORM\Column(type="datetime", nullable=true) */ private $po_edited_at; /** * @ORM\Column(type="text",length=1024, nullable=true) */ private $po_text; /** * @ORM\Column(type="string", nullable=true) */ private $po_image; /** * @ORM\OneToMany(targetEntity=Comment::class, mappedBy="co_post", orphanRemoval=true) */ private $po_comments; /** * @ORM\Column(type="integer") */ private $po_like_count; /** * @ORM\Column(type="integer") */ private $po_comment_count; public function __construct() { $this->po_comments = new ArrayCollection(); } public function getId(): ?string { return $this->po_id; } public function getAuthor(): ?User { return $this->po_author; } public function setAuthor(?User $po_author): self { $this->po_author = $po_author; return $this; } public function getCreatedAt(): ?\DateTimeInterface { return $this->po_created_at; } public function setCreatedAt(\DateTimeInterface $po_created_at): self { $this->po_created_at = $po_created_at; return $this; } public function getEditedAt(): ?\DateTimeInterface { return $this->po_edited_at; } public function setEditedAt(?\DateTimeInterface $po_edited_at): self { $this->po_edited_at = $po_edited_at; return $this; } public function getText(): ?string { return $this->po_text; } public function setText(string $po_text): self { $this->po_text = $po_text; return $this; } public function getImage() { return $this->po_image; } public function setImage($po_image): self { $this->po_image = $po_image; return $this; } /** * @return Collection|Comment[] */ public function getPoComments(): Collection { return $this->po_comments; } public function addPoComment(Comment $poComment): self { if (!$this->po_comments->contains($poComment)) { $this->po_comments[] = $poComment; $poComment->setPost($this); } return $this; } public function removePoComment(Comment $poComment): self { if ($this->po_comments->removeElement($poComment)) { // set the owning side to null (unless already changed) if ($poComment->getPost() === $this) { $poComment->setPost(null); } } return $this; } public function getLikeCount(): ?int { return $this->po_like_count; } public function setLikeCount(int $po_like_count): self { $this->po_like_count = $po_like_count; return $this; } public function getCommentCount(): ?int { return $this->po_comment_count; } public function setCommentCount(int $po_comment_count): self { $this->po_comment_count = $po_comment_count; return $this; } } <file_sep>/src/Controller/SchemaController.php <?php namespace App\Controller; use DateTime; use Opis\JsonSchema\{ Validator, Schema }; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; class SchemaController extends AbstractController { public function validateSchema(string $pathToSchema, object $data){ $schema = Schema::fromJsonString(file_get_contents(__DIR__.$pathToSchema)); $validator = new Validator(); $result = $validator->schemaValidation($data, $schema); if($result->isValid()){ return true; } else{ return $this->getErrorMessage($result); } } static public function verifyDate($date, $strict = true) : bool{ $dateTime = DateTime::createFromFormat('Y-m-d', $date); if ($strict) { $errors = DateTime::getLastErrors(); if (!empty($errors['warning_count'])) { return false; } } return $dateTime !== false; } private function getErrorMessage(object $result) : JsonResponse { switch($result->getFirstError()->keyword()){ case "format": return new JsonResponse(["error"=>"invalid email format"], 400); break; case "type": switch($result->getFirstError()->dataPointer()[0]){ case "text": return new JsonResponse(["error"=>"text has invalid type"], 400); break; case "password": return new JsonResponse(["error"=>"password has invalid type"], 400); break; case "date_of_birth": return new JsonResponse(["error"=>"date has invalid types wrong format"], 400); break; case "email": return new JsonResponse(["error"=>"email has invalid type"], 400); break; case "name": return new JsonResponse(["error"=>"name has invalid type"], 400); break; case "surname": return new JsonResponse(["error"=>"surname has invalid type"], 400); break; case "img": return new JsonResponse(["error"=>"image has invalid type"], 400); break; } break; case "maxLength": switch($result->getFirstError()->dataPointer()[0]){ case "text": return new JsonResponse(["error"=>"text is too long"], 400); break; case "password": return new JsonResponse(["error"=>"password is too long"], 400); break; case "date_of_birth": return new JsonResponse(["error"=>"date of birth has wrong format"], 400); break; case "email": return new JsonResponse(["error"=>"email is too long"], 400); break; case "name": return new JsonResponse(["error"=>"name is too long"], 400); break; case "surname": return new JsonResponse(["error"=>"surname is too long"], 400); break; } break; case "minLength": switch($result->getFirstError()->dataPointer()[0]){ case "password": return new JsonResponse(["error"=>"password is too short"], 400); break; case "date_of_birth": return new JsonResponse(["error"=>"date of birth has wrong format"], 400); break; case "author_uuid": return new JsonResponse(["error"=>"author uuid has wrong fromat"], 400); break; } break; case "required": switch ($result->getFirstError()->keywordArgs()["missing"]) { case "author_uuid": return new JsonResponse(["error"=>"author uuid is missing"], 400); break; case "post_uuid": return new JsonResponse(["error"=>"post uuid is missing"], 400); break; case "password": return new JsonResponse(["error"=>"password is <PASSWORD>"], 400); break; case "date_of_birth": return new JsonResponse(["error"=>"date of birth has wrong format"], 400); break; case "email": return new JsonResponse(["error"=>"email is too long"], 400); break; case "name": return new JsonResponse(["error"=>"name is too long"], 400); break; case "surname": return new JsonResponse(["error"=>"surname is too long"], 400); break; } break; } } } ?><file_sep>/src/EventListener/AuthenticationSuccessListener.php <?php namespace App\EventListener; use App\Entity\User; use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent; use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationSuccessResponse; use Symfony\Component\HttpFoundation\Cookie; class AuthenticationSuccessListener { private $jwtTokenTTL; private $em; private $cookieSecure = false; public function __construct($ttl, $em) { $this->jwtTokenTTL = $ttl; $this->em = $em; } /** * This function is responsible for the authentication part * * @param AuthenticationSuccessEvent $event * @return JWTAuthenticationSuccessResponse */ public function onAuthenticationSuccess(AuthenticationSuccessEvent $event) { /** @var JWTAuthenticationSuccessResponse $response */ $response = $event->getResponse(); $data = $event->getData(); $tokenJWT = $data['token']; unset($data['token']); unset($data['refresh_token']); $event->setData($data); $tempUser = $event->getUser(); $user = $this->em->getRepository(User::class)->findBy(["us_email"=>$tempUser->getUsername()])[0]; $response->headers->setCookie(new Cookie('BEARER', $tokenJWT, ( new \DateTime()) ->add(new \DateInterval('PT' . $this->jwtTokenTTL . 'S')), '/', null, $this->cookieSecure)); $data = [ "id" => $user->getId(), "email" => $user->getEmail(), "roles" => $user->getRoles() ]; $event->setData($data); return $response; } }<file_sep>/src/Controller/CommentController.php <?php namespace App\Controller; use App\Entity\Comment; use App\Entity\Post; use App\Entity\User; use App\Controller\SchemaController; use App\Repository\CommentRepository; use DateTime; use Pagerfanta\Doctrine\ORM\QueryAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; use Pagerfanta\Pagerfanta; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Serializer; use Symfony\Component\Serializer\SerializerInterface; /** * @Route("/v1/api/comments", defaults={"_is_api": true}) */ class CommentController extends AbstractController { /** * @Route("/{postId}", name="get_comments", methods={"GET"}) */ public function index(CommentRepository $repo, Request $request, SerializerInterface $serializer, string $postId): JsonResponse { try{ $page = $request->query->get('page', 1); $qb = $repo->findAllComments($postId); $adapter = new QueryAdapter($qb); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage(25); $pagerfanta->setCurrentPage($page); $comments = array(); foreach($pagerfanta->getCurrentPageResults() as $comment){ $comments[] = $comment; } $data = [ "page"=> $page, "totalPages" => $pagerfanta->getNbPages(), "count" => $pagerfanta->getNbResults(), "comments"=> $comments ]; $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]); $resData = $serializer->serialize($data, "json",['ignored_attributes' => ['usPosts', "transitions", "timezone", "password", "email", "username","roles","gender", "salt", "post"]]); return JsonResponse::fromJsonString($resData); }catch(OutOfRangeCurrentPageException $e){ return new JsonResponse(["message"=>"Page not found"], 404); } } /** * @Route("", name="create_comment",methods={"POST"}) */ public function create(Request $request, SchemaController $schemaController):JsonResponse { $reqData = []; if($content = $request->getContent()){ $reqData=json_decode($content, true); } $result = $schemaController->validateSchema('/../Schemas/commentSchema.json', (object)$reqData); if($result===true){ $comment = new Comment(); $author = $this->getDoctrine()->getRepository(User::class)->find($reqData['author_uuid']); $post = $this->getDoctrine()->getRepository(Post::class)->find($reqData['post_uuid']); if(!$author){ return new JsonResponse(["error"=> "user with this id does not exist!"], 404); } if(!$post){ return new JsonResponse(["message"=>"Post does not exist"], 404); } $comment->setAuthor($author); $comment->setPost($post); $comment->setText($reqData['text']); $comment->setCreatedAt(new DateTime("now")); $post->setCommentCount($post->getCommentCount()+1); $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]); $resData = $serializer->serialize($comment, "json",['ignored_attributes' => ['usPosts', "transitions", "password", "<PASSWORD>", "dateOfBirth", "roles", "email", "username","gender","post"]]); $em = $this->getDoctrine()->getManager(); $em->persist($comment); $em->persist($post); $em->flush(); return JsonResponse::fromJsonString($resData, 201); } else{ return $result; } } /** * @Route("/{id}", name="edit_comment",methods={"PUT"}) */ public function edit(Request $request, string $id, SchemaController $schemaController):JsonResponse { $reqData = []; if($content = $request->getContent()){ $reqData=json_decode($content, true); } $result = $schemaController->validateSchema('/../Schemas/commentEditSchema.json', (object)$reqData); if($result === true){ $em = $this->getDoctrine()->getManager(); $comment = $em->getRepository(Comment::class)->find($id); if(!$comment){ return new JsonResponse(["error"=>"comment does not exist!"], 404); } $comment->setText($reqData['text']); $em->persist($comment); $em->flush(); return new JsonResponse(["message"=>"Post has been edited"], 200); } else{ return $result; } } /** * @Route("/{id}", name="delete_comment", methods={"DELETE"}) */ public function remove(string $id) { $em = $this->getDoctrine()->getManager(); $comment = $em->getRepository(Comment::class)->find($id); if(!$comment){ dump($comment); return new JsonResponse(["message"=>"Comment does not exist"], 404); } $post = $comment->getPost(); $post->setCommentCount($post->getCommentCount()-1); $em->remove($comment); $em->persist($post); $em->flush(); return new JsonResponse(["message"=>"Comment has been deleted"], 200); } }
8cff20092e74f6f5d6c8ba52ab2027c4a0127725
[ "Markdown", "JavaScript", "PHP" ]
26
PHP
PSmigielski/Faceprism
bd07cb8fe763f6d402f5a2444725da2f7cdba3eb
fbb4aab247d324bf182bb35b2529f1bedb193442
refs/heads/master
<file_sep>package de.leafmc.debug.bungee; import de.leafmc.debug.spigot.Debug; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.plugin.Command; public final class CommandBungeeDebug extends Command { public CommandBungeeDebug(final String name, final String permission, final String... aliases) { super(name, permission, aliases); } @SuppressWarnings("deprecation") @Override public void execute(final CommandSender sender, final String[] args) { if(args.length == 1 && args[0].equalsIgnoreCase("show")) { for(final Object object : Debug.getInstance().getManager().getDebugs()) { sender.sendMessage("§c" + object.toString()); } sender.sendMessage(Debug.PREFIX + "§cAnzahl der Debugs§7: §e" + Debug.getInstance().getManager().getDebugs().size()); }else if(args.length == 2 && args[0].equalsIgnoreCase("show")) { if(Debug.getInstance().getManager().isDebugged(args[1])) { for(final Object object : Debug.getInstance().getManager().getDebugs(args[1])) { sender.sendMessage("§c" + object.toString()); } sender.sendMessage(Debug.PREFIX + "§cAnzahl der Debugs§7: §e" + Debug.getInstance().getManager().getDebugs(args[1]).size()); }else { sender.sendMessage(Debug.PREFIX + "§cKeine Debugs zu Plugin §e" + args[1]); } }else { sender.sendMessage(Debug.PREFIX + "§c/bdebug show [PluginName]"); } } } <file_sep>package de.leafmc.debug.spigot; import org.bukkit.plugin.java.JavaPlugin; import de.leafmc.debug.core.Manager; public final class Debug extends JavaPlugin { public static final String PREFIX = "§7[§bDebug§7] "; private static Debug instance; private Manager manager; @Override public void onLoad() { instance = this; manager = new Manager(); } @Override public void onEnable() { getCommand("debug").setExecutor(new CommandDebug()); } public static Debug getInstance() { return instance; } public Manager getManager() { return manager; } } <file_sep>package de.leafmc.debug.core; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public final class Manager { private final List<Object> debugs = new ArrayList<>(); private final Map<String, List<Object>> pluginDebugs = new HashMap<>(); public void add(final Object object) { debugs.add(object); } public void add(final String plugin, final Object object) { if(pluginDebugs.containsKey(plugin)) { pluginDebugs.get(plugin).add(object); }else { final List<Object> list = new ArrayList<>(); list.add(object); pluginDebugs.put(plugin, list); } } public boolean isDebugged(final String pluginName) { for(final String plugin : pluginDebugs.keySet()) { if(plugin.equalsIgnoreCase(pluginName)) return true; } return false; } public List<Object> getDebugs() { return this.debugs; } public List<Object> getDebugs(final String pluginName) { if(isDebugged(pluginName)) { return pluginDebugs.get(pluginName); } return new ArrayList<Object>(); } }
494c9d9f05c03ece3937fb67284509aa25f4987c
[ "Java" ]
3
Java
LeafMC-Devs/DebugSystem
14ba6572de3d03e78c9604fe705a304d2afff0c2
e288b8207fa660cd01e89df09839af940a7b352b
refs/heads/master
<repo_name>aarohan01/Blackjack<file_sep>/old/black_jack.py #!/usr/bin/env python # coding: utf-8 # In[1]: import os import random import pyfiglet import colorama import time # In[2]: #ranks = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King') ranks = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') #suits = ('Spade', 'Clover', 'Diamond', 'Heart') suits = ('S', 'C', 'D', 'H') #values = {'1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'Jack':10, 'Queen':10, 'King':10} values = { '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10} # In[3]: def highscores(): pass # In[4]: class game_help(): ''' Rules : Dealer hits hard 17. if player wins with blackjack : 3:2 i.e if bet 1 will get 1.5 , total 2.5 if player wins : 1:1 , if bet 1 will get 1, total 2 if player draws : bet returned. If bet 1 , will get nothing. total 1 if player loses : bet lost, if bet 1, total 0 if player surrenders : 2:1 , if bet 1 will get 0.5 back . total 0.5 if player doubles down: if player splits: if player insures: ''' print('\n' * 100) print( pyfiglet.figlet_format( "Blackjack", font='slant', width=100, justify='center')) # In[5]: def card_graph(cards, hidden=None): colorama.init(autoreset=True) card_len = len(cards) if hidden is not None: print(f'::::::::::\t' * 2, end='') print('') print(f':: ::\t', end='') print(f':: {cards[1].suit}::') print(f':: ::\t' * 2, end='') print('') print(f'::HIDDEN::\t', end='') rank = cards[1].rank.rjust(2, ' ') print(f':: {rank} ::\t', end='') print('') print(f':: ::\t' * 2, end='') print('') print(f':: ::\t', end='') print(f':: {cards[1].suit}::') print(f'::::::::::\t' * 2, end='') print('') else: print(f'::::::::::\t' * card_len, end='') print('') for i in range(0, card_len): print(f':: {cards[i].suit}::\t', end='') print('') print(f':: ::\t' * card_len, end='') print('') for i in range(0, card_len): rank = cards[i].rank.rjust(2, ' ') print(f':: {rank} ::\t', end='') print('') print(f':: ::\t' * card_len, end='') print('') for i in range(0, card_len): print(f':: {cards[i].suit}::\t', end='') print('') print(f'::::::::::\t' * card_len, end='') print('') # In[6]: class Player(): ''' This class is to create a player. ''' count = 0 def __init__(self, name): self.name = name self.bank = 1000 #self.final_result = None self.blackjack = None Player.count += 1 self.id = Player.count self.bet = 0 # start bet is zero when player created. print(f'Player created.\nName : {self.name} \nBalance : ${self.bank}') self.value = 0 # value at start is zero self.cards = list() @staticmethod def get_name(): ''' This function is to get name of the player. ''' while True: try: name = str(input('Enter player\'s name : ')) if name in {''}: raise ValueError except ValueError: print(f'Do not enter blank name.') else: break return name @staticmethod def get_bank(name): ''' This function is to get the purse value of the player. ''' while True: try: bank = int(input(f'Hello {name}! Enter your purse value : $')) if bank < 100: raise ValueError except ValueError: print(f'Purse value cannot be less than $100 / alphabets / blank.') else: break return bank def get_bet(self): ''' This function is to get the amount of bet player want's to set ''' while True: try: self.bet = int( input(f'Hello {self.name}! How much would you like to bet : $')) if self.bet > self.bank or self.bet < 10: raise ValueError except ValueError: print(f'Bet value cannot be less than $10 or greater than the balance.') else: break ### Subtract the bet amount from the balance of the player ### self.bank -= self.bet print( f'Bet placed for ${self.bet} by {self.name}. New balance : ${self.bank}') def set_value(self, special=None): card_sum = sum([card.card_value() for card in self.cards]) if '1' in [card.rank for card in self.cards] and card_sum == 11: # Ace present check for blackjack condition , Note cards are objects # If ace is considered as 11, value will be 11 + 10 self.value = 21 elif '1' in [card.rank for card in self.cards] and special: max_value = max(card_sum, card_sum + 10) if max_value <= 21: self.value = max_value else: self.value = sum([card.card_value() for card in self.cards]) def display(self): print(f' {self.name.upper()}\'s CARDS :') card_graph(self.cards) print(f'{self.name} cards value : {self.value}') print('\n') def cards_clear(self): ''' This function is to clear cards and value on replay''' self.cards.clear() self.value = 0 self.blackjack = None def black_win_bet(self): self.bank += (self.bet * 2.5) # Bet + 3/2 bet def win_bet(self): self.bank += (self.bet * 2) # Bet + 1/1 bet def lose_bet(self): self.bank = self.bank def tie_bet(self): self.bank += self.bet # In[7]: class Dealer(): ''' This class is to create a dealer and store his info. ''' def __init__(self): self.value = 0 self.cards = list() self.name = 'Dealer' self.blackjack = None def set_value(self): card_sum = sum([card.card_value() for card in self.cards]) if '1' in [card.rank for card in self.cards] and card_sum == 11: # Ace present check for blackjack condition , Note cards are objects # If ace is considered as 11, value will be 11 + 10 self.value = 21 else: self.value = sum([card.card_value() for card in self.cards]) ### NOTE : Regarding dealer and ace. ### ''' When players ask dealer to stand : A hand with an ace which sums to 17 is called soft 17. Casinos differ on whether dealer hits or stands after getting to soft 17. It is to casinos advantage if dealer keeps hitting even with soft 17. Our dealer also hits even though he has soft 17. ''' def display(self, hidden=None): print(f' DEALERS\'s CARDS :') card_graph(self.cards, hidden) if hidden is None: print(f'Dealer\'s cards value : {self.value}') print('\n') def cards_clear(self): ''' This function is to clear cards and value on replay''' self.cards.clear() self.value = 0 self.blackjack = None # In[8]: class Card(): ''' This class is to create a card instance using suit and rank. ''' def __init__(self, suit, rank): self.suit = suit self.rank = rank def card_value(self): return values[self.rank] # In[9]: class Deck(): ''' This class is to create a deck of cards. ''' def __init__(self): self.deck = list() for suit in suits: for rank in ranks: self.deck.append(Card(suit, rank)) # 52 card objects created random.shuffle(self.deck) print(f'Deck created and shuffled.') def shuffle(self): ''' This function is used to shuffle the deck. ''' random.shuffle(self.deck) def draw(self): ''' This function is to draw initial card from the deck. Gamer is either players or dealer object. ''' return self.deck.pop(), self.deck.pop() # pop two cards from the deck list and return # print(len(self.deck)) #lenght for debug def hit(self): return self.deck.pop() # Pop card from the deck objects deck # # 1 player 1 dealer scenario basic # 1. first players chance # 2. if player stands then only dealer chance # 3. ace condition - done # 4. better display : show better cards, display dealers cards # 5. dealer has no option to draw until his count crosses 17 [ ace is valued accordingly ] - done # 6. store purse for replay. # 7. ace conition of dealer at first draw : needs to let player play or insure. # 8. add create py file in ipynb - done # 9. better replay looping # 10. store high score # 11. display final score # 12. PENDING : New info : Only if the first draw hits 21 its called blackjack. And blackjacks trounce even if multiple card values are summed to 21 # # ### future ### # 1. insurance # 2. split # 3. double down # 4. multiplayer # 5. multideck # 6. pygame : In future, display game using pygame library. # # ### BUG ### # after hitting and standing. even if values are same. player loses. check # # # ### cases ### # ## case 1 ## # player gets black jack on first try. # check dealers # if same WINCHECK -> PUSH # elif # # ## case 2 ## # player gets cards and chooses to hit. # # sub-case 1# # value goes over 21 [adusting ace] WINCHECK -> BUST # # sub-case 2# # user hits blackjack WINCHECK -> goto case 1 # # sub-case 3# # user chooses to stand WINCHECK -> goto case 3 # # ## case 3 ## # player gets cards and chooses to stand. # dealer reveals cards. # # sub-case 1# # dealer hits blackjack WINCHECK -> LOSE # # sub-case 2# # dealer goes over 21 WINCHECK -> WIN # # sub-case 3# # dealer goes over 17 WINCHECK -> compare values of cards -> WINCHECK -> WIN OR LOSE # # # In[10]: def graffiti(result): print('\n') print( pyfiglet.figlet_format( result.upper(), font='slant', width=100, justify='center')) print('\n') # In[11]: def printing(player, dealer, result): ''' blackjack cases case 0 : both blackjack - done case 1 : player black jack - done case 2 : dealer black jack - done case 3 : player busts - done case 4 : player hits 21, dealer blackjack - done case 5 : dealer busts - done comparison: case 6 : player hits 21 and dealer hist 21 - done case 7 : player hits 21 , dealer less - done case 8 : player higher, dealer less - done case 9 : dealer high, player less - done case 10 : player and dealer value same - done ''' if result == 0: print('\n\n') print(f'{player.name} hits BLACKJACK !') print('Checking dealer\'s cards..... ', end='') print(f'Dealer hits BLACKJACK as well !') print(f'{player.name} and dealer PUSH ! Game tie !') graffiti('push') elif result == 1: print('\n\n') print(f'{player.name} hits BLACKJACK ! {player.name} WINS ! Congratulations !') graffiti('win') elif result == 2: print('\n\n') print(f'Dealer\'s hit BLACKJACK ! {player.name} LOST !') graffiti('lost') elif result == 3: print('\n\n') print(f' {player.name} BUST ! {player.name} LOST !') graffiti('lost') elif result == 4: print('\n\n') print(f'Dealer\'s hit BLACKJACK ! {player.name} LOST !') graffiti('lost') elif result == 5: print('\n\n') print(f' Dealer BUST ! {player.name} WINS !') graffiti('win') elif result == 6 or result == 10: print('\n\n') print(f'{player.name} and dealer PUSH ! Game tie !') graffiti('push') elif result == 7 or result == 8: print('\n\n') print( f'{player.name} WINS ! {player.name}\'s cards have greater value ! Congratulations !') graffiti('win') elif result == 9: print('\n\n') print(f'{player.name} LOST ! Dealer\'s cards have greater value !') graffiti('lost') # In[12]: def blackjack_check(dealer, player): if player.value == 21 and dealer.value == 21: return 0 elif player.value == 21: return 1 elif dealer.value == 21: return 2 else: return 100 # In[13]: def top_check(dealer, player): if player.value == 21 and dealer.blackjack: return 4 elif player.value == 21: return 100 # not complete result , needs to stand # In[14]: def bust_check(dealer=None, player=None): if dealer is not None: if dealer.value > 21: return 5 elif player is not None: if player.value > 21: return 3 return 101 # In[15]: def win_check(dealer, player): if player.value == 21 and dealer.value == 21: return 6 elif player.value == 21 and dealer.value < 21: return 7 elif dealer.value < player.value: return 8 elif dealer.value > player.value: return 9 elif dealer.value == player.value: return 10 else: return 102 # impossible result, just to break while loop # This push is a tie, Not a blackjack push # In[16]: def hit_or_stand(player): hors = str(input(f'{player.name}, Do you want to hit or stand ? [H/S] :')) while hors.lower() not in {'h', 's', 'hit', 'stand'}: hors = str(input(f'{player.name}, Enter hit or stand only ? [H/S] :')) return hors.lower() # In[17]: def game(replay=None, players=None, dealer=None): ''' This function is to conduct the game. ''' ### highscores ### #highscores = [] # if os.path.exists('HIGHSCORES.txt'): # with open('HIGHSCORES.txt','r') as highscore: # for i in range(0,5): # highscores[i] = highscore.readline() # else: # with open('HIGHSCORES.txt','w') as highscore: # print('') ### Create players for the game ### if replay is None: players = list() # For supporting multiplayer in future name = Player.get_name() # Player created and appended to playes list players.append(Player(name)) ### Create a dealer for the game ### dealer = Dealer() else: # If replay remember players name and balance, but remove cards from # dealer and player players = players for player in players: player.cards_clear() dealer.cards_clear() ### Setup deck ### play_deck = Deck() print([(x.suit, x.rank) for x in play_deck.deck]) # print deck for debug ### Bet amount ### player1 = players[0] # Since currently single player game player1.get_bet() ### Draw the cards for dealer and players ### # for card in play_deck.draw(dealer): for card in play_deck.draw(): dealer.cards.append(card) dealer.set_value() # print(f'Initial dealer value {dealer.value}') # debug for card in play_deck.draw(): player1.cards.append(card) player1.set_value() # print(f'Initial player value : {player1.value}') # debug ### Display cards and values ### print('\n\n' * 100) dealer.display(hidden='x') player1.display() ##### Concept of insurance ########## ### Initial check : Only black jack #### check = blackjack_check(dealer, player1) if check == 0: player1.blackjack = dealer.blackjack = True elif check == 1: player1.blackjack = True dealer.blackjack = False elif check == 2: dealer.blackjack = True player1.blackjack = False if check in { 0, 1}: # if only player has a blackjack or both have ### end game time.sleep(2) print('\n' * 100) dealer.display() player1.display() player1.blackjack = True if check == 0: dealer.blackjack = True printing(player1, dealer, check) else: hors = None while True: if hors != 'as': hors = hit_or_stand(player1) if hors in {'h', 'hit'}: # player1.cards is a list, an atribute of player1 object player1.cards.append(play_deck.hit()) player1.set_value() print([(x.rank, x.suit) for x in player1.cards]) # debug print(player1.value) # debug dealer.display(hidden='x') player1.display() # check if player1 is bust # check will be 3 if player busts check = bust_check(player=player1) if check == 3: break check = top_check(dealer, player1) if check == 4: # player hits 21 and dealer hits blackjack break elif check == 100: # player hits 21 , needs to auto stand. hors = 'as' elif hors in {'s', 'stand', 'as'}: if dealer.blackjack: check = 2 # dealer blackjack restore dealer.display() player.display() break ### Special ace case ### ## If player has ace in his cards, sum of cmp(soft,hard) must be taken ## # EX : player 1,7 dealer 7,9 player1.set_value(special=True) while dealer.value < 17: dealer.cards.append(play_deck.hit()) dealer.set_value() print(dealer.value) # debug print(player1.value) # debug print('\n' * 50) dealer.display() player1.display() time.sleep(2) print('\n' * 50) dealer.display() player1.display() time.sleep(2) # check if dealer is bust check = bust_check(dealer=dealer) if check == 5: break check = win_check(dealer, player1) print(f'last check : {check}') if check != 102: break printing(player1, dealer, check) ### Bank update ### if check in {0, 6, 10}: player1.tie_bet() elif check in {2, 3, 4, 9}: player1.lose_bet() elif check in {5, 7, 8}: player1.win_bet() else: player1.black_win_bet() return players, dealer # for replay # In[18]: def main(): ''' This function controls everything ''' ### Welcome ### print('Welcome to BLACKJACK.') print('\n') # game_help() ### Start ### while True: print('Are you ready to play the game ? : [Y/N] ') try: start = str(input()).lower() if start not in {'y', 'n', 'yes', 'no'}: raise ValueError except ValueError: print('Enter either Y or N.') else: if start in {'y', 'Y'}: print('\n\n' * 100) players, dealer = game() #### If bank goes below 10 should not allow to play ### player1 = players[0] if player1.bank <= 10: print('Bank balance is below the minimum of $10 required') else: while True: # Replay Loop ### TRY CATCH rmaining ### print('\n') print( f'Player score : \nName : {player1.name} \nBalance : ${player1.bank}') print('\n') replay = str( input('Play once again ? : [Y/N] ')).lower() if replay in {'y', 'yes'}: players, dealer = game( replay=replay, players=players, dealer=dealer) else: start = 'n' print('\n') print( f'Final score : \nName : {player1.name} \nBalance : ${player1.bank}') print('\n') # with open('HIGHSCORES.txt','w') as highscore: # for i in highscores: # highscore.writeline(i) break else: print('Bye. Have a nice day !!!') break # In[ ]: try: terminal = get_ipython().__class__.__name__ except Exception: pass else: if get_ipython().__class__.__name__ == 'ZMQInteractiveShell': get_ipython().system('jupyter nbconvert --to python black_jack.ipynb') get_ipython().system('pylint black_jack.py') get_ipython().system('autopep8 --in-place --aggressive black_jack.py') get_ipython().system('pylint black_jack.py ') finally: if __name__ == "__main__": main() <file_sep>/blackjack.py #!/usr/bin/env python # coding: utf-8 # # Future releases: # 1. Better highscore handling by using csv or pandas - done # 2. Better replay looping, code optimization # 3. Use pygame for displaying game # 4. Nano editor like options for hit stand # 5. Better clear screen - done # 6. Add colors - done # 7. Add better fonts for cards as well as text. # 8. merge surrender option in H or S question as "surrender" # # ### gameplay : # 0. surrender - done # 1. insurance # 2. split # 3. double down # 4. multiplayer # 5. multideck # # # In[1]: import os # To clear screen and check file import random # Random selection import pyfiglet # Graffiti and ascii art import time # Sleep import pandas as pd # Highscores csv from termcolor import colored # Colour from colorama import init # Used to initiate teminal for color # In[2]: #ranks = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King') ranks = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') #suits = ('Spade', 'Clover', 'Diamond', 'Heart') suits = ('S', 'C', 'D', 'H') #values = {'1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'Jack':10, 'Queen':10, 'King':10} values = { '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10} space = '\t\t\t\t ' spacec = '\t\t' # for cards # In[3]: def clearscreen(): ''' This function is to clear screen. ''' if os.name == 'nt': os.system('cls') else: os.system('clear') # In[4]: class game_help(): ''' This function is to display logo as well as help. Help is yet to be configured. Rules : Dealer hits hard 17. if player wins with blackjack : 3:2 i.e if bet 1 will get 1.5 , total 2.5 if player wins : 1:1 , if bet 1 will get 1, total 2 if player draws : bet returned. If bet 1 , will get nothing. total 1 if player loses : bet lost, if bet 1, total 0 if player surrenders : 2:1 , if bet 1 will get 0.5 back . total 0.5 if player doubles down: if player splits: if player insures: ''' # print('\n'*100) clearscreen() print('\n' * 3) print( pyfiglet.figlet_format( "Blackjack", font='slant', width=100, justify='center')) # In[5]: def card_graph(cards, hidden=None): ''' This function draws the cards when displayed. ''' card_len = len(cards) init(autoreset=True) if hidden is not None: print( f'{spacec}{colored("::::::::::", color="white", on_color="on_blue")}' * 2, end='') print('') print( f'{spacec}{colored(":: ::", color="white", on_color="on_blue")}', end='') print( f'{spacec}{colored(f":: {cards[1].suit}::", color="white", on_color="on_blue")}') print( f'{spacec}{colored(":: ::", color="white", on_color="on_blue")}' * 2, end='') print('') print( f'{spacec}{colored("::HIDDEN::", color="white", on_color="on_blue")}', end='') rank = cards[1].rank.rjust(2, ' ') print( f'{spacec}{colored(f":: {rank} ::", color="white", on_color="on_blue")}', end='') print('') print( f'{spacec}{colored(":: ::", color="white", on_color="on_blue")}' * 2, end='') print('') print( f'{spacec}{colored(":: ::", color="white", on_color="on_blue")}', end='') print( f'{spacec}{colored(f":: {cards[1].suit}::", color="white", on_color="on_blue")}') print( f'{spacec}{colored("::::::::::", color="white", on_color="on_blue")}' * 2, end='') print('') else: print( f'{spacec}{colored("::::::::::", color="white", on_color="on_blue")}' * card_len, end='') print('') for i in range(0, card_len): print( f'{spacec}{colored(f":: {cards[i].suit}::", color="white", on_color="on_blue")}', end='') print('') print( f'{spacec}{colored(":: ::", color="white", on_color="on_blue")}' * card_len, end='') print('') for i in range(0, card_len): rank = cards[i].rank.rjust(2, ' ') print( f'{spacec}{colored(f":: {rank} ::", color="white", on_color="on_blue")}', end='') print('') print( f'{spacec}{colored(":: ::", color="white", on_color="on_blue")}' * card_len, end='') print('') for i in range(0, card_len): print( f'{spacec}{colored(f":: {cards[i].suit}::", color="white", on_color="on_blue")}', end='') print('') print( f'{spacec}{colored("::::::::::", color="white", on_color="on_blue")}' * card_len, end='') print('') # In[6]: class Player(): ''' This class is to create a player and associated functions. ''' count = 0 def __init__(self, name): self.name = name self.bank = 1000 #self.final_result = None self.blackjack = None Player.count += 1 self.id = Player.count self.bet = 0 # start bet is zero when player created. print( f'{space}Player created.\n{space}Name : {self.name} \n{space}Balance : ${self.bank}') self.value = 0 # value at start is zero self.cards = list() @staticmethod def get_name(): ''' This function is to get name of the player. ''' while True: try: name = str(input(f'{space}Enter player\'s name : ')) if name in {''}: raise ValueError if name.lower() == 'dealer': print(f'{space}Player\'s name cannot be dealer!!') continue except ValueError: print(f'{space}Player\'s name cannot be blank !!') else: break return name # @staticmethod # def get_bank(name): # # ''' This function is to get the purse value of the player. ''' # while True: # try: # bank = int(input(f'{space}Hello {name}! Enter your purse value : $')) # if bank < 100 : # raise ValueError # except ValueError: # print(f'{space}Purse value cannot be less than $100 / alphabets / blank.') # else: # break # # return bank def get_bet(self): ''' This function is to get the amount of bet player want's to set. ''' while True: try: self.bet = int( float( input(f'{space}Hello {self.name}! How much would you like to bet : $'))) if self.bet > self.bank or self.bet < 10: raise ValueError except ValueError: print( f'{space}Bet value cannot be less than $10 or greater than the balance.') else: break ### Subtract the bet amount from the balance of the player ### self.bank -= self.bet print( f'{space}Bet placed for ${self.bet} by {self.name}. New balance : ${self.bank}') def set_value(self, special=None): ''' This function is to set value of player's cards as per the condition. ''' card_sum = sum([card.card_value() for card in self.cards]) if '1' in [card.rank for card in self.cards] and card_sum == 11: # Ace present check for blackjack condition , Note cards are objects # If ace is considered as 11, value will be 11 + 10 self.value = 21 elif '1' in [card.rank for card in self.cards] and special: max_value = max(card_sum, card_sum + 10) if max_value <= 21: self.value = max_value else: self.value = sum([card.card_value() for card in self.cards]) def display(self): ''' This function is to display player's cards. ''' print(f'{space} {self.name.upper()}\'s CARDS :\n') card_graph(self.cards) ### display soft hand ### soft_hand = None card_sum = sum([card.card_value() for card in self.cards]) if '1' in [card.rank for card in self.cards]: if card_sum + 10 <= 21: soft_hand = card_sum + 10 else: soft_hand = None if soft_hand is None or self.value == soft_hand: print('\n') print(f'{space}{self.name}\'s cards value : {self.value}') else: print('\n') print(f'{space}{self.name}\'s cards value : {self.value} or {soft_hand} ') print('\n') def cards_clear(self): ''' This function is to clear cards and value on replay. ''' self.cards.clear() self.value = 0 self.blackjack = None def black_win_bet(self): ''' This function is to set bank if player wins by blackjack. ''' self.bank += (self.bet * 2.5) # Bet + 3/2 bet def win_bet(self): ''' This function is to set bank if player wins. ''' self.bank += (self.bet * 2) # Bet + 1/1 bet def lose_bet(self): ''' This function is to set bank if player loses. ''' self.bank = self.bank def tie_bet(self): ''' This function is to set bank if player ties. ''' self.bank += self.bet def surrender_bet(self): ''' This function is to set bank if player surrenders. ''' self.bank += (self.bet * 0.5) # 1/2 Bet def insure_bet(self, outcome): pass # In[7]: class Dealer(): ''' This class is to create a dealer and store his info. ''' def __init__(self): self.value = 0 self.cards = list() self.name = 'Dealer' self.blackjack = None def set_value(self): ''' This function is to set value of cards for the dealer as per the condition. ''' card_sum = sum([card.card_value() for card in self.cards]) if '1' in [card.rank for card in self.cards] and card_sum == 11: # Ace present check for blackjack condition , Note cards are objects # If ace is considered as 11, value will be 11 + 10 self.value = 21 else: self.value = sum([card.card_value() for card in self.cards]) ### NOTE : Regarding dealer and ace. ### ''' When players ask dealer to stand : A hand with an ace which sums to 17 is called soft 17. Casinos differ on whether dealer hits or stands after getting to soft 17. It is to casinos advantage if dealer keeps hitting even with soft 17. Our dealer also hits even though he has soft 17. ''' def display(self, hidden=None): ''' This function displays dealer's cards ''' print(f'{space} DEALERS\'s CARDS :\n') card_graph(self.cards, hidden) if hidden is None: print('\n') print(f'{space}Dealer\'s cards value : {self.value}') print('\n') def cards_clear(self): ''' This function is to clear cards and value on replay''' self.cards.clear() self.value = 0 self.blackjack = None # In[8]: class Card(): ''' This class is to create a card instance using suit and rank. ''' def __init__(self, suit, rank): self.suit = suit self.rank = rank def card_value(self): ''' This function returns the value of a card. ''' return values[self.rank] # In[9]: class Deck(): ''' This class is to create a deck of cards. ''' def __init__(self): self.deck = list() for suit in suits: for rank in ranks: self.deck.append(Card(suit, rank)) # 52 card objects created random.shuffle(self.deck) print(f'{space}Deck created and shuffled.') def shuffle(self): ''' This function is used to shuffle the deck. ''' random.shuffle(self.deck) def draw(self): ''' This function is to draw initial card from the deck. Gamer is either players or dealer object. ''' return self.deck.pop(), self.deck.pop() # pop two cards from the deck list and return def hit(self): ''' This function is to hit the deck. ''' return self.deck.pop() # Pop card from the deck objects deck # In[10]: def graffiti(result): ''' This function is to draw graffiti at the start and end of game. ''' print('\n') print( pyfiglet.figlet_format( result.upper(), font='slant', width=100, justify='center')) # print('\n') # In[11]: def cases(player, dealer, result): ''' This function receives input check result and declares the result as per check case. blackjack cases case 0 : both blackjack - done case 1 : player black jack - done case 2 : dealer black jack - done case 3 : player busts - done case 4 : player hits 21, dealer blackjack - done case 5 : dealer busts - done comparison: case 6 : player hits 21 and dealer hist 21 - done case 7 : player hits 21 , dealer less - done case 8 : player higher, dealer less - done case 9 : dealer high, player less - done case 10 : player and dealer value same - done ''' if result == 0: print('\n\n') print(f'{space}{player.name} hits BLACKJACK !') print(f'{space}Checking dealer\'s cards..... ', end='') print(f'{space}Dealer hits BLACKJACK as well !') print(f'{space}{player.name} and dealer PUSH ! Game tie !') graffiti('push') elif result == 1: print('\n\n') print( f'{space}{player.name} hits BLACKJACK ! {player.name} WINS ! Congratulations !') graffiti('win') elif result == 2: print('\n\n') print(f'{space}Dealer\'s hit BLACKJACK ! {player.name} LOST !') graffiti('lost') elif result == 3: print('\n\n') print(f'{space}{player.name} BUST ! {player.name} LOST !') graffiti('lost') elif result == 4: print('\n\n') print(f'{space}Dealer\'s hit BLACKJACK ! {player.name} LOST !') graffiti('lost') elif result == 5: print('\n\n') print(f'{space}Dealer BUST ! {player.name} WINS !') graffiti('win') elif result == 6 or result == 10: print('\n\n') print(f'{space}{player.name} and dealer PUSH ! Game tie !') graffiti('push') elif result == 7 or result == 8: print('\n\n') print( f'{space}{player.name} WINS ! {player.name}\'s cards have greater value ! Congratulations !') graffiti('win') elif result == 9: print('\n\n') print(f'{space}{player.name} LOST ! Dealer\'s cards have greater value !') graffiti('lost') elif result == 11: print('\n\n') print(f'{space}{player.name} SURRENDERED !!') graffiti('surrender') # In[12]: def blackjack_check(dealer, player): ''' This function is to check blackjack condition. ''' if player.value == 21 and dealer.value == 21: return 0 elif player.value == 21: return 1 elif dealer.value == 21: return 2 else: return 100 # In[13]: def top_check(dealer, player): ''' This function is to check special case where player has 21 but dealer has blackjack. ''' if player.value == 21 and dealer.blackjack: return 4 elif player.value == 21: return 100 # not complete result , needs to stand # In[14]: def bust_check(dealer=None, player=None): ''' This function is to check the bust condition. ''' if dealer is not None: if dealer.value > 21: return 5 elif player is not None: if player.value > 21: return 3 return 101 # In[15]: def win_check(dealer, player): ''' This function is to check who wins in case there is no blackjack or bust. ''' if player.value == 21 and dealer.value == 21: return 6 elif player.value == 21 and dealer.value < 21: return 7 elif dealer.value < player.value: return 8 elif dealer.value > player.value: return 9 elif dealer.value == player.value: return 10 else: return 102 # impossible result, just to break while loop # This push is a tie, Not a blackjack push # In[16]: def surrender_check(dealer, player): surr = surrender_or_play(player) check, hors = None, None if surr in {'s', 'surrender'}: print(f'{space}Checking if dealer has a blackjack.....\n') if dealer.blackjack: print(f'{space}Cannot surrender, dealer has a BLACKJACK ! ') check = 2 hors = 'as' # Auto Stand else: check = 11 hors = None return check, hors # In[17]: def hit_or_stand(player): ''' This function is to check users choice regarding hit or stand. ''' hors = str( input(f'{space}{player.name}, Do you want to hit or stand ? [H/S] : ')).lower() while hors not in {'h', 's', 'hit', 'stand'}: hors = str( input(f'{space}{player.name}, Enter hit or stand only ? [H/S] : ')).lower() return hors # In[18]: def surrender_or_play(player): surr = str(input( f'{space}{player.name}, Do you want to surrender or play ? [S/P] : ')).lower() while surr not in {'p', 's', 'play', 'surrender'}: surr = str( input(f'{space}{player.name}, Enter surrender or play ? [S/P] : ')).lower() return surr # In[19]: def display_cards(dealer, player, hidden=None): ''' This function is to display cards. ''' clearscreen() # changed print('\n' * 3) dealer.display(hidden=hidden) player.display() # In[20]: class Highscores(): ''' This class is a collection of methods to handle highscores. ''' @staticmethod def load_highscores(): ''' This function is to load highscores once the game starts. ''' if os.path.exists('scoresdb'): highscores = pd.read_csv('scoresdb') else: highscores = pd.DataFrame(columns=['Rank', 'Name', 'Score']) return highscores @staticmethod def update_highscores(highscores, player): ''' This function is to update the highscore as well as store it. ''' ### Add score to highscores ### highscores.loc[len(highscores)] = [None, player.name, player.bank] highscores['Score'] = highscores['Score'].apply(int) ### Sort the highscores ### highscores.sort_values( by='Score', ascending=False, inplace=True, ignore_index=True) ### Update rank according index ### highscores['Rank'] = list(range(1, len(highscores) + 1)) highscores = highscores.head(10) ### Update scoresdb file ### highscores.to_csv('scoresdb', index=False) return highscores @staticmethod def display_highscores(highscores): ''' This function is to display the highscores after game ends. ''' print(f'{space} \t HIGHSCORES : \t \n') for row in highscores.to_string(index=False).split('\n'): print(space + row) # In[21]: def game(replay=None, players=None, dealer=None): ''' This function is to conduct the game. ''' ### Create players for the game ### if replay is None: players = list() # For supporting multiplayer in future name = Player.get_name() # Player created and appended to playes list players.append(Player(name)) ### Create a dealer for the game ### dealer = Dealer() else: ### Remember players if replay and clear cards ### players = players for player in players: player.cards_clear() dealer.cards_clear() ### Setup deck ### play_deck = Deck() ### Bet amount ### player1 = players[0] # Since currently single player game player1.get_bet() ### Draw the cards for dealer and players ### for card in play_deck.draw(): dealer.cards.append(card) dealer.set_value() for card in play_deck.draw(): player1.cards.append(card) player1.set_value() ### Display cards and values ### display_cards(dealer, player1, hidden='x') ##### PENDING : Concept of insurance ########## ### Initial check : Only black jack #### check = blackjack_check(dealer, player1) if check == 0: player1.blackjack = dealer.blackjack = True elif check == 1: player1.blackjack = True dealer.blackjack = False elif check == 2: dealer.blackjack = True player1.blackjack = False ### Player has a blackjack or both have. Game end. ### if check in {0, 1}: time.sleep(2) display_cards(dealer, player1) cases(player1, dealer, check) ### Dealer has a blackjack or no one has. Game continue. ### else: ### Allow player to surrender if dealer does not have a blackjack ### check, hors = surrender_check(dealer, player1) while True: ### Surrendered ### if check == 11: display_cards(dealer, player1) break ### Auto stand if player reaches 21 else ask ### if hors != 'as': hors = hit_or_stand(player1) ### Player Hits ### if hors in {'h', 'hit'}: # player1.cards is a list, an atribute of player1 object player1.cards.append(play_deck.hit()) player1.set_value() display_cards(dealer, player1, hidden='x') # check if player1 is bust # check will be 3 if player busts check = bust_check(player=player1) if check == 3: break check = top_check(dealer, player1) if check == 4: # player hits 21 and dealer hits blackjack break elif check == 100: # player hits 21 , needs to auto stand. hors = 'as' ### Player stands ### elif hors in {'s', 'stand', 'as'}: if dealer.blackjack: check = 2 # dealer blackjack restore display_cards(dealer, player1) break ### Special ace case ### ### If player has ace in his cards, sum of cmp(soft,hard) must be taken ### ### EX : player 1,7 dealer 7,9 ### player1.set_value(special=True) while dealer.value < 17: dealer.cards.append(play_deck.hit()) dealer.set_value() display_cards(dealer, player1) time.sleep(1) display_cards(dealer, player1) # check if dealer is bust check = bust_check(dealer=dealer) if check == 5: break check = win_check(dealer, player1) # comparison check if check != 102: break cases(player1, dealer, check) ### Bank update ### if check in {0, 6, 10}: player1.tie_bet() elif check in {2, 3, 4, 9}: player1.lose_bet() elif check in {5, 7, 8}: player1.win_bet() elif check in {11}: player1.surrender_bet() else: player1.black_win_bet() return players, dealer # for replay # In[22]: def main(): ''' This function controls everything ''' ### Welcome ### print(f'{space}Welcome to BLACKJACK.') print('\n') # game_help() H = Highscores() ### Load highscores ### highscores = H.load_highscores() ### Start ### while True: print(f'{space}Are you ready to play the game ? : [Y/N] ', end='') try: start = str(input()).lower() if start not in {'y', 'n', 'yes', 'no'}: raise ValueError except ValueError: print(f'{space}Enter either Y or N.') else: if start in {'y', 'Y'}: clearscreen() # changed #100 print('\n' * 3) players, dealer = game() while True: # Replay Loop ### TRY CATCH rmaining ### player1 = players[0] print('\n') print( f'{space}Player score : \n{space}Name : {player1.name} \n{space}Balance : ${player1.bank}') print('\n') ### If bank goes below 10 should not allow to play ### if player1.bank <= 10: print( f'{space}Bank balance is below the minimum of $10 required') break ### Else ask for replay #### replay = str( input(f'{space}Play once again ? : [Y/N] ')).lower() if replay in {'y', 'yes'}: players, dealer = game( replay=replay, players=players, dealer=dealer) elif replay in {'n', 'no'}: start = 'n' print('\n') print( f'{space}Final score : \n{space}Name : {player1.name} \n{space}Balance : ${player1.bank}') print('\n') ### Update and Display highscores ### highscores = H.update_highscores(highscores, player1) time.sleep(1) clearscreen() # changed print('\n' * 3) print( pyfiglet.figlet_format( 'GoodBye', font='slant', width=100, justify='center')) print('\n' * 3) H.display_highscores(highscores) print('\n' * 3) break else: continue else: print(f'{space}Bye. Have a nice day !!!') break # In[ ]: try: terminal = get_ipython().__class__.__name__ except Exception: pass else: if get_ipython().__class__.__name__ == 'ZMQInteractiveShell': get_ipython().system('jupyter nbconvert --to python blackjack.ipynb') get_ipython().system('pylint blackjack.py') get_ipython().system('autopep8 --in-place --aggressive blackjack.py') get_ipython().system('pylint blackjack.py ') finally: if __name__ == "__main__": main() <file_sep>/README.md # Blackjack Blackjack game. This is the Blackjack game with only basic gameplay including hit and stand. It currently does not support other moves like insurance,double down or split etc or multiple players. Created as an assignment for Udemy course "Complete Python Bootcamp" for Milestone-2 project.
1c41108791235b9f80a1ea6e458543735347a492
[ "Markdown", "Python" ]
3
Python
aarohan01/Blackjack
cc141adb3067c21a9dbb5b38d53b4ddf1cba999d
a0709adae1a7ba0667cdc74bee653c19c4309b2b
refs/heads/main
<repo_name>alx/nlp_epub_entity_similarities<file_sep>/epub_entity_similarity.py import glob from tqdm import tqdm import ebooklib from bs4 import BeautifulSoup from ebooklib import epub import spacy import networkx as nx MAX_DISTANCE = 150 EPUB_PATH = './sink/' EPUB_GLOB_PATTERN = '*.epub' FILTERED_ENT_LABELS = ["PERSON", "ORG"] OUTPUT_GRAPH_FILEPATH = "./graph.gexf" BOOK_LIST = [] SIMILARITY_THRESHOLD = 0.98 G = nx.Graph() nlp=spacy.load('en_core_web_md') def main(): fetch_books() process_books() process_graph() save_graph() def fetch_books(path=EPUB_PATH, pattern=EPUB_GLOB_PATTERN, books=BOOK_LIST): for filename in glob.glob("{}{}".format(path, pattern)): try: print("--") print("fetch {}".format(filename)) books.append(epub.read_epub(filename)) except: print("error with this epub") pass def process_books(books=BOOK_LIST): for book in books: book_to_entities(book) def process_graph(): nodes = list(G.nodes(data=True)) print("Process graph - {} nodes".format(len(nodes))) before_filter_count = len(nodes) for (n, d) in nodes: # remove nodes with weight == 1 if 'weight' in d and d['weight'] == 1: G.remove_node(n) print("\t- {} removed".format(before_filter_count - len(G.nodes))) nodes = list(G.nodes(data=True)) before_merge_count = len(nodes) for index, (n1, d1) in enumerate(nodes): for (n2, d2) in nodes[(index + 1):]: try: similarity = d1['token'].similarity(d2['token']) if similarity > SIMILARITY_THRESHOLD: nx.contracted_nodes(G, n1, n2, True, False) except: pass print("\t- {} similar nodes merges".format(before_merge_count - len(G.nodes))) def save_graph(graph=G, filepath=OUTPUT_GRAPH_FILEPATH): for (n,d) in G.nodes(data=True): # delete nlp token attributes if "token" in d: del d["token"] print(d) # delete sub-node contractions if "contraction" in d: # append contraction weight to root node for key in d["contraction"]: if 'weight' in d["contraction"][key]: d['weight'] += d["contraction"][key]['weight'] del d["contraction"] nx.write_gexf(G, filepath) def book_to_entities(book): items = book.get_items() with tqdm(total=len(list(items))) as pbar: for item in book.items: if item.get_type() == ebooklib.ITEM_DOCUMENT: soup = BeautifulSoup(item.get_content(), features="lxml") doc=nlp(soup.get_text()) previous_ent = None for ent in [ent for ent in doc.ents if ent.label_ in FILTERED_ENT_LABELS]: if len(ent.text) > 0: graph_add_node(ent.text, G, ent.label_) if previous_ent: distance = ent.start - previous_ent.end if distance < MAX_DISTANCE: graph_add_edge(ent.text, previous_ent.text, G) previous_ent = ent pbar.update(1) def graph_add_node(label, g, t): try: node_labels = [d for (n, d) in g.nodes.data('label')] node_id = node_labels.index(label) g.nodes["n_{}".format(node_id)]['weight']+=1 except: g.add_node( "n_{}".format(len(g.nodes) + 1), label=label, weight=1, type=t, token= nlp("_".join(label.splitlines())) ) def graph_add_edge(label_node_1, label_node_2, g): node_labels = [d for (n, d) in g.nodes.data('label')] node_index_1 = node_labels.index(label_node_1) node_index_2 = node_labels.index(label_node_2) if node_index_1 < node_index_2: n1 = "n_{}".format(node_index_1) n2 = "n_{}".format(node_index_2) else: n1 = "n_{}".format(node_index_2) n2 = "n_{}".format(node_index_1) if g.has_edge(n1, n2): g[n1][n2]['weight']+=1 else: g.add_edge(n1,n2) g[n1][n2]['weight']=1 main() <file_sep>/requirements.txt beautifulsoup4==4.9.3 blis==0.7.4 bs4==0.0.1 catalogue==1.0.0 certifi==2020.12.5 chardet==4.0.0 cymem==2.0.5 decorator==4.4.2 EbookLib==0.17.1 en-core-web-md==2.3.1 en-core-web-sm==2.3.1 idna==2.10 importlib-metadata==3.3.0 lxml==4.6.2 murmurhash==1.0.5 networkx==2.5 numpy==1.19.4 plac==1.1.3 preshed==3.0.5 requests==2.25.1 six==1.15.0 soupsieve==2.1 spacy==2.3.5 srsly==1.0.5 thinc==7.4.5 tqdm==4.54.1 typing-extensions==3.7.4.3 urllib3==1.26.2 wasabi==0.8.0 zipp==3.4.0 <file_sep>/README.md # Epub Entity similarity to gexf Build graph based on nlp entities found in multiple epub files. ![Screenshot](screenshot.png?raw=true "Screenshot") ## Requirements ``` sh git clone https://github.com/alx/epub_entity_similarity.git cd epub_entity_similarity source bin/activate pip install -r requirements.txt ``` # Usage ``` sh # Copy epub files in ./sink/ python epub_entity_similarity.py # open graph.gexf with gephi - https://gephi.org/users/download/ ```
bbd8157df530114a1afb1cf19253f507ba883332
[ "Markdown", "Python", "Text" ]
3
Python
alx/nlp_epub_entity_similarities
ff66c957d76867918f60aeb55c2f259928a490ef
73a70cd4b740fadb6f670877a1500279d3d67bdb
refs/heads/master
<repo_name>rohaima/MyApp<file_sep>/src/components/App.jsx import React,{Component} from 'react'; import { Route } from 'react-router-dom'; import Nav from './Nav'; import Home from './Home'; import Blogs from './Blogs'; import Testimonials from './Testimonials'; import ContactUs from './Contactus'; import Contact from './Contact'; import Something from './somthing' import {data} from './data' class App extends Component{ state={ data:data } render(){ console.log(this.state.data) return (<div className="app"> <Nav/> <Route exact path="/" component={Home}/> <Route path="/blogs" render={()=>{ return(<Blogs blog={this.state.data.blog}/>) }}/> <Something/> <Route path="/testimonials" component={Testimonials}/> <Route path="/contact" render={()=>{return(<Contact cons={this.state.data.contacts}/>)}}/> <ContactUs/> </div>) } } export default App; // class App extends Component{ // // arr=[{name:"ahmad",age:20,education:"computer-science"}, // // {name:"sohaib",age:21,education:"Fine arts"}, // // {name:"hassan",age:22,education:"engeenering"}]; // render(){ // let arr=[1,2,3,4,5]; // var response = arr.map((i)=>{ // return <li key={i}>{i}</li> // }) // // var response = this.arr.map((i)=>{ // // return <ul key={i.age}> // // <li>{i.name} </li> // // <li>{i.age} </li> // // <li>{i.education} </li> // // <hr/> // // </ul> // // }) // // var result=arr.map(function(i){ // // return <li key={i}> // // {i}*2</li> // // }) // return(<div className="app"> // <div><ul>{response}</ul></div> // </div>) // }; <file_sep>/src/components/header.jsx import React,{Component} from 'react'; import AOS from 'aos'; export default class Header extends Component{ slider=[{ image:"./images/bg-slide12.jpg", para:"Welcome To", heading:"NaNoVi Hotel", button:"Book Now" }, { image:"./images/bg-slide1.jpg", para:"Welcome To", heading:"NaNoVi Hotel Here", button:"Book Now" }]; render(){ AOS.init(); var response= this.slider.map(function(index,i){ return(<div className="header-slider1" key={i}> <img src={index.image}/> <div className="header-info"> <p data-aos="fade-up">{index.para}</p> <h1 data-aos="fade-right" data-aos-offset="150">{index.heading}</h1> <button data-aos="fade-down" data-aos-offset="300">{index.button}</button> </div> </div>) }) return(<div> <div className="header section"> {response} </div> </div>) } }<file_sep>/src/components/BestRooms.jsx import React,{Component} from 'react'; import AOS from 'aos'; export default class BestRooms extends Component{ state={ data:[{url:"./images/room1.jpg", deals:"Single Bed Room", price:"$119.96" }, { url:"./images/room4.jpg", deals:"Double Small Room", price:"$97.44" }, { url:"./images/room3.jpg", deals:"Double Bed Luxury Room", price:"$65.76"} ]} render(){ AOS.init(); var response=this.state.data.map((index, i)=>{ return( <div key={i} className="room-deal1 div" data-aos="zoom-in-down"> <div className="room-deal-pic"> <img src={index.url} alt=""/> </div> <h3>{index.deals} <span>{index.price}</span></h3> </div>) }) return(<div className="rooms"> <h1>Best Rooms</h1> <div className="verticle"> </div> <div className="room-deals"> {response} </div> </div>) } }<file_sep>/src/components/data.js export let data={ contacts:[{ contact:{ icon:"fas fa-home", heading:"Address", mobile:"Roeterseiland Campus Building E, 10th floor Amsterdam" }, },{ contact:{ icon:"fas fa-mobile-alt", heading:"Phone", mobile:"(1200)-0989-568-331" }},{ contact:{ icon:"far fa-envelope", heading:"E-mail", mobile:"<EMAIL>" }}, ] ,blog:[{ img:"./images/blog1.jpg", dateDiv:{ date:"23-10-2018" }, heading:"Travel with your loved ones", para:"Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum", button:"Read More" }, { img:"./images/blog2.jpg", dateDiv:{ date:"15-2-2017" }, heading:"Find a good Hotel", para:"Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum", button:"Read More" }, { img:"./images/blog3.jpg", dateDiv:{ date:"05-1-2019" }, heading:"Feel The Love of Nature", para:"Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum", button:"Read More" }, { img:"./images/blog2.jpg", dateDiv:{ date:"15-2-2017" }, heading:"Find a good Hotel", para:"Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum", button:"Read More" }, { img:"./images/blog3.jpg", dateDiv:{ date:"05-1-2019" }, heading:"Feel The Love of Nature", para:"Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum Lorum ispum", button:"Read More" }] }<file_sep>/src/components/Nav.jsx import React,{Component} from 'react'; import {Link} from 'react-router-dom'; class Nav extends Component{ state={ navbar:[ { to:"/", listItem:"Home" }, { to:"/", listItem:"Features" }, { to:"/testimonials", listItem:"Testimonials" }, { to:"/blogs", listItem:"Blogs" }, { to:"/contact", listItem:"Contact" }], headbar:[{ class:"", icon:"fas fa-phone", info:"0900-000-5858" }, { class:"middle-li", icon:"fas fa-map-marker-alt", info:"Street Address Here" }, { class:"", icon:"fas fa-power-off", info:" Login/Register" }, ] } render(){ var response=this.state.navbar.map( (index,i)=>{ return( <li key={i}> <Link to={index.to} className="link">{index.listItem}</Link> </li> ) } ) var headbar=this.state.headbar.map( (index,i)=>{ return( <li key={i} className={index.class}> <i className={index.icon}></i> &nbsp; &nbsp;<p>{index.info}</p> </li> )} ) return(<div className="nav"> <div className="header-bar"> <ul> {headbar} </ul> </div> <div className="menu-bar"> <div className="logo"><img src="./images/logo.png"/></div> <ul> {response} </ul> </div> </div>) } } export default Nav;<file_sep>/src/components/Contactus.jsx import React, {Component} from 'react'; export default class Contact extends Component{ render(){ return( <section class="contact"> <div class="container"> <div class="text-center"> <div class="title">Contact Us</div> <h1 class="sub-title" style={{color: "#fff"}}>Get In Touch</h1> <div class="des-title"> <p>Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. <br/>Done ullamcorper nulla non metus auctor fringilla.</p> </div> </div> <div class="row"> <div class="row-1 rows"> <h3 class="row-item" style={{color: "#fff"}}>Details Address</h3><br/> <p>Roeterseiland Campus Building E, 10th floor Amsterdam</p> <p>Monday to Friday : 9am to 8pm</p> <p style={{color:"#c5a46d"}}><EMAIL></p> <p style={{color:"#c5a46d"}}>(1200)-0989-568-331</p> </div> <div class="row-2 rows"> <h3 class="row-item" style={{color: "#fff"}}>Our Mission</h3><br/> <p>Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p> <br/><p style={{color:"#c5a46d"}}>Read More</p> </div> <div class="row-3 rows"> <h3 class="row-item" style={{color: "#fff"}}>Our History</h3><br/> <p>Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p> <p style={{color:"#c5a46d"}}>Read More</p> </div> </div> </div> <div class="get-contact"> All right reserved &copy; </div> </section>) } }<file_sep>/src/components/Home.jsx import React,{Component} from 'react'; import Header from './header'; import Availability from './availability'; import AboutMain from './About_main'; import BestRooms from './BestRooms'; import SpecialOffer from './SpecialRoom'; import Services from './Services'; export default class Home extends Component{ render(){ return(<div> <Header/> <Availability/> <AboutMain/> <BestRooms/> <SpecialOffer/> <Services/> </div>) } }<file_sep>/src/components/Testimonials.jsx import React,{Component} from 'react'; class Testimonials extends Component{ render(){ return(<div className="testimonials"> <h1 className="heading">Testimonials</h1> <div className="comments"> <div className="testimonials-title"> <p>What our clients says about us</p> </div> <div className="testimonials-group"> <div className="left-arrow"> <i className="fa fa-chevron-left"></i> </div> <div className="testimonials-main"> <div className="testimonials-item"> <div className="image-circle"> <img src="./images/t1.jpg"/> </div> <div className="testimonials-text"> <p style={{color:"#222"}}>Lorum ispum dolor sit amet, Lorum ispum dolor sit amet, Lorum ispum dolor sit amet, Lorum ispum dolor sit ametLorum ispum dolor sit amet, Lorum ispum dolor sit amet, Lorum ispum dolor sit amet, Lorum ispum dolor sit ametLorum ispum dolor sit amet, Lorum ispum dolor sit amet, Lorum ispum dolor sit amet, Lorum ispum dolor sit amet</p> </div> </div> </div> <div className="right-arrow"> <i className="fa fa-chevron-right"></i> </div> </div> <div className="testimonials-circle"> <div className="circles-center"> <span className="circle"></span> <span className="circle"></span> <span className="circle"></span> </div> </div> </div> </div>) } } export default Testimonials;<file_sep>/src/components/SpecialRoom.jsx import React,{Component} from 'react'; import AOS from 'aos'; export default class SpecialOffer extends Component{ render(){ AOS.init(); return(<div className="specialRoom"> <div className="heading_text"> <p>Special Summer Package</p> <h4> Starts from $19 per night Only</h4> <button>Book Now</button> </div> <div className="RoomOffer"> <div className="aboutMain"> <div className="image" data-aos-offset="300" data-aos="fade-right"><img src="./images/room3.jpg" alt=""/></div> <div className="about_info" data-aos="fade-left"> <h1>Special Summer Package</h1> <p style={{color:"black"}}>cdbudyvchv hukbev cdbudyvchv hukbevcdbudyvchv hukbevcdbudyvchv hukbev cdbudyvchv hukbev cdbudyvchv hukbev cdbudyvchv hukbev cdbudyvchv hukbev v cdbudyvchv hukbev </p> <button>cbjhe vb</button> </div> </div> </div> </div>) } }<file_sep>/src/components/Services.jsx import React,{Component} from 'react'; export default class Services extends Component{ render(){ const data=[{ heading:"Restaurant", para:"<NAME> imaginatively crafts delicious dishes, from burgers and game to fine dining and traditional regional specialities. She sources fresh seasonal produce daily from local producers for our Hotel Restaurant", button:"read More" }, { heading:"Cinema Gold", para:"<NAME> imaginatively crafts delicious dishes, from burgers and game to fine dining and traditional regional specialities. She sources fresh seasonal produce daily from local producers for our Hotel Restaurant", button:"read More" }, { heading:"Golf Ground", para:"<NAME> imaginatively crafts delicious dishes, from burgers and game to fine dining and traditional regional specialities. She sources fresh seasonal produce daily from local producers for our Hotel Restaurant", button:"read More" }] const response= data.map((i, index)=>{ return <div className="service1" key={index}> <h1>{i.heading}</h1> <br/> <p>{i.para}</p> <button> {i.button} </button></div> }) return(<div> <div className="service"> <div className="heading"> <h1>Our Services</h1> <div className="verticle"></div></div> <div className="services"> {response} </div> </div> </div>) } }<file_sep>/src/components/Contact.jsx import React,{Component} from 'react' import { data } from './data' class Contact extends Component{ render(){ var b=this.props.cons; console.log(this.props) var contact= b.map((con,i)=>{ return( <div className="contact-info" key={i}> <i class={con.contact.icon}></i> <br/> <h3>{con.contact.heading}</h3><br/> <p>{con.contact.mobile}</p> </div> ) }) return(<div> <div className="Contact-main"> <div className="embed-map"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3400.025395488297!2d74.38078741463168!3d31.550917652790925!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x39190566b2d1463b%3A0xb8edd95e7d7bc2df!2sGovt+Tariq+High+School+Lahore+Cantt!5e0!3m2!1sen!2s!4v1547369730260"></iframe> </div> <div className="contact-information"> {contact} </div> <div className="contact-form"></div> </div> </div>); } } export default Contact;
14bae57f911d7b39e374def9061d70d1aa313740
[ "JavaScript" ]
11
JavaScript
rohaima/MyApp
1706447c0d2295e4c236f5015961c741d36b7413
d0de6000cc2c15bed9bb004412dc034b3bfd3818
refs/heads/gh-pages
<file_sep>import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.event.KeyListener; import java.awt.event.KeyEvent; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.BorderFactory; import javax.swing.Timer; public class DiceRoller extends JPanel implements KeyListener, MouseListener { private Die die1; public DiceRoller() { setBackground(Color.WHITE); // background color setBorder(BorderFactory.createLineBorder(Color.BLACK)); // border color addKeyListener(this); addMouseListener(this); } protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); super.paintComponent(g2d); g.setColor (Color.black); // // START DRAWING CODE int count=0; for (int i=0;i<9;i++){ die1=new Die(i*50,200); die1.draw(g); count = count + die1.getValue(); } String t = "Count is " + Integer.toString(count) ; g.drawString(t,200, 150); // // END DRAWING CODE // } public void addNotify() { super.addNotify(); requestFocus(); } public void mouseClicked(MouseEvent e) { repaint(); } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SPACE) { repaint(); } } public void mousePressed(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public static void main(String[] args) { JFrame window = new JFrame("Dice Roller"); // window title window.setSize(500, 300); // initial window width, height window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); DiceRoller panel = new DiceRoller(); Container c = window.getContentPane(); c.add(panel); window.setVisible(true); } }
ea1771c3739d3b2b8d61afd3a6c6ea67292f360f
[ "Java" ]
1
Java
TDugan23/Dice
36d6280ff974097105cedf35e34acabca0dfc408
36c6a3dd14b20b6e2469429ee74fe1ccfbf8ea6d
refs/heads/master
<file_sep>#include <gLCD.h> const char RST = 8; const char CS = 9; const char Clk = 13; const char Data = 11; gLCD graphic(RST,CS,Clk,Data,HIGH_SPEED); //High speed void setup() { graphic.begin(0,0,0,EPSON); //Normal Epson graphic.setBackColour(GLCD_BLACK); //set the background to lime colour. graphic.Clear(); Serial.begin(9600); } void loop() { graphic.setForeColour(0,13,15); //Text is coloured Blue graphic.setFont(Normal_ClearBG_Wrap); //normal size text, solid background. graphic.setCoordinate(0,30); graphic.print("eth0: 255.255.255.255"); graphic.setCoordinate(0,60); graphic.print("wlan0: 255.255.255.255"); while (1); } <file_sep>/* gLCD Library Example 1: This example shows how to use the basic functions: Line, Plot, Box, Circle, Print, SetForeColour, and SetBackColour. gLCD should work for all Nokia Clone 128x128 screens which have the Epson or Phillips controller chip. */ #include <gLCD.h> //You can use these variables to set the pin numbers const char RST = 8; const char CS = 9; const char Clk = 13; const char Data = 11; /*Create an instance of the display. Lets call it 'graphic'. There are four variables, which define which pins the LCD is connected too. these are: Reset, Chip Select, Clock, Data. A fifth variable 'speed' can be included as 0 or 1, which controls whether to enter high speed mode (see below). If the fifth variable is omitted (i.e. only the first four are given), normal speed mode is implied. gLCD graphic(RST,CS,Clk,Data [,speed]); Note, it is also possible to enable a high speed mode which increases the speed of the display by a factor of >5. This is done through the library bypassing the digitalWrite function and directly addressing port registers. For the Due, High speed mode increases speed to such an extent that this example completes before you can blink. Please note that while this doesn't affect how you use the library (it is all handled internally), it is possible that it may run too fast for your display and thus the display will appear to not work. This is UNLIKELY to happen, and I have checked with several displays which all worked fine. As of version 2.4 nothing special needs to be done to use this high speed mode, so I am now mentioning it is the example file. */ //For normal speed, use: //gLCD graphic(RST,CS,Clk,Data,NORMAL_SPEED); //Normal speed //For high speed, use: gLCD graphic(RST,CS,Clk,Data,HIGH_SPEED); //High speed void setup() { /*Display needs to be initialised. You only need to do this once, You may have to press the Arduino reset button after uploading your code as the screen may fail to startup otherwise The first two variables in the begin() call specify where on the screen origin is. On some screens the first one or two rows/cols of pixels aren't visible, so begin(X,Y,,) allows all X and Y co-ords to be shifted slightly. The third variable specifies whether the colours are inverted. If the White background is Black on your screen, set this to a 1 Else leave it as a zero The fourth variable is the driver to use you can choose from. There are 6 drivers: EPSON (or) EPSON_4 (both are the same) EPSON_5 PHILLIPS_0 PHILLIPS_1 PHILLIPS_2 PHILLIPS_3 To determine the offset (x,y) coordinate, run this example sketch. It will print a 10px x 10px red box in the top left corner of the screen. If that boxes outline does not line up with the corner, try using the offsets. A positive x will shift the screen to the right, negative x to the left. A positve Y will shift the display down, and a negative Y will shift it up. For an Epson Screen: */ //This graphic.begin(0,0,0,EPSON); //Normal Epson //or // graphic.begin(0,0,0,EPSON_4); //Normal Epson //or //graphic.begin(0,0,0,EPSON_5); //16bit mode Epson - suits some rare screens. //For a Phillips Screen: //This //graphic.begin(0,0,0,PHILLIPS_0); //Normal X direction //or //graphic.begin(0,0,0,PHILLIPS_1); //Revesed X direction. //or //graphic.begin(0,0,0,PHILLIPS_2); //Normal X direction, Mirrored. //or //graphic.begin(0,0,0,PHILLIPS_3); //Revesed X direction, Mirrored. graphic.setBackColour(GLCD_LIME); //set the background to lime colour. graphic.Clear(); /*If you can't see the colours properly, then uncomment the graphic.Contrast() function. If the Screen is too dark, or you cant see anything send a value >0x2B (>0x30 for Phillips). If you cant see all the different colours distinctly on the test pattern, send a value <0x2B (<0x30 for Phillips). The default values should work for many screens, so you may not have to use this at all. Range for phillips: -0x3F to 0x3F Range for EPSON: 0x00 to 0x3F */ //graphic.Contrast(0x2B); Serial.begin(9600); } void loop() { graphic.setBackColour(15, 0, 0); graphic.setForeColour(0,0,15); //Text is coloured Blue graphic.setFont(Large_ClearBG); //normal size text, solid background. //graphic.setFont(Normal_SolidBG); //normal size text, solid background. graphic.setCoordinate(0,40); // graphic.print("OK"); char buffer[32]; int ch; Serial.println("Enter..."); String text; char buf[32]; while (1) { if (Serial.available() > 0) { ch = Serial.read(); Serial.print((char)ch); //Serial.println(ch, DEC); text += (char)ch; if (ch == '\r') { Serial.print('\n'); text.toCharArray(buf, sizeof(buf)); graphic.Clear(); graphic.print(buf); text = ""; } } } while (1); } void loop2() { /*Lets draw a box... First we set the background colour and foreground colour We use the SetBackColour function to do this. The function takes three bytes, which are: Red, Green, Blue. Each of these is a 4 bit number where 0 = off, 15 = fully on. */ //We want a white background, so that would be 15 for each variable graphic.setBackColour(15,15,15); //We want a red foreground, so red will be 15 and the others 0 graphic.setForeColour(15,0,0); /*Now We draw our box. Lets use the Box() function. Box( X1, Y1, X2, Y2, format) takes 5 variables. The first two are: X1, Y1. These are bytes which represent the (x,y) co-ord where the box will start The second two are: X2, Y2. These bytes represent the (x,y) co-ord where the box will end. NOTE: This coodinate will also be included in the box The final one is: format. This controls how the box will look (b7..b3 are ignored) b2 | b1 | b0 | Meaning ----+----+----+----------------------------------------------------------------------------- 0 | 1 | x | Draws a box with just a border of colour BackColour ----+----+----+----------------------------------------------------------------------------- 1 | 1 | x | Draws a box with just a border of colour ForeColour ----+----+----+----------------------------------------------------------------------------- 0 | 0 | 0 | Draws a box with border in BackColour and fill inside it with BackColour ----+----+----+----------------------------------------------------------------------------- 1 | 0 | 0 | Draws a box with border in ForeColour and fill inside it with BackColour ----+----+----+----------------------------------------------------------------------------- 0 | 0 | 1 | Draws a box with border in BackColour and fill inside it with ForeColour ----+----+----+----------------------------------------------------------------------------- 1 | 0 | 1 | Draws a box with border in ForeColour and fill inside it with ForeColour Or you can use one of the predefined constants: OutlineBackColour = 0b010 OutlineForeColour = 0b110 SolidBackColour = 0b000 BorderForeColour_FillBackColour = 0b100 BorderBackColour_FillForeColour = 0b001 SolidForeColour = 0b101 Lets draw a box which starts from (10,10) and is 100 pixes square. So, X1 = 10, Y1 = 10, X2 = 10 + 99, <- Because X2,Y2 will be part of the box Y2 = 10 + 99 It will have a border coloured Red, and be filled with the background colour. So, 'format' = 4 */ // graphic.Box(10,10,109,109,4); graphic.Box(0, 0, 128, 131, 4); //Or This: //graphic.Box(10,10,109,109,BorderForeColour_FillBackColour); //Inside is another box filled in the foreground colour graphic.Box(20,20,99,99,5); //Or This: //graphic.Box(20,20,99,99,SolidForeColour); /* Next we will write Hello in the centre. For this we need to use the print() function. This behaves exactly like Serial.print() only it prints to the screen not the serial port. First though we need to setup the text. There are two functions to do this. setCoordinate(X,Y); and setFont(Font); In setCoordinate(X,Y), we set the co-ordinates of where the text will be placed on the screen - (X,Y) pixels denotes the top left corner. NOTE: Currently there is no text wrap so strings that dont fit on the screen will be clipped. However you can use a '\n' character to print the characters following it on a new line directly below. Then, in setFont(Font), we set the Font. This controls the vertical and horizontal scaling of the text, and also whether it has a solid or transparent background. Font bits have the following meaning: (b7..b4 are ignored - maybe future use) b2 | b2 | b1 | b0 | Meaning ----+----+----+----+----------------------------------------------- 0 | x | x | x | Text will be truncated if too long for screen ----+----+----+----+----------------------------------------------- 1 | x | x | x | Text will be wrapped onto new line if too long ----+----+----+----+----------------------------------------------- x | 0 | x | x | Text has transparent background ----+----+----+----+----------------------------------------------- x | 1 | x | x | Text has solid background ----+----+----+----+----------------------------------------------- x | x | 0 | 0 | Text normal. (6 x 8 pixels) ----+----+----+----+----------------------------------------------- x | x | 0 | 1 | Text Wide. (12 x 8 pixels) ----+----+----+----+----------------------------------------------- x | x | 1 | 0 | Text Tall. (6 x 16 pixels) ----+----+----+----+----------------------------------------------- x | x | 1 | 1 | Text Tall and Wide. (12 x 16 pixels) Or you can use one of the predefined constants: Normal_ClearBG = 0b000 = 0 Wide_ClearBG = 0b001 = 1 Tall_ClearBG = 0b010 = 2 Large_ClearBG = 0b011 = 3 Normal_SolidBG = 0b100 = 4 Wide_SolidBG = 0b101 = 5 Tall_SolidBG = 0b110 = 6 Large_SolidBG = 0b111 = 7 Normal_ClearBG_Wrap = 0b1000 = 8 Wide_ClearBG_Wrap = 0b1001 = 9 Tall_ClearBG_Wrap = 0b1010 = 10 Large_ClearBG_Wrap = 0b1011 = 11 Normal_SolidBG_Wrap = 0b1100 = 12 Wide_SolidBG_Wrap = 0b1101 = 13 Tall_SolidBG_Wrap = 0b1110 = 14 Large_SolidBG_Wrap = 0b1111 = 15 We then finally call the print function with our text or variable, e.g. graphic.print("Some Text"); See print() in the Arduino Reference for more details. */ graphic.setForeColour(0,0,15); //Text is coloured Blue graphic.setFont(4); //normal size text, solid background. //graphic.setFont(Normal_SolidBG); //normal size text, solid background. graphic.setCoordinate(40,40); graphic.print("Hello\nWorld"); //Hello and World will be printed on seperate lines as governed by the newline character '\n' graphic.setFont(12); //normal size text, solid background. Wrap string to new line if needed //graphic.setFont(Normal_SolidBG_Wrap); //normal size text, solid background. Wrap string to new line if needed graphic.setCoordinate(0,112); graphic.print("This string is too long for a single line"); //The string is too long for a single line, but by selecting one of the '_Wrap' fonts, it will be automatically split onto new lines. /* Now lets double underline the text twice. Each normal character takes up 6 x 8 pixels, so we need to draw a line 8+9 pixels below the top of the text as there are two lines. The line is 6*5 = 30px long. And a second of the same length which is 11 pixels below the top of the text. For this we can use the Line() Function. Line(X1,X2,Y1,Y2,Colour) takes five variables Firstly X1 and Y1 are both unsigned chars which are where the line starts. The second two are: X2,Y2. These are the last point on the line. Lastly: Colour. This defines whether the line should be in Foreground colour (Colour = 1) or Background colour (Colour = 0) */ graphic.Line(40,57,69,57,4); // The lines will be Blue as that was the last foreground colour that was set. graphic.Line(40,59,69,59,4); /* The next function is Circle(). Circle(X1,Y1,Radius,Format) takes four variables The first two are: X1, Y1. These are bytes which represent the (x,y) co-ord of the centre of the circle. The next is: Radius. This is the radius of the circle in pixels. The final one is: Format. This controls how the Circle will look (b7..b3 are ignored) b2 | b1 | b0 | Meaning ----+----+----+----------------------------------------------------------------------------- 0 | 1 | x | Draws a Circle with just a border of colour BackColour ----+----+----+----------------------------------------------------------------------------- 1 | 1 | x | Draws a Circle with just a border of colour ForeColour ----+----+----+----------------------------------------------------------------------------- 0 | 0 | 0 | Draws a Circle with border in BackColour and fill inside it with BackColour ----+----+----+----------------------------------------------------------------------------- 1 | 0 | 0 | Draws a Circle with border in ForeColour and fill inside it with BackColour ----+----+----+----------------------------------------------------------------------------- 0 | 0 | 1 | Draws a Circle with border in BackColour and fill inside it with ForeColour ----+----+----+----------------------------------------------------------------------------- 1 | 0 | 1 | Draws a Circle with border in ForeColour and fill inside it with ForeColour Or you can use one of the predefined constants: OutlineBackColour = 0b010 OutlineForeColour = 0b110 SolidBackColour = 0b000 BorderForeColour_FillBackColour = 0b100 BorderBackColour_FillForeColour = 0b001 SolidForeColour = 0b101 */ graphic.Circle(66,74,15,4); //Draw circle of radius 10px, filled with the background colour //Or: //graphic.Circle(66,74,15,BorderForeColour_FillBackColour); //Draw circle of radius 10px, filled with the background colour /* The last basic function is Plot(). This simply sets the colour of the pixel at (x,y) to the current foreground colour. Plot(X,Y) takes three variables. X and Y are the co-odinate where the dot is drawn. Colour defines whether the line should be in Foreground colour (Colour = 3) or Background colour (Colour = 0) */ for (int i = 15;i < 19;i++){ for (int j = 17;j < 21;j++){ graphic.Plot((i*4), (j*4),3); //Draw a grid of 16 dots. } } while(1); //Finished }
aac90621b53a54efebc9d587e19f65696223e246
[ "C++" ]
2
C++
doremi/lcd-arduino
ad4b194600b6a8bbd9f6bd0213a2fc36015fa788
c8cf5e3daf785012945f308da3dd88f1c287539b
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; @Component({ templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { constructor() { } ngOnInit() { // // TSLint test. // // const constOne = 1, ConstTwo = 0; // if (true) { // const msg: string = 'Hello World'; // console.log(msg); // } else { } // const singleLine = () => 10; // const multiLine = () => { // return 10; // }; // const argParanthesis = (age: number) => age; // const nonTradFunc = (/*unusedParam: string*/) => { // const someObj = { // someString: 'Some normal object property.', // 'some-weird-property': 'Some kebab-cased named object property.' // }; // return someObj; // }; // console.log(singleLine(), multiLine(), argParanthesis(2), nonTradFunc()); } } // function add(x: number, y: number) { // return x + y; // }
830b54191f30a5dd535812a9e4c5f2230ecfb5b6
[ "TypeScript" ]
1
TypeScript
alexanderbaran/angular-webpack
8880df3045b15209688086baacbd11d5ffda6617
f661aaaed4860bf61ef9e778a5f926c0856d828f