Stepanova Asya il y a 1 an
Parent
commit
4b1948b0e3
4 fichiers modifiés avec 265 ajouts et 0 suppressions
  1. 42 0
      src/store/authReducer.js
  2. 125 0
      src/store/playerReducer.js
  3. 84 0
      src/store/promiseReducer.js
  4. 14 0
      src/store/store.js

+ 42 - 0
src/store/authReducer.js

@@ -0,0 +1,42 @@
+
+// const jwtDecode = token =>{
+//     try{
+//         let payload = JSON.parse(atob(token.split('.')[1]));
+//         return payload;
+//     } catch(e){
+        
+//     }
+//   }
+export const authReducer = function(state, {type, token, user}) {
+    if (state === undefined) {
+        if(localStorage.authToken) {
+            type = "AUTH_LOGIN";
+            token = localStorage.authToken;
+            user = JSON.parse(localStorage.user);
+        } else {
+            type = "AUTH_LOGOUT";
+        };
+    };
+    if (type === "AUTH_LOGIN") {
+        localStorage.authToken = token;
+        localStorage.user = JSON.stringify(user);
+        
+        return {
+            token: token,
+            user: user
+        }
+        
+    };
+    if (type === "AUTH_LOGOUT") {
+        localStorage.removeItem("authToken");
+        return {};
+    };
+  
+    return state || {};
+  };
+  
+  export const actionAuthLogin  = (token, user) => ({type: "AUTH_LOGIN", token, user});
+  export const actionAuthLogout = () => ({type: "AUTH_LOGOUT"});
+  
+
+  

+ 125 - 0
src/store/playerReducer.js

@@ -0,0 +1,125 @@
+//import { store } from '../store/store';
+import { audio } from '../components/playlistById';
+
+export const playerReducer = function(state = {}, {type, duration, track, playlist, playlistIndex, currentTime, volume}) {
+    if (!state) {
+        return {};
+    }
+    if (type === 'PLAY'){
+        return {
+            ...state, 
+            isPlaying: true,
+            isStopped: false
+        }
+    } if (type === "PAUSE"){
+        return {
+            ...state,
+            isStopped: true,
+            isPlaying: false
+        }
+    } if (type === 'GET_DURATION') {
+        return {
+            ...state,
+            duration
+        }
+    } if (type === 'SET_CURRENT_TIME') {
+        return {
+            ...state,
+            currentTime
+        }
+    } if (type === 'SET_VOLUME') {
+        return {
+            ...state,
+            volume
+        }
+    } if (type === 'SET_TRACK' || type === 'SET_NEW_TRACK' || type === "SET_PREV_TRACK") {
+        return {
+            ...state,
+            track,
+            isPlaying: true,
+            isStopped: false
+        }
+    } if (type === 'SET_PLAYLIST') {
+        return {
+            ...state,
+            playlist,
+            playlistIndex
+        }
+    }
+    return state;
+}
+
+
+const actionPlay = () => ({type:'PLAY'})
+export const actionFullPlay = () =>
+    dispatch => {  
+        audio.play();
+        dispatch(actionPlay());
+        dispatch(actionFullGetDuration(msToTime(audio.duration)))
+    }
+
+
+// let audio = new Audio();
+// const actionPlay = () => ({type:'PLAY'})
+// export const actionFullPlay = () =>
+//     dispatch => {  
+//         audio.play();
+//         dispatch(actionPlay());
+//         dispatch(actionFullGetDuration(msToTime(audio.duration)))
+//     }
+
+function msToTime(duration) {
+    let hours,minutes,seconds;
+    hours = Math.floor(duration / 3600);
+    minutes = Math.floor((duration - 3600 * hours) / 60);
+    seconds = Math.floor((duration - 3600 * hours - 60 * minutes) % 60);
+    
+    hours = (hours < 10) ? "0" + hours : hours;
+    minutes = (minutes < 10) ? "0" + minutes : minutes;
+    seconds = (seconds < 10) ? "0" + seconds : seconds;
+    
+    return minutes + ":" + seconds;
+    }
+
+
+const actionPause = () => ({type:'PAUSE'})
+export const actionFullPause = () =>
+    dispatch => {
+        audio.pause();
+        dispatch(actionPause());
+    }
+
+const actionSetVolume = (volume) => ({type:'SET_VOLUME', volume})
+export const actionFullSetVolume = (volume) =>
+    dispatch => {
+        audio.volume = volume / 100;
+        dispatch(actionSetVolume(volume));
+    }
+
+const actionSetTrack = (track) => ({type:'SET_TRACK', track})
+export const actionFullSetTrack = (track) =>
+    dispatch => {
+        //audio.src = `http://player-api/storage/tracks/${track.file}`;
+        dispatch(actionSetTrack(track));
+        dispatch(actionFullPlay());
+        dispatch(actionFullGetDuration(msToTime(audio.duration)));  
+    }
+
+const actionGetDuration = (duration) => ({type:'GET_DURATION', duration})
+export const actionFullGetDuration = (duration) =>
+    dispatch => {
+        dispatch(actionGetDuration(duration));
+    }
+
+const actionSetCurrentTime = (currentTime) => ({type:'SET_CURRENT_TIME', currentTime})
+export const actionFullSetCurrentTime = (currentTime) =>
+    dispatch => {
+        dispatch(actionSetCurrentTime(currentTime));
+    }
+
+
+const actionSetPlaylist = (playlist) => ({type:'SET_PLAYLIST', playlist})
+export const actionFullSetPlaylist = (playlist) =>
+    dispatch => {
+        dispatch(actionSetPlaylist(playlist));
+    }

+ 84 - 0
src/store/promiseReducer.js

@@ -0,0 +1,84 @@
+import { actionAuthLogin } from "./authReducer";
+import { store } from "./store";
+
+
+export function promiseReducer(state={}, {type, name, status, payload, error}) {
+    if (type === 'PROMISE'){
+        return {
+            ...state,
+            [name]:{status, payload, error}
+        }
+    }
+    return state
+}
+
+const actionPending   =       name      => ({type:'PROMISE',name, status: 'PENDING'})
+const actionFulfilled =  (name,payload) => ({type:'PROMISE',name, status: 'FULFILLED', payload})
+const actionRejected  =   (name,error)  => ({type:'PROMISE',name, status: 'REJECTED', error})
+
+export const actionPromise   = (name, promise) =>
+    async dispatch => {
+        dispatch(actionPending(name))
+        try {
+            let payload = await promise
+            dispatch(actionFulfilled(name, payload))
+            return payload
+        }
+        catch(error){
+            dispatch(actionRejected(name, error))
+        }
+    }
+
+    export const backendURL = 'http://player-api/api';
+
+    const getGQL = (backendURL) =>
+    (plusurl) => fetch(backendURL+plusurl, {
+        method: 'GET',
+        headers: {
+            "Content-Type": "application/json",
+            ...(localStorage.authToken ? {"Authorization": "Bearer " + localStorage.authToken} : {})
+        }
+    }).then(res => res.json())
+        .then(data => {
+            return data;
+            // if (data.data){
+            //     return Object.values(data.data)[0] 
+            // } 
+            // else {throw new Error(JSON.stringify(data.errors))}
+            
+        })
+  
+    
+
+    const gql = getGQL(backendURL);
+
+export const actionAllPlaylists = () =>
+    actionPromise('allPlaylists', gql('/playlists'))
+
+
+export const actionUsersPlaylists = (id) =>
+    actionPromise('usersPlaylists', gql('/profile/' + id + '/playlists'))
+
+
+export const actionPlaylistById = (_id) => 
+  actionPromise('plstById', gql('/playlists/'+_id))
+
+
+ export const actionFullLogin = async function(login, password) {
+    let token = await gql("query userLogin($login: String, $password: String) {login(login: $login, password: $password)}", 
+    {"login": login, "password": password});
+
+    store.dispatch(actionAuthLogin(token));
+};
+
+
+// export const actionCreateOrder = () => async (dispatch) => {
+//     let orderGoods = [];
+//     Object.entries(store.getState().cart).map(([_id,{count}])=>orderGoods.push({"count":count,"good":{_id:_id}}))
+//     actionPromise('createOrder',gql(`mutation newOrder($order:OrderInput) {
+//             OrderUpsert(order:$order) {
+//               _id total
+//             }
+//           }`,{order:{orderGoods}}));
+//          await store.dispatch(actionCartClean());
+//     }

+ 14 - 0
src/store/store.js

@@ -0,0 +1,14 @@
+import {createStore, combineReducers, applyMiddleware} from 'redux';
+import thunk from 'redux-thunk';
+import { authReducer } from './authReducer';
+import { promiseReducer } from './promiseReducer';
+import { playerReducer } from './playerReducer';
+
+
+
+
+export const store = createStore(combineReducers({promise: promiseReducer,
+    auth: authReducer, player: playerReducer}), applyMiddleware(thunk))
+
+
+