firebase Service
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject, finalize, map, Observable } from 'rxjs';
import { Auth, } from '@angular/fire/auth';
import { Database, ref, update, get, remove, onValue } from '@angular/fire/database';
import { SystemUser } from '../models/user';
import { AngularFireStorage } from '@angular/fire/compat/storage';
import { CopyToClipboardService } from './copy-to-clipboard.service';
import { SnackBarService } from './snack-bar.service';
// import * as functions from 'firebase-functions';
import { AngularFirestore } from '@angular/fire/compat/firestore';
import { Activity } from '../models/activity';
import { ActivitiesService } from './activities.service';
import { LocalStorageService } from './_local-storage.service';
import { Privilege } from '../models/privilege.model';
@Injectable({
providedIn: 'root'
})
export class FirebaseService {
backEndURL: string = "";
private userSubject: BehaviorSubject<any>;
public user: Observable<any>;
any: any;
//Storage Variables
uploadPercent: Observable<number>;
downloadURL: Observable<string>;
profileUrl: any;
users: SystemUser[] = [];
activity: Activity = new Activity();
constructor(
private db: AngularFirestore,
private activityService: ActivitiesService,
private localStorageService: LocalStorageService,
private snackBarService: SnackBarService,
private copyService: CopyToClipboardService,
private storage: AngularFireStorage,
private router: Router,
private http: HttpClient,
public auth: Auth,
public database: Database
) {
this.userSubject = new BehaviorSubject<any>(JSON.parse(localStorage.getItem('user') || '{}'));
this.user = this.userSubject.asObservable();
const ref = this.storage.ref('users/davideast.jpg');
this.profileUrl = ref.getDownloadURL();
}
public get userValue(): any {
if (this.userSubject.value != '{}') {
return this.userSubject.value;
} else {
this.router.navigate(['/login']);
return null;
}
}
//----------------- USERS ----------------------
getAllUsers() {
return new Promise<any>((resolve) => {
this.db.collection('Users').valueChanges({ idField: 'id' }).subscribe(users => resolve(users));
})
}
getUsers() {
return ref(this.database, "users");
}
getUser(userKey: any) {
return ref(this.database, "users/" + userKey);
}
// updateUser(userKey: any, user: SystemUser) {
// //----------------------------------------------------------
// this.activity.action = "EDITE_USER";
// this.activity.table = "firebase - users";
// this.activity.description = JSON.stringify(user);
// this.activity.employeeCard = this.localStorageService.get("currentEmployee");
// this.activity.icon = "groups";
// this.activity.employeeCard.photo = this.activity.employeeCard.photo;
// //----------------------------------------------------------
// this.activityService.postItem(this.activity).subscribe(res => {
// });
// //----------------------------------------------------------
// user.password = null;
// update(ref(this.database, "users/" + userKey), user)
// }
blockAndUnblockAccount(user: SystemUser) {
//----------------------------------------------------------
this.activity.action = (user.blocked) ? "BLOCK" : "UNBLOCK";
this.activity.table = "firebase - users";
this.activity.description = JSON.stringify(user);
this.activity.employeeCard = this.localStorageService.get("currentEmployee");
this.activity.icon = "groups";
this.activity.employeeCard.photo = this.activity.employeeCard.photo.data;
//----------------------------------------------------------
this.activityService.postItem(this.activity).subscribe(res => {
});
user.blocked = !user.blocked;
update(ref(this.database, "users/" + user.id), user)
}
deleteUser(userKey: any) {
this.activityService.postActivityForDelete("DELETE_USER", "firebase - users", "groups", '', 0);
//----------------------------------------------------------
this.activityService.postItem(this.activity).subscribe(res => {
});
//----------------------------------------------------------
remove(ref(this.database, "users/" + userKey))
}
getUserByEmail(): SystemUser[] {
onValue(ref(this.database, "users"), (snapshot) => {
this.users = [];
const data = snapshot.val();
Object.keys(data).forEach((key: any) => {
this.users.push(data[key]);
this.localStorageService.setAllSystemUsersItem(this.users);
});
});
return this.localStorageService.getAllSystemUsersItem();
}
searchUsers(searchValue: any) {
return get(ref(this.database, "users"));
}
searchUsersByAge(value: any) {
// return this.db.collection('users', ref => ref.orderBy('age').startAt(value)).snapshotChanges();
}
// createUser(user: SystemUser, doneMessage: string, close: string, emailAlreadyInUse: string) {
// this.activityService.postActivityForUpdate("CREATE_NEW_USER", "firebase - users", "groups", user, 0);
// //----------------------------------------------------------
// this.authService.registerUser(user, doneMessage, close, emailAlreadyInUse);
// }
getAvatars() {
// return this.database.collection('/avatar').valueChanges()
}
//---------------------------------
// uploadFile(event: any) {
// const file = event.target.files[0];
// const filePath = "profiles/profile_" + (Math.floor(Math.random() * (150 - 1) + 1)) + "." + file.name.split('.')[1];
// const fileRef = this.storage.ref(filePath);
// const task = this.storage.upload(filePath, file);
// // observe percentage changes
// this.uploadPercent = task.percentageChanges();
// // get notified when the download URL is available
// task.snapshotChanges().pipe(
// finalize(() => {
// this.copyService.copyMessage(fileRef.getDownloadURL().toString(), '');
// this.downloadURL = fileRef.getDownloadURL();
// })
// )
// .subscribe()
// }
//----------------- PRIVILEGES ----------------------
refreshPrivilege(role: Privilege) {
// const d = new Date();
// let ms = d.valueOf();
// role.id = ms.toString();
// role.blocked = false;
//----------------------------------------------------------
update(ref(this.database, "privileges2/" + role.id), role);
// this.snackBarService.success(doneMessage, close);
}
updateRole(role: Privilege) {
//----------------------------------------------------------
update(ref(this.database, "privileges2/" + role.id), role);
}
blockAndUnblockRole(role: Privilege) {
let action = (role.disabled_login) ? "BLOCK_ROLE" : "UNBLOCK_ROLE";
//----------------------------------------------------------
role.disabled_login = !role.disabled_login;
update(ref(this.database, "privileges2/" + role.id), role);
}
getPrivilege(userKey: any) {
return ref(this.database, "privileges2/" + userKey);
}
deleteRole(userKey: any) {
this.activityService.postActivityForDelete("DELETE_ROLE", "firebase - privileges", "admin_panel_settings", userKey, 0);
//----------------------------------------------------------
this.activityService.postItem(this.activity).subscribe(res => {
});
//----------------------------------------------------------
remove(ref(this.database, "privileges2/" + userKey))
}
getPrivileges() {
return ref(this.database, "privileges2");
}
getPrivileges2() {
onValue(ref(this.database, "privileges2"), (snapshot) => {
let roles: any = [];
let currentRoles: any = [];
const data = snapshot.val();
roles = data;
Object.keys(roles).forEach((key: any) => {
currentRoles.push(roles[key]);
});
return currentRoles;
})
}
}
تعليقات
إرسال تعليق