API: unique filename for gpx, Client: pagination status

This commit is contained in:
Sam 2018-05-11 13:45:54 +02:00
parent 7ef643a2fe
commit 288528716c
5 changed files with 54 additions and 14 deletions

View File

@ -6,9 +6,10 @@ from mpwo_api import appLog, db
from sqlalchemy import exc from sqlalchemy import exc
from ..users.utils import authenticate, verify_extension from ..users.utils import authenticate, verify_extension
from .models import Activity from .models import Activity, Sport
from .utils import ( from .utils import (
create_activity, edit_activity_wo_gpx, get_file_path, get_gpx_info create_activity, edit_activity_wo_gpx, get_file_path, get_gpx_info,
get_new_file_path
) )
activities_blueprint = Blueprint('activities', __name__) activities_blueprint = Blueprint('activities', __name__)
@ -140,6 +141,16 @@ def post_activity(auth_user_id):
try: try:
activity_file.save(file_path) activity_file.save(file_path)
gpx_data = get_gpx_info(file_path) gpx_data = get_gpx_info(file_path)
sport = Sport.query.filter_by(id=activity_data.get('sport_id')).first()
new_filepath = get_new_file_path(
auth_user_id=auth_user_id,
activity_date=gpx_data['start'],
activity_file=activity_file,
sport=sport.label
)
os.rename(file_path, new_filepath)
gpx_data['filename'] = new_filepath
except Exception as e: except Exception as e:
appLog.error(e) appLog.error(e)
response_object = { response_object = {
@ -150,7 +161,7 @@ def post_activity(auth_user_id):
try: try:
new_activity = create_activity( new_activity = create_activity(
auth_user_id, activity_data, gpx_data, file_path) auth_user_id, activity_data, gpx_data)
db.session.add(new_activity) db.session.add(new_activity)
db.session.commit() db.session.commit()
response_object = { response_object = {

View File

@ -1,4 +1,5 @@
import os import os
import tempfile
from datetime import datetime, timedelta from datetime import datetime, timedelta
import gpxpy.gpx import gpxpy.gpx
@ -9,7 +10,7 @@ from .models import Activity
def create_activity( def create_activity(
auth_user_id, activity_data, gpx_data=None, file_path=None auth_user_id, activity_data, gpx_data=None
): ):
activity_date = gpx_data['start'] if gpx_data else datetime.strptime( activity_date = gpx_data['start'] if gpx_data else datetime.strptime(
activity_data.get('activity_date'), '%Y-%m-%d %H:%M') activity_data.get('activity_date'), '%Y-%m-%d %H:%M')
@ -24,7 +25,7 @@ def create_activity(
) )
if gpx_data: if gpx_data:
new_activity.gpx = file_path new_activity.gpx = gpx_data['filename']
new_activity.pauses = timedelta(seconds=gpx_data['stop_time']) new_activity.pauses = timedelta(seconds=gpx_data['stop_time'])
new_activity.moving = timedelta(seconds=gpx_data['moving_time']) new_activity.moving = timedelta(seconds=gpx_data['moving_time'])
new_activity.distance = gpx_data['distance'] new_activity.distance = gpx_data['distance']
@ -58,7 +59,7 @@ def edit_activity_wo_gpx(activity, activity_data):
def get_gpx_info(gpx_file): def get_gpx_info(gpx_file):
gpx_data = {'filename': gpx_file} gpx_data = {}
gpx_file = open(gpx_file, 'r') gpx_file = open(gpx_file, 'r')
gpx = gpxpy.parse(gpx_file) gpx = gpxpy.parse(gpx_file)
@ -107,8 +108,26 @@ def get_gpx_info(gpx_file):
def get_file_path(auth_user_id, activity_file): def get_file_path(auth_user_id, activity_file):
filename = secure_filename(activity_file.filename) filename = secure_filename(activity_file.filename)
dir_path = os.path.join( dir_path = os.path.join(
current_app.config['UPLOAD_FOLDER'], 'activities', str(auth_user_id)) current_app.config['UPLOAD_FOLDER'],
'activities',
str(auth_user_id),
'tmp')
if not os.path.exists(dir_path): if not os.path.exists(dir_path):
os.makedirs(dir_path) os.makedirs(dir_path)
file_path = os.path.join(dir_path, filename) file_path = os.path.join(dir_path, filename)
return file_path return file_path
def get_new_file_path(auth_user_id, activity_date, activity_file, sport):
old_filename = secure_filename(activity_file.filename)
extension = '.{}'.format(old_filename.rsplit('.', 1)[1].lower())
fi, new_filename = tempfile.mkstemp(
prefix='{}_{}_'.format(activity_date, sport),
suffix=extension
)
dir_path = os.path.join(
current_app.config['UPLOAD_FOLDER'], 'activities', str(auth_user_id))
if not os.path.exists(dir_path):
os.makedirs(dir_path)
file_path = os.path.join(dir_path, new_filename.replace('/tmp/', ''))
return file_path

View File

@ -3,8 +3,9 @@ import mpwoApi from '../mwpoApi/activities'
import { history } from '../index' import { history } from '../index'
import { setError } from './index' import { setError } from './index'
export const endPagination = () => ({ export const endPagination = status => ({
type: 'END_PAGINATION' type: 'END_PAGINATION',
status,
}) })
export const pushActivities = activities => ({ export const pushActivities = activities => ({
@ -63,8 +64,9 @@ export const deleteActivity = id => dispatch => mpwoGenericApi
.then(ret => { .then(ret => {
if (ret.status === 204) { if (ret.status === 204) {
history.push('/') history.push('/')
} } else {
dispatch(setError(`activities: ${ret.status}`)) dispatch(setError(`activities: ${ret.status}`))
}
}) })
.catch(error => dispatch(setError(`activities: ${error}`))) .catch(error => dispatch(setError(`activities: ${error}`)))
@ -87,8 +89,9 @@ export const getMoreActivities = page => dispatch => mpwoGenericApi
if (ret.status === 'success') { if (ret.status === 'success') {
if (ret.data.activities.length > 0) { if (ret.data.activities.length > 0) {
dispatch(pushActivities(ret.data.activities)) dispatch(pushActivities(ret.data.activities))
} else { }
dispatch(endPagination()) if (ret.data.activities.length < 5) {
dispatch(endPagination(true))
} }
} else { } else {
dispatch(setError(`activities: ${ret.message}`)) dispatch(setError(`activities: ${ret.message}`))

View File

@ -5,7 +5,7 @@ import { connect } from 'react-redux'
import ActivityCard from './ActivityCard' import ActivityCard from './ActivityCard'
import Statistics from './Statistics' import Statistics from './Statistics'
import { getData } from '../../actions' import { getData } from '../../actions'
import { getMoreActivities } from '../../actions/activities' import { endPagination, getMoreActivities } from '../../actions/activities'
class DashBoard extends React.Component { class DashBoard extends React.Component {
constructor(props, context) { constructor(props, context) {
@ -19,6 +19,10 @@ class DashBoard extends React.Component {
this.props.loadActivities() this.props.loadActivities()
} }
componentWillUnmount() {
this.props.resetPaginationStatus(false)
}
render() { render() {
const { const {
activities, loadMoreActivities, message, paginationEnd, sports activities, loadMoreActivities, message, paginationEnd, sports
@ -77,6 +81,9 @@ export default connect(
sports: state.sports.data, sports: state.sports.data,
}), }),
dispatch => ({ dispatch => ({
resetPaginationStatus: () => {
dispatch(endPagination(false))
},
loadActivities: () => { loadActivities: () => {
dispatch(getData('activities', null, 1)) dispatch(getData('activities', null, 1))
}, },

View File

@ -24,7 +24,7 @@ const activities = (state = initial.activities, action) => {
case 'END_PAGINATION': case 'END_PAGINATION':
return { return {
...state, ...state,
pagination_end: true pagination_end: action.status
} }
case 'PUSH_ACTIVITIES': case 'PUSH_ACTIVITIES':
return { return {