Advertisement
Guest User

Untitled

a guest
Apr 15th, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.20 KB | None | 0 0
  1. ------------------------Artist Form Component.ts-----------------------------
  2.  
  3. import { Component, OnInit } from '@angular/core';
  4. import { ArtistsService } from './../../services/artists.service';
  5. import { Artist } from './../../models/artist.model';
  6. import { FormBuilder, FormGroup, Validators } from '@angular/forms';
  7. import { Router } from '@angular/router';
  8. import { AuthService } from 'src/app/services/auth.service';
  9.  
  10. import * as firebase from 'firebase/app';
  11. import 'firebase/app';
  12. import 'firebase/firestore';
  13. import 'firebase/auth';
  14. import 'firebase/database';
  15. import 'firebase/storage';
  16.  
  17.  
  18.  
  19. @Component({
  20. selector: 'app-artist-form',
  21. templateUrl: './artist-form.component.html',
  22. styleUrls: ['./artist-form.component.scss']
  23. })
  24. export class ArtistFormComponent implements OnInit {
  25.  
  26. artistForm: FormGroup;
  27. fileIsUploading = false;
  28. fileUrl: string;
  29. fileUploaded = false;
  30. errorMessage: string;
  31.  
  32. constructor(private formBuilder: FormBuilder,
  33. private artistsService: ArtistsService,
  34. private router: Router,
  35. private authService: AuthService) { }
  36.  
  37. ngOnInit() {
  38. this.initForm();
  39. }
  40.  
  41. initForm() {
  42. this.artistForm = this.formBuilder.group({
  43. nickname: ['', Validators.required],
  44. email: ['', [Validators.required, Validators.email]],
  45. password: ['', [Validators.required, Validators.pattern(/[0-9a-zA-Z]{6,}/)]],
  46. patreon: ['', [Validators.required, Validators.pattern('https://www.patreon.com/[0-9a-zA-Z]{6,}')]],
  47. roles: ['', Validators.required],
  48. country: ['', Validators.required],
  49. photo: ['', Validators.required],
  50. description: ['', Validators.required]
  51. });
  52. }
  53.  
  54. onSaveArtist() {
  55. const nickname = this.artistForm.get('nickname').value;
  56. const email = this.artistForm.get('email').value;
  57. const password = this.artistForm.get('password').value;
  58. const patreon = this.artistForm.get('patreon').value;
  59. const roles = this.artistForm.get('roles').value;
  60. const country = this.artistForm.get('country').value;
  61. const description = this.artistForm.get('description').value;
  62.  
  63. const arrayPath = this.artistForm.get('photo').value.split("\\"); // arrayPath[2] is our photo's name ;) I figured this out by
  64. //displaying arrayPath, you can try that out to be convinced! ;)
  65.  
  66. var photo = 'empty';
  67. const storageRef = firebase.storage().ref();
  68. const photoRef = storageRef.child('/uploads/' + arrayPath[2]);
  69.  
  70. photoRef.getDownloadURL().then( (url) => {
  71. photo = url.toString();
  72.  
  73. this.authService.createNewUser(email, password).then(
  74. () => {
  75. var newArtist = new Artist(nickname, email, password, patreon, roles, 'offline', country, photo, description);
  76. this.artistsService.createNewArtist(newArtist);
  77. this.router.navigate(['/artists']);
  78. },
  79. (error) => {
  80. this.errorMessage = error;
  81. }
  82. );
  83. }).catch(function (error) {
  84. // Handle any errors
  85. console.log("error in getting download url.." + error);
  86. });
  87.  
  88.  
  89. }
  90.  
  91. onUploadFile(file: File) {
  92. this.fileIsUploading = true;
  93. this.artistsService.uploadFile(file).then(
  94. (url: string) => {
  95. this.fileUrl = url;
  96. this.fileIsUploading = false;
  97. this.fileUploaded = true;
  98. }
  99. );
  100. }
  101.  
  102. detectFiles(event) {
  103. this.onUploadFile(event.target.files[0]);
  104. }
  105.  
  106. }
  107.  
  108. ---------------------------------Artists Service---------------------------
  109.  
  110. import * as firebase from 'firebase/app';
  111. import 'firebase/app';
  112. import 'firebase/firestore';
  113. import 'firebase/auth';
  114. import 'firebase/database';
  115. import 'firebase/storage';
  116.  
  117. import { Artist } from '../models/artist.model';
  118. import { Injectable } from '@angular/core';
  119. import { Subject } from 'rxjs/Subject';
  120. import { DataSnapshot } from '@angular/fire/database/interfaces';
  121.  
  122.  
  123. @Injectable()
  124. export class ArtistsService {
  125. constructor() {
  126. this.getArtists();
  127. }
  128.  
  129.  
  130. artists: Artist[] = [];
  131. artistsSubject = new Subject<Artist[]>();
  132. artistsFiltered: Artist[] = [];
  133.  
  134. ids: string[] = [];
  135.  
  136. progress: number;
  137.  
  138. emitArtists() {
  139. this.artistsSubject.next(this.artists);
  140. }
  141.  
  142. saveArtists() {
  143. firebase.database().ref('/artists').set(this.artists);
  144. }
  145.  
  146. getArtists() {
  147. firebase.database().ref('/artists')
  148. .on('value', (data: DataSnapshot) => {
  149. this.ids = [];
  150. this.artists = data.val() ? data.val() : [];
  151. this.emitArtists();
  152. this.artists.forEach((artist, index) => {
  153. this.ids.push(index.toString());
  154. });
  155.  
  156. }
  157. );
  158. }
  159.  
  160. getFilteredArtists(filter: string) { // works perfectly
  161. if(filter)
  162. {
  163. this.artistsFiltered = []; // we need to initialize this or we'll always get the previous filtered artists..
  164. this.ids = [];
  165. for(var i=0; i < this.artists.length; i++ )
  166. {
  167. if(this.artists[i]['nickname'].includes(filter) || this.artists[i]['roles'].indexOf(filter) != -1) // if the artist's nickname includes filter or if filter is one of his roles
  168. {
  169. this.artistsFiltered.push(this.artists[i]); // we add him
  170. this.ids.push(i.toString()); // we add the id so that we keep onViewArtist(id) working correctly
  171. }
  172. }
  173. this.artists = this.artistsFiltered; // we set our new artists array
  174. this.emitArtists();
  175. }
  176. }
  177.  
  178. getSingleArtist(id: number) {
  179. return new Promise(
  180. (resolve, reject) => {
  181. firebase.database().ref('/artists/' + id).once('value').then(
  182. (data: DataSnapshot) => {
  183. resolve(data.val());
  184. }, (error) => {
  185. reject(error);
  186. }
  187. );
  188. }
  189. );
  190. }
  191.  
  192. createNewArtist(newArtist: Artist) {
  193. this.artists.push(newArtist);
  194. this.saveArtists();
  195. //firebase.database().ref('/artists').push(newArtist);
  196. this.emitArtists();
  197. }
  198.  
  199. removeArtist(artist: Artist) {
  200. if(artist.photo) {
  201. const storageRef = firebase.storage().refFromURL(artist.photo);
  202. storageRef.delete().then(
  203. () => {
  204. console.log('Photo removed!');
  205. },
  206. (error) => {
  207. console.log('Could not remove photo! : ' + error);
  208. }
  209. );
  210. }
  211. const artistIndexToRemove = this.artists.findIndex(
  212. (artistEl) => {
  213. if(artistEl === artist) {
  214. return true;
  215. }
  216. }
  217. );
  218. this.artists.splice(artistIndexToRemove, 1);
  219. this.saveArtists();
  220. this.emitArtists();
  221. }
  222.  
  223. uploadFile(file: File) {
  224. return new Promise(
  225. (resolve, reject) => {
  226. const upload = firebase.storage().ref().child('uploads/' + file.name).put(file);
  227. upload.on(firebase.storage.TaskEvent.STATE_CHANGED,
  228. (snapshot) => {
  229. console.log((upload.snapshot.bytesTransferred / upload.snapshot.totalBytes) * 100);
  230. this.progress = (upload.snapshot.bytesTransferred / upload.snapshot.totalBytes) * 100;
  231. },
  232. (error) => {
  233. console.log('Erreur de chargement ! : ' + error);
  234. reject();
  235. },
  236. () => {
  237. resolve(upload.snapshot.downloadURL);
  238. }
  239. );
  240. }
  241. );
  242. }
  243.  
  244. }
  245.  
  246.  
  247. ---------------------------- Follow Service --------------------------
  248.  
  249. import { Injectable } from '@angular/core';
  250. import { AngularFireDatabase } from 'angularfire2/database';
  251. import { Subject } from 'rxjs/Subject';
  252. import { DataSnapshot } from '@angular/fire/database/interfaces';
  253.  
  254.  
  255. import * as firebase from 'firebase/app';
  256. import 'firebase/app';
  257. import 'firebase/firestore';
  258. import 'firebase/auth';
  259. import 'firebase/database';
  260. import 'firebase/storage';
  261.  
  262. @Injectable()
  263. export class FollowService {
  264.  
  265. constructor() { }
  266.  
  267. followers: string[] = []; // in before User[]
  268. nbFollowers: number;
  269. followersSubject = new Subject<string[]>(); // in before Subject<User[]>
  270.  
  271. following: string[] = []; // in before Artist[]
  272. followingSubject = new Subject<string[]>(); // in before Subject<Artist[]>
  273.  
  274. indexFollower: number;
  275. indexFollowing: number;
  276.  
  277. emitFollowers() {
  278. this.followersSubject.next(this.followers);
  279. }
  280.  
  281. emitFollowing() {
  282. this.followingSubject.next(this.following);
  283. }
  284.  
  285. saveFollowers(artistId) {
  286. firebase.database().ref('/artists/' + artistId + '/followers').set(this.followers);
  287. }
  288.  
  289. saveFollowing(userId) {
  290. firebase.database().ref('/users/' + userId + '/following').set(this.following);
  291. }
  292.  
  293. getFollowers(artistId) {
  294. firebase.database().ref('/artists/' + artistId + '/followers')
  295. .on('value', (data: DataSnapshot) => {
  296. this.followers = data.val() ? data.val() : [];
  297. this.nbFollowers = this.followers.length;
  298. this.emitFollowers();
  299. }
  300. );
  301. }
  302.  
  303. getFollowing(userId) {
  304. firebase.database().ref('/users/' + userId + '/following')
  305. .on('value', (data: DataSnapshot) => {
  306. this.following = data.val() ? data.val() : [];
  307. this.emitFollowing();
  308. }
  309. );
  310. }
  311.  
  312. // TO DO: need to find a better way to add only the new people involved in this follow action and not the whole array every time we call it .. smth similar to the addNewUser
  313.  
  314. createNewFollower(newFollower: string, newFollowing: string) {
  315. this.getFollowers(newFollowing); // on obtient la liste des followers de cet artiste ayant artistId comme Id
  316. this.followers.push(newFollower); // on ajoute le nouveau follower dans le tableau local des followers
  317. this.saveFollowers(newFollowing); // on le monte ce tableau des followers dans firebase
  318. this.emitFollowers(); // sans cette fonction, le changement réel ne va pas avoir lieu, j'ai testé sans cette ligne pour voir la difference!
  319.  
  320. this.getFollowing(newFollower); // on obtient la liste des following de ce user ayant userId comme Id
  321. this.following.push(newFollowing); // on ajoute le nouveau artiste dans le tableau local des following
  322. this.saveFollowing(newFollower); // on monte ce tableau des following dans firebase
  323. this.emitFollowing(); // sans cette fonction, le changement réel ne va pas avoir lieu, j'ai testé sans cette ligne pour voir la difference!
  324. }
  325.  
  326. // concernant la suppression, il y'a un prob c'est que si on veut supprimer quelqu'un , ce quelqu'un a evidemment changé de structure, car ces followers/following ne sont plus les mêmes, donc on doit dès le départ les inserer avec des tableau follower/following vides.
  327.  
  328. deleteFollower(follower: string)
  329. {
  330. console.log(this.followers);
  331. this.indexFollower = this.followers.indexOf(follower);
  332. console.log("indexFollower = " + this.indexFollower);
  333. if(this.indexFollower !== -1)
  334. {
  335. this.followers.splice(this.indexFollower, 1);
  336. }
  337. }
  338.  
  339. deleteFollowing(following: string)
  340. {
  341. console.log(this.following);
  342. this.indexFollowing = this.following.indexOf(following);
  343. console.log("indexFollowing = " + this.indexFollowing);
  344.  
  345. console.log(following);
  346. if(this.indexFollowing !== -1)
  347. {
  348. this.following.splice(this.indexFollowing, 1);
  349. }
  350. }
  351.  
  352. // prob is : when I try to remove the follower & the following I just can't since in firebase their attributes are not put in the right order --> I created 2 new models for that
  353.  
  354. removeFollower(follower: string, following: string) {
  355. this.getFollowers(following); // on obtient la liste des followers de cet artiste ayant artistId comme Id
  356. this.deleteFollower(follower); // on supprime ce user du tableau des followers
  357. this.saveFollowers(following); // on monte ce tableau des followers dans firebase
  358. this.emitFollowers();
  359.  
  360. this.getFollowing(follower); // on obtient la liste des following de ce user ayant userId comme Id
  361. this.deleteFollowing(following); // on supprime cet artiste du tableau des following
  362. this.saveFollowing(follower); // on monte ce tableau des following dans firebase
  363. this.emitFollowing();
  364. }
  365.  
  366. }
  367.  
  368. -------------Single Artist Component.ts-------------------------
  369.  
  370. import { Component, OnInit, Input, Query } from '@angular/core';
  371. import { ArtistsService } from './../../services/artists.service';
  372. import { Artist } from './../../models/artist.model';
  373. import { ActivatedRoute, Router } from '@angular/router';
  374. import { FollowService } from 'src/app/services/follow.service';
  375. import { User } from 'src/app/models/user.model';
  376. import { UsersService } from 'src/app/services/users.service';
  377.  
  378. import * as firebase from 'firebase/app';
  379. import 'firebase/auth';
  380.  
  381.  
  382. @Component({
  383. selector: 'app-single-artist',
  384. templateUrl: './single-artist.component.html',
  385. styleUrls: ['./single-artist.component.scss']
  386. })
  387. export class SingleArtistComponent implements OnInit {
  388.  
  389. artist: Artist;
  390. mailLink: string;
  391. currentArtistId;
  392. currentUserId: string;
  393. user: User;
  394. isFollowing: boolean;
  395. nbFollowers: number;
  396. makeItCleaner = 'follower';
  397.  
  398. constructor(private route: ActivatedRoute,
  399. private artistsService: ArtistsService,
  400. private router: Router,
  401. private followService: FollowService,
  402. private usersService: UsersService) { }
  403.  
  404. ngOnInit() {
  405. this.artist = new Artist('', '', '', '', [], '', '','', '');
  406. this.currentArtistId = this.route.snapshot.params['id']; // get the Id of the artist that I'm looking at
  407. this.currentUserId = firebase.auth().currentUser.uid; // get the Id of the current user, we still don't know if he's a user or an artist
  408.  
  409. console.log(this.currentUserId); // for testing
  410.  
  411. // need to get the artist the current user is looking at ;)
  412.  
  413. this.artistsService.getSingleArtist(this.currentArtistId).then(
  414. (artist: Artist) => {
  415. this.artist = artist;
  416. this.mailLink = 'http://' + this.artist.email + '/';
  417. console.log(this.artist);
  418. this.followService.getFollowers(this.currentArtistId); // so that we set the variable nbfollowers in the follow service ;)
  419. this.nbFollowers = this.followService.nbFollowers;
  420. if(this.nbFollowers > 1) this.makeItCleaner += 's';
  421. }
  422. );
  423.  
  424. // then I need to get the current user, the current user and the artist will help me in displaying whether the follow or unfollow button ;)
  425.  
  426. this.usersService.getSingleUser(this.currentUserId).then( // this section is important to determine if the uid we have is really a user's uid
  427. (user: User) => {
  428. this.user = user;
  429. if(this.user)
  430. {
  431. this.followService.getFollowing(this.currentUserId); // so that we set the variable following of the current user to have all the artists he's following
  432. this.isFollowing = this.followService.following.some((item) => item == this.currentArtistId); // so that I know if this user is already following the artist or not.. I'll use it to know which button should I display: Follow or Unfollow btn
  433. console.log(this.isFollowing);
  434. }
  435. else console.log("this is not a user!");
  436. }
  437. );
  438.  
  439. }
  440.  
  441. onBack() { // working perfectly
  442. this.artistsService.getArtists(); // without this line, if we hit return and go to artists page, we'll only find the previous artists so this helps to find all the artists again
  443. this.router.navigate(['/artists']);
  444. }
  445.  
  446. onFollow() {
  447.  
  448. console.log(this.user); // for testing
  449. this.followService.createNewFollower(this.currentUserId, this.currentArtistId);
  450. this.isFollowing = this.followService.following.some((item) => item == this.currentArtistId);
  451.  
  452. // just to make it look more realistic: if the followers were 1 and became 2 for exple ==> we should display 2 followers instead of 2 follower ;)
  453. this.nbFollowers = this.followService.nbFollowers;
  454. if(this.nbFollowers > 1) this.makeItCleaner = 'followers';
  455.  
  456. }
  457.  
  458. onUnfollow() {
  459. console.log(this.user); // for testing
  460. this.followService.removeFollower(this.currentUserId, this.currentArtistId);
  461. this.isFollowing = this.followService.following.some((item) => item == this.currentArtistId);
  462.  
  463. // just to make it look more realistic: if the followers were 2 and became one for exple ==> we should display 1 follower instead of 1 followers ;)
  464. this.nbFollowers = this.followService.nbFollowers;
  465. if(this.nbFollowers < 2) this.makeItCleaner = 'follower';
  466. }
  467.  
  468. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement